diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b065b11..27728a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,3 +43,60 @@ jobs: - if: runner.os == 'Linux' uses: ./.github/actions/linux-deps - run: cargo test --workspace --locked + # The lint job runs on Linux; Windows-only code needs its own pass. + - if: runner.os == 'Windows' + run: cargo clippy --workspace --all-targets --locked -- -D warnings + + askpass-release-windows: + # The release exe is a GUI-subsystem program, unlike the debug build the test job uses; + # ssh runs it as SSH_ASKPASS and reads the answer from its stdout. + name: askpass (windows release build) + runs-on: windows-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Rust toolchain (from rust-toolchain.toml) + run: rustup toolchain install || rustup show + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: release + - name: ssh-keygen opens a key through the release exe as askpass + shell: bash + run: | + set -o pipefail + # Once with the ssh-keygen on PATH (Git for Windows' MSYS build) and once with Windows' + # own OpenSSH, which starts askpass differently (posix_spawnp) and is what most users run. + for keygen in "" 'C:\Windows\System32\OpenSSH\ssh-keygen.exe'; do + REDSHELL_TEST_SSH_KEYGEN="$keygen" cargo test --release --locked -p redshell-app --test askpass -- --nocapture 2>&1 | tee askpass.log + # The test skips itself without a usable ssh-keygen; here that must not pass silently. + if grep -q "skipped:" askpass.log; then echo "::error::the askpass test was skipped"; exit 1; fi + done + + server-arm64: + # The server's crates on the architecture of a Raspberry Pi. + name: test (server, linux arm64) + runs-on: ubuntu-22.04-arm + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Rust toolchain (from rust-toolchain.toml) + run: rustup toolchain install || rustup show + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - run: cargo test --locked -p redshell-server -p redshell-protocol -p redshell-terminal -p redshell-remote -p redshell-core + + web: + name: web (typecheck, lint, test, build) + runs-on: ubuntu-latest + defaults: + run: + working-directory: web + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 + with: + node-version: 24 + cache: npm + cache-dependency-path: web/package-lock.json + - run: npm ci + - run: npm run typecheck + - run: npm run lint + - run: npm test + - run: npm run build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4fe43f4..5f0b988 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -247,8 +247,99 @@ jobs: name: ${{ matrix.name }} path: dist/* + server: + # redshell-server with the RedShell Remote PWA embedded: a tarball everywhere and a .deb + # (with the per-user systemd unit) on Linux. The aarch64 build is the one for a Raspberry Pi + # (64-bit Raspberry Pi OS). Linux builds run on 22.04 so the binaries need glibc 2.35. + needs: version + name: server (${{ matrix.name }}) + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - name: linux-x86_64 + os: ubuntu-22.04 + targets: x86_64-unknown-linux-gnu + deb-arch: amd64 + - name: linux-aarch64 + os: ubuntu-22.04-arm + targets: aarch64-unknown-linux-gnu + deb-arch: arm64 + - name: macos-universal + os: macos-15-intel + targets: aarch64-apple-darwin x86_64-apple-darwin + runs-on: ${{ matrix.os }} + env: + TARGETS: ${{ matrix.targets }} + BASE_NAME: redshell-server-${{ github.event.inputs.tag || github.ref_name }}-${{ matrix.name }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 + with: + node-version: 24 + cache: npm + cache-dependency-path: web/package-lock.json + - name: Build the PWA + working-directory: web + run: | + npm ci + npm run build + test -f dist/index.html + - name: Rust toolchain (from rust-toolchain.toml) + shell: bash + run: | + rustup toolchain install || rustup show + rustup target add $TARGETS + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: server-${{ matrix.name }} + - name: Build + shell: bash + run: | + set -euo pipefail + for target in $TARGETS; do + cargo build --release --locked --target "$target" -p redshell-server + done + mkdir -p out + set -- $TARGETS + if [ $# -gt 1 ]; then + lipo -create $(printf 'target/%s/release/redshell-server ' "$@") -output out/redshell-server + lipo -info out/redshell-server + else + cp "target/$1/release/redshell-server" out/redshell-server + fi + # The PWA must be in the binary, not the placeholder page. + if ! grep -q "manifest.webmanifest" out/redshell-server; then + echo "::error::the PWA was not embedded" + exit 1 + fi + out/redshell-server --version + - name: Package + shell: bash + run: | + set -euo pipefail + mkdir -p dist "$BASE_NAME" + cp out/redshell-server README.md LICENSE CHANGELOG.md docs/REMOTE.md "$BASE_NAME/" + cp "packaging/server/redshell-server@.service" "$BASE_NAME/" + tar -czf "dist/$BASE_NAME.tar.gz" "$BASE_NAME" + if [ -n "${{ matrix.deb-arch }}" ]; then + scripts/package-server-deb.sh out/redshell-server "${TAG#v}" "${{ matrix.deb-arch }}" "dist/$BASE_NAME.deb" + dpkg-deb -I "dist/$BASE_NAME.deb" | head -5 + fi + cd dist + for file in *; do + if command -v sha256sum >/dev/null; then sha256sum "$file"; else shasum -a 256 "$file"; fi > "$file.sha256" + done + ls -la + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: server-${{ matrix.name }} + path: dist/* + publish: - needs: [version, build] + needs: [version, build, server] permissions: contents: write # Publish whatever built, so one stuck runner doesn't block a release; re-run diff --git a/.gitignore b/.gitignore index bd003ec..9ae4076 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ target/ *.db *.db-journal .DS_Store +web/node_modules +web/dist +web/dev-dist diff --git a/CHANGELOG.md b/CHANGELOG.md index cf3259d..8c98e3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,36 +4,103 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and versions follow [Semantic Versioning](https://semver.org/). -## [Unreleased] +## [0.0.3] - 2026-12-04 + +This release adds `redshell-server`, which keeps shells and coding agents running on an +always-on machine such as a Raspberry Pi, for the desktop and for RedShell Remote, the web app it +serves to phones. SSH hosts also get a home in the app: an editor instead of `config.toml`, +password dialogs backed by the system keychain, port forwards and a file browser. + +**Upgrading from 0.0.2.** `ssh.askpass` is on by default: with OpenSSH 8.4 or newer, ssh's +password, passphrase and host key prompts now appear in a RedShell dialog instead of the +terminal, and older clients, such as the OpenSSH 8.1 that ships with Windows 10, keep prompting +in the terminal. Set `ssh.askpass = false` to keep the terminal prompts everywhere. A host in +`[[ssh.hosts]]` whose `name` is also a `Host` alias in `~/.ssh/config` now connects through the +alias (while `ssh.import_ssh_config` is on), so the alias's `IdentityFile`, `ProxyJump` and other +options apply under the fields set in RedShell; rename the entry if it was meant to bypass the +alias. Entries RedShell adds to `config.toml` now list their keys in the order of the settings, +starting with an SSH host's `name`, and leave empty host fields out; existing entries are not +touched, so this is cosmetic. ### Added -- SSH hosts are added and edited in a dialog instead of `config.toml`: *Add SSH Host…* (also the - "+" next to the sidebar's SSH hosts) and *Edit SSH Host…* in the command palette, a right-click - menu on each host in the sidebar to connect, edit, duplicate or delete it, and an edit button - (Alt+E) in the *Connect to SSH Host* picker. -- Hosts can be put in groups, which the sidebar lists them under and the host picker shows. -- Editing a host from `~/.ssh/config` keeps the changes in RedShell and leaves the file alone; - *Reset to ~/.ssh/config* drops them again. -- RedShell asks for SSH passwords, key passphrases and new host keys itself and can remember - passwords and passphrases in the system keychain (`ssh.askpass`, OpenSSH 8.4 or newer). Each - question shows in the window of the tab that asks, one at a time over any open dialog, and - security key prompts show as a notice until they are done. -- The host editor shows whether a host's password is saved in the keychain and changes or - removes it; renaming or deleting a host takes its password along. +- SSH hosts are added and edited in a dialog: *Add SSH Host…* (also the "+" next to the + sidebar's SSH hosts), *Edit SSH Host…*, a right-click menu on each host in the sidebar to + connect, edit, duplicate or delete it, and Alt+E in the *Connect to SSH Host* picker. +- Hosts can be put in groups, which the sidebar and the host picker show. Editing a host from + `~/.ssh/config` keeps the changes in RedShell and leaves the file alone; *Reset to + ~/.ssh/config* drops them. +- RedShell asks for SSH passwords, passphrases and new host keys in its own dialog and can keep + passwords and passphrases in the system keychain (`ssh.askpass`, OpenSSH 8.4 or newer), also + for native tmux attach. The host editor shows, changes or removes a host's saved password. - *Install Key on Server…* adds your public key to a host's `authorized_keys`, as `ssh-copy-id` does, and creates an ed25519 key first if you have none. -- SSH hosts carry port forwards (local, remote and SOCKS) that run as background tunnels: start - and stop them from a host's *Port Forwarding* menu or *SSH Tunnels…*, open them with RedShell - (`auto_start`), and see which hosts have one up in the sidebar. A failed tunnel says why and - stays down until you start it again; quitting closes them all. -- The host editor has a *Port forwarding* section, a *Forward agent* switch (`forward_agent`) and - a *Startup command* run after login, before the shell or the `attach_session` session. -- *Browse Files…* shows an SSH host's files over SFTP: from a host's menu, an SSH tab's menu, the - folder button (Alt+F) in the *Connect to SSH Host* picker or *Browse SSH Host Files…* in the - command palette. It sorts by name, size or date, downloads files and folders, uploads picked or - dropped files, creates, renames and deletes, copies paths and opens a terminal in the folder - shown. Transfers show progress, can be cancelled and keep going while you browse elsewhere or - after the dialog closes. +- Port forwards (local, remote and SOCKS) on SSH hosts, run as background tunnels: start and stop + them from a host's *Port Forwarding* menu or *SSH Tunnels…*, open them with RedShell + (`auto_start`), and see in the sidebar which hosts have one up. +- The host editor sets agent forwarding (`forward_agent`) and a startup command that runs after + login, before the shell or the `attach_session` session. +- *Browse Files…* shows an SSH host's files over SFTP (from a host's or an SSH tab's menu, Alt+F + in the host picker, or *Browse SSH Host Files…*): download, upload by picking or dropping, + create, rename, delete, and open a terminal in the folder. Transfers outlive the dialog. +- `redshell-server` keeps shells, coding agents and SSH sessions running on an always-on machine, + set up in a `[server]` section of its `config.toml` ([docs/REMOTE.md](docs/REMOTE.md)). Releases + carry it for Linux (`.deb` with a per-user systemd unit, and `.tar.gz`) and for macOS. +- Behind Tailscale Serve or cloudflared on the same machine, the server trusts the proxy's + `X-Forwarded-For` without any `trusted_proxies`, so each client meets its own sign-in backoff. +- The server signs in with a password, with backoff, or a passkey (Face ID, Touch ID, Windows + Hello, a security key). Browsers and devices are listed with when they were last seen and can be + revoked, an account can turn password sign-in off, and `redshell-server user` manages accounts. +- Claude Code permission requests can be answered from any connected client or in Claude Code's + own dialog, whichever comes first, and Claude Code and Codex report when they work, wait for + input or finish. A Codex `notify` program of your own still runs. +- Web Push notifications when an agent asks for approval, waits for input or finishes, and when + a program fails or raises a notification, chosen per browser and held back while you are + typing into that session. +- RedShell Remote, the web app the server serves, for phones and browsers: an inbox of sessions + that need you, terminals with a key bar and a composer, approval sheets with diffs, new sessions + in any folder, passkeys, notifications and the server's SSH hosts, in two columns on wide screens. +- The desktop connects to RedShell servers: add them under *Settings → Servers* (`[remote]` in + `config.toml`) and sign in with a password or a short code you approve in a signed-in browser, + which says whether the request came from your own address. The token stays in the keychain. +- A *Servers* section in the sidebar lists a server's sessions with what their agents are doing. + They open as tabs that only detach when closed and come back on the next start, with an agent's + pending approval above the terminal. +- *Send to Server* in an SSH host's menu copies the host to a server, without its identity file, + through the server's hosts API, which edits its `config.toml` in place and keeps the comments. +- `redshell-protocol`, the wire types shared by the server, the desktop and (as TypeScript) + RedShell Remote. + +### Changed +- `ssh.askpass` is on by default, so ssh's prompts appear in RedShell's dialog where OpenSSH 8.4 or + newer is installed. +- A saved host named after a `~/.ssh/config` alias connects through the alias, with the fields + set in RedShell passed on top (`-p`, `-l`, `HostName`). +- New entries in `config.toml` list their keys in the order of the settings, and SSH hosts leave + empty fields out. +- Shift+Tab moves back through dialogs and lists, as Tab moves on. + +### Fixed +- Native tmux tabs get the right size on tmux 3.2, which ignores per-window sizes. +- Hosts listed from `ssh.ssh_config_path` connect: ssh now reads that file too (`-F`). + +### Security +- `redshell-server` accepts browser requests only from its own origin (exactly `public_url` when + that is https), needs `X-RedShell: 1` on every request that changes something (protocol + version 2), and sends HSTS whenever clients reach it over https. +- Adding or removing a passkey, turning passkey-only on or off, approving a pairing and signing + out another browser or device need a re-authentication within the last five minutes. +- Turning passkey-only on ends the password's sign-ins, a password change drops pairing approvals + still waiting, and `user passwd` lists the passkeys that still sign in and takes + `--revoke-passkeys`. +- Strangers cannot fill the server's memory, log or connections: passkey sign-ins are stateless, + limits count IPv6 by /64, bodies, names, pairing requests and connections are bounded, and slow + clients time out. The sign-in backoff stops at 15 minutes per address and 2 per name. +- Push messages go only to public https endpoints on port 443, and *Browse Files…* skips + downloaded names that could leave the target folder. +- RedShell Remote asks "Confirm it's you" (a passkey or the password) before a change that needs + a re-authentication and then makes the change, and its pairing page warns that approving signs + the device in as you, with the address the request came from and a warning when that is + another network. ## [0.0.2] - 2026-12-01 @@ -213,5 +280,6 @@ First public preview. themes; settings UI for fonts, opacity, background image, cursor, safety, history and keybindings; hot-reloaded `config.toml`. +[0.0.3]: https://github.com/redstone-md/RedShell/compare/v0.0.2...v0.0.3 [0.0.2]: https://github.com/redstone-md/RedShell/compare/v0.0.1...v0.0.2 [0.0.1]: https://github.com/redstone-md/RedShell/releases/tag/v0.0.1 diff --git a/Cargo.lock b/Cargo.lock index d6308c9..2f1293a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,26 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.6", +] + [[package]] name = "aes" version = "0.8.4" @@ -31,6 +51,54 @@ dependencies = [ "cpufeatures 0.3.1", ] +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead 0.5.2", + "aes 0.8.4", + "cipher 0.4.4", + "ctr 0.9.2", + "ghash 0.5.1", + "subtle", +] + +[[package]] +name = "aes-gcm" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" +dependencies = [ + "aead 0.6.1", + "aes 0.9.4", + "cipher 0.5.2", + "ctr 0.10.1", + "ctutils", + "ghash 0.6.0", +] + +[[package]] +name = "aes-keywrap" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf71a903b87eeef4903e7077cc9689f0c8449e093395db09dc48d1a39934e770" +dependencies = [ + "aes 0.9.4", + "byteorder", +] + +[[package]] +name = "aes-kw" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41ac571010bd60765c56085a4f1d412012a9be2663b1a2f2b19b49318653fd0d" +dependencies = [ + "aes 0.9.4", + "const-oid 0.10.3", +] + [[package]] name = "ahash" version = "0.8.15" @@ -61,7 +129,7 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bda177466b9524d59f1b12f0dd30b68696788e9992a7e959021c4a0ed96fcf59" dependencies = [ - "base64", + "base64 0.22.1", "bitflags 2.13.2", "home", "libc", @@ -189,6 +257,15 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +[[package]] +name = "arc-swap" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + [[package]] name = "arg_enum_proc_macro" version = "0.3.4" @@ -200,6 +277,30 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2 0.10.6", + "cpufeatures 0.2.17", + "password-hash 0.5.0", +] + +[[package]] +name = "argon2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" +dependencies = [ + "base64ct", + "blake2 0.11.0", + "cpufeatures 0.3.1", + "password-hash 0.6.1", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -286,6 +387,45 @@ dependencies = [ "zbus", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -487,6 +627,28 @@ dependencies = [ "wasm-bindgen-futures", ] +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-task" version = "4.7.1" @@ -578,12 +740,120 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1 0.10.7", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-server" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3766086d344b8f8d2a9cf6fb211b581de5b160e052d7bc75a92e58cc41909054" +dependencies = [ + "arc-swap", + "bytes", + "either", + "fs-err", + "http", + "http-body", + "hyper", + "hyper-util", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "socket2", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bindgen" version = "0.71.1" @@ -604,6 +874,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "binstring" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1c05f270702529040b45d3389e1245bc21c5e5df78b2a509e1e3d7bcd47a18e" + [[package]] name = "bit-set" version = "0.8.0" @@ -707,6 +983,34 @@ dependencies = [ "profiling", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "blake2b_simd" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3560a7b1951efe814fcd721938313adc56753ca39f4b23847d7e9a2402f5dbff" +dependencies = [ + "arrayvec", + "constant_time_eq", +] + [[package]] name = "block" version = "0.1.6" @@ -729,6 +1033,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ "hybrid-array", + "zeroize", ] [[package]] @@ -771,6 +1076,15 @@ dependencies = [ "piper", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bstr" version = "1.14.0" @@ -882,7 +1196,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff" dependencies = [ "heck 0.4.1", - "indexmap", + "indexmap 2.14.2", "log", "proc-macro2", "quote", @@ -981,6 +1295,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ + "block-buffer 0.12.1", "crypto-common 0.2.2", "inout 0.2.6", ] @@ -997,41 +1312,92 @@ dependencies = [ ] [[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - -[[package]] -name = "cocoa" -version = "0.25.0" +name = "clap" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" dependencies = [ - "bitflags 1.3.2", - "block", - "cocoa-foundation 0.1.2", - "core-foundation 0.9.4", - "core-graphics 0.23.2", - "foreign-types", - "libc", - "objc", + "clap_builder", + "clap_derive", ] [[package]] -name = "cocoa" -version = "0.26.0" +name = "clap_builder" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" dependencies = [ - "bitflags 2.13.2", - "block", - "cocoa-foundation 0.2.0", - "core-foundation 0.10.0", - "core-graphics 0.24.0", - "foreign-types", - "libc", - "objc", + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "coarsetime" +version = "0.1.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae63702c5627c75addbfb1ea9d1b3842205a6ffd43e4cce884a2a9eb1828fd7" +dependencies = [ + "libc", + "wasix", + "wasm-bindgen", +] + +[[package]] +name = "cocoa" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c" +dependencies = [ + "bitflags 1.3.2", + "block", + "cocoa-foundation 0.1.2", + "core-foundation 0.9.4", + "core-graphics 0.23.2", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "cocoa" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2" +dependencies = [ + "bitflags 2.13.2", + "block", + "cocoa-foundation 0.2.0", + "core-foundation 0.10.0", + "core-graphics 0.24.0", + "foreign-types", + "libc", + "objc", ] [[package]] @@ -1122,6 +1488,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.3" @@ -1147,6 +1519,12 @@ dependencies = [ "tiny-keccak", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "convert_case" version = "0.4.0" @@ -1399,6 +1777,35 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-bigint" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "serdect", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -1416,9 +1823,74 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", + "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "crypto-glue" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57d90fe73514cb72a4ad8568a184472dfb4c2ffa65409a8e85720b83202cec83" +dependencies = [ + "aes 0.9.4", + "aes-gcm 0.11.1", + "aes-kw", + "argon2 0.6.0", + "base64 0.23.1", + "cbc 0.2.1", + "cipher 0.5.2", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "cts", + "der 0.8.3", + "digest 0.11.3", + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "hex", + "hkdf 0.13.0", + "hmac 0.13.0", "hybrid-array", + "kbkdf", + "md5", + "p256 0.14.0", + "p384 0.14.0", + "p521", + "pbkdf2 0.13.0", + "pkcs8 0.11.0", + "rand 0.10.4", + "rsa", + "sec1 0.8.1", + "serde", + "sha1 0.11.0", + "sha2 0.11.2", + "signature 3.0.0", + "spki 0.8.1", + "subtle", + "tracing", + "uuid", + "wasm-bindgen", + "x509-cert", + "zeroize", +] + +[[package]] +name = "crypto-primes" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f" +dependencies = [ + "crypto-bigint 0.7.11", + "rand_core 0.10.1", ] +[[package]] +name = "ct-codecs" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd" + [[package]] name = "ctor" version = "0.4.3" @@ -1435,6 +1907,33 @@ version = "0.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2" +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher 0.4.4", +] + +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher 0.5.2", +] + +[[package]] +name = "cts" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6ae47d18aa4f3701bc9b644cf9a74a45e6eace39feabeab15864728aa1e45a9" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "ctutils" version = "0.4.8" @@ -1442,6 +1941,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", + "subtle", ] [[package]] @@ -1450,6 +1950,40 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + [[package]] name = "dashmap" version = "6.2.1" @@ -1464,6 +1998,12 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -1476,6 +2016,64 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468 0.7.0", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.3", + "der_derive", + "flagset", + "pem-rfc7468 1.0.0", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + [[package]] name = "derive_more" version = "0.99.20" @@ -1496,6 +2094,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -1507,9 +2106,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", + "zeroize", ] [[package]] @@ -1655,12 +2255,105 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der 0.7.10", + "digest 0.10.7", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", + "signature 2.2.0", + "spki 0.7.3", +] + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.3", + "digest 0.11.3", + "elliptic-curve 0.14.3", + "rfc6979 0.6.0", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", +] + +[[package]] +name = "ece-native" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6911cc97c62febd8cbcb2cb49ed21c58ccd418a80c43f20df4973ee08484e65d" +dependencies = [ + "aes-gcm 0.10.3", + "hkdf 0.12.4", + "sha2 0.10.9", +] + +[[package]] +name = "ed25519-compact" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9547879431a90e352a35863a54416d92898a787b9af09e6ae2e09a96bd78be80" +dependencies = [ + "ct-codecs", + "getrandom 0.4.3", +] + [[package]] name = "either" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct 0.2.0", + "crypto-bigint 0.5.5", + "digest 0.10.7", + "ff 0.13.1", + "generic-array", + "group 0.13.0", + "hkdf 0.12.4", + "pem-rfc7468 0.7.0", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sec1 0.7.3", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct 1.0.0", + "crypto-bigint 0.7.11", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff 0.14.0", + "group 0.14.0", + "hkdf 0.13.0", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sec1 0.8.1", + "subtle", + "zeroize", +] + [[package]] name = "embed-resource" version = "3.0.12" @@ -1735,7 +2428,7 @@ dependencies = [ "anstream", "anstyle", "env_filter", - "jiff", + "jiff 1.0.3", "log", ] @@ -1889,6 +2582,32 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "filedescriptor" version = "0.8.3" @@ -1916,6 +2635,12 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.11" @@ -2068,6 +2793,16 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", + "tokio", +] + [[package]] name = "futf" version = "0.1.5" @@ -2202,6 +2937,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -2253,6 +2989,25 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval 0.6.2", +] + +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval 0.7.3", +] + [[package]] name = "gif" version = "0.14.2" @@ -2413,7 +3168,7 @@ dependencies = [ "rand 0.9.5", "raw-window-handle", "resvg", - "schemars", + "schemars 1.2.3", "seahash", "serde", "serde_json", @@ -2462,7 +3217,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae39dc6d3d201be97e4bc08d96dbef2bc5b5c3d5734e05786e8cc3043342351c" dependencies = [ - "indexmap", + "indexmap 2.14.2", "rustc-hash 2.1.3", ] @@ -2582,7 +3337,7 @@ dependencies = [ "nix 0.29.0", "regex", "rust-embed", - "schemars", + "schemars 1.2.3", "serde", "serde_json", "serde_json_lenient", @@ -2613,6 +3368,28 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12101ecc8225ea6d675bc70263074eab6169079621c2186fe0c66590b2df9681" +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff 0.13.1", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "h2" version = "0.4.21" @@ -2625,7 +3402,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap", + "indexmap 2.14.2", "slab", "tokio", "tokio-util", @@ -2644,6 +3421,12 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.14.5" @@ -2751,6 +3534,35 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "hmac-sha1-compact" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5286b48a73829e3541cd9f533359c01150f7879e2716796eda0631ad5fe7e668" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "hmac-sha256" +version = "1.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad320b3b96fb2a455a0726d16efe0a5afdbd34b71dea5bc53b05ea057714d4e" +dependencies = [ + "digest 0.10.7", + "digest 0.11.3", +] + +[[package]] +name = "hmac-sha512" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66de62217b456dfbbba2bed965a134a4df57c48f0eac4c772018aee528e72244" +dependencies = [ + "digest 0.10.7", + "digest 0.11.3", +] + [[package]] name = "home" version = "0.5.12" @@ -2799,13 +3611,23 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "ctutils", + "serde", + "subtle", "typenum", + "zeroize", ] [[package]] @@ -2822,6 +3644,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2843,6 +3666,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", + "webpki-roots", ] [[package]] @@ -2851,6 +3675,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", "futures-channel", "futures-util", @@ -2858,7 +3683,9 @@ dependencies = [ "http-body", "httparse", "hyper", + "ipnet", "libc", + "percent-encoding", "pin-project-lite", "socket2", "tokio", @@ -2973,6 +3800,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -3040,6 +3873,17 @@ version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -3168,62 +4012,190 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jiff" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" +dependencies = [ + "jiff-core 0.1.8", + "jiff-static 0.2.46", + "jiff-tzdb-platform 0.1.3", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link 0.2.1", +] + [[package]] name = "jiff" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" dependencies = [ - "jiff-core", - "jiff-static", + "jiff-core 1.0.2", + "jiff-static 1.0.3", + "jiff-tzdb-platform 1.0.0", "js-sys", "log", "portable-atomic", "portable-atomic-util", "serde_core", "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" +dependencies = [ + "jiff-core 0.1.8", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-static" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +dependencies = [ + "jiff-core 1.0.2", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb 0.1.10", +] + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb 1.0.0", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", ] [[package]] -name = "jiff-core" -version = "1.0.2" +name = "jwt-simple" +version = "0.12.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +checksum = "06a4207b9d1f423858853fb9ee8b34aebc2b661f3b446ca4efda46c4b3700a2f" dependencies = [ - "log", + "anyhow", + "binstring", + "blake2b_simd", + "coarsetime", + "ct-codecs", + "ed25519-compact", + "hmac-sha1-compact", + "hmac-sha256", + "hmac-sha512", + "k256", + "p256 0.13.2", + "p384 0.13.1", + "rand 0.8.8", + "serde", + "serde_json", + "superboring", + "thiserror 2.0.21", + "zeroize", ] [[package]] -name = "jiff-static" -version = "1.0.3" +name = "k256" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" dependencies = [ - "jiff-core", - "proc-macro2", - "quote", - "syn 3.0.10", + "cfg-if", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "once_cell", + "sha2 0.10.9", + "signature 2.2.0", ] [[package]] -name = "jobserver" -version = "0.1.35" +name = "kbkdf" +version = "0.1.0-rc.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +checksum = "90ac93c9768b8d587407881c98b0c3a5d3e3049daa73408ebe5bfb1ab1cb9c84" dependencies = [ - "getrandom 0.4.3", - "libc", + "digest 0.11.3", ] [[package]] -name = "js-sys" -version = "0.3.107" +name = "keccak" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598" dependencies = [ "cfg-if", - "futures-util", - "wasm-bindgen", + "cpufeatures 0.3.1", ] [[package]] @@ -3466,6 +4438,12 @@ dependencies = [ "libc", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "maybe-rayon" version = "0.1.1" @@ -3486,6 +4464,12 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "md5" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" + [[package]] name = "memchr" version = "2.8.3" @@ -3593,6 +4577,33 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ml-dsa" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c" +dependencies = [ + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", + "hybrid-array", + "module-lattice", + "pkcs8 0.11.0", + "shake", + "signature 3.0.0", +] + +[[package]] +name = "module-lattice" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e412c8ee83a1c678f427806219c49c96b2511b9f07497514f0e43fb26155" +dependencies = [ + "ctutils", + "hybrid-array", + "num-traits", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -3645,7 +4656,7 @@ dependencies = [ "half", "hashbrown 0.15.5", "hexf-parse", - "indexmap", + "indexmap 2.14.2", "log", "num-traits", "once_cell", @@ -3800,6 +4811,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -3997,6 +5014,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -4033,7 +5059,7 @@ dependencies = [ "md-5", "num", "num-bigint-dig", - "pbkdf2", + "pbkdf2 0.12.2", "rand 0.9.5", "serde", "sha2 0.10.9", @@ -4044,6 +5070,12 @@ dependencies = [ "zvariant", ] +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "open" version = "5.4.5" @@ -4076,6 +5108,71 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", + "sha2 0.10.9", +] + +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "fiat-crypto", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.2", +] + +[[package]] +name = "p521" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ad64cc32c2dc466317c12ee5853e61f159f9eab1fe7efade0395dc2e7b43449" +dependencies = [ + "base16ct 1.0.0", + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.2", +] + [[package]] name = "parking" version = "2.2.1" @@ -4105,6 +5202,27 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "password-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b" +dependencies = [ + "getrandom 0.4.3", + "phc", +] + [[package]] name = "paste" version = "1.0.15" @@ -4146,12 +5264,51 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac 0.13.0", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phc" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892" +dependencies = [ + "base64ct", + "ctutils", + "getrandom 0.4.3", +] + [[package]] name = "pico-args" version = "0.5.0" @@ -4201,6 +5358,55 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pkcs1" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6250dd7321adbe93d12b750aee0ced159fd13e77f625edcdf1cb6f83cd99f650" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", +] + +[[package]] +name = "pkcs5" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca" +dependencies = [ + "aes 0.9.4", + "aes-gcm 0.11.1", + "cbc 0.2.1", + "der 0.8.3", + "pbkdf2 0.13.0", + "rand_core 0.10.1", + "scrypt", + "sha2 0.11.2", + "spki 0.8.1", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "pkcs5", + "rand_core 0.10.1", + "spki 0.8.1", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -4253,6 +5459,29 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash 0.5.1", +] + +[[package]] +name = "polyval" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures 0.3.1", + "universal-hash 0.6.1", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -4315,6 +5544,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -4334,6 +5569,42 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint 0.7.11", + "crypto-common 0.2.2", + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve 0.13.8", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve 0.14.3", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -4562,6 +5833,16 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_chacha" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb" +dependencies = [ + "ppv-lite86", + "rand_core 0.10.1", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -4741,7 +6022,7 @@ dependencies = [ [[package]] name = "redshell-agents" -version = "0.0.2" +version = "0.0.3" dependencies = [ "redshell-core", "which 8.0.6", @@ -4749,7 +6030,7 @@ dependencies = [ [[package]] name = "redshell-app" -version = "0.0.2" +version = "0.0.3" dependencies = [ "anyhow", "apple-native-keyring-store", @@ -4768,16 +6049,21 @@ dependencies = [ "redshell-core", "redshell-history", "redshell-plugin", + "redshell-protocol", "redshell-remote", + "redshell-server", "redshell-terminal", "redshell-theme", "redshell-ui", + "rustls", + "rustls-native-certs", "semver", "serde", "serde_json", "shlex 1.3.0", "tempfile", "tokio", + "tokio-tungstenite", "uuid", "which 8.0.6", "windows 0.61.3", @@ -4789,13 +6075,15 @@ dependencies = [ [[package]] name = "redshell-core" -version = "0.0.2" +version = "0.0.3" dependencies = [ "anyhow", "dirs 6.0.0", + "redshell-protocol", "semver", "serde", "serde_json", + "shlex 1.3.0", "tempfile", "toml 0.9.12+spec-1.1.0", "toml_edit 0.25.21+spec-1.1.0", @@ -4805,7 +6093,7 @@ dependencies = [ [[package]] name = "redshell-history" -version = "0.0.2" +version = "0.0.3" dependencies = [ "anyhow", "chrono", @@ -4823,7 +6111,7 @@ dependencies = [ [[package]] name = "redshell-plugin" -version = "0.0.2" +version = "0.0.3" dependencies = [ "anyhow", "crossbeam-channel", @@ -4834,36 +6122,94 @@ dependencies = [ "serde", "serde_json", "tempfile", - "toml 0.9.12+spec-1.1.0", + "toml 0.9.12+spec-1.1.0", +] + +[[package]] +name = "redshell-protocol" +version = "0.0.3" +dependencies = [ + "serde", + "serde_json", + "ts-rs", +] + +[[package]] +name = "redshell-remote" +version = "0.0.3" +dependencies = [ + "anyhow", + "chrono", + "crossbeam-channel", + "dirs 6.0.0", + "libc", + "log", + "parking_lot", + "redshell-core", + "russh-sftp", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tokio", + "uuid", + "which 8.0.6", + "windows-sys 0.61.2", + "zeroize", ] [[package]] -name = "redshell-remote" -version = "0.0.2" +name = "redshell-server" +version = "0.0.3" dependencies = [ "anyhow", - "chrono", + "argon2 0.5.3", + "axum", + "axum-server", + "base64 0.22.1", + "clap", "crossbeam-channel", "dirs 6.0.0", + "env_logger", + "futures-util", + "hmac 0.12.1", + "http-body-util", + "hyper", + "hyper-util", "libc", "log", "parking_lot", + "rand_core 0.6.4", + "redshell-agents", "redshell-core", - "russh-sftp", + "redshell-protocol", + "redshell-remote", + "redshell-terminal", + "reqwest", + "rpassword", + "rusqlite", + "rust-embed", + "rustls", "serde", "serde_json", + "sha2 0.10.9", "tempfile", "thiserror 2.0.21", "tokio", + "tokio-tungstenite", + "toml 0.9.12+spec-1.1.0", + "tower-http", + "url", "uuid", - "which 8.0.6", - "windows-sys 0.61.2", - "zeroize", + "web-push-native", + "webauthn-authenticator-rs", + "webauthn-rs", + "webauthn-rs-proto", ] [[package]] name = "redshell-terminal" -version = "0.0.2" +version = "0.0.3" dependencies = [ "alacritty_terminal", "anyhow", @@ -4878,7 +6224,7 @@ dependencies = [ [[package]] name = "redshell-theme" -version = "0.0.2" +version = "0.0.3" dependencies = [ "anyhow", "gpui", @@ -4888,7 +6234,7 @@ dependencies = [ [[package]] name = "redshell-ui" -version = "0.0.2" +version = "0.0.3" dependencies = [ "gpui", "redshell-core", @@ -4945,6 +6291,44 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + [[package]] name = "resvg" version = "0.45.1" @@ -4959,6 +6343,26 @@ dependencies = [ "usvg", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint 0.7.11", + "hmac 0.13.0", +] + [[package]] name = "rgb" version = "0.8.53" @@ -4988,6 +6392,48 @@ version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" +[[package]] +name = "rpassword" +version = "7.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rsa" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699" +dependencies = [ + "const-oid 0.10.3", + "crypto-bigint 0.7.11", + "crypto-common 0.2.2", + "crypto-primes", + "digest 0.11.3", + "hmac 0.13.0", + "pkcs1", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sha2 0.11.2", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "rusqlite" version = "0.37.0" @@ -5012,7 +6458,7 @@ dependencies = [ "bytes", "dashmap", "gloo-timers 0.4.1", - "jiff", + "jiff 1.0.3", "log", "serde", "serde_bytes", @@ -5043,6 +6489,7 @@ dependencies = [ "proc-macro2", "quote", "rust-embed-utils", + "shellexpand", "syn 2.0.119", "walkdir", ] @@ -5054,6 +6501,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b" dependencies = [ "globset", + "mime_guess", "sha2 0.11.2", "walkdir", ] @@ -5079,6 +6527,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -5219,6 +6676,16 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c" +dependencies = [ + "cfg-if", + "cipher 0.5.2", +] + [[package]] name = "same-file" version = "1.0.6" @@ -5237,6 +6704,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "schemars" version = "1.2.3" @@ -5244,7 +6723,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", - "indexmap", + "indexmap 2.14.2", "ref-cast", "schemars_derive", "serde", @@ -5298,12 +6777,52 @@ dependencies = [ "once_cell", ] +[[package]] +name = "scrypt" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0" +dependencies = [ + "cfg-if", + "pbkdf2 0.13.0", + "salsa20", + "sha2 0.11.2", +] + [[package]] name = "seahash" version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct 0.2.0", + "der 0.7.10", + "generic-array", + "pkcs8 0.10.2", + "subtle", + "zeroize", +] + +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct 1.0.0", + "ctutils", + "der 0.8.3", + "hybrid-array", + "subtle", + "zeroize", +] + [[package]] name = "secret-service" version = "5.2.0" @@ -5378,6 +6897,16 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_cbor_2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aec2709de9078e077090abd848e967abab63c9fb3fdb5d4799ad359d8d482c" +dependencies = [ + "half", + "serde", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -5425,7 +6954,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "foldhash 0.2.0", - "indexmap", + "indexmap 2.14.2", "itoa", "memchr", "serde", @@ -5439,13 +6968,24 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" dependencies = [ - "indexmap", + "indexmap 2.14.2", "itoa", "memchr", "ryu", "serde", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -5487,6 +7027,50 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_with" +version = "3.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56cb1ca7c93ae63d6439b5250f6b6b040f7e121f32e5dd2f5d523dd4149b3204" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff 0.2.46", + "jiff 1.0.3", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cff15a7c864bbec77d9586ca6822bc7c369bdf19e9243134a62b0b51ce26b31f" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", + "serde", +] + [[package]] name = "serial2" version = "0.2.39" @@ -5498,6 +7082,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -5526,6 +7132,17 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "shake" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a" +dependencies = [ + "digest 0.11.3", + "keccak", + "sponge-cursor", +] + [[package]] name = "shared_library" version = "0.1.9" @@ -5542,6 +7159,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" +[[package]] +name = "shellexpand" +version = "3.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" +dependencies = [ + "dirs 6.0.0", +] + [[package]] name = "shlex" version = "1.3.0" @@ -5574,6 +7200,26 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -5689,6 +7335,34 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", + "digest 0.11.3", + "sha2 0.11.2", +] + +[[package]] +name = "sponge-cursor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -5744,6 +7418,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.26.3" @@ -5793,6 +7473,23 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "superboring" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180c01a1d6c13ab0576bcd041ebfe0b66c455fa605de35909f3cee3f5bbf730f" +dependencies = [ + "aes-gcm 0.11.1", + "aes-keywrap", + "getrandom 0.4.3", + "hmac-sha1-compact", + "hmac-sha256", + "hmac-sha512", + "ml-dsa", + "rand 0.10.4", + "rsa", +] + [[package]] name = "sval" version = "2.22.0" @@ -5941,6 +7638,17 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -6119,6 +7827,36 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -6170,6 +7908,27 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tokio" version = "1.54.1" @@ -6219,6 +7978,34 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -6252,7 +8039,7 @@ version = "0.9.12+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" dependencies = [ - "indexmap", + "indexmap 2.14.2", "serde_core", "serde_spanned 1.1.3", "toml_datetime 0.7.5+spec-1.1.0", @@ -6267,7 +8054,7 @@ version = "1.2.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" dependencies = [ - "indexmap", + "indexmap 2.14.2", "serde_core", "serde_spanned 1.1.3", "toml_datetime 1.1.3+spec-1.1.0", @@ -6309,7 +8096,7 @@ version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap", + "indexmap 2.14.2", "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", @@ -6323,7 +8110,7 @@ version = "0.25.21+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" dependencies = [ - "indexmap", + "indexmap 2.14.2", "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", "toml_writer", @@ -6364,6 +8151,25 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", ] [[package]] @@ -6384,6 +8190,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -6415,6 +8222,29 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "ts-rs" +version = "12.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8" +dependencies = [ + "serde_json", + "thiserror 2.0.21", + "ts-rs-macros", +] + +[[package]] +name = "ts-rs-macros" +version = "12.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d90eea51bc7988ef9e674bf80a85ba6804739e535e9cab48e4bb34a8b652aa" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "termcolor", +] + [[package]] name = "ttf-parser" version = "0.20.0" @@ -6436,6 +8266,24 @@ dependencies = [ "core_maths", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "rustls", + "rustls-pki-types", + "sha1 0.10.7", + "thiserror 2.0.21", +] + [[package]] name = "typeid" version = "1.0.3" @@ -6507,6 +8355,15 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-properties" version = "0.1.5" @@ -6537,6 +8394,26 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -6562,7 +8439,7 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" dependencies = [ - "base64", + "base64 0.22.1", "data-url", "flate2", "fontdb 0.23.0", @@ -6756,6 +8633,15 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasix" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae86f02046da16a333a9129d31451423e1657737ecdafed4193838a5f54c5cfe" +dependencies = [ + "wasi", +] + [[package]] name = "wasm-bindgen" version = "0.2.130" @@ -6921,6 +8807,23 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "web-push-native" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7628c93e39aeee4c0bca50ae333052b4f174c653e8fca1d0a8e34f9bc4879c0c" +dependencies = [ + "aes-gcm 0.10.3", + "base64ct", + "ece-native", + "hkdf 0.13.0", + "http", + "jwt-simple", + "p256 0.13.2", + "serde", + "sha2 0.11.2", +] + [[package]] name = "web-sys" version = "0.3.107" @@ -6941,6 +8844,111 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webauthn-attestation-ca" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29cf6bdd3a9dba27c82ccb27df26fe7d98d7593c0c45ddddf85166a117b50301" +dependencies = [ + "crypto-glue", + "serde", + "serde_with", + "tracing", + "uuid", +] + +[[package]] +name = "webauthn-authenticator-rs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bf162a8f7b5d6cd5448576d3468ae151428480a6f7d1a381ed84eaa3c8c5566" +dependencies = [ + "async-stream", + "async-trait", + "base64 0.21.7", + "bitflags 1.3.2", + "crypto-glue", + "futures", + "hex", + "nom 7.1.3", + "num-derive", + "num-traits", + "serde", + "serde_bytes", + "serde_cbor_2", + "serde_json", + "thiserror 1.0.69", + "tokio", + "tokio-stream", + "tracing", + "unicode-normalization", + "url", + "uuid", + "webauthn-rs-core", + "webauthn-rs-proto", +] + +[[package]] +name = "webauthn-rs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a354e6b2ef6edc62835901fc18dd413b1370d624c8cd1aa328493bd809249b" +dependencies = [ + "serde", + "tracing", + "url", + "uuid", + "webauthn-rs-core", +] + +[[package]] +name = "webauthn-rs-core" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d13e555c106095051abd70415b88546a0d3757a7990e05b4659b4fba19e46ac" +dependencies = [ + "base64 0.21.7", + "crypto-glue", + "der-parser", + "hex", + "nom 7.1.3", + "rand 0.10.4", + "rand_chacha 0.10.0", + "serde", + "serde_cbor_2", + "serde_json", + "serde_with", + "thiserror 1.0.69", + "tracing", + "url", + "uuid", + "webauthn-attestation-ca", + "webauthn-rs-proto", + "x509-parser", +] + +[[package]] +name = "webauthn-rs-proto" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5555714098cd069e3c8b31e58ac14250b9ae185e949c21416bccb55ce8ac8a5c" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", + "serde_with", + "url", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -7537,6 +9545,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.4" @@ -7583,6 +9603,37 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "x509-cert" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417" +dependencies = [ + "const-oid 0.10.3", + "der 0.8.3", + "sha1 0.11.0", + "signature 3.0.0", + "spki 0.8.1", + "tls_codec", +] + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "xattr" version = "0.2.3" @@ -7693,7 +9744,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.10", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -7822,7 +9873,7 @@ version = "0.12.15-zed" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac2d05756ff48539950c3282ad7acf3817ad3f08797c205ad1c34a2ce03b9970" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "encoding_rs", "futures-core", @@ -7946,7 +9997,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.10", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e0a6411..f893e39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,11 +10,13 @@ members = [ "crates/redshell-plugin", "crates/redshell-ui", "crates/redshell-app", + "crates/redshell-protocol", + "crates/redshell-server", ] default-members = ["crates/redshell-app"] [workspace.package] -version = "0.0.2" +version = "0.0.3" edition = "2024" license = "MIT" repository = "https://github.com/redstone-md/RedShell" @@ -29,6 +31,7 @@ redshell-remote = { path = "crates/redshell-remote" } redshell-agents = { path = "crates/redshell-agents" } redshell-plugin = { path = "crates/redshell-plugin" } redshell-ui = { path = "crates/redshell-ui" } +redshell-protocol = { path = "crates/redshell-protocol" } gpui = "0.2.2" alacritty_terminal = "0.26.0" diff --git a/README.md b/README.md index 612f3a0..499b675 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,12 @@ after a restart and keeps your SSH hosts, tmux sessions and AI coding agents a k > сохранением комментариев. Терминал спрашивает перед закрытием, только когда можно потерять > работу (Enter и Esc в диалоге *отменяют*), сам подхватывает интеграцию с bash, zsh, fish и > PowerShell и раз в день проверяет, не вышла ли новая версия. Есть плагины (Rust, `plugin.toml` -> или хук-процесс на любом языке) и темы shadcn/tweakcn (CSS вставляется как есть). +> или хук-процесс на любом языке) и темы shadcn/tweakcn (CSS вставляется как есть). SSH-хосты +> редактируются в диалоге, пароли спрашиваются в окне RedShell и хранятся в системной связке +> ключей, есть проброс портов и файловый браузер по SFTP. `redshell-server` держит оболочки и +> агентов на всегда включённой машине, например на Raspberry Pi: десктоп открывает их как вкладки, +> а с телефона они доступны через RedShell Remote, веб-приложение с push-уведомлениями и ответами +> на запросы разрешений Claude Code. ## Why RedShell @@ -85,11 +90,13 @@ into a remote tmux or screen session. The session manager lists, attaches, creat sessions on this computer, on any SSH host and, on Windows, through a native tmux build or WSL. It lists a host in one connection and shows what it found last time while it asks again, and the sidebar's tmux section also lists the sessions on the SSH hosts you have tabs open on, checking each -about once a minute. RedShell asks for passwords, key passphrases and new host keys in its -own dialog, in the window of the tab that connects, and can remember them in the system keychain -(Windows Credential Manager, the macOS keychain or the Secret Service on Linux), where the host -editor also saves, changes or removes a host's password; this needs OpenSSH 8.4 or newer, and -older clients keep prompting in the terminal (see `ssh.askpass` in [docs/CONFIG.md](docs/CONFIG.md)). +about once a minute. + +RedShell asks for passwords, key passphrases and new host keys in its own dialog, in the window of +the tab that connects, and can remember passwords and passphrases in the system keychain (Windows +Credential Manager, the macOS keychain or the Secret Service on Linux), where the host editor also +saves, changes or removes a host's password. This needs OpenSSH 8.4 or newer; older clients keep +prompting in the terminal (see [`ssh.askpass`](docs/CONFIG.md#passwords-and-passphrases)). *Install Key on Server…* in a host's menu or editor does what `ssh-copy-id` does, which Windows lacks: it adds your public key to the host's `authorized_keys`, creating a key first if you have none. @@ -129,6 +136,30 @@ agent repaints its screen, and mouse drags reach agents that track the mouse the agent runs on an SSH host, *Paste Image* uploads a screenshot from your clipboard and types its path into the prompt, [as described below](#pasting-images-into-remote-agents). +### Sessions that keep running elsewhere + +`redshell-server` keeps shells and agents running on an always-on machine such as a Raspberry Pi, +and RedShell opens them as ordinary tabs once you add the server under *Settings → Servers* and +sign in, with a password or by approving a short code from a browser. The sidebar lists each +server's sessions with what their agents are doing, an agent's permission request shows above its +terminal with *Allow*, *Deny* and *Answer in terminal*, and closing a tab only detaches, so the +session is still there from your phone or tomorrow morning. + +On a phone you reach the same sessions through RedShell Remote, the web app the server serves, +which you add to the home screen. Its inbox puts the agents that wait for you first, a Claude Code +permission request opens as a sheet with the command or the diff, and whichever device answers +first wins. The terminal has a key bar and a composer made for a thumb, push notifications tell +you when an agent needs approval, waits for input or finishes, and you sign in with a passkey +(Face ID, Touch ID, Windows Hello, a security key) or a password. The server is one small binary +that idles at about 10 MB of memory, and [REMOTE.md](docs/REMOTE.md) explains installing it and +reaching it through Tailscale or a Cloudflare tunnel. + +

+ RedShell Remote's inbox with a Claude Code session waiting for approval first and two shells below + A Claude Code permission request as a sheet with the command and Allow, Always allow, Deny and Answer in terminal + A shell session on the phone with the composer and the key bar +

+ ### Asks before you lose work Closing a tab asks while a program is running in it, and closing a window or quitting asks when @@ -203,6 +234,20 @@ RedShell checks GitHub for a newer release once a day and tells you when there i download and install it yourself. Turn this off with `updates.check = false` (see [docs/CONFIG.md](docs/CONFIG.md#updates)). +**RedShell Server.** Releases also carry `redshell-server` for Linux on x86_64 and on aarch64 +(64-bit Raspberry Pi OS), each as a `.deb` and a `.tar.gz`, and for macOS as a `.tar.gz`. On a +Raspberry Pi, install the package and start the server as your own user, so that sessions see your +files, SSH keys and agent sign-ins, then open the one-time setup link it logs on the first start: + +```sh +sudo apt install ./redshell-server--linux-aarch64.deb +sudo systemctl enable --now redshell-server@$USER +sudo journalctl -u redshell-server@$USER +``` + +[REMOTE.md](docs/REMOTE.md) covers the other ways to install it and how to reach it from your +phone over HTTPS, which passkeys and push notifications need. + ## Build ```sh @@ -338,11 +383,17 @@ crates/ redshell-theme shadcn token model, tweakcn CSS importer (oklch/hsl/hex), registry redshell-terminal PTY + VT engine, input/mouse encoding, render snapshots, OSC 7/9;9/133 redshell-history SQLite + FTS5 recorder, search, restore, asciicast export - redshell-remote SSH profiles, ~/.ssh/config, tmux/screen over local/SSH/WSL + redshell-remote SSH hosts, askpass, tunnels, SFTP, tmux/screen over local/SSH/WSL redshell-agents AI agent detection and launch profiles redshell-plugin Plugin trait, plugin.toml manifests, JSON-lines hook processes redshell-ui shadcn-style GPUI components (Button, Input, Modal, Toast, …) and Lucide icons - redshell-app the application (workspace, terminal view, palette, settings) + redshell-app the application (workspace, terminal view, palette, settings, server tabs) + redshell-protocol wire types shared by the server, the desktop and RedShell Remote + redshell-server headless server: sessions, accounts, passkeys, push, agent hooks, hosts API +web/ RedShell Remote, the web app the server serves (React, TypeScript) +shell-integration/ the scripts that report a shell's folder and prompts +packaging/ the server's systemd unit +examples/plugins/ an example plugin ``` [Architecture](docs/ARCHITECTURE.md) explains how the crates fit together. Screenshots are taken diff --git a/assets/icon/redshell-badge.svg b/assets/icon/redshell-badge.svg new file mode 100644 index 0000000..74e85f6 --- /dev/null +++ b/assets/icon/redshell-badge.svg @@ -0,0 +1,7 @@ + + + + + diff --git a/assets/icon/redshell-maskable.svg b/assets/icon/redshell-maskable.svg new file mode 100644 index 0000000..6c5aff3 --- /dev/null +++ b/assets/icon/redshell-maskable.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + diff --git a/crates/redshell-app/Cargo.toml b/crates/redshell-app/Cargo.toml index ef2eca2..f82e8b8 100644 --- a/crates/redshell-app/Cargo.toml +++ b/crates/redshell-app/Cargo.toml @@ -20,6 +20,7 @@ redshell-remote.workspace = true redshell-agents.workspace = true redshell-plugin.workspace = true redshell-ui.workspace = true +redshell-protocol.workspace = true gpui.workspace = true anyhow.workspace = true log.workspace = true @@ -40,7 +41,12 @@ shlex = "1.3" # The HTTP client gpui already builds (through gpui_http_client), with features it already # enables, so the update check compiles nothing new. Keep the version in step with gpui's. reqwest = { package = "zed-reqwest", version = "0.12.15-zed", default-features = false, features = ["rustls-tls-native-roots"] } -tokio = { version = "1", default-features = false, features = ["rt"] } +tokio = { version = "1", default-features = false, features = ["rt", "net", "time", "macros"] } +# The WebSocket to RedShell servers (src/remote/), over the rustls with ring that +# the HTTP client already builds: no OpenSSL. +tokio-tungstenite = { version = "0.29", default-features = false, features = ["connect", "rustls-tls-native-roots"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +rustls-native-certs = "0.8" # The OS keychain that keeps SSH passwords and passphrases (src/secrets.rs), with one # store per platform below. keyring-core = "1" @@ -71,6 +77,9 @@ embed-resource = "3" [dev-dependencies] tempfile.workspace = true +# The client tests run a real server in-process. +redshell-server = { path = "../redshell-server" } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "time"] } # Installers built by cargo-packager (pinned in .github/workflows/release.yml): NSIS setup # on Windows, .deb and AppImage on Linux, a .dmg holding RedShell.app on macOS. The version diff --git a/crates/redshell-app/src/closing.rs b/crates/redshell-app/src/closing.rs index 611ef88..d8edec3 100644 --- a/crates/redshell-app/src/closing.rs +++ b/crates/redshell-app/src/closing.rs @@ -15,7 +15,8 @@ pub struct Work { pub tabs: usize, /// Live panes whose session ends with them. pub sessions: usize, - /// Live multiplexer panes: closing only detaches from their session. + /// Live multiplexer and server panes: closing only detaches from their + /// session. pub detached: usize, /// Panes in which a program other than an idle shell runs. pub programs: usize, @@ -36,7 +37,7 @@ impl Work { /// What closing one tab (or pane) made of `views` would end. pub fn of(views: &[Entity], cx: &App) -> Self { let live: Vec<_> = views.iter().map(|v| v.read(cx)).filter(|v| v.is_alive()).collect(); - let detached = live.iter().filter(|v| v.kind() == LaunchKind::Multiplexer).count(); + let detached = live.iter().filter(|v| matches!(v.kind(), LaunchKind::Multiplexer | LaunchKind::Remote)).count(); Self { tabs: usize::from(!live.is_empty()), sessions: live.len() - detached, @@ -69,8 +70,8 @@ impl Work { } match self.detached { 0 => {} - 1 => parts.push("A tmux or screen session only detaches and keeps running.".to_owned()), - n => parts.push(format!("{n} tmux or screen sessions only detach and keep running.")), + 1 => parts.push("A tmux, screen or server session only detaches and keeps running.".to_owned()), + n => parts.push(format!("{n} tmux, screen or server sessions only detach and keep running.")), } parts.extend(kept.sentence().map(str::to_owned)); parts.join(" ") @@ -139,9 +140,12 @@ mod tests { ); assert_eq!( (BUSY + TMUX).summary(Kept::Tabs), - "A program is running and will be stopped. 2 sessions will end. A tmux or screen session only \ - detaches and keeps running. Your tabs come back next time, with their output." + "A program is running and will be stopped. 2 sessions will end. A tmux, screen or server session \ + only detaches and keeps running. Your tabs come back next time, with their output." + ); + assert_eq!( + (TMUX + TMUX).summary(Kept::Nothing), + "2 tmux, screen or server sessions only detach and keep running." ); - assert_eq!((TMUX + TMUX).summary(Kept::Nothing), "2 tmux or screen sessions only detach and keep running."); } } diff --git a/crates/redshell-app/src/confirm.rs b/crates/redshell-app/src/confirm.rs index 4ba11dd..fe1acb5 100644 --- a/crates/redshell-app/src/confirm.rs +++ b/crates/redshell-app/src/confirm.rs @@ -49,6 +49,13 @@ pub enum ConfirmAction { browser: gpui::Entity, paths: Vec, }, + /// Kill a session on a RedShell server. + KillServerSession(redshell_app::remote::SessionRef), + /// Replace server `server`'s host of that name with `host`. + ReplaceServerHost { + server: String, + host: Box, + }, /// Delete a recorded session; `reopen` is the list to return to. DeleteSession { session: redshell_core::SessionId, diff --git a/crates/redshell-app/src/forward_list.rs b/crates/redshell-app/src/forward_list.rs index f25fb40..7224a33 100644 --- a/crates/redshell-app/src/forward_list.rs +++ b/crates/redshell-app/src/forward_list.rs @@ -8,7 +8,7 @@ use gpui::prelude::*; use gpui::{AnyElement, App, Context, Entity, FocusHandle, SharedString, Subscription, Window, div, px}; -use redshell_core::settings::ForwardKind; +use redshell_core::settings::{ForwardKind, ssh}; use redshell_ui::{ Button, ButtonSize, ButtonVariant, IconName, InputEvent, Segmented, Switch, TextInput, ThemeExt, alpha, space, }; @@ -187,8 +187,9 @@ impl ForwardList { fn render_row(&self, index: usize, form: &ForwardForm, cx: &mut Context) -> AnyElement { let t = cx.theme(); let ui = *t.ui(); - let (forward, problems) = form.parse(); - let (title, detail) = match (&forward.label, problems.is_empty()) { + let forward = form.parse(); + let complete = ssh::forward_errors(std::slice::from_ref(&forward)).is_empty(); + let (title, detail) = match (&forward.label, complete) { (_, false) => ("Incomplete".to_owned(), None), (Some(label), true) => (label.clone(), Some(forward.route())), (None, true) => (forward.route(), None), diff --git a/crates/redshell-app/src/host_upload.rs b/crates/redshell-app/src/host_upload.rs new file mode 100644 index 0000000..7b4da86 --- /dev/null +++ b/crates/redshell-app/src/host_upload.rs @@ -0,0 +1,102 @@ +//! Sending a saved SSH host to a RedShell server, so sessions there can +//! reach it too: the host menu's "Send to Server" lists the servers this +//! computer is signed in to. +//! +//! What is sent is the host as this computer connects to it (a host saved +//! over `~/.ssh/config` has the file's entry under it), minus its identity +//! file: that path, and the key in it, are this computer's, and the server +//! connects with its own keys. A host of that name on the server is only +//! replaced once the user says so. +//! +//! This is a child module of `workspace` so it can confirm and show toasts. + +use redshell_app::remote::{ApiFailure, runtime}; +use redshell_core::settings::SshHost; +use redshell_core::settings::ssh_wire::to_wire; +use redshell_protocol::{self as wire, ErrorCode, HostOrigin}; +use redshell_ui::MenuEntry; + +use super::*; +use crate::servers::{Server, Servers}; +use crate::ssh_hosts::HostBook; + +impl Workspace { + /// The "Send to Server" submenu of host `name`, while signed in to a + /// server. + pub(super) fn send_host_menu(&self, name: &str, cx: &mut Context) -> Option { + let ws = cx.entity().downgrade(); + let servers: Vec = Servers::all(cx) + .iter() + .filter(|s| s.signed_in()) + .map(|server| { + let (name, key) = (name.to_owned(), server.key.clone()); + let send = tab_bar::on_workspace(&ws, move |this, window, cx| this.send_host(&name, &key, window, cx)); + MenuEntry::new(server.name.clone(), send) + }) + .collect(); + (!servers.is_empty()).then(|| MenuEntry::submenu("Send to Server", servers).icon(IconName::Cloud)) + } + + /// Sends host `name` to server `key`, asking before it replaces one. + fn send_host(&mut self, name: &str, key: &str, window: &mut Window, cx: &mut Context) { + let Some(host) = sendable(&HostBook::load(cx), name) else { return }; + let Some(api) = Servers::get(key, cx).and_then(Server::api) else { return }; + let sending = runtime::spawn(async move { api.create_host(&host).await.map_err(|err| (err, host)) }); + let key = key.to_owned(); + cx.spawn_in(window, async move |this, cx| { + let sent = sending.await; + this.update_in(cx, |this, window, cx| match sent { + Ok(host) => this.host_sent(&host.name, &key, cx), + Err((ApiFailure::Refused(error), host)) if error.code == ErrorCode::Conflict => { + let server = Servers::get(&key, cx).map(|s| s.name.clone()).unwrap_or_default(); + this.confirm( + format!("Replace “{}” on {server}?", host.name), + format!("{server} has a host of that name already. It gets this computer's settings instead."), + "Replace", + ConfirmAction::ReplaceServerHost { server: key.clone(), host: Box::new(host) }, + None, + window, + cx, + ); + } + Err((err, _)) => this.host_not_sent(err, cx), + }) + .ok(); + }) + .detach(); + } + + /// Replaces the host of that name on server `key` with `host`. + pub(super) fn replace_server_host(&mut self, key: String, host: wire::SshHost, cx: &mut Context) { + let Some(api) = Servers::get(&key, cx).and_then(Server::api) else { return }; + let sending = runtime::spawn(async move { api.replace_host(&host.name, &host).await }); + cx.spawn(async move |this, cx| { + let sent = sending.await; + this.update(cx, |this, cx| match sent { + Ok(host) => this.host_sent(&host.name, &key, cx), + Err(err) => this.host_not_sent(err, cx), + }) + .ok(); + }) + .detach(); + } + + fn host_sent(&mut self, name: &str, key: &str, cx: &mut Context) { + let server = Servers::get(key, cx).map(|s| s.name.clone()).unwrap_or_default(); + let detail = "It connects with its own keys; nothing secret was sent.".to_owned(); + self.toasts.push(ToastKind::Success, format!("Sent “{name}” to {server}"), Some(detail)); + cx.notify(); + } + + fn host_not_sent(&mut self, err: ApiFailure, cx: &mut Context) { + self.toasts.push(ToastKind::Error, "Could not send the host", Some(err.to_string())); + cx.notify(); + } +} + +/// Host `name` as it is sent: as this computer connects to it, without +/// its identity file. +fn sendable(book: &HostBook, name: &str) -> Option { + let host = SshHost { identity_file: None, ..book.resolved(name)? }; + Some(to_wire(&host, HostOrigin::Redshell)) +} diff --git a/crates/redshell-app/src/lib.rs b/crates/redshell-app/src/lib.rs index a14fb4b..4675de9 100644 --- a/crates/redshell-app/src/lib.rs +++ b/crates/redshell-app/src/lib.rs @@ -1,7 +1,8 @@ //! The parts of RedShell that run without a window: the SSH askpass broker, -//! how its questions are routed to windows, and the keychain (reachable -//! from integration tests). +//! how its questions are routed to windows, the keychain, and the clients +//! of RedShell servers (reachable from integration tests). pub mod askpass; pub mod prompt_queue; +pub mod remote; pub mod secrets; diff --git a/crates/redshell-app/src/main.rs b/crates/redshell-app/src/main.rs index 762ad17..cd1ad1f 100644 --- a/crates/redshell-app/src/main.rs +++ b/crates/redshell-app/src/main.rs @@ -19,6 +19,8 @@ mod plugins_view; mod prompt_dialog; mod restore; mod search; +mod server_dialogs; +mod servers; mod settings_view; mod sftp_view; mod ssh_hosts; @@ -33,6 +35,7 @@ use gpui::{App, AppContext as _, Application, Window, WindowOptions}; use redshell_core::AppEvent; use redshell_ui::TitleBar; +use crate::servers::Servers; use crate::state::{AppState, after_settings_change, window_background_appearance}; use crate::tunnels::Tunnels; use crate::workspace::Workspace; @@ -75,6 +78,8 @@ fn main() { Workspace::answer_askpass_requests(cx); Tunnels::init(cx); Workspace::follow_tunnels(cx); + Servers::init(cx); + Workspace::follow_servers(cx); after_settings_change(cx); cx.global_mut::().emit(AppEvent::Started { version: env!("CARGO_PKG_VERSION").into() }); diff --git a/crates/redshell-app/src/overlays.rs b/crates/redshell-app/src/overlays.rs index 433fca5..39653bf 100644 --- a/crates/redshell-app/src/overlays.rs +++ b/crates/redshell-app/src/overlays.rs @@ -211,11 +211,40 @@ impl Workspace { /// Asks for a new title of the active tab (empty: automatic again). pub(super) fn open_rename(&mut self, window: &mut Window, cx: &mut Context) { + // A server session's tab is named by naming the session, for every device. + let remote = self.active_view().and_then(|v| redshell_app::remote::SessionRef::parse(&v.read(cx).profile.id)); + if let Some(target) = remote { + return self.open_rename_remote(target, window, cx); + } let Some(tab) = self.tabs.get(self.active) else { return }; - let tab_id = tab.id; - let current = tab.title(cx); + let (tab_id, current) = (tab.id, tab.title(cx)); + self.ask_name(Renaming::Tab(tab_id), current, "Tab title (empty = automatic)", window, cx); + } + + /// Asks for a new name of server session `target`. + pub(super) fn open_rename_remote( + &mut self, + target: redshell_app::remote::SessionRef, + window: &mut Window, + cx: &mut Context, + ) { + let server = crate::servers::Servers::get(&target.server, cx); + let session = server.and_then(|s| s.session(&target.session)); + let current = session.map(crate::servers::Server::session_title).unwrap_or_default(); + self.ask_name(Renaming::Session(target), current, "Session name (empty = its title)", window, cx); + } + + /// The rename dialog for `renaming`, starting from `current`. + fn ask_name( + &mut self, + renaming: Renaming, + current: String, + placeholder: &'static str, + window: &mut Window, + cx: &mut Context, + ) { let input = cx.new(|cx| { - let mut i = TextInput::new(cx).placeholder("Tab title (empty = automatic)"); + let mut i = TextInput::new(cx).placeholder(placeholder); i.set_value(current, cx); i.select_all(cx); i @@ -223,16 +252,20 @@ impl Workspace { input.read(cx).focus(window); let sub = cx.subscribe_in(&input, window, |this, input, ev: &InputEvent, window, cx| match ev { InputEvent::Submit => { - let title = input.read(cx).value().trim().to_owned(); - if let Some(Overlay::Rename(_, tab_id)) = this.overlay { - this.rename_tab(tab_id, &title, window, cx); + let name = input.read(cx).value().trim().to_owned(); + match this.overlay.as_ref() { + Some(Overlay::Rename(_, Renaming::Tab(tab_id))) => this.rename_tab(*tab_id, &name, window, cx), + Some(Overlay::Rename(_, Renaming::Session(target))) => { + this.rename_remote(target.clone(), &name, cx) + } + _ => {} } this.close_overlay(window, cx); } InputEvent::Cancel => this.close_overlay(window, cx), _ => {} }); - self.set_overlay(Overlay::Rename(input, tab_id), Some(sub), window, cx); + self.set_overlay(Overlay::Rename(input, renaming), Some(sub), window, cx); } /// Gives tab `tab_id` the name `title`, or its automatic title back when @@ -260,6 +293,7 @@ impl Workspace { } SettingsEvent::ImportTheme => this.import_theme_from_clipboard(cx), SettingsEvent::RevealConfig => this.run_command("settings.reveal", window, cx), + SettingsEvent::Notice(title, detail) => this.toasts.push(ToastKind::Info, title.clone(), detail.clone()), }); self.set_overlay(Overlay::Settings(view), Some(sub), window, cx); } diff --git a/crates/redshell-app/src/picker.rs b/crates/redshell-app/src/picker.rs index dcbe6f2..3716d5d 100644 --- a/crates/redshell-app/src/picker.rs +++ b/crates/redshell-app/src/picker.rs @@ -32,6 +32,8 @@ pub enum PickerKind { FileHosts, /// Every port forward of every host; Enter starts or stops its tunnel. Tunnels, + /// What a RedShell server can start a session from. + ServerProfiles, } #[derive(Debug, Clone, Default)] diff --git a/crates/redshell-app/src/remote/api.rs b/crates/redshell-app/src/remote/api.rs new file mode 100644 index 0000000..ac7b4ce --- /dev/null +++ b/crates/redshell-app/src/remote/api.rs @@ -0,0 +1,200 @@ +//! The server's REST API (`/api/*`, see `docs/REMOTE.md`), with the wire +//! types of `redshell-protocol`. Every call needs the tokio runtime: run +//! it through [`super::runtime::spawn`]. + +use std::fmt; +use std::time::Duration; + +use redshell_protocol::{ + ApiError, ApprovalAnswer, CreateSessionRequest, ErrorCode, PairRequest, PairStarted, PairStatus, Profile, + RenameSessionRequest, ServerInfo, SessionInfo, SignInRequest, SignInResponse, SshHost, +}; +use reqwest::{Method, Url}; +use serde::Serialize; +use serde::de::DeserializeOwned; +use zeroize::Zeroizing; + +use super::ServerUrl; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(20); + +/// Why a call failed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApiFailure { + /// The server answered with an error. + Refused(ApiError), + /// No answer: the network, the name, TLS, or a timeout. + Unreachable(String), + /// An answer this client can't read. + Unexpected(String), +} + +impl ApiFailure { + /// The server's error code, when it answered with one. + pub fn code(&self) -> Option { + match self { + Self::Refused(error) => Some(error.code), + _ => None, + } + } +} + +impl fmt::Display for ApiFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Refused(error) => f.write_str(&error.message), + Self::Unreachable(why) => write!(f, "Can't reach the server: {why}"), + Self::Unexpected(why) => write!(f, "Unexpected answer from the server: {why}"), + } + } +} + +impl std::error::Error for ApiFailure {} + +/// `err` and its causes, as one line. +pub(crate) fn describe(err: &(dyn std::error::Error + 'static)) -> String { + let mut text = err.to_string(); + let mut source = err.source(); + while let Some(cause) = source { + let line = cause.to_string(); + if !text.contains(&line) { + text = format!("{text}: {line}"); + } + source = cause.source(); + } + text +} + +/// A REST client for one server, signed in with a device token or not. +#[derive(Clone)] +pub struct Api { + url: ServerUrl, + http: reqwest::Client, + token: Option>, +} + +impl Api { + pub fn new(url: ServerUrl, token: Option>) -> Self { + let http = reqwest::Client::builder() + .user_agent(concat!("RedShell/", env!("CARGO_PKG_VERSION"))) + .timeout(REQUEST_TIMEOUT) + .build() + .unwrap_or_default(); + Self { url, http, token } + } + + pub fn url(&self) -> &ServerUrl { + &self.url + } + + /// What the server is and whether it needs setting up; open to all. + pub async fn info(&self) -> Result { + self.call(Method::GET, &["auth", "info"], None::<&()>).await + } + + /// Signs in as this device with a name and password; the response + /// carries the device token. + pub async fn sign_in(&self, request: &SignInRequest) -> Result { + self.call(Method::POST, &["auth", "sign-in"], Some(request)).await + } + + /// Revokes this device's token on the server. + pub async fn sign_out(&self) -> Result<(), ApiFailure> { + self.call_empty(Method::POST, &["auth", "sign-out"], None::<&()>).await + } + + /// Asks for a pairing request: a code to type in a signed-in browser. + pub async fn start_pairing(&self, request: &PairRequest) -> Result { + self.call(Method::POST, &["pair"], Some(request)).await + } + + /// Where pairing request `started` is; approved once, with the token. + pub async fn poll_pairing(&self, started: &PairStarted) -> Result { + let request = self.http.get(self.url.api(&["pair", &started.id])).bearer_auth(&started.poll_secret); + read(request.send().await).await + } + + pub async fn profiles(&self) -> Result, ApiFailure> { + self.call(Method::GET, &["profiles"], None::<&()>).await + } + + pub async fn sessions(&self) -> Result, ApiFailure> { + self.call(Method::GET, &["sessions"], None::<&()>).await + } + + pub async fn create_session(&self, request: &CreateSessionRequest) -> Result { + self.call(Method::POST, &["sessions"], Some(request)).await + } + + /// Names session `id`, or gives it its title back with `None`. + pub async fn rename_session(&self, id: &str, name: Option) -> Result { + self.call(Method::PATCH, &["sessions", id], Some(&RenameSessionRequest { name })).await + } + + /// Kills session `id`. + pub async fn kill_session(&self, id: &str) -> Result<(), ApiFailure> { + self.call_empty(Method::DELETE, &["sessions", id], None::<&()>).await + } + + pub async fn answer_approval(&self, id: &str, answer: &ApprovalAnswer) -> Result<(), ApiFailure> { + self.call_empty(Method::POST, &["approvals", id], Some(answer)).await + } + + /// Saves a new SSH host; `conflict` when one has its name. + pub async fn create_host(&self, host: &SshHost) -> Result { + self.call(Method::POST, &["hosts"], Some(host)).await + } + + /// Saves `host` over the server's host `name`. + pub async fn replace_host(&self, name: &str, host: &SshHost) -> Result { + self.call(Method::PUT, &["hosts", name], Some(host)).await + } + + async fn call( + &self, + method: Method, + path: &[&str], + body: Option<&impl Serialize>, + ) -> Result { + read(self.request(method, self.url.api(path), body)?.send().await).await + } + + /// A call answered with `{}`. + async fn call_empty(&self, method: Method, path: &[&str], body: Option<&impl Serialize>) -> Result<(), ApiFailure> { + self.call::(method, path, body).await.map(drop) + } + + fn request( + &self, + method: Method, + url: Url, + body: Option<&impl Serialize>, + ) -> Result { + let mut request = self + .http + .request(method, url) + .header(redshell_protocol::CHANGE_HEADER, redshell_protocol::CHANGE_HEADER_VALUE); + if let Some(token) = &self.token { + request = request.bearer_auth(token.as_str()); + } + if let Some(body) = body { + let json = serde_json::to_vec(body).map_err(|err| ApiFailure::Unexpected(err.to_string()))?; + request = request.header(reqwest::header::CONTENT_TYPE, "application/json").body(json); + } + Ok(request) + } +} + +/// The JSON body of a response, or the error it reports. +async fn read(sent: reqwest::Result) -> Result { + let response = sent.map_err(|err| ApiFailure::Unreachable(describe(&err)))?; + let status = response.status(); + let body = response.bytes().await.map_err(|err| ApiFailure::Unreachable(describe(&err)))?; + if status.is_success() { + return serde_json::from_slice(&body).map_err(|err| ApiFailure::Unexpected(err.to_string())); + } + match serde_json::from_slice::(&body) { + Ok(error) => Err(ApiFailure::Refused(error)), + Err(_) => Err(ApiFailure::Unexpected(format!("HTTP {status}"))), + } +} diff --git a/crates/redshell-app/src/remote/client.rs b/crates/redshell-app/src/remote/client.rs new file mode 100644 index 0000000..77c70a1 --- /dev/null +++ b/crates/redshell-app/src/remote/client.rs @@ -0,0 +1,628 @@ +//! The WebSocket of one server (`/api/ws`): the session list, agent +//! activity, and the terminal streams of attached sessions, over one +//! connection that comes back by itself. +//! +//! A [`ServerClient`] runs on the client runtime. Once it has a device +//! token it connects, subscribes to sessions and events, and keeps the +//! connection up: a dropped connection is retried with exponential backoff +//! and jitter ([`backoff`]). After every (re)connect the server lists its +//! sessions; then every attachment is attached again and starts over from +//! a fresh snapshot, and those whose session is no longer listed end. An +//! attachment made while connected waits for its session to be listed (a +//! session just started may not be yet). +//! The server closing the socket with 4001, or refusing the upgrade with +//! 401, means the token was revoked: the client stops until it gets a new +//! one. +//! +//! Terminal bytes never leave the client's thread on their way to an +//! attachment's [`Sink`]; everything else comes out as [`Event`]s. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded}; +use futures::{SinkExt as _, StreamExt as _}; +use redshell_protocol::{ClientMessage, PROTOCOL_VERSION, ServerMessage, Snapshot, User, frame, unframe}; +use tokio::time::Instant; +use tokio_tungstenite::tungstenite::client::IntoClientRequest as _; +use tokio_tungstenite::tungstenite::handshake::client::Request; +use tokio_tungstenite::tungstenite::http::{HeaderValue, StatusCode, header}; +use tokio_tungstenite::tungstenite::protocol::CloseFrame; +use tokio_tungstenite::tungstenite::{self, Message}; +use tokio_tungstenite::{Connector, MaybeTlsStream, WebSocketStream}; +use zeroize::Zeroizing; + +use super::api::describe; +use super::{ServerUrl, runtime}; + +/// The close code of a socket whose credential was revoked. +pub const CLOSE_UNAUTHORIZED: u16 = 4001; +const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); +/// The server pings every 30 seconds; a connection silent for longer than +/// two of those is gone. +const SILENCE: Duration = Duration::from_secs(75); +const BASE_DELAY: Duration = Duration::from_millis(500); +const MAX_DELAY: Duration = Duration::from_secs(10); + +/// Identifies one attachment of a client. +pub type AttachmentId = u64; + +/// Where an attached session's terminal goes. Called on the client's +/// thread, in the order the server sent things; dropped when the +/// attachment ends. +pub trait Sink: Send + 'static { + /// Reset the terminal, size it to `snapshot.cols` × `snapshot.rows` and + /// write `snapshot.data`. + fn snapshot(&mut self, snapshot: &Snapshot); + /// Program output. + fn output(&mut self, bytes: &[u8]); + /// The session took another size. + fn resized(&mut self, cols: u16, rows: u16); +} + +/// Where the connection is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Status { + /// No token: nothing to connect with. + SignedOut, + Connecting, + Connected { + user: User, + }, + /// The connection failed or dropped; the next attempt is on its way. + Reconnecting { + error: String, + }, + /// The server refused the token: the device was revoked. + Unauthorized, + /// The server speaks protocol version `server`, not this client's. + ProtocolMismatch { + server: u32, + }, +} + +#[derive(Debug, Clone)] +pub enum Event { + Status(Status), + /// The session list, approvals, agent events and errors, as the server + /// sent them. + Message(Box), + /// An attachment ended without being detached: its session is gone. + Ended { + attachment: AttachmentId, + session: String, + }, +} + +enum Command { + Token(Option>), + Attach { id: AttachmentId, session: String, size: Option<(u16, u16)>, sink: Box }, + Detach(AttachmentId), + Input(AttachmentId, Vec), + Resize(AttachmentId, u16, u16), + Send(ClientMessage), +} + +/// The handle of one server's connection; clones share it. The connection +/// ends when the last handle is dropped. +#[derive(Clone)] +pub struct ServerClient { + commands: UnboundedSender, + ids: Arc, +} + +impl ServerClient { + /// Starts the client for `url`, signed out; its events come out of the + /// receiver. + pub fn start(url: ServerUrl) -> (Self, UnboundedReceiver) { + let (commands, receiver) = unbounded(); + let (events, events_out) = unbounded(); + let connection = Connection { + url, + commands: receiver, + events, + token: None, + attachments: BTreeMap::new(), + channels: HashMap::new(), + listed: None, + }; + runtime::detach(connection.run()); + (Self { commands, ids: Arc::new(AtomicU64::new(1)) }, events_out) + } + + /// Connects with `token`, or disconnects with `None`. + pub fn set_token(&self, token: Option>) { + self.command(Command::Token(token)); + } + + /// Streams `session` into `sink` from the next (re)connect on, at + /// `size` when known (else the session's own). + pub fn attach(&self, session: &str, size: Option<(u16, u16)>, sink: Box) -> AttachmentId { + let id = self.ids.fetch_add(1, Ordering::Relaxed); + self.command(Command::Attach { id, session: session.to_owned(), size, sink }); + id + } + + /// Stops streaming; the session keeps running. + pub fn detach(&self, id: AttachmentId) { + self.command(Command::Detach(id)); + } + + /// Input for an attached session. Dropped while it is not attached. + pub fn input(&self, id: AttachmentId, bytes: &[u8]) { + self.command(Command::Input(id, bytes.to_vec())); + } + + /// The size the attachment's view wants. + pub fn resize(&self, id: AttachmentId, cols: u16, rows: u16) { + self.command(Command::Resize(id, cols, rows)); + } + + /// Sends `message` while connected. + pub fn send(&self, message: ClientMessage) { + self.command(Command::Send(message)); + } + + fn command(&self, command: Command) { + // Only fails once the connection task ended with the runtime. + let _ = self.commands.unbounded_send(command); + } +} + +/// The delay before reconnect attempt `attempt` (from 0): exponential up +/// to [`MAX_DELAY`], with the upper half random so clients spread out. +/// `random` is in `0.0..=1.0`. +pub fn backoff(attempt: u32, random: f64) -> Duration { + let ceiling = BASE_DELAY.saturating_mul(1 << attempt.min(16)).min(MAX_DELAY); + ceiling / 2 + ceiling.mul_f64(random.clamp(0.0, 1.0)) / 2 +} + +fn random() -> f64 { + getrandom::u32().map_or(0.5, |n| f64::from(n) / f64::from(u32::MAX)) +} + +type Socket = WebSocketStream>; + +struct Attachment { + session: String, + /// The size its view wants, once it said. + size: Option<(u16, u16)>, + channel: Option, + /// `attach` was sent on this connection and not answered yet. + requested: bool, + sink: Box, +} + +/// Why a connection ended, and so what comes next. +enum Ending { + /// Every handle is gone. + Stopped, + /// The token changed: connect again now (or wait for one). + Retry, + Unauthorized, + Mismatch(u32), + Lost(String), +} + +/// What handling a command asks of the connection. +enum Next { + Continue, + /// The token changed. + Reconnect, +} + +struct Connection { + url: ServerUrl, + commands: UnboundedReceiver, + events: UnboundedSender, + token: Option>, + /// In the order they were made, which is the order `attached` answers. + attachments: BTreeMap, + channels: HashMap, + /// The sessions the server listed on this connection, with their size. + listed: Option>, +} + +impl Connection { + async fn run(mut self) { + let mut attempt = 0; + loop { + if self.token.is_none() && !self.wait(None).await { + return; + } + if attempt == 0 { + self.status(Status::Connecting); + } + let connected = match self.request() { + Ok(request) => connect(request).await, + Err(ending) => Err(ending), + }; + let ending = match connected { + Ok(socket) => { + let (ending, greeted) = self.serve(socket).await; + if greeted { + attempt = 0; + } + ending + } + Err(ending) => ending, + }; + self.disconnected(); + match ending { + Ending::Stopped => return, + Ending::Retry => attempt = 0, + Ending::Unauthorized => { + self.token = None; + self.status(Status::Unauthorized); + attempt = 0; + } + Ending::Mismatch(server) => { + self.token = None; + self.status(Status::ProtocolMismatch { server }); + attempt = 0; + } + Ending::Lost(error) => { + self.status(Status::Reconnecting { error }); + let delay = backoff(attempt, random()); + attempt = attempt.saturating_add(1); + if !self.wait(Some(delay)).await { + return; + } + } + } + } + } + + /// Handles commands while offline, until `delay` passed (or, without + /// one, a token came) or the token changed; `false` once every handle + /// is gone. + async fn wait(&mut self, delay: Option) -> bool { + let until = delay.map(|d| Instant::now() + d); + loop { + let command = match until { + Some(until) => tokio::select! { + command = self.commands.next() => command, + () = tokio::time::sleep_until(until) => return true, + }, + None => self.commands.next().await, + }; + let Some(command) = command else { return false }; + if let Next::Reconnect = self.command(command, &mut Vec::new()) + && self.token.is_some() + { + return true; + } + } + } + + /// The upgrade request, signed with the token. + fn request(&self) -> Result { + let token = self.token.as_ref().ok_or(Ending::Retry)?; + let mut request = self.url.websocket().as_str().into_client_request().map_err(|e| lost(&e))?; + let bearer = HeaderValue::from_str(&format!("Bearer {}", token.as_str())).map_err(|e| lost(&e))?; + request.headers_mut().insert(header::AUTHORIZATION, bearer); + request + .headers_mut() + .insert(header::USER_AGENT, HeaderValue::from_static(concat!("RedShell/", env!("CARGO_PKG_VERSION")))); + Ok(request) + } + + /// Runs one connection until it ends; also says whether the server + /// greeted this client (so the backoff starts over). + async fn serve(&mut self, socket: Socket) -> (Ending, bool) { + let (mut write, mut read) = socket.split(); + let mut out = vec![json(&ClientMessage::Subscribe { sessions: true, events: true })]; + let mut greeted = false; + let mut deadline = Instant::now() + SILENCE; + loop { + for message in out.drain(..) { + if let Err(err) = write.feed(message).await { + return (Ending::Lost(describe(&err)), greeted); + } + } + if let Err(err) = write.flush().await { + return (Ending::Lost(describe(&err)), greeted); + } + tokio::select! { + incoming = read.next() => { + deadline = Instant::now() + SILENCE; + match incoming { + Some(Ok(Message::Text(text))) => match serde_json::from_str::(&text) { + Ok(message) => { + if let Err(ending) = self.receive(message, &mut out, &mut greeted) { + let _ = write.send(Message::Close(None)).await; + return (ending, greeted); + } + } + Err(err) => log::warn!("{}: unreadable message: {err}", self.url), + }, + Some(Ok(Message::Binary(bytes))) => self.output(&bytes), + Some(Ok(Message::Close(frame))) => return (closed(frame), greeted), + // Pings are answered on the next flush, at the top of the loop. + Some(Ok(_)) => {} + Some(Err(err)) => return (Ending::Lost(describe(&err)), greeted), + None => return (Ending::Lost("the connection closed".into()), greeted), + } + } + command = self.commands.next() => { + let Some(command) = command else { + let _ = write.send(Message::Close(None)).await; + return (Ending::Stopped, greeted); + }; + match self.command(command, &mut out) { + Next::Continue if greeted => self.attach_listed(&mut out, false), + Next::Continue => {} + Next::Reconnect => { + let _ = write.send(Message::Close(None)).await; + return (Ending::Retry, greeted); + } + } + } + () = tokio::time::sleep_until(deadline) => { + return (Ending::Lost("the server stopped answering".into()), greeted); + } + } + } + } + + /// Applies a command; messages it sends go to `out` (dropped offline). + fn command(&mut self, command: Command, out: &mut Vec) -> Next { + match command { + Command::Token(token) => { + if token.is_none() { + self.status(Status::SignedOut); + } + self.token = token; + return Next::Reconnect; + } + Command::Attach { id, session, size, sink } => { + self.attachments.insert(id, Attachment { session, size, channel: None, requested: false, sink }); + } + Command::Detach(id) => { + if let Some(channel) = self.attachments.remove(&id).and_then(|a| a.channel) { + self.channels.remove(&channel); + out.push(json(&ClientMessage::Detach { channel })); + } + } + Command::Input(id, bytes) => { + if let Some(channel) = self.attachments.get(&id).and_then(|a| a.channel) { + out.push(Message::Binary(frame(channel, &bytes).into())); + } + } + Command::Resize(id, cols, rows) => { + if let Some(attachment) = self.attachments.get_mut(&id) { + attachment.size = Some((cols, rows)); + if let Some(channel) = attachment.channel { + out.push(json(&ClientMessage::Resize { channel, cols, rows })); + } + } + } + Command::Send(message) => out.push(json(&message)), + } + Next::Continue + } + + /// Handles a message from the server; `Err` ends the connection. + fn receive(&mut self, message: ServerMessage, out: &mut Vec, greeted: &mut bool) -> Result<(), Ending> { + match message { + ServerMessage::Hello { protocol_version, user } => { + if protocol_version != PROTOCOL_VERSION { + return Err(Ending::Mismatch(protocol_version)); + } + *greeted = true; + self.status(Status::Connected { user }); + } + ServerMessage::Sessions { sessions } => { + self.listed = Some(sessions.iter().map(|s| (s.id.clone(), (s.cols, s.rows))).collect()); + self.attach_listed(out, true); + self.emit(Event::Message(Box::new(ServerMessage::Sessions { sessions }))); + } + ServerMessage::SessionUpdated { session } => { + if let Some(listed) = &mut self.listed { + listed.insert(session.id.clone(), (session.cols, session.rows)); + } + // A session started a moment ago may be attached before it is listed. + self.attach_listed(out, false); + self.emit(Event::Message(Box::new(ServerMessage::SessionUpdated { session }))); + } + ServerMessage::SessionRemoved { id } => { + if let Some(listed) = &mut self.listed { + listed.remove(&id); + } + // Attached ones hear `detached`; those still waiting end here. + let waiting: Vec<_> = self + .attachments + .iter() + .filter(|(_, a)| a.session == id && a.channel.is_none()) + .map(|(id, _)| *id) + .collect(); + for attachment in waiting { + self.end(attachment); + } + self.emit(Event::Message(Box::new(ServerMessage::SessionRemoved { id }))); + } + ServerMessage::Attached { channel, session, snapshot } => { + let waiting = self + .attachments + .iter_mut() + .find(|(_, a)| a.requested && a.channel.is_none() && a.session == session.id); + match waiting { + Some((id, attachment)) => { + attachment.channel = Some(channel); + attachment.requested = false; + attachment.sink.snapshot(&snapshot); + self.channels.insert(channel, *id); + } + // Detached while the attach was on its way. + None => out.push(json(&ClientMessage::Detach { channel })), + } + } + ServerMessage::Snapshot { channel, snapshot } => { + if let Some(attachment) = self.on_channel(channel) { + attachment.sink.snapshot(&snapshot); + } + } + ServerMessage::Resized { channel, cols, rows } => { + if let Some(attachment) = self.on_channel(channel) { + attachment.sink.resized(cols, rows); + } + } + ServerMessage::Detached { channel } => { + if let Some(id) = self.channels.remove(&channel) { + self.end(id); + } + } + other => self.emit(Event::Message(Box::new(other))), + } + Ok(()) + } + + /// Sends `attach` for every attachment not attached on this connection + /// whose session the server listed. With `end_unlisted` (the server just + /// listed all its sessions) the others end; otherwise they wait for + /// their session to be listed. + fn attach_listed(&mut self, out: &mut Vec, end_unlisted: bool) { + let Some(listed) = &self.listed else { return }; + let mut gone = Vec::new(); + for (id, attachment) in self.attachments.iter_mut().filter(|(_, a)| !a.requested && a.channel.is_none()) { + match listed.get(&attachment.session) { + Some(&own) => { + attachment.requested = true; + let (cols, rows) = attachment.size.unwrap_or(own); + out.push(json(&ClientMessage::Attach { session: attachment.session.clone(), cols, rows })); + } + None if end_unlisted => gone.push(*id), + None => {} + } + } + for id in gone { + self.end(id); + } + } + + fn on_channel(&mut self, channel: u16) -> Option<&mut Attachment> { + let id = self.channels.get(&channel)?; + self.attachments.get_mut(id) + } + + fn output(&mut self, bytes: &[u8]) { + if let Some((channel, bytes)) = unframe(bytes) + && let Some(attachment) = self.on_channel(channel) + { + attachment.sink.output(bytes); + } + } + + /// Ends an attachment the server let go of; its sink is dropped. + fn end(&mut self, id: AttachmentId) { + if let Some(attachment) = self.attachments.remove(&id) { + self.emit(Event::Ended { attachment: id, session: attachment.session }); + } + } + + /// Forgets the connection's channels: the next one attaches everything again. + fn disconnected(&mut self) { + self.listed = None; + self.channels.clear(); + for attachment in self.attachments.values_mut() { + attachment.channel = None; + attachment.requested = false; + } + } + + fn status(&self, status: Status) { + self.emit(Event::Status(status)); + } + + fn emit(&self, event: Event) { + // Nobody listening any more is fine: the app is going away. + let _ = self.events.unbounded_send(event); + } +} + +/// Opens the WebSocket; a refused token is [`Ending::Unauthorized`]. +async fn connect(request: Request) -> Result { + let connector = Connector::Rustls(tls_config().map_err(|e| lost(&e))?); + let connecting = tokio_tungstenite::connect_async_tls_with_config(request, None, true, Some(connector)); + match tokio::time::timeout(CONNECT_TIMEOUT, connecting).await { + Err(_) => Err(Ending::Lost("the server did not answer in time".into())), + Ok(Ok((socket, _))) => Ok(socket), + Ok(Err(tungstenite::Error::Http(response))) if response.status() == StatusCode::UNAUTHORIZED => { + Err(Ending::Unauthorized) + } + Ok(Err(err)) => Err(lost(&err)), + } +} + +fn lost(err: &(dyn std::error::Error + 'static)) -> Ending { + Ending::Lost(describe(err)) +} + +fn json(message: &ClientMessage) -> Message { + // Client messages are plain data: they always serialize. + Message::Text(serde_json::to_string(message).unwrap_or_default().into()) +} + +/// Why the server closed the socket. +fn closed(frame: Option) -> Ending { + match frame { + Some(frame) if u16::from(frame.code) == CLOSE_UNAUTHORIZED => Ending::Unauthorized, + Some(frame) if !frame.reason.is_empty() => { + Ending::Lost(format!("the server closed the connection: {}", frame.reason)) + } + _ => Ending::Lost("the server closed the connection".into()), + } +} + +/// TLS for `wss://`: rustls with ring and the system's root certificates. +fn tls_config() -> Result, rustls::Error> { + static CONFIG: OnceLock> = OnceLock::new(); + if let Some(config) = CONFIG.get() { + return Ok(config.clone()); + } + let mut roots = rustls::RootCertStore::empty(); + let native = rustls_native_certs::load_native_certs(); + for err in &native.errors { + log::warn!("reading the system's certificates: {err}"); + } + let (_added, _ignored) = roots.add_parsable_certificates(native.certs); + let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions()? + .with_root_certificates(roots) + .with_no_client_auth(); + Ok(CONFIG.get_or_init(|| Arc::new(config)).clone()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_doubles_up_to_ten_seconds_with_jitter() { + assert_eq!(backoff(0, 0.0), Duration::from_millis(250)); + assert_eq!(backoff(0, 1.0), Duration::from_millis(500)); + assert_eq!(backoff(1, 0.0), Duration::from_millis(500)); + assert_eq!(backoff(3, 1.0), Duration::from_secs(4)); + for attempt in [5, 20, u32::MAX] { + assert_eq!(backoff(attempt, 0.0), Duration::from_secs(5)); + assert_eq!(backoff(attempt, 1.0), Duration::from_secs(10)); + } + } + + #[test] + fn tls_uses_ring_and_the_system_roots() { + let config = tls_config().unwrap(); + assert!(Arc::ptr_eq(&config, &tls_config().unwrap()), "built once"); + assert!(config.crypto_provider().cipher_suites.iter().all(|s| s.suite() != rustls::CipherSuite::Unknown(0))); + } + + #[test] + fn closes_with_4001_mean_signed_out() { + let frame = |code: u16, reason: &str| Some(CloseFrame { code: code.into(), reason: reason.to_owned().into() }); + assert!(matches!(closed(frame(4001, "signed out")), Ending::Unauthorized)); + assert!(matches!(closed(frame(1001, "going away")), Ending::Lost(why) if why.contains("going away"))); + assert!(matches!(closed(None), Ending::Lost(_))); + } +} diff --git a/crates/redshell-app/src/remote/mod.rs b/crates/redshell-app/src/remote/mod.rs new file mode 100644 index 0000000..e5ab01e --- /dev/null +++ b/crates/redshell-app/src/remote/mod.rs @@ -0,0 +1,86 @@ +//! The desktop's side of RedShell servers (`redshell-server`), without any +//! window: their addresses ([`ServerUrl`]), the REST API ([`Api`]) and the +//! WebSocket that streams sessions and agent activity ([`ServerClient`]), +//! all running on one tokio thread ([`runtime`]). The app builds the +//! server list, the sign-in dialogs and the tabs on top of this. + +pub mod api; +pub mod client; +pub mod runtime; +mod url; + +pub use api::{Api, ApiFailure}; +pub use client::{AttachmentId, Event, ServerClient, Sink, Status}; +pub use url::{ServerUrl, UrlError}; + +/// A session on a server, as the profile id of the tab showing it names +/// it (`remote:#`), so the tab can be found and +/// attached again after a restart. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionRef { + /// The server's address ([`ServerUrl::as_str`]). + pub server: String, + pub session: String, +} + +impl SessionRef { + const PREFIX: &str = "remote:"; + + pub fn new(server: &str, session: &str) -> Self { + Self { server: server.to_owned(), session: session.to_owned() } + } + + pub fn profile_id(&self) -> String { + format!("{}{}#{}", Self::PREFIX, self.server, self.session) + } + + /// The session a profile id names. An address has no `#`, so the first + /// one ends it. + pub fn parse(id: &str) -> Option { + let (server, session) = id.strip_prefix(Self::PREFIX)?.split_once('#')?; + (!server.is_empty() && !session.is_empty()).then(|| Self::new(server, session)) + } +} + +/// What this computer calls itself when it signs in to a server, as the +/// server lists it under the account: `RedShell on `. +pub fn device_name() -> String { + let from_command = || { + let output = std::process::Command::new("hostname").output().ok()?; + String::from_utf8(output.stdout).ok() + }; + let host = std::env::var("COMPUTERNAME") + .ok() + .or_else(from_command) + .map(|name| name.trim().to_owned()) + .filter(|name| !name.is_empty()); + format!("RedShell on {}", host.as_deref().unwrap_or(platform())) +} + +/// This computer's system, as a pairing request shows it. +pub fn platform() -> &'static str { + if cfg!(target_os = "macos") { + "macOS" + } else if cfg!(windows) { + "Windows" + } else { + "Linux" + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn session_refs_round_trip_through_profile_ids() { + let on_a_port = SessionRef::new("http://127.0.0.1:4747", "k3#x"); + assert_eq!(on_a_port.profile_id(), "remote:http://127.0.0.1:4747#k3#x"); + assert_eq!(SessionRef::parse(&on_a_port.profile_id()), Some(on_a_port)); + let behind_a_path = SessionRef::new("https://example.com/redshell", "s1"); + assert_eq!(SessionRef::parse(&behind_a_path.profile_id()), Some(behind_a_path)); + for other in ["ssh:box", "remote:", "remote:https://box", "remote:#s1", "remote:https://box#"] { + assert_eq!(SessionRef::parse(other), None, "{other}"); + } + } +} diff --git a/crates/redshell-app/src/remote/runtime.rs b/crates/redshell-app/src/remote/runtime.rs new file mode 100644 index 0000000..97e4c19 --- /dev/null +++ b/crates/redshell-app/src/remote/runtime.rs @@ -0,0 +1,39 @@ +//! The tokio runtime server clients run on: one thread, started on first +//! use, for the rest of the process. Requests and WebSockets need tokio, +//! which GPUI's executors are not; their results come back as ordinary +//! futures any executor can await. + +use std::future::Future; +use std::sync::OnceLock; + +use tokio::runtime::{Builder, Handle}; + +fn handle() -> &'static Handle { + static HANDLE: OnceLock = OnceLock::new(); + HANDLE.get_or_init(|| { + let runtime = Builder::new_current_thread().enable_all().build().expect("starting the server client runtime"); + let handle = runtime.handle().clone(); + std::thread::Builder::new() + .name("redshell-servers".into()) + .spawn(move || runtime.block_on(std::future::pending::<()>())) + .expect("starting the server client thread"); + handle + }) +} + +/// Runs `future` on the runtime; the result can be awaited anywhere. +pub fn spawn(future: impl Future + Send + 'static) -> impl Future { + let task = handle().spawn(future); + async move { + match task.await { + Ok(value) => value, + // Tasks are never cancelled, so this is a panic: pass it on. + Err(err) => std::panic::resume_unwind(err.into_panic()), + } + } +} + +/// Starts `future` on the runtime and lets it run on its own. +pub fn detach(future: impl Future + Send + 'static) { + handle().spawn(future); +} diff --git a/crates/redshell-app/src/remote/url.rs b/crates/redshell-app/src/remote/url.rs new file mode 100644 index 0000000..c22ef15 --- /dev/null +++ b/crates/redshell-app/src/remote/url.rs @@ -0,0 +1,156 @@ +//! A server's address as the desktop keeps it. + +use std::fmt; +use std::net::IpAddr; + +use reqwest::Url; + +/// Why an address can't be a server's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum UrlError { + Invalid, + /// Not `https` (or `http`). + Scheme, + /// `http` to a machine other than this one: a bearer token would + /// cross the network in clear. + Insecure, + /// A user name, password, query or fragment, which a server address + /// never has. + Extra, +} + +impl fmt::Display for UrlError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Invalid => "Enter the server's address, like https://box.tailnet.ts.net.", + Self::Scheme => "The address starts with https://.", + Self::Insecure => "Use https://. Plain http:// is only for a server on this computer.", + Self::Extra => "Enter only the server's address, without a name, password, ? or #.", + }) + } +} + +impl std::error::Error for UrlError {} + +/// The address of a RedShell server: `https://…`, or `http://` to this +/// computer only (`localhost`, `127.0.0.1`, `::1`), with no trailing +/// slash. It names the server in `config.toml`, in the keychain and in +/// restored tabs, so equal servers have equal addresses. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ServerUrl { + url: Url, + text: String, +} + +impl ServerUrl { + /// Reads an address as typed; one without a scheme is `https`. + pub fn parse(text: &str) -> Result { + let text = text.trim(); + let with_scheme = if text.contains("://") { text.to_owned() } else { format!("https://{text}") }; + let url = Url::parse(&with_scheme).map_err(|_| UrlError::Invalid)?; + let host = url.host_str().filter(|h| !h.is_empty()).ok_or(UrlError::Invalid)?; + if !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some() { + return Err(UrlError::Extra); + } + match url.scheme() { + "https" => {} + "http" if is_loopback(host) => {} + "http" => return Err(UrlError::Insecure), + _ => return Err(UrlError::Scheme), + } + let text = url.as_str().trim_end_matches('/').to_owned(); + Ok(Self { url, text }) + } + + pub fn as_str(&self) -> &str { + &self.text + } + + /// The host (and port) for showing: `box.tailnet.ts.net`. + pub fn host(&self) -> String { + match self.url.port() { + Some(port) => format!("{}:{port}", self.url.host_str().unwrap_or_default()), + None => self.url.host_str().unwrap_or_default().to_owned(), + } + } + + /// The URL of `/api/`, each segment escaped. + pub fn api(&self, segments: &[&str]) -> Url { + self.join(std::iter::once("api").chain(segments.iter().copied())) + } + + /// The WebSocket address, `wss://…/api/ws` (`ws://` over `http`). + pub fn websocket(&self) -> Url { + let mut url = self.api(&["ws"]); + let scheme = if url.scheme() == "https" { "wss" } else { "ws" }; + // Switching between these schemes always succeeds. + let _ = url.set_scheme(scheme); + url + } + + /// The page where a signed-in browser approves a pairing request. + pub fn pair_page(&self) -> Url { + self.join(["pair"]) + } + + fn join<'a>(&self, segments: impl IntoIterator) -> Url { + let mut url = self.url.clone(); + if let Ok(mut path) = url.path_segments_mut() { + path.pop_if_empty().extend(segments); + } + url + } +} + +impl fmt::Display for ServerUrl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.text) + } +} + +/// Whether `host` (as a URL writes it) is this computer. +fn is_loopback(host: &str) -> bool { + let bare = host.trim_start_matches('[').trim_end_matches(']'); + host.eq_ignore_ascii_case("localhost") || bare.parse::().is_ok_and(|ip| ip.is_loopback()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn addresses_are_normalised() { + let url = ServerUrl::parse(" Box.Tailnet.ts.net/ ").unwrap(); + assert_eq!(url.as_str(), "https://box.tailnet.ts.net"); + assert_eq!(ServerUrl::parse("https://box.tailnet.ts.net").unwrap(), url); + let proxied = ServerUrl::parse("https://example.com:8443/redshell/").unwrap(); + assert_eq!(proxied.as_str(), "https://example.com:8443/redshell"); + assert_eq!(proxied.host(), "example.com:8443"); + assert_eq!(proxied.api(&["hosts", "my box"]).as_str(), "https://example.com:8443/redshell/api/hosts/my%20box"); + assert_eq!(proxied.websocket().as_str(), "wss://example.com:8443/redshell/api/ws"); + assert_eq!(proxied.pair_page().as_str(), "https://example.com:8443/redshell/pair"); + } + + #[test] + fn plain_http_only_reaches_this_computer() { + for ok in ["http://127.0.0.1:4747", "http://localhost:4747", "http://[::1]:4747", "http://127.1.2.3"] { + assert!(ServerUrl::parse(ok).is_ok(), "{ok}"); + } + assert_eq!( + ServerUrl::parse("http://127.0.0.1:4747").unwrap().websocket().as_str(), + "ws://127.0.0.1:4747/api/ws" + ); + for (bad, error) in [ + ("http://box.lan:4747", UrlError::Insecure), + ("http://192.168.1.2", UrlError::Insecure), + ("http://localhost.evil.com", UrlError::Insecure), + ("ftp://box", UrlError::Scheme), + ("https://me:pw@box", UrlError::Extra), + ("https://box/?code=KX7", UrlError::Extra), + ("https://", UrlError::Invalid), + ("", UrlError::Invalid), + ] { + assert_eq!(ServerUrl::parse(bad), Err(error), "{bad}"); + } + } +} diff --git a/crates/redshell-app/src/remote_tabs.rs b/crates/redshell-app/src/remote_tabs.rs new file mode 100644 index 0000000..ce35c28 --- /dev/null +++ b/crates/redshell-app/src/remote_tabs.rs @@ -0,0 +1,743 @@ +//! Sessions of RedShell servers as tabs, and the sidebar's Servers section. +//! +//! A server session opens as a pane whose terminal is fed by its server's +//! client (see [`Servers`]) instead of a local PTY: snapshots and output go +//! straight into it, keys and the pane's size go back. The grid has the +//! size the server gives the session (the size of the client that typed +//! last), which follows this pane once it is typed into. The server's +//! terminal answers the program's queries, so this one does not. +//! +//! Closing the pane only detaches: the session keeps running on the server, +//! and killing it is a separate command. A pane whose session is gone +//! before it showed anything (a restored tab) closes and says so; one whose +//! session ends while it is shown keeps its last screen. +//! +//! This is a child module of `workspace` so it can manage tabs directly. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, OnceLock}; + +use futures::StreamExt as _; +use gpui::{FontWeight, Hsla, Pixels, Point, WeakEntity, WindowHandle}; +use redshell_app::remote::{AttachmentId, ServerClient, SessionRef, Sink, runtime}; +use redshell_protocol::{ + AgentState, Approval, ApprovalAnswer, ApprovalDecision, CreateSessionRequest, Profile, SessionInfo, SessionKind, + Snapshot, +}; +use redshell_terminal::{ExternalFeed, ExternalIo, GridSize}; +use redshell_ui::{ActiveTheme, Badge, ListItem, MenuEntry, StyledExt as _}; + +use redshell_history::SessionRecord; + +use super::*; +use crate::servers::{Server, ServerChange, ServerState, Servers}; +use crate::terminal_view::ExternalBackend; + +/// The terminal side of a server pane: keys and sizes go to the client. +struct PaneIo { + client: Option, + attachment: OnceLock, +} + +impl PaneIo { + fn with(&self, f: impl FnOnce(&ServerClient, AttachmentId)) { + if let (Some(client), Some(id)) = (&self.client, self.attachment.get()) { + f(client, *id); + } + } +} + +impl ExternalIo for PaneIo { + fn write(&self, bytes: &[u8]) { + self.with(|client, id| client.input(id, bytes)); + } + + fn resize(&self, size: GridSize) { + self.with(|client, id| client.resize(id, size.cols, size.rows)); + } + + fn close(&self) { + self.with(|client, id| client.detach(id)); + } + + fn sizes_grid(&self) -> bool { + true + } +} + +/// Where a server pane's stream goes: straight into its terminal, on the +/// client's thread. +struct PaneSink { + feed: ExternalFeed, + /// Set by the first snapshot. + drawn: Arc, +} + +impl Sink for PaneSink { + fn snapshot(&mut self, snapshot: &Snapshot) { + self.drawn.store(true, Ordering::Release); + self.feed.reset(snapshot.cols, snapshot.rows); + self.feed.feed(snapshot.data.as_bytes()); + } + + fn output(&mut self, bytes: &[u8]) { + self.feed.feed(bytes); + } + + fn resized(&mut self, cols: u16, rows: u16) { + self.feed.resize(cols, rows); + } +} + +/// A server pane of this window. +struct RemotePane { + view: WeakEntity, + server: String, + attachment: AttachmentId, + drawn: Arc, +} + +/// The server panes of one window. +#[derive(Default)] +pub(super) struct RemoteState { + panes: Vec, + /// The server whose profiles the picker offers. + picking: Option, +} + +impl Workspace { + /// Shows `target` in a new tab, or the tab that has it already, in + /// whichever window that is. + pub(super) fn open_remote(&mut self, target: SessionRef, window: &mut Window, cx: &mut Context) { + if let Some(index) = self.remote_tab(&target, cx) { + return self.activate(index, window, cx); + } + let me = window.window_handle().window_id(); + let others: Vec> = cx + .windows() + .into_iter() + .filter(|w| w.window_id() != me) + .filter_map(|w| w.downcast::()) + .collect(); + for handle in others { + let shown = handle.update(cx, |ws, window, cx| { + let index = ws.remote_tab(&target, cx)?; + ws.activate(index, window, cx); + window.activate_window(); + Some(()) + }); + if matches!(shown, Ok(Some(()))) { + return; + } + } + let view = self.remote_view(&target, None, window, cx); + self.add_tab(PaneNode::Leaf(view.clone()), view, None, window, cx); + } + + /// The tab of this window showing `target`. + fn remote_tab(&self, target: &SessionRef, cx: &App) -> Option { + let id = target.profile_id(); + self.tabs.iter().position(|tab| tab.views().iter().any(|v| v.read(cx).profile.id == id)) + } + + /// A pane attached to `target`; `restored` is the recording it + /// continues (a restored pane), whose title it has until the server + /// lists the session. + pub(super) fn remote_view( + &mut self, + target: &SessionRef, + restored: Option<&SessionRecord>, + window: &mut Window, + cx: &mut Context, + ) -> Entity { + let server = Servers::get(&target.server, cx); + let info = server.and_then(|s| s.session(&target.session)).cloned(); + let server_name = server.map_or_else(|| target.server.clone(), |s| s.name.clone()); + let client = server.and_then(Server::client).cloned(); + let profile = LaunchProfile { + id: target.profile_id(), + name: match (&info, restored) { + (Some(info), _) => Server::session_title(info), + (None, Some(record)) => record.title.clone(), + (None, None) => "Server session".to_owned(), + }, + kind: LaunchKind::Remote, + description: match info.as_ref().and_then(|s| s.profile_name.clone()) { + Some(profile) => format!("{profile} on {server_name}"), + None => format!("On {server_name}"), + }, + available: true, + // No local process: a restored tab attaches its session again. + command: CommandSpec::default(), + }; + let io = Arc::new(PaneIo { client: client.clone(), attachment: OnceLock::new() }); + let drawn = Arc::new(AtomicBool::new(false)); + let backend = ExternalBackend { + io: io.clone(), + size: info.as_ref().map(|s| (s.cols, s.rows)), + connect: Box::new({ + let (io, drawn, session) = (io.clone(), drawn.clone(), target.session.clone()); + move |feed| { + if let Some(client) = &io.client { + let id = client.attach(&session, None, Box::new(PaneSink { feed, drawn })); + let _ = io.attachment.set(id); + } + } + }), + }; + let request = LaunchRequest { profile, session: restored.map(|r| r.id), prelude: None, read_only: false }; + let view = cx.new(|cx| { + let mut v = TerminalView::with_backend(request, Some(backend), window, cx); + // The folder is the server's, so the title is too: no local `cwd`. + v.custom_title = info.and_then(|s| s.name); + if client.is_none() { + v.error = Some(format!("{server_name} is no longer one of your servers. Add it again in Settings.")); + } + v + }); + if let Some(&attachment) = io.attachment.get() { + self.remote.panes.retain(|p| p.view.upgrade().is_some()); + let server = target.server.clone(); + self.remote.panes.push(RemotePane { view: view.downgrade(), server, attachment, drawn }); + } + self.adopt_view(view, window, cx) + } + + /// The session a pane shows, when it is a server's. + fn remote_of(view: &Entity, cx: &App) -> Option { + SessionRef::parse(&view.read(cx).profile.id) + } + + /// Opens a new session like the one of server pane `view` (its profile + /// or command, in its first folder). Returns `false` for other panes. + pub(super) fn remote_duplicate( + &mut self, + view: &Entity, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let Some(target) = Self::remote_of(view, cx) else { return false }; + let info = Servers::get(&target.server, cx).and_then(|s| s.session(&target.session)); + let request = info.map(|s| CreateSessionRequest { + profile: s.profile.clone(), + command: s.command.clone(), + cwd: s.start_cwd.clone(), + ..Default::default() + }); + self.start_remote(target.server, request.unwrap_or_default(), window, cx); + true + } + + /// Starts a session on server `key` and opens it. + fn start_remote( + &mut self, + key: String, + mut request: CreateSessionRequest, + window: &mut Window, + cx: &mut Context, + ) { + let Some(api) = Servers::get(&key, cx).and_then(Server::api) else { return }; + // The size of the pane it will most likely get, so it starts there. + if let Some(size) = self.active_view().and_then(|v| v.read(cx).grid_size()) { + (request.cols, request.rows) = (Some(size.cols), Some(size.rows)); + } + let starting = runtime::spawn(async move { api.create_session(&request).await }); + cx.spawn_in(window, async move |this, cx| { + let started = starting.await; + this.update_in(cx, |this, window, cx| match started { + Ok(session) => { + let target = SessionRef::new(&key, &session.id); + Servers::started(&key, session, cx); + this.open_remote(target, window, cx); + } + Err(err) => this.toasts.push(ToastKind::Error, "Could not start the session", Some(err.to_string())), + }) + .ok(); + }) + .detach(); + } + + /// Follows what windows have to show of the servers, for as long as the + /// app runs. + pub fn follow_servers(cx: &mut App) { + let Some(mut changes) = Servers::take_changes(cx) else { return }; + cx.spawn(async move |cx| { + while let Some(change) = changes.next().await { + if cx.update(|cx| Self::server_changed(change, cx)).is_err() { + break; + } + } + }) + .detach(); + } + + fn server_changed(change: ServerChange, cx: &mut App) { + let windows: Vec> = + cx.windows().into_iter().filter_map(|w| w.downcast::()).collect(); + if let ServerChange::Attention { server, session, title, detail } = change { + // Told once, in the window in front, unless it shows that session. + let active = cx.active_window().map(|w| w.window_id()); + let Some(handle) = windows.iter().find(|w| Some(w.window_id()) == active).or(windows.first()) else { + return; + }; + let target = SessionRef::new(&server, &session); + handle.update(cx, |ws, window, cx| ws.attention(target, title, detail, window, cx)).ok(); + return; + } + for handle in windows { + handle + .update(cx, |ws, window, cx| match &change { + ServerChange::Ended { server, attachment } => ws.remote_ended(server, *attachment, window, cx), + ServerChange::Sessions { server } => ws.follow_sessions(server, cx), + ServerChange::Attention { .. } => {} + }) + .ok(); + } + } + + /// A toast that a session not in front wants the user, with a button + /// that shows it. + fn attention( + &mut self, + target: SessionRef, + title: String, + detail: Option, + window: &mut Window, + cx: &mut Context, + ) { + let in_front = window.is_window_active() + && self.active_view().is_some_and(|v| v.read(cx).profile.id == target.profile_id()); + if in_front { + return; + } + let this = cx.entity().downgrade(); + let open = ToastAction::new("Open", move |window, cx| { + this.update(cx, |this, cx| this.open_remote(target.clone(), window, cx)).ok(); + }); + self.toasts.push_with_action(ToastKind::Info, title, detail, Some(open)); + cx.notify(); + } + + /// Gives the panes of `server`'s sessions their title and name as the + /// server lists them. + fn follow_sessions(&mut self, server: &str, cx: &mut Context) { + let Some(listed) = Servers::get(server, cx) else { return }; + let updates: Vec<(Entity, SessionInfo)> = self + .tabs + .iter() + .flat_map(|tab| tab.views()) + .filter_map(|view| { + let target = Self::remote_of(&view, cx).filter(|t| t.server == server)?; + Some((view, listed.session(&target.session)?.clone())) + }) + .collect(); + for (view, session) in updates { + view.update(cx, |view, cx| { + view.profile.name = session.title; + view.custom_title = session.name; + cx.emit(TerminalViewEvent::TitleChanged); + cx.notify(); + }); + } + } + + /// A pane's session is gone. One that never showed it (a restored tab) + /// closes and says so; one that did keeps its last screen, as ended. + fn remote_ended(&mut self, server: &str, attachment: AttachmentId, window: &mut Window, cx: &mut Context) { + let Some(i) = self.remote.panes.iter().position(|p| p.server == server && p.attachment == attachment) else { + return; + }; + let pane = self.remote.panes.remove(i); + let Some(view) = pane.view.upgrade().filter(|_| !pane.drawn.load(Ordering::Acquire)) else { return }; + let title = view.read(cx).title(); + let name = Servers::get(server, cx).map_or_else(|| server.to_owned(), |s| s.name.clone()); + self.toasts.push(ToastKind::Info, format!("{title} is no longer on {name}"), None); + // The last tab would take the window with it. + if self.tabs.len() == 1 && self.tabs[0].views().len() == 1 { + self.open_default_tab(window, cx); + } + self.remove_view(view.entity_id(), window, cx); + } + + fn kill_remote_confirm(&mut self, target: SessionRef, window: &mut Window, cx: &mut Context) { + let server = Servers::get(&target.server, cx); + let title = server.and_then(|s| s.session(&target.session)).map(Server::session_title).unwrap_or_default(); + let name = server.map(|s| s.name.clone()).unwrap_or_default(); + self.confirm( + format!("Kill “{title}”?"), + format!("Its program on {name} is stopped, for every device attached to it."), + "Kill session", + ConfirmAction::KillServerSession(target), + None, + window, + cx, + ); + } + + /// Kills a server session; its tabs keep their last screen. + pub(super) fn kill_remote(&mut self, target: SessionRef, cx: &mut Context) { + let Some(api) = Servers::get(&target.server, cx).and_then(Server::api) else { return }; + let killing = runtime::spawn(async move { api.kill_session(&target.session).await }); + cx.spawn(async move |this, cx| { + if let Err(err) = killing.await { + this.update(cx, |this, cx| { + this.toasts.push(ToastKind::Error, "Could not kill the session", Some(err.to_string())); + cx.notify(); + }) + .ok(); + } + }) + .detach(); + } + + /// Names a server session, or gives it its title back when empty. + pub(super) fn rename_remote(&mut self, target: SessionRef, name: &str, cx: &mut Context) { + let Some(api) = Servers::get(&target.server, cx).and_then(Server::api) else { return }; + let name = Some(name.trim().to_owned()).filter(|n| !n.is_empty()); + let renaming = runtime::spawn(async move { api.rename_session(&target.session, name).await }); + cx.spawn(async move |this, cx| { + if let Err(err) = renaming.await { + this.update(cx, |this, cx| { + this.toasts.push(ToastKind::Error, "Could not rename the session", Some(err.to_string())); + cx.notify(); + }) + .ok(); + } + }) + .detach(); + } + + /// What stands above server pane `view`: the approval its agent waits + /// for, or what keeps it from its server. + pub(super) fn remote_banner(&self, view: &Entity, cx: &mut Context) -> Option { + let target = Self::remote_of(view, cx)?; + let server = Servers::get(&target.server, cx)?; + if let Some(approval) = server.approval_of(&target.session).cloned() { + return Some(self.approval_banner(target, approval, cx)); + } + let (line, sign_in) = match &server.state { + ServerState::Connected(_) | ServerState::Checking | ServerState::Connecting => return None, + ServerState::Unreachable(_) => (format!("Reconnecting to {}…", server.name), false), + ServerState::SignedOut { .. } => (format!("Signed out of {}.", server.name), true), + other => (format!("{}: {}", server.name, other.label()), false), + }; + let t = cx.theme().clone(); + let key = target.server; + let action = sign_in.then(|| { + Button::new("remote-banner-sign-in") + .label("Sign in…") + .size(ButtonSize::Xs) + .variant(ButtonVariant::Outline) + .on_click(cx.listener(move |this, _, window, cx| this.open_servers_settings(Some(&key), window, cx))) + }); + Some(banner(&t, IconName::Cloud, t.ui().muted_foreground, line, None).children(action).into_any_element()) + } + + fn approval_banner(&self, target: SessionRef, approval: Approval, cx: &mut Context) -> AnyElement { + let t = cx.theme().clone(); + let answer = |id: &'static str, label: &'static str, variant: ButtonVariant, decision: ApprovalDecision| { + let (target, approval) = (target.clone(), approval.id.clone()); + Button::new(id) + .label(label) + .size(ButtonSize::Xs) + .variant(variant) + .on_click(cx.listener(move |this, _, _, cx| this.answer(&target, &approval, decision, cx))) + }; + let buttons = [ + answer("approval-allow", "Allow", ButtonVariant::Primary, ApprovalDecision::Allow), + answer("approval-deny", "Deny", ButtonVariant::Outline, ApprovalDecision::Deny), + answer("approval-terminal", "Answer in terminal", ButtonVariant::Ghost, ApprovalDecision::Terminal), + ]; + let summary = Some(approval.summary).filter(|s| !s.is_empty()); + banner(&t, IconName::Shield, t.ui().primary, approval.tool, summary).children(buttons).into_any_element() + } + + /// Answers approval `id` of `target`'s session. + fn answer(&mut self, target: &SessionRef, id: &str, decision: ApprovalDecision, cx: &mut Context) { + let Some(api) = Servers::get(&target.server, cx).and_then(Server::api) else { return }; + let (id, answer) = (id.to_owned(), ApprovalAnswer { decision, message: None }); + let answering = runtime::spawn(async move { api.answer_approval(&id, &answer).await }); + cx.spawn(async move |this, cx| { + if let Err(err) = answering.await { + this.update(cx, |this, cx| { + this.toasts.push(ToastKind::Error, "Could not answer the approval", Some(err.to_string())); + cx.notify(); + }) + .ok(); + } + }) + .detach(); + } + + /// The menu of a server session in the sidebar. + fn open_remote_menu( + &mut self, + target: SessionRef, + position: Point, + window: &mut Window, + cx: &mut Context, + ) { + let ws = cx.entity().downgrade(); + let on = |f: fn(&mut Workspace, SessionRef, &mut Window, &mut Context)| { + let target = target.clone(); + tab_bar::on_workspace(&ws, move |this, window, cx| f(this, target.clone(), window, cx)) + }; + let menu = Menu::build(window, cx, |menu| { + menu.at(position) + .entry(MenuEntry::new("Open", on(Self::open_remote)).icon(IconName::Terminal)) + .entry(MenuEntry::new("Rename…", on(Self::open_rename_remote)).icon(IconName::Pencil)) + .separator() + .entry(MenuEntry::new("Kill…", on(Self::kill_remote_confirm)).icon(IconName::Trash)) + }); + self.open_menu(menu, cx); + } + + /// The profiles of server `key` (shells, agents, SSH hosts), to start + /// a session from. + pub(super) fn open_remote_profiles(&mut self, key: String, window: &mut Window, cx: &mut Context) { + let Some(server) = Servers::get(&key, cx) else { return }; + let Some(api) = server.api() else { return }; + let title = format!("New session on {}", server.name); + self.remote.picking = Some(key); + self.open_picker(PickerKind::ServerProfiles, &title, "Shell, agent or SSH host…", Vec::new(), None, window, cx); + let Some(Overlay::Picker(picker)) = &self.overlay else { return }; + let picker = picker.downgrade(); + let listing = runtime::spawn(async move { api.profiles().await }); + cx.spawn(async move |this, cx| match listing.await { + Ok(profiles) => { + let items = profiles.into_iter().map(profile_item).collect(); + picker.update(cx, |p, cx| p.set_items(items, cx)).ok(); + } + Err(err) => { + this.update(cx, |this, cx| { + this.toasts.push(ToastKind::Error, "Could not list the server's profiles", Some(err.to_string())); + cx.notify(); + }) + .ok(); + } + }) + .detach(); + } + + /// A profile was picked: start it on the server being picked for. + pub(super) fn remote_pick(&mut self, profile: &str, window: &mut Window, cx: &mut Context) { + let Some(key) = self.remote.picking.take() else { return }; + let request = CreateSessionRequest { profile: Some(profile.to_owned()), ..Default::default() }; + self.start_remote(key, request, window, cx); + } + + /// Each server, then its sessions with what their agents are doing. + pub(super) fn server_rows(&self, cx: &mut Context) -> Vec { + let active = self.active_view().map(|v| v.read(cx).profile.id.clone()); + let servers: Vec<(String, String, ServerState, Vec)> = Servers::all(cx) + .iter() + .map(|s| (s.key.clone(), s.name.clone(), s.state.clone(), s.sessions.clone())) + .collect(); + let mut rows = Vec::new(); + for (key, name, state, sessions) in servers { + rows.push(self.server_header(&key, name, &state, cx)); + for session in sessions { + let target = SessionRef::new(&key, &session.id); + let selected = active.as_deref() == Some(target.profile_id().as_str()); + rows.push(self.session_row(target, &session, selected, cx)); + } + } + rows + } + + /// A server's name, where it is when not connected, and "+" for a new + /// session when it is. + fn server_header(&self, key: &str, name: String, state: &ServerState, cx: &mut Context) -> AnyElement { + let t = cx.theme().clone(); + let muted = t.ui().muted_foreground; + let action = match state { + ServerState::Connected(_) => { + let key = key.to_owned(); + Button::new(SharedString::from(format!("side-server-new-{key}"))) + .icon(IconName::Plus) + .size(ButtonSize::Xs) + .variant(ButtonVariant::Ghost) + .tooltip("New session") + .on_click( + cx.listener(move |this, _, window, cx| this.open_remote_profiles(key.clone(), window, cx)), + ) + .into_any_element() + } + other => { + let signed_out = matches!(other, ServerState::SignedOut { .. }); + let key = key.to_owned(); + div() + .id(SharedString::from(format!("side-server-state-{key}"))) + .text_size(t.text_xs()) + .text_color(alpha(muted, 0.8)) + .cursor_pointer() + .child(other.label()) + .on_click(cx.listener(move |this, _, window, cx| { + let sign_in = signed_out.then_some(key.as_str()); + this.open_servers_settings(sign_in, window, cx); + })) + .into_any_element() + } + }; + div() + .flex() + .items_center() + .gap(px(6.)) + .h(px(24.)) + .pl(px(10.)) + .pr(px(4.)) + .text_size(t.text_xs()) + .font_weight(FontWeight::MEDIUM) + .text_color(muted) + .child(div().flex_1().min_w_0().truncate_line().child(name)) + .child(action) + .into_any_element() + } + + fn session_row( + &self, + target: SessionRef, + session: &SessionInfo, + selected: bool, + cx: &mut Context, + ) -> AnyElement { + let subtitle: Vec = [session.profile_name.clone(), session.cwd.clone()].into_iter().flatten().collect(); + let badge = state_badge(session).map(|(label, variant)| Badge::new(label).variant(variant)); + let (open, menu) = (target.clone(), target.clone()); + ListItem::new(SharedString::from(format!("side-{}", target.profile_id())), Server::session_title(session)) + .icon(match session.kind { + SessionKind::Agent => IconName::Sparkles, + SessionKind::Ssh => IconName::Server, + SessionKind::Shell | SessionKind::Command => IconName::Terminal, + }) + .subtitle(subtitle.join(" · ")) + .dense(true) + .selected(selected) + .dimmed(session.exit.is_some()) + .when_some(badge, ListItem::end) + .on_click(cx.listener(move |this, _, window, cx| this.open_remote(open.clone(), window, cx))) + .on_right_click(cx.listener(move |this, ev: &gpui::MouseDownEvent, window, cx| { + // Keep the root from taking focus away from the menu. + window.prevent_default(); + this.open_remote_menu(menu.clone(), ev.position, window, cx); + })) + .into_any_element() + } + + /// Settings, at the Servers page, signing in to server `sign_in`. + pub(super) fn open_servers_settings(&mut self, sign_in: Option<&str>, window: &mut Window, cx: &mut Context) { + self.open_settings(window, cx); + if let Some(Overlay::Settings(settings)) = &self.overlay { + settings.update(cx, |settings, cx| settings.show_servers(sign_in, window, cx)); + settings.read(cx).focus_handle(cx).focus(window); + } + } +} + +/// A slim bar above a pane: an icon, a line, maybe a muted second part, +/// then the caller's buttons. +fn banner(t: &ActiveTheme, icon: IconName, tint: impl Into, line: String, detail: Option) -> gpui::Div { + let ui = t.ui(); + div() + .flex() + .items_center() + .gap(px(8.)) + .flex_none() + .h(px(34.)) + .px(px(12.)) + .border_b_1() + .border_color(ui.border) + .bg(ui.muted) + .text_size(t.text_sm()) + .child(Icon::new(icon).size(IconSize::Small).color(tint)) + .child(div().flex_none().font_weight(FontWeight::MEDIUM).text_color(ui.foreground).child(line)) + .child( + div() + .flex_1() + .min_w_0() + .truncate_line() + .font_family(t.mono_font.clone()) + .text_color(ui.muted_foreground) + .children(detail), + ) +} + +/// What a session's agent is doing, as its sidebar badge says it. +fn state_badge(session: &SessionInfo) -> Option<(&'static str, BadgeVariant)> { + if session.exit.is_some() { + return Some(("exited", BadgeVariant::Outline)); + } + if session.pending_approvals > 0 { + return Some(("needs approval", BadgeVariant::Destructive)); + } + match session.agent_state? { + AgentState::NeedsApproval => Some(("needs approval", BadgeVariant::Destructive)), + AgentState::NeedsInput => Some(("needs input", BadgeVariant::Primary)), + AgentState::Working => Some(("working", BadgeVariant::Secondary)), + AgentState::Finished => Some(("finished", BadgeVariant::Success)), + AgentState::Idle => None, + } +} + +fn profile_item(profile: Profile) -> PickerItem { + let kind = match profile.kind { + SessionKind::Agent => LaunchKind::Agent, + SessionKind::Ssh => LaunchKind::Ssh, + SessionKind::Shell | SessionKind::Command => LaunchKind::Shell, + }; + let subtitle = match &profile.group { + Some(group) => format!("{} · {group} · {}", kind.label(), profile.description), + None => format!("{} · {}", kind.label(), profile.description), + }; + PickerItem { + icon: Some(kind.into()), + title: profile.name, + subtitle, + dimmed: !profile.available, + id: profile.id, + ..Default::default() + } +} + +#[cfg(test)] +mod tests { + use redshell_protocol::ExitState; + + use super::*; + + fn session(agent_state: Option) -> SessionInfo { + SessionInfo { + id: "s1".into(), + name: None, + title: "claude".into(), + kind: SessionKind::Agent, + profile: Some("agent:claude".into()), + profile_name: Some("Claude Code".into()), + command: None, + start_cwd: None, + agent: Some("claude".into()), + agent_state, + last_message: None, + cwd: None, + cols: 80, + rows: 24, + created_at: 0, + active_at: 0, + last_line: None, + exit: None, + pending_approvals: 0, + } + } + + #[test] + fn badges_put_what_waits_for_the_user_first() { + assert_eq!(state_badge(&session(Some(AgentState::Working))).map(|b| b.0), Some("working")); + assert_eq!(state_badge(&session(Some(AgentState::NeedsInput))).map(|b| b.0), Some("needs input")); + assert_eq!(state_badge(&session(Some(AgentState::Idle))), None); + assert_eq!(state_badge(&session(None)), None); + let asking = SessionInfo { pending_approvals: 1, ..session(Some(AgentState::Working)) }; + assert_eq!(state_badge(&asking).map(|b| b.0), Some("needs approval")); + let exited = SessionInfo { exit: Some(ExitState { code: Some(0), at: 1 }), ..asking }; + assert_eq!(state_badge(&exited).map(|b| b.0), Some("exited")); + } +} diff --git a/crates/redshell-app/src/restore.rs b/crates/redshell-app/src/restore.rs index b69b5b5..787e077 100644 --- a/crates/redshell-app/src/restore.rs +++ b/crates/redshell-app/src/restore.rs @@ -12,9 +12,13 @@ //! to the user, so after a reboot they simply start fresh, in the last //! directory RedShell knew for the pane (tmux does not report the directory //! of the shell inside it, so usually the one the pane was opened in). +//! +//! Panes of a RedShell server's session attach to it again; when it is gone, +//! the pane closes and says so. use std::collections::{HashMap, HashSet}; +use redshell_app::remote::SessionRef; use redshell_core::{LaunchKind, SessionId}; use redshell_history::{SavedTab, SessionRecord}; use redshell_remote::{MuxRef, NativeRef}; @@ -51,6 +55,8 @@ pub enum PaneStep { }, /// Re-attaches a session the user chose, without creating it. Reattach { record: Box, mux: MuxRef }, + /// Attaches a RedShell server's session again. + Remote { record: Box, target: SessionRef }, } /// How one saved tab, or one natively attached tmux session, is reopened. @@ -75,6 +81,9 @@ fn reopen(record: SessionRecord) -> Option { if let Some(native) = NativeRef::parse(&record.profile.id) { return Some(Reopen::Native(native)); } + if let Some(target) = SessionRef::parse(&record.profile.id) { + return Some(Reopen::Pane(PaneStep::Remote { record: Box::new(record), target })); + } // Panes without a command, and local programs opened on a file (the // config editor), are not started again. if record.profile.command.program.is_empty() @@ -180,6 +189,7 @@ mod tests { format!("{what} {}", record.profile.id) } PaneStep::Reattach { record, .. } => format!("reattach {}", record.profile.id), + PaneStep::Remote { target, .. } => format!("attach {} on {}", target.session, target.server), } } @@ -210,6 +220,7 @@ mod tests { record("mux:local:tmux:redshell-1a2b3c", LaunchKind::Multiplexer, "tmux"), record("ssh:box", LaunchKind::Ssh, "ssh"), record("agent:claude", LaunchKind::Agent, "claude"), + record("remote:https://pi.example#k3x", LaunchKind::Remote, ""), ]; assert_eq!( summary(&plan(records, Vec::new())), @@ -219,6 +230,7 @@ mod tests { "relaunch+cwd mux:local:tmux:redshell-1a2b3c", "relaunch+replay ssh:box", "relaunch+replay agent:claude", + "attach k3x on https://pi.example", ] ); } @@ -269,7 +281,9 @@ mod tests { assert_eq!(steps.len(), 2); let RestoreStep::Tab { panes, active_pane, name, active } = &steps[0] else { unreachable!() }; let ids = panes.clone().map(|step| match step { - PaneStep::Relaunch { record, .. } | PaneStep::Reattach { record, .. } => record.id, + PaneStep::Relaunch { record, .. } | PaneStep::Reattach { record, .. } | PaneStep::Remote { record, .. } => { + record.id + } }); assert_eq!(ids, saved[0].layout.root); assert_eq!((*active_pane, name.as_deref(), *active), (b.id, Some("build"), true)); diff --git a/crates/redshell-app/src/secrets.rs b/crates/redshell-app/src/secrets.rs index 3c6cd23..d9b046f 100644 --- a/crates/redshell-app/src/secrets.rs +++ b/crates/redshell-app/src/secrets.rs @@ -1,9 +1,10 @@ -//! SSH passwords and key passphrases kept in the OS keychain: Windows -//! Credential Manager, the macOS login keychain, or the Secret Service on -//! Linux and the BSDs. +//! SSH passwords, key passphrases and RedShell servers' device tokens kept +//! in the OS keychain: Windows Credential Manager, the macOS login +//! keychain, or the Secret Service on Linux and the BSDs. //! //! Each secret is an item of service [`SERVICE`] whose account is -//! [`password_account`] or [`passphrase_account`]. Without a reachable +//! [`password_account`], [`passphrase_account`] or +//! [`server_token_account`]. Without a reachable //! keychain (no Secret Service running) nothing is remembered and //! everything else keeps working. //! @@ -31,6 +32,12 @@ pub fn passphrase_account(key: &str) -> String { format!("ssh-passphrase:{}", normalize_key_path(key)) } +/// The account of the device token a RedShell server gave this computer +/// (`url` is the server's address). +pub fn server_token_account(url: &str) -> String { + format!("server-token:{url}") +} + /// `key` with the platform's separators: Windows accepts and prints both /// `/` and `\\`, and one key must have one account. pub fn normalize_key_path(key: &str) -> String { @@ -253,12 +260,27 @@ impl Secrets { /// Deletes a host's stored password: the host is deleted, or the user /// removed it in the host editor. pub fn forget_host(&self, name: &str) { - let account = password_account(name); - if let Err(err) = self.store.delete(&account) { + self.forget(&password_account(name)); + } + + /// The device token stored for the server at `url`. + pub fn server_token(&self, url: &str) -> Option> { + self.stored(&server_token_account(url)) + } + + /// Keeps the device token of the server at `url`; an error when the + /// keychain can't, and the token lasts only as long as RedShell runs. + pub fn set_server_token(&self, url: &str, token: &str) -> anyhow::Result<()> { + self.store_secret(&server_token_account(url), token) + } + + /// Deletes what is stored for `account`. + pub fn forget(&self, account: &str) { + if let Err(err) = self.store.delete(account) { log::warn!("couldn't delete {account} from the keychain: {err:#}"); } - self.cache.lock().remove(&account); - self.stale.lock().remove(&account); + self.cache.lock().remove(account); + self.stale.lock().remove(account); } } @@ -286,6 +308,18 @@ mod tests { assert!(!secrets.has_password("other")); } + #[test] + fn server_tokens_are_kept_by_address() { + let secrets = Secrets::new(MemoryStore::default()); + let url = "https://box.example.ts.net"; + assert!(secrets.server_token(url).is_none()); + secrets.set_server_token(url, "tok").unwrap(); + assert_eq!(secrets.server_token(url).as_deref().map(String::as_str), Some("tok")); + assert!(secrets.store.get("server-token:https://box.example.ts.net").unwrap().is_some()); + secrets.forget(&server_token_account(url)); + assert!(secrets.server_token(url).is_none()); + } + #[test] fn renaming_and_deleting_a_host_moves_its_password() { let secrets = Secrets::new(MemoryStore::default().with(&password_account("old"), "pw")); diff --git a/crates/redshell-app/src/server_dialogs.rs b/crates/redshell-app/src/server_dialogs.rs new file mode 100644 index 0000000..a25c303 --- /dev/null +++ b/crates/redshell-app/src/server_dialogs.rs @@ -0,0 +1,406 @@ +//! Signing in to a RedShell server, the server giving this computer a +//! device token: with a name and password, or by pairing, where a browser +//! that is signed in already approves a short code this computer shows (so +//! it never sees a password, and passkey-only accounts work). +//! +//! The dialogs work the server list through [`Servers`] and say when they +//! are done; failures stay in the dialog, worded for the user. + +use gpui::prelude::*; +use std::time::Duration; + +use gpui::{ + App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, KeyDownEvent, SharedString, Subscription, + Task, Window, div, px, +}; +use redshell_app::remote::{Api, ApiFailure, device_name, platform, runtime}; +use redshell_protocol::{ErrorCode, PairRequest, PairStarted, PairStatus}; +use redshell_ui::{ + Button, ButtonSize, ButtonVariant, Icon, IconName, IconSize, InputEvent, Modal, TextInput, ThemeExt, key_hints, + modal_footer, modal_header, space, +}; +use zeroize::Zeroizing; + +use crate::servers::Servers; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DialogEvent { + /// Signed in. + Done, + /// Sign in with the browser instead. + Pair, + Cancel, +} + +/// The name-and-password sign-in of one server. +pub struct SignInDialog { + server: String, + title: SharedString, + username: Entity, + password: Entity, + error: Option, + signing_in: Option>, + _subs: [Subscription; 2], +} + +impl EventEmitter for SignInDialog {} + +impl Focusable for SignInDialog { + fn focus_handle(&self, cx: &App) -> FocusHandle { + let empty = self.username.read(cx).value().is_empty(); + if empty { self.username.focus_handle(cx) } else { self.password.focus_handle(cx) } + } +} + +impl SignInDialog { + pub fn new(server: &str, window: &mut Window, cx: &mut Context) -> Self { + let name = Servers::get(server, cx).map(|s| s.name.clone()).unwrap_or_default(); + let username = cx.new(|cx| TextInput::new(cx).placeholder("Name")); + let password = cx.new(|cx| TextInput::new(cx).masked(true).placeholder("Password")); + let to_password = + cx.subscribe_in(&username, window, |this: &mut Self, _, ev: &InputEvent, window, cx| match ev { + InputEvent::Submit | InputEvent::Tab => this.password.read(cx).focus(window), + InputEvent::Cancel => cx.emit(DialogEvent::Cancel), + _ => {} + }); + let submit = cx.subscribe_in(&password, window, |this: &mut Self, _, ev: &InputEvent, window, cx| match ev { + InputEvent::Submit | InputEvent::SubmitStrong => this.submit(cx), + InputEvent::BackTab => this.username.read(cx).focus(window), + InputEvent::Cancel => cx.emit(DialogEvent::Cancel), + _ => {} + }); + username.read(cx).focus(window); + Self { + server: server.to_owned(), + title: format!("Sign in to {name}").into(), + username, + password, + error: None, + signing_in: None, + _subs: [to_password, submit], + } + } + + fn submit(&mut self, cx: &mut Context) { + let username = self.username.read(cx).value().trim().to_owned(); + let password = Zeroizing::new(self.password.read(cx).value().to_owned()); + if username.is_empty() || password.is_empty() || self.signing_in.is_some() { + return; + } + self.error = None; + let signing_in = Servers::sign_in(&self.server, username, password, cx); + self.signing_in = Some(cx.spawn(async move |this, cx| { + let result = signing_in.await; + this.update(cx, |this, cx| { + this.signing_in = None; + match result { + Ok(()) => cx.emit(DialogEvent::Done), + Err(failure) => this.error = Some(sign_in_error(&failure).into()), + } + cx.notify(); + }) + .ok(); + })); + cx.notify(); + } +} + +/// What a failed sign-in tells the user. +fn sign_in_error(failure: &ApiFailure) -> String { + match failure { + ApiFailure::Refused(error) => match error.code { + ErrorCode::InvalidCredentials => "Wrong name or password.".into(), + ErrorCode::PasskeyRequired => { + "This account signs in with passkeys only. Sign in with the browser instead.".into() + } + ErrorCode::RateLimited => match error.retry_after_secs { + Some(secs) => format!("Too many attempts. Try again in {secs} s."), + None => "Too many attempts. Try again later.".into(), + }, + _ => error.message.clone(), + }, + other => other.to_string(), + } +} + +impl Render for SignInDialog { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let t = cx.theme().clone(); + let ui = *t.ui(); + let busy = self.signing_in.is_some(); + let error = self.error.clone().map(|line| { + div() + .flex() + .items_center() + .gap(space::S2) + .text_size(t.text_sm()) + .text_color(ui.destructive) + .child(Icon::new(IconName::CircleAlert).size(IconSize::Small).color(ui.destructive)) + .child(line) + }); + let buttons = vec![ + Button::new("sign-in-cancel") + .label("Cancel") + .variant(ButtonVariant::Outline) + .on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Cancel))) + .into_any_element(), + Button::new("sign-in-ok") + .label(if busy { "Signing in…" } else { "Sign in" }) + .variant(ButtonVariant::Primary) + .on_click(cx.listener(|this, _, _, cx| this.submit(cx))) + .into_any_element(), + ]; + let hint = key_hints([("enter", "sign in"), ("escape", "cancel")], cx); + let description = "This computer gets its own sign-in, which you can revoke from the server's settings."; + Modal::new("server-sign-in").width(px(440.)).child( + div() + .text_color(ui.popover_foreground) + .child(modal_header(self.title.clone(), Some(description.into()), cx)) + .child( + div() + .flex() + .flex_col() + .gap(space::S3) + .px(px(24.)) + .pt(px(8.)) + .child(self.username.clone()) + .child(self.password.clone()) + .children(error) + .child( + div().child( + Button::new("sign-in-browser") + .label("Sign in with the browser instead") + .size(ButtonSize::Sm) + .variant(ButtonVariant::Ghost) + .on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Pair))), + ), + ), + ) + .child(modal_footer(buttons, Some(hint.into_any_element()), cx)), + ) + } +} + +/// How often a waiting pairing request is asked about. +const PAIRING_POLL: Duration = Duration::from_secs(2); + +/// Where the pairing request is. +enum Pairing { + Starting, + /// The code is shown; `trouble` says the server could not be asked lately. + Waiting { + code: SharedString, + trouble: Option, + }, + /// Rejected, expired or failed: what to tell, and "Try again". + Over(String), +} + +/// Pairing with the browser: shows the code to type on the server's +/// pairing page, which it opens, and waits for the answer. +pub struct PairDialog { + server: String, + title: SharedString, + focus: FocusHandle, + pairing: Pairing, + _task: Option>, +} + +impl EventEmitter for PairDialog {} + +impl Focusable for PairDialog { + fn focus_handle(&self, _cx: &App) -> FocusHandle { + self.focus.clone() + } +} + +impl PairDialog { + pub fn new(server: &str, window: &mut Window, cx: &mut Context) -> Self { + let name = Servers::get(server, cx).map(|s| s.name.clone()).unwrap_or_default(); + let focus = cx.focus_handle(); + focus.focus(window); + let mut this = Self { + server: server.to_owned(), + title: format!("Sign in to {name} with the browser").into(), + focus, + pairing: Pairing::Starting, + _task: None, + }; + this.start(cx); + this + } + + /// Asks the server for a request, opens its pairing page and polls. + fn start(&mut self, cx: &mut Context) { + let Some(url) = Servers::get(&self.server, cx).and_then(|s| s.url().cloned()) else { return }; + self.pairing = Pairing::Starting; + let (page, api) = (url.pair_page(), Api::new(url, None)); + let key = self.server.clone(); + self._task = Some(cx.spawn(async move |this, cx| { + let request = PairRequest { device_name: device_name(), platform: Some(platform().to_owned()) }; + let starting = { + let api = api.clone(); + runtime::spawn(async move { api.start_pairing(&request).await }) + }; + let started = match starting.await { + Ok(started) => started, + Err(failure) => { + this.update(cx, |this, cx| this.over(sign_in_error(&failure), cx)).ok(); + return; + } + }; + let shown = this.update(cx, |this, cx| { + this.pairing = Pairing::Waiting { code: started.code.clone().into(), trouble: None }; + cx.open_url(page.as_str()); + cx.notify(); + }); + if shown.is_err() { + return; + } + let token = loop { + cx.background_executor().timer(PAIRING_POLL).await; + match poll(&api, &started).await { + Ok(PairStatus::Pending) => {} + Ok(PairStatus::Approved { device_token, .. }) => break Zeroizing::new(device_token), + Ok(PairStatus::Rejected) => { + let told = "The request was turned down in the browser.".to_owned(); + this.update(cx, |this, cx| this.over(told, cx)).ok(); + return; + } + Err(ApiFailure::Refused(error)) if error.code == ErrorCode::NotFound => { + let told = "The code expired. Try again for a new one.".to_owned(); + this.update(cx, |this, cx| this.over(told, cx)).ok(); + return; + } + // The server or the network may be back by the next poll. + Err(failure) => { + let gone = this.update(cx, |this, cx| { + if let Pairing::Waiting { trouble, .. } = &mut this.pairing { + *trouble = Some(failure.to_string()); + } + cx.notify(); + }); + if gone.is_err() { + return; + } + } + } + }; + this.update(cx, |_, cx| { + Servers::signed_in(&key, token, cx); + cx.emit(DialogEvent::Done); + }) + .ok(); + })); + cx.notify(); + } + + fn over(&mut self, told: String, cx: &mut Context) { + self.pairing = Pairing::Over(told); + cx.notify(); + } + + fn on_key(&mut self, ev: &KeyDownEvent, _window: &mut Window, cx: &mut Context) { + if ev.keystroke.key == "escape" { + cx.emit(DialogEvent::Cancel); + cx.stop_propagation(); + } + } +} + +async fn poll(api: &Api, started: &PairStarted) -> Result { + let (api, started) = (api.clone(), started.clone()); + runtime::spawn(async move { api.poll_pairing(&started).await }).await +} + +impl Render for PairDialog { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let t = cx.theme().clone(); + let ui = *t.ui(); + let muted = |text: String| div().text_size(t.text_sm()).text_color(ui.muted_foreground).child(text); + let body = match &self.pairing { + Pairing::Starting => muted("Asking the server for a code…".into()), + Pairing::Waiting { code, trouble } => div() + .flex() + .flex_col() + .items_center() + .gap(space::S3) + .py(space::S3) + .child( + div() + .font_family(t.mono_font.clone()) + .text_size(px(36.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(ui.foreground) + .child(code.clone()), + ) + .child(muted(match trouble { + Some(trouble) => format!("{trouble} Still waiting."), + None => "Waiting for you to approve it…".into(), + })), + Pairing::Over(told) => div() + .flex() + .items_center() + .gap(space::S2) + .text_size(t.text_sm()) + .text_color(ui.destructive) + .child(Icon::new(IconName::CircleAlert).size(IconSize::Small).color(ui.destructive)) + .child(told.clone()), + }; + let page = Servers::get(&self.server, cx).and_then(|s| s.url()).map(|url| url.pair_page()); + let again = match &self.pairing { + Pairing::Over(_) => Button::new("pair-again") + .label("Try again") + .variant(ButtonVariant::Primary) + .on_click(cx.listener(|this, _, _, cx| this.start(cx))) + .into_any_element(), + _ => Button::new("pair-open") + .label("Open the page again") + .variant(ButtonVariant::Outline) + .disabled(page.is_none()) + .on_click(move |_, _, cx| { + if let Some(page) = &page { + cx.open_url(page.as_str()); + } + }) + .into_any_element(), + }; + let buttons = vec![ + Button::new("pair-cancel") + .label("Cancel") + .variant(ButtonVariant::Ghost) + .on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Cancel))) + .into_any_element(), + again, + ]; + let description = "Type this code on the server's pairing page, which opened in your browser, and approve."; + Modal::new("server-pair").width(px(440.)).child( + div() + .track_focus(&self.focus) + .on_key_down(cx.listener(Self::on_key)) + .text_color(ui.popover_foreground) + .child(modal_header(self.title.clone(), Some(description.into()), cx)) + .child(div().px(px(24.)).pt(px(8.)).pb(px(8.)).child(body)) + .child(modal_footer(buttons, Some(key_hints([("escape", "cancel")], cx).into_any_element()), cx)), + ) + } +} + +#[cfg(test)] +mod tests { + use redshell_protocol::ApiError; + + use super::*; + + #[test] + fn refusals_are_worded_for_the_user() { + let refused = |code, retry_after_secs| { + ApiFailure::Refused(ApiError { code, message: "server words".into(), retry_after_secs }) + }; + assert_eq!(sign_in_error(&refused(ErrorCode::InvalidCredentials, None)), "Wrong name or password."); + assert!(sign_in_error(&refused(ErrorCode::PasskeyRequired, None)).contains("with the browser")); + assert_eq!(sign_in_error(&refused(ErrorCode::RateLimited, Some(8))), "Too many attempts. Try again in 8 s."); + assert_eq!(sign_in_error(&refused(ErrorCode::Forbidden, None)), "server words"); + assert!(sign_in_error(&ApiFailure::Unreachable("refused".into())).starts_with("Can't reach")); + } +} diff --git a/crates/redshell-app/src/servers.rs b/crates/redshell-app/src/servers.rs new file mode 100644 index 0000000..d33d2a2 --- /dev/null +++ b/crates/redshell-app/src/servers.rs @@ -0,0 +1,541 @@ +//! The RedShell servers of `[[remote.servers]]`, app-wide (a GPUI +//! global): a [`ServerClient`] for each, where it is, the sessions and +//! approvals it lists, and signing in and out. +//! +//! A server's device token lives in the system keychain under its address +//! and is read when the server is added to the list (at start, or when the +//! settings change). A server without one is signed out; it is asked what +//! it is, so the Servers page can tell an unreachable server or one of +//! another protocol version. Without a working keychain a token lasts until +//! RedShell quits. +//! +//! Windows follow attachments whose session is gone through +//! [`Servers::take_changes`] (one consumer). +//! + +use futures::StreamExt as _; +use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded}; +use gpui::{App, AppContext as _, AsyncApp, Global, Task}; +use redshell_app::remote::{ + Api, ApiFailure, AttachmentId, Event, ServerClient, ServerUrl, Status, UrlError, device_name, runtime, +}; +use redshell_app::secrets::server_token_account; +use redshell_core::settings::{RemoteServer, SidebarSection}; +use redshell_protocol::{ + AgentState, Approval, PROTOCOL_VERSION, ServerInfo, ServerMessage, SessionInfo, SignInRequest, User, +}; +use zeroize::Zeroizing; + +use crate::state::{AppState, update_settings}; + +/// Where a server is, as the Servers page and the sidebar say it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ServerState { + /// Its address in `config.toml` is not one RedShell connects to. + Refused(UrlError), + /// Being looked up (its token, or what it is). + Checking, + /// No device token; `revoked` when the server refused the last one. + SignedOut { + revoked: bool, + }, + Connecting, + Connected(User), + Unreachable(String), + /// The server speaks protocol version `server`, not this RedShell's. + Mismatch { + server: u32, + }, +} + +impl ServerState { + /// A short label for it. + pub fn label(&self) -> String { + match self { + Self::Refused(_) => "Address refused".into(), + Self::Checking => "Checking…".into(), + Self::SignedOut { revoked: false } => "Signed out".into(), + Self::SignedOut { revoked: true } => "Signed out by the server".into(), + Self::Connecting => "Connecting…".into(), + Self::Connected(user) => format!("Connected as {}", user.username), + Self::Unreachable(_) => "Unreachable".into(), + Self::Mismatch { .. } => "Protocol mismatch".into(), + } + } + + /// What the label leaves out, if anything. + pub fn detail(&self) -> Option { + match self { + Self::Refused(why) => Some(why.to_string()), + Self::SignedOut { revoked: true } => { + Some("This device was signed out on the server. Sign in again.".into()) + } + Self::Unreachable(why) => Some(why.clone()), + Self::Mismatch { server } => Some(format!( + "The server speaks protocol version {server} and this RedShell version {PROTOCOL_VERSION}. Update \ + the older one." + )), + _ => None, + } + } +} + +/// Something a window may have to show. +#[derive(Debug, Clone)] +pub enum ServerChange { + /// An attachment ended because its session is gone. + Ended { server: String, attachment: AttachmentId }, + /// Sessions of the server were listed or changed (title, name, folder). + Sessions { server: String }, + /// A session's agent asks for an approval or for input. + Attention { server: String, session: String, title: String, detail: Option }, +} + +/// One server of the list. +pub struct Server { + pub name: String, + /// Its address as `config.toml` has it, which names it. + pub key: String, + url: Option, + client: Option, + token: Option>, + pub state: ServerState, + /// What it lists, while connected. + pub sessions: Vec, + /// Approvals waiting for an answer. + pub approvals: Vec, + _events: Option>, +} + +impl Server { + /// Its address, unless it was refused. + pub fn url(&self) -> Option<&ServerUrl> { + self.url.as_ref() + } + + /// Whether this device has a token for it. + pub fn signed_in(&self) -> bool { + self.token.is_some() + } + + /// Whether signing in is what it needs: a valid address, no token. + pub fn needs_sign_in(&self) -> bool { + self.client.is_some() && self.token.is_none() + } + + /// The connection, for attaching sessions; there is one while the + /// address is valid, signed in or not. + pub fn client(&self) -> Option<&ServerClient> { + self.client.as_ref() + } + + /// The REST API as this device, while signed in. + pub fn api(&self) -> Option { + Some(Api::new(self.url.clone()?, Some(self.token.clone()?))) + } + + /// The oldest approval waiting in `session`. + pub fn approval_of(&self, session: &str) -> Option<&Approval> { + self.approvals.iter().filter(|a| a.session == session).min_by_key(|a| a.created_at) + } + + /// Lists `session`, or updates it when listed. + fn list(&mut self, session: SessionInfo) { + match self.sessions.iter_mut().find(|s| s.id == session.id) { + Some(listed) => *listed = session, + None => self.sessions.push(session), + } + } + + pub fn session(&self, id: &str) -> Option<&SessionInfo> { + self.sessions.iter().find(|s| s.id == id) + } + + /// What a session is called: its name, else its title. + pub fn session_title(session: &SessionInfo) -> String { + session.name.clone().unwrap_or_else(|| session.title.clone()) + } +} + +pub struct Servers { + servers: Vec, + changes: UnboundedSender, + receiver: Option>, +} + +impl Global for Servers {} + +impl Servers { + pub fn init(cx: &mut App) { + let (changes, receiver) = unbounded(); + cx.set_global(Self { servers: Vec::new(), changes, receiver: Some(receiver) }); + Self::reconcile(cx); + } + + /// What windows have to show, as it comes; the first caller gets it. + pub fn take_changes(cx: &mut App) -> Option> { + cx.global_mut::().receiver.take() + } + + pub fn all(cx: &App) -> &[Server] { + &cx.global::().servers + } + + pub fn get<'a>(key: &str, cx: &'a App) -> Option<&'a Server> { + Self::all(cx).iter().find(|s| s.key == key) + } + + fn get_mut<'a>(key: &str, cx: &'a mut App) -> Option<&'a mut Server> { + cx.global_mut::().servers.iter_mut().find(|s| s.key == key) + } + + /// Makes the list match `[[remote.servers]]`: new servers start (and + /// look for their token), removed ones disconnect. + pub fn reconcile(cx: &mut App) { + let configured = cx.global::().settings.remote.servers.clone(); + let keys: Vec = configured.iter().map(|s| key_of(&s.url)).collect(); + let mut servers = std::mem::take(&mut cx.global_mut::().servers); + servers.retain(|s| keys.contains(&s.key)); + let mut started = Vec::new(); + let list = configured + .iter() + .zip(keys) + .map(|(entry, key)| match servers.iter().position(|s| s.key == key) { + Some(i) => { + let mut server = servers.swap_remove(i); + server.name = display_name(entry); + server + } + None => { + started.push(key.clone()); + Self::start(entry, key, cx) + } + }) + .collect(); + cx.global_mut::().servers = list; + for key in started { + Self::load_token(key, cx); + } + cx.refresh_windows(); + } + + fn start(entry: &RemoteServer, key: String, cx: &mut App) -> Server { + let name = display_name(entry); + let url = ServerUrl::parse(&entry.url); + let (url, state) = match url { + Ok(url) => (Some(url), ServerState::Checking), + Err(why) => (None, ServerState::Refused(why)), + }; + let (client, events) = match &url { + Some(url) => { + let (client, events) = ServerClient::start(url.clone()); + (Some(client), Some(Self::follow(key.clone(), events, cx))) + } + None => (None, None), + }; + Server { + name, + key, + url, + client, + token: None, + state, + sessions: Vec::new(), + approvals: Vec::new(), + _events: events, + } + } + + /// Applies a client's events as they come. + fn follow(key: String, mut events: UnboundedReceiver, cx: &mut App) -> Task<()> { + cx.spawn(async move |cx: &mut AsyncApp| { + while let Some(event) = events.next().await { + if cx.update(|cx| Self::apply(&key, event, cx)).is_err() { + break; + } + } + }) + } + + /// Reads the server's token from the keychain, then connects with it + /// or finds out what the server is. + fn load_token(key: String, cx: &mut App) { + let secrets = cx.global::().secrets.clone(); + let account = key.clone(); + let read = cx.background_spawn(async move { secrets.server_token(&account) }); + cx.spawn(async move |cx: &mut AsyncApp| { + let token = read.await; + cx.update(|cx| match token { + Some(token) => Self::connect(&key, token, cx), + None => Self::check(&key, cx), + }) + .ok(); + }) + .detach(); + } + + /// Connects server `key` with `token`, kept in memory for this run. + fn connect(key: &str, token: Zeroizing, cx: &mut App) { + let Some(server) = Self::get_mut(key, cx) else { return }; + if let Some(client) = &server.client { + client.set_token(Some(token.clone())); + server.token = Some(token); + server.state = ServerState::Connecting; + } + cx.refresh_windows(); + } + + /// Asks a signed-out server what it is. + pub fn check(key: &str, cx: &mut App) { + let Some(url) = Self::get(key, cx).and_then(|s| s.url.clone()) else { return }; + let api = Api::new(url, None); + let info = runtime::spawn(async move { api.info().await }); + let key = key.to_owned(); + cx.spawn(async move |cx: &mut AsyncApp| { + let info = info.await; + cx.update(|cx| { + let Some(server) = Self::get_mut(&key, cx).filter(|s| s.token.is_none()) else { return }; + let revoked = matches!(server.state, ServerState::SignedOut { revoked: true }); + server.state = match info { + Ok(ServerInfo { protocol_version, .. }) if protocol_version != PROTOCOL_VERSION => { + ServerState::Mismatch { server: protocol_version } + } + Ok(_) => ServerState::SignedOut { revoked }, + Err(failure) => ServerState::Unreachable(failure.to_string()), + }; + cx.refresh_windows(); + }) + .ok(); + }) + .detach(); + } + + fn apply(key: &str, event: Event, cx: &mut App) { + let changes = cx.global::().changes.clone(); + let Some(server) = Self::get_mut(key, cx) else { return }; + let mut forget_token = false; + match event { + Event::Status(status) => { + server.state = match status { + Status::SignedOut => ServerState::SignedOut { revoked: false }, + Status::Connecting => ServerState::Connecting, + Status::Connected { user } => ServerState::Connected(user), + Status::Reconnecting { error } => ServerState::Unreachable(error), + Status::Unauthorized => { + forget_token = server.token.take().is_some(); + ServerState::SignedOut { revoked: true } + } + Status::ProtocolMismatch { server } => ServerState::Mismatch { server }, + }; + if !matches!(server.state, ServerState::Connected(_) | ServerState::Unreachable(_)) { + server.sessions.clear(); + server.approvals.clear(); + } + } + Event::Ended { attachment, .. } => { + let _ = changes.unbounded_send(ServerChange::Ended { server: key.to_owned(), attachment }); + } + Event::Message(message) => { + for change in Self::receive(server, *message) { + let _ = changes.unbounded_send(change); + } + } + } + if forget_token { + let secrets = cx.global::().secrets.clone(); + let account = server_token_account(key); + cx.background_spawn(async move { secrets.forget(&account) }).detach(); + } + cx.refresh_windows(); + } + + /// Keeps `server`'s lists up to date; returns what windows have to show + /// of it. + fn receive(server: &mut Server, message: ServerMessage) -> Vec { + let key = server.key.clone(); + let sessions_changed = ServerChange::Sessions { server: key.clone() }; + match message { + ServerMessage::Sessions { sessions } => { + server.sessions = sessions; + vec![sessions_changed] + } + ServerMessage::SessionUpdated { session } => { + let before = server.session(&session.id).and_then(|s| s.agent_state); + let asks = session.agent_state == Some(AgentState::NeedsInput) && before != session.agent_state; + let attention = asks.then(|| ServerChange::Attention { + server: key, + session: session.id.clone(), + title: format!("{} needs input", Server::session_title(&session)), + detail: session.last_message.clone(), + }); + server.list(session); + [sessions_changed].into_iter().chain(attention).collect() + } + ServerMessage::SessionRemoved { id } => { + server.sessions.retain(|s| s.id != id); + server.approvals.retain(|a| a.session != id); + Vec::new() + } + ServerMessage::Approvals { approvals } => { + server.approvals = approvals; + Vec::new() + } + ServerMessage::ApprovalRequested { approval } => { + let title = match server.session(&approval.session) { + Some(session) => format!("{} asks to use {}", Server::session_title(session), approval.tool), + None => format!("An agent asks to use {}", approval.tool), + }; + let attention = ServerChange::Attention { + server: key, + session: approval.session.clone(), + title, + detail: Some(approval.summary.clone()).filter(|s| !s.is_empty()), + }; + server.approvals.retain(|a| a.id != approval.id); + server.approvals.push(approval); + vec![attention] + } + ServerMessage::ApprovalResolved { id, .. } => { + server.approvals.retain(|a| a.id != id); + Vec::new() + } + ServerMessage::Error { message, .. } => { + log::warn!("{key}: {message}"); + Vec::new() + } + _ => Vec::new(), + } + } + + /// A session this device just started, listed before the server says + /// so, for its tab to know it. + pub fn started(key: &str, session: SessionInfo, cx: &mut App) { + if let Some(server) = Self::get_mut(key, cx) { + server.list(session); + } + } + + /// Signs in to server `key` as this device with a name and password. + pub fn sign_in( + key: &str, + username: String, + password: Zeroizing, + cx: &mut App, + ) -> Task> { + let Some(url) = Self::get(key, cx).and_then(|s| s.url.clone()) else { + return Task::ready(Err(ApiFailure::Unexpected("no such server".into()))); + }; + let api = Api::new(url, None); + let request = + SignInRequest { username, password: password.as_str().to_owned(), device_name: Some(device_name()) }; + let signing_in = runtime::spawn(async move { api.sign_in(&request).await }); + let key = key.to_owned(); + cx.spawn(async move |cx: &mut AsyncApp| { + let response = signing_in.await?; + let token = response.device_token.ok_or_else(|| ApiFailure::Unexpected("no device token".into()))?; + cx.update(|cx| Self::signed_in(&key, Zeroizing::new(token), cx)) + .map_err(|_| ApiFailure::Unexpected("RedShell is closing".into())) + }) + } + + /// Keeps a new device token and connects with it. + pub fn signed_in(key: &str, token: Zeroizing, cx: &mut App) { + let secrets = cx.global::().secrets.clone(); + let (account, stored) = (key.to_owned(), token.clone()); + cx.background_spawn(async move { + if let Err(err) = secrets.set_server_token(&account, &stored) { + log::warn!("the token of {account} lasts until RedShell quits: {err:#}"); + } + }) + .detach(); + Self::connect(key, token, cx); + } + + /// Signs this device out of server `key`: the server revokes its token + /// (when it can be reached) and the keychain forgets it. Resolves to + /// whether the server was told. + pub fn sign_out(key: &str, cx: &mut App) -> Task { + let Some(server) = Self::get_mut(key, cx) else { return Task::ready(true) }; + let api = server.api(); + server.token = None; + if let Some(client) = &server.client { + client.set_token(None); + } + let secrets = cx.global::().secrets.clone(); + let account = server_token_account(key); + cx.background_spawn(async move { secrets.forget(&account) }).detach(); + let Some(api) = api else { return Task::ready(true) }; + let revoking = runtime::spawn(async move { api.sign_out().await }); + cx.background_spawn(async move { + match revoking.await { + Ok(()) => true, + Err(err) => { + log::warn!("signing out: {err}"); + false + } + } + }) + } + + /// Adds a server to `[[remote.servers]]`; its name defaults to its host. + pub fn add(name: &str, url: &str, cx: &mut App) -> Result { + let url = ServerUrl::parse(url).map_err(|e| e.to_string())?; + if Self::get(url.as_str(), cx).is_some() { + return Err("This server is in the list already.".into()); + } + let name = Some(name.trim()).filter(|n| !n.is_empty()).map_or_else(|| url.host(), str::to_owned); + let entry = RemoteServer { name, url: url.as_str().to_owned() }; + update_settings(cx, |s| { + // The first server brings its sidebar section. + if s.remote.servers.is_empty() { + s.appearance.set_sidebar_section(SidebarSection::Servers, true); + } + s.remote.servers.push(entry); + }); + Ok(url.as_str().to_owned()) + } + + /// Signs out of server `key` and takes it off the list. + pub fn remove(key: &str, cx: &mut App) { + Self::sign_out(key, cx).detach(); + let key = key.to_owned(); + update_settings(cx, |s| s.remote.servers.retain(|server| key_of(&server.url) != key)); + } +} + +/// What names a configured server: its normalised address, or the text of +/// one RedShell refuses. +fn key_of(url: &str) -> String { + ServerUrl::parse(url).map_or_else(|_| url.trim().to_owned(), |url| url.as_str().to_owned()) +} + +fn display_name(entry: &RemoteServer) -> String { + let name = entry.name.trim(); + if !name.is_empty() { + return name.to_owned(); + } + ServerUrl::parse(&entry.url).map_or_else(|_| entry.url.clone(), |url| url.host()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn servers_are_named_by_their_normalised_address() { + assert_eq!(key_of("Box.example.ts.net/"), "https://box.example.ts.net"); + assert_eq!(key_of(" http://box.lan "), "http://box.lan", "refused addresses keep their text"); + let unnamed = RemoteServer { name: " ".into(), url: "https://box.example.ts.net:8443".into() }; + assert_eq!(display_name(&unnamed), "box.example.ts.net:8443"); + } + + #[test] + fn states_say_what_to_do() { + assert_eq!(ServerState::SignedOut { revoked: false }.label(), "Signed out"); + assert!(ServerState::SignedOut { revoked: true }.detail().unwrap().contains("Sign in again")); + let mismatch = ServerState::Mismatch { server: PROTOCOL_VERSION + 1 }.detail().unwrap(); + assert!(mismatch.contains(&format!("version {}", PROTOCOL_VERSION + 1))); + let user = User { id: 1, username: "me".into(), created_at: 0 }; + assert_eq!(ServerState::Connected(user).label(), "Connected as me"); + } +} diff --git a/crates/redshell-app/src/settings_view.rs b/crates/redshell-app/src/settings_view.rs index aaf79be..df17249 100644 --- a/crates/redshell-app/src/settings_view.rs +++ b/crates/redshell-app/src/settings_view.rs @@ -14,15 +14,19 @@ use crate::state::{AppState, update_settings}; mod options; mod pages; +mod servers; use options::{Tab, follows_system, font_choices, pick_theme}; use pages::reset_section; +use servers::{Notice, ServersPage}; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum SettingsEvent { Close, EditFile, ImportTheme, RevealConfig, + /// A toast for the window: its title and details. + Notice(String, Option), } /// Which font setting the font picker edits. @@ -38,16 +42,19 @@ pub struct SettingsView { font_picker: Option<(FontTarget, Entity, Subscription)>, /// The section whose reset button was clicked once (a second click resets). reset_armed: Option, + /// The Servers page, once shown; it keeps its dialogs and typed text. + servers: Option<(Entity, Subscription)>, } impl EventEmitter for SettingsView {} impl Focusable for SettingsView { fn focus_handle(&self, cx: &App) -> FocusHandle { - match &self.font_picker { - Some((_, picker, _)) => picker.focus_handle(cx), - None => self.focus.clone(), + if let Some((_, picker, _)) = &self.font_picker { + return picker.focus_handle(cx); } + let dialog = self.servers.as_ref().and_then(|(page, _)| page.read(cx).dialog_focus(cx)); + dialog.unwrap_or_else(|| self.focus.clone()) } } @@ -55,7 +62,30 @@ impl SettingsView { pub fn new(window: &mut Window, cx: &mut Context) -> Self { let focus = cx.focus_handle(); focus.focus(window); - Self { focus, tab: Tab::Appearance, font_picker: None, reset_armed: None } + Self { focus, tab: Tab::Appearance, font_picker: None, reset_armed: None, servers: None } + } + + /// Turns to the Servers page, signing in to server `sign_in` there. + pub fn show_servers(&mut self, sign_in: Option<&str>, window: &mut Window, cx: &mut Context) { + self.tab = Tab::Servers; + if let Some(key) = sign_in { + let page = self.servers_page(window, cx); + page.update(cx, |page, cx| page.sign_in(key, window, cx)); + } + cx.notify(); + } + + /// The Servers page, made the first time it is shown. + fn servers_page(&mut self, window: &mut Window, cx: &mut Context) -> Entity { + if let Some((page, _)) = &self.servers { + return page.clone(); + } + let page = cx.new(|cx| ServersPage::new(window, cx)); + let sub = cx.subscribe(&page, |_, _, Notice(title, detail): &Notice, cx| { + cx.emit(SettingsEvent::Notice(title.clone(), detail.clone())); + }); + self.servers = Some((page.clone(), sub)); + page } fn open_font_picker(&mut self, target: FontTarget, window: &mut Window, cx: &mut Context) { @@ -267,12 +297,18 @@ impl SettingsView { } impl Render for SettingsView { - fn render(&mut self, _w: &mut Window, cx: &mut Context) -> impl IntoElement { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = cx.theme().clone(); let ui = *t.ui(); - let rows = self.tab.rows(&cx.global::().settings); - let body: Vec = rows.into_iter().filter_map(|row| row.render(cx)).collect(); - let reset = self.reset_button(cx); + // The Servers page is not a list of settings, and has nothing to reset. + let (body, reset): (Vec, Option) = if self.tab == Tab::Servers { + (vec![self.servers_page(window, cx).into_any_element()], None) + } else { + let rows = self.tab.rows(&cx.global::().settings); + (rows.into_iter().filter_map(|row| row.render(cx)).collect(), Some(self.reset_button(cx))) + }; + let dialog = + self.servers.as_ref().filter(|_| self.tab == Tab::Servers).and_then(|(page, _)| page.read(cx).dialog()); let problems = cx.global::().problems.clone(); let this = cx.entity().downgrade(); let close = this.clone(); @@ -352,10 +388,15 @@ impl Render for SettingsView { .child(SharedString::from(p)) })) .children(body) - .child(reset), + .children(reset), ), ); - // The font picker opens on top of the settings card. - div().absolute().inset_0().child(modal).children(self.font_picker.as_ref().map(|(_, p, _)| p.clone())) + // The font picker and the sign-in dialogs open on top of the settings card. + div() + .absolute() + .inset_0() + .child(modal) + .children(self.font_picker.as_ref().map(|(_, p, _)| p.clone())) + .children(dialog) } } diff --git a/crates/redshell-app/src/settings_view/options.rs b/crates/redshell-app/src/settings_view/options.rs index 9fd7c2a..107b406 100644 --- a/crates/redshell-app/src/settings_view/options.rs +++ b/crates/redshell-app/src/settings_view/options.rs @@ -55,11 +55,13 @@ pub enum Tab { Terminal, Safety, Sessions, + Servers, Keys, } impl Tab { - pub const ALL: [Self; 5] = [Self::Appearance, Self::Terminal, Self::Safety, Self::Sessions, Self::Keys]; + pub const ALL: [Self; 6] = + [Self::Appearance, Self::Terminal, Self::Safety, Self::Sessions, Self::Servers, Self::Keys]; pub fn label(self) -> &'static str { match self { @@ -67,6 +69,7 @@ impl Tab { Self::Terminal => "Terminal", Self::Safety => "Safety", Self::Sessions => "Sessions", + Self::Servers => "Servers", Self::Keys => "Keybindings", } } @@ -77,6 +80,7 @@ impl Tab { Self::Terminal => IconName::Terminal, Self::Safety => IconName::Shield, Self::Sessions => IconName::History, + Self::Servers => IconName::Cloud, Self::Keys => IconName::Keyboard, } } diff --git a/crates/redshell-app/src/settings_view/pages.rs b/crates/redshell-app/src/settings_view/pages.rs index b0e1220..41b21e9 100644 --- a/crates/redshell-app/src/settings_view/pages.rs +++ b/crates/redshell-app/src/settings_view/pages.rs @@ -184,6 +184,8 @@ impl Tab { Tab::Terminal => terminal(s), Tab::Safety => safety(s), Tab::Sessions => sessions(s), + // A page of its own (`servers.rs`): no rows, and nothing to reset. + Tab::Servers => Vec::new(), Tab::Keys => keybindings(s), } } diff --git a/crates/redshell-app/src/settings_view/servers.rs b/crates/redshell-app/src/settings_view/servers.rs new file mode 100644 index 0000000..9f37754 --- /dev/null +++ b/crates/redshell-app/src/settings_view/servers.rs @@ -0,0 +1,265 @@ +//! The Servers page of the Settings panel: the RedShell servers this +//! computer opens sessions of, where each is, signing in and out, and +//! adding and removing them. Its sign-in dialogs open over the panel. + +use gpui::prelude::*; +use gpui::{ + AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, SharedString, Subscription, + Window, div, px, +}; +use redshell_ui::{ + Badge, BadgeVariant, Button, ButtonSize, ButtonVariant, IconName, InputEvent, StyledExt, TextInput, ThemeExt, + section_label, space, +}; + +use crate::server_dialogs::{DialogEvent, PairDialog, SignInDialog}; +use crate::servers::{Server, ServerState, Servers}; + +/// A toast the page asks the window for. +#[derive(Debug, Clone)] +pub struct Notice(pub String, pub Option); + +pub struct ServersPage { + focus: FocusHandle, + url: Entity, + name: Entity, + error: Option, + /// The open dialog and the server it signs in to. + dialog: Option<(Dialog, String, Subscription)>, + _subs: [Subscription; 2], +} + +impl EventEmitter for ServersPage {} + +/// The sign-in dialog open over the page. +enum Dialog { + Password(Entity), + Browser(Entity), +} + +impl ServersPage { + pub fn new(window: &mut Window, cx: &mut Context) -> Self { + let url = cx.new(|cx| TextInput::new(cx).placeholder("https://box.tailnet.ts.net")); + let name = cx.new(|cx| TextInput::new(cx).placeholder("Name (optional)")); + let on_input = + |this: &mut Self, _: &Entity, ev: &InputEvent, window: &mut Window, cx: &mut Context| { + match ev { + InputEvent::Submit => this.add(window, cx), + InputEvent::Cancel => this.focus.focus(window), + InputEvent::Changed(_) if this.error.is_some() => { + this.error = None; + cx.notify(); + } + _ => {} + } + }; + let subs = [cx.subscribe_in(&url, window, on_input), cx.subscribe_in(&name, window, on_input)]; + // Signed-out servers may have come back, or gone, since they were looked at. + let signed_out: Vec = + Servers::all(cx).iter().filter(|s| s.needs_sign_in()).map(|s| s.key.clone()).collect(); + for key in signed_out { + Servers::check(&key, cx); + } + Self { focus: cx.focus_handle(), url, name, error: None, dialog: None, _subs: subs } + } + + /// The open dialog, drawn over the whole panel. + pub fn dialog(&self) -> Option { + self.dialog.as_ref().map(|(dialog, ..)| match dialog { + Dialog::Password(d) => d.clone().into_any_element(), + Dialog::Browser(d) => d.clone().into_any_element(), + }) + } + + /// Where the keyboard goes while a dialog is open. + pub fn dialog_focus(&self, cx: &App) -> Option { + self.dialog.as_ref().map(|(dialog, ..)| match dialog { + Dialog::Password(d) => d.read(cx).focus_handle(cx), + Dialog::Browser(d) => d.read(cx).focus_handle(cx), + }) + } + + fn add(&mut self, window: &mut Window, cx: &mut Context) { + let url = self.url.read(cx).value().to_owned(); + let name = self.name.read(cx).value().to_owned(); + match Servers::add(&name, &url, cx) { + Ok(key) => { + self.error = None; + self.url.update(cx, |input, cx| input.set_value("", cx)); + self.name.update(cx, |input, cx| input.set_value("", cx)); + self.sign_in(&key, window, cx); + } + Err(why) => self.error = Some(why.into()), + } + cx.notify(); + } + + pub fn sign_in(&mut self, key: &str, window: &mut Window, cx: &mut Context) { + let dialog = cx.new(|cx| SignInDialog::new(key, window, cx)); + let sub = cx.subscribe_in(&dialog, window, Self::on_dialog); + self.dialog = Some((Dialog::Password(dialog), key.to_owned(), sub)); + cx.notify(); + } + + /// Pairs with server `key` from the browser. + fn pair(&mut self, key: &str, window: &mut Window, cx: &mut Context) { + let dialog = cx.new(|cx| PairDialog::new(key, window, cx)); + let sub = cx.subscribe_in(&dialog, window, Self::on_dialog); + self.dialog = Some((Dialog::Browser(dialog), key.to_owned(), sub)); + cx.notify(); + } + + fn on_dialog(&mut self, _: &Entity, ev: &DialogEvent, window: &mut Window, cx: &mut Context) { + match ev { + DialogEvent::Done | DialogEvent::Cancel => self.close_dialog(window, cx), + DialogEvent::Pair => { + let Some((_, key, _)) = self.dialog.take() else { return }; + self.pair(&key, window, cx); + } + } + } + + fn close_dialog(&mut self, window: &mut Window, cx: &mut Context) { + self.dialog = None; + self.focus.focus(window); + cx.notify(); + } + + fn sign_out(&mut self, key: &str, cx: &mut Context) { + let name = Servers::get(key, cx).map(|s| s.name.clone()).unwrap_or_default(); + let told = Servers::sign_out(key, cx); + cx.spawn(async move |this, cx| { + if !told.await { + let detail = "It could not be told, so revoke this device in its settings.".to_owned(); + this.update(cx, |_, cx| cx.emit(Notice(format!("Signed out of {name} here"), Some(detail)))).ok(); + } + }) + .detach(); + } + + /// One server: its name, address and state, and what can be done. + fn server_row(&self, server: Row, cx: &mut Context) -> AnyElement { + let t = cx.theme().clone(); + let ui = *t.ui(); + let Row { key, name, state, signed_in, needs_sign_in } = server; + let variant = match &state { + ServerState::Connected(_) => BadgeVariant::Success, + ServerState::Refused(_) + | ServerState::Unreachable(_) + | ServerState::Mismatch { .. } + | ServerState::SignedOut { revoked: true } => BadgeVariant::Destructive, + _ => BadgeVariant::Secondary, + }; + let button = |id: &str, label: &'static str| { + Button::new(SharedString::from(format!("{id}-{key}"))).label(label).size(ButtonSize::Sm) + }; + let sign_in = needs_sign_in.then(|| { + let key = key.clone(); + button("server-sign-in", "Sign in…") + .variant(ButtonVariant::Primary) + .on_click(cx.listener(move |this, _, window, cx| this.sign_in(&key, window, cx))) + }); + let sign_out = signed_in.then(|| { + let key = key.clone(); + button("server-sign-out", "Sign out") + .variant(ButtonVariant::Outline) + .on_click(cx.listener(move |this, _, _, cx| this.sign_out(&key, cx))) + }); + let remove = Button::new(SharedString::from(format!("server-remove-{key}"))) + .icon(IconName::Trash) + .size(ButtonSize::Sm) + .variant(ButtonVariant::Ghost) + .tooltip("Remove") + .on_click({ + let key = key.clone(); + move |_, _, cx| Servers::remove(&key, cx) + }); + let muted = |text: String| div().text_size(t.text_xs()).text_color(ui.muted_foreground).child(text); + div() + .flex() + .items_center() + .gap(space::S3) + .py(space::S3) + .border_b_1() + .border_color(ui.border) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(px(2.)) + .child( + div() + .flex() + .items_center() + .gap(space::S2) + .child(div().font_weight(FontWeight::MEDIUM).truncate_line().child(name)) + .child(Badge::new(state.label()).variant(variant)), + ) + .child(muted(key).truncate_line()) + .children(state.detail().map(muted)), + ) + .child(div().flex().items_center().gap(space::S1_5).children(sign_in).children(sign_out).child(remove)) + .into_any_element() + } +} + +/// What a row shows of a server. +struct Row { + key: String, + name: String, + state: ServerState, + signed_in: bool, + needs_sign_in: bool, +} + +impl Row { + fn of(server: &Server) -> Self { + Self { + key: server.key.clone(), + name: server.name.clone(), + state: server.state.clone(), + signed_in: server.signed_in(), + needs_sign_in: server.needs_sign_in(), + } + } +} + +impl Render for ServersPage { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let t = cx.theme().clone(); + let ui = *t.ui(); + let rows: Vec = Servers::all(cx).iter().map(Row::of).collect(); + let servers: Vec = rows.into_iter().map(|row| self.server_row(row, cx)).collect(); + let empty = servers.is_empty().then(|| { + div().py(space::S3).text_size(t.text_sm()).text_color(ui.muted_foreground).child("No servers yet.") + }); + let error = self.error.clone().map(|e| div().text_size(t.text_xs()).text_color(ui.destructive).child(e)); + div() + .track_focus(&self.focus) + .flex() + .flex_col() + .child(section_label("Servers", cx)) + .children(servers) + .children(empty) + .child(section_label("Add a server", cx)) + .child( + div() + .flex() + .items_center() + .gap(space::S2) + .pt(space::S2) + .child(div().flex_1().min_w_0().child(self.url.clone())) + .child(div().w(px(180.)).child(self.name.clone())) + .child( + Button::new("server-add") + .label("Add") + .icon(IconName::Plus) + .variant(ButtonVariant::Outline) + .on_click(cx.listener(|this, _, window, cx| this.add(window, cx))), + ), + ) + .child(div().pt(space::S1_5).children(error)) + } +} diff --git a/crates/redshell-app/src/sidebar.rs b/crates/redshell-app/src/sidebar.rs index d096599..5fa116c 100644 --- a/crates/redshell-app/src/sidebar.rs +++ b/crates/redshell-app/src/sidebar.rs @@ -145,6 +145,7 @@ impl Workspace { profile_rows(agents, cx) } SidebarSection::Hosts => self.host_rows(cx), + SidebarSection::Servers => self.server_rows(cx), SidebarSection::Multiplexer => self.mux_rows(cx), SidebarSection::Recent => self.recent_rows(cx), }; @@ -339,6 +340,7 @@ impl Workspace { // Only a host with forwards has the submenu. let forwards = (!forwards.is_empty()) .then(|| MenuEntry::submenu("Port Forwarding", forwards).icon(IconName::ArrowRightLeft)); + let send = self.send_host_menu(name, cx); let menu = Menu::build(window, cx, |menu| { let menu = menu .at(position) @@ -353,6 +355,7 @@ impl Workspace { .icon(IconName::Copy), ) .entries(forwards) + .entries(send) .entry( MenuEntry::new( "Install Key on Server…", @@ -468,6 +471,10 @@ fn section_action(section: SidebarSection, cx: &mut Context) -> Optio SidebarSection::Sessions | SidebarSection::Shells => return None, SidebarSection::Agents => ("side-agent", IconName::Plus, "Launch an agent", "agent.launch"), SidebarSection::Hosts => ("side-ssh", IconName::Plus, "Add a host", "ssh.add_host"), + SidebarSection::Servers => { + let button = Button::new("side-servers").icon(IconName::Ellipsis).size(ButtonSize::Xs); + return Some(button.variant(ButtonVariant::Ghost).tooltip("Servers").on_click(open_servers(cx))); + } SidebarSection::Multiplexer => ("side-mux", IconName::Ellipsis, "Manage sessions", "mux.manage"), SidebarSection::Recent => ("side-hist", IconName::Ellipsis, "Browse history", "session.history"), }; @@ -483,6 +490,9 @@ fn empty_hint(section: SidebarSection, cx: &mut Context) -> Option ("No SSH hosts yet.", Some(hint_button("hint-ssh", "Add a host", "ssh.add_host", cx))), + SidebarSection::Servers => { + ("No servers yet.", Some(hint_button_base("hint-servers", "Add a server").on_click(open_servers(cx)))) + } // WSL is not polled; its sessions are listed when the manager opens. SidebarSection::Multiplexer if cx.global::().local_mux().target.poll_interval(true).is_none() => ( "Sessions are listed when you open the manager.", @@ -566,6 +576,11 @@ fn hint_button(id: &'static str, label: &str, command: &'static str, cx: &mut Co hint_button_base(id, label).on_click(cx.listener(move |this, _, w, cx| this.run_command(command, w, cx))) } +/// A click handler opening Settings at the Servers page. +fn open_servers(cx: &mut Context) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { + cx.listener(|this, _, window, cx| this.open_servers_settings(None, window, cx)) +} + /// Turns session recording on (it takes effect after a restart). fn enable_recording_button(cx: &mut Context) -> Button { hint_button_base("hint-history", "Turn on").on_click(cx.listener(|this, _, _, cx| this.turn_on_recording(cx))) diff --git a/crates/redshell-app/src/ssh_hosts.rs b/crates/redshell-app/src/ssh_hosts.rs index d099b5a..600e125 100644 --- a/crates/redshell-app/src/ssh_hosts.rs +++ b/crates/redshell-app/src/ssh_hosts.rs @@ -10,6 +10,7 @@ use std::path::PathBuf; use gpui::{App, AppContext as _}; +use redshell_core::settings::ssh::{self, ForwardError, Replacing}; use redshell_core::settings::{ForwardKind, MultiplexerKind, PortForward, SshHost}; use redshell_remote::ssh_config; use zeroize::Zeroizing; @@ -81,95 +82,56 @@ pub enum Place { Forward(usize, ForwardField), } -/// Why a host can't be saved, reported next to the field it concerns. +/// Why the form can't be saved: a rule every host follows (see +/// [`redshell_core::settings::ssh`]), or text the form can't read. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HostError { - NameMissing, - NameTaken, - NameStartsWithDash, - NameHasControlChars, - /// Hosts from `~/.ssh/config` are saved under their alias. - NameOfImportedHost, - AddressMissing, - AddressStartsWithDash, - BadPort, + Rule(ssh::HostError), + /// The extra arguments don't split like a shell command line. UnbalancedQuotes, - /// ssh would read a command starting with `-` as its own options. - StartupStartsWithDash, - StartupUnbalancedQuotes, - StartupHasControlChars, - Forward(usize, ForwardError), -} - -/// Why one port forward can't be saved. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ForwardError { - BadBindPort, - /// Another forward of the host listens on the same address and port. - BindTaken, - TargetMissing, - BadTargetPort, - /// An address starting with `-`, or holding spaces, slashes or control characters. - BadAddress(ForwardField), -} - -impl ForwardError { - pub fn field(self) -> ForwardField { - match self { - Self::BadBindPort | Self::BindTaken => ForwardField::BindPort, - Self::TargetMissing => ForwardField::TargetHost, - Self::BadTargetPort => ForwardField::TargetPort, - Self::BadAddress(field) => field, - } - } - - pub fn message(self) -> &'static str { - match self { - Self::BadBindPort | Self::BadTargetPort => "Enter a port from 1 to 65535.", - Self::BindTaken => "Another forward of this host already listens there.", - Self::TargetMissing => "Enter the host connections go to.", - Self::BadAddress(_) => "Enter a host name or an IP address.", - } - } } impl HostError { pub fn place(self) -> Place { + use ssh::HostError as Rule; let field = match self { - Self::NameMissing - | Self::NameTaken - | Self::NameStartsWithDash - | Self::NameHasControlChars - | Self::NameOfImportedHost => Field::Name, - Self::AddressMissing | Self::AddressStartsWithDash => Field::Address, - Self::BadPort => Field::Port, Self::UnbalancedQuotes => Field::ExtraArgs, - Self::StartupStartsWithDash | Self::StartupUnbalancedQuotes | Self::StartupHasControlChars => { - Field::StartupCommand - } - Self::Forward(index, error) => return Place::Forward(index, error.field()), + Self::Rule(rule) => match rule { + Rule::NameMissing + | Rule::NameTaken + | Rule::NameStartsWithDash + | Rule::NameHasControlChars + | Rule::NameOfImportedHost => Field::Name, + Rule::AddressMissing | Rule::AddressStartsWithDash => Field::Address, + Rule::BadPort => Field::Port, + Rule::StartupStartsWithDash | Rule::StartupUnbalancedQuotes | Rule::StartupHasControlChars => { + Field::StartupCommand + } + Rule::Forward(index, error) => return Place::Forward(index, forward_field(error)), + }, }; Place::Field(field) } pub fn message(self) -> &'static str { match self { - Self::NameMissing => "Give the host a name.", - Self::NameTaken => "Another host already has this name.", - Self::NameStartsWithDash => "A name can't start with “-”.", - Self::NameHasControlChars => "A name can't contain control characters.", - Self::NameOfImportedHost => "A host from ~/.ssh/config keeps its name there.", - Self::AddressMissing => "Enter an address, or name the host after a ~/.ssh/config alias.", - Self::AddressStartsWithDash => "An address can't start with “-”.", - Self::BadPort => "Enter a port from 1 to 65535.", - Self::UnbalancedQuotes | Self::StartupUnbalancedQuotes => "Close the quotes.", - Self::StartupStartsWithDash => "A startup command can't start with “-”.", - Self::StartupHasControlChars => "A startup command can't contain control characters.", - Self::Forward(_, error) => error.message(), + Self::Rule(rule) => rule.message(), + Self::UnbalancedQuotes => "Close the quotes.", } } } +/// The field of a forward an error is about. +fn forward_field(error: ForwardError) -> ForwardField { + match error { + ForwardError::BadBindPort | ForwardError::BindTaken => ForwardField::BindPort, + ForwardError::TargetMissing => ForwardField::TargetHost, + ForwardError::BadTargetPort => ForwardField::TargetPort, + ForwardError::BadBindAddress => ForwardField::BindAddress, + ForwardError::BadTargetAddress => ForwardField::TargetHost, + } +} + /// One port forward of the form, as text. #[derive(Debug, Clone, Default, PartialEq)] pub struct ForwardForm { @@ -201,50 +163,26 @@ impl ForwardForm { form } - /// The forward the form describes (a SOCKS proxy without a target), and - /// what is wrong with it. - pub fn parse(&self) -> (PortForward, Vec) { + /// The forward the form describes (a SOCKS proxy without a target). A + /// port that doesn't read as one is left unset (0 for the listening + /// port), which the rules then refuse. + pub fn parse(&self) -> PortForward { let value = |field| self.get(field).trim(); let optional = |field| Some(value(field).to_owned()).filter(|v| !v.is_empty()); - let port = |field| value(field).parse::().ok().filter(|p| *p > 0); + let port = |field| value(field).parse::().ok(); let targeted = self.kind != ForwardKind::Dynamic; - let mut errors = Vec::new(); - for field in [ForwardField::BindAddress, ForwardField::TargetHost].into_iter().filter(|f| f.applies(self.kind)) - { - if !value(field).is_empty() && !is_address(value(field)) { - errors.push(ForwardError::BadAddress(field)); - } - } - let bind_port = port(ForwardField::BindPort); - if bind_port.is_none() { - errors.push(ForwardError::BadBindPort); - } - if targeted && value(ForwardField::TargetHost).is_empty() { - errors.push(ForwardError::TargetMissing); - } - let target_port = port(ForwardField::TargetPort).filter(|_| targeted); - if targeted && target_port.is_none() { - errors.push(ForwardError::BadTargetPort); - } - let forward = PortForward { + PortForward { kind: self.kind, bind_address: optional(ForwardField::BindAddress), - bind_port: bind_port.unwrap_or_default(), + bind_port: port(ForwardField::BindPort).unwrap_or_default(), target_host: optional(ForwardField::TargetHost).filter(|_| targeted), - target_port, + target_port: port(ForwardField::TargetPort).filter(|_| targeted), label: optional(ForwardField::Label), auto_start: self.auto_start, - }; - (forward, errors) + } } } -/// Whether ssh can take `address` as a host in a forwarding specification: -/// not an option, and no spaces, slashes or control characters. -fn is_address(address: &str) -> bool { - !address.starts_with('-') && !address.chars().any(|c| c.is_whitespace() || c.is_control() || c == '/') -} - /// The host form as text, one string per [`Field`], plus the choices that /// are not text and the port forwards. #[derive(Debug, Clone, Default, PartialEq)] @@ -286,22 +224,17 @@ impl HostForm { form } - /// The host the form describes, with what didn't parse (a port, - /// arguments, forwards) left unset and reported. + /// The host the form describes, with the text it can't read (a port, + /// arguments) left unset and reported. fn parse(&self) -> (SshHost, Vec) { let value = |field| self.get(field).trim(); let optional = |field| Some(value(field).to_owned()).filter(|v| !v.is_empty()); let port = match value(Field::Port) { "" => Ok(None), - port => port.parse::().ok().filter(|p| *p > 0).map(Some).ok_or(HostError::BadPort), + port => port.parse::().map(Some).map_err(|_| HostError::Rule(ssh::HostError::BadPort)), }; let extra_args = shlex::split(value(Field::ExtraArgs)).ok_or(HostError::UnbalancedQuotes); - let mut errors: Vec = - [port.err(), extra_args.as_ref().err().copied()].into_iter().flatten().collect(); - let startup = value(Field::StartupCommand); - errors.extend(startup_error(startup)); - let (forwards, forward_errors) = parse_forwards(&self.forwards); - errors.extend(forward_errors); + let errors = [port.err(), extra_args.as_ref().err().copied()].into_iter().flatten().collect(); let host = SshHost { name: value(Field::Name).to_owned(), host: value(Field::Address).to_owned(), @@ -316,40 +249,17 @@ impl HostForm { tags: value(Field::Tags).split(',').map(str::trim).filter(|t| !t.is_empty()).map(Into::into).collect(), forward_agent: self.forward_agent, startup_command: optional(Field::StartupCommand), - forwards, + forwards: self.forwards.iter().map(ForwardForm::parse).collect(), }; (host, errors) } } -/// What is wrong with a startup command: ssh must not take it for options, -/// and the shell must see it end where RedShell appends to it. -fn startup_error(command: &str) -> Option { - if command.starts_with('-') { - Some(HostError::StartupStartsWithDash) - } else if command.chars().any(|c| c.is_control() && c != '\t') { - Some(HostError::StartupHasControlChars) - } else if shlex::split(command).is_none() { - Some(HostError::StartupUnbalancedQuotes) - } else { - None - } -} - /// The forwards of `forms` and what is wrong with each, including two /// listening on the same address and port. pub fn parse_forwards(forms: &[ForwardForm]) -> (Vec, Vec) { - let mut forwards: Vec = Vec::new(); - let mut errors = Vec::new(); - for (index, form) in forms.iter().enumerate() { - let (forward, problems) = form.parse(); - let listens_where = |f: &PortForward| (f.kind == ForwardKind::Remote, f.bind_address.clone(), f.bind_port); - let taken = problems.is_empty() && forwards.iter().any(|f| listens_where(f) == listens_where(&forward)); - errors.extend( - problems.into_iter().chain(taken.then_some(ForwardError::BindTaken)).map(|e| HostError::Forward(index, e)), - ); - forwards.push(forward); - } + let forwards: Vec = forms.iter().map(ForwardForm::parse).collect(); + let errors = ssh::forward_errors(&forwards).into_iter().map(HostError::Rule).collect(); (forwards, errors) } @@ -411,6 +321,16 @@ impl HostBook { } } + /// Host `name` as ssh connects to it: an entry saved over a + /// `~/.ssh/config` host is laid over the file's. + pub fn resolved(&self, name: &str) -> Option { + let source = self.source(name)?; + Some(match (&source, self.alias(name)) { + (Source::Saved(_), Some(base)) => ssh::layered(base, &self.host(&source)), + _ => self.host(&source), + }) + } + /// The groups hosts are in, in the order they first appear. pub fn groups(&self) -> Vec { let mut groups: Vec = Vec::new(); @@ -425,63 +345,23 @@ impl HostBook { /// The host `form` describes, if it can replace `source`. pub fn check(&self, source: &Source, form: &HostForm) -> Result> { let (host, parse_errors) = form.parse(); - let mut errors = self.validate(source, &host); + let replacing = match source { + Source::New => Replacing::Nothing, + Source::Saved(name) => Replacing::Saved(name), + Source::Imported(base) => Replacing::Imported(base), + }; + let mut errors: Vec = + ssh::validate(&host, replacing, &self.saved, &self.aliases).into_iter().map(HostError::Rule).collect(); errors.extend(parse_errors); if errors.is_empty() { Ok(host) } else { Err(errors) } } - /// What is wrong with `host` taking the place of `source`. - fn validate(&self, source: &Source, host: &SshHost) -> Vec { - let (name, address) = (host.name.as_str(), host.host.as_str()); - let original = match source { - Source::Saved(name) => Some(name.as_str()), - _ => None, - }; - let name_error = if name.is_empty() { - Some(HostError::NameMissing) - } else if matches!(source, Source::Imported(h) if h.name != name) { - Some(HostError::NameOfImportedHost) - } else if name.starts_with('-') { - Some(HostError::NameStartsWithDash) - } else if name.chars().any(char::is_control) { - Some(HostError::NameHasControlChars) - } else if self.saved.iter().any(|h| h.name == name && Some(name) != original) { - Some(HostError::NameTaken) - } else { - None - }; - let address_error = if address.starts_with('-') { - Some(HostError::AddressStartsWithDash) - } else if address.is_empty() && self.alias(name).is_none() { - Some(HostError::AddressMissing) - } else { - None - }; - name_error.into_iter().chain(address_error).collect() - } - /// What is written for `host` saved over `source`: an imported host /// keeps only the fields that differ from `~/.ssh/config`. fn entry(source: &Source, host: SshHost) -> SshHost { - let Source::Imported(base) = source else { return host }; - fn changed(base: &T, value: T) -> T { - if *base == value { T::default() } else { value } - } - SshHost { - name: host.name, - host: changed(&base.host, host.host), - user: changed(&base.user, host.user), - port: changed(&base.port, host.port), - identity_file: changed(&base.identity_file, host.identity_file), - jump_host: changed(&base.jump_host, host.jump_host), - extra_args: changed(&base.extra_args, host.extra_args), - multiplexer: changed(&base.multiplexer, host.multiplexer), - attach_session: changed(&base.attach_session, host.attach_session), - group: changed(&base.group, host.group), - tags: changed(&base.tags, host.tags), - forward_agent: changed(&base.forward_agent, host.forward_agent), - startup_command: changed(&base.startup_command, host.startup_command), - forwards: changed(&base.forwards, host.forwards), + match source { + Source::Imported(base) => ssh::imported_entry(base, host), + Source::New | Source::Saved(_) => host, } } @@ -639,6 +519,17 @@ mod tests { HostForm::from_host(&host(name, address)) } + #[test] + fn hosts_resolve_as_ssh_sees_them() { + let mut book = book(); + assert_eq!(book.resolved("web"), Some(host("web", "w.example"))); + assert_eq!(book.resolved("box"), Some(book.aliases[0].clone())); + book.saved.push(SshHost { port: Some(22), ..host("box", "") }); + let over = SshHost { user: Some("me".into()), port: Some(22), ..host("box", "10.0.0.5") }; + assert_eq!(book.resolved("box"), Some(over)); + assert_eq!(book.resolved("nowhere"), None); + } + fn errors(source: &Source, form: &HostForm) -> Vec { book().check(source, form).err().unwrap_or_default() } @@ -675,7 +566,7 @@ mod tests { assert_eq!(HostForm::from_host(&host).parse(), (host, Vec::new())); } - /// The errors of a host with just `forward`, from the form. + /// The errors of a host with `forms` as its forwards, from the form. fn forward_errors(forms: &[ForwardForm]) -> Vec { let mut f = form("a", "a.example"); f.forwards = forms.to_vec(); @@ -691,73 +582,49 @@ mod tests { } #[test] - fn forwards_need_ports_a_target_and_plain_addresses() { - use ForwardError::*; + fn forward_errors_point_at_their_fields() { use ForwardField::*; let local = |fields: &[(ForwardField, &str)]| forward_form(ForwardKind::Local, fields); let good = [(BindPort, "8080"), (TargetHost, "db"), (TargetPort, "5432")]; assert!(forward_errors(&[local(&good)]).is_empty()); - let missing = forward_errors(&[local(&[(BindPort, "0")])]); - assert_eq!(missing, [BadBindPort, TargetMissing, BadTargetPort].map(|e| HostError::Forward(0, e))); + // Ports that don't read as ports are refused like missing ones. + let unreadable = forward_errors(&[local(&[(BindPort, "http"), (TargetPort, "70000")])]); assert_eq!( - missing.iter().map(|e| e.place()).collect::>(), + unreadable.iter().map(|e| e.place()).collect::>(), [Place::Forward(0, BindPort), Place::Forward(0, TargetHost), Place::Forward(0, TargetPort)] ); - for (field, address) in [(BindAddress, "-oProxyCommand=x"), (TargetHost, "a b"), (TargetHost, "a/b")] { + for (field, address) in [(BindAddress, "-oProxyCommand=x"), (TargetHost, "a b")] { let mut bad = local(&good); bad.set(field, address); - assert_eq!(forward_errors(&[bad]), [HostError::Forward(0, BadAddress(field))], "{address}"); + assert_eq!( + forward_errors(&[bad]).iter().map(|e| e.place()).collect::>(), + [Place::Forward(0, field)] + ); } - // A SOCKS proxy needs only its port, and keeps no target. let socks = forward_form(ForwardKind::Dynamic, &[(BindPort, "1080"), (TargetHost, "-x"), (TargetPort, "x")]); assert!(forward_errors(std::slice::from_ref(&socks)).is_empty()); - assert_eq!(socks.parse().0.target_host, None); - } - - #[test] - fn two_forwards_cant_listen_on_the_same_port() { - use ForwardField::*; - let socks = forward_form(ForwardKind::Dynamic, &[(BindPort, "1080")]); - let remote = - forward_form(ForwardKind::Remote, &[(BindPort, "1080"), (TargetHost, "localhost"), (TargetPort, "80")]); - assert!(forward_errors(&[socks.clone(), remote]).is_empty(), "a remote port is on the host"); - assert_eq!(forward_errors(&[socks.clone(), socks]), [HostError::Forward(1, ForwardError::BindTaken)]); + assert_eq!(socks.parse().target_host, None, "a SOCKS proxy keeps no target"); + let taken = forward_errors(&[socks.clone(), socks]); + assert_eq!(taken, [HostError::Rule(ssh::HostError::Forward(1, ForwardError::BindTaken))]); } #[test] - fn startup_commands_cant_pass_for_options() { - for (command, error) in [ - ("-oProxyCommand=x", Some(HostError::StartupStartsWithDash)), - ("echo 'open", Some(HostError::StartupUnbalancedQuotes)), - ("ls\u{1b}", Some(HostError::StartupHasControlChars)), - ("cd /srv && htop # go", None), - ] { - let mut f = form("a", "a.example"); - f.set(Field::StartupCommand, command); - assert_eq!(errors(&Source::New, &f), error.into_iter().collect::>(), "{command}"); - } - } - - #[test] - fn names_must_be_given_unique_and_safe() { + fn rule_errors_point_at_their_fields() { let new = Source::New; - assert_eq!(errors(&new, &form("", "a.example")), [HostError::NameMissing]); - assert_eq!(errors(&new, &form("web", "a.example")), [HostError::NameTaken]); - assert_eq!(errors(&new, &form("-oProxyCommand=x", "a.example")), [HostError::NameStartsWithDash]); - assert_eq!(errors(&new, &form("a\nb", "a.example")), [HostError::NameHasControlChars]); - // A host keeps its own name, and may take one nobody else has. - assert!(errors(&Source::Saved("web".into()), &form("web", "w.example")).is_empty()); - assert!(errors(&Source::Saved("web".into()), &form("www", "w.example")).is_empty()); - assert_eq!(errors(&Source::Saved("web".into()), &form("db", "w.example")), [HostError::NameTaken]); + assert_eq!(errors(&new, &form("web", "a.example")), [HostError::Rule(ssh::HostError::NameTaken)]); + let mut f = form("a", "a.example"); + f.set(Field::StartupCommand, "-oProxyCommand=x"); + assert_eq!( + errors(&new, &f).iter().map(|e| e.place()).collect::>(), + [Place::Field(Field::StartupCommand)] + ); + // A config alias needs no address: ssh resolves it. + assert!(errors(&new, &form("box", "")).is_empty()); } #[test] - fn addresses_ports_and_arguments_are_checked() { + fn ports_and_arguments_are_read_from_the_form() { let new = Source::New; - assert_eq!(errors(&new, &form("a", "")), [HostError::AddressMissing]); - assert_eq!(errors(&new, &form("a", "-oProxyCommand=x")), [HostError::AddressStartsWithDash]); - // A config alias needs no address: ssh resolves it. - assert!(errors(&new, &form("box", "")).is_empty()); for (port, ok) in [("22", true), ("65535", true), ("0", false), ("65536", false), ("ssh", false)] { let mut f = form("a", "a.example"); f.set(Field::Port, port); @@ -767,7 +634,11 @@ mod tests { f.set(Field::Port, "0"); f.set(Field::ExtraArgs, "-o 'open"); let found = errors(&new, &f); - assert_eq!(found, [HostError::NameMissing, HostError::BadPort, HostError::UnbalancedQuotes]); + let rule = HostError::Rule; + assert_eq!( + found, + [rule(ssh::HostError::NameMissing), rule(ssh::HostError::BadPort), HostError::UnbalancedQuotes] + ); assert_eq!( found.iter().map(|e| e.place()).collect::>(), [Field::Name, Field::Port, Field::ExtraArgs].map(Place::Field) @@ -790,7 +661,7 @@ mod tests { f.set(Field::Address, "10.0.0.6"); assert_eq!(HostBook::entry(&source, b.check(&source, &f).unwrap()).host, "10.0.0.6"); f.set(Field::Name, "lab-box"); - assert_eq!(errors(&source, &f), [HostError::NameOfImportedHost]); + assert_eq!(errors(&source, &f), [HostError::Rule(ssh::HostError::NameOfImportedHost)]); } #[test] diff --git a/crates/redshell-app/src/state.rs b/crates/redshell-app/src/state.rs index 708152f..4abdddc 100644 --- a/crates/redshell-app/src/state.rs +++ b/crates/redshell-app/src/state.rs @@ -414,13 +414,27 @@ struct Reapply { update_checks: bool, /// Tunnels whose forward changed or went away stop. tunnels: bool, + /// Servers connect and disconnect to match `[remote]`. + servers: bool, } impl Reapply { - const NOTHING: Self = - Self { theme: false, keybindings: false, window_background: false, update_checks: false, tunnels: false }; - const EVERYTHING: Self = - Self { theme: true, keybindings: true, window_background: true, update_checks: true, tunnels: true }; + const NOTHING: Self = Self { + theme: false, + keybindings: false, + window_background: false, + update_checks: false, + tunnels: false, + servers: false, + }; + const EVERYTHING: Self = Self { + theme: true, + keybindings: true, + window_background: true, + update_checks: true, + tunnels: true, + servers: true, + }; fn between(old: &Settings, new: &Settings) -> Self { if old == new { @@ -432,6 +446,7 @@ impl Reapply { window_background: old.appearance.window_background != new.appearance.window_background, update_checks: old.updates != new.updates, tunnels: old.ssh != new.ssh, + servers: old.remote != new.remote, } } } @@ -454,6 +469,10 @@ fn reapply(cx: &mut App, changes: Reapply) { if changes.update_checks { crate::update::Updater::sync(cx); } + // Not yet there while the settings are first applied, before it starts. + if changes.servers && cx.has_global::() { + crate::servers::Servers::reconcile(cx); + } cx.refresh_windows(); } @@ -650,7 +669,7 @@ mod tests { assert_eq!(Reapply::between(&old, &new), Reapply { theme: true, ..Reapply::NOTHING }); new.appearance.window_background = WindowBackground::Blurred; new.keybindings.insert("f2".into(), "tab.new".into()); - let all_but_updates = Reapply { update_checks: false, tunnels: false, ..Reapply::EVERYTHING }; + let all_but_updates = Reapply { update_checks: false, tunnels: false, servers: false, ..Reapply::EVERYTHING }; assert_eq!(Reapply::between(&old, &new), all_but_updates); } diff --git a/crates/redshell-app/src/terminal_view.rs b/crates/redshell-app/src/terminal_view.rs index 09d6251..280cd9f 100644 --- a/crates/redshell-app/src/terminal_view.rs +++ b/crates/redshell-app/src/terminal_view.rs @@ -422,11 +422,12 @@ impl TerminalView { /// `true` when closing would interrupt a program: anything but an idle /// shell. An agent, SSH or editor tab is its program, so it counts while - /// it lives; closing a multiplexer tab only detaches, so it never does. + /// it lives; closing a multiplexer or server tab only detaches, so it + /// never does. pub fn has_running_job(&self) -> bool { self.is_alive() && match self.profile.kind { - LaunchKind::Multiplexer => false, + LaunchKind::Multiplexer | LaunchKind::Remote => false, _ if is_shell(&self.profile) => self.terminal.as_ref().is_some_and(|t| t.has_foreground_job()), _ => true, } @@ -1317,7 +1318,7 @@ impl Render for TerminalView { let inner_h = (bounds.size.height - style.padding * 2.).max(line_height); let cols = ((inner_w / cell_width).floor() as usize).clamp(2, 1000); let rows = ((inner_h / line_height).floor() as usize).clamp(1, 500); - let layout = Layout { + let mut layout = Layout { origin: point(bounds.origin.x + style.padding, bounds.origin.y + style.padding), cell_width, line_height, @@ -1332,6 +1333,11 @@ impl Render for TerminalView { cell_width: f32::from(cell_width) as u16, cell_height: f32::from(line_height) as u16, }); + // A grid sized by the far end (a shared server session) + // can be smaller than the pane. + let grid = t.size(); + layout.cols = layout.cols.min(usize::from(grid.cols)); + layout.rows = layout.rows.min(usize::from(grid.rows)); t.snapshot(style.snapshot) }); (layout, snapshot) diff --git a/crates/redshell-app/src/workspace.rs b/crates/redshell-app/src/workspace.rs index 9109051..b1ef756 100644 --- a/crates/redshell-app/src/workspace.rs +++ b/crates/redshell-app/src/workspace.rs @@ -44,10 +44,14 @@ use crate::window_state; #[path = "files.rs"] mod files; +#[path = "host_upload.rs"] +mod host_upload; #[path = "install_key.rs"] mod install_key; #[path = "overlays.rs"] mod overlays; +#[path = "remote_tabs.rs"] +mod remote_tabs; #[path = "sidebar.rs"] mod sidebar; #[path = "ssh_prompts.rs"] @@ -122,12 +126,21 @@ enum Overlay { Confirm(Entity), Settings(Entity), Mux(Entity), - Rename(Entity, usize), + Rename(Entity, Renaming), Plugins(Entity), HostEditor(Entity), Files(Entity), } +/// What the rename dialog names. +#[derive(Clone)] +enum Renaming { + /// The tab of this id. + Tab(usize), + /// A session on a server. + Session(redshell_app::remote::SessionRef), +} + pub struct Workspace { focus: FocusHandle, tabs: Vec, @@ -169,6 +182,7 @@ pub struct Workspace { /// scrollback, the first prompt) is not "new activity". born: HashMap, native: tmux_native::NativeState, + remote: remote_tabs::RemoteState, ticks: u64, _tick: Task<()>, } @@ -216,6 +230,7 @@ impl Workspace { view_subs: HashMap::new(), born: HashMap::new(), native: Default::default(), + remote: Default::default(), ticks: 0, _tick: tick, }; @@ -498,7 +513,7 @@ impl Workspace { /// gets the default shell there instead of a second copy of itself, and /// a native tmux tab gets a new window of its session. fn duplicate(&mut self, view: &Entity, window: &mut Window, cx: &mut Context) { - if self.native_new_window(view.entity_id()) { + if self.native_new_window(view.entity_id()) || self.remote_duplicate(view, window, cx) { return; } let v = view.read(cx); @@ -846,6 +861,8 @@ impl Workspace { self.show_files(browser.clone(), window, cx); browser.update(cx, |browser, cx| browser.delete(paths, cx)); } + ConfirmAction::KillServerSession(target) => self.kill_remote(target, cx), + ConfirmAction::ReplaceServerHost { server, host } => self.replace_server_host(server, *host, cx), } } @@ -959,10 +976,7 @@ impl Workspace { continue; } }; - let root = panes.map(|pane| { - let request = Self::restore_request(pane, replay, &history, cx); - self.make_view(request, window, cx) - }); + let root = panes.map(|pane| self.restore_view(pane, replay, &history, window, cx)); let views = root.leaves(); let Some(first) = views.first().cloned() else { continue }; let focused = views.into_iter().find(|v| v.read(cx).session == active_pane).unwrap_or(first); @@ -978,10 +992,17 @@ impl Workspace { self.persist(window, cx); } - /// What reopens one saved pane. `replay` is whether restored panes - /// replay their scrollback (`history.restore_scrollback`). - fn restore_request(pane: PaneStep, replay: bool, history: &HistoryStore, cx: &App) -> LaunchRequest { - match pane { + /// Reopens one saved pane. `replay` is whether restored panes replay + /// their scrollback (`history.restore_scrollback`). + fn restore_view( + &mut self, + pane: PaneStep, + replay: bool, + history: &HistoryStore, + window: &mut Window, + cx: &mut Context, + ) -> Entity { + let request = match pane { PaneStep::Relaunch { record, last_cwd, replay: replays } => { let mut profile = record.profile.clone(); if last_cwd && let Some(cwd) = record.cwd.as_ref().map(std::path::PathBuf::from).filter(|p| p.is_dir()) @@ -1000,7 +1021,9 @@ impl Workspace { .map_or_else(|| record.profile.clone(), |client| client.reattach_profile(&mux.session)); LaunchRequest { profile, session: Some(record.id), prelude: None, read_only: false } } - } + PaneStep::Remote { record, target } => return self.remote_view(&target, Some(&record), window, cx), + }; + self.make_view(request, window, cx) } fn open_recording(&mut self, id: SessionId, live: bool, window: &mut Window, cx: &mut Context) { @@ -1296,6 +1319,7 @@ impl Workspace { } } PickerKind::NativeMux => self.native_pick(&id, window, cx), + PickerKind::ServerProfiles => self.remote_pick(&id, window, cx), PickerKind::Fonts | PickerKind::Tunnels => {} PickerKind::History => { if let Ok(uuid) = id.parse() { @@ -1653,7 +1677,13 @@ impl Workspace { .size_full() .min_w_0() .min_h_0() - .child(v.clone()) + .map(|d| match self.remote_banner(v, cx) { + // A server pane's banner stands above it. + Some(banner) => { + d.flex().flex_col().child(banner).child(div().relative().flex_1().min_h_0().child(v.clone())) + } + None => d.child(v.clone()), + }) .when(multi && v.entity_id() == active, |d| { d.child( div() @@ -1976,8 +2006,12 @@ impl Render for Workspace { Some(Overlay::Plugins(p)) => Some(p.clone().into_any_element()), Some(Overlay::HostEditor(e)) => Some(e.clone().into_any_element()), Some(Overlay::Files(f)) => Some(f.clone().into_any_element()), - Some(Overlay::Rename(input, _)) => { + Some(Overlay::Rename(input, renaming)) => { let this = cx.entity().downgrade(); + let title = match renaming { + Renaming::Tab(_) => "Rename tab", + Renaming::Session(_) => "Rename session", + }; Some( Modal::new("rename") .top() @@ -1985,7 +2019,7 @@ impl Render for Workspace { .on_backdrop_click(move |w, cx| { this.update(cx, |this, cx| this.close_overlay(w, cx)).ok(); }) - .child(modal_header("Rename tab", None, cx)) + .child(modal_header(title, None, cx)) .child(div().px(px(24.)).pb(px(20.)).pt(px(4.)).child(input.clone())) .into_any_element(), ) diff --git a/crates/redshell-app/tests/askpass.rs b/crates/redshell-app/tests/askpass.rs index aa7b362..2926900 100644 --- a/crates/redshell-app/tests/askpass.rs +++ b/crates/redshell-app/tests/askpass.rs @@ -12,10 +12,14 @@ use redshell_app::secrets::{MemoryStore, Secrets, passphrase_account}; use redshell_remote::askpass::OpenSshVersion; use redshell_remote::{AskpassMode, AskpassTarget}; -/// `ssh-keygen`, when the `ssh` beside it is 8.4 or later (older clients -/// ignore `SSH_ASKPASS_REQUIRE` and would prompt on the console). +/// `ssh-keygen` (from `PATH`, or `REDSHELL_TEST_SSH_KEYGEN` to pick one +/// such as Windows' own OpenSSH), when the `ssh` beside it is 8.4 or later +/// (older clients ignore `SSH_ASKPASS_REQUIRE` and would prompt on the console). fn modern_ssh_keygen() -> Result { - let keygen = which::which("ssh-keygen").map_err(|_| "ssh-keygen is not installed".to_owned())?; + let keygen = match std::env::var_os("REDSHELL_TEST_SSH_KEYGEN").filter(|p| !p.is_empty()) { + Some(path) => PathBuf::from(path), + None => which::which("ssh-keygen").map_err(|_| "ssh-keygen is not installed".to_owned())?, + }; let ssh = keygen.with_file_name(if cfg!(windows) { "ssh.exe" } else { "ssh" }); let version = OpenSshVersion::detect(&ssh.display().to_string()) .ok_or_else(|| format!("no OpenSSH ssh beside {}", keygen.display()))?; diff --git a/crates/redshell-app/tests/remote.rs b/crates/redshell-app/tests/remote.rs new file mode 100644 index 0000000..e2125a9 --- /dev/null +++ b/crates/redshell-app/tests/remote.rs @@ -0,0 +1,335 @@ +//! The server client against a real `redshell-server`, started in-process +//! on an ephemeral port: signing in, attaching and typing, the binary +//! framing, reconnecting and resyncing after the connection drops, sessions +//! that are gone, and a revoked device. +//! +//! Sessions run `sh`, so these tests are Unix only. +#![cfg(unix)] + +use std::sync::Arc; +use std::time::Duration; + +use futures::StreamExt as _; +use futures::channel::mpsc::UnboundedReceiver; +use parking_lot::Mutex; +use redshell_app::remote::{Api, ApiFailure, Event, ServerClient, ServerUrl, Sink, Status}; +use redshell_protocol::{CreateSessionRequest, ErrorCode, ServerMessage, SignInRequest, Snapshot}; +use redshell_server::{RunningServer, ServerConfig}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::task::JoinHandle; +use zeroize::Zeroizing; + +const PASSWORD: &str = "a long passphrase"; +const WAIT: Duration = Duration::from_secs(15); + +struct Harness { + _dir: tempfile::TempDir, + server: RunningServer, +} + +impl Harness { + async fn start() -> Self { + let dir = tempfile::tempdir().unwrap(); + let config = "[server]\nlisten = \"127.0.0.1:0\"\n[ssh]\nimport_ssh_config = false\n\ + [terminal]\nshell = \"/bin/sh\"\nshell_integration = false\n"; + std::fs::write(dir.path().join("config.toml"), config).unwrap(); + let server = RunningServer::start(ServerConfig::load(dir.path()).unwrap()).await.unwrap(); + let harness = Self { _dir: dir, server }; + harness.set_up_account().await; + harness + } + + fn url(&self) -> ServerUrl { + ServerUrl::parse(&format!("http://{}", self.server.addr)).unwrap() + } + + /// Creates the account through the one-time setup code. + async fn set_up_account(&self) { + let link = self.server.setup_link().unwrap().expect("no account yet"); + let code = link.split("code=").nth(1).unwrap().to_owned(); + let origin = format!("http://{}", self.server.addr); + let body = serde_json::json!({"code": code, "username": "me", "password": PASSWORD}); + let response = reqwest::Client::new() + .post(format!("{origin}/api/setup")) + .header("origin", origin) + .header("content-type", "application/json") + .header(redshell_protocol::CHANGE_HEADER, redshell_protocol::CHANGE_HEADER_VALUE) + .body(body.to_string()) + .send() + .await + .unwrap(); + assert!(response.status().is_success(), "{}", response.status()); + } + + /// A device token, as the sign-in dialog gets one. + async fn sign_in(&self) -> Zeroizing { + let api = Api::new(self.url(), None); + let request = SignInRequest { + username: "me".into(), + password: PASSWORD.into(), + device_name: Some("test desktop".into()), + }; + let signed_in = run(async move { api.sign_in(&request).await }).await.unwrap(); + Zeroizing::new(signed_in.device_token.expect("a device token")) + } + + async fn shell(&self, token: &Zeroizing) -> String { + let api = Api::new(self.url(), Some(token.clone())); + let request = CreateSessionRequest { cols: Some(80), rows: Some(24), ..Default::default() }; + run(async move { api.create_session(&request).await }).await.unwrap().id + } +} + +/// Runs a REST call on the client runtime, as the app does. +async fn run(future: impl Future + Send + 'static) -> T { + redshell_app::remote::runtime::spawn(future).await +} + +/// What a test sink saw, in order. +#[derive(Debug, Clone, PartialEq)] +enum Seen { + Snapshot(u16, u16), + Output(Vec), + Resized(u16, u16), +} + +#[derive(Clone, Default)] +struct Probe(Arc>>); + +impl Probe { + fn output(&self) -> String { + let seen = self.0.lock(); + let bytes: Vec = seen + .iter() + .flat_map(|s| match s { + Seen::Output(bytes) => bytes.clone(), + _ => Vec::new(), + }) + .collect(); + String::from_utf8_lossy(&bytes).into_owned() + } + + fn snapshots(&self) -> usize { + self.0.lock().iter().filter(|s| matches!(s, Seen::Snapshot(..))).count() + } + + async fn until(&self, what: &str, done: impl Fn(&Self) -> bool) { + let deadline = tokio::time::Instant::now() + WAIT; + while !done(self) { + assert!(tokio::time::Instant::now() < deadline, "{what}: saw {:?}", self.0.lock()); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } +} + +impl Sink for Probe { + fn snapshot(&mut self, snapshot: &Snapshot) { + self.0.lock().push(Seen::Snapshot(snapshot.cols, snapshot.rows)); + } + fn output(&mut self, bytes: &[u8]) { + self.0.lock().push(Seen::Output(bytes.to_vec())); + } + fn resized(&mut self, cols: u16, rows: u16) { + self.0.lock().push(Seen::Resized(cols, rows)); + } +} + +/// The next event `pick` takes, skipping the others. +async fn next(events: &mut UnboundedReceiver, what: &str, pick: impl Fn(Event) -> Option) -> T { + let found = tokio::time::timeout(WAIT, async { + while let Some(event) = events.next().await { + if let Some(found) = pick(event) { + return Some(found); + } + } + None + }); + found.await.unwrap_or_else(|_| panic!("no {what} in time")).unwrap_or_else(|| panic!("events ended before {what}")) +} + +fn status(event: Event) -> Option { + match event { + Event::Status(status) => Some(status), + _ => None, + } +} + +async fn connected(events: &mut UnboundedReceiver) { + next(events, "connected", |e| status(e).filter(|s| matches!(s, Status::Connected { .. }))).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn attaches_types_and_follows_the_session_list() { + let h = Harness::start().await; + let token = h.sign_in().await; + let session = h.shell(&token).await; + + let (client, mut events) = ServerClient::start(h.url()); + client.set_token(Some(token.clone())); + connected(&mut events).await; + let listed = next(&mut events, "the session list", |e| match e { + Event::Message(message) => match *message { + ServerMessage::Sessions { sessions } => Some(sessions), + _ => None, + }, + _ => None, + }) + .await; + assert!(listed.iter().any(|s| s.id == session)); + + // Attaching at the session's own size, then typing in binary frames. + let probe = Probe::default(); + let id = client.attach(&session, None, Box::new(probe.clone())); + probe.until("a snapshot", |p| p.snapshots() == 1).await; + assert_eq!(probe.0.lock()[0], Seen::Snapshot(80, 24)); + client.input(id, b"echo hello-$((40+2))\r"); + probe.until("the echo", |p| p.output().contains("hello-42")).await; + + // The view's size is passed on; the session follows its first client. + client.resize(id, 100, 30); + probe.until("the resize", |p| p.0.lock().contains(&Seen::Resized(100, 30))).await; + + // A rename comes back as an update of the list. + client.send(redshell_protocol::ClientMessage::Rename { session: session.clone(), name: Some("build".into()) }); + let renamed = next(&mut events, "the rename", |e| match e { + Event::Message(message) => match *message { + ServerMessage::SessionUpdated { session } => session.name, + _ => None, + }, + _ => None, + }) + .await; + assert_eq!(renamed, "build"); + + // A session started while connected is attached once it is listed. + let fresh = h.shell(&token).await; + let probe = Probe::default(); + client.attach(&fresh, None, Box::new(probe.clone())); + probe.until("the new session's snapshot", |p| p.snapshots() == 1).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn reconnects_and_resyncs_after_the_connection_drops() { + let h = Harness::start().await; + let token = h.sign_in().await; + let session = h.shell(&token).await; + let relay = Relay::start(h.server.addr).await; + + let url = ServerUrl::parse(&format!("http://{}", relay.addr)).unwrap(); + let (client, mut events) = ServerClient::start(url); + client.set_token(Some(token)); + connected(&mut events).await; + let probe = Probe::default(); + let id = client.attach(&session, Some((80, 24)), Box::new(probe.clone())); + probe.until("the first snapshot", |p| p.snapshots() == 1).await; + + relay.drop_connections(); + next(&mut events, "reconnecting", |e| status(e).filter(|s| matches!(s, Status::Reconnecting { .. }))).await; + connected(&mut events).await; + // Attached again: a fresh snapshot, and typing reaches the session. + probe.until("a second snapshot", |p| p.snapshots() == 2).await; + client.input(id, b"echo back-$((1+1))\r"); + probe.until("the echo after reconnecting", |p| p.output().contains("back-2")).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn attachments_of_sessions_that_are_gone_end() { + let h = Harness::start().await; + let token = h.sign_in().await; + let session = h.shell(&token).await; + let (client, mut events) = ServerClient::start(h.url()); + + // A restored tab of a session that is gone: it ends once the server + // listed its sessions. + let missing = client.attach("no-such-session", None, Box::new(Probe::default())); + client.set_token(Some(token.clone())); + let ended = next(&mut events, "the end of the missing one", |e| match e { + Event::Ended { attachment, session } => Some((attachment, session)), + _ => None, + }) + .await; + assert_eq!(ended, (missing, "no-such-session".to_owned())); + + // Killed while attached: the server lets the channel go. + let probe = Probe::default(); + let attached = client.attach(&session, None, Box::new(probe.clone())); + probe.until("a snapshot", |p| p.snapshots() == 1).await; + let api = Api::new(h.url(), Some(token)); + let id = session.clone(); + run(async move { api.kill_session(&id).await }).await.unwrap(); + let ended = next(&mut events, "the end of the killed one", |e| match e { + Event::Ended { attachment, .. } => Some(attachment), + _ => None, + }) + .await; + assert_eq!(ended, attached); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_revoked_device_is_signed_out() { + let h = Harness::start().await; + let token = h.sign_in().await; + let (client, mut events) = ServerClient::start(h.url()); + client.set_token(Some(token.clone())); + connected(&mut events).await; + + // Signing out revokes the token: the open socket closes with 4001. + let api = Api::new(h.url(), Some(token.clone())); + run(async move { api.sign_out().await }).await.unwrap(); + next(&mut events, "signed out", |e| status(e).filter(|s| *s == Status::Unauthorized)).await; + + // The revoked token is refused at the upgrade, and by the API. + client.set_token(Some(token.clone())); + next(&mut events, "refused again", |e| status(e).filter(|s| *s == Status::Unauthorized)).await; + let api = Api::new(h.url(), Some(token)); + let refused = run(async move { api.sessions().await }).await.unwrap_err(); + assert_eq!(refused.code(), Some(ErrorCode::Unauthorized)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_wrong_password_and_an_unreachable_server_say_so() { + let h = Harness::start().await; + let api = Api::new(h.url(), None); + let request = SignInRequest { username: "me".into(), password: "wrong".into(), device_name: Some("x".into()) }; + let refused = run(async move { api.sign_in(&request).await }).await.unwrap_err(); + assert_eq!(refused.code(), Some(ErrorCode::InvalidCredentials)); + + let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap(); + let api = Api::new(ServerUrl::parse(&format!("http://{closed}")).unwrap(), None); + let failure = run(async move { api.info().await }).await.unwrap_err(); + assert!(matches!(failure, ApiFailure::Unreachable(_)), "{failure:?}"); +} + +/// A TCP relay in front of the server whose connections can be cut, as a +/// network that drops them. +struct Relay { + addr: std::net::SocketAddr, + connections: Arc>>>, + _accept: JoinHandle<()>, +} + +impl Relay { + async fn start(server: std::net::SocketAddr) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let connections: Arc>>> = Arc::default(); + let tracked = connections.clone(); + let accept = tokio::spawn(async move { + while let Ok((mut inbound, _)) = listener.accept().await { + let pipe = tokio::spawn(async move { + if let Ok(mut outbound) = TcpStream::connect(server).await { + let _ = tokio::io::copy_bidirectional(&mut inbound, &mut outbound).await; + } + }); + tracked.lock().push(pipe); + } + }); + Self { addr, connections, _accept: accept } + } + + fn drop_connections(&self) { + for pipe in self.connections.lock().drain(..) { + pipe.abort(); + } + } +} diff --git a/crates/redshell-core/Cargo.toml b/crates/redshell-core/Cargo.toml index e97129c..1731563 100644 --- a/crates/redshell-core/Cargo.toml +++ b/crates/redshell-core/Cargo.toml @@ -17,6 +17,10 @@ anyhow.workspace = true dirs.workspace = true which.workspace = true uuid.workspace = true +# Checks that a host's startup command splits like a shell command line. +shlex = "1.3" +# The wire form of SSH hosts, which the desktop sends and the server keeps. +redshell-protocol.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/redshell-core/src/launch.rs b/crates/redshell-core/src/launch.rs index b67d80c..5ebb85a 100644 --- a/crates/redshell-core/src/launch.rs +++ b/crates/redshell-core/src/launch.rs @@ -75,6 +75,8 @@ pub enum LaunchKind { Agent, Multiplexer, Plugin, + /// A session on a RedShell server, attached over the network. + Remote, } impl LaunchKind { @@ -85,6 +87,7 @@ impl LaunchKind { Self::Agent => "AI Agent", Self::Multiplexer => "Multiplexer", Self::Plugin => "Plugin", + Self::Remote => "Server", } } } diff --git a/crates/redshell-core/src/observer.rs b/crates/redshell-core/src/observer.rs index e284e66..1837346 100644 --- a/crates/redshell-core/src/observer.rs +++ b/crates/redshell-core/src/observer.rs @@ -20,6 +20,13 @@ pub trait SessionObserver: Send { fn on_command(&mut self, _command: &str) {} /// Child exited. fn on_exit(&mut self, _code: Option) {} + /// The program rang the bell (BEL). + fn on_bell(&mut self) {} + /// The program asked for a desktop notification (OSC 9 / OSC 777). + fn on_notification(&mut self, _title: Option<&str>, _body: &str) {} + /// The program switched to (`true`) or back from the alternate screen. + /// Called after the [`Self::on_output`] that switched it. + fn on_alt_screen(&mut self, _active: bool) {} } /// Fans one stream out to several observers. @@ -58,4 +65,7 @@ fan_out! { on_cwd(cwd: &str), on_command(command: &str), on_exit(code: Option), + on_bell(), + on_notification(title: Option<&str>, body: &str), + on_alt_screen(active: bool), } diff --git a/crates/redshell-core/src/settings.rs b/crates/redshell-core/src/settings.rs index e26b0f9..fdadbcd 100644 --- a/crates/redshell-core/src/settings.rs +++ b/crates/redshell-core/src/settings.rs @@ -9,6 +9,8 @@ mod edit; mod file; +pub mod ssh; +pub mod ssh_wire; use std::collections::BTreeMap; use std::path::PathBuf; @@ -31,6 +33,10 @@ pub struct Settings { pub agents: AgentSettings, pub plugins: PluginSettings, pub updates: UpdateSettings, + /// The RedShell servers the desktop connects to. + pub remote: RemoteSettings, + /// `redshell-server` only; the desktop ignores it. + pub server: ServerSettings, /// Keystroke → command id, e.g. `"ctrl-shift-t" = "tab.new"`. /// Entries here override (or with an empty value, remove) the defaults. pub keybindings: BTreeMap, @@ -85,6 +91,8 @@ pub enum SidebarSection { Agents, /// SSH hosts. Hosts, + /// Sessions on RedShell servers. + Servers, /// tmux / screen sessions on this computer. Multiplexer, /// Recorded sessions that are no longer open. @@ -93,8 +101,8 @@ pub enum SidebarSection { impl SidebarSection { /// Every section, in canonical order. - pub const ALL: [Self; 6] = - [Self::Sessions, Self::Shells, Self::Agents, Self::Hosts, Self::Multiplexer, Self::Recent]; + pub const ALL: [Self; 7] = + [Self::Sessions, Self::Shells, Self::Agents, Self::Hosts, Self::Servers, Self::Multiplexer, Self::Recent]; pub fn label(self) -> &'static str { match self { @@ -102,6 +110,7 @@ impl SidebarSection { Self::Shells => "Shells", Self::Agents => "AI agents", Self::Hosts => "SSH hosts", + Self::Servers => "Servers", Self::Multiplexer => "Multiplexer", Self::Recent => "Recent", } @@ -630,6 +639,57 @@ impl Default for UpdateSettings { } } +/// The `[remote]` section: the RedShell servers whose sessions the desktop +/// opens as tabs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct RemoteSettings { + pub servers: Vec, +} + +/// One `[[remote.servers]]` entry. The device token it signs in with is in +/// the system keychain, never in this file. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct RemoteServer { + pub name: String, + /// `https://…`, or `http://` to this computer only. + pub url: String, +} + +/// The `[server]` section, read by `redshell-server` from its own config +/// directory. Values stay strings here so a typo never stops the desktop +/// from loading the file; the server parses and checks them at start. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ServerSettings { + /// Address and port to listen on. Anything but loopback needs TLS. + pub listen: String, + /// The HTTPS origin clients use (`https://box.tailnet.ts.net`): setup + /// links, Origin checks, passkeys and push. + pub public_url: Option, + /// PEM certificate chain and private key for built-in TLS. + pub tls_cert: Option, + pub tls_key: Option, + /// Peers (IP addresses) whose `X-Forwarded-For` names the real client. + pub trusted_proxies: Vec, + /// How long an agent's permission request waits for an answer. + pub approval_timeout_secs: u64, +} + +impl Default for ServerSettings { + fn default() -> Self { + Self { + listen: "127.0.0.1:4747".into(), + public_url: None, + tls_cert: None, + tls_key: None, + trusted_proxies: Vec::new(), + approval_timeout_secs: 600, + } + } +} + impl Settings { /// Parses TOML text. pub fn from_toml(text: &str) -> Result { @@ -685,7 +745,7 @@ window_background = "opaque" # opaque | transparent | blurred background_image_opacity = 0.12 tab_bar = "top" # top | bottom | hidden show_sidebar = true -sidebar_sections = ["sessions", "hosts"] # sessions | shells | agents | hosts | multiplexer | recent +sidebar_sections = ["sessions", "hosts"] # sessions | shells | agents | hosts | servers | multiplexer | recent [terminal] # shell = "/bin/zsh" @@ -727,8 +787,18 @@ import_ssh_config = true [updates] check = true # look for a newer release once a day; nothing is downloaded +# [[remote.servers]] # RedShell servers; sign in from Settings → Servers +# name = "Pi" +# url = "https://box.example.ts.net" + [keybindings] # "ctrl-shift-t" = "tab.new" + +# [server] # read by redshell-server only +# listen = "127.0.0.1:4747" # anything but loopback needs tls_cert and tls_key +# public_url = "https://box.example.ts.net" +# trusted_proxies = ["127.0.0.1"] +# approval_timeout_secs = 600 "#; #[cfg(test)] @@ -743,6 +813,24 @@ mod tests { assert_eq!(parsed.safety, d.safety); assert_eq!(parsed.history, d.history); assert_eq!(parsed.terminal, d.terminal); + assert_eq!(parsed.server, d.server); + } + + #[test] + fn server_section_is_optional_and_lenient() { + let s = Settings::from_toml("[server]\nlisten = \"0.0.0.0:443\"\ntrusted_proxies = [\"127.0.0.1\"]\n").unwrap(); + assert_eq!(s.server.listen, "0.0.0.0:443"); + assert_eq!(s.server.trusted_proxies, ["127.0.0.1"]); + assert_eq!(s.server.approval_timeout_secs, 600); + assert_eq!(Settings::default().server.listen, "127.0.0.1:4747"); + } + + #[test] + fn servers_are_listed_by_name_and_address() { + let s = + Settings::from_toml("[[remote.servers]]\nname = \"Pi\"\nurl = \"https://pi.example.ts.net\"\n").unwrap(); + assert_eq!(s.remote.servers, [RemoteServer { name: "Pi".into(), url: "https://pi.example.ts.net".into() }]); + assert!(Settings::default().remote.servers.is_empty()); } #[test] diff --git a/crates/redshell-core/src/settings/edit.rs b/crates/redshell-core/src/settings/edit.rs index ce45c3f..6524955 100644 --- a/crates/redshell-core/src/settings/edit.rs +++ b/crates/redshell-core/src/settings/edit.rs @@ -313,7 +313,7 @@ mod tests { assert_eq!( added, [ - "sidebar_sections = [\"sessions\", \"hosts\", \"recent\"] # sessions | shells | agents | hosts | multiplexer | recent" + "sidebar_sections = [\"sessions\", \"hosts\", \"recent\"] # sessions | shells | agents | hosts | servers | multiplexer | recent" ] ); } diff --git a/crates/redshell-core/src/settings/ssh.rs b/crates/redshell-core/src/settings/ssh.rs new file mode 100644 index 0000000..62c7808 --- /dev/null +++ b/crates/redshell-core/src/settings/ssh.rs @@ -0,0 +1,358 @@ +//! The rules a saved SSH host follows, wherever it is saved: the desktop's +//! host editor and the server's hosts API both check a host with +//! [`validate`] before writing it. +//! +//! A host needs a name that is set, unique and safe on ssh's command line +//! (no leading `-`, no control characters), an address unless its name is +//! a `~/.ssh/config` alias, and a port from 1. Its startup command must not +//! pass for ssh options and must split like a shell command line, and each +//! port forward needs its ports, a target unless it is a SOCKS proxy, plain +//! addresses, and a listening address and port no other forward of the +//! host uses. A host only in `~/.ssh/config` is saved under its own name, +//! as an entry holding the fields that differ from the file +//! ([`imported_entry`]), which ssh layers over it. +//! +//! Turning form text into values (a port typed as text, extra arguments to +//! split) is the form's business; these rules see the values. + +use std::fmt; + +use super::{ForwardKind, PortForward, SshHost}; + +/// Why a host can't be saved. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HostError { + NameMissing, + NameTaken, + NameStartsWithDash, + NameHasControlChars, + /// Hosts from `~/.ssh/config` are saved under their alias. + NameOfImportedHost, + AddressMissing, + AddressStartsWithDash, + BadPort, + /// ssh would read a command starting with `-` as its own options. + StartupStartsWithDash, + StartupUnbalancedQuotes, + StartupHasControlChars, + /// The forward at this index. + Forward(usize, ForwardError), +} + +/// Why one port forward can't be saved. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ForwardError { + BadBindPort, + /// Another forward of the host listens on the same address and port. + BindTaken, + TargetMissing, + BadTargetPort, + /// The listening address starts with `-`, or holds spaces, slashes or + /// control characters. + BadBindAddress, + /// The same, for the target. + BadTargetAddress, +} + +impl ForwardError { + pub fn message(self) -> &'static str { + match self { + Self::BadBindPort | Self::BadTargetPort => "Enter a port from 1 to 65535.", + Self::BindTaken => "Another forward of this host already listens there.", + Self::TargetMissing => "Enter the host connections go to.", + Self::BadBindAddress | Self::BadTargetAddress => "Enter a host name or an IP address.", + } + } +} + +impl HostError { + /// What to tell the user, next to the field it concerns. + pub fn message(self) -> &'static str { + match self { + Self::NameMissing => "Give the host a name.", + Self::NameTaken => "Another host already has this name.", + Self::NameStartsWithDash => "A name can't start with “-”.", + Self::NameHasControlChars => "A name can't contain control characters.", + Self::NameOfImportedHost => "A host from ~/.ssh/config keeps its name there.", + Self::AddressMissing => "Enter an address, or name the host after a ~/.ssh/config alias.", + Self::AddressStartsWithDash => "An address can't start with “-”.", + Self::BadPort => "Enter a port from 1 to 65535.", + Self::StartupUnbalancedQuotes => "Close the quotes.", + Self::StartupStartsWithDash => "A startup command can't start with “-”.", + Self::StartupHasControlChars => "A startup command can't contain control characters.", + Self::Forward(_, error) => error.message(), + } + } +} + +/// The message, and for a forward which one it is (from 1). +impl fmt::Display for HostError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Forward(index, error) => write!(f, "Port forward {}: {}", index + 1, error.message()), + other => f.write_str(other.message()), + } + } +} + +impl std::error::Error for HostError {} + +/// What a host being saved takes the place of. +#[derive(Debug, Clone, Copy)] +pub enum Replacing<'a> { + /// It is a new host. + Nothing, + /// The saved host of this name. + Saved(&'a str), + /// A host only in `~/.ssh/config`, as read from it. + Imported(&'a SshHost), +} + +/// Everything wrong with `host` taking the place of `replacing`, given the +/// `saved` hosts and the `aliases` of `~/.ssh/config`. Empty when it can be +/// saved. +pub fn validate(host: &SshHost, replacing: Replacing<'_>, saved: &[SshHost], aliases: &[SshHost]) -> Vec { + let (name, address) = (host.name.as_str(), host.host.as_str()); + let original = match replacing { + Replacing::Saved(name) => Some(name), + _ => None, + }; + let name_error = if name.is_empty() { + Some(HostError::NameMissing) + } else if matches!(replacing, Replacing::Imported(h) if h.name != name) { + Some(HostError::NameOfImportedHost) + } else if name.starts_with('-') { + Some(HostError::NameStartsWithDash) + } else if name.chars().any(char::is_control) { + Some(HostError::NameHasControlChars) + } else if saved.iter().any(|h| h.name == name && Some(name) != original) { + Some(HostError::NameTaken) + } else { + None + }; + let address_error = if address.starts_with('-') { + Some(HostError::AddressStartsWithDash) + } else if address.is_empty() && !aliases.iter().any(|a| a.name == name) { + Some(HostError::AddressMissing) + } else { + None + }; + let port_error = (host.port == Some(0)).then_some(HostError::BadPort); + let startup_error = host.startup_command.as_deref().and_then(startup_error); + let mut errors: Vec = + [name_error, address_error, port_error, startup_error].into_iter().flatten().collect(); + errors.extend(forward_errors(&host.forwards)); + errors +} + +/// What is wrong with a startup command: ssh must not take it for options, +/// and the shell must see it end where RedShell appends to it. +fn startup_error(command: &str) -> Option { + if command.trim_start().starts_with('-') { + Some(HostError::StartupStartsWithDash) + } else if command.chars().any(|c| c.is_control() && c != '\t') { + Some(HostError::StartupHasControlChars) + } else if shlex::split(command).is_none() { + Some(HostError::StartupUnbalancedQuotes) + } else { + None + } +} + +/// What is wrong with each of `forwards`, in order, including two that +/// listen on the same address and port. +pub fn forward_errors(forwards: &[PortForward]) -> Vec { + let listens_where = |f: &PortForward| (f.kind == ForwardKind::Remote, f.bind_address.clone(), f.bind_port); + let mut errors = Vec::new(); + for (index, forward) in forwards.iter().enumerate() { + let problems = forward_problems(forward); + let taken = problems.is_empty() && forwards[..index].iter().any(|f| listens_where(f) == listens_where(forward)); + errors.extend( + problems.into_iter().chain(taken.then_some(ForwardError::BindTaken)).map(|e| HostError::Forward(index, e)), + ); + } + errors +} + +/// What is wrong with one forward on its own. +fn forward_problems(f: &PortForward) -> Vec { + let targeted = f.kind != ForwardKind::Dynamic; + let bad_address = |a: &Option| a.as_deref().is_some_and(|a| !is_address(a)); + let checks = [ + (bad_address(&f.bind_address), ForwardError::BadBindAddress), + (targeted && bad_address(&f.target_host), ForwardError::BadTargetAddress), + (f.bind_port == 0, ForwardError::BadBindPort), + (targeted && f.target_host.as_deref().is_none_or(str::is_empty), ForwardError::TargetMissing), + (targeted && f.target_port.is_none_or(|p| p == 0), ForwardError::BadTargetPort), + ]; + checks.into_iter().filter_map(|(wrong, error)| wrong.then_some(error)).collect() +} + +/// Whether ssh can take `address` as a host in a forwarding specification: +/// not an option, and no spaces, slashes or control characters. +fn is_address(address: &str) -> bool { + !address.starts_with('-') && !address.chars().any(|c| c.is_whitespace() || c.is_control() || c == '/') +} + +/// What is written for `host` saved over the `~/.ssh/config` host `base`: +/// only the fields that differ, which ssh layers over the file's entry. +pub fn imported_entry(base: &SshHost, host: SshHost) -> SshHost { + fn changed(base: &T, value: T) -> T { + if *base == value { T::default() } else { value } + } + SshHost { + name: host.name, + host: changed(&base.host, host.host), + user: changed(&base.user, host.user), + port: changed(&base.port, host.port), + identity_file: changed(&base.identity_file, host.identity_file), + jump_host: changed(&base.jump_host, host.jump_host), + extra_args: changed(&base.extra_args, host.extra_args), + multiplexer: changed(&base.multiplexer, host.multiplexer), + attach_session: changed(&base.attach_session, host.attach_session), + group: changed(&base.group, host.group), + tags: changed(&base.tags, host.tags), + forward_agent: changed(&base.forward_agent, host.forward_agent), + startup_command: changed(&base.startup_command, host.startup_command), + forwards: changed(&base.forwards, host.forwards), + } +} + +/// The host an entry saved over the `~/.ssh/config` host `base` stands +/// for: `base` with the entry's fields laid over it (the reverse of +/// [`imported_entry`]). +pub fn layered(base: &SshHost, entry: &SshHost) -> SshHost { + fn over(base: &T, value: &T) -> T { + if *value == T::default() { base.clone() } else { value.clone() } + } + SshHost { + name: entry.name.clone(), + host: over(&base.host, &entry.host), + user: over(&base.user, &entry.user), + port: over(&base.port, &entry.port), + identity_file: over(&base.identity_file, &entry.identity_file), + jump_host: over(&base.jump_host, &entry.jump_host), + extra_args: over(&base.extra_args, &entry.extra_args), + multiplexer: over(&base.multiplexer, &entry.multiplexer), + attach_session: over(&base.attach_session, &entry.attach_session), + group: over(&base.group, &entry.group), + tags: over(&base.tags, &entry.tags), + forward_agent: over(&base.forward_agent, &entry.forward_agent), + startup_command: over(&base.startup_command, &entry.startup_command), + forwards: over(&base.forwards, &entry.forwards), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn host(name: &str, address: &str) -> SshHost { + SshHost { name: name.into(), host: address.into(), ..Default::default() } + } + + fn saved() -> Vec { + vec![host("web", "w.example"), host("db", "d.example")] + } + + fn aliases() -> Vec { + vec![SshHost { user: Some("me".into()), port: Some(2200), ..host("box", "10.0.0.5") }] + } + + fn errors(replacing: Replacing<'_>, host: &SshHost) -> Vec { + validate(host, replacing, &saved(), &aliases()) + } + + #[test] + fn names_must_be_given_unique_and_safe() { + let new = Replacing::Nothing; + assert_eq!(errors(new, &host("", "a.example")), [HostError::NameMissing]); + assert_eq!(errors(new, &host("web", "a.example")), [HostError::NameTaken]); + assert_eq!(errors(new, &host("-oProxyCommand=x", "a.example")), [HostError::NameStartsWithDash]); + assert_eq!(errors(new, &host("a\nb", "a.example")), [HostError::NameHasControlChars]); + // A host keeps its own name, and may take one nobody else has. + assert!(errors(Replacing::Saved("web"), &host("web", "w.example")).is_empty()); + assert!(errors(Replacing::Saved("web"), &host("www", "w.example")).is_empty()); + assert_eq!(errors(Replacing::Saved("web"), &host("db", "w.example")), [HostError::NameTaken]); + } + + #[test] + fn addresses_and_ports_are_checked() { + let new = Replacing::Nothing; + assert_eq!(errors(new, &host("a", "")), [HostError::AddressMissing]); + assert_eq!(errors(new, &host("a", "-oProxyCommand=x")), [HostError::AddressStartsWithDash]); + // A config alias needs no address: ssh resolves it. + assert!(errors(new, &host("box", "")).is_empty()); + assert_eq!(errors(new, &SshHost { port: Some(0), ..host("a", "a.example") }), [HostError::BadPort]); + let all = SshHost { port: Some(0), ..host("", "") }; + assert_eq!(errors(new, &all), [HostError::NameMissing, HostError::AddressMissing, HostError::BadPort]); + } + + #[test] + fn an_imported_host_keeps_its_name_and_saves_only_what_changed() { + let base = &aliases()[0]; + assert_eq!(errors(Replacing::Imported(base), &host("lab-box", "10.0.0.5")), [HostError::NameOfImportedHost]); + let edited = SshHost { user: Some("root".into()), group: Some("Lab".into()), ..base.clone() }; + assert!(errors(Replacing::Imported(base), &edited).is_empty()); + let expected = + SshHost { name: "box".into(), user: Some("root".into()), group: Some("Lab".into()), ..Default::default() }; + assert_eq!(imported_entry(base, edited.clone()), expected); + assert_eq!(layered(base, &expected), edited); + } + + #[test] + fn startup_commands_cant_pass_for_options() { + for (command, error) in [ + ("-oProxyCommand=x", Some(HostError::StartupStartsWithDash)), + (" -x", Some(HostError::StartupStartsWithDash)), + ("echo 'open", Some(HostError::StartupUnbalancedQuotes)), + ("ls\u{1b}", Some(HostError::StartupHasControlChars)), + ("cd /srv && htop # go", None), + ] { + let h = SshHost { startup_command: Some(command.into()), ..host("a", "a.example") }; + assert_eq!(errors(Replacing::Nothing, &h), error.into_iter().collect::>(), "{command}"); + } + } + + fn forward(kind: ForwardKind, bind_port: u16, target: Option<(&str, u16)>) -> PortForward { + PortForward { + kind, + bind_port, + target_host: target.map(|(h, _)| h.into()), + target_port: target.map(|(_, p)| p), + ..Default::default() + } + } + + #[test] + fn forwards_need_ports_a_target_and_plain_addresses() { + use ForwardError::*; + let good = forward(ForwardKind::Local, 8080, Some(("db", 5432))); + assert!(forward_errors(std::slice::from_ref(&good)).is_empty()); + let empty = forward(ForwardKind::Local, 0, None); + assert_eq!( + forward_errors(&[empty]), + [BadBindPort, TargetMissing, BadTargetPort].map(|e| HostError::Forward(0, e)) + ); + for (bad, error) in [ + (PortForward { bind_address: Some("-oProxyCommand=x".into()), ..good.clone() }, BadBindAddress), + (PortForward { target_host: Some("a b".into()), ..good.clone() }, BadTargetAddress), + (PortForward { target_host: Some("a/b".into()), ..good.clone() }, BadTargetAddress), + ] { + assert_eq!(forward_errors(&[bad]), [HostError::Forward(0, error)]); + } + // A SOCKS proxy needs only its port; its target is not looked at. + let socks = PortForward { target_host: Some("-x".into()), ..forward(ForwardKind::Dynamic, 1080, None) }; + assert!(forward_errors(&[socks]).is_empty()); + } + + #[test] + fn two_forwards_cant_listen_on_the_same_port() { + let socks = forward(ForwardKind::Dynamic, 1080, None); + let remote = forward(ForwardKind::Remote, 1080, Some(("localhost", 80))); + assert!(forward_errors(&[socks.clone(), remote]).is_empty(), "a remote port is on the host"); + assert_eq!(forward_errors(&[socks.clone(), socks]), [HostError::Forward(1, ForwardError::BindTaken)]); + let message = HostError::Forward(1, ForwardError::BindTaken).to_string(); + assert_eq!(message, "Port forward 2: Another forward of this host already listens there."); + } +} diff --git a/crates/redshell-core/src/settings/ssh_wire.rs b/crates/redshell-core/src/settings/ssh_wire.rs new file mode 100644 index 0000000..8046002 --- /dev/null +++ b/crates/redshell-core/src/settings/ssh_wire.rs @@ -0,0 +1,125 @@ +//! SSH hosts in the form the server's hosts API carries them +//! ([`redshell_protocol::SshHost`]): the server lists its hosts this way, +//! and the desktop sends one of its own. + +use std::path::PathBuf; + +use redshell_protocol::{self as wire, HostOrigin, Multiplexer}; + +use super::{ForwardKind, MultiplexerKind, PortForward, SshHost}; + +/// `host` as the hosts API carries it; `origin` says where it is kept. +pub fn to_wire(host: &SshHost, origin: HostOrigin) -> wire::SshHost { + wire::SshHost { + name: host.name.clone(), + host: host.host.clone(), + user: host.user.clone(), + port: host.port, + identity_file: host.identity_file.as_ref().map(|p| p.display().to_string()), + jump_host: host.jump_host.clone(), + extra_args: host.extra_args.clone(), + multiplexer: host.multiplexer.map(|m| match m { + MultiplexerKind::Tmux => Multiplexer::Tmux, + MultiplexerKind::Screen => Multiplexer::Screen, + }), + attach_session: host.attach_session.clone(), + group: host.group.clone(), + forward_agent: host.forward_agent, + startup_command: host.startup_command.clone(), + forwards: host.forwards.iter().map(forward_to_wire).collect(), + tags: host.tags.clone(), + origin, + } +} + +fn forward_to_wire(f: &PortForward) -> wire::PortForward { + wire::PortForward { + kind: match f.kind { + ForwardKind::Local => wire::ForwardKind::Local, + ForwardKind::Remote => wire::ForwardKind::Remote, + ForwardKind::Dynamic => wire::ForwardKind::Dynamic, + }, + bind_address: f.bind_address.clone(), + bind_port: f.bind_port, + target_host: f.target_host.clone(), + target_port: f.target_port, + label: f.label.clone(), + auto_start: f.auto_start, + } +} + +fn forward_from_wire(f: wire::PortForward) -> PortForward { + let optional = |v: Option| v.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()); + PortForward { + kind: match f.kind { + wire::ForwardKind::Local => ForwardKind::Local, + wire::ForwardKind::Remote => ForwardKind::Remote, + wire::ForwardKind::Dynamic => ForwardKind::Dynamic, + }, + bind_address: optional(f.bind_address), + bind_port: f.bind_port, + target_host: optional(f.target_host), + target_port: f.target_port, + label: optional(f.label), + auto_start: f.auto_start, + } +} + +/// A host from the wire, trimmed, with empty optional fields left unset. +pub fn from_wire(host: wire::SshHost) -> SshHost { + let optional = |v: Option| v.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()); + SshHost { + name: host.name.trim().to_owned(), + host: host.host.trim().to_owned(), + user: optional(host.user), + port: host.port, + identity_file: optional(host.identity_file).map(PathBuf::from), + jump_host: optional(host.jump_host), + extra_args: host.extra_args, + multiplexer: host.multiplexer.map(|m| match m { + Multiplexer::Tmux => MultiplexerKind::Tmux, + Multiplexer::Screen => MultiplexerKind::Screen, + }), + attach_session: optional(host.attach_session), + group: optional(host.group), + forward_agent: host.forward_agent, + startup_command: optional(host.startup_command), + forwards: host.forwards.into_iter().map(forward_from_wire).collect(), + tags: host.tags.into_iter().map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hosts_survive_the_round_trip() { + let host = SshHost { + name: "pi".into(), + host: "pi.lan".into(), + user: Some("me".into()), + port: Some(2222), + identity_file: Some(PathBuf::from("/keys/pi")), + multiplexer: Some(MultiplexerKind::Tmux), + forwards: vec![PortForward { kind: ForwardKind::Dynamic, bind_port: 1080, ..Default::default() }], + tags: vec!["home".into()], + ..Default::default() + }; + assert_eq!(from_wire(to_wire(&host, HostOrigin::Redshell)), host); + } + + #[test] + fn incoming_hosts_are_trimmed() { + let host = wire::SshHost { + name: " pi ".into(), + host: "pi.lan ".into(), + user: Some(" ".into()), + tags: vec![" home ".into(), "".into()], + ..Default::default() + }; + let host = from_wire(host); + assert_eq!((host.name.as_str(), host.host.as_str(), host.user), ("pi", "pi.lan", None)); + assert_eq!(host.tags, ["home"]); + } +} diff --git a/crates/redshell-protocol/Cargo.toml b/crates/redshell-protocol/Cargo.toml new file mode 100644 index 0000000..bdb7738 --- /dev/null +++ b/crates/redshell-protocol/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "redshell-protocol" +description = "Wire types shared by redshell-server, the desktop client and (as TypeScript) the PWA." +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true + +[dev-dependencies] +# Test builds derive `TS` and write the TypeScript definitions into web/src/protocol. +ts-rs = { version = "12", features = ["serde-json-impl", "no-serde-warnings"] } diff --git a/crates/redshell-protocol/src/api.rs b/crates/redshell-protocol/src/api.rs new file mode 100644 index 0000000..d94c3bf --- /dev/null +++ b/crates/redshell-protocol/src/api.rs @@ -0,0 +1,183 @@ +//! REST bodies: server info, setup, sign-in, the account and errors. + +use serde::{Deserialize, Serialize}; + +/// `GET /api/auth/info`, open to everyone: what a client needs before it +/// signs in. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct ServerInfo { + /// `redshell-server` version. + pub version: String, + /// [`crate::PROTOCOL_VERSION`] of the server. + pub protocol_version: u32, + /// No account exists yet: the setup link from the server log creates one. + pub setup_required: bool, + /// Shortest password accepted (the only rule). + pub min_password_length: u32, + /// Passkey sign-in is offered (the server has an https `public_url`). + #[serde(default)] + pub passkeys: bool, +} + +/// `POST /api/setup`: creates the first account with the one-time code +/// from the server log, and signs the browser in. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct SetupRequest { + pub code: String, + pub username: String, + pub password: String, +} + +/// `POST /api/auth/sign-in`. Without `device_name` the browser gets a +/// session cookie; with it, the response carries a bearer device token for +/// that device (the desktop) and no cookie is set. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct SignInRequest { + pub username: String, + pub password: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub device_name: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct SignInResponse { + pub user: User, + /// Bearer token (`Authorization: Bearer …`), shown once. Only when the + /// request named a device. + pub device_token: Option, +} + +/// `GET /api/auth/me`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct User { + pub id: i64, + pub username: String, + pub created_at: i64, +} + +/// `POST /api/auth/reauth`: proves again who is signed in, before a change +/// that needs it (adding or removing a passkey, passkey-only sign-in on or +/// off, approving a pairing, signing out another browser or device, and a +/// password change of a passkey-only account). It holds for five minutes. +/// The password works unless the account signs in with passkeys only; a +/// passkey answers the challenge of `POST /api/auth/reauth/passkey/begin`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(tag = "method", rename_all = "snake_case")] +pub enum ReauthRequest { + Password { + password: String, + }, + Passkey { + ceremony: String, + /// The browser's answer, in its JSON form (`toJSON()`). + credential: serde_json::Value, + }, +} + +/// The answer to [`ReauthRequest`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct ReauthResponse { + /// Until when changes that need a re-authentication go through. + pub reauth_expires_at: i64, +} + +/// `POST /api/account/password`. Signs out every other browser and device. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct ChangePasswordRequest { + pub current_password: String, + pub new_password: String, +} + +/// A device signed in with a bearer token (`GET /api/account/devices`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct Device { + pub id: i64, + pub name: String, + pub created_at: i64, + pub last_seen_at: i64, + pub last_ip: Option, + /// The device making this request. + pub current: bool, +} + +/// A signed-in browser (`GET /api/account/sessions`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct BrowserSession { + pub id: i64, + /// The browser and system it signed in from (`Safari on iPhone`), as + /// its User-Agent said; also who answered an approval from it. + #[serde(default)] + pub name: String, + pub created_at: i64, + pub last_seen_at: i64, + pub expires_at: i64, + pub last_ip: Option, + pub user_agent: Option, + /// The browser making this request. + pub current: bool, +} + +/// `GET /api/fs/folders?path=`: the folders in a folder +/// on the server, for completing paths. Files are not listed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct FolderListing { + /// The folder listed, as given. + pub path: String, + /// Names of its subfolders, sorted. + pub folders: Vec, + /// More folders exist than were listed. + pub truncated: bool, +} + +/// Body of every error response, and of WebSocket `error` messages. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct ApiError { + pub code: ErrorCode, + pub message: String, + /// With `rate_limited`: seconds until the next attempt is accepted + /// (also in the `Retry-After` header). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub retry_after_secs: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + /// The request is malformed or a value is out of range. + BadRequest, + /// Wrong username or password; the same for an unknown user. + InvalidCredentials, + /// Not signed in, or the session or token is no longer valid. + Unauthorized, + /// Signed in, but not allowed (a foreign Origin, an expired setup code). + Forbidden, + NotFound, + /// The thing exists already, or setup was done. + Conflict, + /// Too many failed sign-ins; see `retry_after_secs`. + RateLimited, + /// The right password, but the account signs in with passkeys only. + PasskeyRequired, + /// The change needs a recent re-authentication: `POST /api/auth/reauth` + /// with the password or a passkey, then the same request again. + ReauthRequired, + /// This server is not set up for it (passkeys without an https + /// `public_url`). + Unavailable, + Internal, +} diff --git a/crates/redshell-protocol/src/hosts.rs b/crates/redshell-protocol/src/hosts.rs new file mode 100644 index 0000000..f74637b --- /dev/null +++ b/crates/redshell-protocol/src/hosts.rs @@ -0,0 +1,138 @@ +//! The server's SSH hosts (`/api/hosts`). + +use serde::{Deserialize, Serialize}; + +/// An SSH host as the hosts API lists and takes it: the fields of a +/// `[[ssh.hosts]]` entry in the server's `config.toml`. There is no field +/// for a secret, and a request with any field not listed here is refused: +/// passwords and keys stay on the machine that has them. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(deny_unknown_fields)] +pub struct SshHost { + pub name: String, + /// Address; empty when `name` is a `~/.ssh/config` alias ssh resolves. + #[serde(default)] + #[cfg_attr(test, ts(as = "Option", optional))] + pub host: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub user: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub port: Option, + /// A key file on the server. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub identity_file: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub jump_host: Option, + #[serde(default)] + #[cfg_attr(test, ts(as = "Option>", optional))] + pub extra_args: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub multiplexer: Option, + /// Multiplexer session to attach to (or create) on connect. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub attach_session: Option, + /// Folder it is listed under. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub group: Option, + /// Forward the SSH agent (`ssh -A`) in the host's terminal sessions. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + #[cfg_attr(test, ts(as = "Option", optional))] + pub forward_agent: bool, + /// Run after login, before the shell or the attached session. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub startup_command: Option, + /// Port forwards, run as tunnels by the desktop that has the host. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(test, ts(as = "Option>", optional))] + pub forwards: Vec, + #[serde(default)] + #[cfg_attr(test, ts(as = "Option>", optional))] + pub tags: Vec, + /// Where the host is defined; set by the server, ignored in requests. + #[serde(default)] + #[cfg_attr(test, ts(as = "Option", optional))] + pub origin: HostOrigin, +} + +/// One port forward of a host. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(deny_unknown_fields)] +pub struct PortForward { + pub kind: ForwardKind, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub bind_address: Option, + pub bind_port: u16, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub target_host: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub target_port: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub label: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + #[cfg_attr(test, ts(as = "Option", optional))] + pub auto_start: bool, +} + +/// What a port forward forwards. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum ForwardKind { + /// A port on the client reaches a target as seen from the host (`-L`). + #[default] + Local, + /// A port on the host reaches a target as seen from the client (`-R`). + Remote, + /// A SOCKS proxy on the client (`-D`). + Dynamic, +} + +/// Where a host is defined. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum HostOrigin { + /// A `[[ssh.hosts]]` entry of the server's `config.toml`. + #[default] + Redshell, + /// Only in the server user's `~/.ssh/config`. Saving it (`PUT` under + /// its own name) writes an entry with the fields that differ. + SshConfig, +} + +/// Remote multiplexer the server manages on a host. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum Multiplexer { + Tmux, + Screen, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hosts_refuse_fields_they_do_not_have() { + let host: SshHost = + serde_json::from_str(r#"{"name": "box", "host": "box.lan", "origin": "ssh_config"}"#).unwrap(); + assert_eq!(host.origin, HostOrigin::SshConfig); + let secret = serde_json::from_str::(r#"{"name": "box", "host": "box.lan", "password": "hunter2"}"#); + assert!(secret.is_err()); + } +} diff --git a/crates/redshell-protocol/src/lib.rs b/crates/redshell-protocol/src/lib.rs new file mode 100644 index 0000000..0583875 --- /dev/null +++ b/crates/redshell-protocol/src/lib.rs @@ -0,0 +1,128 @@ +//! # redshell-protocol +//! +//! Everything that crosses the wire between `redshell-server` and its +//! clients: REST request and response bodies ([`api`]), sessions, agents and +//! approvals ([`session`]), SSH hosts ([`hosts`]), desktop pairing +//! ([`pairing`]), passkeys ([`passkeys`]), Web Push ([`push`]), and the +//! WebSocket messages and binary framing +//! ([`ws`]). The PWA uses the same types as TypeScript, generated into +//! `web/src/protocol/` by this crate's tests (`cargo test -p +//! redshell-protocol`), so there is one source of truth. +//! +//! Conventions: JSON field names are `snake_case`, enums are `snake_case` +//! strings, tagged unions carry a `type` field, timestamps are Unix +//! milliseconds and ids of sessions and approvals are opaque strings. +//! Every request that changes something (any method but GET, HEAD and +//! OPTIONS) carries the header `X-RedShell: 1`. `docs/REMOTE.md` lists the +//! endpoints. + +pub mod api; +pub mod hosts; +pub mod pairing; +pub mod passkeys; +pub mod push; +pub mod session; +pub mod ws; + +pub use api::*; +pub use hosts::*; +pub use pairing::*; +pub use passkeys::*; +pub use push::*; +pub use session::*; +pub use ws::*; + +/// Version of this protocol. It goes up on every change a client built +/// against the previous version would misread; additions that old clients +/// can ignore (a new optional field, a new message type) keep it. +/// +/// 2: state-changing requests need `X-RedShell: 1`. +pub const PROTOCOL_VERSION: u32 = 2; + +/// The header every state-changing `/api` request carries, and its value. +/// A cross-site page can't set it without a CORS preflight, which the +/// server never grants. +pub const CHANGE_HEADER: &str = "x-redshell"; +pub const CHANGE_HEADER_VALUE: &str = "1"; + +#[cfg(test)] +mod typescript { + use std::path::Path; + + use ts_rs::{Config, TS}; + + use super::*; + + /// Writes the TypeScript definitions into `web/src/protocol`. The files + /// are committed; a change here that is not committed shows up as a diff. + #[test] + fn export_typescript() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../web/src/protocol"); + // Everything in the folder is generated: clear it so renamed types leave nothing behind. + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten().filter(|e| e.path().extension().is_some_and(|x| x == "ts")) { + std::fs::remove_file(entry.path()).unwrap(); + } + } + let cfg = Config::new().with_large_int("number").with_out_dir(&dir); + macro_rules! export { + ($($ty:ty),* $(,)?) => {{ + $(<$ty>::export_all(&cfg).expect(concat!("exporting ", stringify!($ty)));)* + }}; + } + export!( + ServerInfo, + SetupRequest, + SignInRequest, + SignInResponse, + ChangePasswordRequest, + ReauthRequest, + ReauthResponse, + Device, + FolderListing, + BrowserSession, + ApiError, + Profile, + CreateSessionRequest, + RenameSessionRequest, + ApprovalAnswer, + SshHost, + PairRequest, + PairStarted, + PairStatus, + PairingInfo, + PasskeyChallenge, + PasskeySignInRequest, + RegisterPasskeyRequest, + Passkey, + RenamePasskeyRequest, + PasskeyOnlyRequest, + Account, + PushKey, + PushSubscribeRequest, + PushEventsRequest, + PushEndpoint, + PushSubscriptionInfo, + PushPayload, + ClientMessage, + ServerMessage, + ); + + let mut names: Vec = std::fs::read_dir(&dir) + .unwrap() + .filter_map(|e| e.ok()?.file_name().into_string().ok()) + .filter_map(|n| n.strip_suffix(".ts").map(str::to_owned)) + .filter(|n| n != "index") + .collect(); + names.sort(); + let mut index = String::from("// Generated by redshell-protocol's tests. Do not edit.\n\n"); + index.push_str(&format!("export const PROTOCOL_VERSION = {PROTOCOL_VERSION};\n")); + index.push_str(&format!( + "export const CHANGE_HEADER = {CHANGE_HEADER:?};\nexport const CHANGE_HEADER_VALUE = {CHANGE_HEADER_VALUE:?};\n\n" + )); + for name in names { + index.push_str(&format!("export type {{ {name} }} from \"./{name}\";\n")); + } + std::fs::write(dir.join("index.ts"), index).unwrap(); + } +} diff --git a/crates/redshell-protocol/src/pairing.rs b/crates/redshell-protocol/src/pairing.rs new file mode 100644 index 0000000..2dcef95 --- /dev/null +++ b/crates/redshell-protocol/src/pairing.rs @@ -0,0 +1,84 @@ +//! Desktop pairing: a device asks for a sign-in and shows a short code; a +//! signed-in browser types that code and approves the device. +//! +//! 1. The device: `POST /api/pair` ([`PairRequest`] → [`PairStarted`]), +//! shows `code` and opens `url` in a browser. +//! 2. The browser, signed in: the user types the code; `GET +//! /api/pair/{code}` → [`PairingInfo`], then `POST +//! /api/pair/{code}/approve` or `/reject`. A code never comes from a +//! link: the pairing page has no code in its address. +//! 3. The device polls `GET /api/pair/{id}` with `Authorization: Bearer +//! ` → [`PairStatus`] until it is approved (the device +//! token comes once) or rejected. A request expires after 10 minutes; +//! then, and for a wrong secret, the poll answers `not_found`. + +use serde::{Deserialize, Serialize}; + +use crate::api::User; + +/// `POST /api/pair`, open to everyone and rate-limited. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PairRequest { + /// What the device calls itself, shown when approving (1 to 100 + /// characters); it becomes the device's name. + pub device_name: String, + /// Its system (`macOS`, `Windows`, `Linux`), shown when approving. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub platform: Option, +} + +/// The new request, for the device only. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PairStarted { + /// For polling. + pub id: String, + /// What the user types in the browser: `KX7-4MP`. + pub code: String, + /// Proves the poller started the request. Never shown. + pub poll_secret: String, + pub expires_at: i64, + /// The pairing page to open in a browser (`/pair`). + pub url: String, +} + +/// `GET /api/pair/{id}`: where the device's request is. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum PairStatus { + Pending, + Rejected, + /// Signed in as `user`; `device_token` is the bearer token, returned + /// this one time. + Approved { + user: User, + device_token: String, + }, +} + +/// `GET /api/pair/{code}`: the waiting request a typed code names, for the +/// user to check before approving. Someone may have sent the user a code +/// of a request they started themselves: the page warns that approving +/// signs that device in as the user, shows where the request came from +/// and whether that is where the user is, and says the device's name is +/// what the device calls itself. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PairingInfo { + pub code: String, + /// Named by the device itself: anyone can call a device anything. + pub device_name: String, + pub platform: Option, + /// The address the request came from. + pub ip: String, + /// The request came from the address of the browser asking (for IPv6, + /// the same /64). When it did not, the device is somewhere else. + #[serde(default)] + #[cfg_attr(test, ts(as = "Option", optional))] + pub same_address: bool, + pub created_at: i64, + pub expires_at: i64, +} diff --git a/crates/redshell-protocol/src/passkeys.rs b/crates/redshell-protocol/src/passkeys.rs new file mode 100644 index 0000000..2edec6c --- /dev/null +++ b/crates/redshell-protocol/src/passkeys.rs @@ -0,0 +1,96 @@ +//! Passkeys (WebAuthn): signing in with one, managing them, and +//! passkey-only sign-in. +//! +//! Each ceremony has two steps. `…/begin` returns a [`PasskeyChallenge`]: +//! hand its `options` to `navigator.credentials.create()` (registering) or +//! `.get()` (signing in), with base64url strings turned into bytes as +//! WebAuthn's JSON form says (`PublicKeyCredential.parseCreationOptionsFromJSON` +//! and `parseRequestOptionsFromJSON`). `…/finish` takes the `ceremony` back +//! with the credential the browser made, in its JSON form (`toJSON()`). +//! A ceremony can be finished once, within five minutes. + +use serde::{Deserialize, Serialize}; + +/// `POST /api/auth/passkey/begin` and `POST /api/account/passkeys/begin`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PasskeyChallenge { + pub ceremony: String, + /// `{publicKey: …}` for WebAuthn. Sign-in asks for a discoverable + /// passkey with no `allowCredentials`, so no name is needed; a client + /// that offers passkeys in the name field's autofill adds `mediation: + /// "conditional"` itself. + pub options: serde_json::Value, +} + +/// `POST /api/auth/passkey/finish`. Without `device_name` the browser gets +/// a session cookie; with it, the response carries a device token. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PasskeySignInRequest { + pub ceremony: String, + pub credential: serde_json::Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub device_name: Option, +} + +/// `POST /api/account/passkeys/finish`: registers the new passkey. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct RegisterPasskeyRequest { + pub ceremony: String, + pub credential: serde_json::Value, + /// What the user calls it (`iPhone`, `YubiKey`); 1 to 64 characters. + /// Without one it is named after the browser that registered it. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub name: Option, +} + +/// A registered passkey (`GET /api/account/passkeys`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct Passkey { + pub id: i64, + pub name: String, + pub created_at: i64, + /// Last sign-in with it; `null` before the first. + pub last_used_at: Option, +} + +/// `PATCH /api/account/passkeys/{id}`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct RenamePasskeyRequest { + pub name: String, +} + +/// `PUT /api/account/passkey-only`. Turning it on needs at least one +/// passkey; while it is on, password sign-in answers `passkey_required` +/// and the last passkey cannot be revoked. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PasskeyOnlyRequest { + pub enabled: bool, +} + +/// `GET /api/account`: the signed-in user and how they sign in. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct Account { + pub id: i64, + pub username: String, + pub created_at: i64, + /// Password sign-in is off for this user. + pub passkey_only: bool, + /// How many passkeys the user has. + pub passkeys: u32, + /// Whether this server offers passkeys (it needs an https `public_url`). + pub passkeys_available: bool, + /// Until when this sign-in's last re-authentication holds; absent when + /// a change that needs one would answer `reauth_required`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub reauth_expires_at: Option, +} diff --git a/crates/redshell-protocol/src/push.rs b/crates/redshell-protocol/src/push.rs new file mode 100644 index 0000000..ada722e --- /dev/null +++ b/crates/redshell-protocol/src/push.rs @@ -0,0 +1,110 @@ +//! Web Push (`/api/push/*`) and the message a service worker receives. + +use serde::{Deserialize, Serialize}; + +use crate::session::EventKind; + +/// `GET /api/push/key`: the server's VAPID key, the +/// `applicationServerKey` for `pushManager.subscribe()`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PushKey { + /// Uncompressed P-256 point, base64url. + pub vapid_public_key: String, +} + +/// `POST /api/push/subscriptions`: this browser's subscription, as +/// `PushSubscription.toJSON()` gives it, and the events it wants (every +/// kind when absent). It replaces the browser session's earlier one, and +/// goes when the session signs out. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PushSubscribeRequest { + /// The push service's URL; only `https` on the default port, to a + /// public host, is accepted. + pub endpoint: String, + pub keys: PushSubscriptionKeys, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub events: Option>, +} + +/// The browser's keys for encrypting to it (RFC 8291), base64url. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PushSubscriptionKeys { + pub p256dh: String, + pub auth: String, +} + +/// `PUT /api/push/subscriptions`: what one of the user's subscriptions is +/// sent. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PushEventsRequest { + pub endpoint: String, + pub events: Vec, +} + +/// `DELETE /api/push/subscriptions` and `POST /api/push/test`: one of the +/// user's subscriptions. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PushEndpoint { + pub endpoint: String, +} + +/// `GET /api/push/subscriptions`: the user's subscriptions. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PushSubscriptionInfo { + pub endpoint: String, + pub events: Vec, + pub created_at: i64, + /// The browser making this request. + pub current: bool, +} + +/// What a subscription can be sent. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum PushEvent { + /// An agent asks for permission. + ApprovalRequested, + /// An agent waits for the user to type. + NeedsInput, + /// An agent finished its turn. + Finished, + /// A program exited with an error. + Failed, + /// A program asked for a notification (OSC 9 / OSC 777). + Notification, +} + +impl PushEvent { + pub const ALL: [PushEvent; 5] = + [Self::ApprovalRequested, Self::NeedsInput, Self::Finished, Self::Failed, Self::Notification]; +} + +/// The JSON a push message carries, for the service worker. Nobody is sent +/// one for a session they typed into in the last 30 seconds. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct PushPayload { + pub title: String, + pub body: String, + /// The session it is about, for the link `/s/`; `null` for a + /// test message. + pub session: Option, + /// What happened; `null` for a test message. + pub kind: Option, + /// Same for every message about a session, so a newer one replaces the + /// older notification. + pub tag: String, + /// Alert again when replacing a notification (approvals and questions). + pub renotify: bool, + /// Where to go on a tap: `/s/`, or `/`. + pub url: String, + pub at: i64, +} diff --git a/crates/redshell-protocol/src/session.rs b/crates/redshell-protocol/src/session.rs new file mode 100644 index 0000000..5bf44b1 --- /dev/null +++ b/crates/redshell-protocol/src/session.rs @@ -0,0 +1,222 @@ +//! Sessions, the profiles they start from, agent state, approvals and events. + +use serde::{Deserialize, Serialize}; + +/// What a session runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum SessionKind { + Shell, + /// A coding agent (Claude Code, Codex, …): see [`SessionInfo::agent`]. + Agent, + Ssh, + /// A custom command line. + Command, +} + +/// Something a session can be started from (`GET /api/profiles`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct Profile { + /// `shell`, `agent:` or `ssh:`. + pub id: String, + pub name: String, + pub kind: SessionKind, + pub description: String, + /// `false` when the program is not installed on the server. + pub available: bool, + /// For SSH hosts: the folder they are listed under. + pub group: Option, +} + +/// `POST /api/sessions`. Starts `profile` (the default shell when absent), +/// or `command` when given; `cwd` is the folder it starts in. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct CreateSessionRequest { + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub profile: Option, + /// Program and arguments, run without a shell. + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub command: Option>, + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub cwd: Option, + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub name: Option, + /// Initial size; 100 × 30 when absent. + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub cols: Option, + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub rows: Option, +} + +/// `PATCH /api/sessions/{id}`: a name, or `null` to go back to the title. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct RenameSessionRequest { + pub name: Option, +} + +/// Where an agent is in its turn, from its hooks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum AgentState { + /// Started, nothing asked yet. + Idle, + Working, + /// Waiting for an [`Approval`]. + NeedsApproval, + /// Waiting for the user to type (a question, an idle prompt). + NeedsInput, + /// The turn ended; [`SessionInfo::last_message`] has its last words. + Finished, +} + +/// How a session's program ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct ExitState { + /// Exit code; `null` when the OS could not tell. + pub code: Option, + pub at: i64, +} + +/// A session on the server (`GET /api/sessions`, `sessions` messages). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct SessionInfo { + pub id: String, + /// The name a user gave it. + pub name: Option, + /// The program's title, else the profile's name. + pub title: String, + pub kind: SessionKind, + /// The profile it started from (`shell`, `agent:claude`, `ssh:prod`), + /// absent for a custom command. + pub profile: Option, + /// That profile's name (`Claude Code`, `prod`). + pub profile_name: Option, + /// The custom command it runs, when it was started from one. + pub command: Option>, + /// The folder it was started in: with `profile` or `command`, enough to + /// start it again. + pub start_cwd: Option, + /// Agent id (`claude`, `codex`, …) for agent sessions. + pub agent: Option, + pub agent_state: Option, + /// The agent's last message when its turn finished. + pub last_message: Option, + pub cwd: Option, + pub cols: u16, + pub rows: u16, + pub created_at: i64, + /// Last output or input. + pub active_at: i64, + /// The last line of text on screen. + pub last_line: Option, + /// Set once the program exited. The session stays, with its final + /// screen, until it is killed. + pub exit: Option, + /// Approvals waiting for an answer. + pub pending_approvals: u32, +} + +/// A permission request an agent holds open until a client answers it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct Approval { + pub id: String, + pub session: String, + /// Tool name, as the agent reports it (`Bash`, `Edit`, `WebFetch`, …). + pub tool: String, + /// The tool's input as the agent sent it (for `Bash`: `command`, + /// `description`; for `Edit`: `file_path`, `old_string`, `new_string`). + pub input: serde_json::Value, + /// One line for lists and notifications: the command, the file, the URL. + pub summary: String, + /// What the agent says the call does (`tool_input.description`). + pub description: Option, + /// Permission rules the agent suggests (Claude Code's + /// `permission_suggestions`); `allow_always` applies them. Absent when + /// there are none, and then "always" is not offered. + pub permission_suggestions: Option, + pub created_at: i64, + /// After this the agent asks in its own terminal. + pub expires_at: i64, +} + +/// `POST /api/approvals/{id}` and the `approve` message. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct ApprovalAnswer { + pub decision: ApprovalDecision, + /// With `deny`: told to the agent as the reason. + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub message: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum ApprovalDecision { + Allow, + /// Allow, and apply the approval's `permission_suggestions` so the agent + /// does not ask again. + AllowAlways, + Deny, + /// No decision: the agent shows its own dialog in the terminal. + Terminal, +} + +/// How an approval ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum ApprovalOutcome { + Allowed, + Denied, + /// Left to the agent's own dialog: a client chose to answer in the + /// terminal, or the agent moved on because it was answered there. + Terminal, + TimedOut, + /// The session ended or was killed. + Gone, +} + +/// Something a session wants the user to notice (`event` messages). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct SessionEvent { + pub session: String, + pub kind: EventKind, + pub title: Option, + pub body: Option, + pub at: i64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum EventKind { + /// An agent asks for permission; an `approval_requested` message has it. + ApprovalRequested, + /// An agent waits for the user to type. + NeedsInput, + /// An agent finished its turn; `body` is its last message. + Finished, + /// The program asked for a desktop notification (OSC 9 / OSC 777). + Notification, + /// The program rang the bell. + Bell, + /// The program exited; `body` is the exit code. + Exited, +} diff --git a/crates/redshell-protocol/src/ws.rs b/crates/redshell-protocol/src/ws.rs new file mode 100644 index 0000000..47f8df2 --- /dev/null +++ b/crates/redshell-protocol/src/ws.rs @@ -0,0 +1,240 @@ +//! The WebSocket at `/api/ws`: one per client. +//! +//! Text frames carry JSON [`ClientMessage`]s and [`ServerMessage`]s, tagged +//! by `type`. Binary frames carry terminal bytes for an attached session: +//! a 2-byte big-endian channel number (from [`ServerMessage::Attached`]) +//! followed by the bytes ([`frame`], [`unframe`]). From the server they are +//! program output, to be written to the client's terminal as they come; +//! from a client they are input, like [`ClientMessage::Input`] but for bytes +//! that are not UTF-8. +//! +//! The server's terminal answers the program's queries (device attributes, +//! cursor position, colours), so a client must not forward the replies its +//! own emulator generates while it draws the output. + +use serde::{Deserialize, Serialize}; + +use crate::api::{ErrorCode, User}; +use crate::session::{Approval, ApprovalDecision, ApprovalOutcome, SessionEvent, SessionInfo}; + +/// Messages a client sends. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ClientMessage { + /// Starts streaming a session. The client's terminal is `cols` × `rows`; + /// the session takes that size once this client types into it. Answered + /// by `attached`, then binary output frames. + Attach { + session: String, + cols: u16, + rows: u16, + }, + Detach { + channel: u16, + }, + /// The client's terminal changed size. + Resize { + channel: u16, + cols: u16, + rows: u16, + }, + /// Keys or pasted text for the program, as the terminal encodes them. + Input { + channel: u16, + data: String, + }, + Rename { + session: String, + #[serde(default)] + name: Option, + }, + /// Chooses what is pushed besides attached sessions: the session list + /// (`sessions`, then `session_updated` / `session_removed`) and agent + /// activity (`approvals`, then `approval_requested` / `approval_resolved` + /// / `event`). Each call replaces the previous choice. + Subscribe { + sessions: bool, + events: bool, + }, + Approve { + approval: String, + decision: ApprovalDecision, + #[serde(default)] + message: Option, + }, +} + +/// Messages the server sends. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ServerMessage { + /// First message on every connection. + Hello { + protocol_version: u32, + user: User, + }, + /// Reply to `attach`. Reset the terminal, size it to the snapshot and + /// write `snapshot.data`; binary frames on `channel` follow. + Attached { + channel: u16, + session: SessionInfo, + snapshot: Snapshot, + }, + /// The client fell behind and output was dropped: reset the terminal + /// and redraw it from this snapshot, as after `attached`. + Snapshot { + channel: u16, + snapshot: Snapshot, + }, + /// The session's size changed (another client typed, or a resize). + Resized { + channel: u16, + cols: u16, + rows: u16, + }, + /// The channel is closed: the session was killed, or on `detach`. + Detached { + channel: u16, + }, + Sessions { + sessions: Vec, + }, + SessionUpdated { + session: SessionInfo, + }, + SessionRemoved { + id: String, + }, + /// Approvals waiting when the client subscribed to events. + Approvals { + approvals: Vec, + }, + ApprovalRequested { + approval: Approval, + }, + ApprovalResolved { + id: String, + session: String, + outcome: ApprovalOutcome, + /// Who answered: a device's name, a browser's name (`Safari on + /// iPhone`), or `terminal` when the agent went on after an answer in + /// its own dialog. `null` when it timed out or the session ended. + answered_by: Option, + }, + Event { + event: SessionEvent, + }, + /// A message could not be carried out. + Error { + code: ErrorCode, + message: String, + }, +} + +/// A session's screen for a client that joins: see `redshell-terminal`'s +/// replay. `data` redraws the scrollback and screen in a terminal reset to +/// `cols` × `rows`, and sets the modes listed in `modes` as it goes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct Snapshot { + pub cols: u16, + pub rows: u16, + pub data: String, + pub modes: Modes, +} + +/// Terminal modes a client needs to encode input and draw the screen. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct Modes { + pub alt_screen: bool, + pub app_cursor: bool, + pub app_keypad: bool, + pub bracketed_paste: bool, + /// Mouse events the program wants, `null` when it does not track it. + pub mouse_tracking: Option, + pub mouse_encoding: MouseEncoding, + pub focus_reporting: bool, + pub cursor_visible: bool, + pub cursor_shape: CursorShape, + pub cursor_blinking: bool, + pub title: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum MouseTracking { + /// DECSET 1000: presses and releases. + Click, + /// DECSET 1002: also motion with a button held. + Drag, + /// DECSET 1003: all motion. + Motion, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum MouseEncoding { + Normal, + /// DECSET 1005. + Utf8, + /// DECSET 1006. + Sgr, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum CursorShape { + Block, + Bar, + Underline, + Hollow, + Hidden, +} + +/// A binary frame: `channel` as 2 big-endian bytes, then `bytes`. +pub fn frame(channel: u16, bytes: &[u8]) -> Vec { + let mut out = Vec::with_capacity(bytes.len() + 2); + out.extend_from_slice(&channel.to_be_bytes()); + out.extend_from_slice(bytes); + out +} + +/// The channel and bytes of a binary frame; `None` when it is too short. +pub fn unframe(frame: &[u8]) -> Option<(u16, &[u8])> { + let (channel, bytes) = frame.split_first_chunk::<2>()?; + Some((u16::from_be_bytes(*channel), bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frames_round_trip() { + let f = frame(0x0102, b"hi"); + assert_eq!(f, [1, 2, b'h', b'i']); + assert_eq!(unframe(&f), Some((0x0102, &b"hi"[..]))); + assert_eq!(unframe(&[7]), None); + assert_eq!(unframe(&[0, 7]), Some((7, &b""[..]))); + } + + #[test] + fn messages_are_tagged_snake_case() { + let msg: ClientMessage = + serde_json::from_str(r#"{"type":"attach","session":"s1","cols":80,"rows":24}"#).unwrap(); + assert_eq!(msg, ClientMessage::Attach { session: "s1".into(), cols: 80, rows: 24 }); + let approve = r#"{"type":"approve","approval":"a","decision":"terminal","message":null}"#; + assert!(matches!( + serde_json::from_str(approve).unwrap(), + ClientMessage::Approve { decision: ApprovalDecision::Terminal, .. } + )); + let out = serde_json::to_string(&ServerMessage::Detached { channel: 3 }).unwrap(); + assert_eq!(out, r#"{"type":"detached","channel":3}"#); + } +} diff --git a/crates/redshell-remote/src/location.rs b/crates/redshell-remote/src/location.rs index 6393259..f9ae89c 100644 --- a/crates/redshell-remote/src/location.rs +++ b/crates/redshell-remote/src/location.rs @@ -25,6 +25,8 @@ impl MuxTarget { } match profile.kind { LaunchKind::Ssh => Self::from_id_part(&profile.id, settings, ssh), + // It runs on a RedShell server, which is none of these places. + LaunchKind::Remote => None, LaunchKind::Shell if is_wsl(&profile.command.program) => { Some(Self::Wsl { distribution: wsl_distribution(&profile.command.args) }) } diff --git a/crates/redshell-remote/src/ssh.rs b/crates/redshell-remote/src/ssh.rs index ca7e427..f65360a 100644 --- a/crates/redshell-remote/src/ssh.rs +++ b/crates/redshell-remote/src/ssh.rs @@ -39,6 +39,9 @@ pub struct SshProfile { pub origin: HostOrigin, /// The HostName `~/.ssh/config` gives an alias host without an address. pub config_hostname: Option, + /// `ssh.ssh_config_path`: the config file ssh reads instead of + /// `~/.ssh/config` (`-F`), so the aliases listed from it also resolve. + pub config_file: Option, /// Answers ssh's prompts when `ssh.askpass` is on. pub askpass: Option, } @@ -54,6 +57,9 @@ impl SshProfile { fn base_args(&self, options: &[&str]) -> Vec { let h = &self.host; let mut args = Vec::new(); + if let Some(file) = &self.config_file { + args.extend(["-F".into(), file.display().to_string()]); + } let explicit = self.origin != HostOrigin::Imported; if let Some(port) = h.port.filter(|_| explicit) { args.extend(["-p".into(), port.to_string()]); @@ -340,6 +346,7 @@ impl SshProvider { program: settings.program.clone(), keep_alive_secs: settings.keep_alive_secs, origin, + config_file: settings.ssh_config_path.clone(), ..Default::default() }; let mut profiles: Vec = settings @@ -446,6 +453,8 @@ mod tests { assert_eq!(origin("box"), HostOrigin::Alias); assert_eq!(origin("web"), HostOrigin::Settings); assert_eq!(origin("other"), HostOrigin::Imported); + let config_file = settings.ssh_config_path.as_ref().unwrap().display().to_string(); + assert_eq!(provider.find("other").unwrap().base_args(&[])[..2], ["-F".to_owned(), config_file]); assert_eq!(provider.hosts().len(), 3); assert_eq!(provider.find("box").unwrap().askpass_target().address, "10.0.0.5"); } diff --git a/crates/redshell-remote/src/tmux_control.rs b/crates/redshell-remote/src/tmux_control.rs index ccbe4ef..ffb74df 100644 --- a/crates/redshell-remote/src/tmux_control.rs +++ b/crates/redshell-remote/src/tmux_control.rs @@ -778,8 +778,11 @@ impl ControlClient { } } - /// Sets the size tmux uses for `window` on this client (tmux ≥ 3.2). + /// Sets the size tmux uses for `window` on this client. The client's own + /// size is set too: tmux 3.2 ignores the per-window form and sizes every + /// window from the client, newer ones give `window` its own size. pub fn resize_window(&self, window: u32, cols: u16, rows: u16) { + self.resize_client(cols, rows); self.execute(&format!("refresh-client -C @{window}:{cols}x{rows}")); } diff --git a/crates/redshell-remote/src/tunnel.rs b/crates/redshell-remote/src/tunnel.rs index ef819f4..d403699 100644 --- a/crates/redshell-remote/src/tunnel.rs +++ b/crates/redshell-remote/src/tunnel.rs @@ -340,23 +340,30 @@ mod tests { use super::*; /// A host whose "ssh" runs `script` (from `dir`) with sh. The one - /// fake ssh, shared by every test, runs the script its destination - /// names: an executable written while another test forks can't be - /// run until that child has exec'd ("Text file busy"). + /// fake ssh, shared by every test and every run, runs the script its + /// destination names: an executable written while another test forks + /// can't be run until that child has exec'd ("Text file busy"). It + /// lives at a fixed path in the temp folder, so runs leave no new + /// folders behind, and is replaced by a rename, never rewritten. pub fn ssh(dir: &Path, script: &str) -> SshProfile { - static PROGRAM: std::sync::OnceLock<(tempfile::TempDir, String)> = std::sync::OnceLock::new(); - let (_, program) = PROGRAM.get_or_init(|| { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("ssh"); - let dispatch = "#!/bin/sh\n[ \"$1\" = -V ] && exit 0\nfor last; do :; done\nexec sh \"$last\"\n"; - std::fs::write(&path, dispatch).unwrap(); - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + static PROGRAM: std::sync::OnceLock = std::sync::OnceLock::new(); + let program = PROGRAM.get_or_init(|| { + const DISPATCH: &str = + "#!/bin/sh\n[ \"$1\" = -V ] && exit 0\nfor last; do :; done\nexec sh \"$last\"\n"; + let folder = std::env::temp_dir().join("redshell-test-fake-ssh"); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("ssh"); + if std::fs::read_to_string(&path).ok().as_deref() != Some(DISPATCH) { + let staged = folder.join(format!("ssh.{}", std::process::id())); + std::fs::write(&staged, DISPATCH).unwrap(); + std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::rename(&staged, &path).unwrap(); + } let runnable = || std::process::Command::new(&path).arg("-V").status().is_ok(); while !runnable() { std::thread::sleep(Duration::from_millis(10)); } - let program = path.display().to_string(); - (dir, program) + path.display().to_string() }); let path = dir.join("script.sh"); std::fs::write(&path, script).unwrap(); diff --git a/crates/redshell-server/Cargo.toml b/crates/redshell-server/Cargo.toml new file mode 100644 index 0000000..6d1ac26 --- /dev/null +++ b/crates/redshell-server/Cargo.toml @@ -0,0 +1,69 @@ +[package] +name = "redshell-server" +description = "Headless RedShell: server-owned terminal sessions for the desktop and the RedShell Remote PWA." +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[[bin]] +name = "redshell-server" +path = "src/main.rs" + +[dependencies] +redshell-core.workspace = true +redshell-terminal.workspace = true +redshell-agents.workspace = true +redshell-remote.workspace = true +redshell-protocol.workspace = true +rusqlite.workspace = true +serde.workspace = true +serde_json.workspace = true +toml.workspace = true +anyhow.workspace = true +thiserror.workspace = true +parking_lot.workspace = true +crossbeam-channel.workspace = true +log.workspace = true +env_logger.workspace = true +dirs.workspace = true +uuid.workspace = true + +axum = { version = "0.8", features = ["ws"] } +# TLS through rustls with ring: no OpenSSL and no C toolchain for cross builds. +axum-server = { version = "0.9", features = ["tls-rustls-ring"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "sync", "time"] } +tower-http = { version = "0.6", features = ["set-header"] } +hyper = { version = "1", features = ["client", "http1"] } +hyper-util = { version = "0.1", features = ["tokio"] } +http-body-util = "0.1" +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } +rust-embed = { version = "8", features = ["debug-embed", "interpolate-folder-path", "mime-guess"] } +argon2 = "0.5" +rand_core = { version = "0.6", features = ["getrandom"] } +sha2 = "0.10" +hmac = "0.12" +base64 = "0.22" +clap = { version = "4", features = ["derive", "env"] } +rpassword = "7" +# Passkeys (WebAuthn) on RustCrypto: no OpenSSL. +# State serialisation: sign-in ceremonies travel with the client, signed, so starting one stores nothing. +webauthn-rs = { version = "0.6", features = ["conditional-ui", "danger-allow-state-serialisation"] } +webauthn-rs-proto = "0.6" +# Web Push: RFC 8291 encryption and VAPID in pure Rust. +web-push-native = "0.5" +# Push delivery over rustls with ring. +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] } +url = "2" + +[target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies] +libc = "0.2" + +[dev-dependencies] +tempfile.workspace = true +reqwest = { version = "0.12", default-features = false, features = ["json"] } +tokio-tungstenite = "0.29" +# A software passkey for the WebAuthn tests (RustCrypto too). +webauthn-authenticator-rs = { version = "0.6", features = ["softpasskey"] } diff --git a/crates/redshell-server/build.rs b/crates/redshell-server/build.rs new file mode 100644 index 0000000..7f64733 --- /dev/null +++ b/crates/redshell-server/build.rs @@ -0,0 +1,21 @@ +//! Picks the folder the PWA is embedded from: `web/dist` when it has been +//! built (`npm ci && npm run build` in `web/`), else a placeholder page +//! that says so, so `cargo build` works without Node. +//! +//! Cargo reruns a build script whose watched path is missing on every +//! build, so a missing `web/dist` is not watched: after the first PWA build, +//! `cargo clean -p redshell-server` makes the server pick it up. Changes to +//! an existing `web/dist` are picked up by themselves. + +use std::path::PathBuf; + +fn main() { + let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo")); + let dist = manifest.join("../../web/dist"); + let placeholder = manifest.join("placeholder"); + let built = dist.join("index.html").is_file(); + let folder = if built { &dist } else { &placeholder }; + println!("cargo:rustc-env=REDSHELL_WEB_DIST={}", folder.display()); + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed={}", folder.display()); +} diff --git a/crates/redshell-server/placeholder/index.html b/crates/redshell-server/placeholder/index.html new file mode 100644 index 0000000..6384e0e --- /dev/null +++ b/crates/redshell-server/placeholder/index.html @@ -0,0 +1,14 @@ + + + + + +RedShell Server + + +

RedShell Server is running

+

This build has no RedShell Remote app inside. Build it in web/ with +npm ci && npm run build, then build redshell-server again.

+

The API under /api works as usual.

+ + diff --git a/crates/redshell-server/src/agents/approvals.rs b/crates/redshell-server/src/agents/approvals.rs new file mode 100644 index 0000000..45e0bed --- /dev/null +++ b/crates/redshell-server/src/agents/approvals.rs @@ -0,0 +1,185 @@ +//! Permission requests held open until someone answers. +//! +//! An agent's PermissionRequest hook waits on a [`Approvals::open`] +//! receiver. The first answer wins: a client (allow, deny, answer in the +//! terminal), the agent moving on after an answer in its own dialog, the +//! timeout, or the session ending. Answering something already settled +//! does nothing. + +use std::collections::HashMap; + +use parking_lot::Mutex; +use redshell_protocol::{Approval, ApprovalDecision, ApprovalOutcome}; +use serde_json::Value; +use tokio::sync::oneshot; + +use crate::bus::{Bus, BusEvent}; + +/// A client's answer, handed to the waiting hook. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Answer { + pub decision: ApprovalDecision, + pub message: Option, +} + +struct Pending { + approval: Approval, + reply: oneshot::Sender, +} + +pub struct Approvals { + pending: Mutex>, + bus: Bus, +} + +impl Approvals { + pub fn new(bus: Bus) -> Self { + Self { pending: Mutex::new(HashMap::new()), bus } + } + + /// Registers `approval` and tells the clients. The receiver gets the + /// answer, or an error when it was settled without one. + pub fn open(&self, approval: Approval) -> oneshot::Receiver { + let (reply, rx) = oneshot::channel(); + self.pending.lock().insert(approval.id.clone(), Pending { approval: approval.clone(), reply }); + self.bus.send(BusEvent::ApprovalRequested(approval)); + rx + } + + /// A client answers; `None` when the approval is no longer pending. + pub fn answer(&self, id: &str, answer: Answer, by: &str) -> Option { + let pending = self.pending.lock().remove(id)?; + let outcome = match answer.decision { + ApprovalDecision::Allow | ApprovalDecision::AllowAlways => ApprovalOutcome::Allowed, + ApprovalDecision::Deny => ApprovalOutcome::Denied, + ApprovalDecision::Terminal => ApprovalOutcome::Terminal, + }; + let _ = pending.reply.send(answer); + self.resolved(&pending.approval, outcome, Some(by)); + Some(pending.approval) + } + + /// Settles one approval without an answer (it timed out). + pub fn settle(&self, id: &str, outcome: ApprovalOutcome) { + if let Some(pending) = self.pending.lock().remove(id) { + self.resolved(&pending.approval, outcome, None); + } + } + + /// Settles every approval of `session` without an answer: the agent + /// moved on (`by` = `terminal`) or the session ended. + pub fn settle_session(&self, session: &str, outcome: ApprovalOutcome, by: Option<&str>) { + self.settle_where(session, |_| true, outcome, by); + } + + /// Settles the approvals of `session` for a call of `tool` with `input`, + /// answered in the agent's own dialog: the agent ran or tried that call. + /// Inputs match as JSON values, whatever the order of their keys. + pub fn settle_call(&self, session: &str, tool: &str, input: &Value, by: &str) { + let same_call = |a: &Approval| a.tool == tool && a.input == *input; + self.settle_where(session, same_call, ApprovalOutcome::Terminal, Some(by)); + } + + fn settle_where( + &self, + session: &str, + settles: impl Fn(&Approval) -> bool, + outcome: ApprovalOutcome, + by: Option<&str>, + ) { + let settled: Vec = { + let mut pending = self.pending.lock(); + let ids: Vec = pending + .values() + .filter(|p| p.approval.session == session && settles(&p.approval)) + .map(|p| p.approval.id.clone()) + .collect(); + ids.iter().filter_map(|id| pending.remove(id)).collect() + }; + for p in settled { + self.resolved(&p.approval, outcome, by); + } + } + + fn resolved(&self, approval: &Approval, outcome: ApprovalOutcome, by: Option<&str>) { + self.bus.send(BusEvent::ApprovalResolved { + id: approval.id.clone(), + session: approval.session.clone(), + outcome, + answered_by: by.map(str::to_owned), + }); + } + + pub fn pending(&self) -> Vec { + let mut list: Vec = self.pending.lock().values().map(|p| p.approval.clone()).collect(); + list.sort_by_key(|a| a.created_at); + list + } + + pub fn count(&self, session: &str) -> u32 { + self.pending.lock().values().filter(|p| p.approval.session == session).count() as u32 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn approval(id: &str, session: &str) -> Approval { + Approval { + id: id.into(), + session: session.into(), + tool: "Bash".into(), + input: serde_json::json!({"command": "ls"}), + summary: "ls".into(), + description: None, + permission_suggestions: None, + created_at: 0, + expires_at: 1, + } + } + + #[tokio::test] + async fn first_answer_wins() { + let bus = Bus::default(); + let mut events = bus.subscribe(); + let approvals = Approvals::new(bus); + let rx = approvals.open(approval("a", "s")); + assert_eq!(approvals.count("s"), 1); + let allow = Answer { decision: ApprovalDecision::Allow, message: None }; + assert!(approvals.answer("a", allow.clone(), "phone").is_some()); + assert!(approvals.answer("a", allow.clone(), "laptop").is_none(), "already answered"); + assert_eq!(rx.await.unwrap(), allow); + assert!(matches!(events.recv().await.unwrap(), BusEvent::ApprovalRequested(_))); + assert!(matches!( + events.recv().await.unwrap(), + BusEvent::ApprovalResolved { outcome: ApprovalOutcome::Allowed, answered_by: Some(by), .. } if by == "phone" + )); + } + + #[test] + fn a_finished_call_settles_only_its_own_approval() { + let approvals = Approvals::new(Bus::default()); + let call = |id: &str, input: Value| Approval { input, ..approval(id, "s") }; + let _a = approvals.open(call("a", serde_json::json!({"command": "ls", "description": "List"}))); + let _b = approvals.open(call("b", serde_json::json!({"command": "rm x"}))); + approvals.settle_call("s", "Bash", &serde_json::json!({"command": "pwd"}), "terminal"); + approvals.settle_call("other", "Bash", &serde_json::json!({"description": "List", "command": "ls"}), "t"); + assert_eq!(approvals.count("s"), 2, "another call, or another session"); + approvals.settle_call("s", "Bash", &serde_json::json!({"description": "List", "command": "ls"}), "terminal"); + assert_eq!(approvals.pending().iter().map(|a| a.id.as_str()).collect::>(), ["b"]); + } + + #[tokio::test] + async fn settling_a_session_leaves_the_hook_without_a_decision() { + let approvals = Approvals::new(Bus::default()); + let a = approvals.open(approval("a", "s")); + let b = approvals.open(approval("b", "other")); + approvals.settle_session("s", ApprovalOutcome::Terminal, Some("terminal")); + assert!(a.await.is_err()); + assert_eq!(approvals.pending().len(), 1); + approvals.settle("b", ApprovalOutcome::TimedOut); + assert!(b.await.is_err()); + assert!(approvals.pending().is_empty()); + } +} diff --git a/crates/redshell-server/src/agents/claude.rs b/crates/redshell-server/src/agents/claude.rs new file mode 100644 index 0000000..ac6fab3 --- /dev/null +++ b/crates/redshell-server/src/agents/claude.rs @@ -0,0 +1,217 @@ +//! Claude Code: the settings that add our HTTP hooks, and what each hook +//! means for the session. +//! +//! Hook input and output follow . +//! A PermissionRequest is held until a client answers; Claude shows its own +//! dialog at the same time, and whichever answer comes first wins. When +//! the user answers in the terminal Claude leaves our request open, so a +//! later hook settles it as answered in the terminal: PostToolUse and +//! PostToolUseFailure the request for that very call (same tool, same +//! input), UserPromptSubmit and Stop every request of the session. Another +//! PermissionRequest settles nothing (Claude asks for parallel calls one +//! after another), and neither does Notification: Claude sends one for a +//! waiting prompt about six seconds in. + +use std::time::Duration; + +use redshell_protocol::{Approval, ApprovalDecision}; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::Answer; + +/// The tool name of a hook that names none. +const TOOL: &str = "tool"; + +/// Hook events we subscribe to. +const EVENTS: [&str; 6] = + ["PermissionRequest", "PostToolUse", "PostToolUseFailure", "Notification", "Stop", "UserPromptSubmit"]; + +/// The `--settings` file: one HTTP hook per event, all to `url`. The +/// permission hook outlives our own timeout, so we answer first. +pub fn settings(url: &str, approval_timeout: Duration) -> String { + let hooks: serde_json::Map = EVENTS + .iter() + .map(|event| { + let timeout = if *event == "PermissionRequest" { approval_timeout.as_secs() + 30 } else { 10 }; + (event.to_string(), json!([{ "hooks": [{ "type": "http", "url": url, "timeout": timeout }] }])) + }) + .collect(); + json!({ "hooks": hooks }).to_string() +} + +/// The fields of a hook's input that we use. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct HookInput { + pub hook_event_name: String, + pub tool_name: Option, + pub tool_input: Option, + pub permission_suggestions: Option, + pub notification_type: Option, + pub title: Option, + pub message: Option, + pub last_assistant_message: Option, +} + +/// What a hook event does to the session. +#[derive(Debug, PartialEq)] +pub enum Effect { + /// Hold the request open for an approval. + Ask, + /// A tool call ran or failed: settle its approval, back to work. + ToolDone { + tool: String, + input: Value, + }, + /// The user sent a prompt: settle every approval, back to work. + PromptSubmitted, + /// A turn ended with this message; every approval is settled. + Finished(Option), + /// The agent waits for the user to type. + NeedsInput(Option), + /// Just tell the clients. + Notify { + title: Option, + body: Option, + }, + Nothing, +} + +impl HookInput { + pub fn effect(&self) -> Effect { + match self.hook_event_name.as_str() { + "PermissionRequest" => Effect::Ask, + "PostToolUse" | "PostToolUseFailure" => Effect::ToolDone { + tool: self.tool_name.clone().unwrap_or_else(|| TOOL.into()), + input: self.tool_input.clone().unwrap_or(Value::Null), + }, + "UserPromptSubmit" => Effect::PromptSubmitted, + "Stop" => Effect::Finished(self.last_assistant_message.clone()), + "Notification" => match self.notification_type.as_deref() { + // Already shown as an approval; and a minute after a finished + // turn, which Stop reported. + Some("permission_prompt" | "idle_prompt") => Effect::Nothing, + Some("elicitation_dialog" | "elicitation_url_dialog" | "agent_needs_input") => { + Effect::NeedsInput(self.message.clone()) + } + _ => Effect::Notify { title: self.title.clone(), body: self.message.clone() }, + }, + _ => Effect::Nothing, + } + } + + /// The approval this PermissionRequest asks for. + pub fn approval(&self, id: String, session: String, now: i64, timeout: Duration) -> Approval { + let input = self.tool_input.clone().unwrap_or(Value::Null); + let tool = self.tool_name.clone().unwrap_or_else(|| TOOL.into()); + let text = |key: &str| input.get(key).and_then(Value::as_str).map(str::to_owned); + let summary = ["command", "file_path", "url", "pattern", "path", "query", "prompt"] + .iter() + .find_map(|key| text(key)) + .unwrap_or_else(|| tool.clone()); + let suggestions = self.permission_suggestions.clone().filter(|s| s.as_array().is_some_and(|a| !a.is_empty())); + Approval { + id, + session, + summary: summary.chars().take(300).collect(), + description: text("description"), + permission_suggestions: suggestions, + tool, + input, + created_at: now, + expires_at: now + timeout.as_millis() as i64, + } + } +} + +/// The hook's reply for an answer; `None` is no decision (an empty body), +/// which lets Claude ask in its own dialog. +pub fn decision(answer: Option<&Answer>, approval: &Approval) -> Option { + let decision = match answer?.decision { + ApprovalDecision::Allow => json!({ "behavior": "allow" }), + ApprovalDecision::AllowAlways => match &approval.permission_suggestions { + Some(rules) => json!({ "behavior": "allow", "updatedPermissions": rules }), + None => json!({ "behavior": "allow" }), + }, + ApprovalDecision::Deny => { + let message = answer?.message.clone().unwrap_or_else(|| "The user denied this in RedShell.".into()); + json!({ "behavior": "deny", "message": message }) + } + ApprovalDecision::Terminal => return None, + }; + Some(json!({ "hookSpecificOutput": { "hookEventName": "PermissionRequest", "decision": decision } })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn input(json: Value) -> HookInput { + serde_json::from_value(json).unwrap() + } + + #[test] + fn settings_hook_every_event_with_a_long_permission_timeout() { + let s: Value = + serde_json::from_str(&settings("http://127.0.0.1:9/claude/s/t", Duration::from_secs(600))).unwrap(); + for event in EVENTS { + assert_eq!(s["hooks"][event][0]["hooks"][0]["url"], "http://127.0.0.1:9/claude/s/t"); + assert_eq!(s["hooks"][event][0]["hooks"][0]["type"], "http"); + } + assert_eq!(s["hooks"]["PermissionRequest"][0]["hooks"][0]["timeout"], 630); + } + + #[test] + fn events_map_to_effects() { + let effect = |json: Value| input(json).effect(); + assert_eq!(effect(json!({"hook_event_name": "PermissionRequest"})), Effect::Ask); + assert_eq!( + effect( + json!({"hook_event_name": "PostToolUseFailure", "tool_name": "Bash", "tool_input": {"command": "x"}}) + ), + Effect::ToolDone { tool: "Bash".into(), input: json!({"command": "x"}) } + ); + assert_eq!(effect(json!({"hook_event_name": "UserPromptSubmit"})), Effect::PromptSubmitted); + assert_eq!( + effect(json!({"hook_event_name": "Stop", "last_assistant_message": "Done."})), + Effect::Finished(Some("Done.".into())) + ); + assert_eq!( + effect(json!({"hook_event_name": "Notification", "notification_type": "permission_prompt"})), + Effect::Nothing + ); + assert_eq!( + effect(json!({"hook_event_name": "Notification", "notification_type": "idle_prompt"})), + Effect::Nothing + ); + assert_eq!( + effect( + json!({"hook_event_name": "Notification", "notification_type": "elicitation_dialog", "message": "Pick"}) + ), + Effect::NeedsInput(Some("Pick".into())) + ); + } + + #[test] + fn approvals_and_decisions() { + let request = input(json!({ + "hook_event_name": "PermissionRequest", + "tool_name": "Bash", + "tool_input": {"command": "rm -rf node_modules", "description": "Remove node_modules"}, + "permission_suggestions": [{"type": "addRules", "rules": [{"toolName": "Bash"}], "behavior": "allow"}] + })); + let approval = request.approval("a".into(), "s".into(), 1000, Duration::from_secs(600)); + assert_eq!((approval.summary.as_str(), approval.expires_at), ("rm -rf node_modules", 601_000)); + assert_eq!(approval.description.as_deref(), Some("Remove node_modules")); + let answer = |decision| Answer { decision, message: None }; + let allow = decision(Some(&answer(ApprovalDecision::Allow)), &approval).unwrap(); + assert_eq!(allow["hookSpecificOutput"]["decision"], json!({"behavior": "allow"})); + let always = decision(Some(&answer(ApprovalDecision::AllowAlways)), &approval).unwrap(); + assert_eq!(always["hookSpecificOutput"]["decision"]["updatedPermissions"][0]["type"], "addRules"); + let deny = decision(Some(&answer(ApprovalDecision::Deny)), &approval).unwrap(); + assert_eq!(deny["hookSpecificOutput"]["decision"]["behavior"], "deny"); + assert_eq!(decision(Some(&answer(ApprovalDecision::Terminal)), &approval), None); + assert_eq!(decision(None, &approval), None); + } +} diff --git a/crates/redshell-server/src/agents/codex.rs b/crates/redshell-server/src/agents/codex.rs new file mode 100644 index 0000000..b1f85db --- /dev/null +++ b/crates/redshell-server/src/agents/codex.rs @@ -0,0 +1,129 @@ +//! Codex: its `notify` program reports finished turns. +//! +//! Codex runs the `notify` command after each turn with one more argument, +//! a JSON object such as `{"type": "agent-turn-complete", +//! "last-assistant-message": "…", "cwd": "…", …}`. The command is +//! `redshell-server hook codex`, which posts that JSON to the URL in +//! [`URL_ENV`]. The URL (with its token) travels in the environment rather +//! than on the command line, which every user of the machine can read. +//! +//! `-c notify=…` replaces the `notify` the user set in Codex's own +//! `config.toml`, so the hook runs that program afterwards, as Codex would +//! have. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context as _, ensure}; +use axum::body::Bytes; +use http_body_util::Full; +use hyper::header::{CONTENT_TYPE, HOST}; +use serde::Deserialize; + +/// Environment variable with the session's hook URL. +pub const URL_ENV: &str = "REDSHELL_HOOK_URL"; + +/// The `-c` override: `notify=["", "hook", "codex"]`. A JSON +/// array of strings is valid TOML, which is how Codex parses `-c` values. +pub fn notify_override(exe: &Path) -> String { + let argv = [exe.display().to_string(), "hook".into(), "codex".into()]; + format!("notify={}", serde_json::to_string(&argv).unwrap_or_default()) +} + +/// The notify payload fields we use. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct Notify { + #[serde(rename = "type")] + pub kind: String, + #[serde(rename = "last-assistant-message")] + pub last_assistant_message: Option, +} + +impl Notify { + pub fn turn_complete(&self) -> bool { + self.kind == "agent-turn-complete" + } +} + +/// `redshell-server hook codex `: posts the payload to the hook +/// listener at `url` (from [`URL_ENV`]), then runs the user's own `notify` +/// program with it. A failed post is reported after that program ran. +pub async fn hook(url: Option, payload: String) -> anyhow::Result<()> { + let posted = match url { + Some(url) => post_notify(&url, payload.clone()).await, + None => Err(anyhow::anyhow!("{URL_ENV} is not set: run by Codex inside a server session")), + }; + let home = std::env::var_os("CODEX_HOME").map(PathBuf::from); + if let Some(argv) = user_notify(home, dirs::home_dir()) { + let (program, args) = argv.split_first().context("empty notify")?; + let status = std::process::Command::new(program).args(args).arg(&payload).env_remove(URL_ENV).status(); + match status { + Ok(status) if !status.success() => log::warn!("your Codex notify program ({program}) exited with {status}"), + Ok(_) => {} + Err(err) => log::warn!("running your Codex notify program ({program}): {err}"), + } + } + posted +} + +/// The `notify` program set in Codex's `config.toml` (in `codex_home`, +/// else `~/.codex`), unless it is this hook itself. +pub fn user_notify(codex_home: Option, home: Option) -> Option> { + let dir = codex_home.or_else(|| home.map(|h| h.join(".codex")))?; + let text = std::fs::read_to_string(dir.join("config.toml")).ok()?; + let config: toml::Table = toml::from_str(&text).ok()?; + let argv: Vec = + config.get("notify")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::>()?; + let ours = argv.get(1..).is_some_and(|rest| rest == ["hook", "codex"]); + (!argv.is_empty() && !ours).then_some(argv) +} + +/// Posts a notify payload to the hook listener at `url`. +pub async fn post_notify(url: &str, payload: String) -> anyhow::Result<()> { + let uri: hyper::Uri = url.parse().with_context(|| format!("{URL_ENV} is not a URL"))?; + let authority = uri.authority().context("the hook URL has no host")?.as_str().to_owned(); + let stream = tokio::net::TcpStream::connect(&authority).await.context("connecting to redshell-server")?; + let (mut sender, connection) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?; + tokio::spawn(connection); + let request = hyper::Request::post(uri.path()) + .header(HOST, authority) + .header(CONTENT_TYPE, "application/json") + .body(Full::new(Bytes::from(payload)))?; + let response = sender.send_request(request).await?; + ensure!(response.status().is_success(), "redshell-server answered {}", response.status()); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn override_is_a_toml_array() { + let value = notify_override(Path::new("/opt/redshell server/bin")); + let parsed: toml::Table = toml::from_str(&value).unwrap(); + assert_eq!(parsed["notify"].as_array().unwrap()[0].as_str(), Some("/opt/redshell server/bin")); + let notify: Notify = + serde_json::from_str(r#"{"type":"agent-turn-complete","last-assistant-message":"Done","thread-id":"t"}"#) + .unwrap(); + assert!(notify.turn_complete()); + assert_eq!(notify.last_assistant_message.as_deref(), Some("Done")); + } + + #[test] + fn the_users_notify_is_found_where_codex_looks() { + let dir = tempfile::tempdir().unwrap(); + let (codex_home, home) = (dir.path().join("codex"), dir.path().join("home")); + for folder in [&codex_home, &home.join(".codex")] { + std::fs::create_dir_all(folder).unwrap(); + } + std::fs::write(home.join(".codex/config.toml"), "notify = [\"notify-send\", \"Codex\"]\n").unwrap(); + assert_eq!(user_notify(None, Some(home.clone())), Some(vec!["notify-send".into(), "Codex".into()])); + assert_eq!(user_notify(Some(codex_home.clone()), Some(home.clone())), None, "CODEX_HOME wins"); + std::fs::write(codex_home.join("config.toml"), "notify = [\"/opt/redshell-server\", \"hook\", \"codex\"]\n") + .unwrap(); + assert_eq!(user_notify(Some(codex_home.clone()), None), None, "never itself"); + std::fs::write(codex_home.join("config.toml"), "model = \"o3\"\n").unwrap(); + assert_eq!(user_notify(Some(codex_home), None), None); + } +} diff --git a/crates/redshell-server/src/agents/hooks.rs b/crates/redshell-server/src/agents/hooks.rs new file mode 100644 index 0000000..e6383ff --- /dev/null +++ b/crates/redshell-server/src/agents/hooks.rs @@ -0,0 +1,145 @@ +//! The loopback listener agent hooks post to. +//! +//! Routes: `POST /claude/{session}/{token}` and `POST /codex/{session}/{token}`. +//! An unknown session and a wrong token get the same 404, before the body +//! is read; a body is at most [`MAX_BODY`]. + +use std::sync::Arc; + +use axum::Json; +use axum::Router; +use axum::extract::{DefaultBodyLimit, FromRequestParts, Path, State}; +use axum::http::StatusCode; +use axum::http::request::Parts; +use axum::response::{IntoResponse, Response}; +use axum::routing::post; +use redshell_protocol::{AgentState, ApprovalOutcome, EventKind}; + +use super::claude::{self, Effect, HookInput}; +use super::codex::Notify; +use crate::now_ms; +use crate::sessions::{Ctx, Session, Sessions}; + +/// Who settles an approval the agent moved on from. +const IN_TERMINAL: &str = "terminal"; +/// Largest hook body. PostToolUse carries the tool's whole response; a +/// bigger one is refused, and the approval it would settle is settled by +/// the agent's next prompt or stop instead. +const MAX_BODY: usize = 1 << 20; + +pub fn router(sessions: Arc) -> Router { + Router::new() + .route("/claude/{session}/{token}", post(claude_hook)) + .route("/codex/{session}/{token}", post(codex_hook)) + .layer(DefaultBodyLimit::max(MAX_BODY)) + .with_state(sessions) +} + +/// The session a hook URL names, with its token checked. Extracted from the +/// path alone, ahead of the body, so a wrong token never gets its body read. +struct HookSession(Arc); + +impl FromRequestParts> for HookSession { + type Rejection = StatusCode; + + async fn from_request_parts(parts: &mut Parts, sessions: &Arc) -> Result { + let Path((id, token)) = + Path::<(String, String)>::from_request_parts(parts, sessions).await.map_err(|_| StatusCode::NOT_FOUND)?; + let session = sessions.get(&id).filter(|s| s.hook_token_matches(&token)).ok_or(StatusCode::NOT_FOUND)?; + Ok(Self(session)) + } +} + +async fn claude_hook( + State(sessions): State>, + HookSession(session): HookSession, + Json(input): Json, +) -> Response { + let id = session.id.clone(); + let ctx = sessions.ctx().clone(); + // Requests answered in Claude's own dialog stay open on our side: the agent moving on settles them. + match input.effect() { + Effect::Ask => return ask(&ctx, &session, &input).await, + Effect::ToolDone { tool, input } => { + ctx.approvals.settle_call(&id, &tool, &input, IN_TERMINAL); + working(&ctx, &session); + } + Effect::PromptSubmitted => { + ctx.approvals.settle_session(&id, ApprovalOutcome::Terminal, Some(IN_TERMINAL)); + working(&ctx, &session); + } + Effect::Finished(message) => { + ctx.approvals.settle_session(&id, ApprovalOutcome::Terminal, Some(IN_TERMINAL)); + finished(&ctx, &session, message); + } + Effect::NeedsInput(message) => { + session.update_agent(|_, _| Some((AgentState::NeedsInput, None))); + ctx.event(&id, EventKind::NeedsInput, None, message); + } + Effect::Notify { title, body } => ctx.event(&id, EventKind::Notification, title, body), + Effect::Nothing => {} + } + StatusCode::OK.into_response() +} + +/// Holds a PermissionRequest until it is answered, settled or times out. +async fn ask(ctx: &Arc, session: &Session, input: &HookInput) -> Response { + let id = uuid::Uuid::new_v4().to_string(); + let approval = input.approval(id.clone(), session.id.clone(), now_ms(), ctx.approval_timeout); + session.update_agent(|_, _| Some((AgentState::NeedsApproval, None))); + ctx.event(&session.id, EventKind::ApprovalRequested, Some(approval.tool.clone()), Some(approval.summary.clone())); + let reply = ctx.approvals.open(approval.clone()); + session.changed(); + // Claude may hang up first (it was answered and closed): settle then. + let _guard = SettleOnDrop { ctx: ctx.clone(), id: id.clone() }; + let answer = match tokio::time::timeout(ctx.approval_timeout, reply).await { + Ok(answer) => answer.ok(), + Err(_) => { + ctx.approvals.settle(&id, ApprovalOutcome::TimedOut); + None + } + }; + let reply = claude::decision(answer.as_ref(), &approval); + // Without a decision Claude's own dialog is still up: the session keeps waiting. + if reply.is_some() { + working(ctx, session); + } + session.changed(); + match reply { + Some(body) => Json(body).into_response(), + None => StatusCode::OK.into_response(), + } +} + +/// The agent is back at work, unless another approval still waits. +fn working(ctx: &Ctx, session: &Session) { + let state = if ctx.approvals.count(&session.id) > 0 { AgentState::NeedsApproval } else { AgentState::Working }; + session.update_agent(|_, _| Some((state, None))); +} + +struct SettleOnDrop { + ctx: Arc, + id: String, +} + +impl Drop for SettleOnDrop { + fn drop(&mut self) { + self.ctx.approvals.settle(&self.id, ApprovalOutcome::Terminal); + } +} + +fn finished(ctx: &Ctx, session: &Session, message: Option) { + session.update_agent(|_, _| Some((AgentState::Finished, message.clone()))); + ctx.event(&session.id, EventKind::Finished, None, message); +} + +async fn codex_hook( + State(sessions): State>, + HookSession(session): HookSession, + Json(notify): Json, +) -> StatusCode { + if notify.turn_complete() { + finished(sessions.ctx(), &session, notify.last_assistant_message); + } + StatusCode::OK +} diff --git a/crates/redshell-server/src/agents/mod.rs b/crates/redshell-server/src/agents/mod.rs new file mode 100644 index 0000000..a79f4fa --- /dev/null +++ b/crates/redshell-server/src/agents/mod.rs @@ -0,0 +1,60 @@ +//! Agent awareness through the agents' own extension points. +//! +//! * Claude Code starts with `--settings `, a private file that adds +//! HTTP hooks posting to the hook listener ([`claude`]). +//! * Codex starts with `-c notify=[…]`, which runs `redshell-server hook +//! codex` after each turn ([`codex`]). +//! +//! The hook listener ([`hooks`]) is bound to 127.0.0.1 on a random port and +//! is never part of the public router. A reverse proxy makes every request +//! look local, so being on loopback proves nothing: each URL carries the +//! session id and a random per-session token. + +mod approvals; +mod claude; +mod codex; +pub mod hooks; + +use std::path::Path; + +pub use approvals::{Answer, Approvals}; +pub use codex::{URL_ENV as HOOK_URL_ENV, hook as codex_hook}; + +use crate::auth::secret; +use crate::sessions::launch::Launch; +use crate::sessions::{AgentHook, Ctx}; + +/// Wires `launch` up to report to the hook listener when it starts an +/// agent RedShell understands. +pub fn prepare(launch: &mut Launch, session: &str, ctx: &Ctx) -> anyhow::Result> { + let token = secret::new_token(); + let url = |agent: &str| format!("http://{}/{agent}/{session}/{token}", ctx.hook_addr); + let files = match launch.agent.as_deref() { + Some("claude") => { + let file = ctx.runtime_dir.join(format!("claude-{session}.json")); + write_private(&file, &claude::settings(&url("claude"), ctx.approval_timeout))?; + launch.spec.args.extend(["--settings".to_owned(), file.display().to_string()]); + vec![file] + } + Some("codex") => { + let notify = codex::notify_override(&std::env::current_exe()?); + launch.spec.args.splice(0..0, ["-c".to_owned(), notify]); + launch.spec.env.insert(codex::URL_ENV.into(), url("codex")); + Vec::new() + } + _ => return Ok(None), + }; + Ok(Some(AgentHook { token, files })) +} + +/// Writes a file only the server's user can read. +fn write_private(path: &Path, contents: &str) -> anyhow::Result<()> { + use std::io::Write as _; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(path)?; + file.write_all(contents.as_bytes())?; + Ok(()) +} diff --git a/crates/redshell-server/src/auth/limiter.rs b/crates/redshell-server/src/auth/limiter.rs new file mode 100644 index 0000000..17dbe05 --- /dev/null +++ b/crates/redshell-server/src/auth/limiter.rs @@ -0,0 +1,143 @@ +//! Exponential backoff after failed sign-ins, per client IP and per user. +//! +//! The first [`FREE_FAILURES`] failures cost nothing; after that each +//! attempt has to wait 1 s, 2 s, 4 s, … (at most the limiter's +//! `max_delay`) after the previous failure. A success clears the key, and a key with no failure +//! for a day is forgotten. Entries are dropped lazily, so an idle server +//! does no work. At most [`MAX_KEYS`] are kept: when they are all taken, +//! the tenth that failed least recently is forgotten. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use parking_lot::Mutex; + +const FREE_FAILURES: u32 = 3; +const FORGET_AFTER: Duration = Duration::from_secs(24 * 60 * 60); +/// Beyond this many keys, forgotten ones are swept on the next failure; the +/// next sweep waits until there are twice as many as the sweep left. +const SWEEP_AT: usize = 10_000; +/// Most keys kept, whatever their age. +const MAX_KEYS: usize = 100_000; + +#[derive(Debug, Clone, Copy)] +struct Entry { + failures: u32, + last: Instant, +} + +impl Entry { + fn delay(self, max: Duration) -> Duration { + match self.failures.checked_sub(FREE_FAILURES) { + None => Duration::ZERO, + Some(extra) => Duration::from_secs(1u64 << extra.min(20)).min(max), + } + } +} + +pub struct Limiter { + entries: Mutex, + /// The longest wait a key can earn. + max_delay: Duration, +} + +#[derive(Default)] +struct Entries { + map: HashMap, + /// Size at which the next failure sweeps forgotten keys. + sweep_at: usize, +} + +impl Entries { + /// Makes room for `key` if it is new: forgotten keys go, and with every + /// place still taken, the stalest tenth too. + fn make_room(&mut self, key: &str, now: Instant) { + if self.map.len() >= self.sweep_at.max(SWEEP_AT) { + self.map.retain(|_, e| now.duration_since(e.last) < FORGET_AFTER); + self.sweep_at = self.map.len() * 2; + } + if self.map.len() >= MAX_KEYS && !self.map.contains_key(key) { + let mut lasts: Vec = self.map.values().map(|e| e.last).collect(); + let (_, cutoff, _) = lasts.select_nth_unstable(MAX_KEYS / 10); + let cutoff = *cutoff; + self.map.retain(|_, e| e.last > cutoff); + } + } +} + +impl Limiter { + pub fn new(max_delay: Duration) -> Self { + Self { entries: Mutex::default(), max_delay } + } + + /// `Err(wait)` while `key` has to wait before the next attempt. + pub fn check(&self, key: &str, now: Instant) -> Result<(), Duration> { + let entries = self.entries.lock(); + let Some(entry) = entries.map.get(key) else { return Ok(()) }; + let ready = entry.last + entry.delay(self.max_delay); + if now < ready { Err(ready - now) } else { Ok(()) } + } + + pub fn failure(&self, key: &str, now: Instant) { + let mut entries = self.entries.lock(); + entries.make_room(key, now); + let entry = entries.map.entry(key.to_owned()).or_insert(Entry { failures: 0, last: now }); + if now.duration_since(entry.last) >= FORGET_AFTER { + entry.failures = 0; + } + entry.failures += 1; + entry.last = now; + } + + pub fn success(&self, key: &str) { + self.entries.lock().map.remove(key); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backs_off_exponentially_and_resets() { + const MAX_DELAY: Duration = Duration::from_secs(15 * 60); + let limiter = Limiter::new(MAX_DELAY); + let t0 = Instant::now(); + for _ in 0..FREE_FAILURES { + assert!(limiter.check("ip:a", t0).is_ok()); + limiter.failure("ip:a", t0); + } + assert_eq!(limiter.check("ip:a", t0), Err(Duration::from_secs(1))); + assert!(limiter.check("ip:a", t0 + Duration::from_secs(1)).is_ok()); + limiter.failure("ip:a", t0 + Duration::from_secs(1)); + assert_eq!(limiter.check("ip:a", t0 + Duration::from_secs(1)), Err(Duration::from_secs(2))); + assert!(limiter.check("ip:b", t0).is_ok(), "keys are independent"); + for _ in 0..40 { + limiter.failure("ip:a", t0); + } + assert_eq!(limiter.check("ip:a", t0), Err(MAX_DELAY)); + assert!(limiter.check("ip:a", t0 + FORGET_AFTER).is_ok()); + limiter.success("ip:a"); + assert!(limiter.check("ip:a", t0).is_ok()); + } + + #[test] + fn keeps_a_bounded_number_of_keys() { + let limiter = Limiter::new(Duration::from_secs(60)); + let t0 = Instant::now(); + let at = |i: usize| t0 + Duration::from_millis(i as u64); + for i in 0..MAX_KEYS { + limiter.failure(&format!("user:{i}"), at(i)); + } + let last = MAX_KEYS - 1; + for _ in 0..FREE_FAILURES { + limiter.failure(&format!("user:{last}"), at(last)); + } + limiter.failure("user:new", at(MAX_KEYS)); + let entries = limiter.entries.lock(); + assert!(entries.map.len() < MAX_KEYS && entries.map.len() >= MAX_KEYS * 8 / 10, "{}", entries.map.len()); + assert!(!entries.map.contains_key("user:0"), "the stalest keys made room"); + drop(entries); + assert!(limiter.check(&format!("user:{last}"), at(last)).is_err(), "a recent backoff stays"); + } +} diff --git a/crates/redshell-server/src/auth/mod.rs b/crates/redshell-server/src/auth/mod.rs new file mode 100644 index 0000000..76073ce --- /dev/null +++ b/crates/redshell-server/src/auth/mod.rs @@ -0,0 +1,689 @@ +//! Who is signed in: first-run setup, password sign-in with backoff, +//! browser sessions and device tokens. + +mod limiter; +mod pairing; +mod passkeys; +pub mod password; +mod queue; +mod reauth; +pub mod secret; +mod user_agent; + +use std::net::IpAddr; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use parking_lot::Mutex; +use redshell_protocol::{ChangePasswordRequest, SetupRequest, SignInRequest, User}; + +use crate::bus::{Bus, BusEvent}; +use crate::now_ms; +use crate::store::{AuditEvent, Credential, SignInMethod, Store}; +use limiter::Limiter; +use pairing::Pairings; +pub use pairing::is_code as is_pairing_code; +use passkeys::Passkeys; +use queue::PasswordQueue; + +/// Name of the browser session cookie. The `__Host-` prefix makes browsers +/// accept it only when Secure, for this host and path `/`. +pub const COOKIE: &str = "__Host-redshell-session"; +/// A browser session lasts this long after it was last used. +pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); +/// Use of a credential is written back, and a browser session's expiry +/// pushed out, at most this often. +const TOUCH_EVERY_MS: i64 = 60 * 60 * 1000; +/// How long a setup link works. +const SETUP_TTL: Duration = Duration::from_secs(30 * 60); +/// Longest user name, also for a sign-in: a longer one is refused before +/// it reaches the log, the backoff or the audit log. +const MAX_USERNAME: usize = 64; +/// Throttled sign-ins are logged at most this often. +const THROTTLE_LOG_EVERY: Duration = Duration::from_secs(60); +/// Password checks that may wait in each queue. +const MAX_WAITING_CHECKS: usize = 16; +/// Longest backoff a client address earns. +const MAX_ADDRESS_DELAY: Duration = Duration::from_secs(15 * 60); +/// Longest backoff a user name earns. Anyone who knows the name can earn +/// it, locking its owner out too; kept short so that costs little, while +/// guesses from many addresses still meet it. +const MAX_USER_DELAY: Duration = Duration::from_secs(2 * 60); + +/// A signed-in request's user and credential. +#[derive(Debug, Clone)] +pub struct Principal { + pub user: User, + pub credential: Credential, + /// The device's or browser's name (`Safari on iPhone`): who answered an + /// approval. + pub label: String, + /// The browser session's expiry was pushed out: send the cookie again. + pub renewed: bool, + /// When the credential's use was last recorded. + pub seen_at: i64, + /// SHA-256 of the token: what tells this credential from a later one + /// with the same id. + pub token_hash: [u8; 32], + /// When it last proved who it is (see `reauth`). + pub reauth_at: Option, + pub signed_in_with: SignInMethod, +} + +/// How a new sign-in proved who it is. +#[derive(Debug, Clone, Copy)] +enum Proof { + /// It authenticated itself: a fresh re-authentication too. + Own(SignInMethod), + /// A signed-in user approved it (pairing); they had signed in this way. + Vouched(SignInMethod), +} + +impl Principal { + /// Whether this sign-in still holds (not revoked, not expired). + pub fn still_valid(&self, store: &Store) -> anyhow::Result { + store.credential_live(self.user.id, self.credential, &self.token_hash) + } +} + +/// A credential handed out by sign-in or setup. +#[derive(Debug, Clone)] +pub enum Issued { + /// Goes into the session cookie. + Cookie(String), + /// Returned once to the device. + DeviceToken(String), +} + +pub struct SignedIn { + pub user: User, + pub issued: Issued, +} + +/// Where a request comes from, for throttling and the audit log. +#[derive(Debug, Clone)] +pub struct Client { + pub ip: String, + pub user_agent: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum AuthError { + #[error("wrong username or password")] + InvalidCredentials, + #[error("too many failed attempts; try again in {} s", .0.as_secs().max(1))] + RateLimited(Duration), + #[error("{0}")] + BadRequest(String), + #[error("{0}")] + Forbidden(String), + #[error("{0}")] + Conflict(String), + #[error("{0}")] + NotFound(String), + #[error("this account signs in with a passkey only")] + PasskeyRequired, + #[error("confirm it's you first, with your password or a passkey")] + ReauthRequired, + #[error("{0}")] + PasskeyRejected(String), + /// A feature this server's configuration does not offer. + #[error("{0}")] + Unavailable(String), + #[error(transparent)] + Internal(#[from] anyhow::Error), +} + +struct SetupCode { + code: String, + expires: Instant, +} + +pub struct Auth { + store: Arc, + bus: Bus, + /// Backoff per client address (`ip:`, `pair:`, `pair-poll:` keys). + limiter: Limiter, + /// Backoff per user (`user:` and `pair-code:` keys). + user_limiter: Limiter, + setup: Mutex>, + /// Where setup links point. + base_url: String, + /// Password checks of sign-ins and setup, which anyone can ask for. + open_checks: PasswordQueue, + /// Password checks of signed-in users, apart so that strangers cannot + /// keep them waiting. + account_checks: PasswordQueue, + pairings: Pairings, + /// The WebAuthn relying party, or why passkeys are off. + passkeys: Result, + throttle_log: ThrottleLog, +} + +/// Logs throttled sign-ins at most once every [`THROTTLE_LOG_EVERY`], with +/// how many went unlogged in between: they are free to make, so a flood of +/// them must not flood the log. +#[derive(Default)] +struct ThrottleLog(Mutex<(Option, u64)>); + +impl ThrottleLog { + fn throttled(&self, username: &str, ip: &str, key: &str) { + let mut state = self.0.lock(); + let (last, unlogged) = &mut *state; + let now = Instant::now(); + if last.is_some_and(|at| now.duration_since(at) < THROTTLE_LOG_EVERY) { + *unlogged += 1; + return; + } + let more = match std::mem::take(unlogged) { + 0 => String::new(), + n => format!(", and {n} more since the last report"), + }; + *last = Some(now); + log::warn!("sign-in as {username:?} from {ip} throttled ({key}){more}"); + } +} + +impl Auth { + /// `base_url` is where links point; passkeys need `public_origin`. + pub fn new(store: Arc, bus: Bus, base_url: String, public_origin: Option<&str>) -> Self { + Self { + store, + bus, + limiter: Limiter::new(MAX_ADDRESS_DELAY), + user_limiter: Limiter::new(MAX_USER_DELAY), + setup: Mutex::new(None), + base_url, + open_checks: PasswordQueue::new(MAX_WAITING_CHECKS), + account_checks: PasswordQueue::new(MAX_WAITING_CHECKS), + pairings: Pairings::default(), + passkeys: Passkeys::new(public_origin), + throttle_log: ThrottleLog::default(), + } + } + + pub fn setup_required(&self) -> anyhow::Result { + Ok(self.store.user_count()? == 0) + } + + /// While no account exists, makes sure a setup code is valid (a new one + /// when the last expired) and logs its link. Returns the link. + pub fn announce_setup(&self) -> anyhow::Result> { + if !self.setup_required()? { + *self.setup.lock() = None; + return Ok(None); + } + let mut setup = self.setup.lock(); + let now = Instant::now(); + let fresh = setup.as_ref().is_none_or(|s| s.expires <= now); + if fresh { + *setup = Some(SetupCode { code: secret::random_string(16), expires: now + SETUP_TTL }); + } + let link = + format!("{}/setup?code={}", self.base_url, setup.as_ref().map(|s| s.code.as_str()).unwrap_or_default()); + if fresh { + log::warn!("No account exists yet. Create the first one within 30 minutes at:\n\n {link}\n"); + } + Ok(Some(link)) + } + + /// Creates the first account with the code from the setup link. + pub async fn setup(&self, req: SetupRequest, client: &Client) -> Result { + let _turn = self.open_checks.enter().await?; + let ip_key = ip_key(client); + self.limiter.check(&ip_key, Instant::now()).map_err(AuthError::RateLimited)?; + let valid = self + .setup + .lock() + .as_ref() + .is_some_and(|s| s.expires > Instant::now() && secret::same_secret(&s.code, &req.code)); + if !valid { + self.limiter.failure(&ip_key, Instant::now()); + return Err(AuthError::Forbidden( + "the setup link is not valid; open the newest one in the server log".into(), + )); + } + if !self.setup_required()? { + return Err(AuthError::Conflict("setup is already done".into())); + } + check_username(&req.username)?; + password::check_new(&req.password).map_err(AuthError::BadRequest)?; + let hash = password::hash(req.password).await?; + let user = self + .store + .create_user(&req.username, &hash)? + .ok_or_else(|| AuthError::Conflict("that name is taken".into()))?; + *self.setup.lock() = None; + self.store.audit(AuditEvent::Setup, Some(user.id), Some(&user.username), Some(&client.ip), ""); + log::info!("created the first account, {}", user.username); + self.issue(user, None, client, Proof::Own(SignInMethod::Password)) + } + + /// Password sign-in. Unknown users and wrong passwords fail alike, in + /// time too; repeated failures are throttled per IP and per name. + pub async fn sign_in(&self, req: SignInRequest, client: &Client) -> Result { + if req.username.chars().count() > MAX_USERNAME { + return Err(username_rule()); + } + let _turn = self.open_checks.enter().await?; + let now = Instant::now(); + let keys = [(&self.limiter, ip_key(client)), (&self.user_limiter, user_key(&req.username))]; + for (limiter, key) in &keys { + if let Err(wait) = limiter.check(key, now) { + // Logged (sparingly), not audited: throttled attempts are free to make. + self.throttle_log.throttled(&req.username, &client.ip, key); + return Err(AuthError::RateLimited(wait)); + } + } + let failed = || keys.iter().for_each(|(limiter, key)| limiter.failure(key, Instant::now())); + let device = req.device_name.as_deref().map(device_name).transpose()?; + let record = self.store.find_user(&req.username)?; + let hash = record.as_ref().map(|r| r.password_hash.clone()); + if !password::verify(req.password, hash).await { + failed(); + self.store.audit(AuditEvent::SignInFailed, None, Some(&req.username), Some(&client.ip), ""); + return Err(AuthError::InvalidCredentials); + } + let record = record.ok_or(AuthError::InvalidCredentials)?; + if record.passkey_only { + // Said only to someone who knows the password, so it tells strangers nothing. It + // still counts as a failure, or answering it would let guesses go on unhindered. + failed(); + let user = &record.user; + let ip = Some(client.ip.as_str()); + self.store.audit(AuditEvent::SignInFailed, Some(user.id), Some(&user.username), ip, "passkey only"); + return Err(AuthError::PasskeyRequired); + } + keys.iter().for_each(|(limiter, key)| limiter.success(key)); + let user = record.user; + let detail = device.as_deref().map_or_else(|| "browser".to_owned(), |d| format!("device {d}")); + self.store.audit(AuditEvent::SignIn, Some(user.id), Some(&user.username), Some(&client.ip), &detail); + self.issue(user, device, client, Proof::Own(SignInMethod::Password)) + } + + /// Makes a browser session, or a device token for `device`, recording + /// its `proof`. + fn issue(&self, user: User, device: Option, client: &Client, proof: Proof) -> Result { + let token = secret::new_token(); + let hash = secret::token_hash(&token); + let (credential, issued) = match device { + Some(name) => (self.store.create_device(user.id, &name, &hash, &client.ip)?, Issued::DeviceToken(token)), + None => { + let expires = now_ms() + SESSION_TTL.as_millis() as i64; + let ua = client.user_agent.as_deref(); + let name = user_agent::describe(ua); + ( + self.store.create_browser_session(user.id, &hash, expires, &client.ip, ua, &name)?, + Issued::Cookie(token), + ) + } + }; + let (method, reauth_at) = match proof { + Proof::Own(method) => (method, Some(now_ms())), + Proof::Vouched(method) => (method, None), + }; + self.store.issued(credential, method, reauth_at)?; + Ok(SignedIn { user, issued }) + } + + /// The user behind a session cookie or a bearer device token. Use is + /// recorded, and a browser session extended, at most hourly; the two + /// are apart because an open WebSocket records use without a cookie + /// to renew ([`Self::seen`]). + pub fn authenticate(&self, cookie: Option<&str>, bearer: Option<&str>, client: &Client) -> Option { + let (device, token) = match (bearer, cookie) { + (Some(token), _) => (true, token), + (None, Some(token)) => (false, token), + (None, None) => return None, + }; + let token_hash = secret::token_hash(token); + let owner = match self.store.find_token(device, &token_hash) { + Ok(owner) => owner?, + Err(err) => { + log::error!("checking a token: {err:#}"); + return None; + } + }; + let now = now_ms(); + let ttl = SESSION_TTL.as_millis() as i64; + let extend = owner.expires_at.filter(|expires| now + ttl - expires >= TOUCH_EVERY_MS).map(|_| now + ttl); + let due = now - owner.last_seen_at >= TOUCH_EVERY_MS; + let mut seen_at = owner.last_seen_at; + if due || extend.is_some() { + match self.store.touch(owner.credential, &client.ip, extend) { + Ok(()) => seen_at = now, + Err(err) => log::error!("recording a sign-in's use: {err:#}"), + } + } + Some(Principal { + user: owner.user, + credential: owner.credential, + label: owner.name, + renewed: extend.is_some(), + seen_at, + token_hash, + reauth_at: owner.reauth_at, + signed_in_with: owner.signed_in_with, + }) + } + + /// Records that `principal` is still in use (an open WebSocket), at + /// most hourly. The expiry of a browser session stays: only a request + /// that can renew the cookie pushes it out. + pub fn seen(&self, principal: &mut Principal, client: &Client) { + let now = now_ms(); + if now - principal.seen_at < TOUCH_EVERY_MS { + return; + } + match self.store.touch(principal.credential, &client.ip, None) { + Ok(()) => principal.seen_at = now, + Err(err) => log::error!("recording a sign-in's use: {err:#}"), + } + } + + pub fn sign_out(&self, principal: &Principal, client: &Client) -> Result<(), AuthError> { + self.revoke(principal, principal.credential, client).map(drop) + } + + /// Revokes one of the principal's own credentials; `false` when it has + /// no such credential. Another than its own needs a re-authentication. + pub fn revoke(&self, principal: &Principal, credential: Credential, client: &Client) -> Result { + if credential != principal.credential { + self.require_reauth(principal)?; + } + let user = &principal.user; + if !self.store.revoke(user.id, credential)? { + return Ok(false); + } + let (event, detail) = match credential == principal.credential { + true => (AuditEvent::SignOut, String::new()), + false => (AuditEvent::CredentialRevoked, format!("{credential:?}")), + }; + self.store.audit(event, Some(user.id), Some(&user.username), Some(&client.ip), &detail); + self.bus.send(BusEvent::Revoked(credential)); + Ok(true) + } + + /// Changes the password after checking the current one (and, for a + /// passkey-only account, a recent re-authentication), signs out every + /// other browser and device, and drops pairings this user approved that + /// wait for their device. + pub async fn change_password( + &self, + principal: &Principal, + req: ChangePasswordRequest, + client: &Client, + ) -> Result<(), AuthError> { + let _turn = self.account_checks.enter().await?; + let user = &principal.user; + let key = user_key(&user.username); + self.user_limiter.check(&key, Instant::now()).map_err(AuthError::RateLimited)?; + password::check_new(&req.new_password).map_err(AuthError::BadRequest)?; + let record = self.store.user_by_id(user.id)?.ok_or(AuthError::InvalidCredentials)?; + if record.passkey_only { + self.require_reauth(principal)?; + } + if !password::verify(req.current_password, Some(record.password_hash)).await { + self.user_limiter.failure(&key, Instant::now()); + self.store.audit( + AuditEvent::PasswordChangeFailed, + Some(user.id), + Some(&user.username), + Some(&client.ip), + "", + ); + return Err(AuthError::InvalidCredentials); + } + let hash = password::hash(req.new_password).await?; + self.store.set_password(user.id, &hash)?; + self.store.revoke_all_except(user.id, Some(principal.credential))?; + self.pairings.forget_approved_by(user.id); + self.store.audit(AuditEvent::PasswordChanged, Some(user.id), Some(&user.username), Some(&client.ip), ""); + self.bus.send(BusEvent::RevokedAllBut { user_id: user.id, keep: principal.credential }); + Ok(()) + } + + #[cfg(test)] + pub fn setup_code(&self) -> Option { + self.setup.lock().as_ref().map(|s| s.code.clone()) + } +} + +/// The throttling key of a user name. +fn user_key(username: &str) -> String { + format!("user:{}", username.to_lowercase()) +} + +/// The throttling key of a client address, shared by every way of signing in. +fn ip_key(client: &Client) -> String { + format!("ip:{}", address_key(&client.ip)) +} + +/// What limits count a client address as: itself, or for IPv6 its /64, +/// which one home or machine usually has whole. +pub(crate) fn address_key(ip: &str) -> String { + match ip.parse::() { + Ok(IpAddr::V6(v6)) => match v6.to_ipv4_mapped() { + Some(v4) => v4.to_string(), + None => { + let s = v6.segments(); + format!("{:x}:{:x}:{:x}:{:x}::/64", s[0], s[1], s[2], s[3]) + } + }, + _ => ip.to_owned(), + } +} + +/// A device's name, trimmed: 1 to 100 characters, no control characters. +fn device_name(name: &str) -> Result { + let name = name.trim(); + if (1..=100).contains(&name.chars().count()) && !name.chars().any(char::is_control) { + Ok(name.to_owned()) + } else { + Err(AuthError::BadRequest("a device name has 1 to 100 characters".into())) + } +} + +/// Names have 1 to [`MAX_USERNAME`] letters, digits and `. _ - @`. +fn check_username(name: &str) -> Result<(), AuthError> { + let ok = (1..=MAX_USERNAME).contains(&name.chars().count()) + && name.chars().all(|c| c.is_alphanumeric() || matches!(c, '.' | '_' | '-' | '@')); + if ok { Ok(()) } else { Err(username_rule()) } +} + +fn username_rule() -> AuthError { + AuthError::BadRequest(format!("a name has 1 to {MAX_USERNAME} letters, digits, '.', '_', '-' or '@'")) +} + +/// Validation shared with the `user` CLI. +pub fn valid_username(name: &str) -> Result<(), String> { + check_username(name).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn auth() -> Auth { + Auth::new(Arc::new(Store::in_memory()), Bus::default(), "http://127.0.0.1:4747".into(), None) + } + + fn client() -> Client { + Client { ip: "10.0.0.1".into(), user_agent: Some("test".into()) } + } + + #[tokio::test] + async fn setup_then_sign_in_and_tokens() { + let auth = auth(); + let link = auth.announce_setup().unwrap().unwrap(); + let code = auth.setup_code().unwrap(); + assert!(link.ends_with(&code)); + let bad = SetupRequest { code: "nope".into(), username: "me".into(), password: "long password".into() }; + assert!(matches!(auth.setup(bad, &client()).await, Err(AuthError::Forbidden(_)))); + let req = SetupRequest { code, username: "me".into(), password: "long password".into() }; + let done = auth.setup(req.clone(), &client()).await.unwrap(); + let Issued::Cookie(cookie) = done.issued else { panic!("setup signs the browser in") }; + assert!(auth.announce_setup().unwrap().is_none()); + assert!(matches!(auth.setup(req, &client()).await, Err(AuthError::Forbidden(_))), "the code is used up"); + + let principal = auth.authenticate(Some(&cookie), None, &client()).unwrap(); + assert_eq!(principal.user.username, "me"); + let sign_in = |password: &str, device: Option<&str>| SignInRequest { + username: "ME".into(), + password: password.into(), + device_name: device.map(Into::into), + }; + let device = auth.sign_in(sign_in("long password", Some("laptop")), &client()).await.unwrap(); + let Issued::DeviceToken(token) = device.issued else { panic!("a named device gets a token") }; + assert!(auth.authenticate(None, Some(&token), &client()).is_some()); + assert!(auth.authenticate(None, Some(&cookie), &client()).is_none(), "a cookie is no bearer token"); + assert!(matches!(auth.sign_in(sign_in("wrong", None), &client()).await, Err(AuthError::InvalidCredentials))); + + auth.sign_out(&principal, &client()).unwrap(); + assert!(auth.authenticate(Some(&cookie), None, &client()).is_none()); + } + + #[tokio::test] + async fn browsers_are_named_and_renewed_hourly() { + let auth = auth(); + auth.store.create_user("me", &password::hash("long password".into()).await.unwrap()).unwrap(); + let iphone = Client { + ip: "10.0.0.1".into(), + user_agent: Some("Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) Version/18.1 Safari/604.1".into()), + }; + let req = SignInRequest { username: "me".into(), password: "long password".into(), device_name: None }; + let Issued::Cookie(cookie) = auth.sign_in(req, &iphone).await.unwrap().issued else { panic!() }; + let mut principal = auth.authenticate(Some(&cookie), None, &iphone).unwrap(); + assert_eq!(principal.label, "Safari on iPhone"); + assert!(!principal.renewed, "a fresh session keeps its cookie"); + assert_eq!(auth.store.browser_sessions(principal.user.id).unwrap()[0].name, "Safari on iPhone"); + + // An open WebSocket records use, without pushing out the expiry. + principal.seen_at = 0; + let elsewhere = Client { ip: "10.0.0.9".into(), user_agent: None }; + auth.seen(&mut principal, &elsewhere); + assert!(principal.seen_at > 0); + let session = &auth.store.browser_sessions(principal.user.id).unwrap()[0]; + assert_eq!(session.last_ip.as_deref(), Some("10.0.0.9")); + // An expiry pushed out over an hour ago is pushed out again, with the cookie. + let hours_ago = now_ms() + SESSION_TTL.as_millis() as i64 - 2 * TOUCH_EVERY_MS; + auth.store.touch(principal.credential, "10.0.0.1", Some(hours_ago)).unwrap(); + assert!(auth.authenticate(Some(&cookie), None, &iphone).unwrap().renewed); + assert!(!auth.authenticate(Some(&cookie), None, &iphone).unwrap().renewed); + } + + #[tokio::test] + async fn unknown_users_fail_like_wrong_passwords_and_get_throttled() { + let auth = auth(); + auth.store.create_user("me", &password::hash("long password".into()).await.unwrap()).unwrap(); + let attempt = |name: &str| SignInRequest { username: name.into(), password: "guess".into(), device_name: None }; + for name in ["me", "ghost", "me"] { + assert!(matches!(auth.sign_in(attempt(name), &client()).await, Err(AuthError::InvalidCredentials))); + } + assert!(matches!(auth.sign_in(attempt("other"), &client()).await, Err(AuthError::RateLimited(_)))); + let elsewhere = Client { ip: "10.0.0.2".into(), user_agent: None }; + assert!(matches!(auth.sign_in(attempt("ghost"), &elsewhere).await, Err(AuthError::InvalidCredentials))); + let events = auth.store.audit_events(); + assert_eq!(events.iter().filter(|(e, _)| e == "sign_in_failed").count(), 4); + } + + #[test] + fn ipv6_clients_count_by_their_64() { + assert_eq!(address_key("2001:db8:1:2:aaaa::1"), "2001:db8:1:2::/64"); + assert_eq!(address_key("2001:db8:1:2:bbbb::9"), "2001:db8:1:2::/64"); + assert_eq!(address_key("2001:db8:1:3::1"), "2001:db8:1:3::/64"); + assert_eq!(address_key("::ffff:10.0.0.1"), "10.0.0.1"); + assert_eq!(address_key("10.0.0.1"), "10.0.0.1"); + } + + #[tokio::test] + async fn overlong_names_are_refused_before_anything_records_them() { + let auth = auth(); + let req = SignInRequest { username: "x".repeat(65), password: "guess".into(), device_name: None }; + for _ in 0..5 { + assert!(matches!(auth.sign_in(req.clone(), &client()).await, Err(AuthError::BadRequest(_)))); + } + assert!(auth.store.audit_events().is_empty()); + let ok = SignInRequest { username: "x".repeat(64), ..req }; + assert!(matches!(auth.sign_in(ok, &client()).await, Err(AuthError::InvalidCredentials)), "not throttled"); + } + + #[tokio::test] + async fn the_right_password_of_a_passkey_only_account_still_counts_as_a_failure() { + let auth = auth(); + auth.store.create_user("me", &password::hash("long password".into()).await.unwrap()).unwrap(); + let user = auth.store.find_user("me").unwrap().unwrap().user; + auth.store.add_passkey(user.id, b"cred", "key", "{}").unwrap(); + assert!(auth.store.set_passkey_only(user.id, true).unwrap()); + let right = || SignInRequest { username: "me".into(), password: "long password".into(), device_name: None }; + for _ in 0..3 { + assert!(matches!(auth.sign_in(right(), &client()).await, Err(AuthError::PasskeyRequired))); + } + assert!(matches!(auth.sign_in(right(), &client()).await, Err(AuthError::RateLimited(_)))); + } + + #[test] + fn a_name_earns_a_shorter_backoff_than_an_address() { + let auth = auth(); + let t0 = Instant::now(); + for _ in 0..30 { + auth.limiter.failure("ip:10.0.0.1", t0); + auth.user_limiter.failure("user:me", t0); + } + assert_eq!(auth.limiter.check("ip:10.0.0.1", t0), Err(MAX_ADDRESS_DELAY)); + assert_eq!(auth.user_limiter.check("user:me", t0), Err(MAX_USER_DELAY)); + } + + #[tokio::test] + async fn a_burst_of_guesses_meets_the_backoff() { + let auth = Arc::new(auth()); + auth.store.create_user("me", &password::hash("long password".into()).await.unwrap()).unwrap(); + let guesses = (0..8).map(|i| { + let auth = auth.clone(); + tokio::spawn(async move { + let req = SignInRequest { username: "me".into(), password: format!("guess {i}"), device_name: None }; + auth.sign_in(req, &client()).await + }) + }); + let mut wrong = 0; + for guess in guesses { + match guess.await.unwrap() { + Err(AuthError::InvalidCredentials) => wrong += 1, + Err(AuthError::RateLimited(_)) => {} + other => panic!("{:?}", other.map(|s| s.user)), + } + } + assert_eq!(wrong, 3, "only the free attempts are checked"); + } + + #[tokio::test] + async fn changing_the_password_signs_out_everything_else() { + let auth = auth(); + auth.store.create_user("me", &password::hash("long password".into()).await.unwrap()).unwrap(); + let sign_in = |device: Option<&str>| SignInRequest { + username: "me".into(), + password: "long password".into(), + device_name: device.map(Into::into), + }; + let Issued::Cookie(a) = auth.sign_in(sign_in(None), &client()).await.unwrap().issued else { panic!() }; + let Issued::DeviceToken(b) = auth.sign_in(sign_in(Some("pc")), &client()).await.unwrap().issued else { + panic!() + }; + let principal = auth.authenticate(Some(&a), None, &client()).unwrap(); + let change = |current: &str| ChangePasswordRequest { + current_password: current.into(), + new_password: "new password".into(), + }; + assert!(matches!( + auth.change_password(&principal, change("wrong"), &client()).await, + Err(AuthError::InvalidCredentials) + )); + let pairing = auth.start_pairing("desk", None, &client()).unwrap(); + auth.pairing_by_code(&principal, &pairing.code, Some(true), &client()).unwrap(); + auth.change_password(&principal, change("long password"), &client()).await.unwrap(); + assert!(auth.authenticate(Some(&a), None, &client()).is_some()); + assert!(auth.authenticate(None, Some(&b), &client()).is_none()); + let poll = auth.poll_pairing(&pairing.id, &pairing.poll_secret, &client()); + assert!(matches!(poll, Err(AuthError::NotFound(_))), "the approved pairing went with the old password"); + } +} diff --git a/crates/redshell-server/src/auth/pairing.rs b/crates/redshell-server/src/auth/pairing.rs new file mode 100644 index 0000000..9d8a8d6 --- /dev/null +++ b/crates/redshell-server/src/auth/pairing.rs @@ -0,0 +1,464 @@ +//! Desktop pairing: a device asks for a sign-in, a signed-in browser +//! approves it by typing the short code the device shows. +//! +//! 1. The device opens a request ([`Auth::start_pairing`]) and shows its +//! code (`KX7-4MP`); it keeps the request id and a poll secret. +//! 2. A signed-in user types the code, sees the device's name and system +//! and where the request came from, and approves or rejects it. The code +//! only ever arrives as typed by the user, never from a link, so a +//! request someone else started cannot be approved by clicking. +//! 3. The device polls with its secret ([`Auth::poll_pairing`]) and, once +//! approved, collects its token a single time; the token is made then, +//! so none waits in memory, and only while the sign-in that approved it +//! still holds. +//! +//! Requests live in memory for [`PAIRING_TTL`]. At most [`MAX_PENDING`] +//! wait at once, and [`MAX_PER_ADDRESS`] from one address: past either, a +//! new request pushes out the oldest unanswered one (of that address, or +//! of anyone), so nobody can fill the list for everyone. Starting, polling +//! and typing codes are rate-limited. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use parking_lot::Mutex; +use rand_core::{OsRng, RngCore as _}; +use redshell_protocol::{PairStarted, PairStatus, PairingInfo, User}; + +use super::{Auth, AuthError, Client, Issued, Principal, Proof, address_key, device_name, secret}; +use crate::now_ms; +use crate::store::{AuditEvent, Credential, SignInMethod}; + +/// How long a pairing request can be approved and collected. +pub const PAIRING_TTL: Duration = Duration::from_secs(10 * 60); +/// Requests waiting at once, from everyone. +const MAX_PENDING: usize = 64; +/// Requests waiting at once from one address (an IPv6 /64). +const MAX_PER_ADDRESS: usize = 4; +/// Letters and digits of a code: no `0 O 1 I L`, which read alike. +const ALPHABET: &[u8] = b"23456789ABCDEFGHJKMNPQRSTUVWXYZ"; +/// Characters in a code, without the dash. +const CODE_LEN: usize = 6; + +/// Where a request is. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Stage { + Pending, + /// Approved; the device has not collected its token yet. + Approved(Approver), + Rejected, +} + +/// Who approved a request: the user, and the sign-in they approved it with. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Approver { + user: User, + credential: Credential, + token_hash: [u8; 32], + /// What the approving sign-in was made with; the device counts as made + /// with it too. + signed_in_with: SignInMethod, +} + +impl From<&Principal> for Approver { + fn from(principal: &Principal) -> Self { + Self { + user: principal.user.clone(), + credential: principal.credential, + token_hash: principal.token_hash, + signed_in_with: principal.signed_in_with, + } + } +} + +struct Request { + code: String, + poll_hash: [u8; 32], + device_name: String, + platform: Option, + ip: String, + /// What the request counts against: [`address_key`] of `ip`. + address: String, + created_at: i64, + expires: Instant, + stage: Stage, +} + +impl Request { + fn info(&self) -> PairingInfo { + PairingInfo { + code: display(&self.code), + device_name: self.device_name.clone(), + platform: self.platform.clone(), + ip: self.ip.clone(), + same_address: false, + created_at: self.created_at, + expires_at: self.created_at + PAIRING_TTL.as_millis() as i64, + } + } +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +enum PairingError { + #[error("too many pairing requests are waiting; try again in a few minutes")] + Full, + #[error("no pairing request has that code, or it expired")] + UnknownCode, + #[error("that pairing request was answered already")] + Answered, +} + +impl From for AuthError { + fn from(err: PairingError) -> Self { + match err { + PairingError::Full => AuthError::RateLimited(Duration::from_secs(60)), + PairingError::UnknownCode => AuthError::NotFound(err.to_string()), + PairingError::Answered => AuthError::Conflict(err.to_string()), + } + } +} + +/// The pairing requests in flight. +#[derive(Default)] +pub struct Pairings { + requests: Mutex>, +} + +impl Pairings { + /// Opens a request; its id, code and poll secret. + fn start(&self, device_name: String, platform: Option, ip: String) -> Result { + let mut requests = self.requests.lock(); + let now = Instant::now(); + requests.retain(|_, r| r.expires > now); + let address = address_key(&ip); + let oldest_pending = |requests: &HashMap, address: Option<&str>| { + let pending = + requests.iter().filter(|(_, r)| r.stage == Stage::Pending && address.is_none_or(|a| r.address == a)); + pending.min_by_key(|(_, r)| r.expires).map(|(id, _)| id.clone()) + }; + if requests.values().filter(|r| r.address == address).count() >= MAX_PER_ADDRESS + && let Some(id) = oldest_pending(&requests, Some(&address)) + { + requests.remove(&id); + } + if requests.len() >= MAX_PENDING { + let id = oldest_pending(&requests, None).ok_or(PairingError::Full)?; + requests.remove(&id); + } + let code = loop { + let code = new_code(); + if !requests.values().any(|r| r.code == code) { + break code; + } + }; + let (id, poll_secret) = (secret::random_string(16), secret::new_token()); + let request = Request { + code, + poll_hash: secret::token_hash(&poll_secret), + device_name, + platform, + ip, + address, + created_at: now_ms(), + expires: now + PAIRING_TTL, + stage: Stage::Pending, + }; + let info = request.info(); + requests.insert(id.clone(), request); + Ok(PairStarted { id, code: info.code, poll_secret, expires_at: info.expires_at, url: String::new() }) + } + + /// The pending request with `code`, as typed (any case, dashes and + /// spaces ignored); with `answer`, approved by that approver or rejected. + fn find(&self, code: &str, answer: Option>) -> Result { + let code = normalize(code); + let now = Instant::now(); + let mut requests = self.requests.lock(); + let request = + requests.values_mut().find(|r| r.code == code && r.expires > now).ok_or(PairingError::UnknownCode)?; + if request.stage != Stage::Pending { + return Err(PairingError::Answered); + } + if let Some(approver) = answer { + request.stage = approver.map_or(Stage::Rejected, Stage::Approved); + } + Ok(request.info()) + } + + /// Drops the requests `user_id` approved that wait for their device. + pub(super) fn forget_approved_by(&self, user_id: i64) { + self.requests.lock().retain(|_, r| !matches!(&r.stage, Stage::Approved(a) if a.user.id == user_id)); + } + + /// Where request `id` is, for the holder of `poll_secret`; `None` for + /// an unknown or expired request and a wrong secret alike. An answered + /// request is handed out once and then forgotten, with the device's + /// name. + fn poll(&self, id: &str, poll_secret: &str) -> Option<(Stage, String)> { + let mut requests = self.requests.lock(); + let request = requests.get(id).filter(|r| r.expires > Instant::now())?; + if request.poll_hash != secret::token_hash(poll_secret) { + return None; + } + let answer = (request.stage.clone(), request.device_name.clone()); + if answer.0 != Stage::Pending { + requests.remove(id); + } + Some(answer) + } +} + +impl Auth { + /// A device asks to be paired. + pub fn start_pairing( + &self, + device: &str, + platform: Option<&str>, + client: &Client, + ) -> Result { + let key = format!("pair:{}", address_key(&client.ip)); + self.limiter.check(&key, Instant::now()).map_err(AuthError::RateLimited)?; + let device = device_name(device)?; + let platform = platform.map(|p| p.trim().chars().take(40).collect::()).filter(|p| !p.is_empty()); + // Each request counts against the address; a device that pairs clears it. + self.limiter.failure(&key, Instant::now()); + let mut started = self.pairings.start(device.clone(), platform, client.ip.clone())?; + started.url = format!("{}/pair", self.base_url); + self.store.audit(AuditEvent::PairingRequested, None, None, Some(&client.ip), &device); + Ok(started) + } + + /// The device polls its request `id` with its secret. + pub fn poll_pairing(&self, id: &str, poll_secret: &str, client: &Client) -> Result { + let key = format!("pair-poll:{}", address_key(&client.ip)); + self.limiter.check(&key, Instant::now()).map_err(AuthError::RateLimited)?; + let Some((stage, device)) = self.pairings.poll(id, poll_secret) else { + self.limiter.failure(&key, Instant::now()); + return Err(AuthError::NotFound("no such pairing request, or it expired".into())); + }; + // Failures expire with time only: a valid poll of one's own request must not reset the + // backoff on guessing other requests' ids and secrets. + match stage { + Stage::Pending => Ok(PairStatus::Pending), + Stage::Rejected => Ok(PairStatus::Rejected), + Stage::Approved(approver) => { + let Approver { user, credential, token_hash, signed_in_with } = approver; + if !self.store.credential_live(user.id, credential, &token_hash)? { + let detail = format!("device {device}: the approving sign-in ended"); + let ip = Some(client.ip.as_str()); + self.store.audit(AuditEvent::PairingRejected, Some(user.id), Some(&user.username), ip, &detail); + return Ok(PairStatus::Rejected); + } + let signed_in = self.issue(user, Some(device.clone()), client, Proof::Vouched(signed_in_with))?; + let Issued::DeviceToken(device_token) = signed_in.issued else { + return Err(anyhow::anyhow!("pairing issued a cookie").into()); + }; + let user = signed_in.user; + self.limiter.success(&format!("pair:{}", address_key(&client.ip))); + let detail = format!("device {device}"); + self.store.audit(AuditEvent::Paired, Some(user.id), Some(&user.username), Some(&client.ip), &detail); + Ok(PairStatus::Approved { user, device_token }) + } + } + } + + /// The pending request with the `code` the user typed, and whether it + /// came from the user's address; with `answer`, approves (`true`) or + /// rejects it. + pub fn pairing_by_code( + &self, + principal: &Principal, + code: &str, + answer: Option, + client: &Client, + ) -> Result { + let user = &principal.user; + let key = format!("pair-code:{}", user.id); + self.user_limiter.check(&key, Instant::now()).map_err(AuthError::RateLimited)?; + if answer == Some(true) { + self.require_reauth(principal)?; + } + let decision = answer.map(|approve| approve.then(|| Approver::from(principal))); + // Wrong codes slow the user down; a right one does not undo that, or one + // known code would let them guess on. + let info = self.pairings.find(code, decision).inspect_err(|err| { + if *err == PairingError::UnknownCode { + self.user_limiter.failure(&key, Instant::now()); + } + })?; + let info = PairingInfo { same_address: address_key(&info.ip) == address_key(&client.ip), ..info }; + if let Some(approve) = answer { + let event = if approve { AuditEvent::PairingApproved } else { AuditEvent::PairingRejected }; + let place = if info.same_address { "this address" } else { "elsewhere" }; + let detail = format!("device {} from {} ({place})", info.device_name, info.ip); + self.store.audit(event, Some(user.id), Some(&user.username), Some(&client.ip), &detail); + } + Ok(info) + } +} + +/// Whether a path segment is a pairing code (`KX7-4MP`, `kx74mp`) rather +/// than a request id. +pub fn is_code(text: &str) -> bool { + let code = normalize(text); + code.len() == CODE_LEN && code.bytes().all(|b| ALPHABET.contains(&b)) +} + +fn new_code() -> String { + let mut bytes = [0u8; CODE_LEN]; + OsRng.fill_bytes(&mut bytes); + // 256 is not a multiple of the alphabet's 31 letters; the bias is too small to matter. + bytes.iter().map(|b| ALPHABET[*b as usize % ALPHABET.len()] as char).collect() +} + +/// `kx7 4mp` → `KX74MP`. +fn normalize(code: &str) -> String { + code.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_uppercase()).collect() +} + +/// `KX74MP` → `KX7-4MP`. +fn display(code: &str) -> String { + format!("{}-{}", &code[..CODE_LEN / 2], &code[CODE_LEN / 2..]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn approver() -> Approver { + let user = User { id: 1, username: "me".into(), created_at: 0 }; + Approver { + user, + credential: Credential::Browser(1), + token_hash: [7; 32], + signed_in_with: SignInMethod::Passkey, + } + } + + impl Pairings { + fn expire_all(&self) { + for request in self.requests.lock().values_mut() { + request.expires = Instant::now(); + } + } + } + + #[test] + fn approve_then_collect_once() { + let pairings = Pairings::default(); + let started = pairings.start("laptop".into(), Some("Linux".into()), "10.0.0.2".into()).unwrap(); + assert!(is_code(&started.code) && started.code.as_bytes()[3] == b'-', "{}", started.code); + assert!(!is_code(&started.id)); + assert_eq!(pairings.poll(&started.id, &started.poll_secret), Some((Stage::Pending, "laptop".into()))); + assert_eq!(pairings.poll(&started.id, "wrong"), None); + + let typed = started.code.to_lowercase().replace('-', " "); + let info = pairings.find(&typed, None).unwrap(); + assert_eq!((info.device_name.as_str(), info.ip.as_str()), ("laptop", "10.0.0.2")); + assert_eq!((info.code, info.platform.as_deref()), (started.code.clone(), Some("Linux"))); + pairings.find(&started.code, Some(Some(approver()))).unwrap(); + assert_eq!(pairings.find(&started.code, Some(None)), Err(PairingError::Answered)); + assert_eq!( + pairings.poll(&started.id, &started.poll_secret), + Some((Stage::Approved(approver()), "laptop".into())) + ); + assert_eq!(pairings.poll(&started.id, &started.poll_secret), None, "collected once"); + } + + #[test] + fn rejected_unknown_and_expired() { + let pairings = Pairings::default(); + let started = pairings.start("laptop".into(), None, "ip".into()).unwrap(); + assert_eq!(pairings.find("AAA-AAA", None), Err(PairingError::UnknownCode)); + pairings.find(&started.code, Some(None)).unwrap(); + assert_eq!(pairings.poll(&started.id, &started.poll_secret), Some((Stage::Rejected, "laptop".into()))); + + let late = pairings.start("other".into(), None, "ip".into()).unwrap(); + pairings.expire_all(); + assert_eq!(pairings.find(&late.code, None), Err(PairingError::UnknownCode)); + assert_eq!(pairings.poll(&late.id, &late.poll_secret), None); + } + + #[test] + fn the_approver_learns_whether_the_device_is_where_they_are() { + let auth = Auth::new( + std::sync::Arc::new(crate::store::Store::in_memory()), + crate::bus::Bus::default(), + "https://box.example".into(), + None, + ); + let at = |ip: &str| Client { ip: ip.into(), user_agent: None }; + let started = auth.start_pairing("desk", None, &at("2001:db8:0:1::5")).unwrap(); + let principal = Principal { + user: approver().user, + credential: Credential::Browser(1), + label: "Safari".into(), + renewed: false, + seen_at: 0, + token_hash: [0; 32], + reauth_at: None, + signed_in_with: SignInMethod::Password, + }; + let same = |ip: &str| auth.pairing_by_code(&principal, &started.code, None, &at(ip)).unwrap().same_address; + assert!(same("2001:db8:0:1::9"), "the same /64"); + assert!(!same("2001:db8:0:2::5")); + assert!(!same("10.0.0.1")); + } + + #[test] + fn valid_polls_do_not_reset_the_backoff_on_guesses() { + let auth = Auth::new( + std::sync::Arc::new(crate::store::Store::in_memory()), + crate::bus::Bus::default(), + "https://box.example".into(), + None, + ); + let attacker = Client { ip: "10.0.0.66".into(), user_agent: None }; + let own = auth.start_pairing("mine", None, &attacker).unwrap(); + let mut limited = false; + for _ in 0..4 { + match auth.poll_pairing(&own.id, &own.poll_secret, &attacker) { + Ok(PairStatus::Pending) => {} + Err(AuthError::RateLimited(_)) => limited = true, + other => panic!("{other:?}"), + } + match auth.poll_pairing("guessed-id", "guessed-secret", &attacker) { + Err(AuthError::NotFound(_)) => {} + Err(AuthError::RateLimited(_)) => limited = true, + other => panic!("{other:?}"), + } + } + assert!(limited, "interleaved valid polls kept the guesses free"); + } + + #[test] + fn new_requests_push_out_the_oldest_waiting_ones() { + let pairings = Pairings::default(); + let start = |ip: &str| pairings.start("d".into(), None, ip.into()).unwrap(); + let first = start("2001:db8::1"); + for _ in 1..MAX_PER_ADDRESS { + start("2001:db8::2"); + } + let mine = start("10.0.0.1"); + start("2001:db8::3"); + assert_eq!(pairings.find(&first.code, None), Err(PairingError::UnknownCode), "one /64 keeps four"); + assert!(pairings.find(&mine.code, None).is_ok(), "others' requests stay"); + + let approved = start("10.0.0.2"); + pairings.find(&approved.code, Some(Some(approver()))).unwrap(); + for i in 0..2 * MAX_PENDING { + start(&format!("10.1.{}.{}", i / 250, i % 250)); + } + assert_eq!(pairings.requests.lock().len(), MAX_PENDING); + assert!(pairings.find(&mine.code, None).is_err(), "pushed out by newer ones"); + let kept = pairings.requests.lock().contains_key(&approved.id); + assert!(kept, "an approved request waits for its device"); + + let mut requests = pairings.requests.lock(); + for request in requests.values_mut() { + request.stage = Stage::Rejected; + } + drop(requests); + assert_eq!(pairings.start("d".into(), None, "ip".into()).unwrap_err(), PairingError::Full); + } +} diff --git a/crates/redshell-server/src/auth/passkeys.rs b/crates/redshell-server/src/auth/passkeys.rs new file mode 100644 index 0000000..ee24087 --- /dev/null +++ b/crates/redshell-server/src/auth/passkeys.rs @@ -0,0 +1,574 @@ +//! WebAuthn ceremonies for passkeys, on `webauthn-rs`. +//! +//! The relying party is `server.public_url`: its host is the RP ID and the +//! URL the only accepted origin. Passkeys need a secure context, so they +//! are off unless that URL is `https`, or `http://localhost` for +//! development. +//! +//! A ceremony lasts [`CEREMONY_TTL`] and is finished at most once. +//! Registration asks for a discoverable credential, so a sign-in needs no +//! name: the authenticator says whose passkey it is. +//! +//! Starting a sign-in needs no account, so it must cost the server nothing +//! that strangers could use up: its state goes to the client inside the +//! ceremony id, signed with a key the server makes at start (HMAC-SHA256) +//! and with its expiry, and only finished sign-ins are remembered, until +//! they expire, so none is finished twice. A registration's state stays on +//! the server under a random id, bound to the browser or device that +//! started it; each holds a few (its oldest goes first), and when all +//! places are taken the oldest of anyone's goes. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use hmac::{Hmac, Mac as _}; +use parking_lot::Mutex; +use rand_core::{OsRng, RngCore as _}; +use redshell_protocol::{PasskeyChallenge, PasskeySignInRequest, RegisterPasskeyRequest, User}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::Sha256; +use webauthn_rs::prelude::{ + AuthenticationResult, CredentialID, DiscoverableAuthentication, Passkey, PasskeyAuthentication, + PasskeyRegistration, PublicKeyCredential, RegisterPublicKeyCredential, Url, Uuid, Webauthn, WebauthnBuilder, +}; +use webauthn_rs_proto::ResidentKeyRequirement; + +use super::{Auth, AuthError, Client, Principal, Proof, SignedIn, device_name, ip_key, secret, user_agent}; +use crate::bus::BusEvent; +use crate::now_ms; +use crate::store::{AuditEvent, Credential, Removal, SignInMethod}; + +/// How long a ceremony can be finished. +const CEREMONY_TTL: Duration = Duration::from_secs(5 * 60); + +/// Ceremonies of one kind in flight, each with who started it: a client +/// address or a credential. +struct Ceremonies { + map: Mutex>>, + /// Live ceremonies one starter holds; its oldest goes first. + per_starter: usize, + /// Live ceremonies in all. + total: usize, +} + +struct Ceremony { + state: S, + starter: String, + expires: Instant, +} + +impl Ceremonies { + fn new(per_starter: usize, total: usize) -> Self { + Self { map: Mutex::new(HashMap::new()), per_starter, total } + } + + /// Keeps `state` under a new id, making room by dropping the starter's + /// oldest ceremony, or anyone's when every place is taken. + fn insert(&self, starter: String, state: S) -> String { + let now = Instant::now(); + let mut map = self.map.lock(); + map.retain(|_, c| c.expires > now); + let oldest = |map: &HashMap>, mine: bool| { + let candidates = map.iter().filter(|(_, c)| !mine || c.starter == starter); + candidates.min_by_key(|(_, c)| c.expires).map(|(id, _)| id.clone()) + }; + if map.values().filter(|c| c.starter == starter).count() >= self.per_starter + && let Some(id) = oldest(&map, true) + { + map.remove(&id); + } + if map.len() >= self.total + && let Some(id) = oldest(&map, false) + { + map.remove(&id); + } + let id = secret::new_token(); + map.insert(id.clone(), Ceremony { state, starter, expires: now + CEREMONY_TTL }); + id + } + + /// The live ceremony `id` and who started it, removed: each is used once. + fn take(&self, id: &str) -> Option<(S, String)> { + let ceremony = self.map.lock().remove(id)?; + (ceremony.expires > Instant::now()).then_some((ceremony.state, ceremony.starter)) + } +} + +/// Sign-in ceremonies: signed state handed to the client, and those +/// finished, until they expire. +struct SignIns { + key: [u8; 32], + finished: Mutex>, +} + +/// What a sign-in ceremony id carries, before its signature. +#[derive(Serialize, Deserialize)] +struct SignInState { + state: DiscoverableAuthentication, + /// Unix ms. + expires_at: i64, +} + +impl SignIns { + fn new() -> Self { + let mut key = [0u8; 32]; + OsRng.fill_bytes(&mut key); + Self { key, finished: Mutex::default() } + } + + fn mac(&self) -> Hmac { + Hmac::new_from_slice(&self.key).expect("HMAC takes a key of any length") + } + + /// The ceremony id for `state`: `.`, base64url. + fn seal(&self, state: DiscoverableAuthentication) -> serde_json::Result { + let expires_at = now_ms() + CEREMONY_TTL.as_millis() as i64; + let body = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&SignInState { state, expires_at })?); + let mut mac = self.mac(); + mac.update(body.as_bytes()); + Ok(format!("{body}.{}", URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()))) + } + + /// The state of a ceremony this server started that has not expired or + /// been finished. + fn open(&self, ceremony: &str) -> Result { + let (body, signature) = ceremony.split_once('.').ok_or(CeremonyError::Unknown)?; + let signature = URL_SAFE_NO_PAD.decode(signature).map_err(|_| CeremonyError::Unknown)?; + let mut mac = self.mac(); + mac.update(body.as_bytes()); + mac.verify_slice(&signature).map_err(|_| CeremonyError::Unknown)?; + let json = URL_SAFE_NO_PAD.decode(body).map_err(|_| CeremonyError::Unknown)?; + let sealed: SignInState = serde_json::from_slice(&json).map_err(|_| CeremonyError::Unknown)?; + let finished = self.finished.lock().contains_key(&secret::token_hash(ceremony)); + if sealed.expires_at <= now_ms() || finished { + return Err(CeremonyError::Unknown); + } + Ok(sealed.state) + } + + /// Records a ceremony as finished; `false` when it was already. + fn finish(&self, ceremony: &str) -> bool { + let now = now_ms(); + let mut finished = self.finished.lock(); + finished.retain(|_, expires| *expires > now); + let expires = now + CEREMONY_TTL.as_millis() as i64; + finished.insert(secret::token_hash(ceremony), expires).is_none() + } +} + +/// Why a ceremony did not complete. +#[derive(Debug, thiserror::Error)] +pub enum CeremonyError { + #[error("the passkey request expired or was used already; try again")] + Unknown, + #[error("the browser's answer could not be read")] + Malformed, + #[error("the passkey was not accepted")] + Rejected, +} + +/// A started ceremony: its id, and the options for +/// `navigator.credentials.create()` or `.get()`. +pub struct Challenge { + pub ceremony: String, + pub options: Value, +} + +/// The server's relying party and the ceremonies in flight. +pub struct Passkeys { + webauthn: Webauthn, + registrations: Ceremonies>, + /// Re-authentications, bound like registrations to who started them. + reauths: Ceremonies>, + sign_ins: SignIns, +} + +impl Passkeys { + /// The relying party for `public_origin` (scheme, host and port); an + /// error says why passkeys are off for it. + pub fn new(public_origin: Option<&str>) -> Result { + const NEEDS: &str = + "passkeys need server.public_url set to an https URL (or http://localhost while developing)"; + let origin = Url::parse(public_origin.ok_or(NEEDS)?).map_err(|_| NEEDS)?; + let host = origin.host_str().ok_or(NEEDS)?.to_owned(); + let secure = origin.scheme() == "https" || (origin.scheme() == "http" && host == "localhost"); + if !secure || host.parse::().is_ok() || host.starts_with('[') { + return Err(NEEDS.into()); + } + let webauthn = WebauthnBuilder::new(&host, &origin) + .and_then(|b| b.rp_name("RedShell").timeout(CEREMONY_TTL).build()) + .map_err(|err| format!("passkeys: {err}"))?; + Ok(Self { + webauthn, + registrations: Ceremonies::new(4, 256), + reauths: Ceremonies::new(4, 256), + sign_ins: SignIns::new(), + }) + } + + /// Starts registering a passkey for the user with WebAuthn id `user`, + /// from the browser or device `by`. `existing` passkeys are excluded, so + /// an authenticator is not registered twice. + pub fn start_registration( + &self, + user: Uuid, + username: &str, + by: Credential, + existing: Vec, + ) -> anyhow::Result { + let exclude = (!existing.is_empty()).then_some(existing); + let (mut options, state) = self.webauthn.start_passkey_registration(user, username, username, exclude)?; + // Discoverable, so that signing in needs no name. + if let Some(selection) = options.public_key.authenticator_selection.as_mut() { + selection.resident_key = Some(ResidentKeyRequirement::Required); + selection.require_resident_key = true; + } + let id = self.registrations.insert(starter(by), Box::new(state)); + Ok(Challenge { ceremony: id, options: serde_json::to_value(options)? }) + } + + /// Finishes a registration started by `by`; the new passkey. + pub fn finish_registration(&self, ceremony: &str, by: Credential, answer: Value) -> Result { + let state = match self.registrations.take(ceremony) { + Some((state, started_by)) if started_by == starter(by) => state, + _ => return Err(CeremonyError::Unknown), + }; + let answer: RegisterPublicKeyCredential = + serde_json::from_value(answer).map_err(|_| CeremonyError::Malformed)?; + self.webauthn.finish_passkey_registration(&answer, &state).map_err(|err| { + log::info!("passkey registration refused: {err}"); + CeremonyError::Rejected + }) + } + + /// Starts a re-authentication of `by` with one of `passkeys`, the + /// user's own. + pub fn start_reauth(&self, by: Credential, passkeys: &[Passkey]) -> anyhow::Result { + let (options, state) = self.webauthn.start_passkey_authentication(passkeys)?; + let id = self.reauths.insert(starter(by), Box::new(state)); + Ok(Challenge { ceremony: id, options: serde_json::to_value(options)? }) + } + + /// Checks the answer to a re-authentication `by` started. + pub fn finish_reauth( + &self, + ceremony: &str, + by: Credential, + answer: Value, + ) -> Result { + let state = match self.reauths.take(ceremony) { + Some((state, started_by)) if started_by == starter(by) => state, + _ => return Err(CeremonyError::Unknown), + }; + let answer: PublicKeyCredential = serde_json::from_value(answer).map_err(|_| CeremonyError::Malformed)?; + self.webauthn.finish_passkey_authentication(&answer, &state).map_err(|err| { + log::info!("passkey re-authentication refused: {err}"); + CeremonyError::Rejected + }) + } + + /// Starts a sign-in with any passkey of this server. + pub fn start_sign_in(&self) -> anyhow::Result { + let (mut options, state) = self.webauthn.start_discoverable_authentication()?; + // webauthn-rs asks for conditional mediation (autofill); the sign-in button wants the + // browser's dialog. A client that autofills sets `mediation` itself. + options.mediation = None; + Ok(Challenge { ceremony: self.sign_ins.seal(state)?, options: serde_json::to_value(options)? }) + } + + /// Reads a sign-in answer: the answer, the WebAuthn id of the user it + /// claims and the credential id, for looking up the stored passkey. + pub fn identify(&self, answer: Value) -> Result<(PublicKeyCredential, Uuid, Vec), CeremonyError> { + let answer: PublicKeyCredential = serde_json::from_value(answer).map_err(|_| CeremonyError::Malformed)?; + let (user, credential) = + self.webauthn.identify_discoverable_authentication(&answer).map_err(|_| CeremonyError::Malformed)?; + let credential = credential.to_vec(); + Ok((answer, user, credential)) + } + + /// Checks a sign-in answer against the stored `passkey`, and updates + /// the passkey's counters. `true` when they changed and need saving. + pub fn finish_sign_in( + &self, + ceremony: &str, + answer: &PublicKeyCredential, + passkey: &mut Passkey, + ) -> Result { + let state = self.sign_ins.open(ceremony)?; + let result = self.webauthn.finish_discoverable_authentication_v2(answer, state, &*passkey).map_err(|err| { + log::info!("passkey sign-in refused: {err}"); + CeremonyError::Rejected + })?; + if !self.sign_ins.finish(ceremony) { + return Err(CeremonyError::Unknown); + } + Ok(passkey.update_credential(&result) == Some(true)) + } +} + +/// Who started a registration, as ceremonies record it. +fn starter(credential: Credential) -> String { + format!("{credential:?}") +} + +impl Auth { + /// The relying party, or why passkeys are off on this server. + pub(super) fn relying_party(&self) -> Result<&Passkeys, AuthError> { + self.passkeys.as_ref().map_err(|why| AuthError::Unavailable(why.clone())) + } + + pub fn passkeys_available(&self) -> bool { + self.passkeys.is_ok() + } + + /// Starts a sign-in with any passkey. Open to everyone and free: the + /// backoff applies when the answer comes. + pub fn start_passkey_sign_in(&self) -> Result { + Ok(self.relying_party()?.start_sign_in()?.into()) + } + + /// Signs in with a passkey: a cookie, or a device token with a name. + pub fn passkey_sign_in(&self, req: PasskeySignInRequest, client: &Client) -> Result { + let passkeys = self.relying_party()?; + let key = ip_key(client); + self.limiter.check(&key, Instant::now()).map_err(AuthError::RateLimited)?; + let device = req.device_name.as_deref().map(device_name).transpose()?; + let user = match self.check_passkey(passkeys, &req) { + Ok(user) => user, + Err(err) => { + self.limiter.failure(&key, Instant::now()); + self.store.audit(AuditEvent::SignInFailed, None, None, Some(&client.ip), &format!("passkey: {err}")); + return Err(match err { + PasskeyFailure::Ceremony(err) => AuthError::PasskeyRejected(err.to_string()), + PasskeyFailure::Internal(err) => AuthError::Internal(err), + }); + } + }; + self.limiter.success(&key); + let detail = + device.as_deref().map_or_else(|| "passkey, browser".to_owned(), |d| format!("passkey, device {d}")); + self.store.audit(AuditEvent::SignIn, Some(user.id), Some(&user.username), Some(&client.ip), &detail); + self.issue(user, device, client, Proof::Own(SignInMethod::Passkey)) + } + + /// The user whose stored passkey made the sign-in answer. + fn check_passkey(&self, passkeys: &Passkeys, req: &PasskeySignInRequest) -> Result { + let (answer, user_handle, credential_id) = passkeys.identify(req.credential.clone())?; + let stored = self.store.find_passkey(&credential_id)?; + let Some(stored) = stored.filter(|s| s.webauthn_id == user_handle.as_bytes()) else { + return Err(CeremonyError::Rejected.into()); + }; + let mut passkey: Passkey = serde_json::from_str(&stored.credential).map_err(anyhow::Error::from)?; + let changed = passkeys.finish_sign_in(&req.ceremony, &answer, &mut passkey)?; + let updated = changed.then(|| serde_json::to_string(&passkey)).transpose().map_err(anyhow::Error::from)?; + self.store.passkey_used(stored.id, updated.as_deref())?; + Ok(stored.user) + } + + /// Starts registering a passkey for the signed-in user, who + /// re-authenticated recently. + pub fn start_passkey_registration(&self, principal: &Principal) -> Result { + let passkeys = self.relying_party()?; + self.require_reauth(principal)?; + let user = &principal.user; + let handle = Uuid::from_slice(&self.store.webauthn_id(user.id)?).map_err(anyhow::Error::from)?; + let existing = self.store.passkey_credential_ids(user.id)?; + Ok(passkeys.start_registration(handle, &user.username, principal.credential, existing)?.into()) + } + + /// Finishes registering a passkey, started by the same browser or device. + pub fn register_passkey( + &self, + principal: &Principal, + req: RegisterPasskeyRequest, + client: &Client, + ) -> Result { + let passkeys = self.relying_party()?; + let name = match req.name.as_deref() { + Some(name) => passkey_name(name)?, + None => user_agent::describe(client.user_agent.as_deref()), + }; + let passkey = passkeys + .finish_registration(&req.ceremony, principal.credential, req.credential) + .map_err(|err| AuthError::BadRequest(err.to_string()))?; + let credential = serde_json::to_string(&passkey).map_err(anyhow::Error::from)?; + let user = &principal.user; + let added = self + .store + .add_passkey(user.id, passkey.cred_id().as_ref(), &name, &credential)? + .ok_or_else(|| AuthError::Conflict("this passkey is registered already".into()))?; + self.store.audit(AuditEvent::PasskeyAdded, Some(user.id), Some(&user.username), Some(&client.ip), &name); + Ok(added) + } + + pub fn rename_passkey( + &self, + principal: &Principal, + id: i64, + name: &str, + ) -> Result { + let name = passkey_name(name)?; + self.store + .rename_passkey(principal.user.id, id, &name)? + .ok_or_else(|| AuthError::NotFound("no such passkey".into())) + } + + /// Revokes a passkey. The last one of a passkey-only user is refused: + /// they would be locked out (turn passkey-only off first). + pub fn revoke_passkey(&self, principal: &Principal, id: i64, client: &Client) -> Result<(), AuthError> { + self.require_reauth(principal)?; + let user = &principal.user; + match self.store.remove_passkey(user.id, id)? { + Removal::Done => { + let detail = format!("passkey {id}"); + self.store.audit( + AuditEvent::PasskeyRemoved, + Some(user.id), + Some(&user.username), + Some(&client.ip), + &detail, + ); + Ok(()) + } + Removal::NotFound => Err(AuthError::NotFound("no such passkey".into())), + Removal::LastOfPasskeyOnly => Err(AuthError::Conflict( + "this is your last passkey and you sign in with passkeys only: turn that off first".into(), + )), + } + } + + /// Turns passkey-only sign-in on (needs a passkey) or off. Turning it + /// on ends the user's other sign-ins made with the password, devices + /// paired from one included: the password no longer gets anyone in. + pub fn set_passkey_only(&self, principal: &Principal, on: bool, client: &Client) -> Result<(), AuthError> { + self.require_reauth(principal)?; + let user = &principal.user; + if !self.store.set_passkey_only(user.id, on)? { + return Err(AuthError::Conflict("add a passkey before turning password sign-in off".into())); + } + let detail = match on { + true => { + let ended = self.store.revoke_password_sign_ins(user.id, principal.credential)?; + for credential in &ended { + self.bus.send(BusEvent::Revoked(*credential)); + } + format!("on; {} password sign-in(s) ended", ended.len()) + } + false => "off".to_owned(), + }; + self.store.audit(AuditEvent::PasskeyOnly, Some(user.id), Some(&user.username), Some(&client.ip), &detail); + Ok(()) + } +} + +/// Why a passkey sign-in failed. +#[derive(Debug, thiserror::Error)] +enum PasskeyFailure { + #[error(transparent)] + Ceremony(#[from] CeremonyError), + #[error(transparent)] + Internal(#[from] anyhow::Error), +} + +impl From for PasskeyChallenge { + fn from(challenge: Challenge) -> Self { + Self { ceremony: challenge.ceremony, options: challenge.options } + } +} + +/// A passkey's name, trimmed: 1 to 64 characters. +fn passkey_name(name: &str) -> Result { + let name = name.trim(); + if (1..=64).contains(&name.chars().count()) && !name.chars().any(char::is_control) { + Ok(name.to_owned()) + } else { + Err(AuthError::BadRequest("a passkey's name has 1 to 64 characters".into())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn full_ceremonies_make_room_and_sign_ins_store_nothing() { + let ceremonies = Ceremonies::new(2, 3); + let first = ceremonies.insert("a".into(), 1); + let second = ceremonies.insert("a".into(), 2); + ceremonies.insert("a".into(), 3); + assert!(ceremonies.take(&first).is_none(), "the starter's oldest made room"); + ceremonies.insert("b".into(), 4); + ceremonies.insert("c".into(), 5); + assert!(ceremonies.take(&second).is_none(), "full: the oldest of anyone's made room"); + assert_eq!(ceremonies.map.lock().len(), 3); + + let passkeys = Passkeys::new(Some("https://box.example")).unwrap(); + let me = Credential::Browser(1); + let registration = passkeys.start_registration(Uuid::new_v4(), "me", me, Vec::new()).unwrap(); + for _ in 0..600 { + passkeys.start_sign_in().unwrap(); + } + assert!(passkeys.sign_ins.finished.lock().is_empty()); + let err = passkeys.finish_registration(®istration.ceremony, me, Value::Null).unwrap_err(); + assert!(matches!(err, CeremonyError::Malformed), "a flood of sign-ins left the registration alone"); + } + + #[test] + fn sign_in_ceremonies_are_signed_expire_and_finish_once() { + let passkeys = Passkeys::new(Some("https://box.example")).unwrap(); + let ceremony = passkeys.start_sign_in().unwrap().ceremony; + assert!(passkeys.sign_ins.open(&ceremony).is_ok()); + let (body, signature) = ceremony.split_once('.').unwrap(); + let mut forged = URL_SAFE_NO_PAD.decode(body).unwrap(); + forged[10] ^= 1; + let forged = format!("{}.{signature}", URL_SAFE_NO_PAD.encode(forged)); + assert!(passkeys.sign_ins.open(&forged).is_err(), "changed state"); + let elsewhere = Passkeys::new(Some("https://box.example")).unwrap(); + assert!(elsewhere.sign_ins.open(&ceremony).is_err(), "another server's (or run's) key"); + + let state = passkeys.sign_ins.open(&ceremony).unwrap(); + let expired = SignInState { state, expires_at: now_ms() - 1 }; + let body = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&expired).unwrap()); + let mut mac = passkeys.sign_ins.mac(); + mac.update(body.as_bytes()); + let expired = format!("{body}.{}", URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes())); + assert!(passkeys.sign_ins.open(&expired).is_err(), "expired"); + + assert!(passkeys.sign_ins.finish(&ceremony)); + assert!(passkeys.sign_ins.open(&ceremony).is_err(), "finished"); + assert!(!passkeys.sign_ins.finish(&ceremony)); + } + + #[test] + fn only_secure_origins_with_a_name() { + assert!(Passkeys::new(Some("https://box.tailnet.ts.net")).is_ok()); + assert!(Passkeys::new(Some("http://localhost:4747")).is_ok()); + for refused in [None, Some("http://box.lan"), Some("https://10.0.0.2"), Some("http://127.0.0.1:4747")] { + let err = Passkeys::new(refused).err().unwrap(); + assert!(err.contains("server.public_url"), "{refused:?}: {err}"); + } + } + + #[test] + fn registration_asks_for_a_discoverable_passkey_and_ceremonies_are_single_use() { + let passkeys = Passkeys::new(Some("https://box.example")).unwrap(); + let me = Credential::Browser(1); + let challenge = passkeys.start_registration(Uuid::new_v4(), "me", me, Vec::new()).unwrap(); + let selection = &challenge.options["publicKey"]["authenticatorSelection"]; + assert_eq!(selection["residentKey"], "required"); + assert_eq!(challenge.options["publicKey"]["rp"]["id"], "box.example"); + + let other = Credential::Browser(2); + let err = passkeys.finish_registration(&challenge.ceremony, other, Value::Null).unwrap_err(); + assert!(matches!(err, CeremonyError::Unknown), "bound to the browser that started it"); + let err = passkeys.finish_registration(&challenge.ceremony, me, Value::Null).unwrap_err(); + assert!(matches!(err, CeremonyError::Unknown), "the failed attempt used it up"); + + let sign_in = passkeys.start_sign_in().unwrap(); + assert!(sign_in.options.get("mediation").is_none()); + assert_eq!(sign_in.options["publicKey"]["userVerification"], "required"); + } +} diff --git a/crates/redshell-server/src/auth/password.rs b/crates/redshell-server/src/auth/password.rs new file mode 100644 index 0000000..8bb3ae6 --- /dev/null +++ b/crates/redshell-server/src/auth/password.rs @@ -0,0 +1,76 @@ +//! Argon2id password hashes (PHC strings), computed off the async workers. + +use std::sync::LazyLock; + +use argon2::Argon2; +use argon2::password_hash::{PasswordHash, PasswordHasher as _, PasswordVerifier as _, SaltString}; +use rand_core::OsRng; + +/// Shortest password accepted. +pub const MIN_LENGTH: usize = 10; +/// Longest password hashed, so a huge body cannot keep a CPU busy. +pub const MAX_LENGTH: usize = 1024; + +/// Checked against when the user does not exist, so an unknown name takes +/// as long as a wrong password. +static DUMMY_HASH: LazyLock = LazyLock::new(|| hash_now("not a real password").unwrap_or_default()); + +/// Why a new password is refused, if it is. +pub fn check_new(password: &str) -> Result<(), String> { + let length = password.chars().count(); + if length < MIN_LENGTH { + Err(format!("the password needs at least {MIN_LENGTH} characters")) + } else if password.len() > MAX_LENGTH { + Err(format!("the password can have at most {MAX_LENGTH} bytes")) + } else { + Ok(()) + } +} + +/// Argon2id with the crate's defaults (19 MiB, 2 passes), as OWASP advises. +fn hash_now(password: &str) -> anyhow::Result { + let salt = SaltString::generate(&mut OsRng); + Ok(Argon2::default().hash_password(password.as_bytes(), &salt).map_err(anyhow::Error::msg)?.to_string()) +} + +fn verify_now(password: &str, hash: &str) -> bool { + password.len() <= MAX_LENGTH + && PasswordHash::new(hash) + .is_ok_and(|parsed| Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok()) +} + +pub async fn hash(password: String) -> anyhow::Result { + tokio::task::spawn_blocking(move || hash_now(&password)).await? +} + +/// Verifies `password` against `hash`, or against a dummy hash when there +/// is no user, which always fails but costs the same. +pub async fn verify(password: String, hash: Option) -> bool { + tokio::task::spawn_blocking(move || { + let ok = verify_now(&password, hash.as_deref().unwrap_or(&DUMMY_HASH)); + ok && hash.is_some() + }) + .await + .unwrap_or(false) +} + +/// For the CLI, which has no runtime. +pub fn hash_blocking(password: &str) -> anyhow::Result { + hash_now(password) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn hashes_verify_and_unknown_users_fail() { + let h = hash("correct horse".into()).await.unwrap(); + assert!(h.starts_with("$argon2id$")); + assert!(verify("correct horse".into(), Some(h.clone())).await); + assert!(!verify("wrong horse".into(), Some(h)).await); + assert!(!verify("not a real password".into(), None).await); + assert!(check_new("short").is_err()); + assert!(check_new("long enough").is_ok()); + } +} diff --git a/crates/redshell-server/src/auth/queue.rs b/crates/redshell-server/src/auth/queue.rs new file mode 100644 index 0000000..64d1890 --- /dev/null +++ b/crates/redshell-server/src/auth/queue.rs @@ -0,0 +1,73 @@ +//! Password checks take turns: one Argon2 hash at a time per queue (each +//! takes 19 MiB, and a burst of guesses must meet the backoff the guess +//! before earned). A queue with too many waiting turns newcomers away at +//! once, so a flood cannot hold the server's memory and tasks. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use tokio::sync::{Semaphore, SemaphorePermit}; + +use super::AuthError; + +/// What a client turned away is told to wait. +const BUSY_RETRY: Duration = Duration::from_secs(2); + +pub struct PasswordQueue { + turn: Semaphore, + waiting: AtomicUsize, + max_waiting: usize, +} + +impl PasswordQueue { + pub fn new(max_waiting: usize) -> Self { + Self { turn: Semaphore::new(1), waiting: AtomicUsize::new(0), max_waiting } + } + + /// Waits for this caller's turn, held until the permit drops; refused + /// (`rate_limited`) while `max_waiting` callers wait already. + pub async fn enter(&self) -> Result, AuthError> { + if self.waiting.fetch_add(1, Ordering::AcqRel) >= self.max_waiting { + self.waiting.fetch_sub(1, Ordering::AcqRel); + return Err(AuthError::RateLimited(BUSY_RETRY)); + } + // Counted out on every exit, a caller that gave up waiting too. + let _waiting = Waiting(&self.waiting); + Ok(self.turn.acquire().await.map_err(anyhow::Error::from)?) + } +} + +struct Waiting<'a>(&'a AtomicUsize); + +impl Drop for Waiting<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::AcqRel); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[tokio::test] + async fn a_full_queue_turns_newcomers_away() { + let queue = Arc::new(PasswordQueue::new(2)); + let turn = queue.enter().await.unwrap(); + let waiters: Vec<_> = (0..2) + .map(|_| { + let queue = queue.clone(); + tokio::spawn(async move { queue.enter().await.map(drop).is_ok() }) + }) + .collect(); + while queue.waiting.load(Ordering::Acquire) < 2 { + tokio::task::yield_now().await; + } + assert!(matches!(queue.enter().await, Err(AuthError::RateLimited(_)))); + drop(turn); + for waiter in waiters { + assert!(waiter.await.unwrap(), "those in line get their turn"); + } + assert!(queue.enter().await.is_ok()); + } +} diff --git a/crates/redshell-server/src/auth/reauth.rs b/crates/redshell-server/src/auth/reauth.rs new file mode 100644 index 0000000..dde194f --- /dev/null +++ b/crates/redshell-server/src/auth/reauth.rs @@ -0,0 +1,114 @@ +//! Re-authentication: a signed-in browser or device proves again who it is +//! before a change that could hand the account to whoever holds a stolen +//! or forgotten session: adding or removing a passkey, turning +//! passkey-only sign-in on or off, approving a pairing, signing out another +//! browser or device, and changing the password of a passkey-only account. +//! +//! Signing in with a password or a passkey counts, as does `POST +//! /api/auth/reauth` with either; each holds for [`REAUTH_TTL`]. A device +//! that was paired has proved nothing itself, so it starts without one. +//! The password does not count for a passkey-only account. + +use std::time::{Duration, Instant}; + +use redshell_protocol::{PasskeyChallenge, ReauthRequest, ReauthResponse}; +use serde_json::Value; +use webauthn_rs::prelude::Passkey; + +use super::{Auth, AuthError, Client, Principal, password, user_key}; +use crate::now_ms; +use crate::store::AuditEvent; + +/// How long a re-authentication holds. +pub const REAUTH_TTL: Duration = Duration::from_secs(5 * 60); + +impl Principal { + /// Until when its last re-authentication holds, if it still does. + pub fn reauth_expires_at(&self) -> Option { + self.reauth_at.map(|at| at + REAUTH_TTL.as_millis() as i64).filter(|until| *until > now_ms()) + } +} + +impl Auth { + /// `reauth_required` unless `principal` re-authenticated recently. + pub(super) fn require_reauth(&self, principal: &Principal) -> Result<(), AuthError> { + principal.reauth_expires_at().map(drop).ok_or(AuthError::ReauthRequired) + } + + /// Checks the password or passkey answer again and stamps the sign-in. + /// Failures count against the user's backoff like a wrong password. + pub async fn reauth( + &self, + principal: &Principal, + req: ReauthRequest, + client: &Client, + ) -> Result { + let user = &principal.user; + let key = user_key(&user.username); + self.user_limiter.check(&key, Instant::now()).map_err(AuthError::RateLimited)?; + let checked = match req { + ReauthRequest::Password { password } => self.password_again(principal, password).await, + ReauthRequest::Passkey { ceremony, credential } => self.passkey_again(principal, &ceremony, credential), + }; + let ip = Some(client.ip.as_str()); + match checked { + Ok(method) => { + let now = now_ms(); + self.store.stamp_reauth(principal.credential, now)?; + self.store.audit(AuditEvent::Reauthenticated, Some(user.id), Some(&user.username), ip, method); + Ok(ReauthResponse { reauth_expires_at: now + REAUTH_TTL.as_millis() as i64 }) + } + Err(err @ (AuthError::InvalidCredentials | AuthError::PasskeyRejected(_))) => { + self.user_limiter.failure(&key, Instant::now()); + let detail = err.to_string(); + self.store.audit(AuditEvent::ReauthFailed, Some(user.id), Some(&user.username), ip, &detail); + Err(err) + } + Err(err) => Err(err), + } + } + + async fn password_again(&self, principal: &Principal, password: String) -> Result<&'static str, AuthError> { + let _turn = self.account_checks.enter().await?; + let record = self.store.user_by_id(principal.user.id)?.ok_or(AuthError::InvalidCredentials)?; + if record.passkey_only { + return Err(AuthError::PasskeyRequired); + } + if password::verify(password, Some(record.password_hash)).await { + Ok("password") + } else { + Err(AuthError::InvalidCredentials) + } + } + + fn passkey_again(&self, principal: &Principal, ceremony: &str, answer: Value) -> Result<&'static str, AuthError> { + let result = self + .relying_party()? + .finish_reauth(ceremony, principal.credential, answer) + .map_err(|err| AuthError::PasskeyRejected(err.to_string()))?; + let stored = self.store.find_passkey(result.cred_id().as_ref())?; + let stored = stored + .filter(|s| s.user.id == principal.user.id) + .ok_or_else(|| AuthError::PasskeyRejected("that passkey is not one of this account's".into()))?; + let mut passkey: Passkey = serde_json::from_str(&stored.credential).map_err(anyhow::Error::from)?; + let changed = passkey.update_credential(&result) == Some(true); + let updated = changed.then(|| serde_json::to_string(&passkey)).transpose().map_err(anyhow::Error::from)?; + self.store.passkey_used(stored.id, updated.as_deref())?; + Ok("passkey") + } + + /// A challenge for one of the user's passkeys, to re-authenticate with. + pub fn start_passkey_reauth(&self, principal: &Principal) -> Result { + let relying_party = self.relying_party()?; + let passkeys = self.store.passkey_credentials(principal.user.id)?; + let passkeys: Vec = passkeys + .iter() + .map(|json| serde_json::from_str(json)) + .collect::>() + .map_err(anyhow::Error::from)?; + if passkeys.is_empty() { + return Err(AuthError::Conflict("this account has no passkey; use the password".into())); + } + Ok(relying_party.start_reauth(principal.credential, &passkeys)?.into()) + } +} diff --git a/crates/redshell-server/src/auth/secret.rs b/crates/redshell-server/src/auth/secret.rs new file mode 100644 index 0000000..795bb5c --- /dev/null +++ b/crates/redshell-server/src/auth/secret.rs @@ -0,0 +1,42 @@ +//! Random tokens and their hashes. + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use rand_core::{OsRng, RngCore as _}; +use sha2::{Digest as _, Sha256}; + +/// A fresh random token: 256 bits, base64url (43 characters). +pub fn new_token() -> String { + random_string(32) +} + +/// `bytes` random bytes as base64url. +pub fn random_string(bytes: usize) -> String { + let mut buf = vec![0u8; bytes]; + OsRng.fill_bytes(&mut buf); + URL_SAFE_NO_PAD.encode(buf) +} + +/// SHA-256 of a token: what the database keeps. +pub fn token_hash(token: &str) -> [u8; 32] { + Sha256::digest(token.as_bytes()).into() +} + +/// Compares two secrets without leaking where they differ: their hashes are +/// compared instead of the secrets themselves. +pub fn same_secret(a: &str, b: &str) -> bool { + token_hash(a) == token_hash(b) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tokens_are_long_and_distinct() { + let (a, b) = (new_token(), new_token()); + assert_eq!(a.len(), 43); + assert_ne!(a, b); + assert!(same_secret(&a, &a.clone()) && !same_secret(&a, &b)); + } +} diff --git a/crates/redshell-server/src/auth/user_agent.rs b/crates/redshell-server/src/auth/user_agent.rs new file mode 100644 index 0000000..e148662 --- /dev/null +++ b/crates/redshell-server/src/auth/user_agent.rs @@ -0,0 +1,83 @@ +//! A readable name for a browser from its `User-Agent`: "Safari on +//! iPhone", "Chrome on Windows". It names browser sessions in the account +//! list and says who answered an approval. Only the common browsers and +//! systems are told apart; anything else is "Browser". + +/// Browser markers, most specific first: Edge, Opera and Samsung Internet +/// also claim Chrome and Safari, and Chrome claims Safari. +const BROWSERS: [(&str, &str); 9] = [ + ("Edg", "Edge"), + ("OPR/", "Opera"), + ("SamsungBrowser/", "Samsung Internet"), + ("Firefox/", "Firefox"), + ("FxiOS/", "Firefox"), + ("CriOS/", "Chrome"), + ("Chrome/", "Chrome"), + ("Chromium/", "Chromium"), + ("Safari/", "Safari"), +]; + +/// System markers, most specific first: iPhones and Android also claim +/// "like Mac OS X" and Linux. +const SYSTEMS: [(&str, &str); 7] = [ + ("iPhone", "iPhone"), + ("iPad", "iPad"), + ("Android", "Android"), + ("CrOS", "ChromeOS"), + ("Windows", "Windows"), + ("Macintosh", "Mac"), + ("Linux", "Linux"), +]; + +/// "Safari on iPhone", "Firefox", "Browser on Linux", or "Browser". +pub fn describe(user_agent: Option<&str>) -> String { + let ua = user_agent.unwrap_or_default(); + let find = |table: &[(&str, &'static str)]| table.iter().find(|(marker, _)| ua.contains(marker)).map(|(_, n)| *n); + let browser = find(&BROWSERS).unwrap_or("Browser"); + match find(&SYSTEMS) { + Some(system) => format!("{browser} on {system}"), + None => browser.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_common_browsers() { + let cases = [ + ( + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) \ + Version/18.1 Mobile/15E148 Safari/604.1", + "Safari on iPhone", + ), + ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 \ + Safari/537.36", + "Chrome on Windows", + ), + ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 \ + Safari/537.36 Edg/131.0.0.0", + "Edge on Windows", + ), + ( + "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 \ + Mobile Safari/537.36", + "Chrome on Android", + ), + ("Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0", "Firefox on Linux"), + ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) \ + Version/18.1 Safari/605.1.15", + "Safari on Mac", + ), + ]; + for (ua, name) in cases { + assert_eq!(describe(Some(ua)), name, "{ua}"); + } + assert_eq!(describe(None), "Browser"); + assert_eq!(describe(Some("curl/8.5.0")), "Browser"); + } +} diff --git a/crates/redshell-server/src/bus.rs b/crates/redshell-server/src/bus.rs new file mode 100644 index 0000000..f2add42 --- /dev/null +++ b/crates/redshell-server/src/bus.rs @@ -0,0 +1,51 @@ +//! Server-wide notifications, fanned out to every WebSocket. +//! +//! Senders never wait: a connection that falls behind gets `Lagged` and +//! resends its full view (the session list, the pending approvals). + +use redshell_protocol::{Approval, ApprovalOutcome, SessionEvent}; +use tokio::sync::broadcast; + +use crate::store::Credential; + +#[derive(Debug, Clone)] +pub enum BusEvent { + /// Something in the session's [`redshell_protocol::SessionInfo`] changed. + SessionChanged(String), + SessionRemoved(String), + ApprovalRequested(Approval), + ApprovalResolved { + id: String, + session: String, + outcome: ApprovalOutcome, + answered_by: Option, + }, + Event(SessionEvent), + /// A credential was revoked: its WebSockets close. + Revoked(Credential), + /// Every credential of the user except `keep` was revoked. + RevokedAllBut { + user_id: i64, + keep: Credential, + }, +} + +#[derive(Clone)] +pub struct Bus(broadcast::Sender); + +impl Default for Bus { + fn default() -> Self { + Self(broadcast::channel(1024).0) + } +} + +impl Bus { + pub fn send(&self, event: BusEvent) { + // No receivers (no client connected) is fine. + let _ = self.0.send(event); + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.0.subscribe() + } +} diff --git a/crates/redshell-server/src/cli.rs b/crates/redshell-server/src/cli.rs new file mode 100644 index 0000000..45250d7 --- /dev/null +++ b/crates/redshell-server/src/cli.rs @@ -0,0 +1,115 @@ +//! `redshell-server user …`: accounts from the command line, straight in +//! the database (also while the server runs). + +use std::io::BufRead as _; +use std::path::Path; + +use anyhow::{Context as _, bail}; + +use crate::auth::{password, valid_username}; +use crate::store::{AuditEvent, Store}; + +/// Where a new password comes from. +pub enum PasswordSource { + /// Asked twice on the terminal. + Prompt, + /// The first line of standard input (scripts). + Stdin, +} + +fn open(config_dir: &Path) -> anyhow::Result { + std::fs::create_dir_all(config_dir)?; + crate::config::restrict_dir(config_dir)?; + Store::open(&config_dir.join("server.sqlite3")) +} + +fn read_password(source: PasswordSource) -> anyhow::Result { + let password = match source { + PasswordSource::Stdin => { + let mut line = String::new(); + std::io::stdin().lock().read_line(&mut line)?; + line.trim_end_matches(['\r', '\n']).to_owned() + } + PasswordSource::Prompt => { + let first = rpassword::prompt_password("New password: ")?; + let second = rpassword::prompt_password("Again: ")?; + if first != second { + bail!("the passwords differ"); + } + first + } + }; + password::check_new(&password).map_err(anyhow::Error::msg)?; + Ok(password) +} + +pub fn add_user(config_dir: &Path, username: &str, source: PasswordSource) -> anyhow::Result<()> { + valid_username(username).map_err(anyhow::Error::msg)?; + let store = open(config_dir)?; + if store.find_user(username)?.is_some() { + bail!("{username} exists already"); + } + let hash = password::hash_blocking(&read_password(source)?)?; + let user = store.create_user(username, &hash)?.with_context(|| format!("{username} exists already"))?; + store.audit(AuditEvent::UserAdded, Some(user.id), Some(&user.username), None, "cli"); + println!("added {}", user.username); + Ok(()) +} + +/// Sets a new password and signs the user out everywhere. Their passkeys +/// stay unless `revoke_passkeys`: a password reset after a lost device or a +/// takeover may need them gone too, so they are listed. +pub fn set_password( + config_dir: &Path, + username: &str, + source: PasswordSource, + revoke_passkeys: bool, +) -> anyhow::Result<()> { + let store = open(config_dir)?; + let user = store.find_user(username)?.with_context(|| format!("no user {username}"))?.user; + let hash = password::hash_blocking(&read_password(source)?)?; + store.set_password(user.id, &hash)?; + store.revoke_all_except(user.id, None)?; + store.audit(AuditEvent::PasswordChanged, Some(user.id), Some(&user.username), None, "cli"); + println!("changed the password of {}; every browser and device of theirs is signed out", user.username); + let passkeys = store.passkeys(user.id)?; + if revoke_passkeys { + let removed = store.reset_passkeys(user.id)?; + store.audit(AuditEvent::PasskeysReset, Some(user.id), Some(&user.username), None, "cli"); + println!("removed {removed} passkey(s); password sign-in is on"); + } else if !passkeys.is_empty() { + println!("{} keeps {} passkey(s), which still sign in:", user.username, passkeys.len()); + for passkey in &passkeys { + println!(" {}", passkey.name); + } + println!("run it again with --revoke-passkeys to remove them"); + } + Ok(()) +} + +pub fn remove_user(config_dir: &Path, username: &str) -> anyhow::Result<()> { + let store = open(config_dir)?; + let user = store.find_user(username)?.with_context(|| format!("no user {username}"))?.user; + store.remove_user(&user.username)?; + store.audit(AuditEvent::UserRemoved, Some(user.id), Some(&user.username), None, "cli"); + println!("removed {}", user.username); + Ok(()) +} + +/// Removes every passkey of a user and turns passkey-only sign-in off, for +/// someone who lost theirs: the password signs them in again. +pub fn reset_passkeys(config_dir: &Path, username: &str) -> anyhow::Result<()> { + let store = open(config_dir)?; + let user = store.find_user(username)?.with_context(|| format!("no user {username}"))?.user; + let removed = store.reset_passkeys(user.id)?; + store.audit(AuditEvent::PasskeysReset, Some(user.id), Some(&user.username), None, "cli"); + println!("removed {removed} passkey(s) of {}; password sign-in is on", user.username); + Ok(()) +} + +pub fn list_users(config_dir: &Path) -> anyhow::Result<()> { + for user in open(config_dir)?.users()? { + println!("{}", user.username); + } + Ok(()) +} diff --git a/crates/redshell-server/src/config.rs b/crates/redshell-server/src/config.rs new file mode 100644 index 0000000..b76f30c --- /dev/null +++ b/crates/redshell-server/src/config.rs @@ -0,0 +1,309 @@ +//! Where the server keeps its files and what `config.toml` tells it. +//! +//! The config directory holds `config.toml` (the desktop's format plus a +//! `[server]` section), the SQLite database, shell integration scripts and +//! `run/`, a private folder for per-session files that live only while the +//! server runs (agent hook settings). + +use std::net::{IpAddr, SocketAddr}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{Context as _, bail}; +use parking_lot::{Mutex, RwLock}; +use redshell_core::Settings; +use redshell_core::settings::SettingsFile; + +const CONFIG_FILE: &str = "config.toml"; + +/// Written when the config directory has no `config.toml` yet. +const TEMPLATE: &str = r#"# redshell-server configuration: the desktop's config.toml format. +# [ssh], [agents] and [terminal] mean what they mean on the desktop. +# Reference: docs/REMOTE.md and docs/CONFIG.md + +[server] +listen = "127.0.0.1:4747" # anything but loopback needs tls_cert and tls_key +# public_url = "https://box.example.ts.net" +# tls_cert = "/etc/redshell-server/cert.pem" +# tls_key = "/etc/redshell-server/key.pem" +# trusted_proxies = ["127.0.0.1", "::1"] # the proxy; loopback by default with an https public_url +approval_timeout_secs = 600 + +[ssh] +import_ssh_config = true +"#; + +/// PEM files for built-in TLS. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TlsFiles { + pub cert: PathBuf, + pub key: PathBuf, +} + +/// The server's configuration, checked. +#[derive(Debug, Clone)] +pub struct ServerConfig { + pub dir: PathBuf, + pub settings: Settings, + pub listen: SocketAddr, + /// Origin (`https://host[:port]`) of `public_url`. + pub public_origin: Option, + pub tls: Option, + pub trusted_proxies: Vec, + /// `trusted_proxies` was empty, and loopback is trusted instead: see + /// [`Self::from_settings`]. + pub assumed_local_proxy: bool, + pub approval_timeout: Duration, + /// Connection limits of the public listener (not in `config.toml`). + pub limits: crate::connections::Limits, +} + +impl ServerConfig { + /// `~/.config/redshell-server` (or the platform's equivalent). + pub fn default_dir() -> PathBuf { + dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")).join("redshell-server") + } + + /// Reads `/config.toml`, writing a commented template first when it + /// is missing. Unlike the desktop, a broken file stops the server: it + /// would otherwise start with settings nobody chose. + pub fn load(dir: &Path) -> anyhow::Result { + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + restrict_dir(dir)?; + let path = dir.join(CONFIG_FILE); + if !path.exists() { + std::fs::write(&path, TEMPLATE).with_context(|| format!("writing {}", path.display()))?; + } + let (file, settings) = SettingsFile::open(path); + if let Some(error) = file.error() { + bail!("{error}"); + } + Self::from_settings(dir, settings.sanitized()) + } + + /// Checks the `[server]` section of `settings`. + /// + /// A server on loopback, without TLS of its own but with an https + /// `public_url`, is behind a TLS proxy on the same machine (Tailscale + /// Serve, cloudflared), so every client arrives from loopback. Without + /// `trusted_proxies`, loopback is trusted: otherwise the sign-in backoff + /// would count all clients as one. + pub fn from_settings(dir: &Path, settings: Settings) -> anyhow::Result { + let s = &settings.server; + let listen: SocketAddr = + s.listen.parse().with_context(|| format!("server.listen = {:?} is not an address:port", s.listen))?; + let tls = match (&s.tls_cert, &s.tls_key) { + (Some(cert), Some(key)) => Some(TlsFiles { cert: cert.clone(), key: key.clone() }), + (None, None) => None, + _ => bail!("server.tls_cert and server.tls_key go together"), + }; + if tls.is_none() && !listen.ip().is_loopback() { + bail!( + "server.listen = {listen} is reachable from the network, but there is no TLS: set server.tls_cert and \ + server.tls_key, or listen on 127.0.0.1 behind a TLS proxy (Tailscale Serve, cloudflared)" + ); + } + let public_origin = s.public_url.as_deref().map(origin_of).transpose()?; + let mut trusted_proxies: Vec = s + .trusted_proxies + .iter() + .map(|p| p.parse().with_context(|| format!("server.trusted_proxies: {p:?} is not an IP address"))) + .collect::>()?; + let proxied = public_origin.as_deref().is_some_and(|o| o.starts_with("https://")); + let assumed_local_proxy = proxied && tls.is_none() && listen.ip().is_loopback() && trusted_proxies.is_empty(); + if assumed_local_proxy { + trusted_proxies = vec![IpAddr::from([127, 0, 0, 1]), IpAddr::from(std::net::Ipv6Addr::LOCALHOST)]; + } + Ok(Self { + dir: dir.to_owned(), + listen, + public_origin, + tls, + trusted_proxies, + assumed_local_proxy, + approval_timeout: Duration::from_secs(s.approval_timeout_secs.max(1)), + limits: Default::default(), + settings, + }) + } + + pub fn file(&self) -> PathBuf { + self.dir.join(CONFIG_FILE) + } + + pub fn database(&self) -> PathBuf { + self.dir.join("server.sqlite3") + } + + /// Per-session files (hook settings), private to the server's user. + pub fn runtime_dir(&self) -> PathBuf { + self.dir.join("run") + } + + /// Whether clients reach the server over https: built-in TLS, or an + /// https `public_url` in front of it. + pub fn https(&self) -> bool { + self.tls.is_some() || self.public_origin.as_deref().is_some_and(|o| o.starts_with("https://")) + } + + /// Where clients reach the server: `public_url`, else the address the + /// listener is `bound` to. + pub fn base_url(&self, bound: SocketAddr) -> String { + self.public_origin.clone().unwrap_or_else(|| { + let scheme = if self.tls.is_some() { "https" } else { "http" }; + format!("{scheme}://{bound}") + }) + } +} + +/// `https://Host:443/path` → `https://host`: scheme, host and a port that is +/// not the scheme's default, as browsers send it in `Origin`. +pub fn origin_of(url: &str) -> anyhow::Result { + let (scheme, rest) = url.split_once("://").with_context(|| format!("{url:?} is not a URL"))?; + let scheme = scheme.to_ascii_lowercase(); + let default_port = match scheme.as_str() { + "https" => ":443", + "http" => ":80", + _ => bail!("{url:?} is not an http(s) URL"), + }; + let authority = rest.split(['/', '?', '#']).next().unwrap_or_default().to_ascii_lowercase(); + if authority.is_empty() || authority.contains('@') { + bail!("{url:?} has no host"); + } + let authority = authority.strip_suffix(default_port).unwrap_or(&authority); + Ok(format!("{scheme}://{authority}")) +} + +/// `config.toml` while the server runs: the settings new sessions start +/// with, and changes written back into the file in place, its comments and +/// layout kept (`redshell-core`'s settings edit path). +pub struct LiveSettings { + path: PathBuf, + current: RwLock, + /// One edit at a time, from reading the file to writing it. + editing: Mutex<()>, +} + +/// Why a settings change did not happen. +#[derive(Debug, thiserror::Error)] +pub enum EditError { + /// The change itself was refused. + #[error(transparent)] + Refused(E), + /// The file could not be read or written. + #[error(transparent)] + Failed(#[from] anyhow::Error), +} + +impl LiveSettings { + pub fn new(path: PathBuf, settings: Settings) -> Self { + Self { path, current: RwLock::new(settings), editing: Mutex::new(()) } + } + + pub fn get(&self) -> Settings { + self.current.read().clone() + } + + /// Applies `change` to the file as it is on disk now, writes the + /// difference back and makes the result current, so the server also + /// takes up other changes made to the file since it started. A file + /// that does not load is left alone. + pub fn edit(&self, change: impl FnOnce(&mut Settings) -> Result) -> Result> { + let _turn = self.editing.lock(); + if !self.path.exists() { + return Err(anyhow::anyhow!("{} is gone", self.path.display()).into()); + } + let (file, old) = SettingsFile::open(self.path.clone()); + if let Some(error) = file.error() { + return Err(anyhow::anyhow!("{error}").into()); + } + let mut new = old.clone(); + let result = change(&mut new).map_err(EditError::Refused)?; + file.save_changes(&old, &new)?; + *self.current.write() = new.sanitized(); + Ok(result) + } +} + +/// Makes `dir` private to the server's user (0700). +pub(crate) fn restrict_dir(dir: &Path) -> anyhow::Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)) + .with_context(|| format!("making {} private", dir.display()))?; + } + #[cfg(not(unix))] + let _ = dir; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(toml: &str) -> anyhow::Result { + ServerConfig::from_settings(Path::new("/x"), Settings::from_toml(toml).unwrap()) + } + + #[test] + fn plain_http_only_on_loopback() { + assert!(config("").is_ok()); + assert!(config("[server]\nlisten = \"[::1]:4747\"\n").is_ok()); + let err = config("[server]\nlisten = \"0.0.0.0:4747\"\n").unwrap_err().to_string(); + assert!(err.contains("no TLS"), "{err}"); + let tls = "[server]\nlisten = \"0.0.0.0:443\"\ntls_cert = \"c.pem\"\ntls_key = \"k.pem\"\n"; + assert!(config(tls).unwrap().tls.is_some()); + assert!(config("[server]\ntls_cert = \"c.pem\"\n").is_err()); + assert!(config("[server]\nlisten = \"localhost\"\n").is_err()); + } + + #[test] + fn edits_keep_the_file_and_apply_at_once() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(CONFIG_FILE); + let mine = "# mine\n[ssh]\nimport_ssh_config = false # keep\n"; + std::fs::write(&path, mine).unwrap(); + let live = LiveSettings::new(path.clone(), Settings::default()); + let refused: Result<(), _> = live.edit(|_| Err("no")); + assert!(matches!(refused, Err(EditError::Refused("no")))); + let host = + redshell_core::settings::SshHost { name: "box".into(), host: "box.lan".into(), ..Default::default() }; + live.edit(|s| { + s.ssh.hosts.push(host); + Ok::<_, ()>(()) + }) + .unwrap(); + assert_eq!(live.get().ssh.hosts[0].name, "box"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.starts_with(mine), "{text}"); + assert!(text.contains("[[ssh.hosts]]") && text.contains("name = \"box\""), "{text}"); + std::fs::write(&path, "[ssh\n").unwrap(); + assert!(matches!(live.edit(|_| Ok::<_, ()>(())), Err(EditError::Failed(_))), "a broken file is left alone"); + } + + #[test] + fn origins_drop_paths_and_default_ports() { + assert_eq!(origin_of("https://Box.ts.net/").unwrap(), "https://box.ts.net"); + assert_eq!(origin_of("https://box:443/app?x").unwrap(), "https://box"); + assert_eq!(origin_of("http://127.0.0.1:4747").unwrap(), "http://127.0.0.1:4747"); + assert!(origin_of("ftp://x").is_err()); + assert!(origin_of("https://").is_err()); + let c = config("[server]\npublic_url = \"https://box.ts.net\"\ntrusted_proxies = [\"127.0.0.1\"]\n").unwrap(); + assert_eq!(c.base_url(c.listen), "https://box.ts.net"); + assert!(config("[server]\ntrusted_proxies = [\"proxy\"]\n").is_err()); + } + + #[test] + fn a_local_tls_proxy_is_trusted_when_none_is_named() { + let proxied = config("[server]\npublic_url = \"https://box.ts.net\"\n").unwrap(); + assert!(proxied.assumed_local_proxy); + assert_eq!(proxied.trusted_proxies, ["127.0.0.1".parse::().unwrap(), "::1".parse().unwrap()]); + let named = config("[server]\npublic_url = \"https://box.ts.net\"\ntrusted_proxies = [\"10.0.0.2\"]\n"); + assert_eq!(named.unwrap().trusted_proxies, ["10.0.0.2".parse::().unwrap()]); + for direct in ["", "[server]\npublic_url = \"http://localhost:4747\"\n"] { + let direct = config(direct).unwrap(); + assert!(!direct.assumed_local_proxy && direct.trusted_proxies.is_empty()); + } + } +} diff --git a/crates/redshell-server/src/connections.rs b/crates/redshell-server/src/connections.rs new file mode 100644 index 0000000..ca0417e --- /dev/null +++ b/crates/redshell-server/src/connections.rs @@ -0,0 +1,100 @@ +//! Limits on the public listener's connections: how many are open at once, +//! and how long a client may take to say what it wants. + +use std::io; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; +use std::time::Duration; + +use axum_server::accept::Accept; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; + +/// Bounds on the public listener; tests shorten them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// Connections open at once, WebSockets included. Beyond it, new + /// connections are closed as they come. + pub max_connections: usize, + /// How long a client may take to send a request's headers: the first + /// request of a connection, and the next one on a kept-alive connection, + /// so this is the idle timeout too. + pub request_timeout: Duration, + /// How long a TLS handshake may take. + pub handshake_timeout: Duration, +} + +impl Default for Limits { + fn default() -> Self { + Self { + max_connections: 256, + request_timeout: Duration::from_secs(10), + handshake_timeout: Duration::from_secs(10), + } + } +} + +/// An acceptor that gives each connection one of a fixed number of places, +/// held until the connection closes; with none left, the connection is +/// closed at once. It counts upgraded WebSockets as well, which a +/// per-request limit would not. +#[derive(Clone)] +pub struct ConnectionLimit(Arc); + +impl ConnectionLimit { + pub fn new(max: usize) -> Self { + Self(Arc::new(Semaphore::new(max))) + } +} + +impl Accept for ConnectionLimit { + type Stream = Counted; + type Service = S; + type Future = std::future::Ready, S)>>; + + fn accept(&self, stream: I, service: S) -> Self::Future { + std::future::ready(match self.0.clone().try_acquire_owned() { + Ok(place) => Ok((Counted { stream, _place: place }, service)), + Err(_) => Err(io::Error::other("too many open connections")), + }) + } +} + +/// A connection holding its place. +pub struct Counted { + stream: I, + _place: OwnedSemaphorePermit, +} + +impl AsyncRead for Counted { + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { + Pin::new(&mut self.get_mut().stream).poll_read(cx, buf) + } +} + +impl AsyncWrite for Counted { + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + Pin::new(&mut self.get_mut().stream).poll_write(cx, buf) + } + + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut self.get_mut().stream).poll_write_vectored(cx, bufs) + } + + fn is_write_vectored(&self) -> bool { + self.stream.is_write_vectored() + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().stream).poll_flush(cx) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().stream).poll_shutdown(cx) + } +} diff --git a/crates/redshell-server/src/hosts.rs b/crates/redshell-server/src/hosts.rs new file mode 100644 index 0000000..384eb71 --- /dev/null +++ b/crates/redshell-server/src/hosts.rs @@ -0,0 +1,214 @@ +//! The server's SSH hosts as the hosts API sees them: the `[[ssh.hosts]]` +//! entries of its `config.toml` and the hosts of the server user's +//! `~/.ssh/config`, and the checks a host passes before it is saved. The +//! conversion from and to the wire type is shared with the desktop +//! ([`redshell_core::settings::ssh_wire`]). +//! +//! The checks are the ones the desktop's host editor makes, from +//! [`redshell_core::settings::ssh`]. A host only in `~/.ssh/config` is +//! saved under its own name, as an entry holding the fields that differ +//! from the file, which ssh layers over it. + +use redshell_core::settings::ssh::{self, Replacing}; +pub use redshell_core::settings::ssh_wire::from_wire; +use redshell_core::settings::ssh_wire::to_wire; +use redshell_core::settings::{PortForward, SshHost, SshSettings}; +use redshell_protocol::{self as wire, HostOrigin}; +use redshell_remote::ssh_config; + +/// Why a host cannot be saved or removed; the message is for the user. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum HostError { + /// It breaks a rule every host follows. + #[error(transparent)] + Invalid(#[from] ssh::HostError), + #[error("{0:?} is in ~/.ssh/config on the server; remove it there")] + Imported(String), + #[error("no host is named {0:?}")] + NotFound(String), + #[error("{0} is too long")] + TooLong(&'static str), +} + +/// The saved hosts and the `~/.ssh/config` hosts not saved over. +pub struct HostBook<'a> { + ssh: &'a mut SshSettings, + /// `~/.ssh/config` hosts, with what RedShell reads of them. + aliases: Vec, +} + +impl<'a> HostBook<'a> { + /// Reads `~/.ssh/config` when `ssh` imports it. + pub fn load(ssh: &'a mut SshSettings) -> Self { + let aliases = if ssh.import_ssh_config { ssh_config::load(ssh.ssh_config_path.as_deref()) } else { Vec::new() }; + let aliases = aliases + .into_iter() + .map(|a| SshHost { + name: a.alias, + host: a.hostname.unwrap_or_default(), + user: a.user, + port: a.port, + ..Default::default() + }) + .collect(); + Self { ssh, aliases } + } + + /// Every host: the saved ones, then those only in `~/.ssh/config`. + pub fn list(&self) -> Vec { + let saved = self.ssh.hosts.iter().map(|h| to_wire(h, HostOrigin::Redshell)); + let imported = self.aliases.iter().filter(|a| self.saved(&a.name).is_none()); + saved.chain(imported.map(|h| to_wire(h, HostOrigin::SshConfig))).collect() + } + + /// Saves `host` over the host named `replacing`, or as a new one; the + /// host as listed afterwards. + pub fn save(&mut self, replacing: Option<&str>, host: SshHost) -> Result { + let index = replacing.and_then(|name| self.saved(name)); + let imported = match (replacing, index) { + (Some(name), None) => Some(self.alias(name).ok_or_else(|| HostError::NotFound(name.to_owned()))?.clone()), + _ => None, + }; + let replacing = match (&imported, index) { + (Some(base), _) => Replacing::Imported(base), + (None, Some(i)) => Replacing::Saved(&self.ssh.hosts[i].name), + (None, None) => Replacing::Nothing, + }; + if let Some(field) = oversized(&host) { + return Err(HostError::TooLong(field)); + } + if let Some(error) = ssh::validate(&host, replacing, &self.ssh.hosts, &self.aliases).into_iter().next() { + return Err(error.into()); + } + let entry = match &imported { + Some(base) => ssh::imported_entry(base, host.clone()), + None => host.clone(), + }; + match index { + Some(i) => self.ssh.hosts[i] = entry, + None => self.ssh.hosts.push(entry), + } + Ok(to_wire(&host, HostOrigin::Redshell)) + } + + /// Removes the saved host `name`. + pub fn remove(&mut self, name: &str) -> Result<(), HostError> { + match self.saved(name) { + Some(i) => { + self.ssh.hosts.remove(i); + Ok(()) + } + None if self.alias(name).is_some() => Err(HostError::Imported(name.to_owned())), + None => Err(HostError::NotFound(name.to_owned())), + } + } + + fn saved(&self, name: &str) -> Option { + self.ssh.hosts.iter().position(|h| h.name == name) + } + + fn alias(&self, name: &str) -> Option<&SshHost> { + self.aliases.iter().find(|a| a.name == name) + } +} + +/// The first field of `host` longer than a host is given: names and +/// addresses take 255 characters, paths, arguments and the startup command +/// 4096, and lists 64 entries. +fn oversized(host: &SshHost) -> Option<&'static str> { + const SHORT: usize = 255; + const LONG: usize = 4096; + const ENTRIES: usize = 64; + let over = |text: &str, max: usize| text.chars().count() > max; + let opt = |text: &Option, max: usize| text.as_deref().is_some_and(|t| over(t, max)); + let list = |items: &[String], max: usize| items.len() > ENTRIES || items.iter().any(|t| over(t, max)); + let forward = |f: &PortForward| opt(&f.bind_address, SHORT) || opt(&f.target_host, SHORT) || opt(&f.label, SHORT); + [ + ("the name", over(&host.name, SHORT)), + ("the address", over(&host.host, SHORT)), + ("the user", opt(&host.user, SHORT)), + ("the identity file", host.identity_file.as_ref().is_some_and(|p| p.as_os_str().len() > LONG)), + ("the jump host", opt(&host.jump_host, SHORT)), + ("the list of extra arguments", list(&host.extra_args, LONG)), + ("the session to attach", opt(&host.attach_session, SHORT)), + ("the group", opt(&host.group, SHORT)), + ("the list of tags", list(&host.tags, SHORT)), + ("the startup command", opt(&host.startup_command, LONG)), + ("the list of port forwards", host.forwards.len() > ENTRIES || host.forwards.iter().any(forward)), + ] + .into_iter() + .find_map(|(field, too_long)| too_long.then_some(field)) +} + +#[cfg(test)] +mod tests { + use redshell_core::settings::ForwardKind; + + use super::*; + + fn host(name: &str, address: &str) -> SshHost { + SshHost { name: name.into(), host: address.into(), ..Default::default() } + } + + fn book_of(ssh: &mut SshSettings) -> HostBook<'_> { + let alias = SshHost { user: Some("pi".into()), ..host("pi", "pi.lan") }; + HostBook { ssh, aliases: vec![alias] } + } + + #[test] + fn checks_names_addresses_and_ports() { + let mut ssh = SshSettings { hosts: vec![host("a", "a.lan")], ..Default::default() }; + let mut book = book_of(&mut ssh); + let mut refused = |h| book.save(None, h).unwrap_err(); + assert_eq!(refused(host("a", "x")), ssh::HostError::NameTaken.into()); + assert_eq!(refused(host("-oProxyCommand=x", "x")), ssh::HostError::NameStartsWithDash.into()); + assert_eq!(refused(host("b", "")), ssh::HostError::AddressMissing.into()); + assert_eq!(refused(host(&"b".repeat(256), "x")), HostError::TooLong("the name")); + let args = SshHost { extra_args: vec!["-v".into(); 65], ..host("b", "b.lan") }; + assert_eq!(refused(args), HostError::TooLong("the list of extra arguments")); + let startup = SshHost { startup_command: Some("x".repeat(4097)), ..host("b", "b.lan") }; + assert_eq!(refused(startup), HostError::TooLong("the startup command")); + + let mut book = book_of(&mut ssh); + book.save(Some("a"), host("a", "new.lan")).unwrap(); + book.save(Some("a"), host("c", "c.lan")).unwrap(); + assert_eq!(book.save(Some("a"), host("d", "d")).unwrap_err(), HostError::NotFound("a".into())); + assert_eq!(book.remove("pi").unwrap_err(), HostError::Imported("pi".into())); + book.remove("c").unwrap(); + assert!(ssh.hosts.is_empty()); + } + + #[test] + fn imported_hosts_are_listed_and_saved_as_their_differences() { + let mut ssh = SshSettings::default(); + let mut book = book_of(&mut ssh); + let listed = book.list(); + assert_eq!((listed[0].name.as_str(), listed[0].origin), ("pi", HostOrigin::SshConfig)); + assert_eq!( + book.save(Some("pi"), host("pie", "pi.lan")).unwrap_err(), + ssh::HostError::NameOfImportedHost.into() + ); + let changed = SshHost { user: Some("pi".into()), port: Some(2222), ..host("pi", "pi.lan") }; + let saved = book.save(Some("pi"), changed).unwrap(); + assert_eq!((saved.origin, saved.port), (HostOrigin::Redshell, Some(2222))); + assert_eq!(book.list().len(), 1, "saved over, listed once"); + assert_eq!(ssh.hosts, [SshHost { port: Some(2222), ..host("pi", "") }], "only what differs"); + } + + #[test] + fn startup_commands_and_forwards_are_checked() { + let mut ssh = SshSettings::default(); + let mut book = book_of(&mut ssh); + let mut bad = host("box", "box.example"); + bad.startup_command = Some("-oProxyCommand=x".into()); + assert_eq!(book.save(None, bad), Err(ssh::HostError::StartupStartsWithDash.into())); + let mut bad = host("box", "box.example"); + bad.forwards = vec![PortForward { bind_port: 8080, ..Default::default() }]; + let missing = ssh::HostError::Forward(0, ssh::ForwardError::TargetMissing); + assert_eq!(book.save(None, bad).unwrap_err().to_string(), format!("{missing}")); + let mut good = host("box", "box.example"); + good.startup_command = Some("cd /srv && ls".into()); + good.forwards = vec![PortForward { kind: ForwardKind::Dynamic, bind_port: 1080, ..Default::default() }]; + assert!(book.save(None, good).is_ok()); + } +} diff --git a/crates/redshell-server/src/lib.rs b/crates/redshell-server/src/lib.rs new file mode 100644 index 0000000..20bf02e --- /dev/null +++ b/crates/redshell-server/src/lib.rs @@ -0,0 +1,189 @@ +//! # redshell-server +//! +//! Headless RedShell: terminal sessions (shells, coding agents, SSH hosts) +//! owned by the server, which any number of clients attach to: the desktop +//! and the RedShell Remote PWA it serves. Sessions outlive every client. +//! +//! * [`config`] – the config directory and the `[server]` section. +//! * `store` – SQLite: accounts, credentials, audit log, session metadata. +//! * `auth` – setup, password sign-in with backoff, cookies and device tokens. +//! * `sessions` – PTY sessions, their output fan-out and snapshots. +//! * `agents` – Claude Code and Codex hooks on a loopback listener, and +//! the approvals they hold open. +//! * `hosts` – the SSH hosts the hosts API edits in `config.toml`. +//! * `push` – Web Push to subscribed browsers when a session wants attention. +//! * `web` – the REST API, the WebSocket and the embedded PWA. +//! +//! The wire types live in `redshell-protocol`; `docs/REMOTE.md` describes +//! running the server and the API. + +mod agents; +mod auth; +mod bus; +pub mod cli; +pub mod config; +pub mod connections; +mod hosts; +mod push; +mod sessions; +mod store; +mod web; + +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Context as _; +use axum_server::tls_rustls::{RustlsAcceptor, RustlsConfig}; + +use crate::agents::Approvals; +use crate::auth::Auth; +use crate::bus::Bus; +use crate::config::LiveSettings; +pub use crate::config::ServerConfig; +use crate::connections::{ConnectionLimit, Limits}; +use crate::push::Push; +use crate::sessions::{Ctx, Sessions}; +use crate::store::Store; +use crate::web::AppState; + +pub use agents::{HOOK_URL_ENV, codex_hook}; +pub use web::CSP; + +/// Unix time in milliseconds. +pub(crate) fn now_ms() -> i64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64) +} + +/// `text` cut to `chars` characters, with an ellipsis when it was longer. +pub(crate) fn truncate(text: &str, chars: usize) -> String { + match text.char_indices().nth(chars) { + Some((at, _)) => format!("{}…", &text[..at]), + None => text.to_owned(), + } +} + +/// `server` with the request timeouts of `limits`: hyper's own header +/// timeout (axum-server turns it off), and one for the first request, which +/// also covers a connection that never says which protocol it speaks. +fn limited(mut server: axum_server::Server, limits: &Limits) -> axum_server::Server { + server.http_builder().http1().header_read_timeout(limits.request_timeout); + server.first_request_timeout(limits.request_timeout) +} + +/// A started server. +pub struct RunningServer { + /// Where the public listener is bound. + pub addr: SocketAddr, + /// The loopback listener agent hooks post to. + pub hook_addr: SocketAddr, + app: web::Shared, + handle: axum_server::Handle, + serving: Option>>, + hooks: tokio::task::JoinHandle<()>, + pushing: tokio::task::JoinHandle<()>, +} + +impl RunningServer { + /// Binds both listeners and starts serving. With no account yet, the + /// setup link is logged. + pub async fn start(config: ServerConfig) -> anyhow::Result { + let config = Arc::new(config); + let runtime_dir = config.runtime_dir(); + // Files of the last run are stale (and hold dead tokens). + let _ = std::fs::remove_dir_all(&runtime_dir); + std::fs::create_dir_all(&runtime_dir).with_context(|| format!("creating {}", runtime_dir.display()))?; + config::restrict_dir(&runtime_dir)?; + + let store = Arc::new(Store::open(&config.database())?); + store.end_orphaned_sessions()?; + store.prune_expired_sessions()?; + store.prune_audit_log()?; + + let bus = Bus::default(); + let hook_listener = + tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.context("binding the hook listener")?; + let hook_addr = hook_listener.local_addr()?; + let ctx = Arc::new(Ctx { + settings: LiveSettings::new(config.file(), config.settings.clone()), + config_dir: config.dir.clone(), + runtime_dir, + bus: bus.clone(), + store: store.clone(), + approvals: Approvals::new(bus.clone()), + runtime: tokio::runtime::Handle::current(), + hook_addr, + approval_timeout: config.approval_timeout, + }); + let sessions = Arc::new(Sessions::new(ctx)); + let hook_router = agents::hooks::router(sessions.clone()); + let hooks = tokio::spawn(async move { + if let Err(err) = axum::serve(hook_listener, hook_router).await { + log::error!("hook listener: {err}"); + } + }); + + let listener = + std::net::TcpListener::bind(config.listen).with_context(|| format!("listening on {}", config.listen))?; + let addr = listener.local_addr()?; + let auth = Auth::new(store.clone(), bus.clone(), config.base_url(addr), config.public_origin.as_deref()); + auth.announce_setup()?; + let push = Arc::new(Push::new(store.clone(), config.public_origin.as_deref())?); + let pushing = push.clone().spawn(&bus, sessions.clone()); + let app = Arc::new(AppState { config: config.clone(), auth, sessions, store, bus, push }); + let make_service = web::router(app.clone()).into_make_service_with_connect_info::(); + let handle = axum_server::Handle::new(); + let limits = config.limits; + let server = limited(axum_server::from_tcp(listener)?, &limits).handle(handle.clone()); + let counted = ConnectionLimit::new(limits.max_connections); + let serving = match &config.tls { + Some(tls) => { + let loaded = RustlsConfig::from_pem_file(&tls.cert, &tls.key) + .await + .with_context(|| format!("loading {} and {}", tls.cert.display(), tls.key.display()))?; + // HTTP/1.1 only: hyper's request timeouts are HTTP/1's, and an HTTP/2 connection + // could stay open idle for as long as it likes. + let mut rustls = (*loaded.get_inner()).clone(); + rustls.alpn_protocols = vec![b"http/1.1".to_vec()]; + let rustls = RustlsConfig::from_config(Arc::new(rustls)); + let tls = RustlsAcceptor::new(rustls).handshake_timeout(limits.handshake_timeout).acceptor(counted); + tokio::spawn(server.acceptor(tls).serve(make_service)) + } + None => tokio::spawn(server.acceptor(counted).serve(make_service)), + }; + let scheme = if config.tls.is_some() { "https" } else { "http" }; + log::info!("redshell-server {} listening on {scheme}://{addr}", env!("CARGO_PKG_VERSION")); + if config.assumed_local_proxy { + log::warn!( + "server.public_url is https but the server listens on loopback without TLS: assuming a TLS proxy on \ + this machine and trusting X-Forwarded-For from 127.0.0.1 and ::1. If clients reach this port in \ + another way, set server.trusted_proxies to the proxy's address." + ); + } + Ok(Self { addr, hook_addr, app, handle, serving: Some(serving), hooks, pushing }) + } + + /// The setup link while no account exists. + pub fn setup_link(&self) -> anyhow::Result> { + self.app.auth.announce_setup() + } + + /// Runs until the listener stops (it only does on an error). + pub async fn wait(&mut self) -> anyhow::Result<()> { + if let Some(serving) = self.serving.take() { + serving.await??; + } + Ok(()) + } + + /// Stops accepting, closes connections, kills every session. + pub async fn shutdown(self) { + self.handle.graceful_shutdown(Some(Duration::from_secs(2))); + self.app.sessions.shutdown(); + self.hooks.abort(); + self.pushing.abort(); + if let Some(serving) = self.serving { + let _ = serving.await; + } + } +} diff --git a/crates/redshell-server/src/main.rs b/crates/redshell-server/src/main.rs new file mode 100644 index 0000000..d16fc4d --- /dev/null +++ b/crates/redshell-server/src/main.rs @@ -0,0 +1,140 @@ +//! `redshell-server`: see `docs/REMOTE.md`. + +use std::path::PathBuf; + +use clap::{Parser, Subcommand}; +use redshell_server::cli::{self, PasswordSource}; +use redshell_server::{RunningServer, ServerConfig}; + +#[derive(Parser)] +#[command( + name = "redshell-server", + version, + about = "Headless RedShell: terminal sessions for the desktop and RedShell Remote" +)] +struct Args { + /// Config directory: config.toml, the database and runtime files + /// [default: ~/.config/redshell-server] + #[arg(long, global = true, env = "REDSHELL_SERVER_CONFIG")] + config: Option, + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Run the server (the default) + Serve, + /// Manage accounts + #[command(subcommand)] + User(UserCommand), + /// Report an agent event to the server (agents run this, not people) + #[command(subcommand, hide = true)] + Hook(HookCommand), +} + +#[derive(Subcommand)] +enum UserCommand { + /// Add an account + Add { + name: String, + /// Read the password from the first line of standard input + #[arg(long)] + password_stdin: bool, + }, + /// Set an account's password and sign it out everywhere + Passwd { + name: String, + #[arg(long)] + password_stdin: bool, + /// Remove the account's passkeys too (and turn passkey-only sign-in off) + #[arg(long)] + revoke_passkeys: bool, + }, + /// Remove an account + Remove { name: String }, + /// Remove every passkey of an account and turn passkey-only sign-in off + ResetPasskeys { name: String }, + /// List accounts + List, +} + +#[derive(Subcommand)] +enum HookCommand { + /// Codex's `notify` program: posts its JSON payload to the session's hook URL, then runs the user's own + Codex { + /// The JSON payload Codex appends + payload: String, + }, +} + +fn source(stdin: bool) -> PasswordSource { + if stdin { PasswordSource::Stdin } else { PasswordSource::Prompt } +} + +fn main() -> anyhow::Result<()> { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + let args = Args::parse(); + let dir = args.config.unwrap_or_else(ServerConfig::default_dir); + match args.command.unwrap_or(Command::Serve) { + Command::Serve => serve(dir), + Command::User(UserCommand::Add { name, password_stdin }) => cli::add_user(&dir, &name, source(password_stdin)), + Command::User(UserCommand::Passwd { name, password_stdin, revoke_passkeys }) => { + cli::set_password(&dir, &name, source(password_stdin), revoke_passkeys) + } + Command::User(UserCommand::Remove { name }) => cli::remove_user(&dir, &name), + Command::User(UserCommand::ResetPasskeys { name }) => cli::reset_passkeys(&dir, &name), + Command::User(UserCommand::List) => cli::list_users(&dir), + Command::Hook(HookCommand::Codex { payload }) => { + let url = std::env::var(redshell_server::HOOK_URL_ENV).ok(); + runtime(1)?.block_on(redshell_server::codex_hook(url, payload)) + } + } +} + +fn runtime(workers: usize) -> anyhow::Result { + Ok(tokio::runtime::Builder::new_multi_thread().worker_threads(workers).enable_all().build()?) +} + +fn serve(dir: PathBuf) -> anyhow::Result<()> { + return_large_blocks_to_the_os(); + let _ = rustls::crypto::ring::default_provider().install_default(); + let config = ServerConfig::load(&dir)?; + log::info!("config directory: {}", dir.display()); + // Two workers are plenty for a handful of clients, and keep a Pi idle. + runtime(2)?.block_on(async { + let mut server = RunningServer::start(config).await?; + tokio::select! { + result = server.wait() => result?, + () = stop_signal() => log::info!("stopping"), + } + server.shutdown().await; + Ok(()) + }) +} + +/// Every password check takes 19 MiB for Argon2. glibc raises its mmap +/// threshold after the first such block is freed and keeps later ones in +/// the heap, so an idle server would hold ~20 MiB after one sign-in. A fixed +/// threshold sends blocks of 1 MiB and more back to the OS when freed. +fn return_large_blocks_to_the_os() { + #[cfg(all(target_os = "linux", target_env = "gnu"))] + // SAFETY: only tunes the allocator, before any other thread exists. + unsafe { + libc::mallopt(libc::M_MMAP_THRESHOLD, 1 << 20); + } +} + +async fn stop_signal() { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + let mut term = signal(SignalKind::terminate()).expect("installing a SIGTERM handler"); + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = term.recv() => {} + } + } + #[cfg(not(unix))] + let _ = tokio::signal::ctrl_c().await; +} diff --git a/crates/redshell-server/src/push/mod.rs b/crates/redshell-server/src/push/mod.rs new file mode 100644 index 0000000..63501fb --- /dev/null +++ b/crates/redshell-server/src/push/mod.rs @@ -0,0 +1,230 @@ +//! Web Push: tells subscribed browsers when a session wants attention, +//! also while the PWA is closed. +//! +//! The server signs with a VAPID key it makes on its first start. Each +//! browser session holds at most one subscription, which says what it +//! wants: approval requests, agents waiting for input or finished, +//! programs that exit with an error, OSC 9 / 777 notifications. Nobody is +//! sent a message about a session they typed into in the last +//! [`TYPING_QUIET`]: they are looking at it. A subscription the push +//! service no longer knows (404, 410) is dropped. + +mod sender; +pub mod target; +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use parking_lot::Mutex; +use redshell_protocol::{EventKind, PushEvent, PushPayload, PushSubscribeRequest, SessionEvent}; +use tokio::sync::broadcast; +use web_push_native::jwt_simple::algorithms::ES256KeyPair; +use web_push_native::p256::PublicKey; + +pub use sender::Delivery; +use sender::{AUTH_LEN, Sender}; + +use crate::bus::{Bus, BusEvent}; +use crate::sessions::Sessions; +use crate::store::{PushSubscription, Store}; +use crate::{now_ms, truncate}; + +/// A user who typed into a session this recently gets no push about it. +pub const TYPING_QUIET: Duration = Duration::from_secs(30); +/// Program notifications (OSC 9 / 777) of a session pushed at most this often. +const NOTIFICATION_QUIET: Duration = Duration::from_secs(10); +/// Longest title and body in a message; push services take about 4 KB. +const MAX_TITLE: usize = 120; +const MAX_BODY: usize = 400; + +/// A browser's keys, decoded and checked. +pub struct SubscriptionKeys { + pub p256dh: Vec, + pub auth: Vec, +} + +pub struct Push { + sender: Sender, + store: Arc, + /// When each session last had a notification pushed, so a program + /// printing OSC 9 in a loop does not flood phones. + notified: Mutex>, +} + +impl Push { + /// Loads the VAPID key, making one on the first start. The VAPID + /// subject is `public_url` when it is https. + pub fn new(store: Arc, public_origin: Option<&str>) -> anyhow::Result { + let key = match store.server_key("vapid")? { + Some(bytes) => ES256KeyPair::from_bytes(&bytes)?, + None => { + let key = ES256KeyPair::generate(); + store.set_server_key("vapid", &key.to_bytes())?; + key + } + }; + let contact = public_origin.filter(|o| o.starts_with("https://")).unwrap_or("mailto:redshell-server@localhost"); + Ok(Self { sender: Sender::new(key, contact.to_owned())?, store, notified: Mutex::default() }) + } + + /// The key browsers subscribe with (`applicationServerKey`). + pub fn public_key(&self) -> String { + self.sender.public_key() + } + + /// Sends pushes for session events until the bus closes. + pub fn spawn(self: Arc, bus: &Bus, sessions: Arc) -> tokio::task::JoinHandle<()> { + let mut events = bus.subscribe(); + tokio::spawn(async move { + loop { + match events.recv().await { + Ok(BusEvent::Event(event)) => self.notify(&sessions, &event), + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => break, + } + } + }) + } + + /// Sends a test message to one subscription, waiting for the outcome. + pub async fn test(&self, subscription: PushSubscription) -> Delivery { + let payload = PushPayload { + title: "RedShell".into(), + body: "Notifications from this server reach this device.".into(), + session: None, + kind: None, + tag: "test".into(), + renotify: true, + url: "/".into(), + at: now_ms(), + }; + let Ok(body) = serde_json::to_vec(&payload) else { return Delivery::Failed("encoding".into()) }; + let delivery = self.sender.send(&subscription, &body, true).await; + self.settle(&subscription, &delivery); + delivery + } + + /// Pushes `event` to every subscription that wants it, unless its user + /// is typing into that session. + fn notify(self: &Arc, sessions: &Sessions, event: &SessionEvent) { + let Some(wanted) = push_event(event) else { return }; + if wanted == PushEvent::Notification && !self.notification_due(&event.session) { + return; + } + let Some(session) = sessions.get(&event.session) else { return }; + let info = session.info(); + let payload = payload(event, info.name.as_deref().unwrap_or(&info.title)); + let subscriptions = match self.store.push_subscriptions() { + Ok(subscriptions) => subscriptions, + Err(err) => return log::error!("reading push subscriptions: {err:#}"), + }; + let Ok(body) = serde_json::to_vec(&payload) else { return }; + let body: Arc<[u8]> = body.into(); + for subscription in subscriptions { + if !sends(&subscription, wanted, |user| session.typed_recently(user, TYPING_QUIET)) { + continue; + } + let (this, body, urgent) = (self.clone(), body.clone(), payload.renotify); + tokio::spawn(async move { + let delivery = this.sender.send(&subscription, &body, urgent).await; + this.settle(&subscription, &delivery); + }); + } + } + + /// Whether a program's notification may be pushed for `session` now: + /// at most one per [`NOTIFICATION_QUIET`]. + fn notification_due(&self, session: &str) -> bool { + let now = Instant::now(); + let mut notified = self.notified.lock(); + notified.retain(|_, at| now.duration_since(*at) < NOTIFICATION_QUIET); + if notified.contains_key(session) { + return false; + } + notified.insert(session.to_owned(), now); + true + } + + /// Drops a subscription that is gone; logs a failure. + fn settle(&self, subscription: &PushSubscription, delivery: &Delivery) { + match delivery { + Delivery::Sent => {} + Delivery::Gone => { + log::info!("dropping a push subscription its service no longer knows"); + if let Err(err) = self.store.drop_push_subscription(subscription.id) { + log::error!("dropping a push subscription: {err:#}"); + } + } + // The endpoint is the browser's capability: it stays out of the log. + Delivery::Failed(why) => log::warn!("a push message was not delivered: {why}"), + } + } +} + +/// Checks a subscription from a browser: an endpoint the server may post +/// to, and keys of the right shape. +pub fn check_subscription(req: &PushSubscribeRequest) -> Result { + target::check_endpoint(&req.endpoint)?; + let decode = |text: &str| URL_SAFE_NO_PAD.decode(text.trim_end_matches('=')).ok(); + let p256dh = decode(&req.keys.p256dh) + .filter(|k| PublicKey::from_sec1_bytes(k).is_ok()) + .ok_or("the subscription's p256dh key is not a P-256 public key")?; + let auth = decode(&req.keys.auth) + .filter(|a| a.len() == AUTH_LEN) + .ok_or("the subscription's auth secret is not 16 bytes")?; + Ok(SubscriptionKeys { p256dh, auth }) +} + +/// Whether `subscription` is sent a `wanted` message: it asked for that +/// kind, and its user is not `typing` into the session. +fn sends(subscription: &PushSubscription, wanted: PushEvent, typing: impl Fn(i64) -> bool) -> bool { + subscription.events.contains(&wanted) && !typing(subscription.user_id) +} + +/// What kind of push `event` is; `None` for events never pushed (the +/// bell, a clean exit). +fn push_event(event: &SessionEvent) -> Option { + match event.kind { + EventKind::ApprovalRequested => Some(PushEvent::ApprovalRequested), + EventKind::NeedsInput => Some(PushEvent::NeedsInput), + EventKind::Finished => Some(PushEvent::Finished), + EventKind::Notification => Some(PushEvent::Notification), + EventKind::Exited => match event.body.as_deref() { + Some("0") | Some("unknown") | None => None, + Some(_) => Some(PushEvent::Failed), + }, + EventKind::Bell => None, + } +} + +/// The message for `event` on the session called `name`. +fn payload(event: &SessionEvent, name: &str) -> PushPayload { + let (title, body) = match event.kind { + EventKind::ApprovalRequested => { + let tool = event.title.as_deref().unwrap_or("a tool"); + (format!("{name} asks to run {tool}"), event.body.clone()) + } + EventKind::NeedsInput => (format!("{name} needs your input"), event.body.clone()), + EventKind::Finished => (format!("{name} finished"), event.body.clone()), + EventKind::Exited => (format!("{name} exited with code {}", event.body.as_deref().unwrap_or("unknown")), None), + EventKind::Notification | EventKind::Bell => { + (event.title.clone().unwrap_or_else(|| name.to_owned()), event.body.clone()) + } + }; + PushPayload { + title: truncate(&title, MAX_TITLE), + body: truncate(body.as_deref().unwrap_or_default(), MAX_BODY), + session: Some(event.session.clone()), + kind: Some(event.kind), + // One notification per session: a newer one replaces it. + tag: format!("session-{}", event.session), + renotify: matches!(event.kind, EventKind::ApprovalRequested | EventKind::NeedsInput), + url: format!("/s/{}", event.session), + at: event.at, + } +} diff --git a/crates/redshell-server/src/push/sender.rs b/crates/redshell-server/src/push/sender.rs new file mode 100644 index 0000000..800f4eb --- /dev/null +++ b/crates/redshell-server/src/push/sender.rs @@ -0,0 +1,105 @@ +//! Sends one Web Push message: RFC 8291 encryption and a VAPID signature +//! (`web-push-native`), posted with `reqwest` over rustls. Redirects and +//! proxies are off, and names resolve to public addresses only. + +use std::time::Duration; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use web_push_native::jwt_simple::algorithms::{ECDSAP256PublicKeyLike as _, ES256KeyPair}; +use web_push_native::p256::PublicKey; +use web_push_native::{Auth, WebPushBuilder}; + +use super::target::{PublicResolver, check_endpoint}; +use crate::store::PushSubscription; + +/// How long a push service keeps a message for an offline device; also the +/// lifetime of the VAPID signature (at most 24 hours). +const MESSAGE_TTL: Duration = Duration::from_secs(60 * 60); +/// A push service that has not answered by then is skipped. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(15); +/// Bytes of a subscription's auth secret. +pub const AUTH_LEN: usize = 16; + +/// What became of a message. +#[derive(Debug, PartialEq, Eq)] +pub enum Delivery { + Sent, + /// The subscription is gone for good (404, 410): forget it. + Gone, + Failed(String), +} + +pub struct Sender { + http: reqwest::Client, + vapid: ES256KeyPair, + /// VAPID `sub`: who runs this server, for the push service. + contact: String, + /// Off only in tests, which post to a local fake push service. + check_targets: bool, +} + +impl Sender { + pub fn new(vapid: ES256KeyPair, contact: String) -> anyhow::Result { + let http = reqwest::Client::builder() + .dns_resolver(std::sync::Arc::new(PublicResolver)) + .redirect(reqwest::redirect::Policy::none()) + .no_proxy() + .timeout(REQUEST_TIMEOUT) + .user_agent(concat!("redshell-server/", env!("CARGO_PKG_VERSION"))) + .build()?; + Ok(Self { http, vapid, contact, check_targets: true }) + } + + /// Posts anywhere, for tests against a local push service. + #[cfg(test)] + pub fn unchecked(vapid: ES256KeyPair, contact: String) -> Self { + let http = reqwest::Client::builder().no_proxy().build().unwrap(); + Self { http, vapid, contact, check_targets: false } + } + + /// The VAPID public key (uncompressed point, base64url): the + /// `applicationServerKey` browsers subscribe with. + pub fn public_key(&self) -> String { + URL_SAFE_NO_PAD.encode(self.vapid.public_key().public_key().to_bytes_uncompressed()) + } + + /// Encrypts `payload` for `subscription` and posts it. + pub async fn send(&self, subscription: &PushSubscription, payload: &[u8], urgent: bool) -> Delivery { + match self.request(subscription, payload, urgent) { + Ok(request) => match self.http.execute(request).await { + Ok(response) => match response.status().as_u16() { + 200..=299 => Delivery::Sent, + 404 | 410 => Delivery::Gone, + status => Delivery::Failed(format!("the push service answered {status}")), + }, + // The endpoint is the browser's capability: keep it out of messages and logs. + Err(err) => Delivery::Failed(format!("{}", err.without_url())), + }, + Err(err) => Delivery::Failed(format!("{err:#}")), + } + } + + fn request( + &self, + subscription: &PushSubscription, + payload: &[u8], + urgent: bool, + ) -> anyhow::Result { + if self.check_targets { + check_endpoint(&subscription.endpoint).map_err(anyhow::Error::msg)?; + } + let ua_public = PublicKey::from_sec1_bytes(&subscription.p256dh)?; + // `clone_from_slice` panics on any other length. + anyhow::ensure!(subscription.auth.len() == AUTH_LEN, "the subscription's auth secret is malformed"); + let ua_auth = Auth::clone_from_slice(&subscription.auth); + let request = WebPushBuilder::new(subscription.endpoint.parse()?, ua_public, ua_auth) + .with_valid_duration(MESSAGE_TTL) + .with_vapid(&self.vapid, &self.contact) + .build(payload)?; + let mut request = reqwest::Request::try_from(request)?; + let urgency = if urgent { "high" } else { "normal" }; + request.headers_mut().insert("urgency", reqwest::header::HeaderValue::from_static(urgency)); + Ok(request) + } +} diff --git a/crates/redshell-server/src/push/target.rs b/crates/redshell-server/src/push/target.rs new file mode 100644 index 0000000..95a5a9b --- /dev/null +++ b/crates/redshell-server/src/push/target.rs @@ -0,0 +1,161 @@ +//! Where push requests may go. A push endpoint comes from a browser, so it +//! is input: the server only posts to `https` on the default port, to a +//! host name (never an IP literal) that resolves to public addresses only; +//! IPv6 ranges that reach IPv4 addresses (6to4, Teredo, NAT64) count as +//! not public, as the address inside may be private. +//! Name resolution goes through [`PublicResolver`], so a name that +//! resolves to a private address at sending time is refused too. + +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use reqwest::Url; +use reqwest::dns::{Addrs, Name, Resolve, Resolving}; + +/// Longest endpoint accepted. +const MAX_ENDPOINT: usize = 2048; + +/// The endpoint as a URL, if the server may post to it. +pub fn check_endpoint(endpoint: &str) -> Result { + let refuse = |why: &str| Err(format!("this push endpoint is not accepted: {why}")); + if endpoint.len() > MAX_ENDPOINT { + return refuse("it is too long"); + } + let Ok(url) = Url::parse(endpoint) else { return refuse("it is not a URL") }; + if url.scheme() != "https" { + return refuse("it is not https"); + } + if !url.username().is_empty() || url.password().is_some() { + return refuse("it carries credentials"); + } + if url.port().is_some_and(|p| p != 443) { + return refuse("it is not on port 443"); + } + match url.host() { + Some(url::Host::Domain(name)) if name.contains('.') && !name.ends_with(".localhost") => Ok(url), + Some(url::Host::Domain(_)) => refuse("its host is not a public name"), + Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) => refuse("its host is an IP address"), + None => refuse("it has no host"), + } +} + +/// Whether `ip` is reachable on the public internet: not loopback, +/// private, shared (CGNAT and tailnets), link-local, multicast, +/// documentation or reserved, also when wrapped in an IPv6 address. +pub fn is_public(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => is_public_v4(v4), + IpAddr::V6(v6) => { + if let Some(v4) = v6.to_ipv4_mapped() { + return is_public_v4(v4); + } + let s = v6.segments(); + // NAT64 (64:ff9b::/96) embeds an IPv4 address in the last 32 bits. + if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] { + return is_public_v4(Ipv4Addr::from(((s[6] as u32) << 16) | s[7] as u32)); + } + !(v6.is_loopback() + || v6.is_unspecified() + || v6.is_multicast() + || (s[0] & 0xfe00) == 0xfc00 // unique local + || (s[0] & 0xffc0) == 0xfe80 // link-local + || (s[0] & 0xffc0) == 0xfec0 // site-local + || (s[0] == 0x2001 && s[1] == 0x0db8) // documentation + || (s[0] == 0x2001 && s[1] == 0) // Teredo, which tunnels to an IPv4 address + || s[0] == 0x2002 // 6to4, which embeds an IPv4 address + || s[..3] == [0x64, 0xff9b, 1] // local-use NAT64 + || s[..5] == [0, 0, 0, 0, 0]) // IPv4-compatible and other reserved + } + } +} + +fn is_public_v4(ip: Ipv4Addr) -> bool { + let [a, b, c, _] = ip.octets(); + !(ip.is_private() + || ip.is_loopback() + || ip.is_link_local() + || ip.is_multicast() + || ip.is_broadcast() + || ip.is_documentation() + || ip.is_unspecified() + || a == 0 + || (a == 100 && (64..128).contains(&b)) // shared: CGNAT, Tailscale + || (a == 192 && b == 0 && c == 0) // IETF protocol assignments + || (a == 198 && (18..20).contains(&b)) // benchmarking + || a >= 240) // reserved +} + +/// Resolves names like the system does, keeping public addresses only. +#[derive(Debug, Clone, Copy, Default)] +pub struct PublicResolver; + +impl Resolve for PublicResolver { + fn resolve(&self, name: Name) -> Resolving { + Box::pin(async move { + let host = name.as_str().to_owned(); + let found: Vec = tokio::net::lookup_host((host.as_str(), 0)).await?.collect(); + let public: Vec = found.into_iter().filter(|a| is_public(a.ip())).collect(); + if public.is_empty() { + return Err(format!("{host} has no public address").into()); + } + Ok(Box::new(public.into_iter()) as Addrs) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_https_names_on_the_default_port() { + assert!(check_endpoint("https://fcm.googleapis.com/fcm/send/abc").is_ok()); + assert!(check_endpoint("https://web.push.apple.com:443/QG").is_ok()); + for refused in [ + "http://fcm.googleapis.com/x", + "https://fcm.googleapis.com:8443/x", + "https://127.0.0.1/x", + "https://[::1]/x", + "https://10.0.0.1/x", + "https://localhost/x", + "https://box.localhost/x", + "https://user:pw@push.example/x", + "file:///etc/passwd", + "not a url", + ] { + assert!(check_endpoint(refused).is_err(), "{refused}"); + } + } + + #[test] + fn private_and_special_addresses_are_not_public() { + for ip in [ + "127.0.0.1", + "10.1.2.3", + "172.16.0.1", + "192.168.1.1", + "169.254.169.254", + "100.64.0.1", + "100.100.100.100", + "0.0.0.0", + "224.0.0.1", + "255.255.255.255", + "198.18.0.1", + "::1", + "::", + "fd7a:115c:a1e0::1", + "fe80::1", + "::ffff:10.0.0.1", + "64:ff9b::a00:1", + "64:ff9b:1::8.8.8.8", + "2002:a00:1::1", + "2002:808:808::1", + "2001:0:4136:e378::1", + "2001:db8::1", + ] { + assert!(!is_public(ip.parse().unwrap()), "{ip}"); + } + for ip in ["142.250.74.10", "2a00:1450:4001:80b::200a", "::ffff:142.250.74.10", "100.128.0.1"] { + assert!(is_public(ip.parse().unwrap()), "{ip}"); + } + } +} diff --git a/crates/redshell-server/src/push/tests.rs b/crates/redshell-server/src/push/tests.rs new file mode 100644 index 0000000..234835f --- /dev/null +++ b/crates/redshell-server/src/push/tests.rs @@ -0,0 +1,173 @@ +//! Push against a local fake push service: the message arrives encrypted +//! for the browser's keys (RFC 8291) and signed (VAPID), and a +//! subscription the service no longer knows is dropped. + +use std::sync::Arc; + +use axum::Router; +use axum::body::Bytes; +use axum::extract::State; +use axum::http::{HeaderMap, StatusCode}; +use axum::routing::post; +use redshell_protocol::{PushSubscriptionKeys, SessionEvent}; +use tokio::sync::mpsc; +use web_push_native::p256::SecretKey; +use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint as _; + +use super::*; +use crate::store::Credential; + +/// What the fake push service received. +type Received = (HeaderMap, Bytes); + +/// A push service on loopback: `/ok` takes messages, `/gone` answers 410. +async fn push_service() -> (String, mpsc::UnboundedReceiver) { + let (tx, rx) = mpsc::unbounded_channel(); + let app = Router::new() + .route( + "/ok", + post(|State(tx): State>, headers: HeaderMap, body: Bytes| async move { + let _ = tx.send((headers, body)); + StatusCode::CREATED + }), + ) + .route("/gone", post(|| async { StatusCode::GONE })) + .with_state(tx); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (base, rx) +} + +/// A browser's subscription keys. +struct BrowserKeys { + secret: SecretKey, + auth: [u8; AUTH_LEN], +} + +impl BrowserKeys { + fn new() -> Self { + Self { secret: SecretKey::random(&mut rand_core::OsRng), auth: *b"0123456789abcdef" } + } + + fn public(&self) -> Vec { + self.secret.public_key().to_encoded_point(false).as_bytes().to_vec() + } +} + +fn push(store: Arc) -> Push { + let sender = Sender::unchecked(ES256KeyPair::generate(), "mailto:test@example.com".into()); + Push { sender, store, notified: Mutex::default() } +} + +fn subscribed(store: &Store, endpoint: &str, keys: &BrowserKeys) -> PushSubscription { + let user = store.create_user("u", "h").unwrap().unwrap(); + let Credential::Browser(browser) = + store.create_browser_session(user.id, b"t", now_ms() + 60_000, "ip", None, "Browser").unwrap() + else { + unreachable!() + }; + store.set_push_subscription(user.id, browser, endpoint, (&keys.public(), &keys.auth), &PushEvent::ALL).unwrap(); + store.push_subscription(user.id, endpoint).unwrap().unwrap() +} + +#[tokio::test] +async fn messages_arrive_encrypted_for_the_browser_and_signed() { + let (base, mut received) = push_service().await; + let store = Arc::new(Store::in_memory()); + let keys = BrowserKeys::new(); + let push = push(store.clone()); + let subscription = subscribed(&store, &format!("{base}/ok"), &keys); + assert_eq!(push.test(subscription).await, Delivery::Sent); + + let (headers, body) = received.recv().await.unwrap(); + assert_eq!(headers["content-encoding"], "aes128gcm"); + assert_eq!(headers["urgency"], "high"); + assert!(headers.contains_key("ttl")); + let vapid = headers["authorization"].to_str().unwrap(); + assert!(vapid.starts_with("vapid t=") && vapid.ends_with(&format!("k={}", push.public_key())), "{vapid}"); + let auth = web_push_native::Auth::clone_from_slice(&keys.auth); + let plain = web_push_native::decrypt(body.to_vec(), &keys.secret, &auth).unwrap(); + let payload: PushPayload = serde_json::from_slice(&plain).unwrap(); + assert_eq!((payload.title.as_str(), payload.url.as_str()), ("RedShell", "/")); +} + +#[test] +fn the_vapid_key_is_kept_across_starts() { + let store = Arc::new(Store::in_memory()); + let first = Push::new(store.clone(), Some("https://box.example")).unwrap().public_key(); + assert_eq!(Push::new(store, None).unwrap().public_key(), first); +} + +#[tokio::test] +async fn a_subscription_its_service_forgot_is_dropped() { + let (base, _received) = push_service().await; + let store = Arc::new(Store::in_memory()); + let subscription = subscribed(&store, &format!("{base}/gone"), &BrowserKeys::new()); + assert_eq!(push(store.clone()).test(subscription).await, Delivery::Gone); + assert!(store.push_subscriptions().unwrap().is_empty()); +} + +#[test] +fn program_notifications_are_pushed_at_most_every_few_seconds() { + let push = push(Arc::new(Store::in_memory())); + assert!(push.notification_due("s1")); + assert!(!push.notification_due("s1"), "a program printing OSC 9 in a loop"); + assert!(push.notification_due("s2"), "other sessions are their own"); +} + +#[test] +fn subscriptions_are_checked() { + let keys = BrowserKeys::new(); + let request = |endpoint: &str, auth: &[u8]| PushSubscribeRequest { + endpoint: endpoint.into(), + keys: PushSubscriptionKeys { + p256dh: URL_SAFE_NO_PAD.encode(keys.public()), + auth: URL_SAFE_NO_PAD.encode(auth), + }, + events: None, + }; + let checked = check_subscription(&request("https://fcm.googleapis.com/fcm/send/x", &keys.auth)).unwrap(); + assert_eq!((checked.p256dh, checked.auth), (keys.public(), keys.auth.to_vec())); + assert!(check_subscription(&request("https://fcm.googleapis.com/x", b"short")).is_err()); + assert!(check_subscription(&request("http://fcm.googleapis.com/x", &keys.auth)).is_err()); + assert!(check_subscription(&request("https://169.254.169.254/x", &keys.auth)).is_err()); + let mut bad_key = request("https://fcm.googleapis.com/x", &keys.auth); + bad_key.keys.p256dh = URL_SAFE_NO_PAD.encode([4u8; 65]); + assert!(check_subscription(&bad_key).is_err()); +} + +#[test] +fn events_become_short_messages_for_those_who_want_them() { + let event = |kind, title: Option<&str>, body: Option<&str>| SessionEvent { + session: "s1".into(), + kind, + title: title.map(Into::into), + body: body.map(Into::into), + at: 5, + }; + let approval = event(EventKind::ApprovalRequested, Some("Bash"), Some("rm -rf build")); + assert_eq!(push_event(&approval), Some(PushEvent::ApprovalRequested)); + let message = payload(&approval, "api"); + assert_eq!((message.title.as_str(), message.body.as_str()), ("api asks to run Bash", "rm -rf build")); + assert_eq!((message.url.as_str(), message.renotify, message.session.as_deref()), ("/s/s1", true, Some("s1"))); + + assert_eq!(push_event(&event(EventKind::Exited, None, Some("0"))), None, "a clean exit"); + assert_eq!(push_event(&event(EventKind::Exited, None, Some("2"))), Some(PushEvent::Failed)); + assert_eq!(push_event(&event(EventKind::Bell, None, None)), None); + let long = "x".repeat(5000); + let finished = payload(&event(EventKind::Finished, None, Some(&long)), "api"); + assert_eq!((finished.body.chars().count(), finished.renotify), (MAX_BODY + 1, false)); + + let subscription = PushSubscription { + id: 1, + user_id: 7, + endpoint: String::new(), + p256dh: Vec::new(), + auth: Vec::new(), + events: vec![PushEvent::Finished], + }; + assert!(sends(&subscription, PushEvent::Finished, |_| false)); + assert!(!sends(&subscription, PushEvent::Finished, |user| user == 7), "typing into the session"); + assert!(!sends(&subscription, PushEvent::NeedsInput, |_| false), "not asked for"); +} diff --git a/crates/redshell-server/src/sessions/launch.rs b/crates/redshell-server/src/sessions/launch.rs new file mode 100644 index 0000000..9c5ff12 --- /dev/null +++ b/crates/redshell-server/src/sessions/launch.rs @@ -0,0 +1,188 @@ +//! What a new session runs: the profiles the server offers and how a +//! create request becomes a command line. + +use std::path::{Path, PathBuf}; + +use redshell_agents::AgentRegistry; +use redshell_core::shell::LocalShell; +use redshell_core::shell_integration::ShellIntegration; +use redshell_core::{CommandSpec, Launchable as _, Settings}; +use redshell_protocol::{CreateSessionRequest, Profile, SessionKind}; +use redshell_remote::SshProvider; + +/// Id of the default shell's profile. +pub const SHELL: &str = "shell"; + +/// A resolved request: the command and what it was started from. +#[derive(Debug, Clone)] +pub struct Launch { + pub spec: CommandSpec, + pub kind: SessionKind, + pub profile: Option, + pub profile_name: Option, + /// Agent id for agent sessions. + pub agent: Option, + pub command: Option>, + pub start_cwd: Option, + /// Title until the program sets one. + pub title: String, +} + +/// Everything a session can start from, on this server. +pub fn profiles(settings: &Settings) -> Vec { + let shell = LocalShell::from_settings(&settings.terminal); + let mut out = vec![Profile { + id: SHELL.into(), + name: shell.name(), + kind: SessionKind::Shell, + description: shell.description(), + available: true, + group: None, + }]; + for agent in AgentRegistry::detect(&settings.agents).agents() { + out.push(Profile { + id: format!("agent:{}", agent.id), + name: agent.name.clone(), + kind: SessionKind::Agent, + description: agent.description(), + available: agent.available(), + group: None, + }); + } + for host in SshProvider::new(&settings.ssh).hosts() { + out.push(Profile { + id: format!("ssh:{}", host.host.name), + name: host.name(), + kind: SessionKind::Ssh, + description: host.description(), + available: host.available(), + group: host.host.group.clone(), + }); + } + out +} + +/// Turns a create request into a command. Errors are for the client. +pub fn resolve(req: &CreateSessionRequest, settings: &Settings, config_dir: &Path) -> Result { + let cwd = match req.cwd.as_deref().filter(|c| !c.trim().is_empty()) { + Some(cwd) => Some(folder(cwd)?), + None => None, + }; + let mut launch = match (&req.command, req.profile.as_deref()) { + (Some(_), Some(_)) => return Err("give a profile or a command, not both".into()), + (Some(argv), None) => { + let (program, args) = argv.split_first().ok_or("the command is empty")?; + Launch { + spec: CommandSpec::new(program).args(args.iter().cloned()), + kind: SessionKind::Command, + profile: None, + profile_name: None, + agent: None, + command: Some(argv.clone()), + start_cwd: None, + title: program.clone(), + } + } + (None, None | Some(SHELL)) => { + let shell = LocalShell::from_settings(&settings.terminal); + let mut spec = shell.command(); + if settings.terminal.shell_integration + && let Err(err) = ShellIntegration::new(config_dir).apply(&mut spec) + { + log::warn!("shell integration: {err}"); + } + from_profile(SHELL, shell.name(), SessionKind::Shell, None, spec) + } + (None, Some(id)) => { + if let Some(agent_id) = id.strip_prefix("agent:") { + let registry = AgentRegistry::detect(&settings.agents); + let agent = registry.get(agent_id).filter(|a| a.available()).ok_or("that agent is not installed")?; + from_profile(id, agent.name.clone(), SessionKind::Agent, Some(agent_id.into()), agent.command()) + } else if let Some(host) = id.strip_prefix("ssh:") { + let provider = SshProvider::new(&settings.ssh); + let host = provider.find(host).ok_or("no such SSH host")?; + from_profile(id, host.name(), SessionKind::Ssh, None, host.command()) + } else { + return Err(format!("no profile {id:?}")); + } + } + }; + let cwd = cwd + .or_else(|| launch.spec.cwd.clone()) + .or_else(|| settings.terminal.working_directory.clone()) + .or_else(dirs::home_dir); + launch.start_cwd = cwd.as_ref().map(|c| c.display().to_string()); + launch.spec.cwd = cwd; + for (key, value) in &settings.terminal.env { + launch.spec.env.entry(key.clone()).or_insert_with(|| value.clone()); + } + Ok(launch) +} + +fn from_profile(id: &str, name: String, kind: SessionKind, agent: Option, spec: CommandSpec) -> Launch { + Launch { + spec, + kind, + profile: Some(id.into()), + title: name.clone(), + profile_name: Some(name), + agent, + command: None, + start_cwd: None, + } +} + +/// An existing absolute folder (`~` is the server user's home). +pub fn folder(path: &str) -> Result { + let path = match path.strip_prefix('~') { + Some(rest) if rest.is_empty() || rest.starts_with('/') => { + dirs::home_dir().ok_or("the server user has no home folder")?.join(rest.trim_start_matches('/')) + } + _ => PathBuf::from(path), + }; + if !path.is_absolute() { + return Err("the folder must be an absolute path".into()); + } + if !path.is_dir() { + return Err(format!("{} is not a folder", path.display())); + } + Ok(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_profiles_and_folders() { + let dir = tempfile::tempdir().unwrap(); + let settings = Settings::from_toml( + "[ssh]\nimport_ssh_config = false\n[[ssh.hosts]]\nname = \"box\"\nhost = \"box.lan\"\ngroup = \"lab\"\n", + ) + .unwrap(); + let cwd = dir.path().display().to_string(); + let req = CreateSessionRequest { + command: Some(vec!["sh".into(), "-c".into(), "true".into()]), + cwd: Some(cwd.clone()), + ..Default::default() + }; + let launch = resolve(&req, &settings, dir.path()).unwrap(); + assert_eq!((launch.kind, launch.spec.args.len()), (SessionKind::Command, 2)); + assert_eq!(launch.start_cwd.as_deref(), Some(cwd.as_str())); + + let ssh = resolve( + &CreateSessionRequest { profile: Some("ssh:box".into()), ..Default::default() }, + &settings, + dir.path(), + ) + .unwrap(); + assert_eq!((ssh.kind, ssh.profile_name.as_deref()), (SessionKind::Ssh, Some("box"))); + assert!(ssh.spec.args.contains(&"box.lan".to_string())); + assert!(profiles(&settings).iter().any(|p| p.id == "ssh:box" && p.group.as_deref() == Some("lab"))); + + let bad = |req: CreateSessionRequest| resolve(&req, &settings, dir.path()).unwrap_err(); + bad(CreateSessionRequest { profile: Some("nope".into()), ..Default::default() }); + bad(CreateSessionRequest { command: Some(vec![]), ..Default::default() }); + assert!(bad(CreateSessionRequest { cwd: Some("relative".into()), ..Default::default() }).contains("absolute")); + } +} diff --git a/crates/redshell-server/src/sessions/mod.rs b/crates/redshell-server/src/sessions/mod.rs new file mode 100644 index 0000000..da38b25 --- /dev/null +++ b/crates/redshell-server/src/sessions/mod.rs @@ -0,0 +1,145 @@ +//! The server's terminal sessions: created from profiles, kept until they +//! are killed, whoever is connected. + +pub mod launch; +mod output; +mod session; + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use parking_lot::RwLock; +use redshell_protocol::{CreateSessionRequest, EventKind, SessionInfo, SessionKind, User}; + +pub use output::Feed; +pub use session::{AgentHook, Session, session_name}; + +use crate::agents::{self, Approvals}; +use crate::bus::{Bus, BusEvent}; +use crate::config::LiveSettings; +use crate::now_ms; +use crate::store::Store; + +/// What sessions share with the rest of the server. +pub struct Ctx { + /// `config.toml`, which the hosts API edits while sessions run. + pub settings: LiveSettings, + pub config_dir: PathBuf, + pub runtime_dir: PathBuf, + pub bus: Bus, + pub store: Arc, + pub approvals: Approvals, + pub runtime: tokio::runtime::Handle, + /// The loopback listener agent hooks post to. + pub hook_addr: SocketAddr, + pub approval_timeout: Duration, +} + +impl Ctx { + /// Raises an event on `session` for every subscribed client. + pub fn event(&self, session: &str, kind: EventKind, title: Option, body: Option) { + let event = redshell_protocol::SessionEvent { session: session.to_owned(), kind, title, body, at: now_ms() }; + self.bus.send(BusEvent::Event(event)); + } +} + +#[derive(Debug, thiserror::Error)] +pub enum CreateError { + #[error("{0}")] + BadRequest(String), + #[error(transparent)] + Failed(#[from] anyhow::Error), +} + +pub struct Sessions { + ctx: Arc, + map: RwLock>>, +} + +impl Sessions { + pub fn new(ctx: Arc) -> Self { + Self { ctx, map: RwLock::new(HashMap::new()) } + } + + pub fn ctx(&self) -> &Arc { + &self.ctx + } + + pub fn create(&self, req: CreateSessionRequest, user: &User) -> Result { + let name = session_name(req.name.clone()).map_err(CreateError::BadRequest)?; + let mut launch = + launch::resolve(&req, &self.ctx.settings.get(), &self.ctx.config_dir).map_err(CreateError::BadRequest)?; + let id = uuid::Uuid::new_v4().to_string(); + let hook = agents::prepare(&mut launch, &id, &self.ctx)?; + let size = (req.cols.unwrap_or(100), req.rows.unwrap_or(30)); + let command = launch.spec.display(); + let session = match Session::spawn(id.clone(), launch, hook, size, self.ctx.clone()) { + Ok(session) => session, + Err(err) => return Err(CreateError::BadRequest(format!("{err:#}"))), + }; + if name.is_some() { + session.rename(name); + } + let launch = &session.launch; + let kind = match launch.kind { + SessionKind::Shell => "shell", + SessionKind::Agent => "agent", + SessionKind::Ssh => "ssh", + SessionKind::Command => "command", + }; + let row = crate::store::SessionRow { + id: &id, + kind, + profile: launch.profile.as_deref(), + command: &command, + cwd: launch.start_cwd.as_deref(), + created_by: user.id, + created_at: session.created_at, + }; + if let Err(err) = self.ctx.store.record_session(&row) { + log::error!("recording session {id}: {err:#}"); + } + // The command line stays in the session record: arguments can carry secrets. + log::info!("{} started {kind} session {id}", user.username); + let info = session.info(); + self.map.write().insert(id.clone(), session); + self.ctx.bus.send(BusEvent::SessionChanged(id)); + Ok(info) + } + + pub fn get(&self, id: &str) -> Option> { + self.map.read().get(id).cloned() + } + + /// Every session, oldest first. + pub fn list(&self) -> Vec { + let sessions: Vec> = self.map.read().values().cloned().collect(); + let mut list: Vec = sessions.iter().map(|s| s.info()).collect(); + list.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id))); + list + } + + /// Ends a session and forgets it; `false` when there is none. + pub fn kill(&self, id: &str) -> bool { + let Some(session) = self.map.write().remove(id) else { return false }; + session.kill(); + if !session.is_exited() + && let Err(err) = self.ctx.store.record_session_end(id, None) + { + log::error!("recording the end of session {id}: {err:#}"); + } + self.ctx.bus.send(BusEvent::SessionRemoved(id.to_owned())); + true + } + + /// Kills everything (the server is stopping). + pub fn shutdown(&self) { + let ids: Vec = self.map.read().keys().cloned().collect(); + for id in ids { + self.kill(&id); + } + } +} diff --git a/crates/redshell-server/src/sessions/output.rs b/crates/redshell-server/src/sessions/output.rs new file mode 100644 index 0000000..fe9d2f7 --- /dev/null +++ b/crates/redshell-server/src/sessions/output.rs @@ -0,0 +1,93 @@ +//! Fans a session's output out to its attached clients without ever +//! waiting for one. +//! +//! Every client gets a bounded queue. The PTY reader pushes with +//! `try_send`; a client whose queue is full is dropped from the hub, sees +//! its queue end, and comes back with a fresh snapshot. So a slow phone on +//! a bad network never holds up the program or the other clients, and its +//! backlog is bounded. + +use std::sync::Arc; + +use parking_lot::Mutex; +use tokio::sync::mpsc; + +/// Chunks a client may have queued before it is dropped and resynced. +const QUEUE: usize = 32; + +#[derive(Debug, Clone)] +pub enum Feed { + /// Program output; `end` is the output offset just past these bytes. + Output { + end: u64, + bytes: Arc<[u8]>, + }, + Resized { + cols: u16, + rows: u16, + }, + /// The program left the alternate screen, after the output that did. + /// A client that joined while it was up has no normal screen behind it. + LeftAltScreen, +} + +#[derive(Default)] +pub struct OutputHub { + /// `None` once the session is gone. + subscribers: Mutex>>>, +} + +impl OutputHub { + pub fn new() -> Self { + Self { subscribers: Mutex::new(Some(Vec::new())) } + } + + /// A queue that receives everything published from now on. It ends + /// when the client falls behind or the session goes away. + pub fn subscribe(&self) -> mpsc::Receiver { + let (tx, rx) = mpsc::channel(QUEUE); + if let Some(subscribers) = self.subscribers.lock().as_mut() { + subscribers.push(tx); + } + rx + } + + pub fn publish(&self, feed: Feed) { + if let Some(subscribers) = self.subscribers.lock().as_mut() { + subscribers.retain(|tx| tx.try_send(feed.clone()).is_ok()); + } + } + + /// Ends every queue for good. + pub fn close(&self) { + self.subscribers.lock().take(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn output(end: u64) -> Feed { + Feed::Output { end, bytes: Arc::from(&b"x"[..]) } + } + + #[tokio::test] + async fn a_full_queue_is_dropped_and_others_keep_going() { + let hub = OutputHub::new(); + let mut slow = hub.subscribe(); + let mut fast = hub.subscribe(); + for end in 1..=QUEUE as u64 + 1 { + hub.publish(output(end)); + assert!(matches!(fast.recv().await, Some(Feed::Output { end: e, .. }) if e == end)); + } + let mut drained = 0; + while slow.recv().await.is_some() { + drained += 1; + } + assert_eq!(drained, QUEUE, "the slow queue ends after what it held"); + hub.close(); + assert!(fast.recv().await.is_none()); + assert!(hub.subscribe().recv().await.is_none(), "nothing after close"); + } +} diff --git a/crates/redshell-server/src/sessions/session.rs b/crates/redshell-server/src/sessions/session.rs new file mode 100644 index 0000000..ae2191d --- /dev/null +++ b/crates/redshell-server/src/sessions/session.rs @@ -0,0 +1,454 @@ +//! One server-owned terminal session. +//! +//! The session owns a [`Terminal`] (PTY + VT state) that keeps running +//! whoever is connected. Output reaches clients through the [`OutputHub`], +//! tagged with its byte offset so a client that joins gets a snapshot and +//! then exactly the output after it. A small thread per session drains the +//! terminal's events and writes input, so a program that stops reading its +//! input never blocks an async worker. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::{Duration, Instant}; + +use crossbeam_channel::{Receiver, Sender, TrySendError}; +use parking_lot::Mutex; +use redshell_core::SessionObserver; +use redshell_protocol::{AgentState, ApprovalOutcome, EventKind, ExitState, SessionInfo, SessionKind}; +use redshell_terminal::{GridSize, Replay, Terminal, TerminalEvent, TerminalOptions}; + +use super::Ctx; +use super::launch::Launch; +use super::output::{Feed, OutputHub}; +use crate::bus::BusEvent; +use crate::{now_ms, truncate}; + +/// Lines of history a joining client gets. +pub const REPLAY_SCROLLBACK: usize = 2_000; +/// Session list updates for output are sent at most this often. +const ACTIVITY_DEBOUNCE: Duration = Duration::from_secs(1); +/// Bells closer together than this raise one event. +const BELL_QUIET: Duration = Duration::from_secs(2); +/// Input chunks waiting for a program that does not read. +const INPUT_QUEUE: usize = 1024; +/// Input bytes waiting for a program that does not read; more is refused. +const MAX_QUEUED_INPUT: usize = 4 << 20; +/// Longest session name. +const MAX_NAME: usize = 100; + +/// A session name as given, trimmed; empty means none. Refused past +/// [`MAX_NAME`] characters or with control characters. +pub fn session_name(name: Option) -> Result, String> { + let name = name.map(|n| n.trim().to_owned()).filter(|n| !n.is_empty()); + match name { + Some(n) if n.chars().count() > MAX_NAME || n.chars().any(char::is_control) => { + Err(format!("a session name has at most {MAX_NAME} characters and no control characters")) + } + name => Ok(name), + } +} + +/// A session's hook credentials and the files that carry them. +pub struct AgentHook { + pub token: String, + pub files: Vec, +} + +#[derive(Default)] +struct State { + name: Option, + title: Option, + cwd: Option, + agent_state: Option, + last_message: Option, + exit: Option, + /// The client whose size the session has: the one that typed last. + size_owner: Option, +} + +/// When output last came, and whether a list update for it is scheduled. +struct Activity { + at: AtomicI64, + flush_pending: Arc, +} + +impl Activity { + /// Sends a session list update in a moment, unless one is on its way. + fn schedule_update(&self, ctx: &Ctx, session: &str) { + if !self.flush_pending.swap(true, Ordering::AcqRel) { + let (pending, bus, id) = (self.flush_pending.clone(), ctx.bus.clone(), session.to_owned()); + ctx.runtime.spawn(async move { + tokio::time::sleep(ACTIVITY_DEBOUNCE).await; + pending.store(false, Ordering::Release); + bus.send(BusEvent::SessionChanged(id)); + }); + } + } +} + +pub struct Session { + pub id: String, + pub launch: Launch, + pub created_at: i64, + terminal: Terminal, + hub: Arc, + activity: Arc, + input: Sender>, + /// Bytes in `input`, bounded by [`MAX_QUEUED_INPUT`]. + queued_input: AtomicUsize, + state: Mutex, + /// When each user last typed here, so they are not pushed about it. + typists: Mutex>, + hook: Option, + ctx: Arc, +} + +impl Session { + /// Starts `launch` in a PTY of `cols` × `rows`, kept within what + /// [`clamp_size`] allows. + pub fn spawn( + id: String, + launch: Launch, + hook: Option, + (cols, rows): (u16, u16), + ctx: Arc, + ) -> anyhow::Result> { + let hub = Arc::new(OutputHub::new()); + let terminal_settings = ctx.settings.get().terminal; + let now = now_ms(); + let activity = Arc::new(Activity { at: AtomicI64::new(now), flush_pending: Arc::new(AtomicBool::new(false)) }); + let tap = Tap { + session: id.clone(), + hub: hub.clone(), + activity: activity.clone(), + ctx: ctx.clone(), + offset: 0, + last_bell: None, + }; + let terminal = Terminal::spawn( + &launch.spec, + TerminalOptions { + size: grid(clamp_size(cols, rows)), + scrollback: terminal_settings.scrollback_lines, + term_env: terminal_settings.term, + observer: Some(Box::new(tap)), + ..Default::default() + }, + ) + .inspect_err(|_| { + for file in hook.iter().flat_map(|h| &h.files) { + let _ = std::fs::remove_file(file); + } + })?; + let (input, input_rx) = crossbeam_channel::bounded(INPUT_QUEUE); + let events = terminal.events().clone(); + let agent_state = (launch.kind == SessionKind::Agent).then_some(AgentState::Idle); + let session = Arc::new(Self { + id, + launch, + created_at: now, + terminal, + hub, + activity, + input, + queued_input: AtomicUsize::new(0), + state: Mutex::new(State { agent_state, ..Default::default() }), + typists: Mutex::new(HashMap::new()), + hook, + ctx, + }); + let weak = Arc::downgrade(&session); + std::thread::Builder::new().name("redshell-session".into()).spawn(move || pump(weak, events, input_rx))?; + Ok(session) + } + + pub fn info(&self) -> SessionInfo { + let state = self.state.lock(); + let size = self.terminal.size(); + let launch = &self.launch; + SessionInfo { + id: self.id.clone(), + name: state.name.clone(), + title: state.title.clone().unwrap_or_else(|| launch.title.clone()), + kind: launch.kind, + profile: launch.profile.clone(), + profile_name: launch.profile_name.clone(), + command: launch.command.clone(), + start_cwd: launch.start_cwd.clone(), + agent: launch.agent.clone(), + agent_state: state.agent_state, + last_message: state.last_message.clone(), + cwd: state.cwd.clone().or_else(|| launch.start_cwd.clone()), + cols: size.cols, + rows: size.rows, + created_at: self.created_at, + active_at: self.activity.at.load(Ordering::Relaxed), + last_line: self.terminal.last_line().map(|l| truncate(l.trim_end(), 200)), + exit: state.exit, + pending_approvals: self.ctx.approvals.count(&self.id), + } + } + + /// A queue of output from now on; see [`OutputHub::subscribe`]. + pub fn subscribe(&self) -> tokio::sync::mpsc::Receiver { + self.hub.subscribe() + } + + /// The screen for a joining client. Takes the terminal lock: call it + /// off the async workers. + pub fn replay(&self) -> Replay { + self.terminal.replay(REPLAY_SCROLLBACK) + } + + /// A client attached at its size; the first one sizes the session. + pub fn attached(&self, client: u64, cols: u16, rows: u16) { + let first = { + let mut state = self.state.lock(); + let first = state.size_owner.is_none(); + if first { + state.size_owner = Some(client); + } + first + }; + if first { + self.resize(cols, rows); + } + } + + /// A client's terminal changed size: the session follows if that client + /// owns its size. + pub fn client_resized(&self, client: u64, cols: u16, rows: u16) { + if self.state.lock().size_owner == Some(client) { + self.resize(cols, rows); + } + } + + /// A client detached: it no longer owns the size. + pub fn detached(&self, client: u64) { + let mut state = self.state.lock(); + if state.size_owner == Some(client) { + state.size_owner = None; + } + } + + /// Input from a client of `user`, which takes over the size (tmux's + /// `window-size latest`). `false` when the program is not keeping up: + /// the input is dropped once [`MAX_QUEUED_INPUT`] bytes wait. + pub fn input(&self, client: u64, user: i64, (cols, rows): (u16, u16), bytes: Vec) -> bool { + self.typists.lock().insert(user, Instant::now()); + let submits = bytes.contains(&b'\r'); + { + let mut state = self.state.lock(); + state.size_owner = Some(client); + if state.exit.is_some() { + return true; + } + } + self.resize(cols, rows); + self.activity.at.store(now_ms(), Ordering::Relaxed); + if submits && self.launch.agent.as_deref() != Some("claude") { + // Agents without a prompt hook (Codex) go back to work when the user sends a line; + // Claude Code says so itself (UserPromptSubmit). + self.update_agent(|state, _| { + matches!(state, Some(AgentState::Finished | AgentState::NeedsInput | AgentState::Idle)) + .then_some((AgentState::Working, None)) + }); + } + let len = bytes.len(); + if self.queued_input.fetch_add(len, Ordering::AcqRel) + len > MAX_QUEUED_INPUT { + self.queued_input.fetch_sub(len, Ordering::AcqRel); + return false; + } + match self.input.try_send(bytes) { + Ok(()) => true, + Err(err) => { + self.queued_input.fetch_sub(len, Ordering::AcqRel); + matches!(err, TrySendError::Disconnected(_)) + } + } + } + + fn resize(&self, cols: u16, rows: u16) { + let (cols, rows) = clamp_size(cols, rows); + let size = self.terminal.size(); + if (size.cols, size.rows) == (cols, rows) { + return; + } + self.terminal.resize(grid((cols, rows))); + self.hub.publish(Feed::Resized { cols, rows }); + self.changed(); + } + + /// Names the session; `name` went through [`session_name`]. + pub fn rename(&self, name: Option) { + self.state.lock().name = name; + self.changed(); + } + + /// Changes the agent state when `next` says so, given the current one. + /// `next` returns the new state and, for `Finished`, the last message. + pub fn update_agent( + &self, + next: impl FnOnce(Option, &Option) -> Option<(AgentState, Option)>, + ) { + let changed = { + let mut state = self.state.lock(); + match next(state.agent_state, &state.last_message) { + Some((agent_state, message)) if state.agent_state != Some(agent_state) || message.is_some() => { + state.agent_state = Some(agent_state); + if let Some(message) = message { + state.last_message = Some(truncate(&message, 4000)); + } + true + } + _ => false, + } + }; + if changed { + self.changed(); + } + } + + /// Whether `user` typed here within `within`. + pub fn typed_recently(&self, user: i64, within: Duration) -> bool { + self.typists.lock().get(&user).is_some_and(|at| at.elapsed() < within) + } + + /// Whether `token` is this session's hook token. + pub fn hook_token_matches(&self, token: &str) -> bool { + self.hook.as_ref().is_some_and(|h| crate::auth::secret::same_secret(&h.token, token)) + } + + pub fn is_exited(&self) -> bool { + self.state.lock().exit.is_some() + } + + /// Ends the program and every client's stream. + pub fn kill(&self) { + self.terminal.kill(); + self.hub.close(); + self.release(); + } + + /// Lets go of what only a running program needs. + fn release(&self) { + self.ctx.approvals.settle_session(&self.id, ApprovalOutcome::Gone, None); + for file in self.hook.iter().flat_map(|h| &h.files) { + let _ = std::fs::remove_file(file); + } + } + + pub fn changed(&self) { + self.ctx.bus.send(BusEvent::SessionChanged(self.id.clone())); + } + + fn on_event(&self, event: TerminalEvent) { + match event { + TerminalEvent::Wakeup => self.terminal.ack_wakeup(), + // Agents animate their titles: list updates for them are debounced like output. + TerminalEvent::Title(title) => { + self.state.lock().title = Some(truncate(&title, 200)); + self.activity.schedule_update(&self.ctx, &self.id); + } + TerminalEvent::ResetTitle => { + self.state.lock().title = None; + self.activity.schedule_update(&self.ctx, &self.id); + } + TerminalEvent::Cwd(cwd) => { + self.state.lock().cwd = Some(cwd); + self.changed(); + } + TerminalEvent::Exited(code) => { + self.state.lock().exit = Some(ExitState { code, at: now_ms() }); + self.release(); + if let Err(err) = self.ctx.store.record_session_end(&self.id, code) { + log::error!("recording the end of session {}: {err:#}", self.id); + } + let body = code.map_or_else(|| "unknown".to_owned(), |c| c.to_string()); + self.ctx.event(&self.id, EventKind::Exited, None, Some(body)); + self.changed(); + } + TerminalEvent::Bell | TerminalEvent::ClipboardStore(_) | TerminalEvent::CommandFinished(_) => {} + } + } +} + +impl Drop for Session { + fn drop(&mut self) { + self.release(); + } +} + +/// A client's size as a session takes it: 2 to 1000 columns, 1 to 500 +/// rows. A terminal of 0 × 0 cannot exist, and a huge one would take +/// gigabytes. +fn clamp_size(cols: u16, rows: u16) -> (u16, u16) { + (cols.clamp(2, 1000), rows.clamp(1, 500)) +} + +fn grid((cols, rows): (u16, u16)) -> GridSize { + GridSize { cols, rows, ..GridSize::default() } +} + +/// Drains the terminal's events and writes input, until the session is gone. +fn pump(session: Weak, events: Receiver, input: Receiver>) { + loop { + crossbeam_channel::select! { + recv(events) -> event => { + let (Ok(event), Some(session)) = (event, session.upgrade()) else { break }; + session.on_event(event); + } + recv(input) -> bytes => { + let (Ok(bytes), Some(session)) = (bytes, session.upgrade()) else { break }; + session.terminal.write(&bytes); + session.queued_input.fetch_sub(bytes.len(), Ordering::AcqRel); + } + } + } +} + +/// The session's observer, on the PTY reader thread: output to the hub, +/// bells and notifications to the bus. Never blocks. +struct Tap { + session: String, + hub: Arc, + activity: Arc, + ctx: Arc, + /// Output bytes so far; matches the terminal's count after each chunk. + offset: u64, + last_bell: Option, +} + +impl SessionObserver for Tap { + fn on_output(&mut self, bytes: &[u8]) { + self.offset += bytes.len() as u64; + self.hub.publish(Feed::Output { end: self.offset, bytes: Arc::from(bytes) }); + self.activity.at.store(now_ms(), Ordering::Relaxed); + self.activity.schedule_update(&self.ctx, &self.session); + } + + fn on_bell(&mut self) { + let now = Instant::now(); + if self.last_bell.is_none_or(|last| now.duration_since(last) >= BELL_QUIET) { + self.last_bell = Some(now); + self.ctx.event(&self.session, EventKind::Bell, None, None); + } + } + + fn on_alt_screen(&mut self, active: bool) { + if !active { + self.hub.publish(Feed::LeftAltScreen); + } + } + + fn on_notification(&mut self, title: Option<&str>, body: &str) { + self.ctx.event( + &self.session, + EventKind::Notification, + title.map(|t| truncate(t, 200)), + Some(truncate(body, 1000)), + ); + } +} diff --git a/crates/redshell-server/src/store/audit.rs b/crates/redshell-server/src/store/audit.rs new file mode 100644 index 0000000..7dbcbb5 --- /dev/null +++ b/crates/redshell-server/src/store/audit.rs @@ -0,0 +1,135 @@ +//! Security-relevant events: sign-ins, failures, revocations, approvals. + +use std::sync::atomic::Ordering; + +use rusqlite::params; + +use super::Store; +use crate::now_ms; + +/// Entries older than this are dropped when the server starts, and then +/// with the first entry written each day. +const RETAIN_MS: i64 = 180 * 24 * 60 * 60 * 1000; +/// How often writing an entry prunes the log. +const PRUNE_EVERY_MS: i64 = 24 * 60 * 60 * 1000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AuditEvent { + Setup, + SignIn, + SignInFailed, + SignOut, + PasswordChanged, + PasswordChangeFailed, + CredentialRevoked, + UserAdded, + UserRemoved, + ApprovalAnswered, + HostSaved, + HostRemoved, + PairingRequested, + PairingApproved, + PairingRejected, + Paired, + PasskeyAdded, + PasskeyRemoved, + PasskeyOnly, + PasskeysReset, + Reauthenticated, + ReauthFailed, +} + +impl AuditEvent { + fn name(self) -> &'static str { + match self { + Self::Setup => "setup", + Self::SignIn => "sign_in", + Self::SignInFailed => "sign_in_failed", + Self::SignOut => "sign_out", + Self::PasswordChanged => "password_changed", + Self::PasswordChangeFailed => "password_change_failed", + Self::CredentialRevoked => "credential_revoked", + Self::UserAdded => "user_added", + Self::UserRemoved => "user_removed", + Self::ApprovalAnswered => "approval_answered", + Self::HostSaved => "host_saved", + Self::HostRemoved => "host_removed", + Self::PairingRequested => "pairing_requested", + Self::PairingApproved => "pairing_approved", + Self::PairingRejected => "pairing_rejected", + Self::Paired => "paired", + Self::PasskeyAdded => "passkey_added", + Self::PasskeyRemoved => "passkey_removed", + Self::PasskeyOnly => "passkey_only", + Self::PasskeysReset => "passkeys_reset", + Self::Reauthenticated => "reauthenticated", + Self::ReauthFailed => "reauth_failed", + } + } +} + +impl Store { + /// Appends to the audit log. A failure is logged, never raised: the + /// action itself already happened. + pub fn audit( + &self, + event: AuditEvent, + user_id: Option, + username: Option<&str>, + ip: Option<&str>, + detail: &str, + ) { + let result = self.with(|c| { + c.execute( + "INSERT INTO audit_log (at, event, user_id, username, ip, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![now_ms(), event.name(), user_id, username, ip, detail], + ) + }); + if let Err(err) = result { + log::error!("audit log: {err:#}"); + } + let now = now_ms(); + let last = self.audit_pruned_at.load(Ordering::Relaxed); + if now - last >= PRUNE_EVERY_MS + && self.audit_pruned_at.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() + && let Err(err) = self.prune_audit_log() + { + log::error!("pruning the audit log: {err:#}"); + } + } + + pub fn prune_audit_log(&self) -> anyhow::Result<()> { + let now = now_ms(); + self.audit_pruned_at.store(now, Ordering::Relaxed); + self.with(|c| c.execute("DELETE FROM audit_log WHERE at < ?1", [now - RETAIN_MS]).map(drop)) + } + + #[cfg(test)] + pub fn audit_events(&self) -> Vec<(String, Option)> { + self.with(|c| { + c.prepare("SELECT event, username FROM audit_log ORDER BY id")? + .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect() + }) + .unwrap() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn writing_prunes_old_entries_once_a_day() { + let store = Store::in_memory(); + let old = |store: &Store| { + store.with(|c| c.execute("INSERT INTO audit_log (at, event) VALUES (1, 'sign_in')", [])).unwrap(); + }; + old(&store); + store.audit(AuditEvent::SignIn, None, None, None, ""); + assert_eq!(store.audit_events().len(), 1, "the old entry went"); + old(&store); + store.audit(AuditEvent::SignIn, None, None, None, ""); + assert_eq!(store.audit_events().len(), 3, "not again the same day"); + } +} diff --git a/crates/redshell-server/src/store/credentials.rs b/crates/redshell-server/src/store/credentials.rs new file mode 100644 index 0000000..6b007ff --- /dev/null +++ b/crates/redshell-server/src/store/credentials.rs @@ -0,0 +1,327 @@ +//! Browser sessions (cookies) and devices (bearer tokens), found by the +//! SHA-256 of their token. + +use redshell_protocol::{BrowserSession, Device, User}; +use rusqlite::{OptionalExtension as _, params}; + +use super::Store; +use crate::now_ms; + +/// One way a user is signed in. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Credential { + Browser(i64), + Device(i64), +} + +impl Credential { + fn table(self) -> &'static str { + match self { + Self::Browser(_) => "browser_sessions", + Self::Device(_) => "devices", + } + } + + fn id(self) -> i64 { + match self { + Self::Browser(id) | Self::Device(id) => id, + } + } + + /// The same kind of credential with row `id`. + fn with_id(self, id: i64) -> Self { + match self { + Self::Browser(_) => Self::Browser(id), + Self::Device(_) => Self::Device(id), + } + } +} + +/// What a sign-in was made with. A paired device counts as made with what +/// the browser that approved it was. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SignInMethod { + Password, + Passkey, +} + +impl SignInMethod { + fn as_str(self) -> &'static str { + match self { + Self::Password => "password", + Self::Passkey => "passkey", + } + } + + fn from_str(text: &str) -> Self { + if text == "passkey" { Self::Passkey } else { Self::Password } + } +} + +/// Who a token belongs to. +#[derive(Debug, Clone)] +pub struct TokenOwner { + pub credential: Credential, + pub user: User, + pub last_seen_at: i64, + /// When a browser session ends; `None` for a device. + pub expires_at: Option, + /// The device's name, or the browser's (`Safari on iPhone`). + pub name: String, + /// When it last proved who it is: signed in with a password or passkey, + /// or re-authenticated. `None` for a paired device until it does. + pub reauth_at: Option, + pub signed_in_with: SignInMethod, +} + +impl Store { + pub fn create_browser_session( + &self, + user_id: i64, + token_hash: &[u8], + expires_at: i64, + ip: &str, + user_agent: Option<&str>, + name: &str, + ) -> anyhow::Result { + self.with(|c| { + c.execute( + "INSERT INTO browser_sessions + (user_id, token_hash, created_at, last_seen_at, expires_at, last_ip, user_agent, name) + VALUES (?1, ?2, ?3, ?3, ?4, ?5, ?6, ?7)", + params![user_id, token_hash, now_ms(), expires_at, ip, user_agent, name], + )?; + Ok(Credential::Browser(c.last_insert_rowid())) + }) + } + + pub fn create_device(&self, user_id: i64, name: &str, token_hash: &[u8], ip: &str) -> anyhow::Result { + self.with(|c| { + c.execute( + "INSERT INTO devices (user_id, name, token_hash, created_at, last_seen_at, last_ip) + VALUES (?1, ?2, ?3, ?4, ?4, ?5)", + params![user_id, name, token_hash, now_ms(), ip], + )?; + Ok(Credential::Device(c.last_insert_rowid())) + }) + } + + /// The owner of a live browser session (`device = false`) or device token. + pub fn find_token(&self, device: bool, token_hash: &[u8]) -> anyhow::Result> { + let (table, expires, live) = + if device { ("devices", "NULL", "1") } else { ("browser_sessions", "t.expires_at", "t.expires_at > ?2") }; + let sql = format!( + "SELECT t.id, t.last_seen_at, u.id, u.username, u.created_at, t.name, {expires}, t.reauth_at, t.signed_in_with + FROM {table} t + JOIN users u ON u.id = t.user_id WHERE t.token_hash = ?1 AND {live}" + ); + self.with(|c| { + let mut stmt = c.prepare_cached(&sql)?; + let params = if device { params![token_hash] } else { params![token_hash, now_ms()] }; + stmt.query_row(params, |r| { + let id = r.get(0)?; + Ok(TokenOwner { + credential: if device { Credential::Device(id) } else { Credential::Browser(id) }, + last_seen_at: r.get(1)?, + user: User { id: r.get(2)?, username: r.get(3)?, created_at: r.get(4)? }, + name: r.get(5)?, + expires_at: r.get(6)?, + reauth_at: r.get(7)?, + signed_in_with: SignInMethod::from_str(&r.get::<_, String>(8)?), + }) + }) + .optional() + }) + } + + /// Records use of a credential; a browser session also gets `expires_at`. + pub fn touch(&self, credential: Credential, ip: &str, expires_at: Option) -> anyhow::Result<()> { + self.with(|c| { + let sql = format!( + "UPDATE {} SET last_seen_at = ?2, last_ip = ?3{} WHERE id = ?1", + credential.table(), + if expires_at.is_some() { ", expires_at = ?4" } else { "" } + ); + match expires_at { + Some(expires) => c.execute(&sql, params![credential.id(), now_ms(), ip, expires]), + None => c.execute(&sql, params![credential.id(), now_ms(), ip]), + } + .map(drop) + }) + } + + /// Records how a new sign-in was made, and when it proved who it is + /// (`None` for a paired device, which proved nothing itself). + pub fn issued(&self, credential: Credential, with: SignInMethod, reauth_at: Option) -> anyhow::Result<()> { + let sql = format!("UPDATE {} SET signed_in_with = ?2, reauth_at = ?3 WHERE id = ?1", credential.table()); + self.with(|c| c.execute(&sql, params![credential.id(), with.as_str(), reauth_at]).map(drop)) + } + + /// Ends the user's sign-ins made with the password, but `keep`; those + /// ended. + pub fn revoke_password_sign_ins(&self, user_id: i64, keep: Credential) -> anyhow::Result> { + self.with(|c| { + let mut revoked = Vec::new(); + for kind in [Credential::Browser(0), Credential::Device(0)] { + let table = kind.table(); + let kept = if keep.table() == table { keep.id() } else { -1 }; + let sql = format!( + "DELETE FROM {table} WHERE user_id = ?1 AND signed_in_with = 'password' AND id != ?2 RETURNING id" + ); + let ids = c + .prepare(&sql)? + .query_map(params![user_id, kept], |r| r.get(0))? + .collect::, _>>()?; + revoked.extend(ids.into_iter().map(|id| kind.with_id(id))); + } + Ok(revoked) + }) + } + + /// Records that `credential` just proved who it is. + pub fn stamp_reauth(&self, credential: Credential, at: i64) -> anyhow::Result<()> { + let sql = format!("UPDATE {} SET reauth_at = ?2 WHERE id = ?1", credential.table()); + self.with(|c| c.execute(&sql, params![credential.id(), at]).map(drop)) + } + + pub fn browser_sessions(&self, user_id: i64) -> anyhow::Result> { + self.with(|c| { + c.prepare( + "SELECT id, created_at, last_seen_at, expires_at, last_ip, user_agent, name FROM browser_sessions + WHERE user_id = ?1 AND expires_at > ?2 ORDER BY last_seen_at DESC", + )? + .query_map(params![user_id, now_ms()], |r| { + Ok(BrowserSession { + id: r.get(0)?, + name: r.get(6)?, + created_at: r.get(1)?, + last_seen_at: r.get(2)?, + expires_at: r.get(3)?, + last_ip: r.get(4)?, + user_agent: r.get(5)?, + current: false, + }) + })? + .collect() + }) + } + + pub fn devices(&self, user_id: i64) -> anyhow::Result> { + self.with(|c| { + c.prepare( + "SELECT id, name, created_at, last_seen_at, last_ip FROM devices + WHERE user_id = ?1 ORDER BY last_seen_at DESC", + )? + .query_map([user_id], |r| { + Ok(Device { + id: r.get(0)?, + name: r.get(1)?, + created_at: r.get(2)?, + last_seen_at: r.get(3)?, + last_ip: r.get(4)?, + current: false, + }) + })? + .collect() + }) + } + + /// Whether `credential`, with the token whose hash is `token_hash`, still + /// signs `user_id` in (not revoked, not expired). The hash makes sure it + /// is the same row, not a later one that got the same id. + pub fn credential_live(&self, user_id: i64, credential: Credential, token_hash: &[u8]) -> anyhow::Result { + let sql = + format!("SELECT COUNT(*) FROM {} WHERE id = ?1 AND user_id = ?2 AND token_hash = ?3", credential.table()); + let (sql, now) = match credential { + Credential::Browser(_) => (sql + " AND expires_at > ?4", Some(now_ms())), + Credential::Device(_) => (sql, None), + }; + self.with(|c| { + let count: i64 = match now { + Some(now) => c.query_row(&sql, params![credential.id(), user_id, token_hash, now], |r| r.get(0))?, + None => c.query_row(&sql, params![credential.id(), user_id, token_hash], |r| r.get(0))?, + }; + Ok(count == 1) + }) + } + + /// Signs `user_id` out of one credential; `false` when it is not theirs. + pub fn revoke(&self, user_id: i64, credential: Credential) -> anyhow::Result { + self.with(|c| { + let sql = format!("DELETE FROM {} WHERE id = ?1 AND user_id = ?2", credential.table()); + Ok(c.execute(&sql, params![credential.id(), user_id])? == 1) + }) + } + + /// Signs `user_id` out everywhere but `keep`. + pub fn revoke_all_except(&self, user_id: i64, keep: Option) -> anyhow::Result<()> { + self.with(|c| { + for table in ["browser_sessions", "devices"] { + let kept = keep.filter(|k| k.table() == table).map_or(-1, Credential::id); + c.execute(&format!("DELETE FROM {table} WHERE user_id = ?1 AND id != ?2"), params![user_id, kept])?; + } + Ok(()) + }) + } + + pub fn prune_expired_sessions(&self) -> anyhow::Result<()> { + self.with(|c| c.execute("DELETE FROM browser_sessions WHERE expires_at <= ?1", [now_ms()]).map(drop)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn turning_to_passkeys_ends_password_sign_ins() { + let store = Store::in_memory(); + let user = store.create_user("u", "h").unwrap().unwrap(); + let other = store.create_user("v", "h").unwrap().unwrap(); + let later = now_ms() + 60_000; + let current = store.create_browser_session(user.id, b"a", later, "ip", None, "Safari").unwrap(); + let password = store.create_browser_session(user.id, b"b", later, "ip", None, "Firefox").unwrap(); + let passkey = store.create_browser_session(user.id, b"c", later, "ip", None, "Chrome").unwrap(); + store.issued(passkey, SignInMethod::Passkey, Some(1)).unwrap(); + let desk = store.create_device(user.id, "desk", b"d", "ip").unwrap(); + let theirs = store.create_device(other.id, "theirs", b"e", "ip").unwrap(); + assert_eq!(store.find_token(false, b"c").unwrap().unwrap().signed_in_with, SignInMethod::Passkey); + + let mut revoked = store.revoke_password_sign_ins(user.id, current).unwrap(); + revoked.sort_by_key(|c| format!("{c:?}")); + assert_eq!(revoked, [password, desk]); + assert!(store.credential_live(user.id, current, b"a").unwrap(), "the one making the change stays"); + assert!(store.credential_live(user.id, passkey, b"c").unwrap()); + assert!(store.credential_live(other.id, theirs, b"e").unwrap()); + } + + #[test] + fn tokens_resolve_to_their_owner_until_revoked() { + let store = Store::in_memory(); + let user = store.create_user("u", "h").unwrap().unwrap(); + let browser = + store.create_browser_session(user.id, b"b", now_ms() + 60_000, "1.2.3.4", None, "Safari").unwrap(); + let device = store.create_device(user.id, "laptop", b"d", "::1").unwrap(); + store.create_browser_session(user.id, b"old", now_ms() - 1, "1.2.3.4", None, "Safari").unwrap(); + + assert_eq!(store.find_token(false, b"b").unwrap().unwrap().credential, browser); + assert_eq!(store.find_token(true, b"d").unwrap().unwrap().user.username, "u"); + assert_eq!(store.find_token(false, b"b").unwrap().unwrap().name, "Safari"); + assert!(store.find_token(true, b"b").unwrap().is_none(), "a cookie is not a device token"); + assert!(store.find_token(false, b"old").unwrap().is_none(), "expired"); + assert_eq!(store.browser_sessions(user.id).unwrap().len(), 1); + + store.touch(browser, "5.6.7.8", Some(now_ms() + 120_000)).unwrap(); + assert_eq!(store.browser_sessions(user.id).unwrap()[0].last_ip.as_deref(), Some("5.6.7.8")); + + assert!(store.credential_live(user.id, device, b"d").unwrap()); + assert!(!store.credential_live(user.id + 1, device, b"d").unwrap()); + assert!(!store.credential_live(user.id, device, b"other").unwrap(), "another token"); + assert!(!store.revoke(user.id + 1, device).unwrap(), "only the owner revokes"); + store.revoke_all_except(user.id, Some(device)).unwrap(); + assert!(store.find_token(false, b"b").unwrap().is_none()); + assert!(!store.credential_live(user.id, browser, b"b").unwrap()); + assert!(store.revoke(user.id, device).unwrap()); + assert!(store.devices(user.id).unwrap().is_empty()); + } +} diff --git a/crates/redshell-server/src/store/mod.rs b/crates/redshell-server/src/store/mod.rs new file mode 100644 index 0000000..67e51e0 --- /dev/null +++ b/crates/redshell-server/src/store/mod.rs @@ -0,0 +1,302 @@ +//! The server's SQLite database: accounts, credentials, passkeys, push +//! subscriptions, the audit log and session metadata. +//! +//! Secrets are never stored: passwords as Argon2id hashes, browser sessions +//! and device tokens as the SHA-256 of 256-bit random tokens. The schema is +//! versioned with `PRAGMA user_version`; each entry of [`MIGRATIONS`] runs +//! once. + +mod audit; +mod credentials; +mod passkeys; +mod push; +mod sessions; +mod users; + +use std::path::Path; +use std::sync::atomic::AtomicI64; + +use anyhow::Context as _; +use parking_lot::Mutex; +use rusqlite::Connection; + +pub use audit::AuditEvent; +pub use credentials::{Credential, SignInMethod}; +pub use passkeys::Removal; +pub use push::PushSubscription; +pub use sessions::SessionRow; + +/// Schema changes, oldest first. `user_version` counts those applied. +const MIGRATIONS: &[&str] = &[ + // 1: accounts, browser sessions, device tokens, the audit log, sessions. + "CREATE TABLE users ( + id INTEGER PRIMARY KEY, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + password_hash TEXT NOT NULL, + created_at INTEGER NOT NULL, + password_changed_at INTEGER NOT NULL + ); + CREATE TABLE browser_sessions ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash BLOB NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_ip TEXT, + user_agent TEXT + ); + CREATE TABLE devices ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + token_hash BLOB NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + last_ip TEXT + ); + CREATE TABLE audit_log ( + id INTEGER PRIMARY KEY, + at INTEGER NOT NULL, + event TEXT NOT NULL, + user_id INTEGER, + username TEXT, + ip TEXT, + detail TEXT + ); + CREATE INDEX audit_log_at ON audit_log(at); + CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + profile TEXT, + command TEXT NOT NULL, + cwd TEXT, + created_by INTEGER, + created_at INTEGER NOT NULL, + ended_at INTEGER, + exit_code INTEGER + );", + // 2: a readable name for each browser session, from its User-Agent. + "ALTER TABLE browser_sessions ADD COLUMN name TEXT NOT NULL DEFAULT 'Browser';", + // 3: passkeys, each user's WebAuthn id and passkey-only sign-in. + "ALTER TABLE users ADD COLUMN webauthn_id BLOB; + UPDATE users SET webauthn_id = randomblob(16); + CREATE UNIQUE INDEX users_webauthn_id ON users(webauthn_id); + ALTER TABLE users ADD COLUMN passkey_only INTEGER NOT NULL DEFAULT 0; + CREATE TABLE passkeys ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + credential_id BLOB NOT NULL UNIQUE, + name TEXT NOT NULL, + credential TEXT NOT NULL, + created_at INTEGER NOT NULL, + last_used_at INTEGER + ); + CREATE INDEX passkeys_user ON passkeys(user_id);", + // 4: push subscriptions, one per browser session, and the server's own keys (VAPID). + "CREATE TABLE push_subscriptions ( + id INTEGER PRIMARY KEY, + browser_session_id INTEGER NOT NULL UNIQUE REFERENCES browser_sessions(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + endpoint TEXT NOT NULL UNIQUE, + p256dh BLOB NOT NULL, + auth BLOB NOT NULL, + events TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE TABLE server_keys ( + name TEXT PRIMARY KEY, + value BLOB NOT NULL + );", + // 5: ids of accounts, browser sessions and devices are never used twice + // (AUTOINCREMENT), so nothing that kept an old id can take a new row for + // it. SQLite cannot add that to a table: each is rebuilt and copied. + "CREATE TABLE users_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + password_hash TEXT NOT NULL, + created_at INTEGER NOT NULL, + password_changed_at INTEGER NOT NULL, + webauthn_id BLOB, + passkey_only INTEGER NOT NULL DEFAULT 0 + ); + INSERT INTO users_new (id, username, password_hash, created_at, password_changed_at, webauthn_id, passkey_only) + SELECT id, username, password_hash, created_at, password_changed_at, webauthn_id, passkey_only FROM users; + DROP TABLE users; + ALTER TABLE users_new RENAME TO users; + CREATE UNIQUE INDEX users_webauthn_id ON users(webauthn_id); + CREATE TABLE browser_sessions_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash BLOB NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_ip TEXT, + user_agent TEXT, + name TEXT NOT NULL DEFAULT 'Browser' + ); + INSERT INTO browser_sessions_new + (id, user_id, token_hash, created_at, last_seen_at, expires_at, last_ip, user_agent, name) + SELECT id, user_id, token_hash, created_at, last_seen_at, expires_at, last_ip, user_agent, name + FROM browser_sessions; + DROP TABLE browser_sessions; + ALTER TABLE browser_sessions_new RENAME TO browser_sessions; + CREATE TABLE devices_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + token_hash BLOB NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + last_ip TEXT + ); + INSERT INTO devices_new (id, user_id, name, token_hash, created_at, last_seen_at, last_ip) + SELECT id, user_id, name, token_hash, created_at, last_seen_at, last_ip FROM devices; + DROP TABLE devices; + ALTER TABLE devices_new RENAME TO devices;", + // 6: when each sign-in last proved who it is (signing in, re-authenticating). + "ALTER TABLE browser_sessions ADD COLUMN reauth_at INTEGER; + ALTER TABLE devices ADD COLUMN reauth_at INTEGER;", + // 7: how each sign-in was made, `password` or `passkey` (a paired device: how the browser + // that approved it was), so that turning passkey-only on can end those made with the + // password. Earlier ones are taken to be password sign-ins. + "ALTER TABLE browser_sessions ADD COLUMN signed_in_with TEXT NOT NULL DEFAULT 'password'; + ALTER TABLE devices ADD COLUMN signed_in_with TEXT NOT NULL DEFAULT 'password';", +]; + +/// Thread-safe handle to the database. Queries are short, so callers on +/// async tasks run them inline. +pub struct Store { + conn: Mutex, + /// When the audit log was last pruned (Unix ms). + audit_pruned_at: AtomicI64, +} + +impl Store { + pub fn open(path: &Path) -> anyhow::Result { + let conn = Connection::open(path).with_context(|| format!("opening {}", path.display()))?; + Self::init(conn) + } + + #[cfg(test)] + pub fn in_memory() -> Self { + Self::init(Connection::open_in_memory().unwrap()).unwrap() + } + + fn init(mut conn: Connection) -> anyhow::Result { + // The `user` CLI may write while the server runs. + conn.busy_timeout(std::time::Duration::from_secs(5))?; + conn.execute_batch("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;")?; + migrate(&mut conn)?; + conn.pragma_update(None, "foreign_keys", true)?; + Ok(Self { conn: Mutex::new(conn), audit_pruned_at: AtomicI64::new(0) }) + } + + fn with(&self, f: impl FnOnce(&Connection) -> rusqlite::Result) -> anyhow::Result { + Ok(f(&self.conn.lock())?) + } +} + +/// Applies the migrations not applied yet, each in a transaction. Foreign +/// keys are off meanwhile (turn them on afterwards): rebuilding a table +/// drops the old one, which would otherwise delete every row referring to +/// it. Each migration must leave every reference intact, or it is undone. +fn migrate(conn: &mut Connection) -> anyhow::Result<()> { + conn.pragma_update(None, "foreign_keys", false)?; + let applied: usize = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?; + for (version, sql) in MIGRATIONS.iter().enumerate().skip(applied) { + let version = version + 1; + let tx = conn.transaction()?; + tx.execute_batch(sql).with_context(|| format!("migrating the server database to version {version}"))?; + if tx.prepare("PRAGMA foreign_key_check")?.exists([])? { + anyhow::bail!("migrating the server database to version {version} broke a reference"); + } + tx.pragma_update(None, "user_version", version)?; + tx.commit()?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::now_ms; + + #[test] + fn an_older_database_keeps_its_accounts() { + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch(MIGRATIONS[0]).unwrap(); + conn.pragma_update(None, "user_version", 1).unwrap(); + conn.execute_batch( + "INSERT INTO users (username, password_hash, created_at, password_changed_at) VALUES ('old', 'h', 1, 1); + INSERT INTO browser_sessions (user_id, token_hash, created_at, last_seen_at, expires_at) + VALUES (1, x'01', 1, 1, 9999999999999);", + ) + .unwrap(); + let store = Store::init(conn).unwrap(); + let old = store.find_user("old").unwrap().unwrap(); + assert!(!old.passkey_only); + assert_eq!(store.webauthn_id(old.user.id).unwrap().len(), 16, "given a WebAuthn id"); + assert_eq!(store.browser_sessions(old.user.id).unwrap()[0].name, "Browser"); + let new = store.create_user("new", "h").unwrap().unwrap(); + assert_ne!(store.webauthn_id(new.id).unwrap(), store.webauthn_id(old.user.id).unwrap()); + } + + #[test] + fn ids_are_never_reused_and_rebuilt_tables_keep_their_rows() { + let conn = Connection::open_in_memory().unwrap(); + conn.pragma_update(None, "foreign_keys", true).unwrap(); + for (version, sql) in MIGRATIONS[..4].iter().enumerate() { + conn.execute_batch(sql).unwrap(); + conn.pragma_update(None, "user_version", version + 1).unwrap(); + } + conn.execute_batch( + "INSERT INTO users (id, username, password_hash, created_at, password_changed_at, webauthn_id, passkey_only) + VALUES (1, 'a', 'h', 1, 1, x'01', 1), (2, 'b', 'h', 1, 1, x'02', 0); + INSERT INTO browser_sessions (id, user_id, token_hash, created_at, last_seen_at, expires_at, name) + VALUES (1, 1, x'a1', 1, 1, 9999999999999, 'Safari'), (2, 2, x'b1', 1, 1, 9999999999999, 'Firefox'); + INSERT INTO devices (id, user_id, name, token_hash, created_at, last_seen_at) + VALUES (5, 1, 'laptop', x'a2', 1, 1); + INSERT INTO passkeys (user_id, credential_id, name, credential, created_at) VALUES (1, x'c1', 'key', '{}', 1); + INSERT INTO push_subscriptions (browser_session_id, user_id, endpoint, p256dh, auth, events, created_at) + VALUES (1, 1, 'https://push.example/a', x'00', x'00', '[]', 1);", + ) + .unwrap(); + let store = Store::init(conn).unwrap(); + + let a = store.find_user("a").unwrap().unwrap(); + assert_eq!((a.user.id, a.passkey_only), (1, true)); + assert_eq!(store.webauthn_id(1).unwrap(), [1]); + assert_eq!(store.find_token(false, &[0xa1]).unwrap().unwrap().name, "Safari"); + assert_eq!(store.find_token(true, &[0xa2]).unwrap().unwrap().credential, Credential::Device(5)); + assert_eq!(store.passkeys(1).unwrap().len(), 1); + assert_eq!(store.push_subscriptions().unwrap().len(), 1, "still attached to its browser session"); + + // A removed row's id stays used: the next one is new. + assert!(store.revoke(2, Credential::Browser(2)).unwrap()); + let next = store.create_browser_session(2, b"b2", now_ms() + 60_000, "ip", None, "Firefox").unwrap(); + assert_eq!(next, Credential::Browser(3)); + assert!(store.remove_user("b").unwrap()); + assert_eq!(store.create_user("b", "h").unwrap().unwrap().id, 3, "id 2 is spent"); + assert_eq!(store.create_device(1, "pc", b"a3", "ip").unwrap(), Credential::Device(6)); + + // References still hold: removing an account takes everything of it along. + assert!(store.remove_user("a").unwrap()); + assert!(store.find_token(false, &[0xa1]).unwrap().is_none()); + assert!(store.find_token(true, &[0xa2]).unwrap().is_none()); + assert!(store.push_subscriptions().unwrap().is_empty()); + let passkeys: i64 = store.with(|c| c.query_row("SELECT COUNT(*) FROM passkeys", [], |r| r.get(0))).unwrap(); + assert_eq!(passkeys, 0); + } + + #[test] + fn migrations_run_once() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("db"); + Store::open(&path).unwrap(); + let store = Store::open(&path).unwrap(); + let version: usize = store.with(|c| c.query_row("PRAGMA user_version", [], |r| r.get(0))).unwrap(); + assert_eq!(version, MIGRATIONS.len()); + } +} diff --git a/crates/redshell-server/src/store/passkeys.rs b/crates/redshell-server/src/store/passkeys.rs new file mode 100644 index 0000000..a3d4220 --- /dev/null +++ b/crates/redshell-server/src/store/passkeys.rs @@ -0,0 +1,217 @@ +//! Passkeys and passkey-only sign-in. +//! +//! A passkey row keeps the credential as `webauthn-rs` serialises it (its +//! public key and counters; nothing secret), its credential id for lookup, +//! the user's name for it and when it was last used. Passkey-only mode can +//! only be on while the user has a passkey: the checks are part of the +//! statements that change either, so the `user` CLI running beside the +//! server cannot slip between them. + +use redshell_protocol::Passkey; +use rusqlite::{OptionalExtension as _, params}; + +use super::Store; +use crate::now_ms; + +/// A stored passkey found by its credential id, for signing in. +#[derive(Debug, Clone)] +pub struct StoredPasskey { + pub id: i64, + pub user: redshell_protocol::User, + /// The user's WebAuthn id, which the authenticator must report too. + pub webauthn_id: Vec, + /// The `webauthn_rs` passkey as JSON. + pub credential: String, +} + +/// What removing a passkey did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Removal { + Done, + NotFound, + /// It is the last passkey of a passkey-only user. + LastOfPasskeyOnly, +} + +impl Store { + /// The user's WebAuthn id: random, never shown, fixed for the account. + pub fn webauthn_id(&self, user_id: i64) -> anyhow::Result> { + self.with(|c| c.query_row("SELECT webauthn_id FROM users WHERE id = ?1", [user_id], |r| r.get(0))) + } + + /// The user's passkeys as `webauthn-rs` stored them (JSON). + pub fn passkey_credentials(&self, user_id: i64) -> anyhow::Result> { + self.with(|c| { + c.prepare("SELECT credential FROM passkeys WHERE user_id = ?1")? + .query_map([user_id], |r| r.get(0))? + .collect() + }) + } + + /// Credential ids of the user's passkeys. + pub fn passkey_credential_ids(&self, user_id: i64) -> anyhow::Result>> { + self.with(|c| { + c.prepare("SELECT credential_id FROM passkeys WHERE user_id = ?1")? + .query_map([user_id], |r| r.get(0))? + .collect() + }) + } + + /// Adds a passkey; `None` when that credential is registered already. + pub fn add_passkey( + &self, + user_id: i64, + credential_id: &[u8], + name: &str, + credential: &str, + ) -> anyhow::Result> { + self.with(|c| { + let now = now_ms(); + let added = c.execute( + "INSERT INTO passkeys (user_id, credential_id, name, credential, created_at) + VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(credential_id) DO NOTHING", + params![user_id, credential_id, name, credential, now], + )?; + Ok((added == 1).then(|| Passkey { + id: c.last_insert_rowid(), + name: name.to_owned(), + created_at: now, + last_used_at: None, + })) + }) + } + + pub fn find_passkey(&self, credential_id: &[u8]) -> anyhow::Result> { + self.with(|c| { + c.query_row( + "SELECT p.id, p.credential, u.webauthn_id, u.id, u.username, u.created_at FROM passkeys p + JOIN users u ON u.id = p.user_id WHERE p.credential_id = ?1", + [credential_id], + |r| { + Ok(StoredPasskey { + id: r.get(0)?, + credential: r.get(1)?, + webauthn_id: r.get(2)?, + user: redshell_protocol::User { id: r.get(3)?, username: r.get(4)?, created_at: r.get(5)? }, + }) + }, + ) + .optional() + }) + } + + /// Records a sign-in with passkey `id`, and its updated credential. + pub fn passkey_used(&self, id: i64, credential: Option<&str>) -> anyhow::Result<()> { + self.with(|c| { + c.execute( + "UPDATE passkeys SET last_used_at = ?2, credential = coalesce(?3, credential) WHERE id = ?1", + params![id, now_ms(), credential], + ) + .map(drop) + }) + } + + pub fn passkeys(&self, user_id: i64) -> anyhow::Result> { + self.with(|c| { + c.prepare("SELECT id, name, created_at, last_used_at FROM passkeys WHERE user_id = ?1 ORDER BY created_at")? + .query_map([user_id], |r| { + Ok(Passkey { id: r.get(0)?, name: r.get(1)?, created_at: r.get(2)?, last_used_at: r.get(3)? }) + })? + .collect() + }) + } + + /// Renames one of the user's passkeys; the renamed passkey, if found. + pub fn rename_passkey(&self, user_id: i64, id: i64, name: &str) -> anyhow::Result> { + self.with(|c| { + c.query_row( + "UPDATE passkeys SET name = ?3 WHERE id = ?1 AND user_id = ?2 + RETURNING id, name, created_at, last_used_at", + params![id, user_id, name], + |r| Ok(Passkey { id: r.get(0)?, name: r.get(1)?, created_at: r.get(2)?, last_used_at: r.get(3)? }), + ) + .optional() + }) + } + + /// Removes one of the user's passkeys, unless it is the last one and + /// the user signs in with passkeys only. + pub fn remove_passkey(&self, user_id: i64, id: i64) -> anyhow::Result { + self.with(|c| { + let removed = c.execute( + "DELETE FROM passkeys WHERE id = ?1 AND user_id = ?2 AND NOT ( + (SELECT passkey_only FROM users WHERE id = ?2) + AND (SELECT COUNT(*) FROM passkeys WHERE user_id = ?2) <= 1)", + params![id, user_id], + )?; + if removed == 1 { + return Ok(Removal::Done); + } + let exists: bool = c.query_row( + "SELECT EXISTS (SELECT 1 FROM passkeys WHERE id = ?1 AND user_id = ?2)", + params![id, user_id], + |r| r.get(0), + )?; + Ok(if exists { Removal::LastOfPasskeyOnly } else { Removal::NotFound }) + }) + } + + /// Turns passkey-only sign-in on or off; `false` when turning it on is + /// refused because the user has no passkey. + pub fn set_passkey_only(&self, user_id: i64, on: bool) -> anyhow::Result { + self.with(|c| { + let changed = c.execute( + "UPDATE users SET passkey_only = ?2 + WHERE id = ?1 AND (?2 = 0 OR EXISTS (SELECT 1 FROM passkeys WHERE user_id = ?1))", + params![user_id, on], + )?; + Ok(changed == 1) + }) + } + + /// Removes every passkey of the user and turns passkey-only off; how + /// many there were. + pub fn reset_passkeys(&self, user_id: i64) -> anyhow::Result { + self.with(|c| { + let tx = c.unchecked_transaction()?; + tx.execute("UPDATE users SET passkey_only = 0 WHERE id = ?1", [user_id])?; + let removed = tx.execute("DELETE FROM passkeys WHERE user_id = ?1", [user_id])?; + tx.commit()?; + Ok(removed) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn passkey_only_needs_a_passkey_and_keeps_the_last_one() { + let store = Store::in_memory(); + let user = store.create_user("u", "h").unwrap().unwrap(); + assert_eq!(store.webauthn_id(user.id).unwrap().len(), 16); + assert!(!store.set_passkey_only(user.id, true).unwrap(), "no passkey yet"); + + let first = store.add_passkey(user.id, b"cred-1", "iPhone", "{}").unwrap().unwrap(); + assert!(store.add_passkey(user.id, b"cred-1", "again", "{}").unwrap().is_none()); + let second = store.add_passkey(user.id, b"cred-2", "YubiKey", "{}").unwrap().unwrap(); + assert!(store.set_passkey_only(user.id, true).unwrap()); + assert!(store.find_user("u").unwrap().unwrap().passkey_only); + + assert_eq!(store.remove_passkey(user.id, first.id).unwrap(), Removal::Done); + assert_eq!(store.remove_passkey(user.id, second.id).unwrap(), Removal::LastOfPasskeyOnly); + assert_eq!(store.remove_passkey(user.id + 1, second.id).unwrap(), Removal::NotFound, "not theirs"); + assert_eq!(store.rename_passkey(user.id, second.id, "Key").unwrap().unwrap().name, "Key"); + + let found = store.find_passkey(b"cred-2").unwrap().unwrap(); + assert_eq!((found.user.id, found.webauthn_id.len()), (user.id, 16)); + store.passkey_used(found.id, Some("{\"n\":1}")).unwrap(); + assert!(store.passkeys(user.id).unwrap()[0].last_used_at.is_some()); + assert_eq!(store.find_passkey(b"cred-2").unwrap().unwrap().credential, "{\"n\":1}"); + + assert_eq!(store.reset_passkeys(user.id).unwrap(), 1); + assert!(!store.find_user("u").unwrap().unwrap().passkey_only); + assert_eq!(store.passkey_credential_ids(user.id).unwrap().len(), 0); + } +} diff --git a/crates/redshell-server/src/store/push.rs b/crates/redshell-server/src/store/push.rs new file mode 100644 index 0000000..e9060b2 --- /dev/null +++ b/crates/redshell-server/src/store/push.rs @@ -0,0 +1,202 @@ +//! Push subscriptions, one per browser session and gone with it, each with +//! the events it wants; and the server's own keys (VAPID). + +use redshell_protocol::{PushEvent, PushSubscriptionInfo}; +use rusqlite::{OptionalExtension as _, params}; + +use super::Store; +use crate::now_ms; + +/// Where a browser receives pushes: the push service's endpoint and the +/// browser's keys for encrypting to it (RFC 8291). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PushSubscription { + pub id: i64, + pub user_id: i64, + pub endpoint: String, + /// The browser's P-256 public key, uncompressed. + pub p256dh: Vec, + /// The 16-byte authentication secret. + pub auth: Vec, + pub events: Vec, +} + +impl Store { + /// Sets the subscription of browser session `browser_id`, replacing its + /// earlier one and the user's other holder of the endpoint. `false` when + /// another user holds that endpoint. + pub fn set_push_subscription( + &self, + user_id: i64, + browser_id: i64, + endpoint: &str, + (p256dh, auth): (&[u8], &[u8]), + events: &[PushEvent], + ) -> anyhow::Result { + let events = serde_json::to_string(events)?; + self.with(|c| { + let tx = c.unchecked_transaction()?; + tx.execute( + "DELETE FROM push_subscriptions WHERE browser_session_id = ?1 OR (endpoint = ?2 AND user_id = ?3)", + params![browser_id, endpoint, user_id], + )?; + let added = tx.execute( + "INSERT INTO push_subscriptions (browser_session_id, user_id, endpoint, p256dh, auth, events, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(endpoint) DO NOTHING", + params![browser_id, user_id, endpoint, p256dh, auth, events, now_ms()], + )?; + tx.commit()?; + Ok(added == 1) + }) + } + + /// Changes what the user's subscription at `endpoint` is sent; `false` + /// when the user has none there. + pub fn set_push_events(&self, user_id: i64, endpoint: &str, events: &[PushEvent]) -> anyhow::Result { + let events = serde_json::to_string(events)?; + self.with(|c| { + let sql = "UPDATE push_subscriptions SET events = ?3 WHERE user_id = ?1 AND endpoint = ?2"; + Ok(c.execute(sql, params![user_id, endpoint, events])? == 1) + }) + } + + /// Removes the user's subscription at `endpoint`; `false` when there is + /// none. + pub fn remove_push_subscription(&self, user_id: i64, endpoint: &str) -> anyhow::Result { + self.with(|c| { + let sql = "DELETE FROM push_subscriptions WHERE user_id = ?1 AND endpoint = ?2"; + Ok(c.execute(sql, params![user_id, endpoint])? == 1) + }) + } + + /// Forgets a subscription its push service no longer knows. + pub fn drop_push_subscription(&self, id: i64) -> anyhow::Result<()> { + self.with(|c| c.execute("DELETE FROM push_subscriptions WHERE id = ?1", [id]).map(drop)) + } + + /// The user's subscriptions; `browser_id` marks the current one. + pub fn user_push_subscriptions( + &self, + user_id: i64, + browser_id: Option, + ) -> anyhow::Result> { + self.with(|c| { + c.prepare( + "SELECT endpoint, events, created_at, browser_session_id FROM push_subscriptions + WHERE user_id = ?1 ORDER BY created_at", + )? + .query_map([user_id], |r| { + Ok(PushSubscriptionInfo { + endpoint: r.get(0)?, + events: events(r.get(1)?), + created_at: r.get(2)?, + current: browser_id == Some(r.get(3)?), + }) + })? + .collect() + }) + } + + /// The user's subscription at `endpoint`. + pub fn push_subscription(&self, user_id: i64, endpoint: &str) -> anyhow::Result> { + self.with(|c| { + c.query_row(&format!("{SELECT} WHERE p.user_id = ?1 AND p.endpoint = ?2"), params![user_id, endpoint], row) + .optional() + }) + } + + /// Every subscription of a live browser session. + pub fn push_subscriptions(&self) -> anyhow::Result> { + self.with(|c| { + let sql = + format!("{SELECT} JOIN browser_sessions b ON b.id = p.browser_session_id WHERE b.expires_at > ?1"); + c.prepare(&sql)?.query_map([now_ms()], row)?.collect() + }) + } + + /// A key the server made for itself, such as the VAPID key. + pub fn server_key(&self, name: &str) -> anyhow::Result>> { + self.with(|c| c.query_row("SELECT value FROM server_keys WHERE name = ?1", [name], |r| r.get(0)).optional()) + } + + pub fn set_server_key(&self, name: &str, value: &[u8]) -> anyhow::Result<()> { + self.with(|c| { + c.execute("INSERT OR REPLACE INTO server_keys (name, value) VALUES (?1, ?2)", params![name, value]) + .map(drop) + }) + } +} + +const SELECT: &str = "SELECT p.id, p.user_id, p.endpoint, p.p256dh, p.auth, p.events FROM push_subscriptions p"; + +fn row(r: &rusqlite::Row) -> rusqlite::Result { + Ok(PushSubscription { + id: r.get(0)?, + user_id: r.get(1)?, + endpoint: r.get(2)?, + p256dh: r.get(3)?, + auth: r.get(4)?, + events: events(r.get(5)?), + }) +} + +/// Stored events; unknown ones (from a newer version) are skipped. +fn events(json: String) -> Vec { + let values: Vec = serde_json::from_str(&json).unwrap_or_default(); + values.into_iter().filter_map(|v| serde_json::from_value(v).ok()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::Credential; + + #[test] + fn subscriptions_follow_their_browser_session() { + let store = Store::in_memory(); + let user = store.create_user("u", "h").unwrap().unwrap(); + let browser = |token: &[u8]| { + let Credential::Browser(id) = + store.create_browser_session(user.id, token, now_ms() + 60_000, "ip", None, "Browser").unwrap() + else { + unreachable!() + }; + id + }; + let (first, second) = (browser(b"a"), browser(b"b")); + let keys = (&b"key"[..], &b"auth"[..]); + store.set_push_subscription(user.id, first, "https://push.example/a", keys, &PushEvent::ALL).unwrap(); + store.set_push_subscription(user.id, first, "https://push.example/b", keys, &PushEvent::ALL).unwrap(); + store.set_push_subscription(user.id, second, "https://push.example/c", keys, &[PushEvent::Finished]).unwrap(); + let all = store.push_subscriptions().unwrap(); + assert_eq!(all.len(), 2, "one per browser session"); + let mine = store.user_push_subscriptions(user.id, Some(first)).unwrap(); + assert_eq!((mine[0].endpoint.as_str(), mine[0].current), ("https://push.example/b", true)); + + let other = store.create_user("v", "h").unwrap().unwrap(); + let Credential::Browser(theirs) = + store.create_browser_session(other.id, b"c", now_ms() + 60_000, "ip", None, "Browser").unwrap() + else { + unreachable!() + }; + let taken = store.set_push_subscription(other.id, theirs, "https://push.example/b", keys, &[]).unwrap(); + assert!(!taken, "another user's endpoint stays theirs"); + assert!(store.set_push_events(user.id, "https://push.example/b", &[PushEvent::Failed]).unwrap()); + assert!(!store.set_push_events(user.id + 1, "https://push.example/b", &[]).unwrap(), "not theirs"); + let found = store.push_subscription(user.id, "https://push.example/b").unwrap().unwrap(); + assert_eq!(found.events, [PushEvent::Failed]); + + store.revoke(user.id, Credential::Browser(first)).unwrap(); + assert_eq!(store.push_subscriptions().unwrap().len(), 1, "signing out drops it"); + assert!(store.remove_push_subscription(user.id, "https://push.example/c").unwrap()); + assert!(store.push_subscriptions().unwrap().is_empty()); + } + + #[test] + fn server_keys_persist() { + let store = Store::in_memory(); + assert_eq!(store.server_key("vapid").unwrap(), None); + store.set_server_key("vapid", b"k").unwrap(); + assert_eq!(store.server_key("vapid").unwrap().as_deref(), Some(&b"k"[..])); + } +} diff --git a/crates/redshell-server/src/store/sessions.rs b/crates/redshell-server/src/store/sessions.rs new file mode 100644 index 0000000..f3177c2 --- /dev/null +++ b/crates/redshell-server/src/store/sessions.rs @@ -0,0 +1,45 @@ +//! Which sessions ran, from what, and how they ended. + +use rusqlite::params; + +use super::Store; +use crate::now_ms; + +/// A session as recorded when it starts. +pub struct SessionRow<'a> { + pub id: &'a str, + pub kind: &'a str, + pub profile: Option<&'a str>, + pub command: &'a str, + pub cwd: Option<&'a str>, + pub created_by: i64, + pub created_at: i64, +} + +impl Store { + pub fn record_session(&self, row: &SessionRow) -> anyhow::Result<()> { + self.with(|c| { + c.execute( + "INSERT INTO sessions (id, kind, profile, command, cwd, created_by, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![row.id, row.kind, row.profile, row.command, row.cwd, row.created_by, row.created_at], + ) + .map(drop) + }) + } + + pub fn record_session_end(&self, id: &str, exit_code: Option) -> anyhow::Result<()> { + self.with(|c| { + c.execute( + "UPDATE sessions SET ended_at = ?2, exit_code = ?3 WHERE id = ?1 AND ended_at IS NULL", + params![id, now_ms(), exit_code], + ) + .map(drop) + }) + } + + /// Sessions of an earlier run died with it. + pub fn end_orphaned_sessions(&self) -> anyhow::Result<()> { + self.with(|c| c.execute("UPDATE sessions SET ended_at = ?1 WHERE ended_at IS NULL", [now_ms()]).map(drop)) + } +} diff --git a/crates/redshell-server/src/store/users.rs b/crates/redshell-server/src/store/users.rs new file mode 100644 index 0000000..e63f9f6 --- /dev/null +++ b/crates/redshell-server/src/store/users.rs @@ -0,0 +1,101 @@ +//! Accounts. + +use redshell_protocol::User; +use rusqlite::{OptionalExtension as _, Row, params}; + +use super::Store; +use crate::now_ms; + +/// A user with the password hash, which never leaves the server. +#[derive(Debug, Clone)] +pub struct UserRecord { + pub user: User, + pub password_hash: String, + /// Password sign-in is off: passkeys only. + pub passkey_only: bool, +} + +fn record(row: &Row) -> rusqlite::Result { + Ok(UserRecord { + user: user(row)?, + password_hash: row.get("password_hash")?, + passkey_only: row.get("passkey_only")?, + }) +} + +const SELECT_RECORD: &str = "SELECT id, username, created_at, password_hash, passkey_only FROM users"; + +fn user(row: &Row) -> rusqlite::Result { + Ok(User { id: row.get("id")?, username: row.get("username")?, created_at: row.get("created_at")? }) +} + +impl Store { + pub fn user_count(&self) -> anyhow::Result { + self.with(|c| c.query_row("SELECT COUNT(*) FROM users", [], |r| r.get(0))) + } + + /// Creates a user; `None` when the name is taken (names ignore case). + pub fn create_user(&self, username: &str, password_hash: &str) -> anyhow::Result> { + self.with(|c| { + let now = now_ms(); + let inserted = c.execute( + "INSERT INTO users (username, password_hash, created_at, password_changed_at, webauthn_id) + VALUES (?1, ?2, ?3, ?3, randomblob(16)) ON CONFLICT(username) DO NOTHING", + params![username, password_hash, now], + )?; + Ok((inserted == 1).then(|| User { + id: c.last_insert_rowid(), + username: username.to_owned(), + created_at: now, + })) + }) + } + + pub fn find_user(&self, username: &str) -> anyhow::Result> { + self.with(|c| c.query_row(&format!("{SELECT_RECORD} WHERE username = ?1"), [username], record).optional()) + } + + pub fn user_by_id(&self, id: i64) -> anyhow::Result> { + self.with(|c| c.query_row(&format!("{SELECT_RECORD} WHERE id = ?1"), [id], record).optional()) + } + + pub fn users(&self) -> anyhow::Result> { + self.with(|c| { + c.prepare("SELECT id, username, created_at FROM users ORDER BY username")?.query_map([], user)?.collect() + }) + } + + pub fn set_password(&self, user_id: i64, password_hash: &str) -> anyhow::Result<()> { + self.with(|c| { + c.execute( + "UPDATE users SET password_hash = ?2, password_changed_at = ?3 WHERE id = ?1", + params![user_id, password_hash, now_ms()], + ) + .map(drop) + }) + } + + /// Removes a user with its browser sessions and devices. + pub fn remove_user(&self, username: &str) -> anyhow::Result { + self.with(|c| Ok(c.execute("DELETE FROM users WHERE username = ?1", [username])? == 1)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_unique_ignoring_case() { + let store = Store::in_memory(); + let alice = store.create_user("Alice", "h1").unwrap().unwrap(); + assert!(store.create_user("alice", "h2").unwrap().is_none()); + let found = store.find_user("ALICE").unwrap().unwrap(); + assert_eq!((found.user.id, found.password_hash.as_str()), (alice.id, "h1")); + store.set_password(alice.id, "h3").unwrap(); + assert_eq!(store.user_by_id(alice.id).unwrap().unwrap().password_hash, "h3"); + assert_eq!(store.user_count().unwrap(), 1); + assert!(store.remove_user("alice").unwrap()); + assert!(store.users().unwrap().is_empty()); + } +} diff --git a/crates/redshell-server/src/web/account.rs b/crates/redshell-server/src/web/account.rs new file mode 100644 index 0000000..fef5368 --- /dev/null +++ b/crates/redshell-server/src/web/account.rs @@ -0,0 +1,68 @@ +//! `/api/account/*`: the password and where the user is signed in. + +use axum::extract::{Path, State}; +use axum::{Extension, Json}; +use redshell_protocol::{BrowserSession, ChangePasswordRequest, Device}; +use serde_json::{Value, json}; + +use super::Shared; +use super::error::{ApiResult, Failure}; +use crate::auth::{Client, Principal}; +use crate::store::Credential; + +pub async fn change_password( + State(app): State, + Extension(principal): Extension, + client: Client, + Json(req): Json, +) -> ApiResult { + app.auth.change_password(&principal, req, &client).await?; + Ok(Json(json!({}))) +} + +pub async fn devices(State(app): State, Extension(principal): Extension) -> ApiResult> { + let mut devices = app.store.devices(principal.user.id)?; + for device in &mut devices { + device.current = principal.credential == Credential::Device(device.id); + } + Ok(Json(devices)) +} + +pub async fn browser_sessions( + State(app): State, + Extension(principal): Extension, +) -> ApiResult> { + let mut sessions = app.store.browser_sessions(principal.user.id)?; + for session in &mut sessions { + session.current = principal.credential == Credential::Browser(session.id); + } + Ok(Json(sessions)) +} + +pub async fn revoke_device( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(id): Path, +) -> ApiResult { + revoke(&app, &principal, &client, Credential::Device(id), "device") +} + +pub async fn revoke_browser_session( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(id): Path, +) -> ApiResult { + revoke(&app, &principal, &client, Credential::Browser(id), "browser session") +} + +fn revoke( + app: &Shared, + principal: &Principal, + client: &Client, + credential: Credential, + what: &str, +) -> ApiResult { + if app.auth.revoke(principal, credential, client)? { Ok(Json(json!({}))) } else { Err(Failure::not_found(what)) } +} diff --git a/crates/redshell-server/src/web/assets.rs b/crates/redshell-server/src/web/assets.rs new file mode 100644 index 0000000..01c9f29 --- /dev/null +++ b/crates/redshell-server/src/web/assets.rs @@ -0,0 +1,91 @@ +//! The PWA, embedded in the binary at build time (see `build.rs`), and the +//! security headers every response carries. + +use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Uri, header}; +use axum::response::{IntoResponse, Response}; +use rust_embed::Embed; +use tower_http::set_header::SetResponseHeaderLayer; + +#[derive(Embed)] +#[folder = "$REDSHELL_WEB_DIST"] +struct Pwa; + +/// Scripts, styles and connections only from this origin; no inline script, +/// no plugins, no framing. Inline styles are allowed: terminal renderers +/// (xterm.js) size their elements with them. +pub const CSP: &str = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; \ + img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self'; \ + manifest-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"; + +/// Header layers for every response; HSTS too when clients reach the +/// server over https, itself or through a proxy. HSTS leaves out +/// `includeSubDomains`: the server's name is often one of many under a +/// domain it does not own (a tailnet, a company domain) whose other hosts +/// may still serve plain http. +pub fn security_headers(https: bool) -> Vec> { + let mut headers = vec![ + (header::CONTENT_SECURITY_POLICY, CSP), + (header::X_FRAME_OPTIONS, "DENY"), + (header::REFERRER_POLICY, "no-referrer"), + (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), + ]; + if https { + headers.push((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000")); + } + headers + .into_iter() + .map(|(name, value): (HeaderName, &'static str)| { + SetResponseHeaderLayer::if_not_present(name, HeaderValue::from_static(value)) + }) + .collect() +} + +/// Serves a file of the PWA. Any other path gets `index.html`, so the +/// app's own routes (`/s/`, `/hosts/box.lan`) load it: a path without +/// a file extension, or one a browser navigates to (it accepts HTML). A +/// missing script or image stays a 404. +pub async fn serve(method: Method, uri: Uri, headers: HeaderMap) -> Response { + if method != Method::GET && method != Method::HEAD { + return StatusCode::METHOD_NOT_ALLOWED.into_response(); + } + let path = uri.path().trim_start_matches('/'); + let path = if path.is_empty() { "index.html" } else { path }; + let file_like = path.rsplit('/').next().is_some_and(|name| name.contains('.')); + let navigation = + headers.get(header::ACCEPT).and_then(|a| a.to_str().ok()).is_some_and(|accept| accept.contains("text/html")); + match Pwa::get(path) { + Some(file) => respond(path, file, &headers), + None if file_like && !navigation => StatusCode::NOT_FOUND.into_response(), + None => match Pwa::get("index.html") { + Some(index) => respond("index.html", index, &headers), + None => StatusCode::NOT_FOUND.into_response(), + }, + } +} + +fn respond(path: &str, file: rust_embed::EmbeddedFile, request: &HeaderMap) -> Response { + let etag = format!("\"{}\"", hex(&file.metadata.sha256_hash()[..16])); + let cache = if path.starts_with("assets/") { + // Vite puts content hashes in these names. + "public, max-age=31536000, immutable" + } else { + // index.html, the service worker, the manifest: always revalidated. + "no-cache" + }; + let mut headers = HeaderMap::new(); + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); + if let Ok(etag) = HeaderValue::from_str(&etag) { + headers.insert(header::ETAG, etag); + } + if request.get(header::IF_NONE_MATCH).is_some_and(|v| v.as_bytes() == etag.as_bytes()) { + return (StatusCode::NOT_MODIFIED, headers).into_response(); + } + if let Ok(mime) = HeaderValue::from_str(file.metadata.mimetype()) { + headers.insert(header::CONTENT_TYPE, mime); + } + (headers, file.data.into_owned()).into_response() +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} diff --git a/crates/redshell-server/src/web/auth.rs b/crates/redshell-server/src/web/auth.rs new file mode 100644 index 0000000..6a95135 --- /dev/null +++ b/crates/redshell-server/src/web/auth.rs @@ -0,0 +1,90 @@ +//! `/api/auth/*` and `/api/setup`: open to everyone (sign-out and `me` +//! need a sign-in). + +use axum::extract::State; +use axum::http::header; +use axum::response::{IntoResponse, Response}; +use axum::{Extension, Json}; +use redshell_protocol::{ + PROTOCOL_VERSION, PasskeyChallenge, ReauthRequest, ReauthResponse, ServerInfo, SetupRequest, SignInRequest, + SignInResponse, User, +}; + +use super::Shared; +use super::error::{ApiResult, Failure}; +use super::guard::{clear_cookie, set_cookie}; +use crate::auth::{Client, Issued, Principal, SignedIn, password}; + +pub async fn info(State(app): State) -> ApiResult { + let setup_required = app.auth.announce_setup()?.is_some(); + Ok(Json(ServerInfo { + version: env!("CARGO_PKG_VERSION").into(), + protocol_version: PROTOCOL_VERSION, + setup_required, + min_password_length: password::MIN_LENGTH as u32, + passkeys: app.auth.passkeys_available(), + })) +} + +pub async fn setup( + State(app): State, + client: Client, + Json(req): Json, +) -> Result { + Ok(signed_in(app.auth.setup(req, &client).await?)) +} + +pub async fn sign_in( + State(app): State, + client: Client, + Json(req): Json, +) -> Result { + Ok(signed_in(app.auth.sign_in(req, &client).await?)) +} + +/// The response for a new sign-in: a cookie for a browser, the token in +/// the body for a device. +pub fn signed_in(done: SignedIn) -> Response { + match done.issued { + Issued::Cookie(token) => { + ([(header::SET_COOKIE, set_cookie(&token))], Json(SignInResponse { user: done.user, device_token: None })) + .into_response() + } + Issued::DeviceToken(token) => { + Json(SignInResponse { user: done.user, device_token: Some(token) }).into_response() + } + } +} + +pub async fn sign_out( + State(app): State, + Extension(principal): Extension, + client: Client, +) -> Result { + app.auth.sign_out(&principal, &client)?; + Ok(([(header::SET_COOKIE, clear_cookie())], Json(serde_json::json!({}))).into_response()) +} + +/// `POST /api/auth/reauth`: the password or a passkey again, for changes +/// that need a recent re-authentication. +pub async fn reauth( + State(app): State, + Extension(principal): Extension, + client: Client, + Json(req): Json, +) -> ApiResult { + Ok(Json(app.auth.reauth(&principal, req, &client).await?)) +} + +/// `POST /api/auth/reauth/passkey/begin`: a challenge for one of the +/// user's passkeys. +pub async fn reauth_options( + State(app): State, + Extension(principal): Extension, +) -> ApiResult { + Ok(Json(app.auth.start_passkey_reauth(&principal)?)) +} + +pub async fn me(Extension(principal): Extension) -> Json { + Json(principal.user) +} diff --git a/crates/redshell-server/src/web/error.rs b/crates/redshell-server/src/web/error.rs new file mode 100644 index 0000000..e08a461 --- /dev/null +++ b/crates/redshell-server/src/web/error.rs @@ -0,0 +1,115 @@ +//! Error responses: an [`ApiError`] body with a matching status. + +use axum::Json; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use redshell_core::settings::ssh; +use redshell_protocol::{ApiError, ErrorCode}; + +use crate::auth::AuthError; +use crate::config::EditError; +use crate::hosts::HostError; +use crate::sessions::CreateError; + +#[derive(Debug)] +pub struct Failure(pub ApiError); + +pub type ApiResult = Result, Failure>; + +impl Failure { + pub fn new(code: ErrorCode, message: impl Into) -> Self { + Self(ApiError { code, message: message.into(), retry_after_secs: None }) + } + + pub fn bad_request(message: impl Into) -> Self { + Self::new(ErrorCode::BadRequest, message) + } + + pub fn not_found(what: &str) -> Self { + Self::new(ErrorCode::NotFound, format!("no such {what}")) + } + + pub fn unauthorized() -> Self { + Self::new(ErrorCode::Unauthorized, "sign in first") + } + + pub fn forbidden(message: impl Into) -> Self { + Self::new(ErrorCode::Forbidden, message) + } + + pub fn status(code: ErrorCode) -> StatusCode { + match code { + ErrorCode::BadRequest => StatusCode::BAD_REQUEST, + ErrorCode::InvalidCredentials | ErrorCode::Unauthorized => StatusCode::UNAUTHORIZED, + ErrorCode::Forbidden | ErrorCode::PasskeyRequired | ErrorCode::ReauthRequired => StatusCode::FORBIDDEN, + ErrorCode::Unavailable => StatusCode::SERVICE_UNAVAILABLE, + ErrorCode::NotFound => StatusCode::NOT_FOUND, + ErrorCode::Conflict => StatusCode::CONFLICT, + ErrorCode::RateLimited => StatusCode::TOO_MANY_REQUESTS, + ErrorCode::Internal => StatusCode::INTERNAL_SERVER_ERROR, + } + } +} + +impl IntoResponse for Failure { + fn into_response(self) -> Response { + let retry = self.0.retry_after_secs; + let mut response = (Self::status(self.0.code), Json(self.0)).into_response(); + if let Some(secs) = retry { + response.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from(secs)); + } + response + } +} + +impl From for Failure { + fn from(err: anyhow::Error) -> Self { + log::error!("{err:#}"); + Self::new(ErrorCode::Internal, "something went wrong on the server; its log says what") + } +} + +impl From for Failure { + fn from(err: AuthError) -> Self { + let message = err.to_string(); + match err { + AuthError::InvalidCredentials => Self::new(ErrorCode::InvalidCredentials, message), + AuthError::RateLimited(wait) => Self(ApiError { + code: ErrorCode::RateLimited, + message, + retry_after_secs: Some(wait.as_secs_f64().ceil() as u64), + }), + AuthError::BadRequest(_) => Self::new(ErrorCode::BadRequest, message), + AuthError::Forbidden(_) => Self::new(ErrorCode::Forbidden, message), + AuthError::Conflict(_) => Self::new(ErrorCode::Conflict, message), + AuthError::NotFound(_) => Self::new(ErrorCode::NotFound, message), + AuthError::PasskeyRequired => Self::new(ErrorCode::PasskeyRequired, message), + AuthError::ReauthRequired => Self::new(ErrorCode::ReauthRequired, message), + AuthError::PasskeyRejected(_) => Self::new(ErrorCode::InvalidCredentials, message), + AuthError::Unavailable(_) => Self::new(ErrorCode::Unavailable, message), + AuthError::Internal(err) => err.into(), + } + } +} + +impl From> for Failure { + fn from(err: EditError) -> Self { + match err { + EditError::Refused(err @ HostError::Invalid(ssh::HostError::NameTaken)) => { + Self::new(ErrorCode::Conflict, err.to_string()) + } + EditError::Refused(err @ HostError::NotFound(_)) => Self::new(ErrorCode::NotFound, err.to_string()), + EditError::Refused(err) => Self::bad_request(err.to_string()), + EditError::Failed(err) => err.into(), + } + } +} + +impl From for Failure { + fn from(err: CreateError) -> Self { + match err { + CreateError::BadRequest(message) => Self::bad_request(message), + CreateError::Failed(err) => err.into(), + } + } +} diff --git a/crates/redshell-server/src/web/guard.rs b/crates/redshell-server/src/web/guard.rs new file mode 100644 index 0000000..a8b23b0 --- /dev/null +++ b/crates/redshell-server/src/web/guard.rs @@ -0,0 +1,268 @@ +//! Request checks: who the client is, whether a browser request comes from +//! our own pages, and who is signed in. +//! +//! **Origin.** A state-changing request (anything but GET, HEAD and +//! OPTIONS) and the WebSocket upgrade must, when they carry an `Origin`, +//! come from our own pages: exactly `public_url` when that is `https`; +//! otherwise `public_url`, `https://` when there is no `public_url`, +//! and `http://` only for a loopback host on a server without TLS of +//! its own. Browsers send `Origin` on all of these, so a missing one with a +//! session cookie is refused as well; clients that are not browsers (the +//! desktop, scripts) send none and authenticate with a bearer token. +//! +//! **`X-RedShell: 1`.** Every state-changing request carries this header, +//! from browsers and other clients alike. A page of another site cannot add +//! it without a CORS preflight, which this server never answers, so even a +//! browser that sends the cookie cross-site (an older one, or a site that +//! counts as the same) cannot change anything. + +use std::net::{IpAddr, SocketAddr}; + +use axum::extract::{ConnectInfo, FromRequestParts, Request, State}; +use axum::http::request::Parts; +use axum::http::{HeaderMap, HeaderValue, Method, header}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; + +use redshell_protocol::{CHANGE_HEADER, CHANGE_HEADER_VALUE}; + +use super::Shared; +use super::error::Failure; +use crate::auth::{COOKIE, Client, Principal, SESSION_TTL}; +use crate::config::ServerConfig; + +impl FromRequestParts for Client { + type Rejection = std::convert::Infallible; + + async fn from_request_parts(parts: &mut Parts, app: &Shared) -> Result { + Ok(client(&app.config, parts)) + } +} + +/// The client's address: the peer, or what `X-Forwarded-For` says when the +/// peer is a trusted proxy. The hops are read from the right, each added by +/// the one before: trusted proxies are skipped, and the first other address +/// is the client. A hop that does not read as an address stops the walk at +/// the last trusted proxy, since whatever lies left of it was not vouched for. +pub fn client(config: &ServerConfig, parts: &Parts) -> Client { + let peer = parts.extensions.get::>().map(|c| c.0.ip()); + let mut ip = peer.unwrap_or(IpAddr::from([0, 0, 0, 0])); + if config.trusted_proxies.contains(&ip) { + let headers: Vec<&str> = + parts.headers.get_all("x-forwarded-for").iter().filter_map(|v| v.to_str().ok()).collect(); + for hop in headers.iter().rev().flat_map(|v| v.rsplit(',')) { + let Some(hop) = hop_address(hop) else { break }; + ip = hop; + if !config.trusted_proxies.contains(&hop) { + break; + } + } + } + let user_agent = + parts.headers.get(header::USER_AGENT).and_then(|v| v.to_str().ok()).map(|ua| ua.chars().take(200).collect()); + Client { ip: ip.to_string(), user_agent } +} + +/// One `X-Forwarded-For` hop: `ip`, `ip:port`, `[v6]` or `[v6]:port`. +fn hop_address(hop: &str) -> Option { + let hop = hop.trim(); + if let Ok(ip) = hop.parse() { + return Some(ip); + } + if let Some(bracketed) = hop.strip_prefix('[') { + let (ip, rest) = bracketed.split_once(']')?; + return (rest.is_empty() || rest.strip_prefix(':').is_some_and(|p| p.parse::().is_ok())) + .then(|| ip.parse().ok()) + .flatten(); + } + hop.parse::().ok().map(|a| a.ip()) +} + +/// Refuses cross-site state changes; see the module docs. +pub async fn check_origin(State(app): State, req: Request, next: Next) -> Response { + let upgrade = req.headers().get(header::UPGRADE).is_some_and(|v| v.as_bytes().eq_ignore_ascii_case(b"websocket")); + let changes_state = !matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS); + if changes_state || upgrade { + let host = + req.headers().get(header::HOST).and_then(|h| h.to_str().ok()).or(req.uri().authority().map(|a| a.as_str())); + match req.headers().get(header::ORIGIN).map(|o| o.to_str().unwrap_or_default()) { + Some(origin) if !origin_allowed(&app.config, origin, host) => { + return Failure::forbidden("this request comes from another site").into_response(); + } + None if session_cookie(req.headers()).is_some() => { + return Failure::forbidden("a browser request without an Origin").into_response(); + } + _ => {} + } + } + if changes_state && req.headers().get(CHANGE_HEADER).is_none_or(|v| v.as_bytes() != CHANGE_HEADER_VALUE.as_bytes()) + { + return Failure::forbidden("a request that changes something needs the header X-RedShell: 1").into_response(); + } + next.run(req).await +} + +fn origin_allowed(config: &ServerConfig, origin: &str, host: Option<&str>) -> bool { + let origin = origin.to_ascii_lowercase(); + let host = host.map(str::to_ascii_lowercase); + let from_host = |scheme: &str| { + host.as_deref().is_some_and(|h| crate::config::origin_of(&format!("{scheme}://{h}")).is_ok_and(|o| o == origin)) + }; + // Plain http is only ever this machine talking to itself. + let local_http = || config.tls.is_none() && host.as_deref().is_some_and(is_loopback_host) && from_host("http"); + match config.public_origin.as_deref() { + Some(public) if public.starts_with("https://") => origin == public, + Some(public) => origin == public || local_http(), + None => from_host("https") || local_http(), + } +} + +/// Whether a `Host` header (`name[:port]`, `[v6][:port]`) names this machine. +fn is_loopback_host(host: &str) -> bool { + let name = match host.strip_prefix('[') { + Some(v6) => v6.split(']').next().unwrap_or_default(), + None => host.split(':').next().unwrap_or_default(), + }; + name == "localhost" || name.parse::().is_ok_and(|ip| ip.is_loopback()) +} + +/// Lets signed-in requests through with their [`crate::auth::Principal`] +/// as an extension; a browser session used after an hour gets its cookie +/// again with a fresh lifetime. +pub async fn require_auth(State(app): State, req: Request, next: Next) -> Response { + let (mut parts, body) = req.into_parts(); + let client = client(&app.config, &parts); + let cookie = session_cookie(&parts.headers); + let Some(principal) = principal(&app, &parts.headers, &client) else { + return Failure::unauthorized().into_response(); + }; + let renewed = principal.renewed; + parts.extensions.insert(principal); + let mut response = next.run(Request::from_parts(parts, body)).await; + if renewed + && let Some(token) = cookie + && !response.headers().contains_key(header::SET_COOKIE) + { + response.headers_mut().append(header::SET_COOKIE, set_cookie(&token)); + } + response +} + +/// Who is signed in with the request's cookie or bearer token. +pub fn principal(app: &Shared, headers: &HeaderMap, client: &Client) -> Option { + app.auth.authenticate(session_cookie(headers).as_deref(), bearer(headers).as_deref(), client) +} + +/// The session cookie's token, if the request has one. +pub fn session_cookie(headers: &HeaderMap) -> Option { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|pair| pair.trim().split_once('=')) + .find(|(name, _)| *name == COOKIE) + .map(|(_, value)| value.to_owned()) +} + +pub fn bearer(headers: &HeaderMap) -> Option { + let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?; + let (scheme, token) = value.split_once(' ')?; + scheme.eq_ignore_ascii_case("bearer").then(|| token.trim().to_owned()) +} + +/// `Set-Cookie` for a browser session. +pub fn set_cookie(token: &str) -> HeaderValue { + cookie(token, SESSION_TTL.as_secs()) +} + +/// `Set-Cookie` that deletes the browser session cookie. +pub fn clear_cookie() -> HeaderValue { + cookie("", 0) +} + +fn cookie(value: &str, max_age: u64) -> HeaderValue { + let cookie = format!("{COOKIE}={value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age={max_age}"); + // Tokens are base64url, so the value is always a valid header. + HeaderValue::from_str(&cookie).unwrap_or_else(|_| HeaderValue::from_static("")) +} + +#[cfg(test)] +mod tests { + use super::*; + use redshell_core::Settings; + use std::path::Path; + + fn config(toml: &str) -> ServerConfig { + ServerConfig::from_settings(Path::new("/x"), Settings::from_toml(toml).unwrap()).unwrap() + } + + #[test] + fn origins() { + let plain = config(""); + assert!(origin_allowed(&plain, "http://127.0.0.1:4747", Some("127.0.0.1:4747"))); + assert!(origin_allowed(&plain, "http://[::1]:4747", Some("[::1]:4747"))); + assert!(origin_allowed(&plain, "http://localhost:4747", Some("localhost:4747"))); + assert!(origin_allowed(&plain, "https://box.ts.net", Some("box.ts.net"))); + assert!(!origin_allowed(&plain, "http://box.ts.net", Some("box.ts.net")), "plain http from the network"); + assert!(!origin_allowed(&plain, "https://evil.example", Some("box.ts.net"))); + assert!(!origin_allowed(&plain, "null", Some("box.ts.net"))); + assert!(!origin_allowed(&plain, "http://box.ts.net", None)); + + let public = config("[server]\npublic_url = \"https://box.ts.net\"\n"); + assert!(origin_allowed(&public, "https://box.ts.net", Some("127.0.0.1:4747"))); + assert!(origin_allowed(&public, "https://box.ts.net", Some("box.ts.net"))); + for refused in ["http://box.ts.net", "https://other.ts.net", "http://127.0.0.1:4747"] { + for host in ["box.ts.net", "other.ts.net", "127.0.0.1:4747"] { + assert!(!origin_allowed(&public, refused, Some(host)), "{refused} via {host}"); + } + } + + let dev = config("[server]\npublic_url = \"http://localhost:4747\"\n"); + assert!(origin_allowed(&dev, "http://localhost:4747", Some("box.lan"))); + assert!(origin_allowed(&dev, "http://127.0.0.1:4747", Some("127.0.0.1:4747"))); + assert!(!origin_allowed(&dev, "https://box.lan", Some("box.lan")), "only public_url once it is set"); + + let tls = config("[server]\ntls_cert = \"c\"\ntls_key = \"k\"\n"); + assert!(!origin_allowed(&tls, "http://box:4747", Some("box:4747")), "no plain http next to TLS"); + assert!(!origin_allowed(&tls, "http://127.0.0.1:4747", Some("127.0.0.1:4747"))); + } + + #[test] + fn forwarded_for_only_from_trusted_proxies() { + let parts = |peer: &str, forwarded: &str| { + let mut req = axum::http::Request::builder().header("x-forwarded-for", forwarded).body(()).unwrap(); + req.extensions_mut().insert(ConnectInfo(peer.parse::().unwrap())); + req.into_parts().0 + }; + let trusting = config("[server]\ntrusted_proxies = [\"127.0.0.1\", \"10.0.0.2\"]\n"); + let ip = |peer: &str, forwarded: &str| client(&trusting, &parts(peer, forwarded)).ip; + assert_eq!(ip("127.0.0.1:1", "6.6.6.6, 100.64.0.7"), "100.64.0.7"); + assert_eq!(ip("127.0.0.1:1", "6.6.6.6, 100.64.0.7, 10.0.0.2"), "100.64.0.7", "trusted hops skipped"); + assert_eq!(ip("127.0.0.1:1", "junk"), "127.0.0.1"); + assert_eq!(ip("127.0.0.1:1", "6.6.6.6, junk, 10.0.0.2"), "10.0.0.2", "stops at the last trusted hop"); + assert_eq!(ip("127.0.0.1:1", "6.6.6.6, junk"), "127.0.0.1"); + assert_eq!(ip("127.0.0.1:1", "100.64.0.7:51234"), "100.64.0.7"); + assert_eq!(ip("127.0.0.1:1", "[2001:db8::7]:443"), "2001:db8::7"); + assert_eq!(ip("127.0.0.1:1", "[2001:db8::7]"), "2001:db8::7"); + assert_eq!(ip("127.0.0.1:1", "2001:db8::7"), "2001:db8::7"); + assert_eq!(ip("127.0.0.1:1", "[2001:db8::7]x"), "127.0.0.1"); + assert_eq!(ip("127.0.0.1:1", ""), "127.0.0.1"); + assert_eq!(ip("6.6.6.6:1", "100.64.0.7"), "6.6.6.6", "an untrusted peer speaks for itself"); + assert_eq!(client(&config(""), &parts("127.0.0.1:1", "100.64.0.7")).ip, "127.0.0.1"); + } + + #[test] + fn cookies_and_bearers() { + let mut headers = HeaderMap::new(); + headers.insert(header::COOKIE, HeaderValue::from_static("a=b; __Host-redshell-session=tok; c=d")); + headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Bearer xyz")); + assert_eq!(session_cookie(&headers).as_deref(), Some("tok")); + assert_eq!(bearer(&headers).as_deref(), Some("xyz")); + let cookie = set_cookie("tok"); + let cookie = cookie.to_str().unwrap(); + for flag in ["Secure", "HttpOnly", "SameSite=Strict", "Path=/", "Max-Age=2592000"] { + assert!(cookie.contains(flag), "{cookie}"); + } + } +} diff --git a/crates/redshell-server/src/web/hosts.rs b/crates/redshell-server/src/web/hosts.rs new file mode 100644 index 0000000..2d5df39 --- /dev/null +++ b/crates/redshell-server/src/web/hosts.rs @@ -0,0 +1,89 @@ +//! `/api/hosts`: the server's SSH hosts. Saved hosts are the +//! `[[ssh.hosts]]` entries of its `config.toml`, edited in place with the +//! file's comments kept; hosts only in `~/.ssh/config` are listed too. New +//! sessions and the profile list use a change at once. + +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::{Extension, Json}; +use redshell_protocol::SshHost; +use serde_json::{Value, json}; + +use super::Shared; +use super::error::{ApiResult, Failure}; +use crate::auth::{Client, Principal}; +use crate::hosts::{self, HostBook, HostError}; +use crate::store::AuditEvent; + +pub async fn list(State(app): State) -> ApiResult> { + let ctx = app.sessions.ctx().clone(); + let list = tokio::task::spawn_blocking(move || HostBook::load(&mut ctx.settings.get().ssh).list()); + Ok(Json(list.await.map_err(anyhow::Error::from)?)) +} + +/// Saves a new host; a host the desktop sends to the server arrives here. +pub async fn create( + State(app): State, + Extension(principal): Extension, + client: Client, + Json(host): Json, +) -> Result<(StatusCode, Json), Failure> { + let saved = edit(&app, move |book| book.save(None, hosts::from_wire(host))).await?; + audit(&app, &principal, &client, AuditEvent::HostSaved, &saved_detail(&saved)); + Ok((StatusCode::CREATED, Json(saved))) +} + +/// Saves over the host `name` (possibly renaming it), or over a host of +/// `~/.ssh/config` under its own name. +pub async fn replace( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(name): Path, + Json(host): Json, +) -> ApiResult { + let saved = edit(&app, move |book| book.save(Some(&name), hosts::from_wire(host))).await?; + audit(&app, &principal, &client, AuditEvent::HostSaved, &saved_detail(&saved)); + Ok(Json(saved)) +} + +pub async fn remove( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(name): Path, +) -> ApiResult { + let removed = name.clone(); + edit(&app, move |book| book.remove(&removed)).await?; + audit(&app, &principal, &client, AuditEvent::HostRemoved, &name); + Ok(Json(json!({}))) +} + +/// Runs `change` on the saved hosts as `config.toml` has them now, off the +/// async workers: it reads and writes files. +async fn edit( + app: &Shared, + change: impl FnOnce(&mut HostBook) -> Result + Send + 'static, +) -> Result { + let ctx = app.sessions.ctx().clone(); + let edited = tokio::task::spawn_blocking(move || ctx.settings.edit(|s| change(&mut HostBook::load(&mut s.ssh)))); + Ok(edited.await.map_err(anyhow::Error::from)??) +} + +/// A saved host for the audit log: its name, and the fields that run +/// commands on connect (extra ssh arguments, the startup command) in full. +fn saved_detail(host: &SshHost) -> String { + let mut detail = host.name.clone(); + if !host.extra_args.is_empty() { + detail.push_str(&format!("; extra_args: {:?}", host.extra_args)); + } + if let Some(command) = &host.startup_command { + detail.push_str(&format!("; startup_command: {command:?}")); + } + detail +} + +fn audit(app: &Shared, principal: &Principal, client: &Client, event: AuditEvent, host: &str) { + let user = &principal.user; + app.store.audit(event, Some(user.id), Some(&user.username), Some(&client.ip), host); +} diff --git a/crates/redshell-server/src/web/mod.rs b/crates/redshell-server/src/web/mod.rs new file mode 100644 index 0000000..871155c --- /dev/null +++ b/crates/redshell-server/src/web/mod.rs @@ -0,0 +1,108 @@ +//! The public HTTP side: the REST API under `/api`, the WebSocket and the +//! PWA. Every `/api` route needs a sign-in except `/api/auth/info`, +//! sign-in and setup, passkey sign-in, and starting and polling a pairing. + +mod account; +mod assets; +mod auth; +mod error; +mod guard; +mod hosts; +mod pairing; +mod passkeys; +mod push; +mod sessions; +mod ws; + +use std::sync::Arc; + +use axum::Router; +use axum::extract::DefaultBodyLimit; +use axum::middleware::from_fn_with_state; +use axum::routing::{delete, get, patch, post, put}; + +use crate::auth::Auth; +use crate::bus::Bus; +use crate::config::ServerConfig; +use crate::push::Push; +use crate::sessions::Sessions; +use crate::store::Store; +use error::Failure; + +pub use assets::CSP; + +/// What request handlers share. +pub struct AppState { + pub config: Arc, + pub auth: Auth, + pub sessions: Arc, + pub store: Arc, + pub bus: Bus, + pub push: Arc, +} + +pub type Shared = Arc; + +/// Largest body of a request that needs no sign-in: names, a password, a +/// passkey's answer. +const OPEN_BODY_LIMIT: usize = 16 << 10; +/// Largest body of a signed-in request; a passkey registration with its +/// attestation is the biggest. +const BODY_LIMIT: usize = 64 << 10; + +pub fn router(app: Shared) -> Router { + let open = Router::new() + .route("/auth/info", get(auth::info)) + .route("/auth/sign-in", post(auth::sign_in)) + .route("/setup", post(auth::setup)) + .route("/auth/passkey/begin", post(passkeys::sign_in_options)) + .route("/auth/passkey/finish", post(passkeys::sign_in)) + .route("/pair", post(pairing::start)) + // A request id (the device polling) or a code (a signed-in browser): see `pairing::show`. + .route("/pair/{key}", get(pairing::show)) + .layer(DefaultBodyLimit::max(OPEN_BODY_LIMIT)); + let signed_in = Router::new() + .route("/auth/sign-out", post(auth::sign_out)) + .route("/auth/me", get(auth::me)) + .route("/auth/reauth", post(auth::reauth)) + .route("/auth/reauth/passkey/begin", post(auth::reauth_options)) + .route("/account", get(passkeys::account)) + .route("/account/password", post(account::change_password)) + .route("/account/passkeys", get(passkeys::list)) + .route("/account/passkeys/begin", post(passkeys::registration_options)) + .route("/account/passkeys/finish", post(passkeys::register)) + .route("/account/passkeys/{id}", patch(passkeys::rename).delete(passkeys::revoke)) + .route("/account/passkey-only", put(passkeys::passkey_only)) + .route("/account/devices", get(account::devices)) + .route("/account/devices/{id}", delete(account::revoke_device)) + .route("/account/sessions", get(account::browser_sessions)) + .route("/account/sessions/{id}", delete(account::revoke_browser_session)) + .route("/profiles", get(sessions::profiles)) + .route("/sessions", get(sessions::list).post(sessions::create)) + .route("/sessions/{id}", patch(sessions::rename).delete(sessions::kill)) + .route("/approvals", get(sessions::approvals)) + .route("/approvals/{id}", post(sessions::answer)) + .route("/fs/folders", get(sessions::folders)) + .route("/pair/{code}/approve", post(pairing::approve)) + .route("/pair/{code}/reject", post(pairing::reject)) + .route("/push/key", get(push::key)) + .route( + "/push/subscriptions", + get(push::list).post(push::subscribe).put(push::set_events).delete(push::unsubscribe), + ) + .route("/push/test", post(push::test)) + .route("/hosts", get(hosts::list).post(hosts::create)) + .route("/hosts/{name}", put(hosts::replace).delete(hosts::remove)) + .route("/ws", get(ws::upgrade)) + .layer(DefaultBodyLimit::max(BODY_LIMIT)) + .route_layer(from_fn_with_state(app.clone(), guard::require_auth)); + let api = open + .merge(signed_in) + .fallback(|| async { Failure::not_found("API endpoint") }) + .layer(from_fn_with_state(app.clone(), guard::check_origin)); + let mut router = Router::new().nest("/api", api).fallback(assets::serve); + for layer in assets::security_headers(app.config.https()) { + router = router.layer(layer); + } + router.with_state(app) +} diff --git a/crates/redshell-server/src/web/pairing.rs b/crates/redshell-server/src/web/pairing.rs new file mode 100644 index 0000000..2c33e4d --- /dev/null +++ b/crates/redshell-server/src/web/pairing.rs @@ -0,0 +1,73 @@ +//! `/api/pair*`: desktop pairing (see `auth::pairing`). Starting a request +//! and polling it are open; looking up, approving and rejecting a code +//! need a sign-in. A code is only taken from the path the app builds from +//! what the user typed: a request carrying a query is refused, so no link +//! can stand in for typing. + +use axum::extract::{Path, RawQuery, State}; +use axum::http::HeaderMap; +use axum::response::{IntoResponse, Response}; +use axum::{Extension, Json}; +use redshell_protocol::{PairRequest, PairStarted, PairingInfo}; + +use super::Shared; +use super::error::{ApiResult, Failure}; +use super::guard::{bearer, principal}; +use crate::auth::{Client, Principal, is_pairing_code}; + +pub async fn start(State(app): State, client: Client, Json(req): Json) -> ApiResult { + Ok(Json(app.auth.start_pairing(&req.device_name, req.platform.as_deref(), &client)?)) +} + +/// `GET /api/pair/{key}`: with a code, the request it names, for a +/// signed-in user (`PairingInfo`); with a request id, its state for the +/// device polling with `Authorization: Bearer ` (`PairStatus`). +/// Ids and codes never look alike. +pub async fn show( + State(app): State, + client: Client, + Path(key): Path, + RawQuery(query): RawQuery, + headers: HeaderMap, +) -> Result { + if is_pairing_code(&key) { + let principal = principal(&app, &headers, &client).ok_or_else(Failure::unauthorized)?; + return Ok(answer(&app, &principal, &client, &key, query, None)?.into_response()); + } + let secret = bearer(&headers).unwrap_or_default(); + Ok(Json(app.auth.poll_pairing(&key, &secret, &client)?).into_response()) +} + +pub async fn approve( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(code): Path, + RawQuery(query): RawQuery, +) -> ApiResult { + answer(&app, &principal, &client, &code, query, Some(true)) +} + +pub async fn reject( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(code): Path, + RawQuery(query): RawQuery, +) -> ApiResult { + answer(&app, &principal, &client, &code, query, Some(false)) +} + +fn answer( + app: &Shared, + principal: &Principal, + client: &Client, + code: &str, + query: Option, + approve: Option, +) -> ApiResult { + if query.is_some_and(|q| !q.is_empty()) { + return Err(Failure::bad_request("type the code the device shows; links are not accepted")); + } + Ok(Json(app.auth.pairing_by_code(principal, code, approve, client)?)) +} diff --git a/crates/redshell-server/src/web/passkeys.rs b/crates/redshell-server/src/web/passkeys.rs new file mode 100644 index 0000000..caf30cd --- /dev/null +++ b/crates/redshell-server/src/web/passkeys.rs @@ -0,0 +1,93 @@ +//! Passkeys over REST: signing in with one (open), and registering, +//! listing, renaming and revoking them, the account and passkey-only mode +//! (signed in). + +use axum::extract::{Path, State}; +use axum::response::Response; +use axum::{Extension, Json}; +use redshell_protocol::{ + Account, Passkey, PasskeyChallenge, PasskeyOnlyRequest, PasskeySignInRequest, RegisterPasskeyRequest, + RenamePasskeyRequest, +}; +use serde_json::{Value, json}; + +use super::Shared; +use super::auth::signed_in; +use super::error::{ApiResult, Failure}; +use crate::auth::{Client, Principal}; + +pub async fn sign_in_options(State(app): State) -> ApiResult { + Ok(Json(app.auth.start_passkey_sign_in()?)) +} + +pub async fn sign_in( + State(app): State, + client: Client, + Json(req): Json, +) -> Result { + Ok(signed_in(app.auth.passkey_sign_in(req, &client)?)) +} + +pub async fn registration_options( + State(app): State, + Extension(principal): Extension, +) -> ApiResult { + Ok(Json(app.auth.start_passkey_registration(&principal)?)) +} + +pub async fn register( + State(app): State, + Extension(principal): Extension, + client: Client, + Json(req): Json, +) -> ApiResult { + Ok(Json(app.auth.register_passkey(&principal, req, &client)?)) +} + +pub async fn list(State(app): State, Extension(principal): Extension) -> ApiResult> { + Ok(Json(app.store.passkeys(principal.user.id)?)) +} + +pub async fn rename( + State(app): State, + Extension(principal): Extension, + Path(id): Path, + Json(req): Json, +) -> ApiResult { + Ok(Json(app.auth.rename_passkey(&principal, id, &req.name)?)) +} + +pub async fn revoke( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(id): Path, +) -> ApiResult { + app.auth.revoke_passkey(&principal, id, &client)?; + Ok(Json(json!({}))) +} + +pub async fn passkey_only( + State(app): State, + Extension(principal): Extension, + client: Client, + Json(req): Json, +) -> ApiResult { + app.auth.set_passkey_only(&principal, req.enabled, &client)?; + account(State(app), Extension(principal)).await +} + +/// `GET /api/account`: the user and how they sign in. +pub async fn account(State(app): State, Extension(principal): Extension) -> ApiResult { + let user = &principal.user; + let record = app.store.user_by_id(user.id)?.ok_or_else(Failure::unauthorized)?; + Ok(Json(Account { + id: user.id, + username: user.username.clone(), + created_at: user.created_at, + passkey_only: record.passkey_only, + passkeys: app.store.passkeys(user.id)?.len() as u32, + passkeys_available: app.auth.passkeys_available(), + reauth_expires_at: principal.reauth_expires_at(), + })) +} diff --git a/crates/redshell-server/src/web/push.rs b/crates/redshell-server/src/web/push.rs new file mode 100644 index 0000000..3b4871a --- /dev/null +++ b/crates/redshell-server/src/web/push.rs @@ -0,0 +1,91 @@ +//! `/api/push/*`: the VAPID key, the user's subscriptions and what each is +//! sent, and a test message. A browser session subscribes itself; the +//! others are named by their endpoint and must be the user's own. + +use axum::extract::State; +use axum::{Extension, Json}; +use redshell_protocol::{ + ErrorCode, PushEndpoint, PushEvent, PushEventsRequest, PushKey, PushSubscribeRequest, PushSubscriptionInfo, +}; +use serde_json::{Value, json}; + +use super::Shared; +use super::error::{ApiResult, Failure}; +use crate::auth::Principal; +use crate::push::{self, Delivery}; +use crate::store::Credential; + +pub async fn key(State(app): State) -> Json { + Json(PushKey { vapid_public_key: app.push.public_key() }) +} + +pub async fn list( + State(app): State, + Extension(principal): Extension, +) -> ApiResult> { + let browser = match principal.credential { + Credential::Browser(id) => Some(id), + Credential::Device(_) => None, + }; + Ok(Json(app.store.user_push_subscriptions(principal.user.id, browser)?)) +} + +/// Subscribes this browser session, replacing its earlier subscription. +pub async fn subscribe( + State(app): State, + Extension(principal): Extension, + Json(req): Json, +) -> ApiResult { + let Credential::Browser(browser) = principal.credential else { + return Err(Failure::bad_request("push notifications are for browsers")); + }; + let keys = push::check_subscription(&req).map_err(Failure::bad_request)?; + let events = req.events.unwrap_or_else(|| PushEvent::ALL.to_vec()); + let (user, keys) = (principal.user.id, (keys.p256dh.as_slice(), keys.auth.as_slice())); + if app.store.set_push_subscription(user, browser, &req.endpoint, keys, &events)? { + Ok(Json(json!({}))) + } else { + Err(Failure::new(ErrorCode::Conflict, "another account receives pushes at this endpoint")) + } +} + +pub async fn set_events( + State(app): State, + Extension(principal): Extension, + Json(req): Json, +) -> ApiResult { + found(app.store.set_push_events(principal.user.id, &req.endpoint, &req.events)?) +} + +pub async fn unsubscribe( + State(app): State, + Extension(principal): Extension, + Json(req): Json, +) -> ApiResult { + found(app.store.remove_push_subscription(principal.user.id, &req.endpoint)?) +} + +/// Sends a test message to one of the user's subscriptions and says +/// whether the push service took it. Why it did not goes to the log only: +/// the answer of a host the browser named is not repeated to the client. +pub async fn test( + State(app): State, + Extension(principal): Extension, + Json(req): Json, +) -> ApiResult { + let subscription = app.store.push_subscription(principal.user.id, &req.endpoint)?; + match app.push.test(subscription.ok_or_else(|| Failure::not_found("push subscription"))?).await { + Delivery::Sent => Ok(Json(json!({}))), + // A subscription the push service no longer knows is dropped; the answer is the same. + failed => { + if let Delivery::Failed(why) = failed { + log::info!("a test push was not delivered: {why}"); + } + Err(Failure::new(ErrorCode::Unavailable, "the push service did not take the test message")) + } + } +} + +fn found(changed: bool) -> ApiResult { + if changed { Ok(Json(json!({}))) } else { Err(Failure::not_found("push subscription")) } +} diff --git a/crates/redshell-server/src/web/sessions.rs b/crates/redshell-server/src/web/sessions.rs new file mode 100644 index 0000000..aa893eb --- /dev/null +++ b/crates/redshell-server/src/web/sessions.rs @@ -0,0 +1,116 @@ +//! Sessions, profiles, approvals and folder completion over REST. + +use axum::extract::{Path, Query, State}; +use axum::{Extension, Json}; +use redshell_protocol::{ + Approval, ApprovalAnswer, CreateSessionRequest, FolderListing, Profile, RenameSessionRequest, SessionInfo, +}; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::Shared; +use super::error::{ApiResult, Failure}; +use crate::agents::Answer; +use crate::auth::{Client, Principal}; +use crate::sessions::{launch, session_name}; +use crate::store::AuditEvent; + +/// Most folders one listing returns. +const MAX_FOLDERS: usize = 200; + +pub async fn profiles(State(app): State) -> ApiResult> { + let settings = app.sessions.ctx().settings.get(); + Ok(Json(tokio::task::spawn_blocking(move || launch::profiles(&settings)).await.map_err(anyhow::Error::from)?)) +} + +pub async fn list(State(app): State) -> Json> { + Json(app.sessions.list()) +} + +pub async fn create( + State(app): State, + Extension(principal): Extension, + Json(req): Json, +) -> ApiResult { + let sessions = app.sessions.clone(); + let info = tokio::task::spawn_blocking(move || sessions.create(req, &principal.user)) + .await + .map_err(anyhow::Error::from)??; + Ok(Json(info)) +} + +pub async fn rename( + State(app): State, + Path(id): Path, + Json(req): Json, +) -> ApiResult { + let session = app.sessions.get(&id).ok_or_else(|| Failure::not_found("session"))?; + session.rename(session_name(req.name).map_err(Failure::bad_request)?); + Ok(Json(session.info())) +} + +pub async fn kill(State(app): State, Path(id): Path) -> ApiResult { + if app.sessions.kill(&id) { Ok(Json(json!({}))) } else { Err(Failure::not_found("session")) } +} + +pub async fn approvals(State(app): State) -> Json> { + Json(app.sessions.ctx().approvals.pending()) +} + +pub async fn answer( + State(app): State, + Extension(principal): Extension, + client: Client, + Path(id): Path, + Json(req): Json, +) -> ApiResult { + answer_approval(&app, &principal, &client, &id, req)?; + Ok(Json(json!({}))) +} + +/// Hands an answer to the waiting agent; also used by the WebSocket. +pub fn answer_approval( + app: &Shared, + principal: &Principal, + client: &Client, + id: &str, + req: ApprovalAnswer, +) -> Result<(), Failure> { + let answer = Answer { decision: req.decision, message: req.message }; + let approval = app + .sessions + .ctx() + .approvals + .answer(id, answer, &principal.label) + .ok_or_else(|| Failure::not_found("approval"))?; + let detail = format!("{:?} {}: {}", req.decision, approval.tool, approval.summary); + let user = &principal.user; + app.store.audit(AuditEvent::ApprovalAnswered, Some(user.id), Some(&user.username), Some(&client.ip), &detail); + Ok(()) +} + +#[derive(Deserialize)] +pub struct FolderQuery { + path: String, +} + +/// Subfolders of an absolute folder, as the server's user sees them. +pub async fn folders(Query(query): Query) -> ApiResult { + let path = launch::folder(&query.path).map_err(Failure::bad_request)?; + let listing = tokio::task::spawn_blocking(move || -> Result { + let entries = std::fs::read_dir(&path).map_err(|err| format!("{}: {err}", path.display()))?; + let mut folders: Vec = entries + .filter_map(Result::ok) + .filter(|e| e.path().is_dir()) + .filter_map(|e| e.file_name().into_string().ok()) + .collect(); + folders.sort_by_key(|name| name.to_lowercase()); + let truncated = folders.len() > MAX_FOLDERS; + folders.truncate(MAX_FOLDERS); + Ok(FolderListing { path: query.path, folders, truncated }) + }) + .await + .map_err(anyhow::Error::from)? + .map_err(Failure::forbidden)?; + Ok(Json(listing)) +} diff --git a/crates/redshell-server/src/web/ws.rs b/crates/redshell-server/src/web/ws.rs new file mode 100644 index 0000000..c898457 --- /dev/null +++ b/crates/redshell-server/src/web/ws.rs @@ -0,0 +1,371 @@ +//! `/api/ws`: one WebSocket per client, multiplexing attached sessions. +//! +//! The connection task reads client messages and server-wide events; one +//! writer task owns the socket; each attached session has a forwarder task +//! that turns its output queue into binary frames. A forwarder whose queue +//! ended because the client fell behind sends a fresh snapshot and goes on; +//! one whose session is gone sends `detached`. A client whose snapshot was +//! taken on the alternate screen has nothing behind it, so it gets a fresh +//! snapshot as well when the program leaves that screen. + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use axum::Extension; +use axum::extract::State; +use axum::extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade}; +use axum::response::Response; +use futures_util::{SinkExt as _, StreamExt as _}; +use redshell_protocol::{ + ApprovalAnswer, ClientMessage, ErrorCode, Modes, MouseEncoding as WireEncoding, MouseTracking as WireTracking, + PROTOCOL_VERSION, ServerMessage, Snapshot, frame, unframe, +}; +use redshell_terminal::{CursorShape, MouseEncoding, MouseTracking, Replay}; +use tokio::sync::{broadcast, mpsc}; +use tokio::task::AbortHandle; + +use super::Shared; +use super::error::Failure; +use super::sessions::answer_approval; +use crate::auth::{Client, Principal}; +use crate::bus::BusEvent; +use crate::sessions::{Feed, Session, session_name}; + +/// Largest message a client may send. +const MAX_MESSAGE: usize = 1 << 20; +/// Messages waiting for the socket. +const OUTBOX: usize = 32; +/// Pings find connections a phone dropped without closing. +const PING_EVERY: Duration = Duration::from_secs(30); + +/// Ids of attachments across connections, for "the client that typed last". +static NEXT_CLIENT: AtomicU64 = AtomicU64::new(1); + +pub async fn upgrade( + ws: WebSocketUpgrade, + State(app): State, + Extension(principal): Extension, + client: Client, +) -> Response { + ws.max_message_size(MAX_MESSAGE).on_upgrade(move |socket| Connection::run(app, principal, client, socket)) +} + +struct Attachment { + session: Arc, + client: u64, + size: (u16, u16), + forwarder: AbortHandle, +} + +struct Connection { + app: Shared, + principal: Principal, + client: Client, + out: mpsc::Sender, + channels: HashMap, + next_channel: u16, + sessions: bool, + events: bool, +} + +impl Connection { + async fn run(app: Shared, principal: Principal, client: Client, socket: WebSocket) { + let (mut sink, mut stream) = socket.split(); + let (out, mut outbox) = mpsc::channel::(OUTBOX); + let writer = tokio::spawn(async move { + while let Some(message) = outbox.recv().await { + let close = matches!(message, Message::Close(_)); + if sink.send(message).await.is_err() || close { + break; + } + } + }); + let mut bus = app.bus.subscribe(); + let mut this = Self { + app, + principal, + client, + out, + channels: HashMap::new(), + next_channel: 1, + sessions: false, + events: false, + }; + this.send(&ServerMessage::Hello { protocol_version: PROTOCOL_VERSION, user: this.principal.user.clone() }) + .await; + let mut ping = tokio::time::interval_at(tokio::time::Instant::now() + PING_EVERY, PING_EVERY); + loop { + tokio::select! { + message = stream.next() => match message { + Some(Ok(Message::Text(text))) => this.on_text(&text).await, + Some(Ok(Message::Binary(bytes))) => this.on_binary(&bytes).await, + Some(Ok(Message::Ping(_) | Message::Pong(_))) => {} + Some(Ok(Message::Close(_)) | Err(_)) | None => break, + }, + event = bus.recv() => match event { + Ok(event) => if !this.on_bus(event).await { break }, + Err(broadcast::error::RecvError::Lagged(_)) => this.resend_views().await, + Err(broadcast::error::RecvError::Closed) => break, + }, + _ = ping.tick() => { + // Also catches sign-outs from elsewhere: the `user` CLI, an expired cookie. + if !this.still_signed_in() { + this.close().await; + break; + } + this.app.auth.seen(&mut this.principal, &this.client); + let _ = this.out.send(Message::Ping(Default::default())).await; + } + } + } + for (_, attachment) in this.channels.drain() { + attachment.forwarder.abort(); + attachment.session.detached(attachment.client); + } + drop(this); + let _ = writer.await; + } + + async fn send(&self, message: &ServerMessage) { + send(&self.out, message).await; + } + + async fn fail(&self, failure: Failure) { + self.send(&ServerMessage::Error { code: failure.0.code, message: failure.0.message }).await; + } + + async fn on_text(&mut self, text: &str) { + match serde_json::from_str::(text) { + Ok(message) => { + if let Err(failure) = self.on_message(message).await { + self.fail(failure).await; + } + } + Err(err) => self.fail(Failure::bad_request(format!("unreadable message: {err}"))).await, + } + } + + async fn on_binary(&mut self, bytes: &[u8]) { + let result = match unframe(bytes) { + Some((channel, data)) => self.input(channel, data.to_vec()), + None => Err(Failure::bad_request("a binary frame starts with a 2-byte channel")), + }; + if let Err(failure) = result { + self.fail(failure).await; + } + } + + async fn on_message(&mut self, message: ClientMessage) -> Result<(), Failure> { + match message { + ClientMessage::Attach { session, cols, rows } => self.attach(&session, cols, rows).await?, + ClientMessage::Detach { channel } => { + let attachment = self.channels.remove(&channel).ok_or_else(|| Failure::not_found("channel"))?; + attachment.forwarder.abort(); + attachment.session.detached(attachment.client); + self.send(&ServerMessage::Detached { channel }).await; + } + ClientMessage::Resize { channel, cols, rows } => { + let attachment = self.channels.get_mut(&channel).ok_or_else(|| Failure::not_found("channel"))?; + attachment.size = (cols, rows); + attachment.session.client_resized(attachment.client, cols, rows); + } + ClientMessage::Input { channel, data } => self.input(channel, data.into_bytes())?, + ClientMessage::Rename { session, name } => { + let name = session_name(name).map_err(Failure::bad_request)?; + self.app.sessions.get(&session).ok_or_else(|| Failure::not_found("session"))?.rename(name); + } + ClientMessage::Subscribe { sessions, events } => { + (self.sessions, self.events) = (sessions, events); + self.resend_views().await; + } + ClientMessage::Approve { approval, decision, message } => { + answer_approval( + &self.app, + &self.principal, + &self.client, + &approval, + ApprovalAnswer { decision, message }, + )?; + } + } + Ok(()) + } + + fn input(&self, channel: u16, bytes: Vec) -> Result<(), Failure> { + let attachment = self.channels.get(&channel).ok_or_else(|| Failure::not_found("channel"))?; + if attachment.session.input(attachment.client, self.principal.user.id, attachment.size, bytes) { + Ok(()) + } else { + Err(Failure::new(ErrorCode::Conflict, "input dropped: the program is not reading it")) + } + } + + async fn attach(&mut self, id: &str, cols: u16, rows: u16) -> Result<(), Failure> { + let session = self.app.sessions.get(id).ok_or_else(|| Failure::not_found("session"))?; + let channel = (0..u16::MAX) + .map(|i| self.next_channel.wrapping_add(i).max(1)) + .find(|c| !self.channels.contains_key(c)) + .ok_or_else(|| Failure::bad_request("too many attached sessions"))?; + self.next_channel = channel.wrapping_add(1); + let client = NEXT_CLIENT.fetch_add(1, Ordering::Relaxed); + session.attached(client, cols, rows); + let (queue, replay) = subscribe(&session).await?; + let attached = ServerMessage::Attached { channel, session: session.info(), snapshot: snapshot(&replay) }; + self.send(&attached).await; + let forwarder = + tokio::spawn(forward(self.app.clone(), session.clone(), channel, self.out.clone(), queue, replay)); + self.channels + .insert(channel, Attachment { session, client, size: (cols, rows), forwarder: forwarder.abort_handle() }); + Ok(()) + } + + /// Handles a server-wide event; `false` closes the connection. + async fn on_bus(&mut self, event: BusEvent) -> bool { + let mine = self.principal.credential; + match event { + BusEvent::Revoked(credential) if credential == mine => return self.close().await, + BusEvent::RevokedAllBut { user_id, keep } if user_id == self.principal.user.id && keep != mine => { + return self.close().await; + } + BusEvent::SessionChanged(id) if self.sessions => { + if let Some(session) = self.app.sessions.get(&id) { + self.send(&ServerMessage::SessionUpdated { session: session.info() }).await; + } + } + BusEvent::SessionRemoved(id) if self.sessions => self.send(&ServerMessage::SessionRemoved { id }).await, + BusEvent::ApprovalRequested(approval) if self.events => { + self.send(&ServerMessage::ApprovalRequested { approval }).await; + } + BusEvent::ApprovalResolved { id, session, outcome, answered_by } if self.events => { + self.send(&ServerMessage::ApprovalResolved { id, session, outcome, answered_by }).await; + } + BusEvent::Event(event) if self.events => self.send(&ServerMessage::Event { event }).await, + _ => {} + } + true + } + + /// Sends the full session list and pending approvals the client chose. + async fn resend_views(&self) { + if self.sessions { + self.send(&ServerMessage::Sessions { sessions: self.app.sessions.list() }).await; + } + if self.events { + self.send(&ServerMessage::Approvals { approvals: self.app.sessions.ctx().approvals.pending() }).await; + } + } + + fn still_signed_in(&self) -> bool { + self.principal.still_valid(&self.app.store).unwrap_or_else(|err| { + log::error!("checking a sign-in: {err:#}"); + true + }) + } + + async fn close(&self) -> bool { + let frame = CloseFrame { code: 4001, reason: "signed out".into() }; + let _ = self.out.send(Message::Close(Some(frame))).await; + false + } +} + +async fn send(out: &mpsc::Sender, message: &ServerMessage) -> bool { + match serde_json::to_string(message) { + Ok(text) => out.send(Message::Text(text.into())).await.is_ok(), + Err(err) => { + log::error!("encoding a message: {err}"); + true + } + } +} + +/// Output from now on, and the screen up to where it starts. +async fn subscribe(session: &Arc) -> Result<(mpsc::Receiver, Replay), Failure> { + let queue = session.subscribe(); + let s = session.clone(); + let replay = tokio::task::spawn_blocking(move || s.replay()).await.map_err(anyhow::Error::from)?; + Ok((queue, replay)) +} + +/// Streams a session's output to one channel; see the module docs. +async fn forward( + app: Shared, + session: Arc, + channel: u16, + out: mpsc::Sender, + mut queue: mpsc::Receiver, + replay: Replay, +) { + let mut offset = replay.offset; + // The client's screen came from the alternate screen. + let mut on_alt = replay.modes.alt_screen; + loop { + while let Some(feed) = queue.recv().await { + let sent = match feed { + Feed::Output { end, bytes } => { + if end <= offset { + continue; + } + let skip = offset.saturating_sub(end - bytes.len() as u64) as usize; + offset = end; + out.send(Message::Binary(frame(channel, &bytes[skip..]).into())).await.is_ok() + } + Feed::Resized { cols, rows } => send(&out, &ServerMessage::Resized { channel, cols, rows }).await, + Feed::LeftAltScreen if on_alt => break, + Feed::LeftAltScreen => continue, + }; + if !sent { + return; + } + } + if app.sessions.get(&session.id).is_none() { + send(&out, &ServerMessage::Detached { channel }).await; + return; + } + // The client fell behind, or lacks the screen the program went back to: start over. + let Ok((fresh, replay)) = subscribe(&session).await else { return }; + (queue, offset, on_alt) = (fresh, replay.offset, replay.modes.alt_screen); + if !send(&out, &ServerMessage::Snapshot { channel, snapshot: snapshot(&replay) }).await { + return; + } + } +} + +/// The wire form of a terminal replay. +fn snapshot(replay: &Replay) -> Snapshot { + let m = &replay.modes; + Snapshot { + cols: replay.cols, + rows: replay.rows, + data: replay.data.clone(), + modes: Modes { + alt_screen: m.alt_screen, + app_cursor: m.app_cursor, + app_keypad: m.app_keypad, + bracketed_paste: m.bracketed_paste, + mouse_tracking: m.mouse.map(|p| match p.tracking { + MouseTracking::Click => WireTracking::Click, + MouseTracking::Drag => WireTracking::Drag, + MouseTracking::Motion => WireTracking::Motion, + }), + mouse_encoding: match m.mouse.map(|p| p.encoding) { + Some(MouseEncoding::Sgr) => WireEncoding::Sgr, + Some(MouseEncoding::Utf8) => WireEncoding::Utf8, + Some(MouseEncoding::Normal) | None => WireEncoding::Normal, + }, + focus_reporting: m.focus_reporting, + cursor_visible: m.cursor_visible, + cursor_shape: match m.cursor_shape { + CursorShape::Block => redshell_protocol::CursorShape::Block, + CursorShape::Bar => redshell_protocol::CursorShape::Bar, + CursorShape::Underline => redshell_protocol::CursorShape::Underline, + CursorShape::Hollow => redshell_protocol::CursorShape::Hollow, + CursorShape::Hidden => redshell_protocol::CursorShape::Hidden, + }, + cursor_blinking: m.cursor_blinking, + title: m.title.clone(), + }, + } +} diff --git a/crates/redshell-server/tests/server.rs b/crates/redshell-server/tests/server.rs new file mode 100644 index 0000000..67bdbc1 --- /dev/null +++ b/crates/redshell-server/tests/server.rs @@ -0,0 +1,1362 @@ +//! The server end to end: started on an ephemeral port with a temporary +//! config directory, driven over real HTTP and WebSocket connections. +//! +//! Sessions run `sh` and fake agent scripts, so those tests are Unix only; +//! Windows runs the auth and HTTP tests. + +// The WebSocket helpers serve the Unix-only session tests. +#![cfg_attr(not(unix), allow(dead_code, unused_imports))] + +use std::time::Duration; + +use futures_util::{SinkExt as _, StreamExt as _}; +use redshell_protocol::{ClientMessage, ServerMessage, SessionInfo, frame, unframe}; +use redshell_server::connections::Limits; +use redshell_server::{RunningServer, ServerConfig}; +use reqwest::StatusCode; +use reqwest::header::{HeaderMap, HeaderValue}; +use serde_json::{Value, json}; +use tokio_tungstenite::tungstenite::{self, Message, client::IntoClientRequest as _}; + +const PASSWORD: &str = "a long passphrase"; + +struct Harness { + dir: tempfile::TempDir, + server: RunningServer, + http: reqwest::Client, +} + +type Ws = tokio_tungstenite::WebSocketStream>; + +impl Harness { + async fn start(extra: &str) -> Self { + Self::start_with("listen = \"127.0.0.1:0\"", extra).await + } + + /// A server whose `public_url` is `http://localhost:`, which + /// passkeys accept while developing. The port is picked before the + /// server binds it, so another test may take it first: then it tries + /// another. + async fn on_localhost() -> Self { + for _ in 0..10 { + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let server = format!("listen = \"127.0.0.1:{port}\"\npublic_url = \"http://localhost:{port}\""); + if let Ok(started) = Self::try_start(&server, "", |_| {}).await { + return started; + } + } + panic!("no free port for a localhost server"); + } + + async fn start_with(server: &str, extra: &str) -> Self { + Self::start_tuned(server, extra, |_| {}).await + } + + /// Like [`Self::start_with`], with the loaded configuration changed by `tune`. + async fn start_tuned(server: &str, extra: &str, tune: impl FnOnce(&mut ServerConfig)) -> Self { + Self::try_start(server, extra, tune).await.unwrap() + } + + async fn try_start(server: &str, extra: &str, tune: impl FnOnce(&mut ServerConfig)) -> anyhow::Result { + let _ = rustls::crypto::ring::default_provider().install_default(); + let dir = tempfile::tempdir().unwrap(); + let config = format!( + "[server]\n{server}\napproval_timeout_secs = 5\n[ssh]\nimport_ssh_config = false\n\ + [terminal]\nshell = \"/bin/sh\"\nshell_integration = false\n{extra}" + ); + std::fs::write(dir.path().join("config.toml"), config).unwrap(); + let mut config = ServerConfig::load(dir.path()).unwrap(); + tune(&mut config); + let server = RunningServer::start(config).await?; + Ok(Self { dir, server, http: client() }) + } + + fn origin(&self) -> String { + format!("http://{}", self.server.addr) + } + + fn url(&self, path: &str) -> String { + format!("{}{path}", self.origin()) + } + + fn post(&self, path: &str, body: Value) -> reqwest::RequestBuilder { + self.http.post(self.url(path)).header("origin", self.origin()).json(&body) + } + + /// Creates the account through the setup link; returns the cookie. + async fn setup(&self) -> String { + self.setup_from(&self.origin()).await + } + + /// Like [`Self::setup`], from a page at `origin`. + async fn setup_from(&self, origin: &str) -> String { + let link = self.server.setup_link().unwrap().expect("no account yet"); + let code = link.split("code=").nth(1).unwrap(); + let body = json!({"code": code, "username": "me", "password": PASSWORD}); + let res = self.http.post(self.url("/api/setup")).header("origin", origin).json(&body).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::OK); + cookie(res.headers()).expect("setup signs the browser in") + } + + async fn device_token(&self) -> String { + let body = json!({"username": "me", "password": PASSWORD, "device_name": "test"}); + let res: Value = self.post("/api/auth/sign-in", body).send().await.unwrap().json().await.unwrap(); + res["device_token"].as_str().unwrap().to_owned() + } + + async fn create(&self, token: &str, body: Value) -> SessionInfo { + let res = self.http.post(self.url("/api/sessions")).bearer_auth(token).json(&body).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "{}", res.text().await.unwrap()); + res.json().await.unwrap() + } + + async fn ws(&self, token: &str) -> Ws { + let mut req = format!("ws://{}/api/ws", self.server.addr).into_client_request().unwrap(); + req.headers_mut().insert("authorization", HeaderValue::from_str(&format!("Bearer {token}")).unwrap()); + let (mut ws, _) = tokio_tungstenite::connect_async(req).await.unwrap(); + assert!(matches!(next(&mut ws).await, Event::Json(ServerMessage::Hello { .. }))); + ws + } +} + +/// An HTTP client that sends `X-RedShell: 1`, as every client of the API does. +fn client() -> reqwest::Client { + let headers = HeaderMap::from_iter([( + reqwest::header::HeaderName::from_static(redshell_protocol::CHANGE_HEADER), + HeaderValue::from_static(redshell_protocol::CHANGE_HEADER_VALUE), + )]); + reqwest::Client::builder().default_headers(headers).build().unwrap() +} + +/// The session cookie a response sets, checking its flags. +fn cookie(headers: &HeaderMap) -> Option { + let set = headers.get("set-cookie")?.to_str().unwrap(); + for flag in ["HttpOnly", "Secure", "SameSite=Strict", "Path=/"] { + assert!(set.contains(flag), "{set}"); + } + let value = set.strip_prefix("__Host-redshell-session=")?.split(';').next()?; + Some(value.to_owned()) +} + +#[expect(clippy::large_enum_variant, reason = "short-lived test values")] +enum Event { + Json(ServerMessage), + /// Output bytes of an attached session. + Output(Vec), + Closed, +} + +async fn next(ws: &mut Ws) -> Event { + loop { + let message = tokio::time::timeout(Duration::from_secs(10), ws.next()).await.expect("no message in 10 s"); + return match message { + Some(Ok(Message::Text(text))) => Event::Json(serde_json::from_str(&text).unwrap()), + Some(Ok(Message::Binary(bytes))) => { + let (_channel, data) = unframe(&bytes).unwrap(); + Event::Output(data.to_vec()) + } + Some(Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_))) => continue, + Some(Ok(Message::Close(_)) | Err(_)) | None => Event::Closed, + }; + } +} + +async fn send(ws: &mut Ws, message: ClientMessage) { + ws.send(Message::text(serde_json::to_string(&message).unwrap())).await.unwrap(); +} + +/// Reads until `wanted` returns something, collecting output on the way. +async fn until(ws: &mut Ws, output: &mut Vec, mut wanted: impl FnMut(&Event, &[u8]) -> Option) -> T { + loop { + let event = next(ws).await; + if let Event::Output(data) = &event { + output.extend_from_slice(data); + } + if let Some(found) = wanted(&event, output) { + return found; + } + assert!(!matches!(event, Event::Closed), "the socket closed"); + } +} + +/// Reads until the output collected so far shows `needle`. +async fn output_with(ws: &mut Ws, output: &mut Vec, needle: &str) { + if !contains(output, needle) { + until(ws, output, |_, out| contains(out, needle).then_some(())).await; + } +} + +fn contains(haystack: &[u8], needle: &str) -> bool { + haystack.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +#[tokio::test] +async fn setup_creates_the_first_account_once() { + let h = Harness::start("").await; + let info: Value = h.http.get(h.url("/api/auth/info")).send().await.unwrap().json().await.unwrap(); + assert_eq!(info["setup_required"], true); + assert_eq!(info["min_password_length"], 10); + assert!(h.server.setup_link().unwrap().unwrap().starts_with(&h.origin())); + + let wrong = + h.post("/api/setup", json!({"code": "guess", "username": "me", "password": PASSWORD})).send().await.unwrap(); + assert_eq!(wrong.status(), StatusCode::FORBIDDEN); + let cookie = h.setup().await; + + let me: Value = h + .http + .get(h.url("/api/auth/me")) + .header("cookie", format!("__Host-redshell-session={cookie}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(me["username"], "me"); + let info: Value = h.http.get(h.url("/api/auth/info")).send().await.unwrap().json().await.unwrap(); + assert_eq!(info["setup_required"], false); + assert!(h.server.setup_link().unwrap().is_none()); +} + +#[tokio::test] +async fn sign_in_fails_alike_and_backs_off() { + let h = Harness::start("").await; + h.setup().await; + let attempt = |user: &str| h.post("/api/auth/sign-in", json!({"username": user, "password": "wrong password"})); + let unknown = attempt("ghost").send().await.unwrap(); + let wrong = attempt("me").send().await.unwrap(); + assert_eq!((unknown.status(), wrong.status()), (StatusCode::UNAUTHORIZED, StatusCode::UNAUTHORIZED)); + assert_eq!(unknown.text().await.unwrap(), wrong.text().await.unwrap(), "no hint whether the user exists"); + assert_eq!(attempt("me").send().await.unwrap().status(), StatusCode::UNAUTHORIZED); + let throttled = attempt("me").send().await.unwrap(); + assert_eq!(throttled.status(), StatusCode::TOO_MANY_REQUESTS); + assert!(throttled.headers().contains_key("retry-after")); + let body: Value = throttled.json().await.unwrap(); + assert_eq!(body["code"], "rate_limited"); + // Even the right password waits now. + let right = h.post("/api/auth/sign-in", json!({"username": "me", "password": PASSWORD})).send().await.unwrap(); + assert_eq!(right.status(), StatusCode::TOO_MANY_REQUESTS); +} + +#[tokio::test] +async fn browser_requests_need_our_origin() { + let h = Harness::start("").await; + let cookie = format!("__Host-redshell-session={}", h.setup().await); + let create = |origin: Option<&str>| { + let mut req = h.http.post(h.url("/api/auth/sign-out")).header("cookie", &cookie).json(&json!({})); + if let Some(origin) = origin { + req = req.header("origin", origin); + } + req + }; + assert_eq!(create(Some("https://evil.example")).send().await.unwrap().status(), StatusCode::FORBIDDEN); + assert_eq!(create(None).send().await.unwrap().status(), StatusCode::FORBIDDEN); + let mut req = format!("ws://{}/api/ws", h.server.addr).into_client_request().unwrap(); + req.headers_mut().insert("cookie", HeaderValue::from_str(&cookie).unwrap()); + req.headers_mut().insert("origin", HeaderValue::from_static("https://evil.example")); + match tokio_tungstenite::connect_async(req).await { + Err(tungstenite::Error::Http(res)) => assert_eq!(res.status(), 403), + other => panic!("cross-site WebSocket accepted: {:?}", other.map(|_| ())), + } + let ok = create(Some(&h.origin())).send().await.unwrap(); + assert_eq!(ok.status(), StatusCode::OK); + assert!(ok.headers().get("set-cookie").unwrap().to_str().unwrap().contains("Max-Age=0"), "sign-out clears it"); + let after = h.http.get(h.url("/api/auth/me")).header("cookie", &cookie).send().await.unwrap(); + assert_eq!(after.status(), StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn state_changes_need_the_redshell_header() { + let h = Harness::start("").await; + let cookie = format!("__Host-redshell-session={}", h.setup().await); + let bare = reqwest::Client::new(); + // A body-less POST as a cross-site form or `fetch` without a preflight would send it. + let res = bare + .post(h.url("/api/auth/sign-out")) + .header("cookie", &cookie) + .header("origin", h.origin()) + .header("content-type", "text/plain") + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::FORBIDDEN); + assert!(res.text().await.unwrap().contains("X-RedShell")); + let token = h.device_token().await; + let res = bare.delete(h.url("/api/sessions/nope")).bearer_auth(&token).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::FORBIDDEN, "bearer clients send it too"); + let wrong = bare.post(h.url("/api/auth/sign-out")).bearer_auth(&token).header("x-redshell", "0").send(); + assert_eq!(wrong.await.unwrap().status(), StatusCode::FORBIDDEN); + let read = bare.get(h.url("/api/auth/me")).header("cookie", &cookie).send().await.unwrap(); + assert_eq!(read.status(), StatusCode::OK, "reading needs nothing"); + let ok = h.http.post(h.url("/api/auth/sign-out")).header("cookie", &cookie).header("origin", h.origin()).send(); + assert_eq!(ok.await.unwrap().status(), StatusCode::OK); +} + +#[tokio::test] +async fn an_https_public_url_is_the_only_browser_origin_and_gets_hsts() { + let h = Harness::start_with("listen = \"127.0.0.1:0\"\npublic_url = \"https://box.example.test\"", "").await; + let cookie = format!("__Host-redshell-session={}", h.setup_from("https://box.example.test").await); + let headers = h.http.get(h.url("/")).send().await.unwrap().headers().clone(); + assert_eq!(headers["strict-transport-security"], "max-age=31536000"); + let api = h.http.get(h.url("/api/auth/info")).send().await.unwrap(); + assert!(api.headers().contains_key("strict-transport-security")); + + let from = |origin: &str, path: &str| { + h.http + .post(h.url(path)) + .header("host", "box.example.test") + .header("cookie", &cookie) + .header("origin", origin) + .send() + }; + for origin in ["http://box.example.test", "http://127.0.0.1", &h.origin(), "https://evil.example"] { + for path in ["/api/account/passkeys/begin", "/api/pair/KX7-4MP/approve", "/api/auth/sign-out"] { + assert_eq!(from(origin, path).await.unwrap().status(), StatusCode::FORBIDDEN, "{origin} {path}"); + } + let mut req = format!("ws://{}/api/ws", h.server.addr).into_client_request().unwrap(); + req.headers_mut().insert("cookie", HeaderValue::from_str(&cookie).unwrap()); + req.headers_mut().insert("host", HeaderValue::from_static("box.example.test")); + req.headers_mut().insert("origin", HeaderValue::from_str(origin).unwrap()); + match tokio_tungstenite::connect_async(req).await { + Err(tungstenite::Error::Http(res)) => assert_eq!(res.status(), 403), + other => panic!("WebSocket from {origin} accepted: {:?}", other.map(|_| ())), + } + } + assert_eq!(from("https://box.example.test", "/api/auth/sign-out").await.unwrap().status(), StatusCode::OK); +} + +#[tokio::test] +async fn oversized_input_is_refused_before_it_is_recorded() { + let h = Harness::start("").await; + h.setup().await; + let long_name = h.post("/api/auth/sign-in", json!({"username": "x".repeat(65), "password": "wrong password"})); + let res = long_name.send().await.unwrap(); + assert_eq!(res.status(), StatusCode::BAD_REQUEST); + let huge = json!({"username": "me", "password": "p".repeat(17 << 10)}); + assert_eq!(h.post("/api/auth/sign-in", huge).send().await.unwrap().status(), StatusCode::PAYLOAD_TOO_LARGE); + let pair = json!({"device_name": "d".repeat(17 << 10)}); + assert_eq!(h.post("/api/pair", pair).send().await.unwrap().status(), StatusCode::PAYLOAD_TOO_LARGE); + + let token = h.device_token().await; + let host = json!({"name": "box", "host": "box.lan", "startup_command": "x".repeat(65 << 10)}); + let res = h.http.post(h.url("/api/hosts")).bearer_auth(&token).json(&host).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE); + let host = json!({"name": "box", "host": "box.lan", "startup_command": "x".repeat(5000)}); + let res = h.http.post(h.url("/api/hosts")).bearer_auth(&token).json(&host).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::BAD_REQUEST); + let long = json!({"command": ["true"], "name": "n".repeat(101)}); + let res = h.http.post(h.url("/api/sessions")).bearer_auth(&token).json(&long).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::BAD_REQUEST, "a session name has at most 100 characters"); +} + +#[tokio::test] +async fn a_trusted_proxy_names_the_client() { + let h = Harness::start_with("listen = \"127.0.0.1:0\"\ntrusted_proxies = [\"127.0.0.1\"]", "").await; + h.setup().await; + let sign_in = |forwarded: &str| { + let body = json!({"username": "me", "password": PASSWORD}); + h.post("/api/auth/sign-in", body).header("x-forwarded-for", forwarded).send() + }; + let h = &h; + let last_ip = |res: reqwest::Response| async move { + let cookie = format!("__Host-redshell-session={}", cookie(res.headers()).unwrap()); + let sessions: Value = h + .http + .get(h.url("/api/account/sessions")) + .header("cookie", &cookie) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let current = sessions.as_array().unwrap().iter().find(|s| s["current"] == true).unwrap().clone(); + current["last_ip"].as_str().unwrap().to_owned() + }; + assert_eq!(last_ip(sign_in("6.6.6.6, [2001:db8::7]:443").await.unwrap()).await, "2001:db8::7"); + assert_eq!(last_ip(sign_in("6.6.6.6, junk").await.unwrap()).await, "127.0.0.1", "nothing left of junk counts"); +} + +#[tokio::test] +async fn device_tokens_until_revoked() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + assert_eq!(h.http.get(h.url("/api/sessions")).send().await.unwrap().status(), StatusCode::UNAUTHORIZED); + let devices: Value = + h.http.get(h.url("/api/account/devices")).bearer_auth(&token).send().await.unwrap().json().await.unwrap(); + assert_eq!((devices[0]["name"].as_str(), devices[0]["current"].as_bool()), (Some("test"), Some(true))); + let id = devices[0]["id"].as_i64().unwrap(); + + let mut ws = h.ws(&token).await; + let other = h.device_token().await; + let revoke = h.http.delete(h.url(&format!("/api/account/devices/{id}"))).bearer_auth(&other).send().await.unwrap(); + assert_eq!(revoke.status(), StatusCode::OK); + assert!(matches!(next(&mut ws).await, Event::Closed), "a revoked device's socket closes"); + assert_eq!( + h.http.get(h.url("/api/sessions")).bearer_auth(&token).send().await.unwrap().status(), + StatusCode::UNAUTHORIZED + ); +} + +#[tokio::test] +async fn a_socket_ends_with_its_sign_in_even_when_the_row_id_comes_back() { + let h = Harness::start("").await; + // The first browser session: row 1 of an empty table, which a new row would get again + // if ids were reused. + let first = format!("__Host-redshell-session={}", h.setup().await); + let mut req = format!("ws://{}/api/ws", h.server.addr).into_client_request().unwrap(); + req.headers_mut().insert("cookie", HeaderValue::from_str(&first).unwrap()); + req.headers_mut().insert("origin", HeaderValue::from_str(&h.origin()).unwrap()); + let (mut ws, _) = tokio_tungstenite::connect_async(req).await.unwrap(); + assert!(matches!(next(&mut ws).await, Event::Json(ServerMessage::Hello { .. }))); + + // The CLI signs everyone out behind the server's back; a new sign-in follows at once. + let mut passwd = std::process::Command::new(env!("CARGO_BIN_EXE_redshell-server")) + .args(["--config", h.dir.path().to_str().unwrap(), "user", "passwd", "me", "--password-stdin"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + use std::io::Write as _; + writeln!(passwd.stdin.take().unwrap(), "{PASSWORD}").unwrap(); + assert!(passwd.wait().unwrap().success()); + let res = h.post("/api/auth/sign-in", json!({"username": "me", "password": PASSWORD})).send().await.unwrap(); + let second = format!("__Host-redshell-session={}", cookie(res.headers()).unwrap()); + assert_eq!(h.http.get(h.url("/api/auth/me")).header("cookie", &first).send().await.unwrap().status(), 401); + assert_eq!(h.http.get(h.url("/api/auth/me")).header("cookie", &second).send().await.unwrap().status(), 200); + + // The socket notices at its next ping (every 30 s). + let closed = tokio::time::timeout(Duration::from_secs(40), async { + loop { + match ws.next().await { + Some(Ok(Message::Close(_)) | Err(_)) | None => break, + Some(Ok(_)) => {} + } + } + }); + closed.await.expect("the old socket stayed open"); +} + +#[tokio::test] +async fn static_pages_carry_security_headers() { + let h = Harness::start("").await; + for path in ["/", "/s/abc", "/signin", "/pair", "/settings/passkeys", "/hosts/box.lan"] { + let res = h.http.get(h.url(path)).header("accept", "text/html,*/*").send().await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "{path}"); + let headers = res.headers(); + assert_eq!(headers["x-frame-options"], "DENY"); + assert_eq!(headers["referrer-policy"], "no-referrer"); + assert_eq!(headers["x-content-type-options"], "nosniff"); + assert_eq!(headers["cache-control"], "no-cache"); + assert!(headers["content-security-policy"].to_str().unwrap().contains("script-src 'self';")); + assert!(headers["content-type"].to_str().unwrap().starts_with("text/html")); + } + assert_eq!(h.http.get(h.url("/missing.js")).send().await.unwrap().status(), StatusCode::NOT_FOUND); + let api = h.http.get(h.url("/api/nope")).send().await.unwrap(); + assert_eq!(api.status(), StatusCode::NOT_FOUND); + assert_eq!(api.json::().await.unwrap()["code"], "not_found"); +} + +#[tokio::test] +async fn slow_idle_and_surplus_connections_are_closed() { + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + use tokio::net::TcpStream; + + let limits = Limits { max_connections: 3, request_timeout: Duration::from_secs(1), ..Limits::default() }; + let h = Harness::start_tuned("listen = \"127.0.0.1:0\"", "", |c| c.limits = limits).await; + let addr = h.server.addr; + /// How long until the server closes `stream`, reading whatever it sends. + async fn closed_after(stream: &mut TcpStream) -> Duration { + let start = std::time::Instant::now(); + let mut buf = [0u8; 4096]; + loop { + match tokio::time::timeout(Duration::from_secs(5), stream.read(&mut buf)).await { + Ok(Ok(0) | Err(_)) => return start.elapsed(), + Ok(Ok(_)) => {} + Err(_) => panic!("still open after 5 s"), + } + } + } + + // Headers that never end (slowloris). + let mut slow = TcpStream::connect(addr).await.unwrap(); + slow.write_all(b"GET /api/auth/info HTTP/1.1\r\nHost: x\r\nX-Slow: ").await.unwrap(); + assert!(closed_after(&mut slow).await < Duration::from_secs(3)); + // A kept-alive connection that goes quiet after its request. + let mut idle = TcpStream::connect(addr).await.unwrap(); + idle.write_all(b"GET /api/auth/info HTTP/1.1\r\nHost: x\r\n\r\n").await.unwrap(); + assert!(closed_after(&mut idle).await < Duration::from_secs(3)); + + // Three silent connections take every place: a fourth is closed at once. + let mut silent = Vec::new(); + for _ in 0..3 { + silent.push(TcpStream::connect(addr).await.unwrap()); + } + tokio::time::sleep(Duration::from_millis(200)).await; + let mut surplus = TcpStream::connect(addr).await.unwrap(); + assert!(closed_after(&mut surplus).await < Duration::from_millis(500)); + for mut stream in silent { + closed_after(&mut stream).await; + } + let info = h.http.get(h.url("/api/auth/info")).send().await.unwrap(); + assert_eq!(info.status(), StatusCode::OK, "their places are free again"); +} + +/// A browser with a software passkey, standing in for the user's phone. +struct Browser<'a> { + h: &'a Harness, + cookie: String, + key: webauthn_authenticator_rs::softpasskey::SoftPasskey, + origin: reqwest::Url, +} + +impl Browser<'_> { + fn post(&self, path: &str, body: Value) -> reqwest::RequestBuilder { + self.h.post(path, body).header("cookie", &self.cookie) + } + + /// Registers a passkey; returns its credential id and the user handle. + async fn register(&mut self, name: &str) -> (String, String) { + use webauthn_authenticator_rs::WebauthnAuthenticator as _; + let begin: Value = + self.post("/api/account/passkeys/begin", json!({})).send().await.unwrap().json().await.unwrap(); + let mut options = begin["options"].clone(); + let selection = &mut options["publicKey"]["authenticatorSelection"]; + assert_eq!(selection["residentKey"], "required", "a discoverable passkey"); + // The software key stores no credentials of its own; the test keeps the user handle instead. + selection["requireResidentKey"] = json!(false); + selection["residentKey"] = json!("discouraged"); + let handle = options["publicKey"]["user"]["id"].as_str().unwrap().to_owned(); + let credential = + self.key.do_registration(self.origin.clone(), serde_json::from_value(options).unwrap()).unwrap(); + let credential = serde_json::to_value(credential).unwrap(); + let finish = json!({"ceremony": begin["ceremony"], "credential": credential, "name": name}); + let res = self.post("/api/account/passkeys/finish", finish).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "{}", res.text().await.unwrap()); + (credential["id"].as_str().unwrap().to_owned(), handle) + } + + /// Answers a sign-in challenge as a browser would with a discoverable passkey. + fn sign_in_answer(&mut self, begin: &Value, credential_id: &str, handle: &str) -> Value { + use webauthn_authenticator_rs::WebauthnAuthenticator as _; + let mut options = begin["options"].clone(); + assert!(options["publicKey"]["allowCredentials"].as_array().is_none_or(Vec::is_empty), "no name needed"); + options["publicKey"]["allowCredentials"] = json!([{"type": "public-key", "id": credential_id}]); + let answer = self.key.do_authentication(self.origin.clone(), serde_json::from_value(options).unwrap()).unwrap(); + let mut answer = serde_json::to_value(answer).unwrap(); + answer["response"]["userHandle"] = json!(handle); + answer + } +} + +#[tokio::test] +async fn passkeys_register_sign_in_and_can_replace_the_password() { + let h = Harness::on_localhost().await; + let info: Value = h.http.get(h.url("/api/auth/info")).send().await.unwrap().json().await.unwrap(); + assert_eq!(info["passkeys"], true); + let session = format!("__Host-redshell-session={}", h.setup().await); + let origin = format!("http://localhost:{}", h.server.addr.port()).parse().unwrap(); + let mut browser = + Browser { h: &h, cookie: session, key: webauthn_authenticator_rs::softpasskey::SoftPasskey::new(true), origin }; + let (credential_id, handle) = browser.register("Test key").await; + let list: Value = h + .http + .get(h.url("/api/account/passkeys")) + .header("cookie", &browser.cookie) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!((list[0]["name"].as_str(), list[0]["last_used_at"].is_null()), (Some("Test key"), true)); + + // Usernameless sign-in, for a desktop. + let begin: Value = h.post("/api/auth/passkey/begin", json!({})).send().await.unwrap().json().await.unwrap(); + let answer = browser.sign_in_answer(&begin, &credential_id, &handle); + let finish = json!({"ceremony": begin["ceremony"], "credential": answer, "device_name": "Desk"}); + let signed: Value = h.post("/api/auth/passkey/finish", finish.clone()).send().await.unwrap().json().await.unwrap(); + assert_eq!(signed["user"]["username"], "me"); + let token = signed["device_token"].as_str().unwrap(); + let account: Value = + h.http.get(h.url("/api/account")).bearer_auth(token).send().await.unwrap().json().await.unwrap(); + assert_eq!((account["passkeys"].as_u64(), account["passkey_only"].as_bool()), (Some(1), Some(false))); + let replay = h.post("/api/auth/passkey/finish", finish).send().await.unwrap(); + assert_eq!(replay.status(), StatusCode::UNAUTHORIZED, "a ceremony is used once"); + + // A browser gets a cookie, also after strangers started more sign-ins than the server ever held. + let begin: Value = h.post("/api/auth/passkey/begin", json!({})).send().await.unwrap().json().await.unwrap(); + for _ in 0..600 { + assert_eq!(h.post("/api/auth/passkey/begin", json!({})).send().await.unwrap().status(), StatusCode::OK); + } + let answer = browser.sign_in_answer(&begin, &credential_id, &handle); + let res = h + .post("/api/auth/passkey/finish", json!({"ceremony": begin["ceremony"], "credential": answer})) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + assert!(cookie(res.headers()).is_some()); + let list: Value = + h.http.get(h.url("/api/account/passkeys")).bearer_auth(token).send().await.unwrap().json().await.unwrap(); + assert!(list[0]["last_used_at"].is_i64()); + let id = list[0]["id"].as_i64().unwrap(); + + // Passkey-only: the right password is refused with a reason, the last passkey stays. + let only = |enabled: bool| { + h.http.put(h.url("/api/account/passkey-only")).bearer_auth(token).json(&json!({"enabled": enabled})).send() + }; + let account: Value = only(true).await.unwrap().json().await.unwrap(); + assert_eq!(account["passkey_only"], true); + let password = h.post("/api/auth/sign-in", json!({"username": "me", "password": PASSWORD})).send().await.unwrap(); + assert_eq!(password.status(), StatusCode::FORBIDDEN); + assert_eq!(password.json::().await.unwrap()["code"], "passkey_required"); + let wrong = + h.post("/api/auth/sign-in", json!({"username": "me", "password": "not the password"})).send().await.unwrap(); + assert_eq!(wrong.json::().await.unwrap()["code"], "invalid_credentials", "strangers learn nothing"); + let revoke = || h.http.delete(h.url(&format!("/api/account/passkeys/{id}"))).bearer_auth(token).send(); + assert_eq!(revoke().await.unwrap().status(), StatusCode::CONFLICT); + let renamed = h + .http + .patch(h.url(&format!("/api/account/passkeys/{id}"))) + .bearer_auth(token) + .json(&json!({"name": "Phone"})) + .send() + .await + .unwrap(); + assert_eq!(renamed.json::().await.unwrap()["name"], "Phone"); + + // The CLI gives a user who lost their passkeys their password back. + let status = std::process::Command::new(env!("CARGO_BIN_EXE_redshell-server")) + .args(["--config", h.dir.path().to_str().unwrap(), "user", "reset-passkeys", "me"]) + .output() + .unwrap(); + assert!(status.status.success(), "{status:?}"); + let password = h.post("/api/auth/sign-in", json!({"username": "me", "password": PASSWORD})).send().await.unwrap(); + assert_eq!(password.status(), StatusCode::OK); + assert_eq!(revoke().await.unwrap().status(), StatusCode::NOT_FOUND, "already gone"); + assert_eq!(only(true).await.unwrap().status(), StatusCode::CONFLICT, "needs a passkey"); +} + +/// Makes every sign-in's last re-authentication too old to count. +fn expire_reauth(h: &Harness) { + let db = rusqlite::Connection::open(h.dir.path().join("server.sqlite3")).unwrap(); + db.execute_batch("UPDATE browser_sessions SET reauth_at = 0; UPDATE devices SET reauth_at = 0;").unwrap(); +} + +#[tokio::test] +async fn account_takeover_steps_need_a_recent_reauthentication() { + let h = Harness::on_localhost().await; + let session = format!("__Host-redshell-session={}", h.setup().await); + let origin = format!("http://localhost:{}", h.server.addr.port()).parse().unwrap(); + let mut browser = + Browser { h: &h, cookie: session, key: webauthn_authenticator_rs::softpasskey::SoftPasskey::new(true), origin }; + browser.register("Test key").await; + let call = |method: reqwest::Method, path: &str, body: Value| { + h.http + .request(method, h.url(path)) + .header("cookie", &browser.cookie) + .header("origin", h.origin()) + .json(&body) + .send() + }; + let account = || async { + let res = call(reqwest::Method::GET, "/api/account", json!(null)).await.unwrap(); + res.json::().await.unwrap() + }; + let refused = |res: reqwest::Response| async move { + assert_eq!(res.status(), StatusCode::FORBIDDEN); + assert_eq!(res.json::().await.unwrap()["code"], "reauth_required"); + }; + assert!(account().await["reauth_expires_at"].is_i64(), "signing in counts"); + + expire_reauth(&h); + assert!(account().await.get("reauth_expires_at").is_none()); + let device = h.device_token().await; + let devices: Value = + h.http.get(h.url("/api/account/devices")).bearer_auth(&device).send().await.unwrap().json().await.unwrap(); + let device_id = devices[0]["id"].as_i64().unwrap(); + let passkeys: Value = + call(reqwest::Method::GET, "/api/account/passkeys", json!(null)).await.unwrap().json().await.unwrap(); + let passkey_id = passkeys[0]["id"].as_i64().unwrap(); + let started: Value = + h.post("/api/pair", json!({"device_name": "Desk"})).send().await.unwrap().json().await.unwrap(); + let code = started["code"].as_str().unwrap(); + + refused(call(reqwest::Method::POST, "/api/account/passkeys/begin", json!({})).await.unwrap()).await; + refused(call(reqwest::Method::PUT, "/api/account/passkey-only", json!({"enabled": true})).await.unwrap()).await; + refused(call(reqwest::Method::DELETE, &format!("/api/account/passkeys/{passkey_id}"), json!(null)).await.unwrap()) + .await; + refused(call(reqwest::Method::DELETE, &format!("/api/account/devices/{device_id}"), json!(null)).await.unwrap()) + .await; + refused(call(reqwest::Method::POST, &format!("/api/pair/{code}/approve"), json!({})).await.unwrap()).await; + let shown = call(reqwest::Method::GET, &format!("/api/pair/{code}"), json!(null)).await.unwrap(); + assert_eq!(shown.status(), StatusCode::OK, "looking needs nothing more"); + + // The password again. + let wrong = call(reqwest::Method::POST, "/api/auth/reauth", json!({"method": "password", "password": "nope"})); + assert_eq!(wrong.await.unwrap().json::().await.unwrap()["code"], "invalid_credentials"); + let right = call(reqwest::Method::POST, "/api/auth/reauth", json!({"method": "password", "password": PASSWORD})); + let right: Value = right.await.unwrap().json().await.unwrap(); + assert!(right["reauth_expires_at"].as_i64().unwrap() > 0); + let revoked = call(reqwest::Method::DELETE, &format!("/api/account/devices/{device_id}"), json!(null)); + assert_eq!(revoked.await.unwrap().status(), StatusCode::OK); + + // Or a passkey. + expire_reauth(&h); + let begin: Value = + call(reqwest::Method::POST, "/api/auth/reauth/passkey/begin", json!({})).await.unwrap().json().await.unwrap(); + let answer = { + use webauthn_authenticator_rs::WebauthnAuthenticator as _; + let options = serde_json::from_value(begin["options"].clone()).unwrap(); + serde_json::to_value(browser.key.do_authentication(browser.origin.clone(), options).unwrap()).unwrap() + }; + let reauth = json!({"method": "passkey", "ceremony": begin["ceremony"], "credential": answer}); + let res = call(reqwest::Method::POST, "/api/auth/reauth", reauth.clone()).await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "{}", res.text().await.unwrap()); + let replay = call(reqwest::Method::POST, "/api/auth/reauth", reauth).await.unwrap(); + assert_eq!(replay.status(), StatusCode::UNAUTHORIZED, "a ceremony is used once"); + let approved = call(reqwest::Method::POST, &format!("/api/pair/{code}/approve"), json!({})).await.unwrap(); + assert_eq!(approved.status(), StatusCode::OK); + + // A paired device has proved nothing itself. + let url = h.url(&format!("/api/pair/{}", started["id"].as_str().unwrap())); + let collected: Value = h + .http + .get(url) + .bearer_auth(started["poll_secret"].as_str().unwrap()) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let paired = collected["device_token"].as_str().unwrap(); + let res = h.http.post(h.url("/api/account/passkeys/begin")).bearer_auth(paired).json(&json!({})).send().await; + refused(res.unwrap()).await; + + // Passkey-only: the password no longer re-authenticates. + let only = call(reqwest::Method::PUT, "/api/account/passkey-only", json!({"enabled": true})).await.unwrap(); + assert_eq!(only.status(), StatusCode::OK); + let me = h.http.get(h.url("/api/auth/me")).bearer_auth(paired).send().await.unwrap(); + assert_eq!(me.status(), StatusCode::UNAUTHORIZED, "paired from a password sign-in, so it ended"); + let password = call(reqwest::Method::POST, "/api/auth/reauth", json!({"method": "password", "password": PASSWORD})); + assert_eq!(password.await.unwrap().json::().await.unwrap()["code"], "passkey_required"); +} + +#[tokio::test] +async fn passkeys_need_a_secure_public_url() { + let h = Harness::start("").await; + let info: Value = h.http.get(h.url("/api/auth/info")).send().await.unwrap().json().await.unwrap(); + assert_eq!(info["passkeys"], false); + let res = h.post("/api/auth/passkey/begin", json!({})).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE); + let body: Value = res.json().await.unwrap(); + assert_eq!(body["code"], "unavailable"); + assert!(body["message"].as_str().unwrap().contains("public_url")); +} + +#[tokio::test] +async fn desktops_pair_with_a_code_typed_in_a_signed_in_browser() { + let h = Harness::start("").await; + let cookie = format!("__Host-redshell-session={}", h.setup().await); + let pair = |name: &str| h.post("/api/pair", json!({"device_name": name, "platform": "Linux"})).send(); + let started: Value = pair("Work laptop").await.unwrap().json().await.unwrap(); + let (id, code, secret) = (&started["id"], started["code"].as_str().unwrap(), &started["poll_secret"]); + assert_eq!(started["url"], format!("{}/pair", h.origin())); + let poll = + |secret: &str| h.http.get(h.url(&format!("/api/pair/{}", id.as_str().unwrap()))).bearer_auth(secret).send(); + let status: Value = poll(secret.as_str().unwrap()).await.unwrap().json().await.unwrap(); + assert_eq!(status["state"], "pending", "polled before approval"); + assert_eq!(poll("wrong secret").await.unwrap().status(), StatusCode::NOT_FOUND); + + // The browser: the code needs a sign-in, comes only in the path, and a wrong one is not found. + let browser = |method: reqwest::Method, path: &str| { + h.http.request(method, h.url(path)).header("cookie", &cookie).header("origin", h.origin()) + }; + let anonymous = h.http.get(h.url(&format!("/api/pair/{code}"))).send().await.unwrap(); + assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED); + let wrong = browser(reqwest::Method::GET, "/api/pair/ZZZ-ZZZ").send().await.unwrap(); + assert_eq!(wrong.status(), StatusCode::NOT_FOUND); + let info: Value = browser(reqwest::Method::GET, &format!("/api/pair/{}", code.to_lowercase())) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!((info["device_name"].as_str(), info["platform"].as_str()), (Some("Work laptop"), Some("Linux"))); + assert_eq!(info["same_address"], true, "both on this machine"); + let from_link = + browser(reqwest::Method::POST, &format!("/api/pair/{code}/approve?code={code}")).send().await.unwrap(); + assert_eq!(from_link.status(), StatusCode::BAD_REQUEST, "a code in a link is not accepted"); + let cross_site = h.http.post(h.url(&format!("/api/pair/{code}/approve"))).header("cookie", &cookie); + let cross_site = cross_site.header("origin", "https://evil.example").send().await.unwrap(); + assert_eq!(cross_site.status(), StatusCode::FORBIDDEN); + let approved = browser(reqwest::Method::POST, &format!("/api/pair/{code}/approve")).send().await.unwrap(); + assert_eq!(approved.status(), StatusCode::OK); + let again = browser(reqwest::Method::POST, &format!("/api/pair/{code}/reject")).send().await.unwrap(); + assert_eq!(again.status(), StatusCode::CONFLICT); + + // The device collects its token once. + let status: Value = poll(secret.as_str().unwrap()).await.unwrap().json().await.unwrap(); + assert_eq!((status["state"].as_str(), status["user"]["username"].as_str()), (Some("approved"), Some("me"))); + let token = status["device_token"].as_str().unwrap(); + let devices: Value = + h.http.get(h.url("/api/account/devices")).bearer_auth(token).send().await.unwrap().json().await.unwrap(); + assert_eq!(devices[0]["name"], "Work laptop"); + assert_eq!(poll(secret.as_str().unwrap()).await.unwrap().status(), StatusCode::NOT_FOUND, "only once"); + + // A rejected request tells the device so. + let started: Value = pair("Stranger").await.unwrap().json().await.unwrap(); + let code = started["code"].as_str().unwrap(); + browser(reqwest::Method::POST, &format!("/api/pair/{code}/reject")).send().await.unwrap(); + let url = h.url(&format!("/api/pair/{}", started["id"].as_str().unwrap())); + let status: Value = h + .http + .get(url) + .bearer_auth(started["poll_secret"].as_str().unwrap()) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(status["state"], "rejected"); + + // An approval lasts only as long as the sign-in that gave it. + let started: Value = pair("Late").await.unwrap().json().await.unwrap(); + let code = started["code"].as_str().unwrap(); + let approved = browser(reqwest::Method::POST, &format!("/api/pair/{code}/approve")).send().await.unwrap(); + assert_eq!(approved.status(), StatusCode::OK); + browser(reqwest::Method::POST, "/api/auth/sign-out").send().await.unwrap(); + let url = h.url(&format!("/api/pair/{}", started["id"].as_str().unwrap())); + let status: Value = h + .http + .get(url) + .bearer_auth(started["poll_secret"].as_str().unwrap()) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(status["state"], "rejected", "the approving browser signed out before the device collected"); +} + +#[tokio::test] +async fn browsers_subscribe_to_push_and_choose_events() { + let h = Harness::start("").await; + let cookie = format!("__Host-redshell-session={}", h.setup().await); + let key: Value = + h.http.get(h.url("/api/push/key")).header("cookie", &cookie).send().await.unwrap().json().await.unwrap(); + assert_eq!(key["vapid_public_key"].as_str().unwrap().len(), 87, "an uncompressed P-256 point"); + let call = |method: reqwest::Method, path: &str, body: Value| { + h.http.request(method, h.url(path)).header("cookie", &cookie).header("origin", h.origin()).json(&body).send() + }; + // A browser's subscription, never posted to here: .invalid names resolve nowhere. + let endpoint = "https://push.example.invalid/send/abc"; + let p256dh = "BLn9b-VR0ca83knDNZ32dCHGyjJp-1riX9ZTN40MqV8K_LpQmLqxC_DoHvqvFXO_nGdAB4W9dogZb_sM-uV4JbY"; + let subscription = |endpoint: &str| json!({"endpoint": endpoint, "expirationTime": null, "keys": {"p256dh": p256dh, "auth": "_ordMnz7uTCmrpBTeUV4Bw"}}); + let res = call(reqwest::Method::POST, "/api/push/subscriptions", subscription(endpoint)).await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "{}", res.text().await.unwrap()); + let private = + call(reqwest::Method::POST, "/api/push/subscriptions", subscription("https://10.0.0.1/x")).await.unwrap(); + assert_eq!(private.status(), StatusCode::BAD_REQUEST); + let plain = call(reqwest::Method::POST, "/api/push/subscriptions", subscription("http://push.example.com/x")) + .await + .unwrap(); + assert_eq!(plain.status(), StatusCode::BAD_REQUEST); + let token = h.device_token().await; + let device = h + .http + .post(h.url("/api/push/subscriptions")) + .bearer_auth(&token) + .json(&subscription(endpoint)) + .send() + .await + .unwrap(); + assert_eq!(device.status(), StatusCode::BAD_REQUEST, "for browsers only"); + + let list: Value = + call(reqwest::Method::GET, "/api/push/subscriptions", json!(null)).await.unwrap().json().await.unwrap(); + assert_eq!((list[0]["endpoint"].as_str(), list[0]["current"].as_bool()), (Some(endpoint), Some(true))); + assert_eq!(list[0]["events"].as_array().unwrap().len(), 5, "everything by default"); + let events = json!({"endpoint": endpoint, "events": ["approval_requested", "failed"]}); + assert_eq!(call(reqwest::Method::PUT, "/api/push/subscriptions", events).await.unwrap().status(), StatusCode::OK); + let list: Value = + call(reqwest::Method::GET, "/api/push/subscriptions", json!(null)).await.unwrap().json().await.unwrap(); + assert_eq!(list[0]["events"], json!(["approval_requested", "failed"])); + + let gone = json!({"endpoint": endpoint}); + assert_eq!( + call(reqwest::Method::DELETE, "/api/push/subscriptions", gone.clone()).await.unwrap().status(), + StatusCode::OK + ); + assert_eq!( + call(reqwest::Method::DELETE, "/api/push/subscriptions", gone).await.unwrap().status(), + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn hosts_are_saved_in_the_config_and_offered_at_once() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + let hosts = || h.http.get(h.url("/api/hosts")).bearer_auth(&token).send(); + let send = |method: reqwest::Method, path: &str, body: Value| { + h.http.request(method, h.url(path)).bearer_auth(&token).json(&body).send() + }; + let profiles = || async { + let list: Vec = + h.http.get(h.url("/api/profiles")).bearer_auth(&token).send().await.unwrap().json().await.unwrap(); + list.into_iter().filter_map(|p| p["id"].as_str().map(str::to_owned)).collect::>() + }; + + let host = json!({"name": "box", "host": "box.lan", "port": 2222, "group": "lab", "origin": "redshell"}); + let created = send(reqwest::Method::POST, "/api/hosts", host.clone()).await.unwrap(); + assert_eq!(created.status(), StatusCode::CREATED); + assert!(profiles().await.contains(&"ssh:box".to_owned()), "offered without a restart"); + let listed: Value = hosts().await.unwrap().json().await.unwrap(); + assert_eq!((listed[0]["name"].as_str(), listed[0]["origin"].as_str()), (Some("box"), Some("redshell"))); + let config = std::fs::read_to_string(h.dir.path().join("config.toml")).unwrap(); + assert!(config.starts_with("[server]\n") && config.contains("[[ssh.hosts]]\nname = \"box\""), "{config}"); + + let taken = send(reqwest::Method::POST, "/api/hosts", host).await.unwrap(); + assert_eq!(taken.status(), StatusCode::CONFLICT); + let dash = send(reqwest::Method::POST, "/api/hosts", json!({"name": "x", "host": "-oProxyCommand=sh"})).await; + assert_eq!(dash.unwrap().status(), StatusCode::BAD_REQUEST); + let secret = json!({"name": "pw", "host": "pw.lan", "password": "hunter2"}); + assert!(send(reqwest::Method::POST, "/api/hosts", secret).await.unwrap().status().is_client_error()); + + let renamed = send(reqwest::Method::PUT, "/api/hosts/box", json!({"name": "pi", "host": "pi.lan"})).await.unwrap(); + assert_eq!(renamed.status(), StatusCode::OK); + assert!(profiles().await.contains(&"ssh:pi".to_owned())); + assert!(!profiles().await.contains(&"ssh:box".to_owned())); + let gone = h.http.delete(h.url("/api/hosts/pi")).bearer_auth(&token).send().await.unwrap(); + assert_eq!(gone.status(), StatusCode::OK); + let missing = h.http.delete(h.url("/api/hosts/pi")).bearer_auth(&token).send().await.unwrap(); + assert_eq!(missing.status(), StatusCode::NOT_FOUND); + assert_eq!(hosts().await.unwrap().json::().await.unwrap(), json!([])); +} + +#[tokio::test] +async fn folders_list_subfolders_only() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + let root = tempfile::tempdir().unwrap(); + for folder in ["b", "A"] { + std::fs::create_dir(root.path().join(folder)).unwrap(); + } + std::fs::write(root.path().join("file.txt"), "x").unwrap(); + let list = |path: String| h.http.get(h.url("/api/fs/folders")).query(&[("path", path)]).bearer_auth(&token).send(); + let listing: Value = list(root.path().display().to_string()).await.unwrap().json().await.unwrap(); + assert_eq!(listing["folders"], json!(["A", "b"])); + assert_eq!(listing["truncated"], false); + assert_eq!(list("relative".into()).await.unwrap().status(), StatusCode::BAD_REQUEST); + let missing = root.path().join("missing").display().to_string(); + assert_eq!(list(missing).await.unwrap().status(), StatusCode::BAD_REQUEST); +} + +#[cfg(unix)] +#[tokio::test] +async fn sessions_stream_to_late_joiners_and_follow_the_typist() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + let script = "printf hi; read line; echo \"got:$line\"; sleep 5"; + let session = h.create(&token, json!({"command": ["sh", "-c", script], "cols": 80, "rows": 24})).await; + assert_eq!(session.kind, redshell_protocol::SessionKind::Command); + + let mut first = h.ws(&token).await; + send(&mut first, ClientMessage::Attach { session: session.id.clone(), cols: 80, rows: 24 }).await; + let mut out1 = Vec::new(); + let (channel, data) = until(&mut first, &mut out1, |e, _| match e { + Event::Json(ServerMessage::Attached { channel, snapshot, .. }) => Some((*channel, snapshot.data.clone())), + _ => None, + }) + .await; + out1.extend_from_slice(data.as_bytes()); + output_with(&mut first, &mut out1, "hi").await; + + // A late joiner gets the screen as a snapshot. + let mut second = h.ws(&token).await; + send(&mut second, ClientMessage::Attach { session: session.id.clone(), cols: 100, rows: 30 }).await; + let mut out2 = Vec::new(); + let (channel2, snapshot) = until(&mut second, &mut out2, |e, _| match e { + Event::Json(ServerMessage::Attached { channel, snapshot, session }) => { + Some((*channel, (snapshot.clone(), session.cols))) + } + _ => None, + }) + .await; + assert!(snapshot.0.data.contains("hi"), "{:?}", snapshot.0.data); + assert_eq!((snapshot.0.cols, snapshot.1), (80, 80), "the first client still sizes it"); + + // Typing from the second client sizes the session to it; both see the output. + second.send(Message::binary(frame(channel2, b"abc\r"))).await.unwrap(); + until(&mut first, &mut out1, |e, _| { + matches!(e, Event::Json(ServerMessage::Resized { cols: 100, rows: 30, .. })).then_some(()) + }) + .await; + output_with(&mut first, &mut out1, "got:abc").await; + output_with(&mut second, &mut out2, "got:abc").await; + let list: Vec = + h.http.get(h.url("/api/sessions")).bearer_auth(&token).send().await.unwrap().json().await.unwrap(); + assert_eq!((list[0].cols, list[0].rows), (100, 30)); + + // The first client resizes; it does not own the size, so nothing changes. + send(&mut first, ClientMessage::Resize { channel, cols: 60, rows: 20 }).await; + send(&mut first, ClientMessage::Input { channel, data: String::new() }).await; + until(&mut second, &mut out2, |e, _| { + matches!(e, Event::Json(ServerMessage::Resized { cols: 60, rows: 20, .. })).then_some(()) + }) + .await; + + let killed = + h.http.delete(h.url(&format!("/api/sessions/{}", session.id))).bearer_auth(&token).send().await.unwrap(); + assert_eq!(killed.status(), StatusCode::OK); + until(&mut first, &mut out1, |e, _| matches!(e, Event::Json(ServerMessage::Detached { .. })).then_some(())).await; + let list: Vec = + h.http.get(h.url("/api/sessions")).bearer_auth(&token).send().await.unwrap().json().await.unwrap(); + assert!(list.is_empty()); +} + +/// Reads until `needle` shows in the output or in a snapshot; returns +/// whether a snapshot (a resync) came on the way. +async fn seen_with_resync(ws: &mut Ws, needle: &str) -> bool { + let mut out = Vec::new(); + let mut resynced = false; + until(ws, &mut out, |e, out| { + if let Event::Json(ServerMessage::Snapshot { snapshot, .. }) = e { + resynced = true; + if snapshot.data.contains(needle) { + return Some(()); + } + } + contains(&out[out.len().saturating_sub(64 * 1024)..], needle).then_some(()) + }) + .await; + resynced +} + +#[cfg(unix)] +#[tokio::test] +async fn a_slow_client_blocks_nobody_and_resyncs() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + let flood = "read go; head -c 40000000 /dev/zero | tr '\\0' x; echo; echo END-MARK; sleep 10"; + let session = h.create(&token, json!({"command": ["sh", "-c", flood]})).await; + let attach = ClientMessage::Attach { session: session.id.clone(), cols: 80, rows: 24 }; + let mut slow = h.ws(&token).await; + send(&mut slow, attach.clone()).await; + let mut fast = h.ws(&token).await; + send(&mut fast, attach).await; + let mut out = Vec::new(); + let channel = until(&mut fast, &mut out, |e, _| match e { + Event::Json(ServerMessage::Attached { channel, .. }) => Some(*channel), + _ => None, + }) + .await; + send(&mut fast, ClientMessage::Input { channel, data: "\r".into() }).await; + // The other client keeps up while `slow` reads nothing at all. + tokio::time::timeout(Duration::from_secs(60), seen_with_resync(&mut fast, "END-MARK")).await.unwrap(); + assert!(seen_with_resync(&mut slow, "END-MARK").await, "the slow client was resynced"); +} + +#[cfg(unix)] +#[tokio::test] +async fn sizes_are_clamped_and_unread_input_is_bounded() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + let tiny = h.create(&token, json!({"command": ["sleep", "30"], "cols": 0, "rows": 0})).await; + assert_eq!((tiny.cols, tiny.rows), (2, 1)); + let huge = h.create(&token, json!({"command": ["sleep", "30"], "cols": 65535, "rows": 65535})).await; + assert_eq!((huge.cols, huge.rows), (1000, 500)); + + // `sleep` reads nothing: once 4 MiB wait, more input is refused with an error. + let mut ws = h.ws(&token).await; + send(&mut ws, ClientMessage::Attach { session: tiny.id.clone(), cols: 80, rows: 24 }).await; + let mut out = Vec::new(); + let channel = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::Attached { channel, .. }) => Some(*channel), + _ => None, + }) + .await; + let chunk = vec![b'x'; 1000 << 10]; + for _ in 0..6 { + ws.send(Message::binary(frame(channel, &chunk))).await.unwrap(); + } + let refused = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::Error { code, message }) => Some((*code, message.clone())), + _ => None, + }) + .await; + assert_eq!(refused.0, redshell_protocol::ErrorCode::Conflict, "{}", refused.1); + for session in [&tiny, &huge] { + h.http.delete(h.url(&format!("/api/sessions/{}", session.id))).bearer_auth(&token).send().await.unwrap(); + } +} + +#[cfg(unix)] +#[tokio::test] +async fn sessions_outlive_clients_and_report_exit() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + let mut ws = h.ws(&token).await; + send(&mut ws, ClientMessage::Subscribe { sessions: true, events: true }).await; + let session = h.create(&token, json!({"command": ["sh", "-c", "printf 'done\\a'; exit 3"], "name": "job"})).await; + let mut out = Vec::new(); + let exited = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::SessionUpdated { session: s }) if s.id == session.id && s.exit.is_some() => { + Some(s.clone()) + } + _ => None, + }) + .await; + assert_eq!(exited.exit.unwrap().code, Some(3)); + assert_eq!(exited.name.as_deref(), Some("job")); + drop(ws); + // Still listed, with its final screen, until killed. + let mut late = h.ws(&token).await; + send(&mut late, ClientMessage::Attach { session: session.id.clone(), cols: 80, rows: 24 }).await; + let data = until(&mut late, &mut out, |e, _| match e { + Event::Json(ServerMessage::Attached { snapshot, .. }) => Some(snapshot.data.clone()), + _ => None, + }) + .await; + assert!(data.contains("done")); +} + +#[cfg(unix)] +#[tokio::test] +async fn leaving_the_alt_screen_resyncs_clients_that_joined_on_it() { + let h = Harness::start("").await; + h.setup().await; + let token = h.device_token().await; + let script = "echo normal-line; printf '\\033[?1049hfull-screen'; read go; printf '\\033[?1049l'; sleep 10"; + let session = h.create(&token, json!({"command": ["sh", "-c", script]})).await; + screen_with(&h, &token, &session.id, "full-screen").await; + + let mut ws = h.ws(&token).await; + send(&mut ws, ClientMessage::Attach { session: session.id.clone(), cols: 80, rows: 24 }).await; + let mut out = Vec::new(); + let (channel, attached) = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::Attached { channel, snapshot, .. }) => Some((*channel, snapshot.clone())), + _ => None, + }) + .await; + assert!(attached.modes.alt_screen && !attached.data.contains("normal-line")); + send(&mut ws, ClientMessage::Input { channel, data: "\r".into() }).await; + let resync = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::Snapshot { snapshot, .. }) => Some(snapshot.clone()), + _ => None, + }) + .await; + assert!(!resync.modes.alt_screen); + assert!(resync.data.contains("normal-line"), "{:?}", resync.data); +} + +/// Attaches to a session and reads until its screen shows `needle`. +#[cfg(unix)] +async fn screen_with(h: &Harness, token: &str, session: &str, needle: &str) -> String { + let mut ws = h.ws(token).await; + send(&mut ws, ClientMessage::Attach { session: session.into(), cols: 1000, rows: 24 }).await; + let mut out = Vec::new(); + until(&mut ws, &mut out, |e, out| match e { + Event::Json(ServerMessage::Attached { snapshot, .. }) if snapshot.data.contains(needle) => { + Some(snapshot.data.clone()) + } + _ => contains(out, needle).then(|| String::from_utf8_lossy(out).into_owned()), + }) + .await +} + +/// Reads until an approval is requested; its id. +async fn requested(ws: &mut Ws, out: &mut Vec) -> String { + until(ws, out, |e, _| match e { + Event::Json(ServerMessage::ApprovalRequested { approval }) => Some(approval.id.clone()), + _ => None, + }) + .await +} + +/// A fake agent: prints its arguments and hook URL, then waits. +#[cfg(unix)] +fn fake_agent(dir: &std::path::Path, name: &str) -> String { + use std::os::unix::fs::PermissionsExt as _; + let path = dir.join(name); + std::fs::write(&path, "#!/bin/sh\nprintf 'ARGS=%s URL=%s END\\n' \"$*\" \"$REDSHELL_HOOK_URL\"\nsleep 30\n") + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path.display().to_string() +} + +#[cfg(unix)] +#[tokio::test] +async fn claude_permission_requests_wait_for_a_client() { + let bin = tempfile::tempdir().unwrap(); + let claude = fake_agent(bin.path(), "claude"); + let h = Harness::start(&format!( + "[[agents.custom]]\nid = \"claude\"\nname = \"Claude Code\"\ncommand = \"{claude}\"\n" + )) + .await; + h.setup().await; + let token = h.device_token().await; + let mut ws = h.ws(&token).await; + send(&mut ws, ClientMessage::Subscribe { sessions: false, events: true }).await; + let session = h.create(&token, json!({"profile": "agent:claude"})).await; + assert_eq!(session.agent.as_deref(), Some("claude")); + + let settings_file = h.dir.path().join(format!("run/claude-{}.json", session.id)); + { + use std::os::unix::fs::PermissionsExt as _; + assert_eq!(std::fs::metadata(&settings_file).unwrap().permissions().mode() & 0o777, 0o600); + } + let settings: Value = serde_json::from_str(&std::fs::read_to_string(&settings_file).unwrap()).unwrap(); + let hook_url = settings["hooks"]["PermissionRequest"][0]["hooks"][0]["url"].as_str().unwrap().to_owned(); + assert!(hook_url.starts_with(&format!("http://{}/claude/{}/", h.server.hook_addr, session.id))); + + let request = json!({ + "session_id": "abc", "cwd": "/tmp", "hook_event_name": "PermissionRequest", "tool_name": "Bash", + "tool_input": {"command": "mkdir zz_probe", "description": "Make a folder"}, + "permission_suggestions": [{"type": "addRules", "rules": [{"toolName": "Bash", "ruleContent": "mkdir:*"}], "behavior": "allow", "destination": "localSettings"}] + }); + let http = h.http.clone(); + let (url, body) = (hook_url.clone(), request.clone()); + let held = tokio::spawn(async move { http.post(url).json(&body).send().await.unwrap().text().await.unwrap() }); + + let mut out = Vec::new(); + let approval = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::ApprovalRequested { approval }) => Some(approval.clone()), + _ => None, + }) + .await; + assert_eq!((approval.tool.as_str(), approval.summary.as_str()), ("Bash", "mkdir zz_probe")); + assert_eq!(approval.description.as_deref(), Some("Make a folder")); + assert!(approval.permission_suggestions.is_some()); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!held.is_finished(), "the hook waits for an answer"); + let decision = redshell_protocol::ApprovalDecision::Allow; + send(&mut ws, ClientMessage::Approve { approval: approval.id.clone(), decision, message: None }).await; + let reply: Value = serde_json::from_str(&held.await.unwrap()).unwrap(); + assert_eq!(reply["hookSpecificOutput"]["hookEventName"], "PermissionRequest"); + assert_eq!(reply["hookSpecificOutput"]["decision"]["behavior"], "allow"); + let answered_by = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::ApprovalResolved { answered_by, .. }) => Some(answered_by.clone()), + _ => None, + }) + .await; + assert_eq!(answered_by.as_deref(), Some("test")); + + // Answered in Claude's own dialog: the hook of that very call settles the held request with no + // decision; a parallel request and another call's hook leave it alone. + let hold = |body: Value| { + let (http, url) = (h.http.clone(), hook_url.clone()); + tokio::spawn(async move { http.post(url).json(&body).send().await.unwrap().text().await.unwrap() }) + }; + let first = hold(request.clone()); + let first_id = requested(&mut ws, &mut out).await; + let mut parallel = request.clone(); + parallel["tool_input"] = json!({"command": "ls", "description": "List"}); + let second = hold(parallel); + let second_id = requested(&mut ws, &mut out).await; + let post_tool = |tool_input: Value| json!({"hook_event_name": "PostToolUse", "tool_name": "Bash", "tool_input": tool_input, "tool_response": {}}); + let other_call = post_tool(json!({"command": "pwd"})); + assert_eq!(h.http.post(&hook_url).json(&other_call).send().await.unwrap().status(), StatusCode::OK); + // The same input with its keys in another order. + let this_call = post_tool(json!({"description": "Make a folder", "command": "mkdir zz_probe"})); + assert_eq!(h.http.post(&hook_url).json(&this_call).send().await.unwrap().status(), StatusCode::OK); + assert_eq!(first.await.unwrap(), "", "no decision: Claude keeps its own answer"); + let (id, by) = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::ApprovalResolved { id, answered_by, .. }) => Some((id.clone(), answered_by.clone())), + _ => None, + }) + .await; + assert_eq!((id, by.as_deref()), (first_id, Some("terminal"))); + assert!(!second.is_finished(), "the parallel request still waits"); + + let stop = json!({"hook_event_name": "Stop", "last_assistant_message": "All done."}); + h.http.post(&hook_url).json(&stop).send().await.unwrap(); + assert_eq!(second.await.unwrap(), "", "Stop settles every request"); + let id = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::ApprovalResolved { id, .. }) => Some(id.clone()), + _ => None, + }) + .await; + assert_eq!(id, second_id); + let finished = until(&mut ws, &mut out, |e, _| match e { + Event::Json(ServerMessage::Event { event }) if event.kind == redshell_protocol::EventKind::Finished => { + Some(event.clone()) + } + _ => None, + }) + .await; + assert_eq!(finished.body.as_deref(), Some("All done.")); + + // A wrong token, and the public port, know nothing of hooks. + let wrong = hook_url.rsplit_once('/').unwrap().0.to_owned() + "/wrong-token"; + assert_eq!(h.http.post(&wrong).json(&stop).send().await.unwrap().status(), StatusCode::NOT_FOUND); + let unread = h.http.post(&wrong).header("content-type", "application/json").body("not json").send().await; + assert_eq!(unread.unwrap().status(), StatusCode::NOT_FOUND, "the token is checked before the body is read"); + let huge = json!({"hook_event_name": "Notification", "message": "x".repeat(1 << 20)}); + assert_eq!(h.http.post(&hook_url).json(&huge).send().await.unwrap().status(), StatusCode::PAYLOAD_TOO_LARGE); + let path = hook_url.split_once(&h.server.hook_addr.to_string()).unwrap().1; + let public = h.http.post(h.url(path)).json(&request).send().await.unwrap(); + assert_eq!(public.status(), StatusCode::METHOD_NOT_ALLOWED); + + // Killing the session removes its settings file. + h.http.delete(h.url(&format!("/api/sessions/{}", session.id))).bearer_auth(&token).send().await.unwrap(); + assert!(!settings_file.exists()); +} + +#[cfg(unix)] +#[tokio::test] +async fn codex_turns_finish_through_notify() { + let bin = tempfile::tempdir().unwrap(); + let codex = fake_agent(bin.path(), "codex"); + let h = + Harness::start(&format!("[[agents.custom]]\nid = \"codex\"\nname = \"Codex\"\ncommand = \"{codex}\"\n")).await; + h.setup().await; + let token = h.device_token().await; + let session = h.create(&token, json!({"profile": "agent:codex", "cols": 1000})).await; + let screen = screen_with(&h, &token, &session.id, " END").await; + let line = screen.lines().find(|l| l.contains(" END")).unwrap(); + assert!(line.contains("ARGS=-c notify=["), "{line}"); + assert!(line.contains("\"hook\",\"codex\"]"), "{line}"); + let url = line.split("URL=").nth(1).unwrap().split(' ').next().unwrap(); + assert!(url.starts_with(&format!("http://{}/codex/{}/", h.server.hook_addr, session.id))); + + let payload = json!({"type": "agent-turn-complete", "last-assistant-message": "Patched it.", "thread-id": "t"}); + // The user's own notify program, which ours replaces on Codex's command line and runs in turn. + let codex_home = tempfile::tempdir().unwrap(); + let ran = codex_home.path().join("ran"); + let notify = format!("notify = [\"sh\", \"-c\", \"printf %s \\\"$1\\\" > '{}'\", \"notify\"]\n", ran.display()); + std::fs::write(codex_home.path().join("config.toml"), notify).unwrap(); + // As Codex runs it: the notify program with the payload appended. + let (url, payload, home) = (url.to_owned(), payload.to_string(), codex_home.path().to_owned()); + let sent = payload.clone(); + let status = tokio::task::spawn_blocking(move || { + std::process::Command::new(env!("CARGO_BIN_EXE_redshell-server")) + .args(["hook", "codex", &sent]) + .env(redshell_server::HOOK_URL_ENV, url) + .env("CODEX_HOME", home) + .status() + .unwrap() + }) + .await + .unwrap(); + assert!(status.success()); + assert_eq!(std::fs::read_to_string(&ran).unwrap(), payload, "the user's notify ran with the payload"); + let list: Vec = + h.http.get(h.url("/api/sessions")).bearer_auth(&token).send().await.unwrap().json().await.unwrap(); + assert_eq!(list[0].agent_state, Some(redshell_protocol::AgentState::Finished)); + assert_eq!(list[0].last_message.as_deref(), Some("Patched it.")); +} diff --git a/crates/redshell-terminal/src/engine.rs b/crates/redshell-terminal/src/engine.rs index ffddc30..2232daa 100644 --- a/crates/redshell-terminal/src/engine.rs +++ b/crates/redshell-terminal/src/engine.rs @@ -23,6 +23,7 @@ use crate::input::{InputModes, encode_paste}; use crate::links::{self, Link}; use crate::mouse::{MouseProtocol, MouseReport}; use crate::output::{OutputParser, Parsed, prompt_lines, row_text}; +use crate::replay::{Replay, build_replay}; use crate::search::{self, SearchDirection, SearchQuery, SearchStatus}; use crate::snapshot::{Snapshot, SnapshotOptions, build_snapshot}; @@ -100,21 +101,49 @@ type SharedWriter = Arc>>>; pub trait ExternalIo: Send + Sync + 'static { /// Input for the program (keys, pastes, mouse reports). fn write(&self, bytes: &[u8]); - /// The view changed the grid size. + /// The view changed the grid size; when [`Self::sizes_grid`], the size + /// the view would like. fn resize(&self, _size: GridSize) {} /// The terminal was killed or dropped; stop feeding it. fn close(&self) {} + /// Whether the far end decides the grid's size (a session shared with + /// other clients), through [`ExternalFeed::resize`] and + /// [`ExternalFeed::reset`]. The view's size then only reaches + /// [`Self::resize`] as a wish, and the grid keeps the far end's size. + fn sizes_grid(&self) -> bool { + false + } +} + +/// What goes into an external terminal, in order. +enum Feed { + Output(Vec), + Resize(u16, u16), + Reset(u16, u16), } /// Delivers program output to an external terminal. The terminal exits /// once every clone has been dropped. #[derive(Clone)] -pub struct ExternalFeed(Sender>); +pub struct ExternalFeed(Sender); impl ExternalFeed { /// Returns `false` once the terminal is gone. pub fn feed(&self, bytes: &[u8]) -> bool { - bytes.is_empty() || self.0.send(bytes.to_vec()).is_ok() + bytes.is_empty() || self.0.send(Feed::Output(bytes.to_vec())).is_ok() + } + + /// The far end took `cols` × `rows`: the grid follows, after the output + /// fed so far. + pub fn resize(&self, cols: u16, rows: u16) -> bool { + self.0.send(Feed::Resize(cols, rows)).is_ok() + } + + /// Starts over after the output fed so far: a reset terminal of `cols` + /// × `rows` with no scrollback, ready for a redraw of the far end's + /// screen (fed next). + pub fn reset(&self, cols: u16, rows: u16) -> bool { + self.0.send(Feed::Reset(cols, rows)).is_ok() } } @@ -131,32 +160,6 @@ impl Write for ExternalWriter { } } -/// A blocking reader over the chunks sent through an [`ExternalFeed`], so -/// external terminals share the PTY I/O loop. -struct ChannelReader { - rx: Receiver>, - chunk: Vec, - pos: usize, -} - -impl Read for ChannelReader { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - if self.pos >= self.chunk.len() { - match self.rx.recv() { - Ok(chunk) => { - self.chunk = chunk; - self.pos = 0; - } - Err(_) => return Ok(0), - } - } - let n = buf.len().min(self.chunk.len() - self.pos); - buf[..n].copy_from_slice(&self.chunk[self.pos..self.pos + n]); - self.pos += n; - Ok(n) - } -} - /// State shared between the UI handle, the VT listener and the I/O thread. struct Shared { writer: SharedWriter, @@ -172,6 +175,8 @@ struct Shared { /// Answer terminal queries (DA, colour and size reports). Off for /// external terminals whose far end (tmux) answers them itself. answers_queries: AtomicBool, + /// Window title (OSC 0/2), which alacritty keeps to itself. + title: RwLock>, } impl Shared { @@ -211,12 +216,15 @@ impl EventListener for Listener { VtEvent::PtyWrite(text) => shared.reply(text.as_bytes()), VtEvent::Title(title) => { shared.observe(|o| o.on_title(&title)); + *shared.title.write() = Some(title.clone()); let _ = shared.events.send(TerminalEvent::Title(title)); } VtEvent::ResetTitle => { + *shared.title.write() = None; let _ = shared.events.send(TerminalEvent::ResetTitle); } VtEvent::Bell => { + shared.observe(|o| o.on_bell()); let _ = shared.events.send(TerminalEvent::Bell); } VtEvent::ClipboardStore(_, text) => { @@ -269,7 +277,9 @@ impl Default for TerminalOptions { } struct PtyHandle { - master: Box, + /// Locked so a [`Terminal`] can be shared between threads (a server + /// writes input on one and resizes or kills from others). + master: Mutex>, killer: Mutex>, pid: Option, /// The shell is a WSL launcher `bash.exe`, whose programs run in the WSL @@ -285,6 +295,8 @@ pub struct Terminal { events: Receiver, pty: Option, external: Option>, + /// The size the view last asked for, when the far end sizes the grid. + wanted: Mutex>, exited: Arc, /// Parser for [`Self::feed`] (kept so sequences may span calls). feed_parser: Mutex, @@ -307,6 +319,7 @@ impl Terminal { integrated: AtomicBool::new(false), bytes_out: AtomicU64::new(0), answers_queries: AtomicBool::new(true), + title: RwLock::new(None), }); let config = TermConfig { scrolling_history: opts.scrollback, @@ -327,6 +340,7 @@ impl Terminal { events, pty: None, external: None, + wanted: Mutex::new(None), exited: Arc::new(AtomicBool::new(true)), feed_parser: Mutex::new(OutputParser::default()), search: Mutex::new(None), @@ -351,14 +365,13 @@ impl Terminal { *shared.writer.lock() = Some(Box::new(ExternalWriter(io.clone()))); let (tx, rx) = unbounded(); - let reader = Box::new(ChannelReader { rx, chunk: Vec::new(), pos: 0 }); let exited = Arc::new(AtomicBool::new(false)); { let term = term.clone(); let shared = shared.clone(); let exited = exited.clone(); std::thread::Builder::new().name("redshell-external".into()).spawn(move || { - io_loop(reader, &term, &shared); + external_loop(&rx, &term, &shared); exited.store(true, Ordering::Release); shared.observe(|o| o.on_exit(None)); let _ = shared.events.send(TerminalEvent::Exited(None)); @@ -370,6 +383,7 @@ impl Terminal { events, pty: None, external: Some(io), + wanted: Mutex::new(None), exited, feed_parser: Mutex::new(OutputParser::default()), search: Mutex::new(None), @@ -435,13 +449,14 @@ impl Terminal { shared, events, pty: Some(PtyHandle { - master: pair.master, + master: Mutex::new(pair.master), killer: Mutex::new(killer), pid, #[cfg(windows)] wsl_launcher: redshell_core::shell::is_wsl_launcher(&spec.program), }), external: None, + wanted: Mutex::new(None), exited, feed_parser: Mutex::new(OutputParser::default()), search: Mutex::new(None), @@ -519,14 +534,27 @@ impl Terminal { *self.shared.size.read() } + /// Resizes the grid to the view's size; when the far end sizes it (see + /// [`ExternalIo::sizes_grid`]), only tells the far end the view's size. pub fn resize(&self, size: GridSize) { - if size.cols == 0 || size.rows == 0 || *self.shared.size.read() == size { + if size.cols == 0 || size.rows == 0 { + return; + } + if let Some(io) = self.external.as_ref().filter(|io| io.sizes_grid()) { + let mut wanted = self.wanted.lock(); + if *wanted != Some(size) { + *wanted = Some(size); + io.resize(size); + } + return; + } + if *self.shared.size.read() == size { return; } *self.shared.size.write() = size; resize_keeping_top(&mut self.term.lock(), size); if let Some(pty) = &self.pty { - let _ = pty.master.resize(size.pty()); + let _ = pty.master.lock().resize(size.pty()); } if let Some(io) = &self.external { io.resize(size); @@ -545,6 +573,31 @@ impl Terminal { build_snapshot(&self.term.lock(), &palette, opts, search.as_mut()) } + /// The screen, up to `scrollback` lines of history and the modes, as + /// bytes that redraw them in a fresh terminal (see [`Replay`]). + pub fn replay(&self, scrollback: usize) -> Replay { + let term = self.term.lock(); + let offset = self.shared.bytes_out.load(Ordering::Acquire); + build_replay(&term, self.shared.title.read().as_deref(), scrollback, offset) + } + + /// The window title the program set, if any. + pub fn title(&self) -> Option { + self.shared.title.read().clone() + } + + /// The last line on screen, up to the cursor, that holds text. + pub fn last_line(&self) -> Option { + let term = self.term.lock(); + let cursor = term.grid().cursor.point.line; + (0..=cursor.0).rev().map(|l| Self::line_text(&term, Line(l))).find(|text| !text.trim().is_empty()) + } + + #[cfg(test)] + pub(crate) fn with_term(&self, f: impl FnOnce(&Term) -> R) -> R { + f(&self.term.lock()) + } + // ----- find ------------------------------------------------------------- /// Sets the find pattern and focuses the nearest match (keeping the @@ -764,7 +817,7 @@ impl Terminal { #[cfg(unix)] { if let Some(pty) = &self.pty - && let (Some(leader), Some(pid)) = (pty.master.process_group_leader(), pty.pid) + && let (Some(leader), Some(pid)) = (pty.master.lock().process_group_leader(), pty.pid) { return leader as u32 != pid; } @@ -800,6 +853,9 @@ impl Terminal { } } + /// Output bytes read from the program so far. The count moves together + /// with the grid, so it marks where a [`Replay`] leaves off: output + /// reported to the observer ends at this offset after each chunk. pub fn bytes_received(&self) -> u64 { self.shared.bytes_out.load(Ordering::Relaxed) } @@ -807,7 +863,7 @@ impl Terminal { pub fn kill(&self) { if let Some(pty) = self.pty.as_ref() { #[cfg(unix)] - disable_eof(pty.master.as_ref()); + disable_eof(pty.master.lock().as_ref()); let _ = pty.killer.lock().kill(); } if let Some(io) = self.external.as_ref() { @@ -856,22 +912,71 @@ fn io_loop(mut reader: Box, term: &FairMutex>, s Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue, Err(_) => break, }; - let chunk = &buf[..n]; - shared.bytes_out.fetch_add(n as u64, Ordering::Relaxed); - parser.advance(&mut *term.lock(), chunk, |event| match event { - Parsed::Cwd(cwd) => { - shared.observe(|o| o.on_cwd(&cwd)); - let _ = shared.events.send(TerminalEvent::Cwd(cwd)); - } - Parsed::PromptStart => shared.integrated.store(true, Ordering::Release), - Parsed::Command(text) => shared.observe(|o| o.on_command(&text)), - Parsed::CommandFinished(code) => { - let _ = shared.events.send(TerminalEvent::CommandFinished(code)); + ingest(&mut parser, &buf[..n], term, shared); + } +} + +/// Applies what is fed to an external terminal until every feed is gone. +fn external_loop(feed: &Receiver, term: &FairMutex>, shared: &Shared) { + let mut parser = OutputParser::default(); + for item in feed.iter() { + match item { + Feed::Output(bytes) => ingest(&mut parser, &bytes, term, shared), + Feed::Resize(cols, rows) => resize_to(cols, rows, &mut term.lock(), shared), + Feed::Reset(cols, rows) => { + parser = OutputParser::default(); + let mut grid = term.lock(); + resize_to(cols, rows, &mut grid, shared); + // RIS: a fresh screen and modes, and no scrollback. + parser.advance(&mut grid, b"\x1bc", |_| {}); + drop(grid); + shared.wake(); } - }); - shared.observe(|o| o.on_output(chunk)); - shared.wake(); + } + } +} + +/// Gives an external grid the far end's size, keeping the cell metrics. +fn resize_to(cols: u16, rows: u16, term: &mut Term, shared: &Shared) { + if cols == 0 || rows == 0 { + return; } + let size = { + let mut current = shared.size.write(); + *current = GridSize { cols, rows, ..*current }; + *current + }; + resize_keeping_top(term, size); + shared.observe(|o| o.on_resize(cols, rows)); + shared.wake(); +} + +/// Parses one chunk of program output into the grid, reporting what the +/// observer and the view need. +fn ingest(parser: &mut OutputParser, chunk: &[u8], term: &FairMutex>, shared: &Shared) { + let mut grid = term.lock(); + let alt_before = grid.mode().contains(TermMode::ALT_SCREEN); + parser.advance(&mut grid, chunk, |event| match event { + Parsed::Cwd(cwd) => { + shared.observe(|o| o.on_cwd(&cwd)); + let _ = shared.events.send(TerminalEvent::Cwd(cwd)); + } + Parsed::PromptStart => shared.integrated.store(true, Ordering::Release), + Parsed::Command(text) => shared.observe(|o| o.on_command(&text)), + Parsed::CommandFinished(code) => { + let _ = shared.events.send(TerminalEvent::CommandFinished(code)); + } + Parsed::Notify { title, body } => shared.observe(|o| o.on_notification(title.as_deref(), &body)), + }); + // Counted under the lock, so a replay's offset matches its grid. + shared.bytes_out.fetch_add(chunk.len() as u64, Ordering::Release); + let alt_after = grid.mode().contains(TermMode::ALT_SCREEN); + drop(grid); + shared.observe(|o| o.on_output(chunk)); + if alt_after != alt_before { + shared.observe(|o| o.on_alt_screen(alt_after)); + } + shared.wake(); } fn trim_line_ends(text: &str) -> String { @@ -976,6 +1081,12 @@ mod tests { assert_eq!(encode_paste("a\nb\x1b[201~", t.input_modes()), b"\x1b[200~a\rb\x1b[201~"); } + #[test] + fn terminals_can_be_shared_between_threads() { + fn shareable() {} + shareable::(); + } + #[test] fn prompt_stripping() { assert_eq!(strip_prompt("user@box:~$ ls -la").as_deref(), Some("ls -la")); @@ -1057,6 +1168,51 @@ mod tests { assert!(t.is_exited()); } + /// A far end that sizes the grid, like a server session other clients share. + #[derive(Default)] + struct ServerIo(Recorder); + + impl ExternalIo for ServerIo { + fn write(&self, bytes: &[u8]) { + self.0.write(bytes); + } + fn resize(&self, size: GridSize) { + self.0.resize(size); + } + fn sizes_grid(&self) -> bool { + true + } + } + + #[test] + fn a_far_end_that_sizes_the_grid_resets_and_resizes_it_in_order() { + let io = Arc::new(ServerIo::default()); + let (t, feed) = Terminal::external(opts(), io.clone()).unwrap(); + let size = |t: &Terminal| (t.size().cols, t.size().rows); + + // The view's size is only a wish, said once. + let view = GridSize { cols: 120, rows: 40, cell_width: 8, cell_height: 16 }; + t.resize(view); + t.resize(view); + assert_eq!(io.0.sizes.lock().as_slice(), [(120, 40)]); + + // A redraw starts from a reset grid of the far end's size. + feed.feed(b"before the snapshot\r\n"); + feed.reset(40, 10); + feed.feed(b"snapshot"); + feed.resize(60, 12); + feed.feed(b" live"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !t.plain_text().contains("live") { + assert!(std::time::Instant::now() < deadline, "{}", t.plain_text()); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(size(&t), (60, 12)); + assert!(!t.plain_text().contains("before"), "{}", t.plain_text()); + assert!(t.plain_text().starts_with("snapshot live")); + assert_eq!(io.0.sizes.lock().len(), 1, "the far end's sizes are not echoed back"); + } + #[test] fn external_kill_closes_io() { let io = Arc::new(Recorder::default()); @@ -1166,6 +1322,46 @@ mod tests { assert!(t.plain_text().contains("hi-from-pty")); } + #[cfg(unix)] + #[derive(Clone, Default)] + struct Alerts(Arc>>); + + #[cfg(unix)] + impl SessionObserver for Alerts { + fn on_output(&mut self, _bytes: &[u8]) {} + fn on_bell(&mut self) { + self.0.lock().push("bell".into()); + } + fn on_notification(&mut self, title: Option<&str>, body: &str) { + self.0.lock().push(format!("{title:?}: {body}")); + } + fn on_alt_screen(&mut self, active: bool) { + self.0.lock().push(format!("alt screen {active}")); + } + } + + #[cfg(unix)] + #[test] + fn bell_and_notifications_reach_the_observer() { + let alerts = Alerts::default(); + let spec = CommandSpec::new("/bin/sh").arg("-c").arg(r"printf '\033]777;notify;Agent;Done\007\a'"); + let t = Terminal::spawn(&spec, TerminalOptions { observer: Some(Box::new(alerts.clone())), ..opts() }).unwrap(); + wait_for(&t, |ev| matches!(ev, TerminalEvent::Exited(_))); + assert_eq!(*alerts.0.lock(), ["Some(\"Agent\"): Done", "bell"]); + assert_eq!(t.replay(0).offset, t.bytes_received()); + } + + #[cfg(unix)] + #[test] + fn alt_screen_switches_reach_the_observer() { + let alerts = Alerts::default(); + let script = r"printf '\033[?1049h'; sleep 0.2; printf '\033[?1049l'"; + let spec = CommandSpec::new("/bin/sh").arg("-c").arg(script); + let t = Terminal::spawn(&spec, TerminalOptions { observer: Some(Box::new(alerts.clone())), ..opts() }).unwrap(); + wait_for(&t, |ev| matches!(ev, TerminalEvent::Exited(_))); + assert_eq!(*alerts.0.lock(), ["alt screen true", "alt screen false"]); + } + #[cfg(unix)] #[test] fn interrupted_program_exits_like_in_a_shell() { diff --git a/crates/redshell-terminal/src/lib.rs b/crates/redshell-terminal/src/lib.rs index 4ec071e..e6ce556 100644 --- a/crates/redshell-terminal/src/lib.rs +++ b/crates/redshell-terminal/src/lib.rs @@ -13,6 +13,9 @@ //! * [`mouse`] encodes mouse reports in the protocol a program enabled. //! * [`osc`] picks up shell integration marks (OSC 7 / OSC 9;9 / OSC 133); //! prompt positions are kept in the grid for prompt-to-prompt navigation. +//! Notifications (OSC 9 / OSC 777) and the bell go to the observer. +//! * [`replay`] serializes the screen and its modes as ANSI, for a client +//! joining a running session. pub mod engine; mod exit_status; @@ -23,6 +26,7 @@ pub mod osc; mod output; #[cfg(any(windows, test))] mod process_tree; +pub mod replay; pub mod search; mod selection_guard; pub mod snapshot; @@ -31,6 +35,7 @@ pub use engine::{ExternalFeed, ExternalIo, GridSize, Terminal, TerminalEvent, Te pub use input::{InputModes, KeyMods, encode_key, encode_paste}; pub use links::Link; pub use mouse::{MouseAction, MouseButton, MouseEncoding, MouseProtocol, MouseReport, MouseTracking}; +pub use replay::{Replay, ScreenModes}; pub use search::{SearchDirection, SearchQuery, SearchStatus}; pub use snapshot::{BgSpan, CursorShape, CursorState, MatchSpan, Segment, Snapshot, SnapshotOptions}; diff --git a/crates/redshell-terminal/src/osc.rs b/crates/redshell-terminal/src/osc.rs index ad9a8d8..4b91ee6 100644 --- a/crates/redshell-terminal/src/osc.rs +++ b/crates/redshell-terminal/src/osc.rs @@ -1,7 +1,8 @@ //! Streaming scanner for the OSC sequences RedShell cares about but the VT -//! parser does not surface: OSC 7 and OSC 9;9 (working directory) and OSC 133 -//! (shell integration prompt/command marks). Sequences may be split across -//! reads. +//! parser does not surface: OSC 7 and OSC 9;9 (working directory), OSC 133 +//! (shell integration prompt/command marks) and the desktop notifications of +//! OSC 9 (iTerm2) and OSC 777 (`notify`, urxvt). Sequences may be split +//! across reads. //! //! Each event carries the offset just past its terminator within the fed //! chunk, so the caller can advance the VT parser exactly up to the mark and @@ -21,6 +22,9 @@ pub enum OscEvent { OutputStart, /// OSC 133;D[;code] CommandFinished(Option), + /// OSC 9;`body` or OSC 777;notify;`title`;`body`: the program asks for + /// a desktop notification. + Notify { title: Option, body: String }, } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] @@ -91,6 +95,16 @@ impl OscScanner { Some(path) => OscEvent::Cwd(path), None => return, } + } else if let Some(rest) = text.strip_prefix("777;notify;") { + let (title, body) = rest.split_once(';').unwrap_or(("", rest)); + OscEvent::Notify { title: (!title.is_empty()).then(|| title.to_owned()), body: body.to_owned() } + } else if let Some(body) = text.strip_prefix("9;") { + // ConEmu uses OSC 9;;… for progress, cwd and more. + let code = body.split(';').next().unwrap_or_default(); + if !code.is_empty() && code.bytes().all(|b| b.is_ascii_digit()) { + return; + } + OscEvent::Notify { title: None, body: body.to_owned() } } else if let Some(rest) = text.strip_prefix("133;") { let mut parts = rest.split(';'); match parts.next() { @@ -343,6 +357,22 @@ mod tests { assert_eq!(PathStyle::Unix.conemu_path("relative"), None); } + #[test] + fn notifications() { + let mut s = OscScanner::default(); + let mut out = Vec::new(); + s.feed(b"\x1b]9;Build done\x07\x1b]777;notify;Claude;Needs; input\x1b\\\x1b]777;notify;;x\x07", &mut out); + let events: Vec<_> = out.into_iter().map(|(_, e)| e).collect(); + assert_eq!( + events, + vec![ + OscEvent::Notify { title: None, body: "Build done".into() }, + OscEvent::Notify { title: Some("Claude".into()), body: "Needs; input".into() }, + OscEvent::Notify { title: None, body: "x".into() }, + ] + ); + } + #[test] fn osc_9_9_is_scanned_and_other_9_codes_ignored() { let path = if cfg!(windows) { r"C:\x" } else { "/x" }; diff --git a/crates/redshell-terminal/src/output.rs b/crates/redshell-terminal/src/output.rs index 67b0306..f0b8a0d 100644 --- a/crates/redshell-terminal/src/output.rs +++ b/crates/redshell-terminal/src/output.rs @@ -31,6 +31,11 @@ pub(crate) enum Parsed { /// The text of a submitted command (between OSC 133;B and ;C). Command(String), CommandFinished(Option), + /// A desktop notification (OSC 9 / OSC 777). + Notify { + title: Option, + body: String, + }, } #[derive(Default)] @@ -77,6 +82,7 @@ impl OutputParser { self.stop_marking(term); emit(Parsed::CommandFinished(code)); } + OscEvent::Notify { title, body } => emit(Parsed::Notify { title, body }), } } self.osc = events; diff --git a/crates/redshell-terminal/src/replay.rs b/crates/redshell-terminal/src/replay.rs new file mode 100644 index 0000000..22751b3 --- /dev/null +++ b/crates/redshell-terminal/src/replay.rs @@ -0,0 +1,422 @@ +//! The screen as a byte stream that redraws it in a fresh terminal. +//! +//! A client that joins a running session (a phone attaching to a server +//! session) needs what is on screen now, not the whole history of bytes. A +//! [`Replay`] holds the recent scrollback and the screen as ANSI text, then +//! the state a program left behind that is invisible in the cells: the +//! cursor position and pen, the input and mouse modes, the cursor style and +//! the title. Feeding it into a terminal of the same size, right after a +//! reset, gives that terminal the same grid and modes; the live output that +//! follows (from [`Replay::offset`] on) then lands exactly as it would have. +//! +//! Known gaps: a scroll region (DECSTBM), saved cursors and character sets +//! are not carried, and while a full-screen program uses the alternate +//! screen only that screen is sent (the normal screen behind it is not +//! reachable through alacritty's API), so it comes back blank once the +//! program exits. Programs redraw on the resize a joining client causes. + +use std::fmt::Write as _; + +use alacritty_terminal::grid::Dimensions; +use alacritty_terminal::index::{Column, Line}; +use alacritty_terminal::term::cell::{Cell, Flags}; +use alacritty_terminal::term::{Term, TermMode}; +use alacritty_terminal::vte::ansi::{Color, CursorShape as VtCursorShape}; + +use crate::mouse::MouseProtocol; +use crate::snapshot::CursorShape; + +/// Terminal state that decides how input is encoded and how the screen is +/// drawn, as carried by a [`Replay`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScreenModes { + pub alt_screen: bool, + /// DECCKM: arrows send `ESC O A` instead of `ESC [ A`. + pub app_cursor: bool, + /// DECKPAM: the keypad sends application sequences. + pub app_keypad: bool, + pub bracketed_paste: bool, + /// Mouse reporting the program asked for, with its encoding. + pub mouse: Option, + /// DECSET 1004: focus in and out are reported. + pub focus_reporting: bool, + pub cursor_visible: bool, + pub cursor_shape: CursorShape, + pub cursor_blinking: bool, + pub title: Option, +} + +/// The screen and recent scrollback serialized as ANSI, plus the modes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Replay { + pub cols: u16, + pub rows: u16, + /// Write this into a reset terminal of `cols` × `rows`. + pub data: String, + pub modes: ScreenModes, + /// Output bytes parsed into the grid when this was taken (see + /// [`crate::Terminal::output_offset`]); live output continues from here. + pub offset: u64, +} + +/// SGR state of a cell: what the pen has to be to draw it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Pen { + fg: Color, + bg: Color, + flags: Flags, + underline: Option, +} + +/// Flags that are not drawing attributes. +const LAYOUT_FLAGS: Flags = + Flags::WRAPLINE.union(Flags::WIDE_CHAR).union(Flags::WIDE_CHAR_SPACER).union(Flags::LEADING_WIDE_CHAR_SPACER); + +impl Pen { + fn of(cell: &Cell) -> Self { + Self { fg: cell.fg, bg: cell.bg, flags: cell.flags - LAYOUT_FLAGS, underline: cell.underline_color() } + } + + fn plain() -> Self { + Self::of(&Cell::default()) + } + + /// `ESC [ 0 ; … m`: resets, then sets every attribute of this pen. + fn write(&self, out: &mut String) { + out.push_str("\x1b[0"); + let flags = [ + (Flags::BOLD, "1"), + (Flags::DIM, "2"), + (Flags::ITALIC, "3"), + (Flags::UNDERLINE, "4"), + (Flags::DOUBLE_UNDERLINE, "4:2"), + (Flags::UNDERCURL, "4:3"), + (Flags::DOTTED_UNDERLINE, "4:4"), + (Flags::DASHED_UNDERLINE, "4:5"), + (Flags::INVERSE, "7"), + (Flags::HIDDEN, "8"), + (Flags::STRIKEOUT, "9"), + ]; + for (flag, code) in flags { + if self.flags.contains(flag) { + out.push(';'); + out.push_str(code); + } + } + write_color(out, self.fg, 30, 90, 38); + write_color(out, self.bg, 40, 100, 48); + if let Some(color) = self.underline { + write_color(out, color, 58, 58, 58); + } + out.push('m'); + } +} + +/// Appends `;` for `color`: `base + n` for the 8 standard colours, +/// `bright + n` for the bright ones, `extended;5;i` or `extended;2;r;g;b` +/// otherwise. Default colours add nothing. +fn write_color(out: &mut String, color: Color, base: u8, bright: u8, extended: u8) { + let _ = match color { + Color::Named(named) => match named as usize { + n @ 0..=7 if base != extended => write!(out, ";{}", base as usize + n), + n @ 8..=15 if base != extended => write!(out, ";{}", bright as usize + n - 8), + n @ 0..=15 => write!(out, ";{extended};5;{n}"), + _ => Ok(()), + }, + Color::Indexed(i) => write!(out, ";{extended};5;{i}"), + Color::Spec(rgb) => write!(out, ";{extended};2;{};{};{}", rgb.r, rgb.g, rgb.b), + }; +} + +/// Draws cells while keeping track of the pen, so SGR is written only when +/// the style changes. +struct Painter { + out: String, + pen: Pen, +} + +impl Painter { + /// Draws the cell at column `col` (0-based) of the current row. + fn cell(&mut self, cell: &Cell, col: usize) { + let pen = Pen::of(cell); + if pen != self.pen { + pen.write(&mut self.out); + self.pen = pen; + } + self.out.push(cell.c); + if cell.c == '\t' { + // A tab keeps '\t' in its first cell and jumps to the next stop; + // come back so the cells it skipped are drawn like any other. + let _ = write!(self.out, "\x1b[{}G", col + 2); + } + if let Some(zerowidth) = cell.zerowidth() { + self.out.extend(zerowidth); + } + } + + fn reset_pen(&mut self) { + if self.pen != Pen::plain() { + self.out.push_str("\x1b[0m"); + self.pen = Pen::plain(); + } + } +} + +/// Whether a cell is an unstyled blank: trailing ones are not written. +fn is_blank(cell: &Cell) -> bool { + cell.c == ' ' && Pen::of(cell) == Pen::plain() +} + +/// Whether a cell is the right half of a wide glyph, or the gap left where +/// one did not fit; the terminal recreates both when the glyph is written. +fn is_spacer(cell: &Cell) -> bool { + cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) +} + +/// Serializes `term` (with at most `scrollback` lines of history) for a +/// fresh terminal of the same size. `title` is the window title, which +/// alacritty keeps private. +pub(crate) fn build_replay(term: &Term, title: Option<&str>, scrollback: usize, offset: u64) -> Replay { + let grid = term.grid(); + let mode = *term.mode(); + let (cols, rows) = (term.columns(), term.screen_lines()); + let history = grid.history_size().min(scrollback); + let mut painter = Painter { out: String::from("\x1bc"), pen: Pen::plain() }; + if mode.contains(TermMode::ALT_SCREEN) { + painter.out.push_str("\x1b[?1049h"); + } + + let total = history + rows; + for i in 0..total { + let row = &grid[Line(i as i32 - history as i32)]; + let wrapped = row[Column(cols - 1)].flags.contains(Flags::WRAPLINE); + let end = + if wrapped { cols } else { (0..cols).rev().find(|&c| !is_blank(&row[Column(c)])).map_or(0, |c| c + 1) }; + for c in 0..end { + let cell = &row[Column(c)]; + if !is_spacer(cell) { + painter.cell(cell, c); + } + } + if i + 1 < total && !wrapped { + // A newline that scrolls fills the new row with the pen's background. + painter.reset_pen(); + painter.out.push_str("\r\n"); + } + } + + restore_cursor(&mut painter, term); + let out = &mut painter.out; + write_modes(out, mode); + let style = term.cursor_style(); + let shape = match style.shape { + VtCursorShape::Block => CursorShape::Block, + VtCursorShape::Underline => CursorShape::Underline, + VtCursorShape::Beam => CursorShape::Bar, + VtCursorShape::HollowBlock => CursorShape::Hollow, + VtCursorShape::Hidden => CursorShape::Hidden, + }; + let decscusr = match shape { + CursorShape::Underline => Some(3), + CursorShape::Bar => Some(5), + CursorShape::Block if style.blinking => Some(1), + _ => None, + }; + if let Some(code) = decscusr { + // Odd codes blink, the even code after each is steady. + let _ = write!(out, "\x1b[{} q", code + u8::from(!style.blinking && code != 1)); + } + let title = title.map(|t| t.chars().filter(|c| !c.is_control()).collect::()); + if let Some(title) = &title { + let _ = write!(out, "\x1b]2;{title}\x07"); + } + + Replay { + cols: cols as u16, + rows: rows as u16, + data: painter.out, + modes: ScreenModes { + alt_screen: mode.contains(TermMode::ALT_SCREEN), + app_cursor: mode.contains(TermMode::APP_CURSOR), + app_keypad: mode.contains(TermMode::APP_KEYPAD), + bracketed_paste: mode.contains(TermMode::BRACKETED_PASTE), + mouse: MouseProtocol::from_mode(mode), + focus_reporting: mode.contains(TermMode::FOCUS_IN_OUT), + cursor_visible: mode.contains(TermMode::SHOW_CURSOR), + cursor_shape: shape, + cursor_blinking: style.blinking, + title, + }, + offset, + } +} + +/// Moves the cursor where it is, with a pending wrap when the program left +/// one (the next glyph goes to the next row), and sets the pen it draws with. +fn restore_cursor(painter: &mut Painter, term: &Term) { + let grid = term.grid(); + let cursor = &grid.cursor; + let line = cursor.point.line; + let last = term.columns() - 1; + painter.reset_pen(); + if cursor.input_needs_wrap { + // Rewriting the last glyph of the row leaves the terminal waiting to wrap. + let row = &grid[line]; + let col = if row[Column(last)].flags.contains(Flags::WIDE_CHAR_SPACER) { last - 1 } else { last }; + let _ = write!(painter.out, "\x1b[{};{}H", line.0 + 1, col + 1); + painter.cell(&row[Column(col)], col); + } else { + let _ = write!(painter.out, "\x1b[{};{}H", line.0 + 1, cursor.point.column.0 + 1); + } + painter.reset_pen(); + let pen = Pen::of(&cursor.template); + if pen != Pen::plain() { + pen.write(&mut painter.out); + } +} + +/// DECSET/DECRST sequences for the modes that differ from a reset terminal. +fn write_modes(out: &mut String, mode: TermMode) { + let private = [ + (TermMode::APP_CURSOR, 1, true), + (TermMode::LINE_WRAP, 7, false), + (TermMode::SHOW_CURSOR, 25, false), + (TermMode::MOUSE_REPORT_CLICK, 1000, true), + (TermMode::MOUSE_DRAG, 1002, true), + (TermMode::MOUSE_MOTION, 1003, true), + (TermMode::FOCUS_IN_OUT, 1004, true), + (TermMode::UTF8_MOUSE, 1005, true), + (TermMode::SGR_MOUSE, 1006, true), + (TermMode::BRACKETED_PASTE, 2004, true), + ]; + for (flag, code, off_by_default) in private { + let on = mode.contains(flag); + if on == off_by_default { + let _ = write!(out, "\x1b[?{code}{}", if on { 'h' } else { 'l' }); + } + } + if mode.contains(TermMode::INSERT) { + out.push_str("\x1b[4h"); + } + if mode.contains(TermMode::LINE_FEED_NEW_LINE) { + out.push_str("\x1b[20h"); + } + if mode.contains(TermMode::APP_KEYPAD) { + out.push_str("\x1b="); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::engine::{GridSize, Terminal, TerminalOptions}; + use crate::mouse::{MouseEncoding, MouseTracking}; + + fn terminal(cols: u16, rows: u16) -> Terminal { + Terminal::detached(TerminalOptions { + size: GridSize { cols, rows, cell_width: 8, cell_height: 16 }, + ..Default::default() + }) + } + + /// Feeds `bytes` into a terminal, replays it into a fresh one, and checks + /// both agree; then feeds `after` into both and checks again, which + /// catches a wrong pen, cursor or pending wrap. + fn round_trip(cols: u16, rows: u16, bytes: &[u8], after: &[u8]) -> (Terminal, Terminal) { + let source = terminal(cols, rows); + source.feed(bytes); + let replay = source.replay(usize::MAX); + assert_eq!((replay.cols, replay.rows), (cols, rows)); + let copy = terminal(cols, rows); + copy.feed(replay.data.as_bytes()); + assert_same(&source, ©, "after the replay"); + assert_eq!(copy.replay(usize::MAX).modes, replay.modes, "modes survive the replay"); + source.feed(after); + copy.feed(after); + assert_same(&source, ©, "after more output"); + (source, copy) + } + + fn assert_same(a: &Terminal, b: &Terminal, when: &str) { + a.with_term(|ta| { + b.with_term(|tb| { + let (ga, gb) = (ta.grid(), tb.grid()); + assert_eq!(ga.history_size(), gb.history_size(), "history {when}"); + assert_eq!(ga.cursor.point, gb.cursor.point, "cursor {when}"); + assert_eq!(ga.cursor.input_needs_wrap, gb.cursor.input_needs_wrap, "pending wrap {when}"); + assert_eq!(Pen::of(&ga.cursor.template), Pen::of(&gb.cursor.template), "pen {when}"); + let relevant = TermMode::ANY - TermMode::VI; + assert_eq!(*ta.mode() & relevant, *tb.mode() & relevant, "modes {when}"); + assert_eq!(ta.cursor_style(), tb.cursor_style(), "cursor style {when}"); + let history = ga.history_size() as i32; + for line in -history..ta.screen_lines() as i32 { + for col in 0..ta.columns() { + let (ca, cb) = (&ga[Line(line)][Column(col)], &gb[Line(line)][Column(col)]); + let at = format!("cell {line},{col} {when}"); + assert_eq!(ca.c, cb.c, "{at}"); + assert_eq!(Pen::of(ca), Pen::of(cb), "{at}"); + assert_eq!(ca.flags & LAYOUT_FLAGS, cb.flags & LAYOUT_FLAGS, "{at}"); + assert_eq!(ca.zerowidth(), cb.zerowidth(), "{at}"); + } + } + }) + }); + } + + #[test] + fn styled_text_scrollback_and_wrapping() { + let mut bytes = Vec::new(); + for i in 0..12 { + bytes.extend(format!("\x1b[3{}mline {i}\x1b[0m plain\r\n", i % 8).as_bytes()); + } + bytes.extend(b"\x1b[1;4:3;38;5;202;48;2;10;20;30mfancy\x1b[0m \x1b[7;9mrev\x1b[0m\r\n"); + bytes.extend("a long line that wraps across rows: 日本語 e\u{301} 0123456789\r\n".as_bytes()); + bytes.extend(b"\x1b[44m \x1b[0m trailing bg\r\na\tb\r\n\tindented\tx\r\n\x1b[32;1mpen left on "); + round_trip(20, 6, &bytes, b"more\r\n\r\nand more text that wraps around\r\n"); + } + + #[test] + fn pending_wrap_and_wide_glyphs_at_the_edge() { + let (_, copy) = round_trip(10, 4, "0123456789".as_bytes(), b"x"); + assert!(copy.plain_text().contains("0123456789\nx")); + round_trip(10, 4, "abcdefgh日".as_bytes(), "y".as_bytes()); + round_trip(10, 4, "abcdefghi日z".as_bytes(), b"\r\nnext"); + } + + #[test] + fn modes_cursor_and_title() { + let bytes = + b"\x1b]2;my title\x07\x1b[?1h\x1b=\x1b[?2004h\x1b[?1002h\x1b[?1006h\x1b[?1004h\x1b[?25l\x1b[6 q\x1b[3;4Hx"; + let (source, _) = round_trip(20, 5, bytes, b"\x1b[?25hy"); + source.feed(b"\x1b[?25l"); + let modes = source.replay(0).modes; + assert_eq!(modes.title.as_deref(), Some("my title")); + assert!(modes.app_cursor && modes.app_keypad && modes.bracketed_paste && modes.focus_reporting); + assert_eq!(modes.mouse, Some(MouseProtocol { tracking: MouseTracking::Drag, encoding: MouseEncoding::Sgr })); + assert!(!modes.cursor_visible); + assert_eq!((modes.cursor_shape, modes.cursor_blinking), (CursorShape::Bar, false)); + } + + #[test] + fn alternate_screen() { + let bytes = b"shell output\r\n$ vim\r\n\x1b[?1049h\x1b[H\x1b[2J\x1b[7m status \x1b[0m\x1b[2;1H~\x1b[3;1H~"; + let (source, copy) = round_trip(20, 5, bytes, b"\x1b[4;1Hedit"); + assert!(source.replay(0).modes.alt_screen); + // Leaving it shows the normal screen, which the replay could not carry. + copy.feed(b"\x1b[?1049l"); + assert!(!copy.replay(0).modes.alt_screen); + } + + #[test] + fn scrollback_is_capped() { + let t = terminal(20, 3); + for i in 0..50 { + t.feed(format!("row {i}\r\n").as_bytes()); + } + let copy = terminal(20, 3); + copy.feed(t.replay(10).data.as_bytes()); + let text = copy.plain_text(); + assert!(text.starts_with("row 38\n"), "{text}"); + assert!(text.ends_with("row 49")); + } +} diff --git a/crates/redshell-ui/icons/cloud.svg b/crates/redshell-ui/icons/cloud.svg new file mode 100644 index 0000000..e88cf55 --- /dev/null +++ b/crates/redshell-ui/icons/cloud.svg @@ -0,0 +1 @@ + diff --git a/crates/redshell-ui/src/components/icon.rs b/crates/redshell-ui/src/components/icon.rs index 8fe038c..89f5dbe 100644 --- a/crates/redshell-ui/src/components/icon.rs +++ b/crates/redshell-ui/src/components/icon.rs @@ -53,6 +53,7 @@ icons! { CircleAlert => "circle-alert", ClipboardPaste => "clipboard-paste", Close => "x", + Cloud => "cloud", Columns2 => "columns-2", Command => "command", Copy => "copy", @@ -113,6 +114,7 @@ impl From for IconName { LaunchKind::Agent => Self::Sparkles, LaunchKind::Multiplexer => Self::LayoutGrid, LaunchKind::Plugin => Self::Puzzle, + LaunchKind::Remote => Self::Cloud, } } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7979e65..3f1a36e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -7,14 +7,23 @@ GPU. ``` redshell-app ──► redshell-ui ──► redshell-theme (feature "gpui") │ - ├──► redshell-terminal ──► alacritty_terminal, portable-pty + ├──► redshell-terminal ──► redshell-theme, alacritty_terminal, portable-pty ├──► redshell-history ──► rusqlite (bundled, FTS5) ├──► redshell-remote (ssh, sftp, tmux, screen, WSL) ├──► redshell-agents ├──► redshell-plugin ──► redshell-theme - └──► redshell-core (shared by every crate) + ├──► redshell-protocol (talking to RedShell servers) + └──► redshell-core (shared by every crate) ──► redshell-protocol (SSH hosts on the wire) + +redshell-server ──► axum, tokio, rustls (ring), rusqlite, argon2, webauthn-rs, web-push-native + ├──► redshell-terminal, redshell-agents, redshell-remote, redshell-core + └──► redshell-protocol ──► serde (ts-rs in tests: web/src/protocol/*.ts) ``` +`redshell-server` and `redshell-protocol` do not depend on GPUI either; the server is a separate +binary with no OpenSSL, which cross-builds for a Raspberry Pi with the C compiler SQLite and ring +need. + ## Key abstractions * **`Launchable` / `LaunchProfile`** (core): anything that can open in a tab. Local shells, SSH @@ -25,6 +34,9 @@ redshell-app ──► redshell-ui ──► redshell-theme (feature "gpui") * **`SessionObserver`** (core): the terminal I/O thread reports output, input, resizes, titles, the working directory, commands and exit to it. The history `Recorder` is one observer. `ObserverSet` fans out to several. +* **`Replay`** (terminal): the screen, recent scrollback and the modes a program set, as ANSI + bytes that redraw them in a fresh terminal, cut at the exact output offset the live stream + continues from. A client that joins a server session gets one. * **`Terminal`** (terminal): owns the PTY and the VT state. An I/O thread parses output and scans OSC 7, 9;9 and 133. The parser is advanced exactly up to each mark, and cells printed after `OSC 133;A` carry an internal hyperlink id, so prompt positions follow scrolling and reflow. @@ -61,9 +73,17 @@ redshell-app ──► redshell-ui ──► redshell-theme (feature "gpui") runtime of its own, so its calls are plain futures any executor (GPUI's) can await. In the app, `FileBrowser` (`sftp_view.rs`, drawn by `sftp_render.rs`) is the dialog, and the workspace (`files.rs`) keeps a closed browser only while its transfers run. +* **`ServerClient`** (app, `remote/`): the desktop's connection to one RedShell server, with no + GPUI in it so it is tested against a real server in-process: the REST API, and one WebSocket on + a tokio thread that reconnects with backoff, resyncs the session list and re-attaches what was + attached. Each attachment streams into a `Sink` from that thread; for a tab it feeds a + `Terminal::external` whose grid the server sizes (`ExternalIo::sizes_grid`), so snapshots, + output and resizes land in order. The app's `Servers` global keeps one client per configured + server and its tokens in the keychain; `remote_tabs` turns sessions into tabs and sidebar rows. * **`PaneNode`** (`panes.rs`): the split layout of a tab, generic over its leaf so splitting, closing and divider dragging are plain, unit-tested data operations. Each split keeps one size - ratio per child (kept in memory only). + ratio per child, and a tree of session ids with its ratios is what `open_tabs` saves as a tab's + layout. * **`ActiveTheme`** (ui): a GPUI global. Components read shadcn tokens from it and never use hard-coded colours. * **`Icon` / `IconName`** (ui): a small Lucide SVG set compiled into the binary and served to @@ -97,6 +117,31 @@ session the user picked is re-attached without being created (`attach-session -t native tmux session is attached once in control mode, which brings back all of its windows. The session a tab belongs to is read back from its profile id (`redshell_remote::session_ref`). +## Server + +`redshell-server` (see [REMOTE.md](REMOTE.md)) keeps sessions on an always-on machine: + +* **`Sessions` / `Session`** (`sessions/`): each session owns a `Terminal` and a small thread + that drains its events and writes input, so a program that stops reading never blocks an async + worker. The session's `SessionObserver` (`Tap`) publishes output, tagged with its byte offset, + to an `OutputHub`: one bounded queue per attached client, filled with `try_send`, so a slow + client is dropped and resynced with a fresh `Replay` instead of slowing anyone down. +* **`Auth`** (`auth/`): setup codes, Argon2id passwords, per-address and per-name backoff, + passkeys (`webauthn-rs`), desktop pairing and re-authentication, with browser sessions and + device tokens stored as SHA-256 hashes. +* **`Store`** (`store/`): SQLite with `user_version` migrations, like the history database: + accounts, credentials, passkeys, push subscriptions, the audit log and session records. +* **Agent hooks** (`agents/`): a loopback-only listener for Claude Code HTTP hooks and Codex's + `notify`, and `Approvals`, the permission requests held open until a client answers. +* **`Push`** (`push/`): Web Push to subscribed browsers when a session wants attention, with the + checks that keep a browser-supplied endpoint from reaching private addresses. +* **`HostBook`** (`hosts.rs`): the hosts API's view of `[[ssh.hosts]]` and `~/.ssh/config`, + written back through `LiveSettings`, which edits `config.toml` in place. +* **Web** (`web/`): the REST routes, the WebSocket and the embedded web app. `guard.rs` checks the + `Origin`, the `X-RedShell` header and the sign-in, and `connections.rs` caps open connections. +* **`Bus`**: a broadcast of session, approval and revocation events that every WebSocket + connection (`web/ws.rs`) filters for its client. + ## Rendering `TerminalView` paints with a single GPUI `canvas`: diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 21d1fa1..046b175 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -50,7 +50,7 @@ options on that page. The *Keybindings* page lists every command with its curren | `tab_bar` | `"top"` | `top` (in the title bar), `bottom` or `hidden`. The title bar with the sidebar toggle and window controls always stays at the top. | | `show_sidebar` | `true` | | | `sidebar_width` | `264` | In px, 160 to 640. Drag the sidebar's right edge to change it; double-click the edge to reset it. | -| `sidebar_sections` | `["sessions", "hosts"]` | Sidebar sections, shown in this order: `sessions` (open tabs), `shells`, `agents`, `hosts` (SSH), `multiplexer` (tmux/screen sessions on this computer and on the SSH hosts you have tabs on or that set `attach_session`) and `recent` (closed recorded sessions). Unknown names are ignored. | +| `sidebar_sections` | `["sessions", "hosts"]` | Sidebar sections, shown in this order: `sessions` (open tabs), `shells`, `agents`, `hosts` (SSH), `servers` (sessions on RedShell servers, turned on with the first server), `multiplexer` (tmux/screen sessions on this computer and on the SSH hosts you have tabs on or that set `attach_session`) and `recent` (closed recorded sessions). Unknown names are ignored. | | `show_status_bar` | `true` | | | `inactive_pane_dim` | `0.35` | How much unfocused split panes are dimmed. | @@ -211,7 +211,9 @@ bind_port = 1080 You rarely need to write these entries by hand: *Add SSH Host…* (the "+" next to the sidebar's SSH hosts) and *Edit…* in a host's right-click menu open a dialog with every field, and it saves -the entry here, keeping your comments. +the entry here, keeping your comments. `ssh_config_path` uses another file than `~/.ssh/config` +(an absolute path): RedShell lists its `Host` entries, and every ssh it starts reads it instead of +`~/.ssh/config` and the system-wide file (`ssh -F`). A host whose `name` is a `Host` alias in `~/.ssh/config` connects through that alias, so the file's options apply, and the fields set here are passed on top of them (`port`, `user`, an @@ -252,9 +254,9 @@ Linux and Windows they also end when RedShell is killed or crashes; on macOS the then, and the next start reports their ports as in use until you end the leftover `ssh -N` processes. -Tunnels ask for passwords in the active window like tabs do (with `askpass` on), use `keep_alive_secs` -(30 seconds when it is 0), exit as soon as their forward can't be set up (`ExitOnForwardFailure`), -and never share a connection through `ControlMaster`, so stopping one really closes it. +Tunnels ask for passwords in the active window (with `askpass` on), use `keep_alive_secs` (30 +seconds when it is 0), exit as soon as their forward can't be set up (`ExitOnForwardFailure`), and +never share a connection through `ControlMaster`, so stopping one really closes it. *Browse Files…* connects the same way: its ssh runs the host's `sftp` subsystem, asks for passwords in the active window, uses `keep_alive_secs` (30 seconds when it is 0) and leaves out @@ -292,8 +294,9 @@ never ask, and they skip keyboard-interactive logins such as one-time codes. This needs OpenSSH 8.4 or newer (`SSH_ASKPASS_REQUIRE`). Older clients, among them the OpenSSH 8.1 that ships with Windows 10, keep prompting in the terminal and background connections need key or agent authentication; install a newer Win32-OpenSSH release and point `program` at it -to get the dialogs. Only `ssh` processes RedShell starts for a host get the askpass setting: `ssh` or `git` run inside a local shell keep -prompting in the terminal. `askpass = false` turns all of this off. +to get the dialogs. Only `ssh` processes RedShell starts for a host get the askpass setting: +`ssh` or `git` run inside a local shell keep prompting in the terminal. `askpass = false` turns +all of this off. ## `[agents]` @@ -336,6 +339,37 @@ whatever this setting says, and also reports when you are up to date or the chec Releases are compared by version (`v0.0.10` is newer than `v0.0.9`). A pre-release tag such as `v0.1.0-beta.1` is only offered to builds that are pre-releases themselves. +## `[remote]` + +The RedShell servers this computer opens sessions of. *Settings → Servers* adds and removes +them; see [REMOTE.md](REMOTE.md#the-desktop). + +```toml +[[remote.servers]] +name = "Pi" +url = "https://box.tailnet.ts.net" +``` + +| Key | Notes | +|---|---| +| `name` | What the sidebar and the tabs call it. | +| `url` | The address you open RedShell Remote at. Plain `http://` works only for a server on this computer. | + +The device token of each server is kept in the system keychain, not here. + +## `[server]` + +Read only by `redshell-server` from its own config directory; the desktop ignores it. See +[REMOTE.md](REMOTE.md#configuration) for running the server. + +| Key | Default | Notes | +|---|---|---| +| `listen` | `"127.0.0.1:4747"` | Address and port. A non-loopback address is refused unless `tls_cert` and `tls_key` are set. | +| `public_url` | none | The https origin clients open, such as `https://box.tailnet.ts.net`. The setup and pairing links use it, passkeys need it, and when it is https, browsers may send changes from this origin only and the server sends HSTS. | +| `tls_cert`, `tls_key` | none | PEM certificate chain and private key for built-in TLS. | +| `trusted_proxies` | `[]` | Peer IP addresses whose `X-Forwarded-For` names the real client, for the sign-in backoff and the audit log. When it is empty, `public_url` is https and `listen` is loopback without TLS of its own, the server trusts `127.0.0.1` and `::1` (a TLS proxy on the same machine, such as Tailscale Serve or cloudflared). | +| `approval_timeout_secs` | `600` | How long an agent's permission request waits for an answer before the agent asks in its own terminal. | + ## `[keybindings]` Keys use GPUI's syntax: `ctrl-shift-t`, `ctrl-alt-1`, `f11`, or `ctrl-k ctrl-t` for a chord. The value is diff --git a/docs/REMOTE.md b/docs/REMOTE.md new file mode 100644 index 0000000..0084d5f --- /dev/null +++ b/docs/REMOTE.md @@ -0,0 +1,575 @@ +# RedShell Server + +`redshell-server` is RedShell without a window. It runs terminal sessions (shells, coding agents +such as Claude Code and Codex, SSH hosts) on an always-on machine, a Raspberry Pi for example, +and keeps them running whether or not anyone is connected. The desktop RedShell opens them as +tabs, and phones use RedShell Remote, the web app the server serves. The design behind it is in +[design/remote-server.md](design/remote-server.md). + +A session is a terminal started from a profile: the server's default shell (`shell`), an agent +found on its `PATH` or in `[[agents.custom]]` (`agent:claude`), one of its SSH hosts +(`ssh:prod`), or a command line in a folder. Sessions +run as the server's user and keep running when every client is gone; one whose program exits +keeps its final screen until it is killed. They live as long as the server process does, so +stopping or restarting the server ends them all. + +Every client shows the same screen. A session has the size of the client that typed into it +last, as with tmux's `window-size latest`; the first client to attach sizes it until someone +types, and the others show it at that size. Full-screen programs redraw when a new client changes +the size. + +## Install + +Every [release](https://github.com/redstone-md/RedShell/releases) carries `redshell-server` for +Linux on x86_64 and on aarch64 (64-bit Raspberry Pi OS), each as a `.deb` and a `.tar.gz`, and +for macOS as a universal `.tar.gz`, with RedShell Remote built into the binary. The Linux builds +need glibc 2.35 or newer, which Debian 12, Ubuntu 22.04 and later have. + +### Debian package + +```sh +sudo apt install ./redshell-server--linux-aarch64.deb +sudo systemctl enable --now redshell-server@$USER +sudo journalctl -u redshell-server@$USER # the setup link of the first start +``` + +The package installs `/usr/bin/redshell-server` and the systemd unit `redshell-server@.service`, +and starts nothing by itself. The unit runs the server as the user named after the `@`, in that +user's home folder, so sessions see their files, SSH keys and agent sign-ins, and the server +keeps its state in their `~/.config/redshell-server`. Upgrading the package restarts the +instances that are running, which ends their sessions. + +### Tarball + +The `.tar.gz` holds the binary, the same unit file, and this document with the changelog and the +licence. On Linux, the unit expects the binary at `/usr/bin/redshell-server`: + +```sh +sudo install -m 755 redshell-server /usr/bin/redshell-server +sudo install -m 644 redshell-server@.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now redshell-server@$USER +``` + +On macOS, or to try it out, run `./redshell-server` in a terminal; Ctrl+C stops it and its +sessions. + +### From source + +```sh +(cd web && npm ci && npm run build) +cargo build --release -p redshell-server +./target/release/redshell-server # same as `redshell-server serve` +``` + +RedShell Remote is embedded in the binary at build time from `web/dist`. Without it the server +serves a page that says so, and the API works as usual. When `web/dist` appears after the server +was built, run `cargo clean -p redshell-server` once so the next build embeds it; later builds of +the web app are picked up by themselves. + +## First start + +The server keeps everything in its config directory, which it makes private (0700): `--config +` or `REDSHELL_SERVER_CONFIG`, by default `~/.config/redshell-server` on Linux and +`~/Library/Application Support/redshell-server` on macOS. + +| Path | What | +|---|---| +| `config.toml` | The desktop's configuration format with an extra `[server]` section. Written with comments on the first start. | +| `server.sqlite3` | Accounts, passkeys, sign-ins, push subscriptions and the VAPID key, the audit log and which sessions ran. | +| `run/` | Files that only live while the server runs, such as agent hook settings. | +| `shell-integration/` | The scripts that report a shell's folder and prompts. | + +While there is no account, the server logs a one-time setup link that is valid for 30 minutes: + +``` +No account exists yet. Create the first one within 30 minutes at: + + https://box.tailnet.ts.net/setup?code=… +``` + +Open it, choose a name and a password of at least 10 characters, and that browser is signed in. +The link starts with `public_url` when it is set and with the listening address otherwise, so +set up how you reach the server (below) and restart it before you open the link; each start logs +a new one. Once a link has expired, the +server logs a new one the next time RedShell Remote asks whether setup is needed. You can also +create the account from a shell with `redshell-server user add `. + +### Command line + +``` +redshell-server [--config ] [serve] +redshell-server user add [--password-stdin] +redshell-server user passwd [--password-stdin] [--revoke-passkeys] +redshell-server user remove +redshell-server user reset-passkeys +redshell-server user list +``` + +The `user` commands write to the database directly, so they also work while the server runs. +`--password-stdin` reads the password from the first line of standard input, for scripts. +`user passwd` signs the user out everywhere and lists the passkeys they keep, which still sign +in; `--revoke-passkeys` removes those too and turns passkey-only sign-in off, for a reset after a +lost device or a takeover. `user reset-passkeys` removes a user's passkeys and turns passkey-only +off, so their password works again. + +### Configuration + +The server reads `config.toml` as the desktop does: `[terminal]` (shell, environment, +scrollback), `[ssh]` (hosts, `~/.ssh/config`) and `[agents]` (extra arguments, custom agents) +mean the same thing (see [CONFIG.md](CONFIG.md)). Unlike the desktop, a file that does not parse +stops the server, and the server reads the file when it starts: restart it after you edit the +file by hand (`sudo systemctl restart redshell-server@$USER`), which ends its sessions. Changes +made through the hosts API apply at once. The `[server]` keys: + +| Key | Default | Notes | +|---|---|---| +| `listen` | `"127.0.0.1:4747"` | Address and port. A non-loopback address is refused unless `tls_cert` and `tls_key` are set. | +| `public_url` | none | The https origin clients open, such as `https://box.tailnet.ts.net`. The setup and pairing links use it, passkeys need it, and when it is https, browsers may send changes from this origin only and the server sends HSTS. | +| `tls_cert`, `tls_key` | none | PEM certificate chain and private key for built-in TLS (rustls). | +| `trusted_proxies` | `[]` | Peer IP addresses whose `X-Forwarded-For` names the real client, for the sign-in backoff and the audit log. When it is empty, `public_url` is https and `listen` is loopback without TLS of its own, the server trusts `127.0.0.1` and `::1` (a TLS proxy on the same machine) and logs that it does. | +| `approval_timeout_secs` | `600` | How long an agent's permission request waits for an answer before the agent asks in its own terminal. | + +## Reaching it + +Keep the server on loopback and put a TLS proxy in front of it. HTTPS is not optional in +practice: passkeys and Web Push only work in a secure context, the session cookie is `Secure`, +and a desktop's device token would otherwise cross the network in the clear. + +### Tailscale Serve (recommended) + +Tailscale gives the machine a name and a certificate inside your tailnet, and nothing is exposed +to the internet: + +```sh +tailscale serve --bg 4747 +``` + +That proxies `https://..ts.net` to `http://127.0.0.1:4747`. Tell the server +about it in `config.toml`: + +```toml +[server] +listen = "127.0.0.1:4747" +public_url = "https://box.tailnet.ts.net" +``` + +and restart the server. Every client now arrives from the proxy on loopback, so the server trusts `X-Forwarded-For` from +`127.0.0.1` and `::1` and says so in its log; otherwise one client failing to sign in would slow +down sign-ins for everyone. Set `trusted_proxies` to the proxy's address when clients can reach +the port some other way. + +That is all passkeys and push notifications need: `public_url` is https, and its host +(`box.tailnet.ts.net`) becomes the passkeys' relying party. From there, a complete setup is: + +1. Start the server and open the setup link from its log on your phone, over the tailnet. +2. Under the account, add a passkey, and add a second one from your computer or a security key so + losing the phone does not lock you out ([Passkeys](#passkeys)). +3. Add RedShell Remote to the home screen and turn on notifications ([The phone](#the-phone)). +4. On the desktop, add the server under *Settings → Servers* and sign in, or pair it from the + phone ([The desktop](#the-desktop)). + +### Cloudflare named tunnel + +A named tunnel publishes the server on a hostname of a domain you have on Cloudflare, with no +open port at home: + +```sh +cloudflared tunnel login +cloudflared tunnel create redshell +cloudflared tunnel route dns redshell shell.example.com +``` + +`~/.cloudflared/config.yml`: + +```yaml +tunnel: redshell +credentials-file: /home/pi/.cloudflared/.json +ingress: + - hostname: shell.example.com + service: http://127.0.0.1:4747 + - service: http_status:404 +``` + +Run `cloudflared tunnel run redshell` (or install it as a service), set +`public_url = "https://shell.example.com"` and restart the server; as with Tailscale, it then +trusts the proxy on loopback. Cloudflare terminates TLS, so it sees the traffic; putting Cloudflare Access in front +adds a second sign-in. + +### Built-in TLS + +With a certificate of your own, the server can listen on the network directly: + +```toml +[server] +listen = "0.0.0.0:443" +public_url = "https://shell.example.com" +tls_cert = "/etc/redshell-server/fullchain.pem" +tls_key = "/etc/redshell-server/privkey.pem" +``` + +Built-in TLS speaks HTTP/1.1 only. Keep `public_url` set: passkeys need it. + +## Passkeys + +Passkeys sign in with Face ID, Touch ID, Windows Hello, an Android screen lock or a security key, +with nothing to type and nothing to phish. They need `public_url` over https (or +`http://localhost` while developing); without it the passkey endpoints answer `unavailable`, +`/api/auth/info` reports `passkeys: false`, and RedShell Remote leaves passkeys out and says why. +The host of `public_url` is the relying party, so a passkey works for that address only: keep +`public_url` when you move the server, since a new host name needs new passkeys. + +Add passkeys under the account while signed in, and name each one; the list shows when each was +last used, and each can be renamed or revoked. Registration asks for a discoverable passkey, so +*Sign in with a passkey* needs no name: the authenticator says whose it is. A desktop can sign in +with a passkey too, or be paired from a browser that signed in with one. + +A ceremony lasts five minutes and can be finished once. Starting a sign-in needs no account, so +it stores nothing that strangers could use up: its state travels in the ceremony id, signed with +a key the server makes at start, and only finished sign-ins are remembered until they expire. A +registration's state stays on the server and can only be finished by the browser or device that +started it; when every place is taken, the oldest goes. Failed passkey sign-ins count against the +address like wrong passwords; starting one is free. + +Adding or removing a passkey and turning passkey-only on or off need a recent re-authentication +(see the [security model](#security-model)). + +**Passkey-only.** With at least one passkey, a user can turn password sign-in off. That ends +their sign-ins made with the password and the devices paired from one. From then on the right +password is answered with +`passkey_required` (a wrong one still with `invalid_credentials`, so strangers learn nothing, and +both count against the backoff), the password no longer re-authenticates, and revoking the last +passkey is refused until passkey-only is turned off, so nobody locks themselves out by accident. +Someone who lost every passkey gets their password back with +`redshell-server user reset-passkeys ` on the server. + +## The desktop + +The desktop RedShell lists its servers in `config.toml` under `[remote]` (see +[CONFIG.md](CONFIG.md#remote)) and manages them under *Settings → Servers*: add one by the +address you open RedShell Remote at, sign in, sign out and remove it. Each server shows where it +stands: connected (and as whom), signed out, unreachable, or running another protocol version, +which means one of the two needs an update. An address is `https://` unless it is on this +computer: plain `http://` is refused for any other host, since the password and the device token +would cross the network in the clear. + +Signing in gives this computer its own device token, which it keeps in the system keychain (the +macOS Keychain, Windows Credential Manager, the Secret Service on Linux), never in +`config.toml`; without a working keychain the token lasts until RedShell quits. The token shows +under the account as *RedShell on* the computer's name and can be revoked there, which signs the +device out at once. *Sign out* revokes the token on the server too, and says so when the server +could not be told. + +A connected server has a section in the sidebar (`servers` in `appearance.sidebar_sections`, +turned on when you add the first server) listing its sessions with what their agents are doing: +*needs approval*, *needs input*, *working*, *finished* or *exited*. "+" starts a session from the +server's profiles (its shells, agents and SSH hosts), and a session's menu opens, renames or +kills it. A session opens as a tab of its own, once in the whole app: + +- Its screen comes from the server, which sizes it for the device that typed last, so it looks + the same on every device attached to it. +- Closing the tab only detaches; the session keeps running on the server. *Kill* stops it for + every device. +- An agent's pending approval stands above its terminal with *Allow*, *Deny* and *Answer in + terminal*, and a session in another tab that asks for approval or input raises a notice with + *Open*. A server that cannot be reached shows above its tabs while RedShell reconnects; the tabs + come back with their screens as soon as it is reachable again. +- Tabs of server sessions come back on the next start like any other (with + `history.restore_tabs`) and attach to their session again; one whose session is gone closes and + says so. + +The connection is one WebSocket per server, which reconnects by itself with a growing, jittered +delay of up to ten seconds. + +*Send to Server* in an SSH host's menu copies the host to a server as the desktop connects to it, +without its identity file (a path on the desktop; the server connects with its own keys), and +asks before replacing a host of that name. + +### Pairing + +Instead of typing a password into the desktop, you can approve it from a browser that is signed +in already, with a passkey for example: + +1. Under *Settings → Servers*, choose *Sign in with the browser instead*. The desktop asks the + server for a pairing request (`POST /api/pair` with its name and system), shows the short code + it gets, such as `KX7-4MP`, and opens `/pair`. +2. In the browser, type that code. The page shows the device's name (as the device calls itself) + and system, the address the request came from and whether that is your own address, and you + approve or reject it. Approving needs a recent re-authentication. +3. The desktop polls its request with a secret only it holds and receives its device token, once. + The device then shows under the account like any other. + +The code is only ever typed: the pairing page has no link that fills it in, and the server refuses +a code that comes with a query string, so a request someone else started cannot be approved by +clicking a link. Someone can still send you a code and ask you to type it, which is why the page +warns that approving signs that device in as you, and says when the request came from somewhere +else. A request expires after 10 minutes. At most 64 requests wait at once and 4 per address (an +IPv6 /64), and past either limit a new one pushes out the oldest unanswered one. Starting, +polling and typing codes are rate-limited, and wrong codes slow down that user's further attempts. +The token is handed out only while the sign-in that approved it holds, and a password change +drops the approvals still waiting for their device. Requests, approvals, rejections and collected +tokens are in the audit log. + +## The phone + +RedShell Remote is the web app the server serves at `public_url`, made for a phone and laid out +in two columns on a wide screen. Its inbox puts the sessions that need you first, with what each +agent is doing; a session opens as a full terminal with a key bar and a composer for typing on a +phone, and a permission request opens as a sheet with the command or the diff. New sessions start +from the server's profiles in any folder, and the settings hold the server's SSH hosts with their +port forwards, agent forwarding and startup command, your passkeys, browsers and devices, desktop +pairing and notifications. + +Install it from the browser: on iPhone and iPad, Safari's *Share → Add to Home Screen*; on +Android and desktop browsers, the browser's install option. Installed, it opens without the +browser's chrome, and its icon shows how many sessions need you where the system shows badges. + +### Notifications + +RedShell Remote can be told about a session while it is closed, through Web Push: when an agent +asks for approval or waits for input, when it finishes its turn, when a program exits with an +error, and when a program raises a notification (OSC 9 / 777). Each browser turns notifications +on for itself and chooses which of these it gets. On iPhone and iPad, notifications only work +once RedShell Remote is on the Home Screen, and like passkeys they need the app opened over https. + +Nobody is sent a message about a session they typed into, from any device, in the last 30 +seconds: they are looking at it. A message carries a short title and body and a link to the +session (`/s/`); a newer one about the same session replaces the older notification. A +program's own notifications are pushed at most once every 10 seconds per session, so one that +prints OSC 9 in a loop cannot flood a phone. + +The server makes its VAPID key on the first start and keeps it in its database. Messages are +encrypted for the browser (RFC 8291) in pure Rust, without OpenSSL. A subscription belongs to its +browser session and goes when that signs out; one its push service no longer knows is dropped. + +A push endpoint comes from the browser, so the server treats it as input: it posts only to +`https` on port 443, to a host name that resolves to public addresses only (never loopback, +private, link-local, CGNAT or tailnet addresses, nor IPv6 ranges that lead to IPv4 ones: 6to4, +Teredo, NAT64; checked again on every send), with redirects and proxies off. Failures are logged +without the endpoint, a test message answers only whether it was taken, and an endpoint stays +with the account that subscribed it. + +## Agents and approvals + +The server knows what Claude Code and Codex are doing through their own extension points, so +sessions stay the real terminal programs the desktop shows. + +- **Claude Code** starts with `--settings `, a 0600 file in `run/` that adds HTTP hooks for + PermissionRequest, PostToolUse, PostToolUseFailure, Notification, Stop and UserPromptSubmit. + Your own settings and hooks still apply; these are added to them. +- **Codex** starts with `-c notify=["", "hook", "codex"]`. After each turn Codex + runs it with a JSON payload, which it posts to the server. That override replaces a `notify` + set in your own `~/.codex/config.toml` (or `$CODEX_HOME/config.toml`), so the hook runs your + program afterwards with the same payload. +- **Any program** can raise a notification with OSC 9 (`ESC ] 9 ; text BEL`), OSC 777 + (`ESC ] 777 ; notify ; title ; body BEL`) or the bell. + +Agent states: `idle` (started), `working`, `needs_approval`, `needs_input` (Claude Code's idle and +question prompts) and `finished` (with the last message). + +A permission request is held open and shown to every client subscribed to events. Claude Code +shows its own dialog at the same time, and the first answer wins: *allow*, *allow always* +(applies the rules Claude Code suggested), *deny*, or *answer in terminal* (no decision, so +Claude Code's dialog decides). Who answered is shown with the result: a device's name, a +browser's name such as `Safari on iPhone`, or `terminal`. When the user answers in Claude Code's +dialog, Claude Code does not close the server's request, so later hooks settle it as answered in +the terminal: PostToolUse or PostToolUseFailure for the same call (same tool and input) settles +that request, and UserPromptSubmit and Stop settle every request of the session. Another +PermissionRequest settles nothing, since Claude Code asks for parallel calls one after another. +After `approval_timeout_secs` a request is settled with no decision. + +Hooks post to a second listener bound to 127.0.0.1 on a random port, which is never part of the +public listener. Every hook URL carries the session id and a random per-session token; for Codex +the URL travels in the session's environment (`REDSHELL_HOOK_URL`), not on a command line that +every user of the machine can read. The token is checked before a hook's body is read, and a body +is at most 1 MiB: a bigger PostToolUse is refused, and a request it would have settled is settled +by the agent's next prompt or stop. + +## Security model + +- No default account and no default password; the first account comes from the setup link in the + log, or from the `user` command. +- Passwords are Argon2id hashes and need at least 10 characters; nothing else is enforced. + Sign-in has the same error, and takes the same time, for an unknown name and a wrong password. + After 3 failures per client address (an IPv6 /64) and per name, each attempt waits 1 s, 2 s, + 4 s, … after the last failure, up to 15 minutes for an address and 2 minutes for a name. + Anyone who knows a name can earn its backoff and lock its owner out, so that one stays short, + while guesses spread over many addresses still meet it. Every attempt is in the audit log; + throttled ones are logged at most once a minute. A name longer than 64 characters is refused + before anything records it, and password checks run one at a time, sign-ins apart from + signed-in users, with at most 16 waiting before more are answered `rate_limited`. +- A signed-in browser or device re-authenticates before a change that could hand the account to + whoever holds a stolen or forgotten session: adding or removing a passkey, turning passkey-only + on or off, approving a pairing, signing out another browser or device, and changing the password + of a passkey-only account (other accounts give the current password). Signing in with a password + or passkey counts, and `POST /api/auth/reauth` does it again. It holds for five minutes; + otherwise these answer `reauth_required` (403). A paired device starts without one. +- Tokens are 256-bit random values, and the database keeps only their SHA-256. Ids of accounts, + browser sessions and devices are never used twice, and an open WebSocket stays open only while + its own token is valid. +- Browsers get a `__Host-redshell-session` cookie (HttpOnly, Secure, SameSite=Strict) that lasts + 30 days from its last use; other clients get a named bearer device token, which does not + expire. Both are listed under the account, a browser named after its User-Agent + (`Safari on iPhone`), with when and from where it was last used (refreshed hourly, also while a + WebSocket stays open), and can be revoked. Revoking one, signing out, and changing the password + (which signs out everything else) close its open WebSockets at once; changes made with the + `user` command, and a cookie that expires, close them within 30 seconds. +- A state-changing request (any method but GET, HEAD and OPTIONS) and the WebSocket upgrade are + refused when they carry an `Origin` other than the server's own: exactly `public_url` when it + is https; otherwise `public_url`, or `https://` when there is none, and `http://` + only for a loopback host on a server without TLS of its own. A request with the session cookie + and no `Origin` is refused too. Clients that are not browsers send no `Origin` and use bearer + tokens. +- Every state-changing `/api` request carries the header `X-RedShell: 1`, from every client. A + page of another site cannot add it without a CORS preflight, which the server never answers. +- Bodies are at most 16 KiB on endpoints that need no sign-in and 64 KiB on the others (1 MiB for + agent hooks, whose token is checked first). A client gets 10 seconds for a request's headers, + also between requests on a kept-alive connection, and 10 for a TLS handshake; at most 256 + connections are open at once, WebSockets included. +- Every `/api` endpoint needs a sign-in except `/api/auth/info`, `/api/auth/sign-in`, + `/api/auth/passkey/*`, `/api/setup`, and starting and polling a pairing request. Responses never + include password or token hashes. The log carries no command lines of sessions (their record in + the database does), and the audit log is pruned of entries older than 180 days at start and + then daily, as entries are written. +- Every response carries `Content-Security-Policy` (below), `X-Frame-Options: DENY`, + `Referrer-Policy: no-referrer` and `X-Content-Type-Options: nosniff`, plus HSTS for a year when + clients reach the server over https (built-in TLS or an https `public_url`). HSTS leaves out + `includeSubDomains`: the server's name is often one of many under a domain it does not own, such + as a tailnet's, whose other hosts may still serve plain http. + + ``` + default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; + font-src 'self' data:; connect-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; + base-uri 'none'; frame-ancestors 'none'; form-action 'self' + ``` + +- Every user of a server is trusted with all of its sessions: there is no isolation between + users, and sessions run as the server's user. + +## Protocol + +The wire types are in the `redshell-protocol` crate; its tests generate the TypeScript definitions +in `web/src/protocol/` (`index.ts` re-exports them with `PROTOCOL_VERSION`). JSON uses +`snake_case`, tagged unions carry a `type` field, and times are Unix milliseconds. Errors are an +`ApiError` (`{code, message, retry_after_secs?}`) with a matching status. `GET /api/auth/info` +reports the server's `protocol_version`, which goes up when a change would break an older client; +version 2 requires `X-RedShell: 1` on every state-changing request. + +### REST + +| Method and path | Body → response | +|---|---| +| `GET /api/auth/info` | → `ServerInfo`: version, protocol version, whether setup is needed, the password minimum, whether passkeys are offered | +| `POST /api/setup` | `SetupRequest` → `SignInResponse`, sets the cookie | +| `POST /api/auth/sign-in` | `SignInRequest` → `SignInResponse`: a cookie, or with `device_name` a `device_token` | +| `POST /api/auth/passkey/begin` | → `PasskeyChallenge` for `navigator.credentials.get()` (open) | +| `POST /api/auth/passkey/finish` | `PasskeySignInRequest` → `SignInResponse`: a cookie, or with `device_name` a `device_token` (open) | +| `POST /api/auth/sign-out` | → `{}`, revokes this cookie or token | +| `POST /api/auth/reauth` | `ReauthRequest` (`{method: "password", password}` or `{method: "passkey", ceremony, credential}`) → `ReauthResponse` | +| `POST /api/auth/reauth/passkey/begin` | → `PasskeyChallenge` for `navigator.credentials.get()`, with the user's passkeys | +| `GET /api/auth/me` | → `User` | +| `GET /api/account` | → `Account`: the user, passkey-only, how many passkeys, whether passkeys are offered, until when the last re-authentication holds | +| `POST /api/account/password` | `ChangePasswordRequest` → `{}` | +| `GET /api/account/passkeys` | → `Passkey[]` | +| `POST /api/account/passkeys/begin` | → `PasskeyChallenge` for `navigator.credentials.create()` | +| `POST /api/account/passkeys/finish` | `RegisterPasskeyRequest` → `Passkey` | +| `PATCH /api/account/passkeys/{id}` | `RenamePasskeyRequest` → `Passkey` | +| `DELETE /api/account/passkeys/{id}` | → `{}` | +| `PUT /api/account/passkey-only` | `PasskeyOnlyRequest` → `Account` | +| `GET /api/account/devices` | → `Device[]` | +| `DELETE /api/account/devices/{id}` | → `{}` | +| `GET /api/account/sessions` | → `BrowserSession[]` | +| `DELETE /api/account/sessions/{id}` | → `{}` | +| `GET /api/profiles` | → `Profile[]` | +| `GET /api/sessions` | → `SessionInfo[]` | +| `POST /api/sessions` | `CreateSessionRequest` → `SessionInfo` | +| `PATCH /api/sessions/{id}` | `RenameSessionRequest` → `SessionInfo` | +| `DELETE /api/sessions/{id}` | → `{}`, kills it | +| `GET /api/approvals` | → `Approval[]` waiting for an answer | +| `POST /api/approvals/{id}` | `ApprovalAnswer` → `{}` | +| `GET /api/fs/folders?path=` | → `FolderListing`: up to 200 subfolders, for path completion | +| `POST /api/pair` | `PairRequest` → `PairStarted` (open, rate-limited) | +| `GET /api/pair/{id}` | with `Authorization: Bearer ` → `PairStatus` (open) | +| `GET /api/pair/{code}` | → `PairingInfo`: the waiting request a typed code names, and whether it came from the caller's address | +| `POST /api/pair/{code}/approve`, `/reject` | → `PairingInfo` (approving needs a recent re-authentication) | +| `GET /api/push/key` | → `PushKey`: the VAPID key to subscribe with | +| `GET /api/push/subscriptions` | → `PushSubscriptionInfo[]`: the user's subscriptions | +| `POST /api/push/subscriptions` | `PushSubscribeRequest` → `{}`: subscribes this browser | +| `PUT /api/push/subscriptions` | `PushEventsRequest` → `{}`: what a subscription is sent | +| `DELETE /api/push/subscriptions` | `PushEndpoint` → `{}` | +| `POST /api/push/test` | `PushEndpoint` → `{}` once the push service took a test message | +| `GET /api/hosts` | → `SshHost[]`: saved hosts (`origin: "redshell"`), then those only in `~/.ssh/config` (`"ssh_config"`) | +| `POST /api/hosts` | `SshHost` → `SshHost` (201) | +| `PUT /api/hosts/{name}` | `SshHost` → `SshHost`: saves over `name`, renaming it if the body says so | +| `DELETE /api/hosts/{name}` | → `{}` | +| `GET /api/ws` | WebSocket upgrade | + +### SSH hosts + +The hosts API reads and writes the server's `[[ssh.hosts]]` in `config.toml` in place: comments +and the rest of the file stay as they are, and new sessions and `GET /api/profiles` use a change +at once. Each edit starts from the file as it is on disk, so changes made to the file by hand +since the server started apply too, and a file that does not load is never written. + +`SshHost` has no field for a secret, and a body with a field it does not have is refused. A host +is checked by the same rules as in the desktop's host editor (`redshell_core::settings::ssh`): a +unique name that does not start with `-`, an address that does not start with `-` (or none when +the name is a `~/.ssh/config` alias), a port from 1 to 65535, no control characters, a startup +command that does not start with `-` and closes its quotes, and port forwards with their ports, a +target unless they are SOCKS proxies, plain addresses, and a listening port no other forward of +the host takes. Names and addresses are at most 255 characters, paths, arguments and the startup +command at most 4,096, and lists at most 64 entries. Saving a host that is only in the server +user's `~/.ssh/config` (`PUT` under its own name) writes an entry with the fields that differ, +which ssh layers over the file's own. The audit log keeps a saved host's extra arguments and +startup command in full. + +### WebSocket + +One connection per client at `/api/ws`. Text frames are JSON, binary frames are terminal bytes: +two bytes of channel number (big-endian), then the bytes. + +Client → server (`ClientMessage`): + +| `type` | Fields | | +|---|---|---| +| `attach` | `session, cols, rows` | Answered by `attached`, then output frames. | +| `detach` | `channel` | Answered by `detached`. | +| `resize` | `channel, cols, rows` | The client's terminal size. | +| `input` | `channel, data` | Keys and pastes as text; binary frames carry any bytes. | +| `rename` | `session, name` | | +| `subscribe` | `sessions, events` | Session list and agent activity; replaces the last choice. | +| `approve` | `approval, decision, message?` | `allow`, `allow_always`, `deny`, `terminal`. | + +Server → client (`ServerMessage`): `hello` (first, with the user), `attached` (channel, session, +snapshot), `snapshot` (a resync), `resized`, `detached`, `sessions` / `session_updated` / +`session_removed`, `approvals` / `approval_requested` / `approval_resolved` (with who answered), +`event` (approval requested, needs input, finished, notification, bell, exited) and `error`. + +On `attached` and `snapshot`, reset the terminal, size it to `snapshot.cols` × `snapshot.rows` and +write `snapshot.data`; then write each output frame as it comes. The server's terminal answers the +program's queries (device attributes, cursor position, colours), so a client must not forward the +replies its own terminal emulator generates while drawing. + +A snapshot is the screen and up to 2,000 lines of scrollback as ANSI text, followed by the state +a program set that the cells do not show: cursor position and pen, application cursor and keypad, +bracketed paste, mouse reporting and its encoding, focus reporting, cursor visibility and shape, +and the title. It is cut exactly where the live stream continues, so no output is lost or +repeated. Not carried: a scroll region, saved cursors and character sets, and, while a full-screen +program uses the alternate screen, the normal screen behind it; a client that joined while the +alternate screen was up therefore gets a fresh `snapshot` when the program leaves it. A client +that cannot keep up never slows the program or the other clients: each client has a small queue, +and when it is full that client's output is dropped and it gets a fresh `snapshot` once it catches +up. + +The server pings every 30 seconds; a revoked credential's socket is closed with code 4001. + +## Resource use + +An idle server does no work: there are no timers while nothing happens, besides a WebSocket ping +every 30 seconds per connected client. Each session costs a PTY reader thread and a small event +thread, plus its scrollback. Output to a client is queued at most 32 chunks deep on each side of +the socket, and input waiting for a program that does not read it at most 4 MiB (more is refused +with an `error`). Measured on Linux x86_64 (release build): 8.8 MB resident at start, most of it +the binary's own pages, 11.5 MB with five idle shell sessions, and no CPU time at all over 15 idle +seconds. Each password check briefly takes 19 MiB for Argon2, which goes back to the OS +afterwards. diff --git a/docs/design/remote-pwa-visual.md b/docs/design/remote-pwa-visual.md index ed739c8..4392f3b 100644 --- a/docs/design/remote-pwa-visual.md +++ b/docs/design/remote-pwa-visual.md @@ -69,7 +69,7 @@ There is no fainter text tier. Anything quieter than `--muted-foreground` fails - the single primary action on a screen, including the composer's send button; - the terminal cursor; - the focus ring; -- the 2px edge of the selected session in the wide layout, as on the desktop. +- the 2px edge of the selected row (a session, or the current footer row) in the wide layout, as on the desktop. Everything else that marks "on" or "selected" (switches, checkmarks, the latched Ctrl key, the selected segment) uses `--foreground`. @@ -114,8 +114,8 @@ Code text on both tints stays `--foreground` (15:1). - selection `--primary` at 28%. **Scrims:** -- **Under sheets:** black 55% (dark) and `rgb(10 10 18 / 30%)` (light). The terminal behind stays legible as context. -- **Under centred dialogs:** the desktop's values, black 72% and `rgb(10 10 18 / 45%)`. +- **Under sheets:** black 55% (dark) and `rgb(23 15 16 / 30%)` (light, the warm near-black of `--foreground`). The terminal behind stays legible as context. +- **Under centred dialogs:** black 72% (dark, the desktop's value) and `rgb(23 15 16 / 45%)` (light). ### 1.3 Type @@ -183,8 +183,10 @@ Elevation is hairlines first, shadow only where something floats over the termin |---|---|---|---| | 0 | Page, terminal, header | `--background`, no shadow | same | | 1 | List groups | `--card` + 1px `--border` | same | -| 2 | Sheets, menus, dialogs | `--popover` + 1px `--border` + scrim, no shadow | adds `0 -8px 32px rgb(23 15 16 / 10%)` for sheets and `0 8px 24px rgb(23 15 16 / 12%)` for menus | -| 3 | Toasts, banners | `--popover` + 1px `--border` + `0 8px 24px rgb(0 0 0 / 50%)` | `0 4px 16px rgb(23 15 16 / 12%)` | +| 2 | Sheets, dialogs | `--popover` + 1px `--border` + scrim, no shadow | adds `0 -8px 32px rgb(23 15 16 / 10%)` for sheets and `0 8px 24px rgb(23 15 16 / 12%)` for dialogs | +| 3 | Toasts, banners, menus | `--popover` + 1px `--border` + `0 8px 24px rgb(0 0 0 / 50%)` | `0 4px 16px rgb(23 15 16 / 12%)` | + +Menus float over the page without a scrim, so they take the level-3 shadow to separate from the rows beneath them in the dark theme. The header gets its bottom hairline only once content has scrolled under it. @@ -292,26 +294,31 @@ The header gets its bottom hairline only once content has scrolled under it. - **Shape:** 48px tall, `--muted` fill, 1px `--field-border` outline, `--radius-lg`, 12px horizontal padding, `--text-body`. - **Label:** above the field in `--text-footnote` 500. - **Helper or error:** below the field in `--text-footnote`. Errors are `--destructive` with a 14px `circle-alert` icon, and `aria-describedby` links them to the field. +- **Inline errors everywhere** (under a field, above a sheet's actions, in a dialog) use that same form: the 14px `circle-alert`, `--text-footnote` `--destructive`, and a sentence that ends with a period ("Username or password is incorrect."). - **Focus:** a 1px `--ring` border plus the ring. Mono values (host, path) use `--mono-body` at 16px. - **Passwords:** a 44px eye toggle sits inside the field on the right. +- **Gutters:** forms of stacked fields keep everything on the 16px screen gutter: body text, labels, inputs and errors. Only section headers and footnotes of inset groups sit at 20px. + +**Field row.** Forms with many short values (an SSH host, a port forward) use inline rows inside a group instead of stacked fields: a 48px row with the label on the left in `--text-body` and the value as a right-aligned input, as a read-only row shows it, with a placeholder that shows the kind of value expected ("prod-api", "10.0.4.12", "22"). The row tints `--accent` while its field has focus. Helpers and errors go under the group as a footnote, linked with `aria-describedby`. **Switch.** The native `` where supported, otherwise a styled checkbox: - 51×31px, with a 27px thumb; - when on, the track is `--foreground` and the thumb is `--background`; -- when off, the track is `--secondary` with a 1px `--field-border` and the thumb is `--muted-foreground`; +- when off, the track is `--secondary` with a 1px `--field-border`; the thumb is `--muted-foreground` on dark, and on light it is white with a 1px `--field-border` and `0 1px 2px rgb(23 15 16 / 20%)`, so it reads on the pale track; - the whole row is the target. ### 3.3 Segmented control - 44px tall, `--secondary` track, `--radius-lg`, 2px inner padding. -- The selected segment is `--popover` with 1px `--border` (dark) or `#fff` with `0 1px 2px rgb(23 15 16 / 10%)` (light). Its label is `--foreground` 500; the others are `--muted-foreground`. +- The selected segment is `color-mix(in oklch, var(--foreground) 12%, var(--secondary))` with 1px `--border` (dark: lighter than the track, so it reads as raised, not pressed in) or `#fff` with `0 1px 2px rgb(23 15 16 / 10%)` (light). Its label is `--foreground` 500; the others are `--muted-foreground`. - The selection slides 200ms `--ease-out`, or switches instantly under reduced motion. - It is a `radiogroup`, and arrow keys move the selection. ### 3.4 List row and group - **Group:** `--card`, 1px `--border`, `--radius-xl`, inset 16px from the screen edges. Rows inside are separated by `--border` hairlines that are inset to the text start. -- **Single-line row:** 48px, with an optional 20px leading icon in `--muted-foreground`, the label in `--text-body`, and a trailing value in `--muted-foreground` and/or a `chevron-right` 16px. Detail rows end in a chevron; action rows don't. +- **Single-line row:** 48px, the label in `--text-body`, and a trailing value in `--muted-foreground` and/or a `chevron-right` 16px. Detail rows end in a chevron; action rows don't. +- **Leading marks:** rows of things (sessions, agents and shells in New session, SSH hosts) lead with the 32px tile of §3.5, and their hairlines are inset to the text after it. Action rows ("Add port forward") lead with a 20px glyph in `--muted-foreground`. - **Two-line row:** 60px, with the title in `--text-body` 500 and the subtitle in `--text-footnote` `--muted-foreground` (mono for hosts and paths). - **Section header:** `--text-footnote` 500 `--muted-foreground`, 16px from the screen edge plus 4, with an optional count after one space in the same style. - **Footnote under a group:** `--text-footnote` `--muted-foreground`, 8px below it. This is where explanations live, not in the rows. @@ -340,8 +347,10 @@ A two-line row inside a group, 68px tall, and the whole row is one target. **Line 2:** - The state badge (§3.6), then 6px, then the detail on one line with an ellipsis. +- After a bare badge ("Ended", "Done", "Working") a ` · ` in `--muted-foreground` sits between them, 6px either side, so the label and the detail never run together. A tinted pill is its own separator. - In Needs you rows the detail is `--foreground` mono: the command, the file being edited ("edit src/lib/feed.ts") or the question. -- In other rows it is `--muted-foreground` mono: the last line of output, with ANSI stripped. +- In other rows it is `--muted-foreground` mono: the last line of output, with ANSI stripped. A line that is only prompt characters (`>`, `$`, `❯`, `›`, `#`, `%`) says nothing and is left out. +- While a row's menu is open, the row stays tinted `--accent`. **Interaction:** - Pressing tints the row `--accent`. @@ -363,13 +372,13 @@ A two-line row inside a group, 68px tall, and the whole row is one target. ┌──────────────────────────────────────────┐ │ esc tab ctrl │ <- up dn -> │ paste │ └──────────────────────────────────────────┘ - 5 + 3×44 + 9 + 4×44 + 9 + 44 + 5 = 390 + 5 + 44 + 45 + 47 + 9 + 4×44 + 9 + 44 + 5 = 384 ``` -The bar holds exactly eight keys at 390px: three modifiers, four arrows and Paste, with two 9px dividers and 5px end padding. +The bar holds eight keys at 390px, with 6px to spare: three modifiers, four arrows and Paste (the modifiers as wide as their labels need, the rest 44px), with two 9px dividers (a 1px rule and 4px either side) and 5px end padding. On a narrower phone the bar scrolls sideways. **Key caps:** -- 32px tall visuals centred in 44×44 targets, `--secondary` fill, `--radius-sm`; +- 32px tall visuals, at least 36px wide (4px side padding around the label), each in a target 8px wider and at least 44×44, so every pair of caps is 8px apart; `--secondary` fill, `--radius-sm`; - labels are `--mono-body` lowercase, with arrows as Lucide `arrow-left`, `arrow-up`, `arrow-down`, `arrow-right` and Paste as `clipboard-paste`; - the dividers are a 1px hairline, 20px tall and centred; - on screens narrower than 390px, or at large text sizes, the row scrolls horizontally with Paste last. Keys never shrink. @@ -377,7 +386,7 @@ The bar holds exactly eight keys at 390px: three modifiers, four arrows and Past **Keys:** - **Esc** sends `\x1b`. - **Tab** sends `\t`. -- **Long-press Tab (350ms)** sends Shift+Tab (`\x1b[Z`), which cycles Claude Code's permission modes. The cap shows a small `⇧` at its top right in `--muted-foreground` as the hint, and the Android haptic fires when the long-press registers. +- **Long-press Tab (350ms)** sends Shift+Tab (`\x1b[Z`), which cycles Claude Code's permission modes. The cap shows a 9px `⇧` inside it, 3px from its top and 4px from its right, in `--muted-foreground` as the hint (the cap takes 10px of right padding for it), and the Android haptic fires when the long-press registers. - **Ctrl** is a sticky modifier: - one tap latches it for the next key, filling the cap with `--foreground` and turning its label `--background`; - a double tap locks it, adding a 2px `--background` underline to the label until the next tap; @@ -400,16 +409,19 @@ A 56px row above the key bar: a 40px field with 8px vertical padding, 12px side ``` **Field:** -- `--muted` fill, 1px `--field-border`, `--radius-lg`, `--text-body` (16px minimum) and `--font-sans`; +- `--muted` fill, 1px `--field-border`, `--radius-lg`, `--text-body` (16px minimum) and `--font-sans`; shell and SSH sessions, whose input is a command, use `--font-mono` at 16px; - it grows to 5 lines (about 140px) and then scrolls; -- placeholders: "Message Claude" (or Codex, or OpenCode), "Command" for shells, "Command on prod-api" for SSH. +- placeholders: "Message Claude" (or Codex, or OpenCode), "Command" for shells, "Command on prod-api" for SSH; +- a tap focuses it with the 1px `--ring` border alone; the focus halo of §2.3 is for keyboard focus with a fine pointer. -**Send:** a 36px circle inside a 44px target, always present. +**Send:** a 36px circle inside a 44px target, always present, 12px from the right edge (as the field is from the left). It sits on the field's bottom edge, 2px inside it, so on a multi-line field it stays next to the last line. - **With text:** `--primary-solid` with a white Lucide `arrow-up`. It sends the text followed by `\r`, bracketed when the text has newlines and the session has bracketed paste on. - **Empty:** `--secondary` with a `--foreground` Lucide `corner-down-left`, labelled "Return". It sends `\r` alone, which confirms an option the agent's TUI has highlighted. - The two faces cross-fade over 160ms. - Return on the phone keyboard also sends (`enterkeyhint="send"`). On desktop, Enter sends and Shift+Enter adds a newline. +**Wide layout:** the field and the send button are capped at 720px together, starting from the terminal's left edge; the row's hairline and fill still span the pane. Compose stays the default with a fine pointer too, so the composer never moves between layouts. + **Modes:** - **Compose** is the default for every session. - **Direct.** Tapping the terminal focuses xterm. Keys then go straight to the PTY, the composer row collapses (the terminal grows by 56px) and the key bar stays where it is. When xterm loses focus, which happens when the keyboard is dismissed, the composer comes back. There is no mode button: the composer is visible exactly when xterm doesn't have focus. @@ -450,8 +462,11 @@ The most important surface in the app. It is a bottom sheet with a grabber (36× **Preview:** - The tool's `description` field, when present, goes above the block as body text. -- The block is `--sunken`, `--radius-md`, 12px padding, `--mono-body`, and wraps with a 2-character hanging indent. It never scrolls horizontally. +- The block is `--sunken`, `--radius-md`, 12px padding, `--mono-body` without ligatures (it shows the characters that will run), and wraps with a 2-character hanging indent. It never scrolls horizontally. - A `$ ` prompt in `--muted-foreground` starts each command. +- The description and block scroll together in the sheet's middle, which never shrinks below 120px (about five lines). When it clips, a 24px fade into `--popover` at its bottom says there is more, and a compact ghost "Show all" under it raises the sheet to full height (the page-sheet height of §4.6). The action rows below never move. + +**Landscape** (viewport height under 500px): the sheet uses two columns. The header and the preview fill the left; the actions sit in a 280px column on the right, aligned to the bottom, with any error above them. **Actions, in thumb order (the highest-value action is lowest and to the right):** - **Allow** (primary, 2fr) and **Deny** (secondary, 1fr), large. @@ -477,17 +492,19 @@ The most important surface in the app. It is a bottom sheet with a grabber (36× │ ╰──────────────────────────────────────╯ │ ``` -- **File header:** the path in mono `--foreground`, ellipsized from the start so the file name is kept ("…/lib/feed.ts"), and the counts at the right in `--diff-add-fg` / `--diff-del-fg`. +- **File header:** the path in mono `--foreground`, ellipsized from the start so the file name is kept ("…/lib/feed.ts"), and the counts at the right in `--diff-add-fg` / `--diff-del-fg`, `+12 −3` with a real minus (U+2212). The header stays at the top of the scrolling preview. - **Lines:** - a 2ch sign column in the sign colours, and no line numbers on phones (line numbers appear at 900px and wider, in `--muted-foreground`); - - lines wrap with the background tint spanning the full row; + - lines wrap with the background tint spanning the full row, and a wrapped line hangs 2ch further in than its start (`padding-left: 2ch; text-indent: -2ch`); - three lines of context around each hunk. +- **Opening position:** when the diff doesn't fit, the preview opens scrolled to its first change with one line of context above it, under the file header, so a short sheet shows the − and + lines rather than the context. - **Write** to a new file shows the header label "New file" and all lines as additions, truncated at 40 lines with "Show all 212 lines". - **MultiEdit** shows each edit as a hunk, separated by `⋯`. **Other tools** (WebFetch, MCP tools and the rest) show a key-value list inside the sunken block: -- keys in `--text-footnote` `--muted-foreground`; -- values in mono `--foreground`; +- keys in `--text-footnote` `--muted-foreground`, written for people: `url` is "URL", `file_path` "File path", `max_results` "Max results"; +- values in mono `--foreground`, which may break after each `/` (a ``), so URLs and paths wrap between segments rather than inside a name; +- values that are prose (a prompt or question of three or more words, without code punctuation) in sans `--text-body`; - long values clamped to 4 lines with "Show all". **Lifecycle:** @@ -496,12 +513,12 @@ The most important surface in the app. It is a bottom sheet with a grabber (36× - **Dismissal** (drag, Esc or scrim tap) doesn't answer. The sheet collapses into a 48px peek bar above the composer reading "● Claude wants to run npm ci", with a "Review" ghost button. Tapping it reopens the sheet. - **Answered on another device:** the action rows are replaced by a single line, "Allowed on MacBook" or "Denied on MacBook", with a `check` or `x` glyph. The sheet closes after 1.2s, and the next queued request slides in. - **Timed out:** the action rows are replaced by "Timed out. Claude will ask in the terminal." and an "Open terminal" secondary button. -- **Send failed:** an inline error under the actions reads "Couldn't send your answer. Check the connection and try again." The buttons stay live, and the sheet stays open. +- **Send failed:** an inline error (§3.2) between the preview and Always allow reads "Couldn't send your answer. Check the connection and try again." The sheet grows upwards to fit it, so the action rows never move under the thumb that just tapped them; in the wide layout the dialog keeps its bottom edge where it opened for the same reason. The buttons stay live, and the sheet stays open. - **Success:** no toast. The sheet closing and the badge change are the feedback. ### 3.10 Toast -- **Placement:** bottom centre, 12px above the bottom chrome (above the composer in a session, above the home indicator elsewhere). +- **Placement:** bottom centre, 12px above the bottom chrome: in a session its bottom is the composer's top (or the peek bar's, or the ended bar's) minus 12px, and it follows the composer as it grows and the keyboard as it opens; elsewhere it sits 12px above the home indicator. - **Shape:** full width minus 32px, at most 420px wide, 48px minimum height, level-3 surface, `--radius-lg`. - **Content:** a 16px leading glyph (none, `check` in `--state-done`, or `circle-alert` in `--destructive`), the text in `--text-footnote` `--foreground`, and an optional trailing ghost action such as "Undo" or "Retry". - **Behaviour:** one toast at a time, shown for 4s, or 6s with an action. Swiping down dismisses it, and it has `role="status"`. @@ -510,8 +527,23 @@ The most important surface in the app. It is a bottom sheet with a grabber (36× ### 3.11 Banner (attention from elsewhere) - **Placement:** at the top, under the status bar, inset 8px, level-3 surface, `--radius-xl`, 64px tall. -- **Content:** the agent tile, "Codex needs approval" in body 500 with the session title in footnote, and a "Review" ghost button. +- **Content:** the agent tile, then an 8px `--primary` dot and "Codex needs approval" in body 500 on one line with an end ellipsis, the session title in footnote under it, and a compact 36px "Review" ghost button. - **Behaviour:** shown for 6s, and an upward swipe dismisses it. Tapping it opens that session with its sheet. Only one banner shows at a time, the newest replacing the old one. +- **Where:** only where the arrival isn't already on screen. Never on the inbox, where the row rises into Needs you; never in the wide layout, whose sidebar is the inbox and always visible; and never in the session that asks, where the sheet opens instead. Every arrival is still announced in the live region. + +### 3.13 Empty and error screens + +One template for every screen with nothing to show or that failed: a 40px Lucide glyph in `--muted-foreground`, a `--text-heading` title, a `--text-body` muted body, and 16px below it the action (or a command block). It sits 18vh down a screen that has a header, or centred on a page that has none. + +| Screen | Glyph | Title / body | Action | +|---|---|---|---| +| No sessions | `terminal` | "No sessions yet" / "Start an agent, a shell or an SSH session on pi." | primary New session | +| Sessions failed | `circle-alert` | "Couldn't load sessions" / "The server didn't send the list. Try again in a moment." | Retry | +| Unreachable | `wifi-off` | "Can't reach pi.tail9c2.ts.net" / "Check that you're on your tailnet or network." | Retry | +| Session gone | `square-dashed` | "This session no longer exists" / "It ended and was removed from the server." | Back to sessions (the header keeps its back chevron) | +| Setup link expired | `timer-off` | "This setup link has expired" / how to get a new one | `redshell-server user add` in a `--sunken` mono block, 12px padding, `--radius-md`, never wrapping mid-command | +| No SSH hosts | `server` | "No SSH hosts yet" / where hosts come from | primary Add host | +| Wide, no session open | `terminal` | "No session open" / "Pick a session, or start a new one." | primary New session | ### 3.12 Passkey button @@ -533,8 +565,8 @@ All sketches are 390×844 and use the 47px top and 34px bottom insets. Heights o │ ┌──────┐ │ │ │ >_ ▬ │ │ 64 app icon │ └──────┘ │ 16 -│ Sign in to │ 34 title, 28/600 -│ pi.tail9c2.ts.net │ 20 host, mono footnote, muted +│ Sign in to pi │ 34 title, 28/600, the short host +│ pi.tail9c2.ts.net │ 20 full host, mono footnote, muted │ │ 32 │ ╭──────────────────────────────────────╮ │ │ │ (key) Sign in with passkey │ │ 52 primary @@ -555,16 +587,18 @@ All sketches are 390×844 and use the 47px top and 34px bottom insets. Heights o └──────────────────────────────────────────┘ ``` +- **Title:** "Sign in to pi", with the same short host as "Sign out of pi?" (the first label of the host), and the full host under it. - **Passkey first.** The passkey button is the only primary, and password sign-in is a secondary button below it. The username field also offers passkey autofill (conditional mediation), so a user who taps the field gets the passkey suggestion from the system. -- **Errors:** one generic message under the password field, "Username or password is incorrect", for an unknown user and a wrong password alike. +- **Errors:** one generic message under the password field, "Username or password is incorrect.", for an unknown user and a wrong password alike. - **Rate limit:** the message becomes "Too many attempts. Try again in 0:42.", counting down with tabular numbers, and the Sign in button stays disabled until it reaches zero. -- **Passkey-only accounts:** a password sign-in gets the same generic error. The server never reveals which accounts are passkey-only. -- **Offline:** "Can't reach pi.tail9c2.ts.net. Check that you're on your tailnet or network." with a Retry secondary button, replacing the form. +- **Passkey-only accounts:** the right password gets "This account signs in with a passkey." under the password field; a wrong one gets the same generic error as any other, so strangers learn nothing. +- **Without passkeys:** a server without an https `public_url` offers none (`ServerInfo.passkeys`). The passkey button, the "or" divider and the autofill go, and Sign in becomes the primary. +- **Offline:** the unreachable screen of §3.13, "Can't reach pi.tail9c2.ts.net" over "Check that you're on your tailnet or network." with a Retry secondary button, replacing the form. - **Wide layout:** a 400px column centred on `--background`. There is no card around it. ### 4.2 First-run setup -Reached through the one-time `/setup?code=…` link. There are three steps plus a closing screen. The header shows "Step 1 of 3" in footnote muted, and steps advance with the 200ms fade and translate. +Reached through the one-time `/setup?code=…` link. There are three steps plus a closing screen (two on a server without passkeys, which skips adding one). The header shows "Step 1 of 3" in footnote muted, and steps advance with the 200ms fade and translate. ``` ┌──────────────────────────────────────────┐ @@ -602,17 +636,24 @@ Reached through the one-time `/setup?code=…` link. There are three steps plus - title "Get notified when an agent needs you", with a primary "Turn on notifications" (the permission prompt fires from this tap) and a ghost "Not now"; - on iOS outside the installed app, this step instead shows the install instructions from the closing screen and says notifications work once RedShell is on the Home Screen. +**Steps without a form** (passkey, notifications and the closing screen) put a 48px glyph in `--muted-foreground` above the title (the passkey mark; Lucide `bell`; `circle-check` in `--state-done` for "You're set") and centre the glyph, title and body in the space between the step line and the actions. The 44px step line keeps its height on the closing screen, empty, so titles never jump. + **Closing screen ("You're set"):** a two-line summary, and on iOS Safari a compact instruction row: Lucide `share`, "Share → Add to Home Screen". Then a primary "Open sessions". -**Expired or used link:** the whole screen reads "This setup link has expired" with the body "Setup links work for 30 minutes. Restart redshell-server to get a new link, or create the account with `redshell-server user add` on the server." No form is shown. +**Expired or used link:** the whole screen is the §3.13 template: "This setup link has expired", the body "Setup links work for 30 minutes. Restart redshell-server to get a new link, or create the account on the server with:", and `redshell-server user add` in a sunken mono block that never wraps mid-command. No form is shown. ### 4.3 Pair a device (`/pair`) - It reuses sign-in: an unauthenticated visitor signs in first. - **Code entry:** the title "Pair a device", then the body "Enter the code shown in RedShell on your computer.", then a single 48px input in `--mono-code`, uppercase, `autocomplete="one-time-code"` and `inputmode="text"`. The code is formatted as `KX7-4MP` while typing. -- **Approval card:** once a valid code is entered, it shows the device name, the platform and "Requested 2 minutes ago", with a primary "Approve" and a secondary "Cancel". +- The input takes only the letters codes are made of (no 0, 1, I, L or O). +- **Approval card:** once a valid code is entered, it shows the device name, then "Named by the device · macOS" (anyone can call a device anything) and "Requested 2 minutes ago from 100.64.0.2" with the address in mono, with a primary "Approve" and a secondary "Reject". Either answer replaces the page with "MacBook Pro is paired" or "MacBook Pro was turned away" and a Done button. +- **Warning:** above the actions, after a hairline, "Approving signs this device in as andy, with access to every session on this server." in `--text-body` `--foreground`. When the request came from another address than this browser's (`same_address` is false), a line above it in `--text-footnote` 500 `--state-warn` with a 14px `triangle-alert` says "This request came from a different network than this browser. If someone sent you this code, reject it." It is a warning, not an error, so it is not red. +- **Approving** needs a recent re-authentication: "Confirm it's you" opens over the page when the server asks for one (§4.8), and the approval goes through once confirmed. - **Expired or unknown code:** the inline error "That code has expired or doesn't exist. Start pairing again on your computer." -- The code is never pre-filled from the URL. +- **Too many wrong codes:** "Too many wrong codes. Try again in 0:42." +- The code is never pre-filled from the URL, and the field has no placeholder: an example that looks like a real code invites typing it. +- The body, the field and errors share the 16px gutter. ### 4.4 Inbox (home) @@ -675,13 +716,14 @@ Reached through the one-time `/setup?code=…` link. There are three steps plus - "No sessions yet" in heading; - "Start an agent, a shell or an SSH session on pi." in body muted; - a 16px gap, then a primary "New session" button at its natural width. -- **Reconnecting:** a 32px strip under the nav row on `--muted` reads "Reconnecting…" with a 14px `wifi-off` in `--state-warn`. +- **Reconnecting:** a 32px strip under the nav row on `--muted` reads "Reconnecting…" with a 14px `wifi-off` in `--state-warn`, with 12px of space between it and the large title. - It appears only after 1s disconnected, so blips never flash it. + - It doesn't appear while the list itself failed to load: that error says enough, and a second message would contradict it. - Rows keep their last known state at 60% opacity, and their times freeze. - When the connection returns, the strip collapses over 160ms and the rows return to full opacity. - **Offline** (`navigator.onLine === false`): the same strip reads "Offline. Showing the last known state." - **Session ended elsewhere:** the row moves to Recent with the FLIP reorder. -- **Error loading** (non-network): "Couldn't load sessions." with a Retry secondary, centred. +- **Error loading** (non-network): the §3.13 template, "Couldn't load sessions" with a Retry secondary. It shows after the first failed request and at most one retry a second later, so the skeleton never lingers for seconds before it. ### 4.5 Session view @@ -716,7 +758,7 @@ Reached through the one-time `/setup?code=…` link. There are three steps plus - A back button (`chevron-left`, 44px). - A two-line title: the session title in `--text-body` 600, and the cwd in `--mono-caption` `--muted-foreground` ellipsized from the start, or `user@host` for SSH. - The state badge. -- An overflow menu (`ellipsis`) with Rename, Copy path, Font size, Select text, Scroll to bottom and End session. +- An overflow menu (`ellipsis`) with Rename, Copy path, Font size, Select text, Scroll to bottom and End session. It opens 4px below the header's bottom edge, right-aligned with the button, and a hairline sets End session apart. **Terminal:** - **Grid:** 13px gives 47 columns and 39 rows at 390px wide; landscape at 844px gives about 105 columns. @@ -738,8 +780,8 @@ Reached through the one-time `/setup?code=…` link. There are three steps plus - on reconnect, the fresh snapshot replaces the screen. - **Approval pending:** the sheet (§3.9), or the 48px peek bar above the composer. - **Needs input:** the badge changes, the composer placeholder becomes "Claude is waiting for you", and the composer is focused if the app is in the foreground and the keyboard was already open. The keyboard is never forced open. -- **Ended:** the composer and key bar are replaced by a 56px bar reading "Ended" (exit 0, muted) or "Failed · exit 1" (destructive), with the time, and a secondary "Start again" that starts the same kind in the same folder. The terminal keeps its final screen. -- **Session not found** (ended and pruned): the centred text "This session no longer exists." and a secondary "Back to sessions". +- **Ended:** the composer and key bar are replaced by a 56px bar reading "Ended · 14:02" (exit 0, muted) or "Failed · exit 255 · Mon 14:02" (destructive, the time muted), and a secondary "Start again" that starts the same kind in the same folder. The time is the time of day today, the weekday and time within the week, and the date and time before that, on a 24-hour clock. The terminal keeps its final screen. +- **Session not found** (ended and pruned): the §3.13 template under a header that keeps its back chevron: "This session no longer exists", "It ended and was removed from the server." and a secondary "Back to sessions". ### 4.6 New session @@ -780,9 +822,11 @@ A page sheet: it slides up over the inbox and the sheet scrim to the full height - **Agent:** the server's agent profiles (single choice) and a folder. - **Shell:** the server's shell profiles and a folder. - **SSH:** a search field (48px, `search` icon) and hosts grouped by `group`, as in §4.7, single choice. There is no folder section. -- **Folder list:** the last 5 recent folders on the server, then "Other folder…", which pushes a path input with server-side completion. Completions appear as 44px mono rows under the field. +- **Rows:** agents, shells and hosts lead with the 32px tile (§3.4). +- **Not installed:** an agent the server can't find stays in the list at 40% opacity with "Not installed" at its end, can't be chosen and is never the default. A footnote under the group says what to do: "Install `opencode` on pi to use it." (the program in mono; several are listed as "`gemini`, `copilot` or `opencode`"). +- **Folder list:** the last 5 recent folders on the server, then "Other folder…", which pushes a path input with server-side completion. A back chevron inside the field, at its left, returns to the list. Paths may start with `~`: the server reads it as its user's home and lists the folder in the same terms, so `~/src/a` completes to `~/src/aurora`. Completions appear as 44px mono rows under the field. - **Selection:** a `check` in `--foreground` at the row's end, and nothing else (no row fill). -- **Defaults:** the agent and folder used last. +- **Defaults:** the agent and folder used last, if that agent is still installed, else the first installed one. - **Start:** pressing it shows a spinner in the button, then navigates straight into the new session. On failure the sheet stays, with an inline error above the button such as "Couldn't start Claude Code: `claude` was not found on the server." - **Wide layout:** a 520px dialog, `--radius-xl`, max 80vh. @@ -799,7 +843,7 @@ Reached from Settings → SSH hosts. │ ╰──────────────────────────────────────╯ │ 24 │ Production │ 28 group header │ ╭──────────────────────────────────────╮ │ -│ │ ▤ prod-api › │ │ 60 two-line row +│ │ ▤ prod-api › │ │ 60 two-line row, 32px server tile │ │ deploy@10.0.4.12 │ │ mono subtitle │ ├──────────────────────────────────────┤ │ │ │ ▤ staging › │ │ 60 @@ -817,11 +861,14 @@ Reached from Settings → SSH hosts. - **Groups:** named groups first, alphabetically, then "Other", then the hosts imported from `~/.ssh/config`, which are read-only. - **Host detail:** - the title is the host name, with a primary "Connect" at the top; - - then a group of fields: Name, Host, User, Port, Identity file, Jump host and Group; + - then the fields as field rows (§3.2), in two groups: Name ("prod-api") and Host ("10.0.4.12", mono), with the footnote "Leave Host empty to use the name as a ~/.ssh/config alias."; then User ("deploy"), Port ("22"), Identity file ("~/.ssh/id_ed25519"), Jump host ("bastion"), all mono, and Group ("Production"). A bad port shows its error under that group; + - then "On connect": a "Forward SSH agent" switch row and a mono "Startup command" field row in one group; + - then "Port forwards": one two-line row per forward (its label, then `5432 → db.internal:5432` in mono; unlabelled ones show the mono line as the label) and an "Add port forward" row with a plus. The footnote reads "RedShell on your computer runs these as tunnels while it is connected to this host. The server only keeps them."; - then "Remove host" (destructive, confirmed) at the bottom; - - imported hosts show the fields as read-only values and no remove. -- **Add (+):** the same form with "Save" in the header right as a ghost button, enabled when Name and Host are filled. -- **Empty:** "No SSH hosts yet" with "Add one here, or add Host entries to ~/.ssh/config on pi." and a primary "Add host". + - imported hosts show the same rows as read-only values and no remove. +- **Port forward:** a page sheet like New session (§4.6), with ghost Cancel, the title ("Port forward" or "New port forward") and a ghost Done in its header, Done enabled once the ports and destination are valid. Under a segmented Local / Remote / SOCKS, field rows: the port it listens on ("Local port", or "Port on the host" for a remote forward), then Destination and Port (not for SOCKS), with a footnote saying where connections go; then Bind address (placeholder `localhost`), Label and a "Start on connect" switch row. For an existing forward, "Remove forward" is a destructive row in its own group, 24px below the last one. In the wide layout it is the 520px dialog of a page sheet. +- **Add (+):** the same form with "Save" in the header right as a ghost button, enabled when Name is filled and Port, if any, is a port. +- **Empty:** the §3.13 template: "No SSH hosts yet" with "Add one here, or add Host entries to ~/.ssh/config on pi." and a primary "Add host". ### 4.8 Settings @@ -857,41 +904,52 @@ Reached from Settings → SSH hosts. └──────────────────────────────────────────┘ ``` +**Terminal font size:** the stepper's − and + are 32px `--secondary` caps with `--radius-sm`, as in the key bar, in 44px targets, and each is disabled (40%) at its limit, 10 or 20. + **Passkey-only:** - The switch is disabled while the account has no passkey. Its footnote then reads "Add a passkey to turn this on." - When off with passkeys present, the footnote reads "Turn this on to sign in only with passkeys." - When on, the footnote reads "Password sign-in is turned off for this account." -- Turning it on asks for confirmation in a centred alert: "Turn off password sign-in?" with "You'll sign in only with your passkeys. Keep at least two in case you lose a device.", plus Cancel and Turn off (primary). +- Turning it on asks for confirmation in a centred alert: "Turn off password sign-in?" with "You'll sign in only with your passkeys, and other browsers and devices that signed in with your password are signed out. Keep at least two passkeys in case you lose a device.", plus Cancel and Turn off (primary). Once it is on, the device and browser lists are fetched again, since the server ended those sign-ins. **Passkeys:** - Two-line rows: the name, then "Added 3 Mar · last used today". -- Tapping a row opens Rename and Remove. Remove is destructive and confirmed, and is blocked with an explanation when it would remove the last passkey while passkey-only is on. +- On a server without passkeys the Passkeys row reads "Off", the passkey-only footnote reads "Passkeys need this server at an https address.", and the Passkeys screen shows "Add a passkey" as a disabled row, with the group footnote "Passkeys need this server at an https address. Set `public_url` in its config to turn them on." under it. +- Tapping a row opens Rename and Remove. Remove is destructive and confirmed, and is blocked with an explanation when it would remove the last passkey while passkey-only is on; should the server refuse it anyway (409), the confirmation shows the same explanation. - The primary "Add a passkey" sits at the bottom of the list. **Password:** current, new and confirm fields, with Save. In passkey-only mode the row shows "Off" and opens an explanation instead. **Devices:** -- Two-line rows: the device name ("MacBook Pro · RedShell desktop" or "iPhone · Safari"), then "Last seen 5m ago". +- Two-line rows: the device name ("MacBook Pro · RedShell desktop", or the server's name for a browser such as "Safari on iPhone"), then "Last seen 5m ago". - This device is marked "This device" in `--muted-foreground`. - Revoke is a destructive row in the detail view, confirmed. -- A ghost "Pair a device" link explains `/pair`. +- The list's footnote reads "To sign in to RedShell on a computer, choose Pair with browser there, then tap Pair a device here.", and a "Pair a device" row under it opens `/pair`. **Notifications:** - **State row:** - - "On" when push is subscribed; + - "On" when the server has this browser's subscription (it drops it when the browser signs out); - "Off" with a primary "Turn on notifications" when permission is default; - "Blocked" with the footnote "Allow notifications for this site in your browser settings." when permission is denied; - "Install first" on iOS Safari outside standalone, with the footnote "On iPhone, notifications work once RedShell is on your Home Screen. Tap Share, then Add to Home Screen." -- **Event switches** (all on by default): Approvals, Waiting for input, Finished, Failed. -- A secondary "Send a test notification". +- **Event switches**, shown while on and kept on the server's subscription for this browser (all on when it subscribes): Approvals, Waiting for input, Finished, Failed, Program notifications. +- A secondary "Send a test notification" and a ghost "Turn off on this device", while on. +- **Other browsers:** the account's other subscriptions, named after their push service ("Chrome", "Safari"), with "Since 25 Nov · 3 of 5 kinds". Tapping one asks "Stop notifications to Chrome?" and removes it. **Sign out:** confirmed with "Sign out of pi?" and the actions Cancel and Sign out (destructive). +**Confirm it's you:** adding or removing a passkey, passkey-only on or off, revoking another device or browser, approving a pairing and a passkey-only account's password change need a re-authentication from the last five minutes (a sign-in counts). Without one, the server answers `reauth_required` and a centred dialog opens over whatever asked, the confirmation alert included, so the change goes through on its own once confirmed: +- Title "Confirm it's you", then a muted body that names what works: "Use a passkey or your password to make this change.", or only one of them. +- With a passkey on a server that offers them, the large primary "Use a passkey" with the passkey mark comes first, then the "or" divider of §4.1. +- Unless the account is passkey-only, a Password field, then Cancel and Continue (Continue is the primary when there is no passkey button). +- Errors are inline: "The password is incorrect." under the field, "That passkey wasn't accepted. Try another one." under the button, and "Too many attempts. Try again in 0:42." counting down with both actions disabled. Cancelling the dialog or the system passkey sheet is silent, and the change that asked shows no error. +- Adding a passkey asks first when the last re-authentication has lapsed, before the registration starts. + ### 4.9 Notifications (push payloads) - **Title:** "Claude needs approval", "Codex is waiting for you", "Claude finished" or "aurora failed (exit 1)". - **Body:** the detail and the session title: "npm ci · aurora" or "Edit src/lib/feed.ts · aurora". -- **Grouping:** `tag` is the session id, so a newer event replaces the older one, and `renotify` is true for approvals. +- **Grouping:** the server's `tag` is the same for every message about a session, so a newer event replaces the older one, and `renotify` is true for approvals and questions. A tap opens `/s/`, or the inbox for a test message. - **Action buttons:** none. Approving needs the preview, so tapping opens that session with its sheet. - **Icon** is the app icon, and the **badge** is the monochrome glyph (§5). - **Text style:** notification text carries no emoji or decoration. @@ -902,7 +960,7 @@ One breakpoint. Below 900px everything is the phone layout, centred at a maximum ``` ┌───────────────────────┬──────────────────────────────────────────────┐ -│ Sessions [set] [+] │ aurora ~/src/aurora ▮ Working [kbd] [⋯] │ 52 +│ Sessions [+] │ aurora ~/src/aurora ▮ Working [kbd] [⋯] │ 52 │ pi.tail9c2.ts.net ├──────────────────────────────────────────────┤ │ │ │ │ Needs you 2 │ │ @@ -923,8 +981,8 @@ One breakpoint. Below 900px everything is the phone layout, centred at a maximum - 320px on `--sidebar` with a right hairline, as on the desktop app; - session rows are flat rather than grouped cards, 56px with a 28px tile; - the selected row has an `--accent` fill and a 2px `--primary` left edge, exactly as on the desktop; - - SSH hosts and Settings live in the sidebar footer as two 40px rows. -- **Main pane:** the session, or Settings and Hosts as a centred 640px column. + - SSH hosts and Settings live in the sidebar footer as two 40px rows, so the sidebar header holds only New session; the footer row of the screen in the main pane has the selected row's `--accent` fill and 2px `--primary` edge. +- **Main pane:** the session, or Settings and Hosts as a centred 640px column. With no session open it shows the §3.13 template: "No session open", "Pick a session, or start a new one." and a primary New session. - **Key bar:** hidden with `pointer: fine`; the header `keyboard` button toggles it. - **Dialogs:** sheets become centred dialogs, `--radius-xl`, with the dialog scrim. The approval dialog is 560px wide, centred over the terminal pane and not the whole window. - **Keyboard shortcuts:** only inside a pending approval dialog, where Enter does nothing, `A` Allows, `D` Denies, `T` answers in terminal and Esc dismisses. The letter keys share the buttons' 500ms guard. There are no global shortcuts, because every key belongs to the terminal. @@ -1005,7 +1063,7 @@ These shaped the direction and were studied, not copied. Links are to the origin - **AI Coding Agent Panel / Dark Mode** (Dribbble, [shots/27936755](https://dribbble.com/shots/27936755-AI-Coding-Agent-Panel-Dark-Mode)). Taken: a compact in-flow diff block with a file header row, and the circular send button at the end of the composer. Not taken: the purple and the tool-call card stack. - **1Code, "A calm, visual client for parallel work"** (Are.na, [block/44658161](https://www.are.na/block/44658161)). Taken: the confirmation that a monochrome, almost colourless dark UI reads as calm for parallel agents, with mono used for headings of data only. - **Opal technical specifications** (Cosmos, image by barth?, [cdn.cosmos.so/5135c4c2…](https://cdn.cosmos.so/5135c4c2-f834-4366-af5b-5c86ae7ce467?format=jpeg&w=1600)). Taken: the layout rhythm of hairline-separated rows on near-black, with generous vertical spacing and one high-contrast pill action. -- **Patterns taken from products in daily use** (from hands-on familiarity, not from this search): +- **Patterns taken from products in daily use** (from hands-on familiarity rather than the references above): - **Claude app Remote Control:** one session per screen; permission prompts as sheets with the tool and input verbatim. - **Linear mobile:** an inbox ordered by what needs you; sentence-case section headers; long-press menus instead of swipe actions. - **Blink Shell and Termius:** a key row docked to the keyboard; a sticky Ctrl; long-press arrow repeat. diff --git a/docs/design/remote-server.md b/docs/design/remote-server.md index e9348ef..e6e3262 100644 --- a/docs/design/remote-server.md +++ b/docs/design/remote-server.md @@ -50,7 +50,7 @@ web/ PWA: Vite + React + TypeScript, xterm.js, TanStack Qu - `tls_cert` / `tls_key` (optional built-in TLS); - `trusted_proxies`. SSH hosts, agent and terminal settings mean the same thing as on the desktop. -- **Store.** SQLite (`rusqlite`, already used): users, password hashes, passkeys, browser sessions and device tokens (stored as SHA-256 of 256-bit random tokens), WebAuthn ceremonies in flight, push subscriptions, VAPID keys, audit log, sessions metadata. +- **Store.** SQLite (`rusqlite`, already used): users, password hashes, passkeys, browser sessions and device tokens (stored as SHA-256 of 256-bit random tokens), push subscriptions, VAPID keys, audit log, sessions metadata. WebAuthn ceremonies and pairing requests in flight live only in memory: they last minutes. - **Sessions.** Each session is a `redshell-terminal` engine (alacritty VT + portable-pty) on the server. - A late client gets a snapshot and then the live stream. The snapshot is the screen and recent scrollback serialized as ANSI, plus the terminal modes a client needs to send the right input and draw the right screen: alt screen, application cursor and keypad, bracketed paste, mouse reporting and its encoding, focus reporting, cursor visibility and shape, and the title. - Size follows the client that last typed (like tmux `window-size latest`). @@ -73,7 +73,7 @@ web/ PWA: Vite + React + TypeScript, xterm.js, TanStack Qu - **First start.** It prints a one-time setup link (`/setup?code=…`, valid 30 minutes) to the log, and the first account is created there. CLI subcommands are `redshell-server user add|passwd|remove|reset-passkeys` and `redshell-server serve`. - **Passwords.** Argon2id. Sign-in is rate-limited per IP and per user (exponential backoff), with the same error for an unknown user and a wrong password, and the attempt is logged. - **Passkeys.** `webauthn-rs`: discoverable credentials, so "Sign in with a passkey" works without typing a name. Several passkeys per user, each with a name and a last-used time, and each can be revoked. Passkey-only mode refuses password sign-in for that user; it can be switched on only while the user has a passkey. -- **Browser sessions.** A `__Host-` cookie, HttpOnly, Secure, SameSite=Strict, with a 30-day sliding expiry. Every state-changing request needs a matching Origin, and the WebSocket upgrade is checked against `public_url`. +- **Browser sessions.** A `__Host-` cookie, HttpOnly, Secure, SameSite=Strict, with a 30-day sliding expiry. Every state-changing request needs a matching Origin (exactly `public_url` when it is https) and the header `X-RedShell: 1`, and the WebSocket upgrade is checked against `public_url`. - **Desktop devices.** Bearer device tokens. The desktop gets one either by username and password in its dialog, or by browser pairing: 1. the desktop asks for a pairing request and shows its short code (for example `KX7-4MP`), then opens `/pair`; 2. the user signs in there, including by passkey, and types the code shown on the desktop. The page then shows the device name and asks to approve it. A link that pre-fills the code is never offered, so a pairing request someone else started cannot be approved by clicking a link; diff --git a/docs/screenshots/remote/approval-dark.png b/docs/screenshots/remote/approval-dark.png new file mode 100644 index 0000000..38e470a Binary files /dev/null and b/docs/screenshots/remote/approval-dark.png differ diff --git a/docs/screenshots/remote/approval-diff-light.png b/docs/screenshots/remote/approval-diff-light.png new file mode 100644 index 0000000..ad7a852 Binary files /dev/null and b/docs/screenshots/remote/approval-diff-light.png differ diff --git a/docs/screenshots/remote/confirm-identity-dark.png b/docs/screenshots/remote/confirm-identity-dark.png new file mode 100644 index 0000000..64d597d Binary files /dev/null and b/docs/screenshots/remote/confirm-identity-dark.png differ diff --git a/docs/screenshots/remote/host-dark.png b/docs/screenshots/remote/host-dark.png new file mode 100644 index 0000000..62b7677 Binary files /dev/null and b/docs/screenshots/remote/host-dark.png differ diff --git a/docs/screenshots/remote/inbox-dark.png b/docs/screenshots/remote/inbox-dark.png new file mode 100644 index 0000000..3ee7415 Binary files /dev/null and b/docs/screenshots/remote/inbox-dark.png differ diff --git a/docs/screenshots/remote/new-session-light.png b/docs/screenshots/remote/new-session-light.png new file mode 100644 index 0000000..7ef9582 Binary files /dev/null and b/docs/screenshots/remote/new-session-light.png differ diff --git a/docs/screenshots/remote/pair-dark.png b/docs/screenshots/remote/pair-dark.png new file mode 100644 index 0000000..8d8c575 Binary files /dev/null and b/docs/screenshots/remote/pair-dark.png differ diff --git a/docs/screenshots/remote/passkeys-dark.png b/docs/screenshots/remote/passkeys-dark.png new file mode 100644 index 0000000..0fadd5a Binary files /dev/null and b/docs/screenshots/remote/passkeys-dark.png differ diff --git a/docs/screenshots/remote/session-dark.png b/docs/screenshots/remote/session-dark.png new file mode 100644 index 0000000..4b41d70 Binary files /dev/null and b/docs/screenshots/remote/session-dark.png differ diff --git a/docs/screenshots/remote/settings-dark.png b/docs/screenshots/remote/settings-dark.png new file mode 100644 index 0000000..857f4f3 Binary files /dev/null and b/docs/screenshots/remote/settings-dark.png differ diff --git a/docs/screenshots/remote/wide-dark.png b/docs/screenshots/remote/wide-dark.png new file mode 100644 index 0000000..fae8212 Binary files /dev/null and b/docs/screenshots/remote/wide-dark.png differ diff --git a/packaging/server/redshell-server@.service b/packaging/server/redshell-server@.service new file mode 100644 index 0000000..9468564 --- /dev/null +++ b/packaging/server/redshell-server@.service @@ -0,0 +1,24 @@ +# RedShell Server for one user: sessions run as that user, with their home, +# shells, SSH keys and agent sign-ins. Enable it for a user with +# sudo systemctl enable --now redshell-server@pi +# State lives in ~/.config/redshell-server of that user. +[Unit] +Description=RedShell Server for %i +Documentation=https://github.com/redstone-md/RedShell/blob/main/docs/REMOTE.md +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=%i +WorkingDirectory=~ +ExecStart=/usr/bin/redshell-server serve +Restart=on-failure +RestartSec=3 +# Sessions are the user's own shells and agents, so the service is not +# sandboxed further: it must see the user's files like a login would. +KillMode=mixed +TimeoutStopSec=10 + +[Install] +WantedBy=multi-user.target diff --git a/scripts/package-server-deb.sh b/scripts/package-server-deb.sh new file mode 100755 index 0000000..5b5e711 --- /dev/null +++ b/scripts/package-server-deb.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Builds the redshell-server .deb from an already built binary: +# scripts/package-server-deb.sh +# It installs /usr/bin/redshell-server, the per-user systemd unit +# redshell-server@.service and the docs. Nothing starts by itself: the +# server is enabled per user with `systemctl enable --now redshell-server@`. +set -euo pipefail + +if [ $# -ne 4 ]; then + echo "usage: $0 " >&2 + exit 2 +fi +binary=$1 version=$2 arch=$3 out=$4 +root=$(cd "$(dirname "$0")/.." && pwd) +stage=$(mktemp -d) +chmod 755 "$stage" +trap 'rm -rf "$stage"' EXIT + +install -Dm755 "$binary" "$stage/usr/bin/redshell-server" +install -Dm644 "$root/packaging/server/redshell-server@.service" "$stage/lib/systemd/system/redshell-server@.service" +install -Dm644 "$root/docs/REMOTE.md" "$stage/usr/share/doc/redshell-server/REMOTE.md" +install -Dm644 "$root/LICENSE" "$stage/usr/share/doc/redshell-server/copyright" + +mkdir -p "$stage/DEBIAN" +cat > "$stage/DEBIAN/control" < +Homepage: https://github.com/redstone-md/RedShell +Section: net +Priority: optional +Depends: libc6 (>= 2.35) +Installed-Size: $(du -sk "$stage/usr" "$stage/lib" | awk '{s += $1} END {print s}') +Description: Headless RedShell: terminal and agent sessions for the desktop and phones + redshell-server keeps shells, coding agents and SSH sessions running on an + always-on machine. The RedShell desktop attaches to them, and phones use the + RedShell Remote web app it serves. Enable it per user with + systemctl enable --now redshell-server@USER. +CONTROL +cat > "$stage/DEBIAN/postinst" <<'POSTINST' +#!/bin/sh +set -e +if [ "$1" = configure ] && [ -d /run/systemd/system ]; then + systemctl daemon-reload >/dev/null 2>&1 || true + # Restart the instances that were running, so an upgrade takes effect. + for unit in $(systemctl list-units --plain --no-legend 'redshell-server@*.service' 2>/dev/null | awk '{print $1}'); do + systemctl try-restart "$unit" >/dev/null 2>&1 || true + done +fi +POSTINST +cat > "$stage/DEBIAN/postrm" <<'POSTRM' +#!/bin/sh +set -e +if [ -d /run/systemd/system ]; then + systemctl daemon-reload >/dev/null 2>&1 || true +fi +POSTRM +chmod 755 "$stage/DEBIAN/postinst" "$stage/DEBIAN/postrm" + +dpkg-deb --root-owner-group --build "$stage" "$out" >/dev/null +echo "$out" diff --git a/web/.gitignore b/web/.gitignore new file mode 100644 index 0000000..80487ef --- /dev/null +++ b/web/.gitignore @@ -0,0 +1,2 @@ +/shots +/dist-mock diff --git a/web/README.md b/web/README.md new file mode 100644 index 0000000..4ad465d --- /dev/null +++ b/web/README.md @@ -0,0 +1,79 @@ +# RedShell Remote + +The web app that `redshell-server` serves, a PWA you install on a phone's home screen: the inbox +of sessions, terminals, approvals and settings. The server embeds `web/dist` when it is built +(see [docs/REMOTE.md](../docs/REMOTE.md#from-source)); the design is in +[docs/design/remote-pwa-visual.md](../docs/design/remote-pwa-visual.md). + +## Development + +```sh +npm ci +npm run dev # http://localhost:5173, /api proxied to a server on 127.0.0.1:4747 +``` + +`npm run typecheck`, `npm run lint` and `npm run test` check the code, and `npm run build` +writes `dist/` for the server to embed. + +The types in `src/protocol/` are generated from `redshell-protocol` by ts-rs (`cargo test -p +redshell-protocol`); don't edit them. Every call the app makes to the server is in +`src/api/client.ts`. + +## End-to-end test + +`npm run e2e` runs the app against a real `redshell-server` in Chromium. It builds the PWA and +the server that embeds it, starts the server on a free port with a throwaway config directory and +home under the system temp folder, and walks through: password sign-in, a shell session that +runs what the composer sends, renaming and ending it, an agent's permission request allowed from +the sheet, adding a passkey right after signing in (which counts as a re-authentication) and +signing in with it from the button and from autofill (Chromium's virtual authenticator), pairing +a device by its code (the device side with curl) under the page's warning, and an SSH host with a +port forward written to the server's `config.toml`. Before approving the pairing and before +signing out another browser, the test lets the last re-authentication lapse (it clears it in the +server's database), so "Confirm it's you" asks first: for the passkey, then for the password. The +agent is a fake `claude` put first on the server's `PATH`, so no real agent runs. Every process it started is stopped and its folder +removed, also when a step fails. + +It needs cargo, curl, `playwright-core` and a Chromium at `/usr/bin/chromium` (`CHROMIUM=` to +use another), and is not part of `npm test`. `npm run e2e -- --no-build` skips the builds, and +`--shots ` saves screenshots of the real screens. + +## Mock mode + +Without a server, add `?mock` to any URL of the dev server: a mock backend in the browser speaks +the same REST and WebSocket protocol, with live agents, approvals and shells that echo. It stays +on for the tab until the tab is closed. `npm run build:mock` writes a build into `dist-mock/` that +always runs on the mock. The production build (`npm run build`, what the server embeds) has no +mock at all: the chunk isn't emitted and `?mock` does nothing, so no link can dress a real +server's address in a fake app. `?mock=` starts from a particular state: + +| Scenario | Shows | +| --- | --- | +| `empty` | No sessions yet | +| `loading`, `error` | The session list loading forever, or failing | +| `signed-out`, `rate-limited`, `unreachable` | Sign-in, its backoff, and a server that is down | +| `setup`, `setup-expired` | First-run setup, and a setup code that is used up | +| `no-passkeys`, `passkey-only` | Accounts without passkeys, or with password sign-in off | +| `passkeys-off` | A server without an https `public_url`, so without passkeys (signed out) | +| `push-on` | This browser subscribed to notifications, with its event switches | +| `reconnecting`, `arrival` | A dropped WebSocket, and a banner from another session | +| `diff`, `write`, `other`, `expiring` | An edit, a new file, a web fetch, and a request about to time out | +| `answer-fails`, `remote-answer` | Answers that fail to send, or come from another device | + +In mock mode, /pair knows one code: `KX7-4MP`, from another network than the browser's. A +signed-in scenario starts without a recent re-authentication, so adding or removing a passkey, +passkey-only, approving a pairing and revoking a device ask "Confirm it's you" first (any +password of 10 characters or more, or the passkey sheet) until the next five minutes are up. + +## Icons and screenshots + +`npm run icons` renders the app icons, the maskable icon, the notification badge and the iOS +splash screens from the repository's `assets/icon/*.svg` into `public/`, and writes the splash `` tags +into `index.html`. + +`npm run screenshots` builds the mock build, serves it with `vite preview` on a free port for the +run, and saves every screen and state in Chromium at 390×844, 844×390 (the approval sheet in +landscape) and 1280×800, light and dark, into `shots/` at 2x (`--scale`). `--only name,name` +picks shots by prefix, `--no-build` reuses `dist-mock/`, and `--url` shoots a server that is +already running, such as the dev server. It needs `playwright-core` and a Chromium at +`/usr/bin/chromium`. diff --git a/web/eslint.config.js b/web/eslint.config.js new file mode 100644 index 0000000..507ebda --- /dev/null +++ b/web/eslint.config.js @@ -0,0 +1,30 @@ +import js from "@eslint/js"; +import reactHooks from "eslint-plugin-react-hooks"; +import reactRefresh from "eslint-plugin-react-refresh"; +import globals from "globals"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + // src/protocol is generated by redshell-protocol's tests. + { ignores: ["dist", "dist-mock", "dev-dist", "src/protocol", "eslint.config.js"] }, + { + files: ["**/*.{ts,tsx}"], + extends: [js.configs.recommended, ...tseslint.configs.strictTypeChecked], + languageOptions: { + ecmaVersion: 2022, + globals: { ...globals.browser }, + parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname }, + }, + plugins: { "react-hooks": reactHooks, "react-refresh": reactRefresh }, + rules: { + ...reactHooks.configs.recommended.rules, + "react-refresh/only-export-components": ["warn", { allowConstantExport: true }], + "@typescript-eslint/restrict-template-expressions": ["error", { allowNumber: true }], + "@typescript-eslint/no-confusing-void-expression": ["error", { ignoreArrowShorthand: true }], + }, + }, + { + files: ["scripts/**", "*.config.ts"], + languageOptions: { globals: { ...globals.node } }, + }, +); diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..a03948f --- /dev/null +++ b/web/index.html @@ -0,0 +1,50 @@ + + + + + + RedShell + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..9ad8bda --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,9171 @@ +{ + "name": "redshell-remote", + "version": "0.0.3", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "redshell-remote", + "version": "0.0.3", + "dependencies": { + "@simplewebauthn/browser": "^14.0.0", + "@tanstack/react-query": "^5.108.4", + "@xterm/addon-fit": "^0.11.0", + "@xterm/addon-unicode11": "^0.9.0", + "@xterm/addon-web-links": "^0.12.0", + "@xterm/addon-webgl": "^0.19.0", + "@xterm/xterm": "^6.0.0", + "lucide-react": "^1.87.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router": "^8.5.3", + "zustand": "^5.1.0" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@tailwindcss/vite": "^4.3.5", + "@types/node": "^26.6.11", + "@types/react": "^19.3.3", + "@types/react-dom": "^19.3.0", + "@vite-pwa/assets-generator": "^2.0.0", + "@vitejs/plugin-react": "^6.3.1", + "eslint": "^10.16.0", + "eslint-plugin-react-hooks": "^7.1.1", + "eslint-plugin-react-refresh": "^0.5.8", + "globals": "^17.15.0", + "playwright-core": "^1.65.2", + "tailwindcss": "^4.3.5", + "typescript": "~6.0.3", + "typescript-eslint": "^8.74.0", + "vite": "^8.4.1", + "vite-plugin-pwa": "^2.0.0", + "vitest": "^5.1.2", + "workbox-build": "^7.4.1", + "workbox-precaching": "^7.4.1", + "workbox-routing": "^7.4.1", + "workbox-window": "^7.4.1" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.17.tgz", + "integrity": "sha512-IdlVpcDeoDATtN2cfmnVk0A4XJKhu7SlpGuSaiOFdko09YC1MD07WokWUSEdw5R2o4o8VObX2LzViQW6VXnzkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.17", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.17.tgz", + "integrity": "sha512-pC/HCNB1loXYCLB9S7FDieWKJiXH8LJTUGFvVAm+7hWUKBjL07EcvVITNH9KlXdS/TTSbChZHZCYx/yag6LbRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.17.tgz", + "integrity": "sha512-dP4g0UpATLviwEEb46bBaeL5MyW3q7LwqGoaQJvjXGS8tdpxckLtDTI9FBwA5ioVHnYoR2nRqCf1BmlMwbZV5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.17", + "@babel/generator": "^7.29.17", + "@babel/helper-compilation-targets": "^7.29.17", + "@babel/helper-module-transforms": "^7.29.17", + "@babel/helpers": "^7.29.17", + "@babel/parser": "^7.29.17", + "@babel/template": "^7.29.17", + "@babel/traverse": "^7.29.17", + "@babel/types": "^7.29.17", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.17.tgz", + "integrity": "sha512-xjNUVINWex7s4U0vESYwa8ChCBnmvhCQ6nkAdnhM8WYPlhXvU9D9fPurOSYQLV4FwcNXacDkN/MWIPNHsTI2OA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.17", + "@babel/types": "^7.29.17", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.17.tgz", + "integrity": "sha512-fvR+p3NNtZADSaekH7R5hVcv8uv0kDCXWlro7XVlH867QOLHs+u1e6NVcmCX7TUJNL9nqIVwNcz0Um3Glo0niQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.17.tgz", + "integrity": "sha512-6uFqkZstBw0lSRaEr/7HNuqURHubX4BvnN0FbbIBNFa5/nUcKLp5AFubCcUlbik9mI/Ztsz3mdjjpqoF3dVqrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.17", + "@babel/helper-validator-option": "^7.29.17", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.17.tgz", + "integrity": "sha512-wN402n5bTKhdw+DY0VgE+RU7evPzrLgiFpW10yo0Zo24cuPLGmgPVSWojfcAlXs8FkztWde8q+8poku1zACEnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.17", + "@babel/helper-member-expression-to-functions": "^7.29.17", + "@babel/helper-optimise-call-expression": "^7.29.17", + "@babel/helper-replace-supers": "^7.29.17", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.17", + "@babel/traverse": "^7.29.17", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-regexp-features-plugin": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.29.17.tgz", + "integrity": "sha512-SjOQHRXd37vQXhvtfmWO84qZvqZtr193/5Lq2s+4rMuoXylhwt1WYylTaeI4x9Oy5NTVKWCMvN+KrtOf+ok8TQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.17", + "regexpu-core": "^6.5.4", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-define-polyfill-provider": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.8.tgz", + "integrity": "sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "debug": "^4.4.3", + "lodash.debounce": "^4.0.8", + "resolve": "^1.22.11" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.17.tgz", + "integrity": "sha512-SeQUwFlH8hH1vjUmBFeqwxt6Nsjp01MKEZOtZPJ86lpA4GBdb/o0dShjC+Awf7v74/+84KIL1RiJ4TOJj6gU+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.17.tgz", + "integrity": "sha512-/mTo42pDFDxzfYCCL24qxlMPKHcz47iUXr9GfhbV/CHnFkOaAFObtsJQ2y3G3e2qP3eRrvlQ29QqBfVllOhonQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.17", + "@babel/traverse": "^7.29.17", + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.17.tgz", + "integrity": "sha512-bLxkfvUEHeWShbadKTm7EfDCkosXZh6PjWEa9bYiCuob24c0nm388ara2Hz6KisGaXe+XCsi6VyfJNSJjeUUwg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.17", + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.17.tgz", + "integrity": "sha512-eY/pAYlV7pC5biPmW0M7fDqv1D+opqI0Ioa6OQeg0AV3465b8K8g9I9fvZIV11u35f7jU6q5RXYlUD6k4QLC3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.17", + "@babel/helper-validator-identifier": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.29.17.tgz", + "integrity": "sha512-3D6B+IxDVqg0s3oLUe6p5nQ4VYtJSeLLyvd9c2dwrxVbd4uoyPjUNq23uhfhq21kjhFX2pJu15jVcMBYgLstjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.17.tgz", + "integrity": "sha512-pdztM6tDPJu52CYy07frAD1XpDAvndtxPhPyehcarNv5Pyq5hutWmTVXd0XIPaI749vUIJ+vxG6KYWoVExn+lg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-remap-async-to-generator": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.29.17.tgz", + "integrity": "sha512-F9ozmdIK2VONOv/sGnx7hVvA/bEUHMxSnoeaBN/E3FjZ7PnrUqJx7jnRH8qtqvw4mj37qpex00Fc0Bcu1C4RiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.17", + "@babel/helper-wrap-function": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-replace-supers": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.17.tgz", + "integrity": "sha512-yFmWa/3E81mCG9aHvkgfgnEncEM7QrpYwl5HawGN1ZbJ0n7UgegbcVYZRB+YJraRVAxhsrgqVQXjjnojdumcSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-member-expression-to-functions": "^7.29.17", + "@babel/helper-optimise-call-expression": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.17.tgz", + "integrity": "sha512-Qu080ZNwb6ZDozXfjjWvPTy+6dTWanQgmBHb/wIivl3yeZvvE27UWBEdn5d6U1WOide3kh+/B+7Xm0tvI/+Ygg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.17", + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.17.tgz", + "integrity": "sha512-iY5lvqFhfgMXp4o4zWads4NvQZXizBxzCoADPOgFMcMwk1XefAdBJbc9i1y94aflY57lokjOjRTa3AOOW9R7BQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.17.tgz", + "integrity": "sha512-AG+olLB+teKhkQ2WYJeaZqJwNLjtWTz1waQIP/tEYITzVzpdHLP7IXx2c/bH2JTsNCgvWlkqdCv91xcb8lul8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.17.tgz", + "integrity": "sha512-Pr+bjfbd4TYVax16KyHVyElTnid5nbWQWQvA/dPlESoKVZ8B4eTAUhoqug/mtD9hWAEgIQIOyvjUBMI9HjdrGw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-wrap-function": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.29.17.tgz", + "integrity": "sha512-2kpH7/YkL1aHQKBOKRN5gdSkUQmvVbXl0ZIx6q5vTn2Xn6iifvZDAFJyvPfvNSiYBJQN0lMV9yn4ZVGaGqNdYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.17", + "@babel/traverse": "^7.29.17", + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.17.tgz", + "integrity": "sha512-Q7LRJjIiFAiOtfkVBzXe4op1tQ8dXYsRsdojKzLfERndnXcmyyn9RZIBlSJzFo0O3CouXV3Tvb8AGolaDr1M7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.17", + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.17.tgz", + "integrity": "sha512-I+0olVqWMm9bimQJc/5B3jn1nivNDXtnMtDVs07XdHzZLcWa2N/mlCTPmAsQg95QcKoXSuFD2Yz4fwdtoyk7DQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.17" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-firefox-class-in-computed-class-key": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-7.29.17.tgz", + "integrity": "sha512-8jtzP+p4ixtQbd+yP3SYJ/T9ocGeUdgf0ZowzozebM3IEdk8iXNMcJfPUv15y3QyD0iE3kjrw8PmuNBZ0wLqZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-class-field-initializer-scope": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-class-field-initializer-scope/-/plugin-bugfix-safari-class-field-initializer-scope-7.29.17.tgz", + "integrity": "sha512-bOG06fJnQdsoc0L2eQQQl7NZpuqjMrifAvf2/3RSqzh0pNg6fJYqSowZMfLAxMs6K/LqEy5r5VB/Shfo6GtRxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.29.17.tgz", + "integrity": "sha512-PSl5Q1XxtW8y4zuxEqBHU2HzWGJTTlglJVk9RWwUtduKUtX5l8tDiBT06oGhar0WW/3hgdRmc3LbBiEXHPGyUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array/-/plugin-bugfix-safari-rest-destructuring-rhs-array-7.29.17.tgz", + "integrity": "sha512-DNah44OKcoypJTyIeYM0yAYX/DToo16e2rj0bjGwcf4Kelv8XFG/GQWhWGhN/m6gp11v8GrnOQ4UiUxbOvJlMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.29.17.tgz", + "integrity": "sha512-o8zNqHKXc467fbxtLPEnEFZedQtD5zx/UEClyg3X4G5FHrquHBcFdeUC3SlGT9b9H7Ld9yd4vR4xLbFoiMQGhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.17", + "@babel/plugin-transform-optional-chaining": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.13.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-7.29.17.tgz", + "integrity": "sha512-Ok8XJAVmprYl4HyIz+JZqaJrX3NHN2QrDScujOqz1F5wav8DnJ7Qyl0BnNGI59g94S30hLW9TrE3BaIKgd5mEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", + "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-assertions": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.29.17.tgz", + "integrity": "sha512-UA1lZTaghMx8HgkcLTkpFodJFWEbl3ICWQNNTJOFM9gFv2jxZFwLrhSYja+NS6sFY5jozkLpkcQFBcUlzJciXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.29.17.tgz", + "integrity": "sha512-LAVq6GOC7+6LSgVP+aPFAyDtqb90dMNdxkAR1y6jG3rP9LTmX4BIshEDV4o4CczrlHv5UL/dXfUK9DnigphOBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-unicode-sets-regex": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-unicode-sets-regex/-/plugin-syntax-unicode-sets-regex-7.18.6.tgz", + "integrity": "sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.18.6", + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-arrow-functions": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.29.17.tgz", + "integrity": "sha512-q2MPYTsdY9ct1Iae6m1Dzs0H0PkDoavQtTtEvnvUdkE2xr8pcMnHLNVEdzH9KCDKg7fGxxQgir8mZhpQCIYTcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-generator-functions": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.29.17.tgz", + "integrity": "sha512-GYhyjAK/sXGs8H941mFVH+Z69nta9jSN1tGY48MJB2xwSc4jQPnNDsRGhcHBFJ8uR3os25sC3r9zdvFhH24FvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-remap-async-to-generator": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-to-generator": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.29.17.tgz", + "integrity": "sha512-gjOtlu+GMs2WR9zOFNzQTbx5IYAtchEyfolBsYP01iuF0FFz4b9MeSb5cp7MwVcFoFuavaO+EfjB+0pgBtfS/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-remap-async-to-generator": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoped-functions": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.29.17.tgz", + "integrity": "sha512-Rrjn6t0ItbnLcA35jPK68I8uWxOnA1EsFi7BkLHYQ7eQ9s3FM8JKtiv3FOHKKZVxJfxXkKlmhAQXK2ECfDG4pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoping": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.29.17.tgz", + "integrity": "sha512-nUSscxaV0qMvS/ZR4Lc7dXBWcz/PwISV1pySs5xhxRuuWkRGhH7W0/hk/8LojZPgG4r3+rMIFGU8+oaRDBR6Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-properties": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.29.17.tgz", + "integrity": "sha512-bAPPnc6aGv3QzTkKV97Kodh2cruhycr0B9bFq8AGsQm81PyCSG+lcBCmdRtYAhvpKz+xno7REssecXrmrk6qbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-static-block": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.29.17.tgz", + "integrity": "sha512-B53EzbzOZgeW+5IE3wv/MWMaPIlpZNuwY1kd0PMGBVr2nmP5ELWZJ8wywgBlfUxLgX97rZNW6j6ljenQUZtK1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0" + } + }, + "node_modules/@babel/plugin-transform-classes": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.29.17.tgz", + "integrity": "sha512-BJZSyh8x5BdNV4LM7gyU8i29vb18R9jpAw/hLPOWPRnmmHblFnlNeu/F+zq638/Bqt1/Gp7BEomQU+142ckbbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.17", + "@babel/helper-compilation-targets": "^7.29.17", + "@babel/helper-globals": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-replace-supers": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-computed-properties": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.29.17.tgz", + "integrity": "sha512-8NE8coilcPpSRsqp9Ioufl6DQLPdtAW2+ay5Ke6mqeJLlutyJrHlaZnFLh2gG5FU+YvFBeFZK7mWg/PVnJO2gQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/template": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-destructuring": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.29.17.tgz", + "integrity": "sha512-iebptXn9fRatXQ/t0TsrZXll2WOqnoGE4NnYmTTOIJ5rto5UQOy/UJ4zfwhk39DwEwl1wWgLd1I183H2SSB3Cw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-dotall-regex": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.29.17.tgz", + "integrity": "sha512-iqLxKeSRciKpLRladclQ9xFA4kRkeKuFtU9o0HuHJXO9ssgctwqjPwGMNmqr1eibry60h5tSw2PtRZ5x/TLcrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-duplicate-keys": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.29.17.tgz", + "integrity": "sha512-w7oGKMEvyJV3P7stk2ERELBagPjkn9aawjLeTnfPZ2l8LB4+JCutQGiTP3Bc6rwvdHIGTtJyyKQjgK3/SyV4NQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-duplicate-named-capturing-groups-regex": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-7.29.17.tgz", + "integrity": "sha512-APR4PomE5QAbQ9dNhTipDecw/JiiEOOd8dO9t17X8M2GsZvxfmgdmx2Erwpb/Q7lX3miVpEViVvKwefuGGpmpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-dynamic-import": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-7.29.17.tgz", + "integrity": "sha512-eFBofeV+TMF2mLxkyGWL3yTYqwjX43v5BP5i7lGEVbKZPupLOrQuHrz6KpAYq0JA5oMRYfgkdAQ/PtdZFa984w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-explicit-resource-management": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.29.17.tgz", + "integrity": "sha512-kqsd+xyA/2FFhhnJrdoaBCb1dmsPnGA23mD8YV/gUQd1n/4dulxksX32peqne5Yl48ehPofQCYvl7L5aFsFNEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/plugin-transform-destructuring": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-exponentiation-operator": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.29.17.tgz", + "integrity": "sha512-NWti5xxKeoUSIr7K6dCxYTR35ca40QDJMh51AGmzViJqCX0ynJAA90vozSdaYgRmPSpIx/sMbLaVh2KCLYRi6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-export-namespace-from": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-7.29.17.tgz", + "integrity": "sha512-lVj1+lRiOm2RC9SVOFJ8gslt5XWJaJofEFdqzDakbEw6ImtmuJqPVcPnJwofPq16o0zTXaRKNdvWmkIy/ASblg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-for-of": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.29.17.tgz", + "integrity": "sha512-biX//ow5MvNtYDTzmrn/CBkvCagj3sBCtYbvnz4ID1pjOh9jcH/M+j2ExNijIH0m8gMRrI+JZUVLLA8UHEj2iQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-function-name": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.29.17.tgz", + "integrity": "sha512-4IUF7769cOCnc44O/QAFDHkl/tT5CuMW220NVSNEf5WTiMubN2A6R7dSKS58LuyuJHsUHg4z++nGGCGcclhyMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-json-strings": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.29.17.tgz", + "integrity": "sha512-wESwmOL8vIlODnh3ML4jRj/qmexmF6JOYJItxZm7VV2dddmfQliS4pjVvT0o6dQ7bRKv/pflWsUQc/6ayDixDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-literals": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.29.17.tgz", + "integrity": "sha512-9+dpLK5HnTpCSqgRhIEqmy5efBd82wwIWYYA6W+sUhoT9ICFHloD6UYR0hCYfJJMKJS+p6j7rCRXV+A268sTtw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-logical-assignment-operators": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.29.17.tgz", + "integrity": "sha512-XNVE+kwpsqhkyhiqQ4TIhuBD5z1sDpp0i9AlZwoeTJQjEgOjO/FsNZawlQ35Ohex3cLwNGog9T76a8pagdF5Ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-member-expression-literals": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.29.17.tgz", + "integrity": "sha512-IT8hmtSjwfIymQ4/sYSs5Ni5hp1uTi173U9G2NTcNPd7b4Crt4fnsIvXcMaBBuXirqkudgdidEGH6eXvd6FGFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-amd": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.29.17.tgz", + "integrity": "sha512-pWJUQqVnUdcIIErXDBgbiGbgraz/hc95/RtdqyGyUf4c8KDEVQ/4lFKWz8Q62uipq3+yYMjhCfwiSrGNntBTPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.17.tgz", + "integrity": "sha512-pm8Y/ei0BNKnQDlgBxt1Gdh6nD+ulWB0xooAADgiT8TTXXPxDzU93F2OraEfei2s2X0UFvFExc4Ag9A5GE4XWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-systemjs": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.29.17.tgz", + "integrity": "sha512-BpPzdCkJTHguUouCuc0S5+35OMzkvSXysD6082AhtoIL74NCJJkvAQNmYiF9hEkQzl+Xo8p5Vq1S3U7FIWxwgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-validator-identifier": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-umd": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.29.17.tgz", + "integrity": "sha512-LUwkZJRe1p7xUYSx8EYBThjT7xdNhFUUEHoTJAdDIRoIcxNmEWZRBiKKUvTm+w59SFF6V2tnaeH0kjEwGymHug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.29.17.tgz", + "integrity": "sha512-TeLMadZJwUx9DXETgUsGNNRJ0tiRBLyCEduJxgqz0euez3cw5OhXp9ooCnkfOSNMZ5kzSXhJXPp6b6s2Tz+rnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-new-target": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.29.17.tgz", + "integrity": "sha512-BjpKlXJ+feuIux+ctjdXJHsdM7syyMgXJbYBKAq0Pil2Y9kG0TtXjC+u7wQm3MHHPHHo8WWx2I8McBrPxSQ+Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.29.17.tgz", + "integrity": "sha512-hFUy6UxMqhaJSSaSKlBOPreiWWQQV0/W03nS3WSqe14LwLpbeZcvF/HTSC32Njd61JbJS9nGnadGqQB7qPeIVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-numeric-separator": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.29.17.tgz", + "integrity": "sha512-Rmt/dkJf/+xTxlFa/ZrxKp+p/TdQut3x8u1g1w0gNzqXjRvlKsHKZv9oPy/veGZGjEczcLzw4Cry5o5PmuuY+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-rest-spread": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.29.17.tgz", + "integrity": "sha512-Po5+rRF461T40ARmQUMBuWW+ciqvezMLopf4n2GS6AR/MCVYkMB96nSUmRjMwsZiU9yWSef7Bu9pi3fXTe4F+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/plugin-transform-destructuring": "^7.29.17", + "@babel/plugin-transform-parameters": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-super": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.29.17.tgz", + "integrity": "sha512-yruEO4LT5rpkNA65Sp0f6MQO/ioPjvlyoJPj9ghrbmYzmLpF4B3bxTtq90ydy++MxWqkIBoIXWA40h013jM/NA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-replace-supers": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-catch-binding": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.29.17.tgz", + "integrity": "sha512-62+soYiJwm7GqbTsejo23BAASW3lC9x80lJqrEPbDv5P/JNq0D6FEt7mfQkNrr0HRZBG7NOV81FtuSdPru31/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-chaining": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.29.17.tgz", + "integrity": "sha512-RY0fenokpzl4GF1zXdWd1c7gPvInnbIQBh9SGlp3VJrcbZ12ZRXijlMMtehTpFsPum/m+7T9j6ZjIBMN9b1KhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-parameters": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.29.17.tgz", + "integrity": "sha512-AB4p3TS9gGPJnVOWOTFzA0r6JZCQVIonmgBhuGaxUIRPIkR3H91mCxOyFy4nLx/6GxOQ+dVoav1I+aNeKEX4rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-methods": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.29.17.tgz", + "integrity": "sha512-pvDf/4JPHHI+qCf/An3PNpqWgPi5nrMTJhF1VQ6TwehNSx8UUALYkeVPoW3mVSdWi88up+OwKCrP3P1EZXY0OA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-property-in-object": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.29.17.tgz", + "integrity": "sha512-aL+JlLI+FjgHpMVd6NIMPHKBfEcwA7rfD53knSIUVc4RfqTArr/WyGd7AFEGuew/VgJPJZZThgxDqy0HKFmSRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.17", + "@babel/helper-create-class-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-property-literals": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.29.17.tgz", + "integrity": "sha512-O/ABojCLBDgi1UkuY/tZPRgd1TZp+8DaNCZUXSaqctopv06RWnNseDlYdGjsPJy3jM4u6eUPCy/9kTIv8psQdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-regenerator": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.17.tgz", + "integrity": "sha512-eYOeX3AUcgvVatFST0l5R2a7J71sCqkckgB1+I8UT+cQrixj2XKvC/el/zu/2Exe3o8IhmTJ9dBwCUW8DDXr5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/traverse": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-regexp-modifiers": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-7.29.17.tgz", + "integrity": "sha512-mPG8dYn4XF4s2UJjGiAJxUI0YhYRaE9W9OsX9YTSZXFymRaSiC3xOSkITw66ImmP+cam5qYa/W85MNDT4M+iPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-reserved-words": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.29.17.tgz", + "integrity": "sha512-rXP/0AGqDzOakfegZpdy0d3aMS5cI7aH8r1tp24M/lYI+tGD9LXWOFf9PqU77WqHNKwEItQfRWFGxE595WBOPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-shorthand-properties": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.29.17.tgz", + "integrity": "sha512-Ip4Jg7tcuIj6fS1vHZPW5EWKqoAaojBKXhN+nkIVWP3jZROJj2w4CkgCTgR3YGLLYfoD6HBhE6RESr3DxeZimw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-spread": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.29.17.tgz", + "integrity": "sha512-HTugAMid6Pb5OVY24Pde7daQqxJUlkFnX1RjLUEbSwKZ5bzwc9N+/c3EtodMvINIyGDlJ20sM+I9kc1CkzRS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-sticky-regex": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.29.17.tgz", + "integrity": "sha512-N1uO0PX1nQIKO5S5GYc4u7O1a6b0JbVYJvtCgOqgckMdLILUDjfIs/zenF9KAAqSfEWkZOcIMLLt6KIueUIDEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-template-literals": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.29.17.tgz", + "integrity": "sha512-FP1wNBcgqBxy5Yun/enep9Qv2T8ur02ObbM+o/TJvwH1qOfqWJTA5G5n+jxjhLOMm5LRA+mjjOhzan3M1RrYEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typeof-symbol": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.29.17.tgz", + "integrity": "sha512-4PWdL3zRYJKtUJ7rCBq5SjmJa+sl0V7C9CsipCrwycPtfmcBmLqI57QO6nlplj5icCkr3MoMeKFe2va3qDbNmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-escapes": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.29.17.tgz", + "integrity": "sha512-jYKefjRRdWw0lgwGTBE8DdC1c7cnZApeRPGxVkXJ+aDCmup4uyEdeMY/bzy/X3+aSg3Rlf3o30X3whqOedXCKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-property-regex": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.29.17.tgz", + "integrity": "sha512-EOLDjq6FzuPVbfoJO2ad9PmegP5lfJ/O6Fi3l2ZK4qaUZeIaz6Qas51w3CMTYcZrZMnOuhNFGdr3J90qUBlxgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-regex": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.29.17.tgz", + "integrity": "sha512-blvNpLZuO4qmj9oMakw/fDhiTxFUDmgR3kd07yRPIPDXR1cWBUdMeYs8amgAp5W4UUWgp5sJ0TODd71WNbAuHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-sets-regex": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.29.17.tgz", + "integrity": "sha512-8dh2fnyWihUCt1FtlzbJ37SzZfkgMfqP2I/3KZbRdbZ03xt/3wwQTT7yNfgieJ3svh2VIGObVWmj7PjltPW+DA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/preset-env": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.29.17.tgz", + "integrity": "sha512-LQ72QZm7CZDM/jFE+iDkREhftXu1RIMYz3XZ0W47bgemlfp9vYlLIu/22LE/FwOopTSOIqMheuOgwMlxD/TI/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.17", + "@babel/helper-compilation-targets": "^7.29.17", + "@babel/helper-plugin-utils": "^7.29.17", + "@babel/helper-validator-option": "^7.29.17", + "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^7.29.17", + "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^7.29.17", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.29.17", + "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "^7.29.17", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.29.17", + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.29.17", + "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", + "@babel/plugin-syntax-import-assertions": "^7.29.17", + "@babel/plugin-syntax-import-attributes": "^7.29.17", + "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", + "@babel/plugin-transform-arrow-functions": "^7.29.17", + "@babel/plugin-transform-async-generator-functions": "^7.29.17", + "@babel/plugin-transform-async-to-generator": "^7.29.17", + "@babel/plugin-transform-block-scoped-functions": "^7.29.17", + "@babel/plugin-transform-block-scoping": "^7.29.17", + "@babel/plugin-transform-class-properties": "^7.29.17", + "@babel/plugin-transform-class-static-block": "^7.29.17", + "@babel/plugin-transform-classes": "^7.29.17", + "@babel/plugin-transform-computed-properties": "^7.29.17", + "@babel/plugin-transform-destructuring": "^7.29.17", + "@babel/plugin-transform-dotall-regex": "^7.29.17", + "@babel/plugin-transform-duplicate-keys": "^7.29.17", + "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^7.29.17", + "@babel/plugin-transform-dynamic-import": "^7.29.17", + "@babel/plugin-transform-explicit-resource-management": "^7.29.17", + "@babel/plugin-transform-exponentiation-operator": "^7.29.17", + "@babel/plugin-transform-export-namespace-from": "^7.29.17", + "@babel/plugin-transform-for-of": "^7.29.17", + "@babel/plugin-transform-function-name": "^7.29.17", + "@babel/plugin-transform-json-strings": "^7.29.17", + "@babel/plugin-transform-literals": "^7.29.17", + "@babel/plugin-transform-logical-assignment-operators": "^7.29.17", + "@babel/plugin-transform-member-expression-literals": "^7.29.17", + "@babel/plugin-transform-modules-amd": "^7.29.17", + "@babel/plugin-transform-modules-commonjs": "^7.29.17", + "@babel/plugin-transform-modules-systemjs": "^7.29.17", + "@babel/plugin-transform-modules-umd": "^7.29.17", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.29.17", + "@babel/plugin-transform-new-target": "^7.29.17", + "@babel/plugin-transform-nullish-coalescing-operator": "^7.29.17", + "@babel/plugin-transform-numeric-separator": "^7.29.17", + "@babel/plugin-transform-object-rest-spread": "^7.29.17", + "@babel/plugin-transform-object-super": "^7.29.17", + "@babel/plugin-transform-optional-catch-binding": "^7.29.17", + "@babel/plugin-transform-optional-chaining": "^7.29.17", + "@babel/plugin-transform-parameters": "^7.29.17", + "@babel/plugin-transform-private-methods": "^7.29.17", + "@babel/plugin-transform-private-property-in-object": "^7.29.17", + "@babel/plugin-transform-property-literals": "^7.29.17", + "@babel/plugin-transform-regenerator": "^7.29.17", + "@babel/plugin-transform-regexp-modifiers": "^7.29.17", + "@babel/plugin-transform-reserved-words": "^7.29.17", + "@babel/plugin-transform-shorthand-properties": "^7.29.17", + "@babel/plugin-transform-spread": "^7.29.17", + "@babel/plugin-transform-sticky-regex": "^7.29.17", + "@babel/plugin-transform-template-literals": "^7.29.17", + "@babel/plugin-transform-typeof-symbol": "^7.29.17", + "@babel/plugin-transform-unicode-escapes": "^7.29.17", + "@babel/plugin-transform-unicode-property-regex": "^7.29.17", + "@babel/plugin-transform-unicode-regex": "^7.29.17", + "@babel/plugin-transform-unicode-sets-regex": "^7.29.17", + "@babel/preset-modules": "0.1.6-no-external-plugins", + "babel-plugin-polyfill-corejs2": "^0.4.15", + "babel-plugin-polyfill-corejs3": "^0.14.0", + "babel-plugin-polyfill-regenerator": "^0.6.6", + "core-js-compat": "^3.48.0", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-modules": { + "version": "0.1.6-no-external-plugins", + "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz", + "integrity": "sha512-HrcgcIESLm9aIR842yhJ5RWan/gebQUJ6E/E5+rf0y9o6oj7w0Br+sWuL6kEQ/o/AdfvR1Je9jG18/gnpwjEyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/types": "^7.4.4", + "esutils": "^2.0.2" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.17.tgz", + "integrity": "sha512-CvlZdpED5dsu21yK0DfpXksJWt1zeW09lY49hp7P9cA5Qedx/QkwEs1PfluSJjijH9i94oT9LmtgGWlPY8ISzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.17.tgz", + "integrity": "sha512-D4nOLKOzIBwn7/Z78h3UPEwzFObmPVTukBJ9+63BijgMVeLj6mQ77FJb6YCZ4QBo6VjAk/yj4QnpKusTcBy6vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.17", + "@babel/parser": "^7.29.17", + "@babel/types": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.17.tgz", + "integrity": "sha512-q+CnfQcmNfDdOUARkt9FWtdR0HPOCcyQBj1Z7l2SOpFIfUB/XI3dXS0B5UOlZWwQCun80xVhgcv4ip6w128u9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.17", + "@babel/generator": "^7.29.17", + "@babel/helper-globals": "^7.29.17", + "@babel/parser": "^7.29.17", + "@babel/template": "^7.29.17", + "@babel/types": "^7.29.17", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.17", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.17.tgz", + "integrity": "sha512-kzo3lZUbI0gARA4QvhmOTH/aws2SrZ880ECQRIjPPSrdfBM0bZCkj1U7UN2fB0GNeXayqCiLVXa2+1jAhn377Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.17", + "@babel/helper-validator-identifier": "^7.29.17" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@cacheable/memory": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", + "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/utils": "^2.5.0", + "@keyv/bigmap": "^1.3.1", + "hookified": "^1.15.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@cacheable/utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", + "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.5.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@canvas/image-data": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@canvas/image-data/-/image-data-1.1.0.tgz", + "integrity": "sha512-QdObRRjRbcXGmM1tmJ+MrHcaz1MftF2+W7YI+MsphnsCrmtyfS0d5qJbk0MeSbUeyM/jCb0hmnkXPsy026L7dA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.4", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.4.tgz", + "integrity": "sha512-1qH3WeISXHFS8P3QI0lntHlMrlfTh1OarxlRbPNDEkSCqoyXC3apBE7MDyRKOL8HpuW48aQtff30wvEFww/4ww==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.23.7", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.7.tgz", + "integrity": "sha512-Ix1tmZjA7/OmE7ROAfORe83hVnqlDzLpZVHFjHQt5mvLm1U03qMexpaxKqFIL362QV32SoPaZqmKQr3tdqFY2w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^3.0.5", + "debug": "^4.3.1", + "minimatch": "^11.0.5" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", + "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/core": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/js": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "eslint": "^10.0.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/object-schema": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", + "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1", + "levn": "^0.4.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.6.tgz", + "integrity": "sha512-KYADSb7k/uEBsH4qROTt7d3Kyw/6EhJ7U3cfAnS3lNLahelMWpLkCNkkYQEcC0fvo2B5v4zbRS+iNvcARKS57A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.5" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.6.tgz", + "integrity": "sha512-JmPryNzWaIMVgJp0wtGH9Cnzg2y9iZBCh0ZpydpjX81GrrJ6TV5fdZ2iqY/41dzXZNi7zUfNCrOEO/gyxb9WzA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.5" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.6.tgz", + "integrity": "sha512-LJKJXPzEEodPm/sxojGM3Hyw+ZRLEyiGWb7kbFSKp45Myu5z6Nz8AtXvPxRPYLqrovf57fVx2vMJjp8QpyK1kw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.6" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.5.tgz", + "integrity": "sha512-MJiGpG6czDeMzK6UdnrrCLYJEouGtLtsqiZZK8MOk0i+GPuKQ+lcpt7Hdi28h5Q0PLGpgTSm1AdWtAxSn6CD+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.5.tgz", + "integrity": "sha512-jFJxbGYWkY2heVwjNBMGq0C3p/iXO185mnTXXHmMsSU++/gUJRKRaeyEkNXAMq4/G5S+0wgI9cgJi6uPI+N1xw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.5.tgz", + "integrity": "sha512-rxz62CIW3nu8nVQtjNzLsxU3I590vF3KyD5WIlGAxkFRAF8SRgCxuwJDxMUDFoRXDohHFuBO9l3KNOBY4FfPzQ==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.5.tgz", + "integrity": "sha512-uobFASVW42cKPBb+Vzk/ISzq9POzJ2BurZFvZqamTctzBxcAHc8mOBg3m+kxywHoDaOFziZeTg6uCcMv3s3vkA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.5.tgz", + "integrity": "sha512-GGNQrxW1GlzSrAYU1s0e6Uf8w24xefGnqxdeC5nebMq/3vG5zhn1nejvUOEmCP97K2W8OnE3jkz+mJiYZonR9g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.5.tgz", + "integrity": "sha512-GPkVkpYZ0SUIntq4rVW5rdw9MDYCMHnRk4rk7jUb9kyBHaK4hZIyzaco5c4scbcOrihrx00ju2moYIVwaQb76g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.5.tgz", + "integrity": "sha512-euEyiYAiYzQsQaMiD2ozdHIhv6z7zpQAQ/+DF4U+rK+WX5O/HOtoUG4gzE9RDG3SnH14fjmb0doIETOmSXIXnQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.5.tgz", + "integrity": "sha512-3VGDsRGFGVidz6AIeLWYxNlo6yZizVkEr0O3dgex6rsNHtCm6jgIj6bseSfOamn8Nq/Hcw6JZ9TxTT5ASjy+Sg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.5.tgz", + "integrity": "sha512-9HL8D3phclHet2O7tYDc2iCvXWwK53K2Aq8vAhyRP0sGlaaPkNrjPSIHB0Zv70OV/k2XEOfM/R/TOQZf5YqTuA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.5.tgz", + "integrity": "sha512-jqKulDPZucLJvnGhItA8h48eIiV8NbN5pPhYfv2KOYAA7JhuKSLIyrkhXcSoOpeTGpp6M9ALEPWR3WSD1lWTFg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.6.tgz", + "integrity": "sha512-Bt+upJ9wz8U77LRFAX+Js8m4YV77rSJzQaproiujWp+iuGixrb5K7fiB45r4z6Ggr2bNKtwOTAAYz/QwfLtGjw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.6.tgz", + "integrity": "sha512-XcdFuf3VFqBnbe6GzK2HJVrm4qxZFjvVt7MUO3+kIY2vVVt92/6RgnFlyYPr2jIMMYh2L0u3y6Cu51W+vlDeXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.5" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.6.tgz", + "integrity": "sha512-kjOL3DyNNtMZp/yMMNjak5F0LrAB0tdkI23mq5vLBqKBbT/z4+Xm3BIt588j/1OIuj2/zT37B6HuuL65KLDUJQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.5" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.6.tgz", + "integrity": "sha512-Py3xmzx9Kdfon125Y8mhUxty+8HT002EZvXpO/5ChlBUssL7/wTsdioqe90ssgcKUacBIY6XPWDCNy3ga3vO7g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.5" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.6.tgz", + "integrity": "sha512-zaUowlVkx7BNhLh4FwTiR3rPK24BzgdS31V2FBdYZPVPqCjevlWj+UyoEvAjUEsaVAIBBWvJ3ykExLgMAIz/rQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.5" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.6.tgz", + "integrity": "sha512-z3/TzV7HWy04uyYKJwZPoUIbiKeFhDZCfDbnSs8QidcXNT+EIWm5TqveYCRqcpN3prdZsG4rp58ImdPZXmeKQQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.5" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.6.tgz", + "integrity": "sha512-1Zm1Fls7MArY5PYUDb9NXjm12oKCmhMoT0gd2u+gIzzXURtEe00Z7iBOYmgHmeSOk2vnQt1mQ73wvnRoWLT5Ag==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.5" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.6.tgz", + "integrity": "sha512-PW4giS1EckJ9xRssMaqByoapbipIlHqeisneFxzyMfe6DzWm7l0n7P/6pYXisNKVG0YCLpGi2O7SHlap0qn7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.5" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.6.tgz", + "integrity": "sha512-rHnklXQRJbyqcbSXK6mKSep9M9XM70xtiYQfwmlgzlWDgXutzvDXRL8Si2lYleuypW1VENqZoupsiKJEaS0kjg==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.6.tgz", + "integrity": "sha512-N7Bw58M1wpNGLdW7i0PQ79Mrp9btFePJEee68kD1ucxBcMbEwbQHGrzClqDZ1S7eNDK5LuSqs661VwW9LilAlA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.6" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.6.tgz", + "integrity": "sha512-KpzGhqW+gri4DQI2qWNSWFluXyX6Ads+9I+zAvfTzBJGPV77M8fx7pNSrt/U9LiYpgQwLFxINl0QpKckYD5h3A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.6.tgz", + "integrity": "sha512-c/6yly6sQDY0C4f95WJ798K6pkzVETMrxCoWeaZAS7G/GKdQAgJXZZ410KhTle0xsmVYn1APJgiuSERRIgX4FQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.6.tgz", + "integrity": "sha512-EUgDbmorr4LYwGXHxhioVad3HkCu3kFVuuDzIQqEKrk6XwOCxXEIgqQchMdZpzfb1rnWLa/jDlC2ZLU5hz6zNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@isaacs/cliui": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz", + "integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@keyv/bigmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.4.0", + "hookified": "^1.15.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.6.0" + } + }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@oxc-project/types": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz", + "integrity": "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@quansync/fs": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@quansync/fs/-/fs-1.1.0.tgz", + "integrity": "sha512-qAPG/t3HqML1TlN7sY/pTbEjzFVAKsMjNNMGheyDosro+kT4iw2KCUoHcVdmliwWjorm4elZbgNQyU2eD97eDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "quansync": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/@remix-run/route-pattern": { + "version": "0.22.1", + "resolved": "https://registry.npmjs.org/@remix-run/route-pattern/-/route-pattern-0.22.1.tgz", + "integrity": "sha512-czdGJWh09Lapvcqt7Vb09KlrU2PhRJ8xQaI+AItTuD9aDJ5MAgxnS38lnys6Ll+6RJEqPiaUqTwIQhVLwFvv+w==", + "license": "MIT" + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.4.tgz", + "integrity": "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.4.tgz", + "integrity": "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.4.tgz", + "integrity": "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.4.tgz", + "integrity": "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.4.tgz", + "integrity": "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.4.tgz", + "integrity": "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.4.tgz", + "integrity": "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.4.tgz", + "integrity": "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.4.tgz", + "integrity": "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.4.tgz", + "integrity": "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.4.tgz", + "integrity": "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.4.tgz", + "integrity": "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.4.tgz", + "integrity": "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@oxc-project/types": "0.160.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.4.tgz", + "integrity": "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.4.tgz", + "integrity": "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/plugin-babel": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-6.1.0.tgz", + "integrity": "sha512-dFZNuFD2YRcoomP4oYf+DvQNSUA9ih+A3vUqopQx5EdtPGo3WBnQcI/S8pwpz91UsGfL0HsMSOlaMld8HrbubA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.18.6", + "@rollup/pluginutils": "^5.0.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0", + "@types/babel__core": "^7.1.9", + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "@types/babel__core": { + "optional": true + }, + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", + "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-replace": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-6.0.3.tgz", + "integrity": "sha512-J4RZarRvQAm5IF0/LwUUg+obsm+xZhYnbMXmXROyoSE1ATJe3oXSb9L5MMppdxP2ylNSjv6zFBwKYjcKMucVfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "magic-string": "^0.30.3" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-replace/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@rollup/plugin-terser": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-1.1.0.tgz", + "integrity": "sha512-b6C6M5XyeKyMe+gmoquyRmrKEmaBfgHO1A/Z5NHDV060ECJEfmi4XV/7UuPm2UcT9IHmB65l0Hmi7ZZYSPRAtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "serialize-javascript": "^7.0.3", + "smob": "^1.0.0", + "terser": "^5.49.2" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "rollup": "^2.0.0||^3.0.0||^4.0.0||^5.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.6.0.tgz", + "integrity": "sha512-sHGIxCuydUbd2Rr3eg5TQqXSIA5Gi7esaC0T+v1Wr4n2jbJMXb9r133pRajV+5HM3dgr0bJIQQPO6ZxXabFTYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0||^5.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.69.3.tgz", + "integrity": "sha512-WDG3WNktJVR+OTqdP/OrBg2b+JXXIgIZ+Ppzp7gjaRK9C59fn3vcFhUqjtxiscE9lygTYP3EFxY9xTLUfEFRaw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.69.3.tgz", + "integrity": "sha512-D5NgwE943sMSNRGoWFg9r2jPUG7EWk0/BYNgG3C/lIHAqY1M+GTA7EvQtCAJxKUv6gtb4lBOvx/0+8GS6yOIdA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.69.3.tgz", + "integrity": "sha512-qT8AKzfYdZfAsoI/UFggqr1ghJfhW9GgGgDHTrYDviKvgGzqcteSjfaK0AwwJtbnbLu+FrMGF7RlGXfrZ1uFuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.69.3.tgz", + "integrity": "sha512-UdQ9EDKcIyJEyQ7rKcxwfTVZt4SoM4o2NxTEWb6WFSK2SDEJKMEXjkEd6csGOfzKnr8xBUAtOLN7WnocRSjqdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.69.3.tgz", + "integrity": "sha512-i1a4Erge+lLWo3sSlwX9LU/KK4CkaLZe7kvCc6Fc8NNKiW6mRcXcebRze9pPdGyfdA5SVcnl9pxekXK4O+Gbcw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.69.3.tgz", + "integrity": "sha512-w30OkToJS0ed5UEqXBu61gg8/adzmcnvOc7qoZi+92FsOYtVmLlQGHeVqBn9GGiruk2aiDJpd1fMHwZhOhj8rw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.69.3.tgz", + "integrity": "sha512-Ze4Bo4axd2xzxG72ltgQtOcRuY1zyw47Z8bye5gDwgehBglMA0AQwGy2dL1MZ4ZutjdImwVc8jbL/geawm3wjA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.69.3.tgz", + "integrity": "sha512-hzMaEmx1VYvlfesicuLSI58962aaPvwK+J8Ksi1Qqy6GfM/Nsq8IDKYzw/Mg3DI5JlCwnuEcPj9ymzsAtk+sPA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.69.3.tgz", + "integrity": "sha512-EZRv+RnscDTuXinvItllk8VNO81mdYjWlupt1QexTPOuSt9UDkRHH6C2ArJBiNyaHqxA/dDAuK3vWAFKLmMgAA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.69.3.tgz", + "integrity": "sha512-8TNXGRkMqZ7QIL3KvpL0MXGE1ueqWnm1I40CQijo6G/CCKzoMUOsMdVmfgjPGl/G22+FtQMb3+6Moc6obmZ5vQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.69.3.tgz", + "integrity": "sha512-VWRKTMZq9N9EWxDRYgLAxE4Ory+O9ZO7+m0RjWlTjhtEF9V9ts/fnfgEjDisF2wYmmJA40c98HuREBlIT29S+w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.69.3.tgz", + "integrity": "sha512-UNm9BN6OuckVOAYvsDT0JHGQF3Lt7gjcrZL5JzmR8JvzfMb4SGjUcWtBL+fkUjdwT81vsBvUyZMZCman6dwNxw==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.69.3.tgz", + "integrity": "sha512-8w6fC76ChAodM1ZAEdpNlIkV7jq+HDHpa1xawVfOdwFsgWVWQkKcYa36bFlo58PWxfinMEuMWnyyWl4Ro3mjZA==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.69.3.tgz", + "integrity": "sha512-5J/hPeDhQ8hZLRpmaNpzI5G4fT0qQQC47uj1dwCdJwd8/yk8v0aiZJ0V+Sw4HGiScgMBANKVZyrzedHqRCilIQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.69.3.tgz", + "integrity": "sha512-MBOWof2RZbbM2gTUagZsEwmIUAesxvB2zxnX3Af4M69NVdqDvGEXGkV8zYfXjLoJjiU7J1mzDHABmXhz5jMlZQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.69.3.tgz", + "integrity": "sha512-pzpggub9hyhZ89uAcXORCg6loWFoQOoTFatNpcJuiCqRdQvQa1oK37eG+vnVdFbULAzIuRlMZu23l3433OZi1g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.69.3.tgz", + "integrity": "sha512-kUlaRxOwQKcdLSo2CrHpTVFZaKrrEONZz6yDmX2UUgzSsIUvNPGlgGEQ6mxBwCYWzIrXWtu0nILkYIc+5dZWDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.69.3.tgz", + "integrity": "sha512-N/xL1PKN8D+CIX6/Mdnkr/T5FuZVzov5JbzQiGGaMlsVdPBi9If0qN8E91p3ex/JT9nCYKe9WNrKeml7xi87lg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.69.3.tgz", + "integrity": "sha512-uBpTadP1uQZZvVe+AV4dsTwNfs1H92Ra231OcHW2PVOYdW83PS899Wr3bXGbJO5erxWVfiZ70oPnhCPJ5utL3A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.69.3.tgz", + "integrity": "sha512-4MWQvR0w9Ao4REGwJoFZxKKtU//Bd6vl0wIexJaG0EhxbrzMdIKotNkih+qJxlZjdJHf6/W3ETZ0CrEXeNTTcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.69.3.tgz", + "integrity": "sha512-GC5b98fZgnb4MD0GSO/7XFVK7z2m/geaVS4CATdb7QA1VetuXhQJxTdlJblk4uriCmS9oexARH2fVbWR+FQOLA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.69.3.tgz", + "integrity": "sha512-jrsZxYM1Zyr0QXuHVHoRGC6tvqakkr96Vvy2eM8HYqxtmlWpjITW7pCEzDkg/X/IjLuUdyGJ693E4WJ5NcUXxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.69.3.tgz", + "integrity": "sha512-SnAwiYVNy5lfxVL7BQhtg3UbrAvAhSSonI342A5JbrznG6t8VvvkCDyLRXypQsRBvxIBVDrelpgR9yDIAlwS4w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.69.3.tgz", + "integrity": "sha512-85tt4vmTGSq04BsY0FKnYif4JHD2aR+MeoC1cUbdZkTvjOIYO3iHmPTpOf2nOympL6yZngvJjLmeoBzUsGUJmA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.69.3.tgz", + "integrity": "sha512-IpRuzCYcIfSNxcqHertICkJ7JSHM74TeN5lGleOE1jGK9dPphyIB2EfFud/8oZRrt3CVd3z10UIRzLJQflnVcg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.69.3.tgz", + "integrity": "sha512-dyv+ETPjCDTn03T5ZAnk+OvB+4+yg1onKgTb7jjv9LQ8KEwcvUkZmIPtNTdreULsKX0Amaod6C2W1iSFseTiwQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@simplewebauthn/browser": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/@simplewebauthn/browser/-/browser-14.0.0.tgz", + "integrity": "sha512-1odWVqeEBTl7lJ9zMKLEsmTlnyrDO5iRcTvfMKKk1WThUnp/i8JJdffdj2icP+tty159s4PgwE3BiMoEW9NFow==", + "license": "MIT" + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.5.tgz", + "integrity": "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "tailwindcss": "4.3.5" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tanstack/query-core": { + "version": "5.108.4", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.108.4.tgz", + "integrity": "sha512-2Ks5dlLWz4eXJrthOyG0qW3SLt3xx0RrQmAmN0rnmogiaaOYuWiAe6HAm9KE2b2v8nig+vraNz8fsfZ6fF6zFg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.108.4", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.108.4.tgz", + "integrity": "sha512-GlTa94kfEKTVsbzXe58rFA3GZ0ZE7N1aFtbZAfOS3XxMv8YNn4C+8rsz40LorHLazdm5PsqCroWaYAR+ZkMXMQ==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.108.4" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@trickfilm400/rollup-plugin-off-main-thread": { + "version": "3.0.0-pre1", + "resolved": "https://registry.npmjs.org/@trickfilm400/rollup-plugin-off-main-thread/-/rollup-plugin-off-main-thread-3.0.0-pre1.tgz", + "integrity": "sha512-/67zpWDBLV+oYAEL682s1ktXL0HgqX76f6gaVGkGnVZlBbm1zd0v4Bz8MFF2GGhoX9rvfq3KSQHubFHwa6w6/Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "ejs": "^3.1.10", + "json5": "^2.2.3", + "magic-string": "^0.30.21", + "string.prototype.matchall": "^4.0.12" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@trickfilm400/rollup-plugin-off-main-thread/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/esrecurse": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", + "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.11.tgz", + "integrity": "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.11", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz", + "integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.3", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.3.tgz", + "integrity": "sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.74.0.tgz", + "integrity": "sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/type-utils": "8.74.0", + "@typescript-eslint/utils": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.74.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.17", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.17.tgz", + "integrity": "sha512-0c3zcBRlWmcKhcIQWckzkYncJRv5HHB8O32wO/FcWL8DDXWDJgiEF6SX9ThbTv5h/eZ+xJK+VvDjjQ+cQJhp3Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.74.0.tgz", + "integrity": "sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.74.0.tgz", + "integrity": "sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.74.0", + "@typescript-eslint/types": "^8.74.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.74.0.tgz", + "integrity": "sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.74.0.tgz", + "integrity": "sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.74.0.tgz", + "integrity": "sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/utils": "8.74.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.74.0.tgz", + "integrity": "sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.74.0.tgz", + "integrity": "sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.74.0", + "@typescript-eslint/tsconfig-utils": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", + "debug": "^4.4.3", + "minimatch": "^11.0.1", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", + "typescript": ">=4.8.4 <6.1.0" + }, + "peerDependenciesMeta": { + "@typescript/native": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.74.0.tgz", + "integrity": "sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.74.0.tgz", + "integrity": "sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.74.0", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@vite-pwa/assets-generator": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@vite-pwa/assets-generator/-/assets-generator-2.0.0.tgz", + "integrity": "sha512-GBjHBLBzOP1GDJTc7MjeDdeJTi+PS9eFjw3HYjNHXnEbkS7vRS/YFwl8VW5/4vWF0Fo35Mji1yXAABvSVzu0Ew==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^7.0.0", + "consola": "^3.4.2", + "picocolors": "^1.1.1", + "sharp": "^0.35.4", + "sharp-ico": "^0.1.5", + "unconfig": "^7.5.0" + }, + "bin": { + "pwa-assets-generator": "bin/pwa-assets-generator.mjs" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.1.tgz", + "integrity": "sha512-kYc/mQZ8hnpFXNJXdrbm6kUbLya+V+Q5o3V2j06tR+4lVSyY9Pgx0eBw+eYTVseNUiMY2hr/3PM/EHVOYNKuHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.1.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.2.tgz", + "integrity": "sha512-UGc97wUIy0Ji2+9GxzHEJiOhiwkaukgE7VYcUNnjpX3sWnwQ8XogmNXX4WyOukxYgKb8Nh2XFa7KId0ZjpmVhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.2", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.5" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.2.tgz", + "integrity": "sha512-PQl0/3+p9GaY71+MHywN6oyHfLhVDD5kcbm7oNRldA2F0ExMU3S8RQdnpteJ9gFAdK5P6KCgE6LqCpUgy57KzA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/addon-unicode11": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-unicode11/-/addon-unicode11-0.9.0.tgz", + "integrity": "sha512-FxDnYcyuXhNl+XSqGZL/t0U9eiNb/q3EWT5rYkQT/zuig8Gz/VagnQANKHdDWFM2lTMk9ly0EFQxxxtZUoRetw==", + "license": "MIT" + }, + "node_modules/@xterm/addon-web-links": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.12.0.tgz", + "integrity": "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==", + "license": "MIT" + }, + "node_modules/@xterm/addon-webgl": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.19.0.tgz", + "integrity": "sha512-b3fMOsyLVuCeNJWxolACEUED0vm7qC0cy4wRvf3oURSzDTYVQiGPhTnhWZwIHdvC48Y+oLhvYXnY4XDXPoJo6A==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/babel-plugin-polyfill-corejs2": { + "version": "0.4.17", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz", + "integrity": "sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-define-polyfill-provider": "^0.6.8", + "semver": "^6.3.1" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/babel-plugin-polyfill-corejs3": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.14.2.tgz", + "integrity": "sha512-coWpDLJ410R781Npmn/SIBZEsAetR4xVi0SxLMXPaMO4lSf1MwnkGYMtkFxew0Dn8B3/CpbpYxN0JCgg8mn67g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.8", + "core-js-compat": "^3.48.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/babel-plugin-polyfill-regenerator": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.8.tgz", + "integrity": "sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.8" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.42", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.42.tgz", + "integrity": "sha512-zZavzWoNo65+3gcv5AQetEgQ86Rbsge3QPe3wjQFjl1D4/mYzqreOR6DkE0SMMBqYr95w0mLi+69+V0SSeOStQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/brace-expansion": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.2.tgz", + "integrity": "sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/browserslist": { + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cac": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/cac/-/cac-7.1.1.tgz", + "integrity": "sha512-8zc+h51HxpodKsA7L4PpBNd+9qlrfuUcyUDE5a793BJfN4NZgwk7v9NmrY3ptZ+Sk0+ToigxSzkb47AsEgyizw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/cacheable": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", + "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/memory": "^2.2.0", + "@cacheable/utils": "^2.5.0", + "hookified": "^1.15.0", + "keyv": "^5.6.0", + "qified": "^0.10.1" + } + }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001830", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001830.tgz", + "integrity": "sha512-0TFl6VuW52V0JxUPXnqjNNxZ9I8bAH9to34KYZZBUWe/5yD+YBWda/mBXxlwnLLHm5LSoGyyo2KeuNheSJXywA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/common-tags": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.8.2.tgz", + "integrity": "sha512-gk/Z852D2Wtb//0I+kRFNKKE9dIIVirjoqPoA1wJU+XePVXZfGeBpk45+A1rKO4Q43prqWBNY/MiIeRLbPWUaA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie-es": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-3.1.1.tgz", + "integrity": "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==", + "license": "MIT" + }, + "node_modules/core-js-compat": { + "version": "3.51.0", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.51.0.tgz", + "integrity": "sha512-52r6fkXgxv4GLMjmFcMWRx7X9bw071xTTdrDcdyPGRqU2oE+9pCG0bAOMifSBdLw0JRBZKEF0q3B55qPlLuE8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.29.3" + }, + "engines": { + "node": ">=6.4.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/cross-spawn": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz", + "integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/crypto-random-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", + "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decode-bmp": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/decode-bmp/-/decode-bmp-0.2.1.tgz", + "integrity": "sha512-NiOaGe+GN0KJqi2STf24hfMkFitDUaIoUU3eKvP/wAbLe8o6FuW5n/x7MHPR0HKvBokp6MQY/j7w8lewEeVCIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@canvas/image-data": "^1.0.0", + "to-data-view": "^1.1.0" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/decode-ico": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/decode-ico/-/decode-ico-0.4.1.tgz", + "integrity": "sha512-69NZfbKIzux1vBOd31al3XnMnH+2mqDhEgLdpygErm4d60N+UwA5Sq5WFjmEDQzumgB9fElojGwWG0vybVfFmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@canvas/image-data": "^1.0.0", + "decode-bmp": "^0.2.0", + "to-data-view": "^1.1.0" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.501", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.501.tgz", + "integrity": "sha512-UVcdnFm1UW3UZBBL/Nsi7mLqdxGqUbzW0rO0WsdEqwJr4vnFWrs93MBig2neS0TnQ5MUCwg3y91FhM/+oZE4hg==", + "dev": true, + "license": "ISC" + }, + "node_modules/enhanced-resolve": { + "version": "5.27.2", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.2.tgz", + "integrity": "sha512-Cpp3nuaI7ZdgEsvVP6zzk08uxrfGTSUnDwijv6PZfe8qHjcUYv5X9bJF71WTt5HwOeaeVandf9zACK4jcWroNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/es-abstract": { + "version": "1.24.2", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", + "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-abstract-get": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-abstract-get/-/es-abstract-get-1.0.0.tgz", + "integrity": "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.2", + "is-callable": "^1.2.7", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.4.tgz", + "integrity": "sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-abstract-get": "^1.0.0", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "is-callable": "^1.2.7", + "is-date-object": "^1.1.0", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "10.16.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.16.0.tgz", + "integrity": "sha512-Xu3PRLG/wCaZWZ20gkExUcNqL2mWWsXTR+Lln3Sof4Y9WuA678fH9hrlQ8B6UNwbTnsKdDdBYOd2jxtycXVTGQ==", + "dev": true, + "license": "MIT", + "workspaces": [ + "packages/*" + ], + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.2", + "@eslint/config-array": "^0.23.7", + "@eslint/config-helpers": "^0.7.0", + "@eslint/core": "^1.2.1", + "@eslint/plugin-kit": "^0.7.3", + "@humanfs/node": "^0.16.8", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^9.1.2", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "esquery": "^1.7.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "11.1.5 || >11.1.6 <12", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "minimatch": "^11.0.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", + "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" + } + }, + "node_modules/eslint-plugin-react-refresh": { + "version": "0.5.8", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.8.tgz", + "integrity": "sha512-VYgz1iCC5LxeAd6YRz5ATfg8WKrNb1ulHMpCe4pQpn3CS9DiYpZi5wcag73O8iChLhrl/CmlGMmzA6eXZ2cX4Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "eslint": "^9 || ^10" + } + }, + "node_modules/eslint-scope": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", + "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@types/esrecurse": "^4.3.1", + "@types/estree": "^1.0.8", + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eta": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/eta/-/eta-4.6.1.tgz", + "integrity": "sha512-odwOCWIEfyStcDCfVBp54924ZnaqXxUUHR9HV8Mt+Kir9pA+EfJ6V8alZRZlLjthQ5jz+Ibm8kscnMYp9qXpMA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/bgub/eta?sponsor=1" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "11.1.5", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", + "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^6.1.23" + } + }, + "node_modules/filelist": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz", + "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/filelist/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.8.tgz", + "integrity": "sha512-BnlDzDYQoplTsZSvPi86CNzmbcb07X8ufR8fk1zivaiEJlXJkiq1MQyDCVmlWcsWbj6aWXqHnrwwevbrm/Saig==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "6.1.23", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", + "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cacheable": "^2.5.0", + "flatted": "^3.4.2", + "hookified": "^1.15.0" + } + }, + "node_modules/flatted": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.6.0.tgz", + "integrity": "sha512-1Szo+c/GCm/cKBovrfT0Wpqw7fiqZg/xzlZtLtvWlYyvT4zUGZTS8Qo3sXPQ0nWqMg3N4nEFL2Ukzrjnsopwbg==", + "dev": true, + "license": "ISC" + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.2.0.tgz", + "integrity": "sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2", + "hasown": "^2.0.4", + "is-callable": "^1.2.7", + "is-document.all": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-own-enumerable-property-symbols": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", + "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", + "dev": true, + "license": "ISC" + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.1.0.tgz", + "integrity": "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "foreground-child": "^3.3.1", + "jackspeak": "^4.1.1", + "minimatch": "^10.1.1", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "17.15.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.15.0.tgz", + "integrity": "sha512-OyBOdPnzu9B2lFpums9/4wcyNHx4haAxY2X5PgO9LqCvXJgKYMMr/1y4TU7om/vTy4eYqRsVes1ZTJEJYKap8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hashery": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", + "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^1.15.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/hookified": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", + "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/ico-endec": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/ico-endec/-/ico-endec-0.1.6.tgz", + "integrity": "sha512-ZdLU38ZoED3g1j3iEyzcQj+wAkY2xfWNkymszfJPoxucIUhK7NayQ+/C4Kv0nDFMIsbtbEHldv3V8PU494/ueQ==", + "dev": true, + "license": "MPL-2.0" + }, + "node_modules/idb": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz", + "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-document.all": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-document.all/-/is-document.all-1.0.0.tgz", + "integrity": "sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", + "integrity": "sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz", + "integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^9.0.0" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jake": { + "version": "10.9.4", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", + "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonpointer": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/jsonpointer/-/jsonpointer-5.0.1.tgz", + "integrity": "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/keyv": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "1.87.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.87.0.tgz", + "integrity": "sha512-SknCZh7z3kMrElgPqccejETuS8GQwm69UoISu9XyeyXZIXdVUmrBukvbfAsy81JwrrojoiyZmnYRo/uzABIpFw==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/minimatch": { + "version": "11.0.10", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.10.tgz", + "integrity": "sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/napi-windows-process-start-time": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/napi-windows-process-start-time/-/napi-windows-process-start-time-0.1.0.tgz", + "integrity": "sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw==", + "cpu": [ + "x64", + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.67", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.67.tgz", + "integrity": "sha512-qgSZT38oj+YV4qyFmdPQEGRFQRP1l8a0wccOECrcrdGl9KldZlCXrEz7uOviThiOWR1KyqiQYeLrf7M9xRi1bg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/object-inspect": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/own-keys": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz", + "integrity": "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.5.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.4.tgz", + "integrity": "sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright-core": { + "version": "1.65.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.2.tgz", + "integrity": "sha512-aHu9F46Mx5ha9iiB+VLZMUUtex3PBw4am9MHptc0IXaJhz++6YXsH96eEyThwCwMkIUiB8TdZcwXqnb3xKDzmA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.5.34", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.34.tgz", + "integrity": "sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.4" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/pretty-bytes": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-6.1.1.tgz", + "integrity": "sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qified": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", + "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^2.1.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/qified/node_modules/hookified": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", + "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", + "dev": true, + "license": "MIT" + }, + "node_modules/quansync": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-1.0.0.tgz", + "integrity": "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-router": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-8.5.3.tgz", + "integrity": "sha512-oPYDMFH4CFeJ8n2dKvKHPAByYQhEikuvUf6OruNMuxgrq2hvZn7jz0cO/IdFW//EH1a/Vcwi84v405B2Q/gxTw==", + "license": "MIT", + "dependencies": { + "@remix-run/route-pattern": "^0.22.1", + "cookie-es": "^3.1.1" + }, + "engines": { + "node": ">=22.22.0" + }, + "peerDependencies": { + "@types/react": ">=19.2.0", + "@types/react-dom": ">=19.2.0", + "react": ">=19.2.7", + "react-dom": ">=19.2.7" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regenerate": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.5.0.tgz", + "integrity": "sha512-1s+CxXjJ71i7LNVy8nYwg47XV4y6lAnOEhsMtSKq3WpmPfhl9LuKlTqKIn/3yUpE8lBz+W+TT88Bxyhnr0U4yw==", + "dev": true, + "license": "MIT" + }, + "node_modules/regenerate-unicode-properties": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.3.0.tgz", + "integrity": "sha512-9ns8odR8e9q3otKeHj3DE80jZYKg6zVeZKE+zQmRKXFoVUcuiTGeO6iusDhPRoIQQPVPRvH+SfBhrTud4eczuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "regenerate": "^1.4.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexpu-core": { + "version": "6.5.5", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-6.5.5.tgz", + "integrity": "sha512-NfnTxZioujrDAhcN0V+sBehScLHgt43JdRJzgoWbo+cJ4SxTvbFd4juBAUNfbVJqi+e1HCJhDiUOsSvXpbqy4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "regenerate": "^1.5.0", + "regenerate-unicode-properties": "^10.3.0", + "regjsgen": "^0.8.0", + "regjsparser": "^1.0.1", + "unicode-match-property-ecmascript": "^2.0.0", + "unicode-match-property-value-ecmascript": "^2.2.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regjsgen": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.8.0.tgz", + "integrity": "sha512-RvwtGe3d7LvWiDQXeQw8p5asZUmfU1G/l6WbUXeHta7Y2PEIvBTwH6E2EfmYUK8pxcxEdEmaomqyp0vZZ7C+3Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/regjsparser": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-1.0.1.tgz", + "integrity": "sha512-ZBYo+KTM71P9fdt2tN1WQKGxx0r0VJ/UrVzBAN/x+gLxU8h+jA5D4Alhc66PkrNk/Ii3wP4rcZ1F3M98qxWnDQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "jsesc": "~3.1.0" + }, + "bin": { + "regjsparser": "bin/parser" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.14", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.18.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rolldown": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz", + "integrity": "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.160.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.3.4", + "@rolldown/binding-android-arm64": "1.3.4", + "@rolldown/binding-darwin-arm64": "1.3.4", + "@rolldown/binding-darwin-x64": "1.3.4", + "@rolldown/binding-freebsd-x64": "1.3.4", + "@rolldown/binding-linux-arm-gnueabihf": "1.3.4", + "@rolldown/binding-linux-arm64-gnu": "1.3.4", + "@rolldown/binding-linux-arm64-musl": "1.3.4", + "@rolldown/binding-linux-ppc64-gnu": "1.3.4", + "@rolldown/binding-linux-s390x-gnu": "1.3.4", + "@rolldown/binding-linux-x64-gnu": "1.3.4", + "@rolldown/binding-linux-x64-musl": "1.3.4", + "@rolldown/binding-openharmony-arm64": "1.3.4", + "@rolldown/binding-wasm32-wasi": "1.3.4", + "@rolldown/binding-win32-arm64-msvc": "1.3.4", + "@rolldown/binding-win32-x64-msvc": "1.3.4" + } + }, + "node_modules/rollup": { + "version": "4.69.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.69.3.tgz", + "integrity": "sha512-IvHhlznYBMqePMsPb0Z5QLJIweHo4L6gQb5XC1cfmRDMNLfnx3bCLzcepRQFjVi5jXer4areo5CjcqSvab5ftA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.69.3", + "@rollup/rollup-android-arm64": "4.69.3", + "@rollup/rollup-android-x64": "4.69.3", + "@rollup/rollup-darwin-arm64": "4.69.3", + "@rollup/rollup-darwin-x64": "4.69.3", + "@rollup/rollup-freebsd-arm64": "4.69.3", + "@rollup/rollup-freebsd-x64": "4.69.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.69.3", + "@rollup/rollup-linux-arm-musleabihf": "4.69.3", + "@rollup/rollup-linux-arm64-gnu": "4.69.3", + "@rollup/rollup-linux-arm64-musl": "4.69.3", + "@rollup/rollup-linux-loong64-gnu": "4.69.3", + "@rollup/rollup-linux-loong64-musl": "4.69.3", + "@rollup/rollup-linux-ppc64-gnu": "4.69.3", + "@rollup/rollup-linux-ppc64-musl": "4.69.3", + "@rollup/rollup-linux-riscv64-gnu": "4.69.3", + "@rollup/rollup-linux-riscv64-musl": "4.69.3", + "@rollup/rollup-linux-s390x-gnu": "4.69.3", + "@rollup/rollup-linux-x64-gnu": "4.69.3", + "@rollup/rollup-linux-x64-musl": "4.69.3", + "@rollup/rollup-openbsd-x64": "4.69.3", + "@rollup/rollup-openharmony-arm64": "4.69.3", + "@rollup/rollup-win32-arm64-msvc": "4.69.3", + "@rollup/rollup-win32-ia32-msvc": "4.69.3", + "@rollup/rollup-win32-x64-gnu": "4.69.3", + "@rollup/rollup-win32-x64-msvc": "4.69.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", + "integrity": "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/serialize-javascript": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/sharp": { + "version": "0.35.6", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.6.tgz", + "integrity": "sha512-6MTx2/BiKtKIqmYG49Rovjaw9pSk/CM8w4Dy6gMCPFKw+ZpK/icwIJQnEGlkIzCR+HS4arUBzxNM6sE9CgNyeA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.6" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.6", + "@img/sharp-darwin-x64": "0.35.6", + "@img/sharp-freebsd-wasm32": "0.35.6", + "@img/sharp-libvips-darwin-arm64": "1.3.5", + "@img/sharp-libvips-darwin-x64": "1.3.5", + "@img/sharp-libvips-linux-arm": "1.3.5", + "@img/sharp-libvips-linux-arm64": "1.3.5", + "@img/sharp-libvips-linux-ppc64": "1.3.5", + "@img/sharp-libvips-linux-riscv64": "1.3.5", + "@img/sharp-libvips-linux-s390x": "1.3.5", + "@img/sharp-libvips-linux-x64": "1.3.5", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.5", + "@img/sharp-libvips-linuxmusl-x64": "1.3.5", + "@img/sharp-linux-arm": "0.35.6", + "@img/sharp-linux-arm64": "0.35.6", + "@img/sharp-linux-ppc64": "0.35.6", + "@img/sharp-linux-riscv64": "0.35.6", + "@img/sharp-linux-s390x": "0.35.6", + "@img/sharp-linux-x64": "0.35.6", + "@img/sharp-linuxmusl-arm64": "0.35.6", + "@img/sharp-linuxmusl-x64": "0.35.6", + "@img/sharp-webcontainers-wasm32": "0.35.6", + "@img/sharp-win32-arm64": "0.35.6", + "@img/sharp-win32-ia32": "0.35.6", + "@img/sharp-win32-x64": "0.35.6" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/sharp-ico": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/sharp-ico/-/sharp-ico-0.1.5.tgz", + "integrity": "sha512-a3jODQl82NPp1d5OYb0wY+oFaPk7AvyxipIowCHk7pBsZCWgbe0yAkU2OOXdoH0ENyANhyOQbs9xkAiRHcF02Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "decode-ico": "*", + "ico-endec": "*", + "sharp": "*" + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/smob": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.6.2.tgz", + "integrity": "sha512-RQsvleCbF8cVHEv+xuDGaA4pOizFqJ0GgjtMSRo6oP8pnN7WsigHgVGey6aILRBKv4W2YOMHLqbKdnB6hpB9fw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/source-map": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0.tgz", + "integrity": "sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.3.0.tgz", + "integrity": "sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/string.prototype.matchall": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.1.0.tgz", + "integrity": "sha512-tHNHTxInrYLCga9O9YGxWA3G9/nnzQw8UGAyqGx3Ar1pSTTzIuM4woFSq4SowkXCjJIwq5sIiQvEfRI9tCH1qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.2", + "get-intrinsic": "^1.3.0", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "regexp.prototype.flags": "^1.5.4", + "set-function-name": "^2.0.2", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.11.tgz", + "integrity": "sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-object-atoms": "^1.1.2", + "has-property-descriptors": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.10.tgz", + "integrity": "sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/stringify-object": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", + "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-comments/-/strip-comments-2.0.1.tgz", + "integrity": "sha512-ZprKx+bBLXv067WTCALv8SSz5l2+XhpYCsVtSqlMnkAXMWDq+/ekVbl1ghqP9rUHTzv6sm/DwCOiYutU/yp1fw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/temp-dir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz", + "integrity": "sha512-aoBAniQmmwtcKp/7BzsH8Cxzv8OL736p7v1ihGb5e9DJ9kTwGWHrQrVB5+lfVDzfGrdRzXch+ig7LHaY1JTOrg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/tempy": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tempy/-/tempy-0.6.0.tgz", + "integrity": "sha512-G13vtMYPT/J8A4X2SjdtBTphZlrp1gKv6hZiOjw14RCWg6GbHuQBGtjlx75xLbYV/wEc0D7G5K4rxKP/cXk8Bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-stream": "^2.0.0", + "temp-dir": "^2.0.0", + "type-fest": "^0.16.0", + "unique-string": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/terser": { + "version": "5.51.4", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.4.tgz", + "integrity": "sha512-VPi1CkDvCWLGUVIToctNBG+NdHbSXwOPjHJnQ3pdB0XknaldnI76wSkAFOGxV2ZdkzOP5d6gpQ5c58XvDghRvw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.15.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tinybench": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz", + "integrity": "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.4.0.tgz", + "integrity": "sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/to-data-view": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/to-data-view/-/to-data-view-1.1.0.tgz", + "integrity": "sha512-1eAdufMg6mwgmlojAx3QeMnzB/BTVp7Tbndi3U7ftcT2zCZadjxkkmLmd97zmaxWi+sgGcgWrokmpEoy0Dn0vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.16.0.tgz", + "integrity": "sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.5.tgz", + "integrity": "sha512-0FHJvLPqZ7KJzp17O13jfsAjsqazgrxBu2zEK95PmUz8lv2+GjRuxUInCr2Rk9Dms3ihN21zJ929ZO43yJ95QQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.8.tgz", + "integrity": "sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "is-typed-array": "^1.1.15", + "possible-typed-array-names": "^1.1.0", + "reflect.getprototypeof": "^1.0.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.74.0.tgz", + "integrity": "sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.74.0", + "@typescript-eslint/parser": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/utils": "8.74.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/unconfig": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/unconfig/-/unconfig-7.5.0.tgz", + "integrity": "sha512-oi8Qy2JV4D3UQ0PsopR28CzdQ3S/5A1zwsUwp/rosSbfhJ5z7b90bIyTwi/F7hCLD4SGcZVjDzd4XoUQcEanvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@quansync/fs": "^1.0.0", + "defu": "^6.1.4", + "jiti": "^2.6.1", + "quansync": "^1.0.0", + "unconfig-core": "7.5.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/unconfig-core": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/unconfig-core/-/unconfig-core-7.5.0.tgz", + "integrity": "sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@quansync/fs": "^1.0.0", + "quansync": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/unicode-canonical-property-names-ecmascript": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz", + "integrity": "sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz", + "integrity": "sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "unicode-canonical-property-names-ecmascript": "^2.0.0", + "unicode-property-aliases-ecmascript": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-value-ecmascript": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.2.1.tgz", + "integrity": "sha512-JQ84qTuMg4nVkx8ga4A16a1epI9H6uTXAknqxkGF/aFfRLw1xC/Bp24HNLaZhHSkWd3+84t8iXnp1J0kYcZHhg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-property-aliases-ecmascript": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.2.0.tgz", + "integrity": "sha512-hpbDzxUY9BFwX+UeBnxv3Sh1q7HFxj48DTmXchNgRa46lO8uj3/1iEn3MiNUYTg1g9ctIqXCCERn8gYZhHC5lQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unique-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", + "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "crypto-random-string": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/upath": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.2.0.tgz", + "integrity": "sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4", + "yarn": "*" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz", + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.4.1.tgz", + "integrity": "sha512-2bl8n3+GkKBKQQR8CZC+t+3NvjWCBNh9S0Dbfu7hr7+Jjeg71jcZk7uKF6mo8GZXjIws+Nl6jhvAfHUO320VuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.34", + "rolldown": "~1.3.4", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3", + "napi-windows-process-start-time": "^0.1.0" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-plugin-pwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/vite-plugin-pwa/-/vite-plugin-pwa-2.0.0.tgz", + "integrity": "sha512-6G9dsPKT9QKYpeTuTLJM28zZL3HsXUTUM/QUZBEgQk2jbfrPJDq2i8gTewAKqi1c9Mt6MiidrL4SFI+HthiQMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.6", + "pretty-bytes": "^6.1.1", + "tinyglobby": "^0.2.10", + "workbox-build": "^7.4.1", + "workbox-window": "^7.4.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vite-pwa/assets-generator": "^1.0.0 || ^2.0.0", + "vite": "^3.1.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", + "workbox-build": "^7.4.1", + "workbox-window": "^7.4.1" + }, + "peerDependenciesMeta": { + "@vite-pwa/assets-generator": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.2.tgz", + "integrity": "sha512-VIa2wXV208WraXUbzH+dQUrGcFpPuaiRA8HlhXS8R6/sy9cynw6OMqGj8fmAlH1hot7huTCtWUE14+FdXU3eLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.2", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.5", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.3", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.2", + "@vitest/browser-preview": "5.1.2", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.2", + "@vitest/coverage-v8": "5.1.2", + "@vitest/ui": "5.1.2", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz", + "integrity": "sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/workbox-background-sync": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-background-sync/-/workbox-background-sync-7.4.1.tgz", + "integrity": "sha512-HhT7KE8tOWDm02wRNshXUnUPofMlhenF2DBdUnDPOubhizzPeItkYTmAB6td1Z2cjYPa98vzEiPLEuzn5hN66g==", + "dev": true, + "license": "MIT", + "dependencies": { + "idb": "^7.0.1", + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-broadcast-update": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-broadcast-update/-/workbox-broadcast-update-7.4.1.tgz", + "integrity": "sha512-uAlgslKLvbQY+suirIdnBCSYrcgBhjp81Nj4l1lj/Jmj0MJO2CJERnCJjT0GFVwmReV0N+zs78K6gqd5gr9/+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-build": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-build/-/workbox-build-7.4.1.tgz", + "integrity": "sha512-SDhxIvEAde9Gy/5w4Yo1Jh/M49Z0qE3q0oteyE8zGq0DScxFqVBcCtIXFuLtmtxRQZCMbf0prco4VyEu3KBQuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@apideck/better-ajv-errors": "^0.3.1", + "@babel/core": "^7.24.4", + "@babel/preset-env": "^7.11.0", + "@babel/runtime": "^7.11.2", + "@rollup/plugin-babel": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.3", + "@rollup/plugin-replace": "^6.0.3", + "@rollup/plugin-terser": "^1.0.0", + "@trickfilm400/rollup-plugin-off-main-thread": "^3.0.0-pre1", + "ajv": "^8.6.0", + "common-tags": "^1.8.0", + "eta": "^4.5.1", + "fast-json-stable-stringify": "^2.1.0", + "fs-extra": "^9.0.1", + "glob": "^11.0.1", + "pretty-bytes": "^5.3.0", + "rollup": "^4.53.3", + "source-map": "^0.8.0-beta.0", + "stringify-object": "^3.3.0", + "strip-comments": "^2.0.1", + "tempy": "^0.6.0", + "upath": "^1.2.0", + "workbox-background-sync": "7.4.1", + "workbox-broadcast-update": "7.4.1", + "workbox-cacheable-response": "7.4.1", + "workbox-core": "7.4.1", + "workbox-expiration": "7.4.1", + "workbox-google-analytics": "7.4.1", + "workbox-navigation-preload": "7.4.1", + "workbox-precaching": "7.4.1", + "workbox-range-requests": "7.4.1", + "workbox-recipes": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1", + "workbox-streams": "7.4.1", + "workbox-sw": "7.4.1", + "workbox-window": "7.4.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/workbox-build/node_modules/@apideck/better-ajv-errors": { + "version": "0.3.7", + "resolved": "https://registry.npmjs.org/@apideck/better-ajv-errors/-/better-ajv-errors-0.3.7.tgz", + "integrity": "sha512-TajUJwGWbDwkCx/CZi7tRE8PVB7simCvKJfHUsSdvps+aTM/PDPP4gkLmKnc+x3CE//y9i/nj74GqdL/hwk7Iw==", + "dev": true, + "license": "MIT", + "dependencies": { + "jsonpointer": "^5.0.1", + "leven": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "ajv": ">=8" + } + }, + "node_modules/workbox-build/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/workbox-build/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/workbox-build/node_modules/pretty-bytes": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-5.6.0.tgz", + "integrity": "sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/workbox-cacheable-response": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-cacheable-response/-/workbox-cacheable-response-7.4.1.tgz", + "integrity": "sha512-8xaFoJdDc2OjrlbbL3gEeBO1WKcMwRqwLRupgqahYXu75yXajPLuwrbXMrIGZuWYXrQwk0xDjOxZ/ujCy/oJYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-core": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-core/-/workbox-core-7.4.1.tgz", + "integrity": "sha512-DT+vu46eh/2vRsSHTY4Xmc32Z1rr9PRlQUXr1Dx30ZuXRWwOsvZgGgcwxcasubQLQmbTNYZjv44LkBAQ4tT5tQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/workbox-expiration": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-expiration/-/workbox-expiration-7.4.1.tgz", + "integrity": "sha512-lRKUF7b+OGbeXkQk1s6MHXOa3d7Xxf7Of31W6c6hCfipfIyrtdWZ89stq21AHZMaoG7VNFoHply4Ox+rU31TWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "idb": "^7.0.1", + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-google-analytics": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-google-analytics/-/workbox-google-analytics-7.4.1.tgz", + "integrity": "sha512-Mks1JwLEt++ZAkF6sS1OpSh9RtAMIsiDgRpK+codiHGIPXeaUOgi4cPc3GFadUl8V5QPeypEk8Oxgl3HlwVzHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-background-sync": "7.4.1", + "workbox-core": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1" + } + }, + "node_modules/workbox-navigation-preload": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-navigation-preload/-/workbox-navigation-preload-7.4.1.tgz", + "integrity": "sha512-C4KVsjPcYKJOhr631AxR9XoG2rLF3QiTk5aMv36MXOjtWvm8axwNFAtKUPGsWUwLXXAMgYM1En7fsvndaXeXRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-precaching": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-precaching/-/workbox-precaching-7.4.1.tgz", + "integrity": "sha512-cdr/9qByww7yzEp7zg/qI4ukUrrNjQLgN+ONQRpjy/VqGQXwkgHwr00KksGJK8v0VifwDXBb8a4cWNZH71jn3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1" + } + }, + "node_modules/workbox-range-requests": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-range-requests/-/workbox-range-requests-7.4.1.tgz", + "integrity": "sha512-7i2oxAUE82gHdAJBCAQ04JzNOdRPqzuOzGfoUyJpFSmeqBNYGPrAH8GPoPjUQTfp+NycwrD2H68VtuF8qxv0vQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-recipes": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-recipes/-/workbox-recipes-7.4.1.tgz", + "integrity": "sha512-gnbVfmV4/TtmQaM4x9AtuXhcdstJsep3XMVeztOrQVPT+R6+6DeBjGTCQ7fFCXm+4GEHUA5VEBTyi5+4gWGeog==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-cacheable-response": "7.4.1", + "workbox-core": "7.4.1", + "workbox-expiration": "7.4.1", + "workbox-precaching": "7.4.1", + "workbox-routing": "7.4.1", + "workbox-strategies": "7.4.1" + } + }, + "node_modules/workbox-routing": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-routing/-/workbox-routing-7.4.1.tgz", + "integrity": "sha512-yubJGErZOusuidAenaL5ypfhQOa7urxP/f8E0ws7FPb4039RiWXUWBAyUkmUoOL/BcQGen3h0J8872d51IYxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-strategies": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-strategies/-/workbox-strategies-7.4.1.tgz", + "integrity": "sha512-GZxpaw9NbmOelj7667uZ2kpk5BFpOGbO4X0qjwh5ls8XQ8C+Lha5LQchTiUzsTFSS+NlUpftYAyOVXvQUrcqOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1" + } + }, + "node_modules/workbox-streams": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-streams/-/workbox-streams-7.4.1.tgz", + "integrity": "sha512-HWWtraKUbJknd9kgqGcpQ3G114HOPYvqs8HaJMDs2ebLNAimDkVDaWfAXE6Ybl+m8U6KsCE6pWyLYuigWmnAXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "workbox-core": "7.4.1", + "workbox-routing": "7.4.1" + } + }, + "node_modules/workbox-sw": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-sw/-/workbox-sw-7.4.1.tgz", + "integrity": "sha512-fez5f2DUlDJWTFYkCWQpY10N8gtztd849NswCbVFk0QlcSM4HT5A8x4g4ii650yem4I8tHY0R7JZahwp3ltIPw==", + "dev": true, + "license": "MIT" + }, + "node_modules/workbox-window": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/workbox-window/-/workbox-window-7.4.1.tgz", + "integrity": "sha512-notZDH2u8VXaqyuD7xaqIfEFi6SRM4SUSd7ewe9PDsVqADuepxX2ZMY3uvuZGxzY5ZOsGC/vD3A/3smFtJt4/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/trusted-types": "^2.0.2", + "workbox-core": "7.4.1" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + }, + "node_modules/zustand": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.1.0.tgz", + "integrity": "sha512-ciJZlP48M1PTQbVQq81CGVFxHTLpZNrFjKqwjtCU34AWuXTZT/jrF3p9+fI84Cf1eSCMLapxqBy/SNTfwOBuqA==", + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..9973467 --- /dev/null +++ b/web/package.json @@ -0,0 +1,56 @@ +{ + "name": "redshell-remote", + "private": true, + "version": "0.0.3", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "build:mock": "tsc -b && vite build --mode mock --outDir dist-mock", + "preview": "vite preview", + "typecheck": "tsc -b", + "lint": "eslint .", + "test": "vitest run", + "icons": "node scripts/icons.ts", + "screenshots": "node scripts/screenshots.ts", + "e2e": "node scripts/e2e.ts" + }, + "dependencies": { + "@simplewebauthn/browser": "^14.0.0", + "@tanstack/react-query": "^5.108.4", + "@xterm/addon-fit": "^0.11.0", + "@xterm/addon-unicode11": "^0.9.0", + "@xterm/addon-web-links": "^0.12.0", + "@xterm/addon-webgl": "^0.19.0", + "@xterm/xterm": "^6.0.0", + "lucide-react": "^1.87.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router": "^8.5.3", + "zustand": "^5.1.0" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@tailwindcss/vite": "^4.3.5", + "@types/node": "^26.6.11", + "@types/react": "^19.3.3", + "@types/react-dom": "^19.3.0", + "@vite-pwa/assets-generator": "^2.0.0", + "@vitejs/plugin-react": "^6.3.1", + "eslint": "^10.16.0", + "eslint-plugin-react-hooks": "^7.1.1", + "eslint-plugin-react-refresh": "^0.5.8", + "globals": "^17.15.0", + "playwright-core": "^1.65.2", + "tailwindcss": "^4.3.5", + "typescript": "~6.0.3", + "typescript-eslint": "^8.74.0", + "vite": "^8.4.1", + "vite-plugin-pwa": "^2.0.0", + "vitest": "^5.1.2", + "workbox-build": "^7.4.1", + "workbox-precaching": "^7.4.1", + "workbox-routing": "^7.4.1", + "workbox-window": "^7.4.1" + } +} diff --git a/web/public/apple-splash-portrait-dark-1125x2436.png b/web/public/apple-splash-portrait-dark-1125x2436.png new file mode 100644 index 0000000..dd3652d Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1125x2436.png differ diff --git a/web/public/apple-splash-portrait-dark-1170x2532.png b/web/public/apple-splash-portrait-dark-1170x2532.png new file mode 100644 index 0000000..8f469ba Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1170x2532.png differ diff --git a/web/public/apple-splash-portrait-dark-1179x2556.png b/web/public/apple-splash-portrait-dark-1179x2556.png new file mode 100644 index 0000000..6e75f7b Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1179x2556.png differ diff --git a/web/public/apple-splash-portrait-dark-1206x2622.png b/web/public/apple-splash-portrait-dark-1206x2622.png new file mode 100644 index 0000000..9760474 Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1206x2622.png differ diff --git a/web/public/apple-splash-portrait-dark-1242x2688.png b/web/public/apple-splash-portrait-dark-1242x2688.png new file mode 100644 index 0000000..6d2c8d9 Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1242x2688.png differ diff --git a/web/public/apple-splash-portrait-dark-1260x2736.png b/web/public/apple-splash-portrait-dark-1260x2736.png new file mode 100644 index 0000000..8b9449b Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1260x2736.png differ diff --git a/web/public/apple-splash-portrait-dark-1290x2796.png b/web/public/apple-splash-portrait-dark-1290x2796.png new file mode 100644 index 0000000..85f7116 Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1290x2796.png differ diff --git a/web/public/apple-splash-portrait-dark-1320x2868.png b/web/public/apple-splash-portrait-dark-1320x2868.png new file mode 100644 index 0000000..da46b01 Binary files /dev/null and b/web/public/apple-splash-portrait-dark-1320x2868.png differ diff --git a/web/public/apple-splash-portrait-dark-750x1334.png b/web/public/apple-splash-portrait-dark-750x1334.png new file mode 100644 index 0000000..1f4edd8 Binary files /dev/null and b/web/public/apple-splash-portrait-dark-750x1334.png differ diff --git a/web/public/apple-splash-portrait-dark-828x1792.png b/web/public/apple-splash-portrait-dark-828x1792.png new file mode 100644 index 0000000..1b17c2d Binary files /dev/null and b/web/public/apple-splash-portrait-dark-828x1792.png differ diff --git a/web/public/apple-splash-portrait-light-1125x2436.png b/web/public/apple-splash-portrait-light-1125x2436.png new file mode 100644 index 0000000..5d38472 Binary files /dev/null and b/web/public/apple-splash-portrait-light-1125x2436.png differ diff --git a/web/public/apple-splash-portrait-light-1170x2532.png b/web/public/apple-splash-portrait-light-1170x2532.png new file mode 100644 index 0000000..5865413 Binary files /dev/null and b/web/public/apple-splash-portrait-light-1170x2532.png differ diff --git a/web/public/apple-splash-portrait-light-1179x2556.png b/web/public/apple-splash-portrait-light-1179x2556.png new file mode 100644 index 0000000..7dba25d Binary files /dev/null and b/web/public/apple-splash-portrait-light-1179x2556.png differ diff --git a/web/public/apple-splash-portrait-light-1206x2622.png b/web/public/apple-splash-portrait-light-1206x2622.png new file mode 100644 index 0000000..092df22 Binary files /dev/null and b/web/public/apple-splash-portrait-light-1206x2622.png differ diff --git a/web/public/apple-splash-portrait-light-1242x2688.png b/web/public/apple-splash-portrait-light-1242x2688.png new file mode 100644 index 0000000..324499a Binary files /dev/null and b/web/public/apple-splash-portrait-light-1242x2688.png differ diff --git a/web/public/apple-splash-portrait-light-1260x2736.png b/web/public/apple-splash-portrait-light-1260x2736.png new file mode 100644 index 0000000..ab47a6c Binary files /dev/null and b/web/public/apple-splash-portrait-light-1260x2736.png differ diff --git a/web/public/apple-splash-portrait-light-1290x2796.png b/web/public/apple-splash-portrait-light-1290x2796.png new file mode 100644 index 0000000..bab57c9 Binary files /dev/null and b/web/public/apple-splash-portrait-light-1290x2796.png differ diff --git a/web/public/apple-splash-portrait-light-1320x2868.png b/web/public/apple-splash-portrait-light-1320x2868.png new file mode 100644 index 0000000..91808d6 Binary files /dev/null and b/web/public/apple-splash-portrait-light-1320x2868.png differ diff --git a/web/public/apple-splash-portrait-light-750x1334.png b/web/public/apple-splash-portrait-light-750x1334.png new file mode 100644 index 0000000..9357e1e Binary files /dev/null and b/web/public/apple-splash-portrait-light-750x1334.png differ diff --git a/web/public/apple-splash-portrait-light-828x1792.png b/web/public/apple-splash-portrait-light-828x1792.png new file mode 100644 index 0000000..86e62fe Binary files /dev/null and b/web/public/apple-splash-portrait-light-828x1792.png differ diff --git a/web/public/apple-touch-icon-180.png b/web/public/apple-touch-icon-180.png new file mode 100644 index 0000000..590ac7d Binary files /dev/null and b/web/public/apple-touch-icon-180.png differ diff --git a/web/public/badge-96.png b/web/public/badge-96.png new file mode 100644 index 0000000..8260879 Binary files /dev/null and b/web/public/badge-96.png differ diff --git a/web/public/favicon.ico b/web/public/favicon.ico new file mode 100644 index 0000000..e0d75f3 Binary files /dev/null and b/web/public/favicon.ico differ diff --git a/web/public/favicon.svg b/web/public/favicon.svg new file mode 100644 index 0000000..affb978 --- /dev/null +++ b/web/public/favicon.svg @@ -0,0 +1,8 @@ + + + + + + + diff --git a/web/public/fonts/JetBrainsMono-Bold.woff2 b/web/public/fonts/JetBrainsMono-Bold.woff2 new file mode 100644 index 0000000..c32e152 Binary files /dev/null and b/web/public/fonts/JetBrainsMono-Bold.woff2 differ diff --git a/web/public/fonts/JetBrainsMono-Regular.woff2 b/web/public/fonts/JetBrainsMono-Regular.woff2 new file mode 100644 index 0000000..ba66ef6 Binary files /dev/null and b/web/public/fonts/JetBrainsMono-Regular.woff2 differ diff --git a/web/public/fonts/OFL.txt b/web/public/fonts/OFL.txt new file mode 100644 index 0000000..8bee414 --- /dev/null +++ b/web/public/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/web/public/maskable-512.png b/web/public/maskable-512.png new file mode 100644 index 0000000..ff8c0f7 Binary files /dev/null and b/web/public/maskable-512.png differ diff --git a/web/public/pwa-192.png b/web/public/pwa-192.png new file mode 100644 index 0000000..21e3e60 Binary files /dev/null and b/web/public/pwa-192.png differ diff --git a/web/public/pwa-512.png b/web/public/pwa-512.png new file mode 100644 index 0000000..46915c3 Binary files /dev/null and b/web/public/pwa-512.png differ diff --git a/web/public/pwa-64.png b/web/public/pwa-64.png new file mode 100644 index 0000000..29c2dd1 Binary files /dev/null and b/web/public/pwa-64.png differ diff --git a/web/public/theme-init.js b/web/public/theme-init.js new file mode 100644 index 0000000..0c4e091 --- /dev/null +++ b/web/public/theme-init.js @@ -0,0 +1,16 @@ +// Runs before the stylesheet: index.html ships , and this removes the class +// when the stored appearance (src/state/prefs.ts) or the system asks for light, so the app +// never flashes the wrong theme. External because the CSP allows no inline script. +(function () { + var appearance = "system"; + try { + var stored = JSON.parse(localStorage.getItem("redshell:prefs") || "null"); + if (stored && stored.state && stored.state.appearance) appearance = stored.state.appearance; + } catch (_) { + // Storage blocked or unreadable: follow the system. + } + var light = + appearance === "light" || + (appearance === "system" && window.matchMedia("(prefers-color-scheme: light)").matches); + if (light) document.documentElement.classList.remove("dark"); +})(); diff --git a/web/scripts/e2e.ts b/web/scripts/e2e.ts new file mode 100644 index 0000000..072c51a --- /dev/null +++ b/web/scripts/e2e.ts @@ -0,0 +1,118 @@ +// End-to-end test of RedShell Remote against a real redshell-server, in Chromium. +// +// npm run e2e [-- --no-build] [--shots ] +// +// Builds the PWA and the server that embeds it (unless --no-build), starts the server with a +// throwaway config directory and home on a free port, and walks through the app: password +// sign-in, a shell session, an agent's approval, passkeys with Chromium's virtual authenticator, +// pairing a device, "Confirm it's you" before signing out another browser, and an SSH host with +// a port forward (e2e/steps.ts). The agent is a fake +// `claude`, so no real agent runs. Every process it starts is stopped and its folder removed, +// however it ends. With --shots, it saves screenshots of the real screens into . +// Needs cargo, curl and Chromium at /usr/bin/chromium (CHROMIUM=/path to override). + +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { parseArgs } from "node:util"; +import { chromium, type Page } from "playwright-core"; +import { build, Cleanup, serverBinary, StaleBuild, startServer, type TestServer } from "./e2e/server.ts"; +import { STEPS, type Test } from "./e2e/steps.ts"; + +const { values: options } = parseArgs({ + options: { + "no-build": { type: "boolean", default: false }, + shots: { type: "string" }, + }, +}); + +const cleanup = new Cleanup(); +// Interrupted, killed by a timeout or left by its terminal: clean up all the same. +for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]] as const) { + process.on(signal, () => { + void cleanup.run().then(() => process.exit(code)); + }); +} + +/** Starts the server; a server built before web/dist existed embeds none, so that gets rebuilt once. */ +async function server(dir: string): Promise { + const binary = await serverBinary(); + try { + return await startServer(binary, dir, cleanup); + } catch (error) { + if (!(error instanceof StaleBuild) || options["no-build"]) throw error; + await build(true); + return startServer(binary, join(dir, "rebuilt"), cleanup); + } +} + +async function browserPage(): Promise { + const browser = await chromium.launch({ + executablePath: process.env.CHROMIUM ?? "/usr/bin/chromium", + // The WebGL terminal draws at the device scale only when Chromium is told it at launch. + args: ["--no-sandbox", "--force-device-scale-factor=2"], + }); + cleanup.add(() => browser.close()); + const context = await browser.newContext({ + viewport: { width: 390, height: 844 }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + colorScheme: "dark", + serviceWorkers: "block", + }); + await context.addInitScript(() => { + // Screen-reader mode puts the terminal's rows in the DOM, where the steps read them. + if (!localStorage.getItem("redshell:prefs")) { + localStorage.setItem("redshell:prefs", JSON.stringify({ state: { screenReader: true }, version: 0 })); + } + // A step that signs in with the passkey button turns the username field's autofill off. + if (sessionStorage.getItem("e2e:no-autofill")) PublicKeyCredential.isConditionalMediationAvailable = () => Promise.resolve(false); + }); + const page = await context.newPage(); + page.setDefaultTimeout(20_000); + page.on("pageerror", (error) => { + console.error(`page error: ${error.message}`); + }); + return page; +} + +async function main(): Promise { + if (!options["no-build"]) await build(false); + const dir = await mkdtemp(join(tmpdir(), "redshell-e2e-")); + cleanup.add(() => rm(dir, { recursive: true, force: true })); + const shots = options.shots; + if (shots) await mkdir(shots, { recursive: true }); + + const test: Test = { + server: await server(dir), + page: await browserPage(), + shell: "", + shoot: async (name) => { + if (!shots) return; + await test.page.evaluate(() => document.fonts.ready); + await test.page.waitForTimeout(600); + await test.page.screenshot({ path: join(shots, `${name}.png`) }); + }, + }; + for (const [index, step] of STEPS.entries()) { + const started = Date.now(); + try { + await step.run(test); + } catch (error) { + const shown = await test.page.evaluate(() => document.body.innerText).catch(() => ""); + throw new Error(`step ${index + 1} failed: ${step.name}\nThe page was at ${test.page.url()}, showing:\n${shown}`, { cause: error }); + } + console.log(`ok ${index + 1} ${step.name} (${((Date.now() - started) / 1000).toFixed(1)}s)`); + } +} + +try { + await main(); + console.log(`\nAll ${STEPS.length} steps passed.`); +} catch (error) { + console.error("\nFAILED:", error); + process.exitCode = 1; +} finally { + await cleanup.run(); +} diff --git a/web/scripts/e2e/server.ts b/web/scripts/e2e/server.ts new file mode 100644 index 0000000..4886c87 --- /dev/null +++ b/web/scripts/e2e/server.ts @@ -0,0 +1,203 @@ +// The server side of the e2e test (../e2e.ts): builds, a redshell-server with a throwaway config +// directory and home, and an API client that talks to it with curl, as a desktop would. + +import { execFile, spawn } from "node:child_process"; +import { chmod, mkdir, open, readdir, readFile, writeFile } from "node:fs/promises"; +import { createServer } from "node:net"; +import { join, resolve } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { createHttp, type Http } from "../../src/api/http.ts"; +import type { SignInResponse } from "../../src/protocol/index.ts"; + +export const WEB = fileURLToPath(new URL("../..", import.meta.url)); +const ROOT = resolve(WEB, ".."); +export const USER = { username: "andy", password: "e2e-correct-horse-battery" }; + +const exec = promisify(execFile); +const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms)); + +/** Things to undo when the test ends, however it ends; the last added goes first. */ +export class Cleanup { + private readonly undo: (() => Promise)[] = []; + + add(undo: () => Promise): void { + this.undo.push(undo); + } + + async run(): Promise { + for (const undo of this.undo.splice(0).reverse()) { + await undo().catch((error: unknown) => { + console.error("cleanup:", error); + }); + } + } +} + +/** Runs a build step with its output on this terminal. */ +async function run(command: string, args: string[], cwd: string): Promise { + const child = spawn(command, args, { cwd, stdio: "inherit" }); + const code = await new Promise((done) => child.on("exit", done)); + if (code !== 0) throw new Error(`${command} ${args.join(" ")} exited with ${String(code)}`); +} + +/** The PWA, then the server that embeds it; `clean` first makes cargo embed a new web/dist. */ +export async function build(clean: boolean): Promise { + await run("npm", ["run", "build"], WEB); + if (clean) await run("cargo", ["clean", "-p", "redshell-server"], ROOT); + await run("cargo", ["build", "-p", "redshell-server"], ROOT); +} + +/** Sends a request with curl: no browser, no Origin, like the desktop or a script. */ +async function curl(url: string, init: RequestInit): Promise { + const args = ["-s", "-X", init.method ?? "GET", "-w", "\n%{http_code}"]; + new Headers(init.headers).forEach((value, name) => args.push("-H", `${name}: ${value}`)); + if (typeof init.body === "string") args.push("--data-raw", init.body); + const { stdout } = await exec("curl", [...args, url]); + const cut = stdout.lastIndexOf("\n"); + return new Response(stdout.slice(0, cut) || null, { status: Number(stdout.slice(cut + 1)) }); +} + +/** The fake Claude Code: asks for two permissions through the hook URL in its `--settings` file. */ +const FAKE_CLAUDE = `#!${process.execPath} +const fs = require("node:fs"); +const args = process.argv.slice(2); +const settings = JSON.parse(fs.readFileSync(args[args.indexOf("--settings") + 1], "utf8")); +const url = settings.hooks.PermissionRequest[0].hooks[0].url; +async function ask(tool_name, tool_input) { + const response = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ hook_event_name: "PermissionRequest", tool_name, tool_input, permission_suggestions: [] }), + }); + const text = await response.text(); + return text ? JSON.parse(text).hookSpecificOutput.decision.behavior : "none"; +} +(async () => { + console.log("fake-claude: started"); + console.log("fake-claude decision: " + (await ask("Bash", { command: "npm test", description: "Run the test suite" }))); + await ask("Edit", { file_path: "src/feed.ts", old_string: "const limit = 10;", new_string: "const limit = 50;" }); +})(); +setInterval(() => {}, 1 << 30); +`; + +const NO_CODEX = "#!/bin/sh\necho 'codex does not run in the e2e test'\nexit 1\n"; + +async function freePort(): Promise { + const server = createServer(); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + const address = server.address(); + await new Promise((done) => server.close(done)); + if (address === null || typeof address === "string") throw new Error("no free port"); + return address.port; +} + +/** Processes whose environment carries `marker`: the server and every session it started. */ +async function processesMarked(marker: string): Promise { + const found: number[] = []; + for (const entry of await readdir("/proc").catch(() => [])) { + if (!/^\d+$/.test(entry) || Number(entry) === process.pid) continue; + const environ = await readFile(`/proc/${entry}/environ`, "utf8").catch(() => ""); + if (environ.split("\0").includes(marker)) found.push(Number(entry)); + } + return found; +} + +export interface TestServer { + /** What the browser opens: `http://localhost:`, the server's `public_url`. */ + url: string; + config: string; + /** A folder sessions start in. */ + project: string; + /** The API as a client that is not a browser, signed in with `token` when given. */ + as: (token?: string) => Http; + /** The API as a desktop signed in as the test user. */ + device: Http; + /** Lets every browser's last re-authentication lapse, as five minutes would. */ + expireReauth: () => void; +} + +/** The server embeds an older PWA than web/dist (see crates/redshell-server/build.rs). */ +export class StaleBuild extends Error { + constructor() { + super("The server embeds another web/dist than the one built: run the test without --no-build."); + } +} + +/** + * Starts the server in `dir`, with `[terminal] shell = "/bin/sh"`, its own home (so neither the + * user's ~/.ssh/config nor their agents' settings are read), the fake `claude` and a refusing + * `codex` first on its PATH, and the test user. + */ +export async function startServer(binary: string, dir: string, cleanup: Cleanup): Promise { + const port = await freePort(); + const url = `http://localhost:${port}`; + const config = join(dir, "config"); + const home = join(dir, "home"); + const bin = join(dir, "bin"); + const project = join(home, "src", "aurora"); + for (const folder of [config, bin, project]) await mkdir(folder, { recursive: true }); + await writeFile(join(config, "config.toml"), `[server]\nlisten = "127.0.0.1:${port}"\npublic_url = "${url}"\n\n[terminal]\nshell = "/bin/sh"\n`); + await writeFile(join(bin, "claude"), FAKE_CLAUDE); + await writeFile(join(bin, "codex"), NO_CODEX); + for (const agent of ["claude", "codex"]) await chmod(join(bin, agent), 0o755); + + const env = { PATH: `${bin}:/usr/bin:/bin`, HOME: home, XDG_CONFIG_HOME: join(home, ".config"), LANG: "C.UTF-8", REDSHELL_E2E: dir }; + const add = spawn(binary, ["--config", config, "user", "add", USER.username, "--password-stdin"], { env, stdio: ["pipe", "ignore", "inherit"] }); + add.stdin.end(`${USER.password}\n`); + if ((await new Promise((done) => add.on("exit", done))) !== 0) throw new Error("user add failed"); + + const logFile = join(dir, "server.log"); + const log = await open(logFile, "w"); + cleanup.add(() => log.close()); + const server = spawn(binary, ["--config", config, "serve"], { env, cwd: home, stdio: ["ignore", log.fd, log.fd] }); + const exited = () => server.exitCode !== null || server.signalCode !== null; + cleanup.add(async () => { + server.kill("SIGTERM"); + for (let i = 0; i < 50 && !exited(); i++) await sleep(100); + if (!exited()) server.kill("SIGKILL"); + // Sessions inherit the server's environment; none may outlive the test. + for (const pid of await processesMarked(`REDSHELL_E2E=${dir}`)) { + try { + process.kill(pid, "SIGKILL"); + } catch { + // It exited since the scan. + } + } + }); + + const as = (token?: string) => + createHttp((path, init) => { + const headers = new Headers(init.headers); + if (token) headers.set("Authorization", `Bearer ${token}`); + return curl(`${url}${path}`, { ...init, headers }); + }); + for (let tries = 0; !(await as().get("/api/auth/info").then(() => true, () => false)); tries++) { + if (exited() || tries > 300) throw new Error(`the server did not start:\n${await readFile(logFile, "utf8")}`); + await sleep(100); + } + const served = await fetch(`http://127.0.0.1:${port}/`).then((response) => response.text()); + if (served !== (await readFile(join(WEB, "dist", "index.html"), "utf8"))) throw new StaleBuild(); + + const { device_token: token } = await as().post("/api/auth/sign-in", { ...USER, device_name: "e2e" }); + if (!token) throw new Error("no device token"); + const expireReauth = () => { + const db = new DatabaseSync(join(config, "server.sqlite3")); + try { + db.exec("UPDATE browser_sessions SET reauth_at = NULL"); + } finally { + db.close(); + } + }; + return { url, config, project, as, device: as(token), expireReauth }; +} + +export async function serverBinary(): Promise { + const { stdout } = await exec("cargo", ["metadata", "--format-version", "1", "--no-deps"], { cwd: ROOT, maxBuffer: 64 << 20 }); + const metadata: unknown = JSON.parse(stdout); + if (typeof metadata !== "object" || metadata === null || !("target_directory" in metadata) || typeof metadata.target_directory !== "string") { + throw new Error("cargo metadata names no target directory"); + } + return join(metadata.target_directory, "debug", "redshell-server"); +} diff --git a/web/scripts/e2e/steps.ts b/web/scripts/e2e/steps.ts new file mode 100644 index 0000000..5dd6f65 --- /dev/null +++ b/web/scripts/e2e/steps.ts @@ -0,0 +1,263 @@ +// What the e2e test (../e2e.ts) does in the browser, step by step, against the real server. +// Steps run in order and build on each other: one page, one signed-in browser. + +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { Locator, Page } from "playwright-core"; +import type { BrowserSession, PairStarted, PairStatus, Passkey, SessionInfo, User } from "../../src/protocol/index.ts"; +import { type TestServer, USER } from "./server.ts"; + +export interface Test { + page: Page; + server: TestServer; + /** Saves a screenshot of the page as `.png` when the run collects them. */ + shoot: (name: string) => Promise; + /** The shell session the steps start, rename and end. */ + shell: string; +} + +export interface Step { + name: string; + run: (test: Test) => Promise; +} + +const visible = (locator: Locator) => locator.first().waitFor({ state: "visible" }); + +/** The dialog that asks for the password or a passkey before a change that needs it. */ +const confirmIdentity = (page: Page) => page.getByRole("dialog", { name: "Confirm it's you" }); + +/** The terminal's rows as xterm's screen-reader mode puts them in the DOM. */ +const terminal = (page: Page) => page.locator(".xterm-accessibility-tree"); + +/** Opens the session menu in the header and picks `item`. */ +async function sessionMenu(page: Page, item: string): Promise { + await page.getByRole("button", { name: "More" }).click(); + await page.getByRole("menuitem", { name: item }).click(); +} + +async function startFromSheet(page: Page, kind: "Agent" | "Shell", profile: RegExp): Promise { + await page.getByRole("button", { name: "New session" }).first().click(); + await page.getByRole("radio", { name: kind, exact: true }).click(); + await page.getByRole("radio", { name: profile }).click(); + await page.getByRole("button", { name: "Start", exact: true }).click(); + await page.waitForURL(/\/s\//); + return decodeURIComponent(new URL(page.url()).pathname.slice("/s/".length)); +} + +async function signOut({ page, server }: Test): Promise { + await page.goto(`${server.url}/settings`); + await page.getByRole("button", { name: "Sign out" }).click(); + await page.getByRole("dialog").getByRole("button", { name: "Sign out" }).click(); + await page.waitForURL(/\/signin/); +} + +/** Back where it signed out from, and with the passkey: its last use moved. */ +async function signedInWithPasskey({ page, server }: Test, before: number | null): Promise { + await page.waitForURL(`${server.url}/settings`); + await visible(page.getByRole("heading", { name: "Settings" })); + const [passkey] = await server.device.get("/api/account/passkeys"); + if (!passkey?.last_used_at || passkey.last_used_at === before) throw new Error("the passkey was not used to sign in"); +} + +const lastUsed = async ({ server }: Test) => (await server.device.get("/api/account/passkeys"))[0]?.last_used_at ?? null; + +export const STEPS: Step[] = [ + { + name: "a session started elsewhere is in the inbox after a password sign-in", + run: async ({ page, server }) => { + await server.device.post("/api/sessions", { profile: "shell", cwd: server.project, name: "dev server" }); + await page.goto(`${server.url}/`); + await page.waitForURL(/\/signin/); + await page.getByLabel("Username").fill(USER.username); + await page.getByLabel("Password", { exact: true }).fill(USER.password); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + await page.waitForURL(`${server.url}/`); + await visible(page.getByText("dev server", { exact: true })); + }, + }, + { + name: "a new shell session runs what the composer sends", + run: async (test) => { + const { page } = test; + test.shell = await startFromSheet(page, "Shell", /^sh/); + const composer = page.getByRole("textbox").last(); + await composer.fill("echo e2e-$((6*7))"); + await composer.press("Enter"); + await visible(terminal(page).getByText("e2e-42")); + await test.shoot("session-dark"); + }, + }, + { + name: "the session is renamed on the server", + run: async ({ page, server, shell }) => { + await sessionMenu(page, "Rename"); + await page.getByRole("textbox", { name: "Name" }).fill("build shell"); + await page.getByRole("button", { name: "Save" }).click(); + await visible(page.getByRole("heading", { name: "build shell" })); + const sessions = await server.device.get("/api/sessions"); + if (sessions.find((s) => s.id === shell)?.name !== "build shell") throw new Error("the server kept the old name"); + }, + }, + { + name: "an agent's permission request is allowed from the sheet", + run: async ({ page, shoot }) => { + await page.getByRole("button", { name: "Back to sessions" }).click(); + await startFromSheet(page, "Agent", /Claude Code/); + await visible(terminal(page).getByText("fake-claude: started")); + await visible(page.getByText("npm test")); + await shoot("approval-dark"); + await page.getByRole("button", { name: "Allow", exact: true }).click(); + await visible(terminal(page).getByText("fake-claude decision: allow")); + }, + }, + { + name: "the inbox shows the agent waiting again and the renamed shell", + run: async ({ page, server, shoot }) => { + // The fake asks a second time, and that sheet stays up over the session. + await visible(page.getByText("src/feed.ts")); + await page.goto(`${server.url}/`); + await visible(page.getByText("build shell")); + await visible(page.getByText("Needs you")); + await shoot("inbox-dark"); + }, + }, + { + name: "ending the shell kills it on the server", + run: async ({ page, server, shell }) => { + await page.goto(`${server.url}/s/${encodeURIComponent(shell)}`); + await sessionMenu(page, "End session"); + await page.getByRole("dialog").getByRole("button", { name: "End session" }).click(); + await page.waitForURL(`${server.url}/`); + const sessions = await server.device.get("/api/sessions"); + if (sessions.some((s) => s.id === shell)) throw new Error("the session is still running"); + }, + }, + { + name: "a passkey is added in settings", + run: async ({ page, server, shoot }) => { + const cdp = await page.context().newCDPSession(page); + await cdp.send("WebAuthn.enable"); + await cdp.send("WebAuthn.addVirtualAuthenticator", { + options: { + protocol: "ctap2", + transport: "internal", + hasResidentKey: true, + hasUserVerification: true, + isUserVerified: true, + automaticPresenceSimulation: true, + }, + }); + // Signing in with the password counts as a re-authentication: no "Confirm it's you". + await page.goto(`${server.url}/settings/passkeys`); + await page.getByRole("button", { name: "Add a passkey" }).click(); + await visible(page.getByText(/^Added /)); + if (await confirmIdentity(page).isVisible()) throw new Error("adding a passkey right after signing in asked to confirm it's the user"); + const passkeys = await server.device.get("/api/account/passkeys"); + if (passkeys.length !== 1) throw new Error(`expected one passkey, the server has ${passkeys.length}`); + await shoot("passkeys-dark"); + }, + }, + { + name: "the passkey signs in from the button", + run: async (test) => { + const before = await lastUsed(test); + // Without autofill the sign-in screen waits for the button. + await test.page.evaluate(() => sessionStorage.setItem("e2e:no-autofill", "1")); + await signOut(test); + await test.page.getByRole("button", { name: "Sign in with passkey" }).click(); + await signedInWithPasskey(test, before); + await test.page.evaluate(() => sessionStorage.removeItem("e2e:no-autofill")); + }, + }, + { + name: "the passkey signs in from the username field's autofill", + run: async (test) => { + const before = await lastUsed(test); + // The virtual authenticator answers the conditional request at once, like a tap on the suggestion. + await signOut(test); + await signedInWithPasskey(test, before); + }, + }, + { + name: "a device is paired by typing its code, confirmed with a passkey, and collects its token", + run: async ({ page, server, shoot }) => { + const started = await server.as().post("/api/pair", { device_name: "Workstation", platform: "Linux" }); + await page.goto(`${server.url}/pair`); + await page.getByLabel("Pairing code").fill(started.code); + await visible(page.getByText("Workstation")); + await visible(page.getByText(/^Approving signs this device in as andy/)); + await visible(page.getByText(/from 127\.0\.0\.1$/)); + // The browser and curl share an address, so the request isn't from another network. + if (await page.getByText(/different network/).isVisible()) throw new Error("a pairing from this address is flagged as from elsewhere"); + await shoot("pair-dark"); + // Approving needs a recent re-authentication: the passkey gives it, and the approval goes on. + server.expireReauth(); + await page.getByRole("button", { name: "Approve" }).click(); + await confirmIdentity(page).getByRole("button", { name: "Use a passkey" }).click(); + await visible(page.getByText("Workstation is paired")); + + const status = await server.as(started.poll_secret).get(`/api/pair/${started.id}`); + if (status.state !== "approved") throw new Error(`the pairing is ${status.state}`); + const me = await server.as(status.device_token).get("/api/auth/me"); + if (me.username !== USER.username) throw new Error("the device token is not the user's"); + }, + }, + { + name: "signing out another browser asks to confirm it's you once the last time has lapsed", + run: async ({ page, server, shoot }) => { + await server.as().post("/api/auth/sign-in", USER); + const browsers = await server.device.get("/api/account/sessions"); + const other = browsers.reduce((newest, b) => (b.created_at > newest.created_at ? b : newest)); + server.expireReauth(); + + await page.goto(`${server.url}/settings/devices/browser/${other.id}`); + await page.getByRole("button", { name: "Revoke" }).click(); + await page.getByRole("dialog").getByRole("button", { name: "Revoke" }).click(); + const dialog = confirmIdentity(page); + await dialog.getByLabel("Password", { exact: true }).fill(USER.password); + await shoot("confirm-identity-dark"); + await dialog.getByRole("button", { name: "Continue" }).click(); + await page.waitForURL(`${server.url}/settings/devices`); + const left = await server.device.get("/api/account/sessions"); + if (left.some((b) => b.id === other.id)) throw new Error("the other browser is still signed in"); + }, + }, + { + name: "an SSH host with a port forward is saved to the server's config", + run: async ({ page, server, shoot }) => { + await page.goto(`${server.url}/hosts/new`); + await page.getByLabel("Name", { exact: true }).fill("lab"); + await page.getByLabel("Host", { exact: true }).fill("10.0.4.20"); + await page.getByLabel("User", { exact: true }).fill("andy"); + await page.getByText("Forward SSH agent").click(); + await page.getByRole("button", { name: "Add port forward" }).click(); + const dialog = page.getByRole("dialog"); + await dialog.getByLabel("Local port").fill("5432"); + await dialog.getByLabel("Destination").fill("db.internal"); + await dialog.getByLabel("Port", { exact: true }).fill("5432"); + await dialog.getByLabel("Label").fill("Postgres"); + await dialog.getByRole("button", { name: "Done" }).click(); + await page.getByRole("button", { name: "Save" }).click(); + await page.waitForURL(`${server.url}/hosts`); + await page.getByText("lab", { exact: true }).click(); + await page.getByText("Host saved").waitFor({ state: "hidden" }); + await page.getByRole("heading", { name: "On connect" }).evaluate((heading) => { + heading.scrollIntoView({ block: "start" }); + }); + await visible(page.getByText("Postgres")); + await shoot("host-dark"); + + const config = await readFile(join(server.config, "config.toml"), "utf8"); + for (const line of ['name = "lab"', "forward_agent = true", 'target_host = "db.internal"']) { + if (!config.includes(line)) throw new Error(`config.toml lacks ${line}:\n${config}`); + } + }, + }, + { + name: "notifications are offered in settings", + run: async ({ page, server }) => { + await page.goto(`${server.url}/settings/notifications`); + await visible(page.getByRole("button", { name: "Turn on notifications" })); + }, + }, +]; diff --git a/web/scripts/icons.ts b/web/scripts/icons.ts new file mode 100644 index 0000000..56a98ef --- /dev/null +++ b/web/scripts/icons.ts @@ -0,0 +1,104 @@ +// Renders the PWA icons, badge and iOS splash screens into public/ from the source SVGs in +// assets/icon (docs/design/remote-pwa-visual.md §5), and writes the splash tags into +// index.html. Run with `npm run icons` after changing an icon; the output is committed. + +import { copyFile, readFile, writeFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import type { ImageAssets } from "@vite-pwa/assets-generator/api"; +import { generateAssets } from "@vite-pwa/assets-generator/api/generate-assets"; +import { generateHtmlMarkup } from "@vite-pwa/assets-generator/api/generate-html-markup"; +import { instructions } from "@vite-pwa/assets-generator/api/instructions"; +import { createAppleSplashScreens, type AppleDeviceName, type Preset } from "@vite-pwa/assets-generator/config"; + +const web = fileURLToPath(new URL("..", import.meta.url)); +const icons = fileURLToPath(new URL("../../assets/icon/", import.meta.url)); +const output = `${web}public`; + +const none = { sizes: [], padding: 0 }; + +/** One iPhone per distinct portrait resolution. */ +const IPHONES: AppleDeviceName[] = [ + "iPhone 17 Pro Max", + "iPhone 17 Pro", + "iPhone Air", + "iPhone 16 Plus", + "iPhone 16", + "iPhone 14", + "iPhone 13 mini", + "iPhone 11 Pro Max", + "iPhone 11", + 'iPhone SE 4.7"', +]; + +const sources: { file: string; preset: Preset }[] = [ + { + // The tile with its shadow: the "any" icons and the splash screens. + file: "redshell.svg", + preset: { + transparent: { sizes: [64, 192, 512], padding: 0 }, + maskable: none, + apple: none, + assetName: (_, size) => `pwa-${size.width}.png`, + appleSplashScreens: createAppleSplashScreens( + { + padding: 0.6, + resizeOptions: { background: "#fefcfc", fit: "contain" }, + darkResizeOptions: { background: "#0f0b0b", fit: "contain" }, + linkMediaOptions: { log: false, addMediaScreen: true, basePath: "/", xhtml: false }, + }, + IPHONES, + ), + }, + }, + { + // Full-bleed and square: Android masks it, iOS rounds it. + file: "redshell-maskable.svg", + preset: { + transparent: none, + maskable: { sizes: [512], padding: 0 }, + apple: { sizes: [180], padding: 0 }, + assetName: (type, size) => (type === "maskable" ? `maskable-${size.width}.png` : `apple-touch-icon-${size.width}.png`), + }, + }, + { + file: "redshell-badge.svg", + preset: { transparent: { sizes: [96], padding: 0 }, maskable: none, apple: none, assetName: (_, size) => `badge-${size.width}.png` }, + }, + { + file: "redshell-small.svg", + preset: { transparent: { sizes: [], padding: 0, favicons: [[48, "favicon.ico"]] }, maskable: none, apple: none }, + }, +]; + +let splashLinks: string[] = []; + +for (const { file, preset } of sources) { + const path = `${icons}${file}`; + const assets: ImageAssets = { + imageResolver: () => readFile(path), + imageName: path, + preset, + faviconPreset: "2023", + htmlLinks: { xhtml: false, includeId: false }, + basePath: "/", + resolveSvgName: (name) => name, + }; + const instruction = await instructions(assets); + // Portrait only: the app never opens in landscape from the Home Screen icon on iPhone. + instruction.appleSplashScreen = Object.fromEntries( + Object.entries(instruction.appleSplashScreen).filter(([name]) => name.includes("portrait")), + ); + await generateAssets(instruction, true, output); + if (Object.keys(instruction.appleSplashScreen).length > 0) { + splashLinks = generateHtmlMarkup(instruction).filter((link) => link.includes("apple-touch-startup-image")); + } +} + +await copyFile(`${icons}redshell-small.svg`, `${output}/favicon.svg`); + +const index = `${web}index.html`; +const html = await readFile(index, "utf8"); +const block = splashLinks.map((link) => ` ${link}`).join("\n"); +await writeFile(index, html.replace(/( *)[\s\S]*?/, `$1\n${block}\n$1`)); + +console.log(`icons: wrote ${splashLinks.length} splash links`); diff --git a/web/scripts/screenshots.ts b/web/scripts/screenshots.ts new file mode 100644 index 0000000..660ab38 --- /dev/null +++ b/web/scripts/screenshots.ts @@ -0,0 +1,354 @@ +// Screenshots of every screen and key state against the mock backend, for design review. +// +// npm run screenshots -- [--out dir] [--scale 3] [--only name,name] [--no-build] [--url http://localhost:5173] +// +// Builds the mock build (`vite build --mode mock` into dist-mock/; --no-build reuses it), serves +// it with `vite preview` on a free port for the run, and stops it at the end. --url shoots a server +// that is already running instead, such as the dev server. Production builds carry no mock. +// Uses the system Chromium (CHROMIUM=/path to override) through playwright-core. + +import { mkdir } from "node:fs/promises"; +import { parseArgs } from "node:util"; +import { chromium, type Page } from "playwright-core"; +import { build, preview, type PreviewServer } from "vite"; + +const { values } = parseArgs({ + options: { + out: { type: "string", default: "shots" }, + scale: { type: "string", default: "2" }, + only: { type: "string" }, + url: { type: "string" }, + "no-build": { type: "boolean", default: false }, + }, +}); + +type Scheme = "dark" | "light"; + +interface Shot { + name: string; + path: string; + scheme?: Scheme; + wide?: boolean; + /** A phone on its side, 844×390. */ + landscape?: boolean; + offline?: boolean; + wait?: number; + act?: (page: Page) => Promise; +} + +const PHONE = { width: 390, height: 844 }; +const LANDSCAPE = { width: 844, height: 390 }; +const DESKTOP = { width: 1280, height: 800 }; + +/** Opens the new-session sheet and its "Other folder…" path field, typing `path`. */ +async function otherFolder(page: Page, path: string): Promise { + await page.getByRole("button", { name: "New session" }).first().click(); + await page.getByRole("button", { name: "Other folder…" }).click(); + await page.getByRole("textbox", { name: "Folder" }).fill(path); + await page.waitForTimeout(500); +} + +/** Through setup's account step to the passkey step. */ +async function setupAccount(page: Page): Promise { + await page.getByLabel("Username").fill("andy"); + await page.getByLabel("Password", { exact: true }).fill("a long password"); + await page.getByLabel("Confirm password").fill("a long password"); + await page.getByRole("button", { name: "Continue" }).click(); + await page.getByRole("heading", { name: "Add a passkey" }).waitFor(); + await page.waitForTimeout(400); +} + +const both = (shot: Shot): Shot[] => [ + { ...shot, name: `${shot.name}-dark`, scheme: "dark" }, + { ...shot, name: `${shot.name}-light`, scheme: "light" }, +]; + +const shots: Shot[] = [ + ...both({ name: "signin", path: "/signin?mock=signed-out" }), + { + name: "signin-rate-limited-dark", + path: "/signin?mock=rate-limited", + act: async (page) => { + await page.getByLabel("Username").fill("andy"); + await page.getByLabel("Password", { exact: true }).fill("not the password"); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + await page.getByText("Too many attempts").waitFor(); + }, + }, + { name: "signin-unreachable-dark", path: "/signin?mock=unreachable", wait: 1200 }, + { name: "signin-passkeys-off-dark", path: "/signin?mock=passkeys-off" }, + { + name: "passkeys-off-dark", + path: "/signin?mock=passkeys-off", + act: async (page) => { + await page.getByLabel("Username").fill("andy"); + await page.getByLabel("Password", { exact: true }).fill("a long password"); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + // The mock keeps its state for the page load only: move inside the app. + await page.getByRole("link", { name: "Settings" }).click(); + await page.getByRole("link", { name: /Passkeys/ }).click(); + await page.waitForTimeout(600); + }, + }, + { + name: "signin-passkey-required-dark", + path: "/settings?mock=passkey-only", + act: async (page) => { + await page.getByRole("button", { name: "Sign out" }).click(); + await page.getByRole("dialog").getByRole("button", { name: "Sign out" }).click(); + await page.getByLabel("Username").fill("andy"); + await page.getByLabel("Password", { exact: true }).fill("a long password"); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + await page.getByText("signs in with a passkey").waitFor(); + }, + }, + ...both({ name: "setup", path: "/setup?mock=setup&code=demo" }), + { name: "setup-passkey-dark", path: "/setup?mock=setup&code=demo", act: setupAccount }, + { + name: "setup-notifications-dark", + path: "/setup?mock=setup&code=demo", + act: async (page) => { + await setupAccount(page); + await page.getByRole("button", { name: "Skip for now" }).click(); + await page.waitForTimeout(400); + }, + }, + { + name: "setup-done-dark", + path: "/setup?mock=setup&code=demo", + act: async (page) => { + await setupAccount(page); + await page.getByRole("button", { name: "Skip for now" }).click(); + await page.getByRole("button", { name: "Not now" }).click(); + await page.waitForTimeout(400); + }, + }, + { name: "setup-expired-dark", path: "/setup?mock=setup-expired&code=old" }, + { + name: "pair-dark", + path: "/pair?mock", + act: async (page) => { + await page.getByLabel("Pairing code").fill("kx74mp"); + await page.getByRole("button", { name: "Approve" }).waitFor(); + await page.waitForTimeout(400); + }, + }, + ...both({ name: "inbox", path: "/?mock" }), + { name: "inbox-empty-dark", path: "/?mock=empty" }, + { name: "inbox-loading-dark", path: "/?mock=loading", wait: 800 }, + { name: "inbox-error-dark", path: "/?mock=error", wait: 1500 }, + { name: "inbox-reconnecting-dark", path: "/?mock=reconnecting", wait: 3500 }, + { name: "inbox-offline-light", path: "/?mock", scheme: "light", offline: true }, + { + name: "inbox-menu-dark", + path: "/?mock", + act: async (page) => { + await page.getByRole("link", { name: /^docs,/ }).click({ button: "right" }); + await page.waitForTimeout(400); + }, + }, + // Banners come only from other screens than the inbox. + { name: "banner-dark", path: "/settings?mock=arrival", wait: 3400 }, + ...both({ name: "approval-command", path: "/s/aurora?mock", wait: 1600 }), + ...both({ name: "approval-diff", path: "/s/aurora?mock=diff", wait: 1600 }), + { name: "approval-other-dark", path: "/s/aurora?mock=other", wait: 1600 }, + { name: "approval-command-landscape-dark", path: "/s/aurora?mock", landscape: true, wait: 1600 }, + { name: "approval-diff-landscape-dark", path: "/s/aurora?mock=diff", landscape: true, wait: 1600 }, + { name: "approval-other-landscape-light", path: "/s/aurora?mock=other", landscape: true, scheme: "light", wait: 1600 }, + { name: "approval-write-dark", path: "/s/aurora?mock=write", wait: 1600 }, + { name: "approval-write-landscape-dark", path: "/s/aurora?mock=write", landscape: true, wait: 1600 }, + { + name: "approval-write-landscape-all-dark", + path: "/s/aurora?mock=write", + landscape: true, + wait: 1600, + act: async (page) => { + await page.getByRole("button", { name: "Show all", exact: true }).click(); + await page.waitForTimeout(400); + }, + }, + { + name: "approval-send-failed-landscape-dark", + path: "/s/aurora?mock=answer-fails", + landscape: true, + wait: 1600, + act: async (page) => { + await page.getByRole("button", { name: "Allow", exact: true }).click(); + await page.getByRole("alert").waitFor(); + }, + }, + { name: "approval-expiring-dark", path: "/s/aurora?mock=expiring", wait: 1600 }, + { name: "approval-remote-dark", path: "/s/aurora?mock=remote-answer", wait: 4600 }, + { + name: "approval-send-failed-dark", + path: "/s/aurora?mock=answer-fails", + wait: 1600, + act: async (page) => { + await page.getByRole("button", { name: "Allow", exact: true }).click(); + await page.getByRole("alert").waitFor(); + }, + }, + { + name: "session-peek-dark", + path: "/s/aurora?mock", + wait: 1600, + act: async (page) => { + await page.keyboard.press("Escape"); + await page.waitForTimeout(500); + }, + }, + ...both({ name: "session-input", path: "/s/api-gateway?mock", wait: 1200 }), + { name: "session-working-dark", path: "/s/aurora-web?mock", wait: 3000 }, + { name: "session-shell-light", path: "/s/shell-aurora?mock", scheme: "light", wait: 1200 }, + { name: "session-failed-dark", path: "/s/prod-api?mock", wait: 1200 }, + { name: "session-reconnecting-dark", path: "/s/docs?mock=reconnecting", wait: 3500 }, + { name: "session-gone-dark", path: "/s/nope?mock", wait: 800 }, + { + name: "session-menu-dark", + path: "/s/docs?mock", + wait: 1200, + act: async (page) => { + await page.getByRole("button", { name: "More" }).click(); + await page.waitForTimeout(400); + }, + }, + { + name: "session-toast-dark", + path: "/s/docs?mock", + wait: 1200, + act: async (page) => { + await page.getByRole("button", { name: "More" }).click(); + await page.getByRole("menuitem", { name: "Copy path" }).click(); + await page.waitForTimeout(500); + }, + }, + { + name: "session-composer-light", + path: "/s/shell-aurora?mock", + scheme: "light", + wait: 1200, + act: async (page) => { + const composer = page.getByRole("textbox").last(); + await composer.fill("for f in src/*.ts\ndo wc -l \"$f\"\ndone"); + await page.waitForTimeout(300); + }, + }, + ...both({ + name: "new-session", + path: "/?mock", + act: async (page) => { + await page.getByRole("button", { name: "New session" }).first().click(); + await page.waitForTimeout(700); + }, + }), + { name: "new-session-folder-dark", path: "/?mock", act: (page) => otherFolder(page, "~/src/a") }, + { + name: "new-session-error-dark", + path: "/?mock", + act: async (page) => { + await otherFolder(page, "~/src/nope"); + await page.getByRole("button", { name: "Start", exact: true }).click(); + await page.getByRole("alert").waitFor(); + }, + }, + ...both({ name: "settings", path: "/settings?mock" }), + { name: "settings-passkey-only-dark", path: "/settings?mock=passkey-only" }, + { name: "passkeys-dark", path: "/settings/passkeys?mock" }, + { name: "devices-dark", path: "/settings/devices?mock" }, + { + name: "confirm-identity-dark", + path: "/settings/devices/device/1?mock", + act: async (page) => { + await page.getByRole("button", { name: "Revoke" }).click(); + await page.getByRole("dialog").getByRole("button", { name: "Revoke" }).click(); + await page.getByRole("dialog", { name: "Confirm it's you" }).waitFor(); + await page.waitForTimeout(400); + }, + }, + { name: "notifications-dark", path: "/settings/notifications?mock" }, + { name: "notifications-on-dark", path: "/settings/notifications?mock=push-on" }, + { name: "password-light", path: "/settings/password?mock", scheme: "light" }, + ...both({ name: "hosts", path: "/hosts?mock" }), + { name: "host-detail-dark", path: "/hosts/prod-api?mock" }, + { + name: "host-forwards-dark", + path: "/hosts/prod-api?mock", + act: async (page) => { + await page.getByRole("heading", { name: "Port forwards" }).scrollIntoViewIfNeeded(); + await page.waitForTimeout(300); + }, + }, + ...both({ + name: "host-forward", + path: "/hosts/prod-api?mock", + act: async (page) => { + await page.getByRole("button", { name: /Postgres/ }).click(); + await page.waitForTimeout(700); + }, + }), + ...both({ name: "host-new", path: "/hosts/new?mock" }), + { name: "host-imported-dark", path: "/hosts/gpu-box?mock" }, + { name: "wide-session-dark", path: "/s/aurora?mock", wide: true, wait: 1600 }, + { name: "wide-session-light", path: "/s/aurora-web?mock", wide: true, scheme: "light", wait: 1600 }, + { name: "wide-empty-dark", path: "/?mock", wide: true }, + { name: "wide-settings-dark", path: "/settings?mock", wide: true }, + { + name: "wide-send-failed-dark", + path: "/s/aurora?mock=answer-fails", + wide: true, + wait: 1600, + act: async (page) => { + await page.getByRole("button", { name: "Allow", exact: true }).click(); + await page.getByRole("alert").waitFor(); + }, + }, + { name: "wide-signin-dark", path: "/signin?mock=signed-out", wide: true }, +]; + +const only = values.only?.split(","); +const selected = only ? shots.filter((shot) => only.some((name) => shot.name.startsWith(name))) : shots; +await mkdir(values.out, { recursive: true }); + +const OUT_DIR = "dist-mock"; +let server: PreviewServer | null = null; +let base = values.url; +if (!base) { + if (!values["no-build"]) await build({ mode: "mock", logLevel: "warn", build: { outDir: OUT_DIR } }); + server = await preview({ mode: "mock", build: { outDir: OUT_DIR }, preview: { port: 0, host: "127.0.0.1" }, logLevel: "warn" }); + base = server.resolvedUrls?.local[0]?.replace(/\/$/, ""); + if (!base) throw new Error("vite preview has no local URL"); +} + +const browser = await chromium.launch({ + executablePath: process.env.CHROMIUM ?? "/usr/bin/chromium", + // The WebGL terminal draws at the device scale only when Chromium is told it at launch. + args: ["--no-sandbox", `--force-device-scale-factor=${values.scale}`], +}); + +for (const shot of selected) { + const context = await browser.newContext({ + viewport: shot.wide ? DESKTOP : shot.landscape ? LANDSCAPE : PHONE, + deviceScaleFactor: Number(values.scale), + colorScheme: shot.scheme ?? "dark", + hasTouch: !shot.wide, + isMobile: !shot.wide, + serviceWorkers: "block", + }); + const page = await context.newPage(); + page.on("pageerror", (error) => console.error(`${shot.name}: ${error.message}`)); + await page.goto(`${base}${shot.path}`); + if (shot.offline) { + await page.waitForTimeout(1200); + await context.setOffline(true); + await page.evaluate(() => window.dispatchEvent(new Event("offline"))); + } + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(shot.wait ?? 900); + await shot.act?.(page); + await page.screenshot({ path: `${values.out}/${shot.name}.png` }); + console.log(shot.name); + await context.close(); +} + +await browser.close(); +await server?.close(); diff --git a/web/src/api/browser.ts b/web/src/api/browser.ts new file mode 100644 index 0000000..703afee --- /dev/null +++ b/web/src/api/browser.ts @@ -0,0 +1,95 @@ +import { + browserSupportsWebAuthnAutofill, + type PublicKeyCredentialCreationOptionsJSON, + type PublicKeyCredentialRequestOptionsJSON, + startAuthentication, + startRegistration, + WebAuthnAbortService, +} from "@simplewebauthn/browser"; +import { browserWebPush } from "../pwa/browserPush"; +import type { Transport } from "./client"; +import type { JsonValue } from "./types"; + +function isObject(value: JsonValue): value is { [key in string]: JsonValue } { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * The `publicKey` member of a `PasskeyChallenge`'s options: webauthn-rs sends + * `{publicKey: {…}}` with binary fields in base64url, which is the JSON form SimpleWebAuthn takes. + */ +const publicKey = (options: JsonValue) => (isObject(options) ? options.publicKey : undefined); + +function isRequestOptions(value: unknown): value is PublicKeyCredentialRequestOptionsJSON { + return typeof value === "object" && value !== null && "challenge" in value && typeof value.challenge === "string"; +} + +function isCreationOptions(value: unknown): value is PublicKeyCredentialCreationOptionsJSON { + return ( + isRequestOptions(value) && + "rp" in value && + "pubKeyCredParams" in value && + "user" in value && + typeof value.user === "object" && + value.user !== null && + "id" in value.user && + typeof value.user.id === "string" + ); +} + +/** The real outside world: the page's origin, its WebSocket and the platform's passkeys. */ +export function browserTransport(): Transport { + const scheme = location.protocol === "https:" ? "wss:" : "ws:"; + return { + fetch: (input, init) => fetch(input, init), + createSocket: (url) => new WebSocket(url), + socketUrl: `${scheme}//${location.host}/api/ws`, + host: location.host, + webPush: browserWebPush(), + webauthn: { + authenticate: (options, autofill) => { + const optionsJSON = publicKey(options); + if (!isRequestOptions(optionsJSON)) throw new Error("The server sent no sign-in options"); + return startAuthentication({ optionsJSON, useBrowserAutofill: autofill }); + }, + register: (options) => { + const optionsJSON = publicKey(options); + if (!isCreationOptions(optionsJSON)) throw new Error("The server sent no registration options"); + return startRegistration({ optionsJSON }); + }, + supportsAutofill: browserSupportsWebAuthnAutofill, + cancel: () => WebAuthnAbortService.cancelCeremony(), + }, + }; +} + +const MOCK_KEY = "redshell:mock"; + +/** + * The mock scenario for this tab, or `null` for the real server. `?mock` (or `?mock=`) + * switches it on and is remembered for the tab; a mock build (`--mode mock`) is always on it. + */ +function mockScenario(): string | null { + const param = new URLSearchParams(location.search).get("mock"); + if (param !== null) { + const scenario = param || "default"; + sessionStorage.setItem(MOCK_KEY, scenario); + return scenario; + } + const remembered = sessionStorage.getItem(MOCK_KEY); + if (remembered !== null) return remembered; + return import.meta.env.MODE === "mock" ? "default" : null; +} + +/** + * The transport the app runs on. The mock backend exists only in the dev server and in mock + * builds: in a production build the condition is a constant `false`, so the mock chunk is never + * emitted and no link can put a convincing fake app in front of a real server's users. + */ +export async function createTransport(): Promise { + if (!(import.meta.env.DEV || import.meta.env.MODE === "mock")) return browserTransport(); + const scenario = mockScenario(); + if (scenario === null) return browserTransport(); + const { createMockTransport } = await import("./mock"); + return createMockTransport(scenario); +} diff --git a/web/src/api/client.ts b/web/src/api/client.ts new file mode 100644 index 0000000..fe10e05 --- /dev/null +++ b/web/src/api/client.ts @@ -0,0 +1,193 @@ +import type { AuthenticationResponseJSON, RegistrationResponseJSON } from "@simplewebauthn/browser"; +import { createHttp, type FetchFn, type Http, type HttpHooks } from "./http"; +import { Connection, type SocketFactory } from "./socket"; +import type { + Account, + Approval, + ApprovalAnswer, + BrowserSession, + ChangePasswordRequest, + CreateSessionRequest, + Device, + FolderListing, + JsonValue, + PairingInfo, + Passkey, + PasskeyChallenge, + PasskeySignInRequest, + Profile, + PushEndpoint, + PushEventsRequest, + PushKey, + PushSubscribeRequest, + PushSubscriptionInfo, + ReauthRequest, + ReauthResponse, + RegisterPasskeyRequest, + RenameSessionRequest, + ServerInfo, + SessionInfo, + SetupRequest, + SignInRequest, + SignInResponse, + SshHost, + User, +} from "./types"; + +/** + * The platform side of a WebAuthn ceremony (the system passkey sheet). It takes a + * `PasskeyChallenge`'s `options` as the server sends them (`{publicKey: …}`). + */ +export interface WebAuthn { + /** `autofill` runs it as conditional mediation: the passkey appears in the username field's suggestions. */ + authenticate(options: JsonValue, autofill: boolean): Promise; + register(options: JsonValue): Promise; + supportsAutofill(): Promise; + /** Stops a ceremony in flight, such as the autofill one when the sign-in screen goes away. */ + cancel(): void; +} + +/** Why this browser can't get notifications: iPhone outside the Home Screen, no Push API, or denied. */ +export type PushBlocker = "install" | "unsupported" | "blocked"; + +/** This browser's side of Web Push: its permission and its subscription with its push service. */ +export interface WebPush { + blocker(): PushBlocker | null; + /** The endpoint of its subscription, if it has one. */ + endpoint(): Promise; + /** Asks for permission; call it first thing in a tap, before any request, or the browser won't ask. */ + allow(): Promise; + /** Subscribes with the server's VAPID key, once allowed. */ + subscribe(vapidKey: string): Promise>; + /** Drops its subscription with the push service. */ + unsubscribe(): Promise; +} + +/** Everything the API needs from the outside world; the mock backend provides its own. */ +export interface Transport { + fetch: FetchFn; + createSocket: SocketFactory; + socketUrl: string; + /** The server's host as people know it (`pi.tail9c2.ts.net`). */ + host: string; + webauthn: WebAuthn; + webPush: WebPush; +} + +const enc = encodeURIComponent; + +/** A ceremony's answer as the browser gives it, where the protocol only says JSON. */ +type WithCredential = Omit & { credential: Credential }; + +/** A re-authentication: the password, or the answer to a passkey challenge. */ +export type ReauthBody = + | Extract + | WithCredential, AuthenticationResponseJSON>; + +/** Signing in with a passkey, and the account's own passkeys. */ +const passkeysApi = (http: Http) => ({ + /** Sign-in with a discoverable passkey: begin, then finish with the browser's answer. */ + signInBegin: () => http.post("/api/auth/passkey/begin"), + signInFinish: (body: WithCredential) => + http.post("/api/auth/passkey/finish", body), + list: () => http.get("/api/account/passkeys"), + registerBegin: () => http.post("/api/account/passkeys/begin"), + registerFinish: (body: WithCredential) => + http.post("/api/account/passkeys/finish", body), + rename: (id: number, name: string) => http.patch(`/api/account/passkeys/${id}`, { name }), + /** Refused (409) for the last passkey while passkey-only sign-in is on. */ + remove: (id: number) => http.delete(`/api/account/passkeys/${id}`), +}); + +/** Approving a desktop by the code it shows; the code is always one the user typed. */ +const pairingApi = (http: Http) => ({ + /** 404 when the code is unknown or expired. */ + get: (code: string) => http.get(`/api/pair/${enc(code)}`), + approve: (code: string) => http.post(`/api/pair/${enc(code)}/approve`), + reject: (code: string) => http.post(`/api/pair/${enc(code)}/reject`), +}); + +/** The server's side of Web Push: its key, and the account's subscriptions. */ +const pushApi = (http: Http) => ({ + key: () => http.get("/api/push/key"), + list: () => http.get("/api/push/subscriptions"), + subscribe: (body: PushSubscribeRequest) => http.post("/api/push/subscriptions", body), + setEvents: (body: PushEventsRequest) => http.put("/api/push/subscriptions", body), + unsubscribe: (body: PushEndpoint) => http.delete("/api/push/subscriptions", body), + test: (body: PushEndpoint) => http.post("/api/push/test", body), +}); + +/** The server's `[[ssh.hosts]]`. */ +const hostsApi = (http: Http) => ({ + list: () => http.get("/api/hosts"), + /** Adds `host`, or saves it over `previousName` (renaming it when the names differ). */ + save: (host: SshHost, previousName: string | null) => + previousName === null + ? http.post("/api/hosts", host) + : http.put(`/api/hosts/${enc(previousName)}`, host), + remove: (name: string) => http.delete(`/api/hosts/${enc(name)}`), +}); + +/** + * The typed client of redshell-server (docs/REMOTE.md): REST under `/api` and the one + * WebSocket. Every call the PWA makes is listed here. + */ +export function createApi(transport: Transport, hooks: HttpHooks) { + const http = createHttp(transport.fetch, hooks); + const connection = new Connection(transport.socketUrl, transport.createSocket); + + return { + connection, + webauthn: transport.webauthn, + webPush: transport.webPush, + host: transport.host, + + info: () => http.get("/api/auth/info"), + + auth: { + me: () => http.get("/api/auth/me"), + signIn: (body: SignInRequest) => http.post("/api/auth/sign-in", body), + signOut: () => http.post("/api/auth/sign-out"), + setup: (body: SetupRequest) => http.post("/api/setup", body), + /** Confirms it's the user again, before a change that needs it; holds for five minutes. */ + reauth: (body: ReauthBody) => http.post("/api/auth/reauth", body), + /** A challenge for one of the user's passkeys to re-authenticate with; 409 when they have none. */ + reauthBegin: () => http.post("/api/auth/reauth/passkey/begin"), + }, + + account: { + get: () => http.get("/api/account"), + /** Refused (409) when turning it on without a passkey. */ + setPasskeyOnly: (enabled: boolean) => http.put("/api/account/passkey-only", { enabled }), + changePassword: (body: ChangePasswordRequest) => http.post("/api/account/password", body), + devices: () => http.get("/api/account/devices"), + revokeDevice: (id: number) => http.delete(`/api/account/devices/${id}`), + browsers: () => http.get("/api/account/sessions"), + revokeBrowser: (id: number) => http.delete(`/api/account/sessions/${id}`), + }, + + passkeys: passkeysApi(http), + pairing: pairingApi(http), + push: pushApi(http), + hosts: hostsApi(http), + + sessions: { + list: () => http.get("/api/sessions"), + create: (body: CreateSessionRequest) => http.post("/api/sessions", body), + rename: (id: string, body: RenameSessionRequest) => http.patch(`/api/sessions/${enc(id)}`, body), + kill: (id: string) => http.delete(`/api/sessions/${enc(id)}`), + }, + + approvals: { + list: () => http.get("/api/approvals"), + answer: (id: string, body: ApprovalAnswer) => http.post(`/api/approvals/${enc(id)}`, body), + }, + + profiles: () => http.get("/api/profiles"), + + /** Subfolders of an absolute folder on the server, for path completion. */ + folders: (path: string) => http.get(`/api/fs/folders?path=${enc(path)}`), + }; +} + +export type Api = ReturnType; diff --git a/web/src/api/framing.ts b/web/src/api/framing.ts new file mode 100644 index 0000000..6df36a3 --- /dev/null +++ b/web/src/api/framing.ts @@ -0,0 +1,19 @@ +// Binary WebSocket frames: a 2-byte big-endian channel number (from `attached`), then the +// terminal bytes. Mirrors `frame` / `unframe` in crates/redshell-protocol/src/ws.rs. + +export function frame(channel: number, bytes: Uint8Array): Uint8Array { + const out = new Uint8Array(bytes.length + 2); + out[0] = (channel >> 8) & 0xff; + out[1] = channel & 0xff; + out.set(bytes, 2); + return out; +} + +/** The channel and bytes of a frame; `null` when it is too short to carry a channel. */ +export function unframe(data: ArrayBuffer | Uint8Array): { channel: number; bytes: Uint8Array } | null { + const view = data instanceof Uint8Array ? data : new Uint8Array(data); + if (view.length < 2) return null; + const high = view[0] ?? 0; + const low = view[1] ?? 0; + return { channel: (high << 8) | low, bytes: view.subarray(2) }; +} diff --git a/web/src/api/http.test.ts b/web/src/api/http.test.ts new file mode 100644 index 0000000..58d7891 --- /dev/null +++ b/web/src/api/http.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it, vi } from "vitest"; +import { askReauth, settleReauth } from "../state/reauth"; +import { ApiRequestError, createHttp, type FetchFn } from "./http"; +import type { ApiError } from "./types"; + +const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status }); +const reauthRequired = () => json(403, { code: "reauth_required", message: "Confirm it's you." } satisfies ApiError); + +/** A server that answers with `replies` in turn and records what it was sent. */ +function server(...replies: Response[]) { + const sent: RequestInit[] = []; + const fetchFn: FetchFn = (_path, init) => { + sent.push(init); + return Promise.resolve(replies.shift() ?? json(500, { code: "internal", message: "no reply" })); + }; + return { sent, fetchFn }; +} + +describe("the HTTP layer", () => { + it("sends the change header on changes, and not on reads", async () => { + const { sent, fetchFn } = server(json(200, {}), json(200, {})); + const http = createHttp(fetchFn); + await http.get("/api/account"); + await http.delete("/api/account/sessions/2"); + expect(new Headers(sent[0]?.headers).has("x-redshell")).toBe(false); + expect(new Headers(sent[1]?.headers).get("x-redshell")).toBe("1"); + }); + + it("asks the user to confirm it's them, then sends the change once more", async () => { + const { sent, fetchFn } = server(reauthRequired(), json(200, { done: true })); + const reauthenticate = vi.fn(() => Promise.resolve()); + const result = await createHttp(fetchFn, { reauthenticate }).delete("/api/account/sessions/2"); + expect(result).toEqual({ done: true }); + expect(reauthenticate).toHaveBeenCalledOnce(); + expect(sent).toHaveLength(2); + }); + + it("gives up after one retry, and when the user declines", async () => { + const twice = server(reauthRequired(), reauthRequired()); + const again = createHttp(twice.fetchFn, { reauthenticate: () => Promise.resolve() }).post("/api/pair/KX74MP/approve"); + await expect(again).rejects.toBeInstanceOf(ApiRequestError); + + const declined = server(reauthRequired()); + const cancel = new DOMException("no", "AbortError"); + const refused = createHttp(declined.fetchFn, { reauthenticate: () => Promise.reject(cancel) }).post("/api/pair/KX74MP/approve"); + await expect(refused).rejects.toBe(cancel); + expect(declined.sent).toHaveLength(1); + }); + + it("reads an error page that isn't JSON by its status", async () => { + const { fetchFn } = server(new Response("

Payload Too Large

", { status: 413 })); + await expect(createHttp(fetchFn).post("/api/hosts", {})).rejects.toMatchObject({ status: 413, code: "bad_request" }); + }); +}); + +describe("confirming it's the user", () => { + it("shares one answer between the changes that wait for it", async () => { + const first = askReauth(); + const second = askReauth(); + expect(second).toBe(first); + settleReauth(true); + await expect(Promise.all([first, second])).resolves.toEqual([undefined, undefined]); + + const declined = askReauth(); + settleReauth(false); + await expect(declined).rejects.toMatchObject({ name: "AbortError" }); + }); +}); diff --git a/web/src/api/http.ts b/web/src/api/http.ts new file mode 100644 index 0000000..3214d1f --- /dev/null +++ b/web/src/api/http.ts @@ -0,0 +1,125 @@ +import { CHANGE_HEADER, CHANGE_HEADER_VALUE } from "../protocol/index.ts"; +import type { ApiError, ErrorCode } from "./types"; + +/** The server answered with an error body (`ApiError`). */ +export class ApiRequestError extends Error { + readonly status: number; + readonly code: ErrorCode; + readonly retryAfterSecs: number | null; + + constructor(status: number, body: ApiError) { + super(body.message); + this.name = "ApiRequestError"; + this.status = status; + this.code = body.code; + this.retryAfterSecs = body.retry_after_secs ?? null; + } +} + +/** How long a `rate_limited` answer says to wait, in ms; `null` for any other error. */ +export function rateLimitMs(error: unknown): number | null { + return error instanceof ApiRequestError && error.code === "rate_limited" ? (error.retryAfterSecs ?? 30) * 1000 : null; +} + +/** The request never got an answer: offline, DNS, TLS, or the server is down. */ +export class NetworkError extends Error { + constructor(cause: unknown) { + super("The server could not be reached", { cause }); + this.name = "NetworkError"; + } +} + +export type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; + +export type FetchFn = (input: string, init: RequestInit) => Promise; + +/** Status → error code for responses whose body isn't an `ApiError` (a proxy's 502 page). */ +function codeForStatus(status: number): ErrorCode { + if (status === 401) return "unauthorized"; + if (status === 403) return "forbidden"; + if (status === 404) return "not_found"; + if (status === 409) return "conflict"; + if (status === 429) return "rate_limited"; + if (status < 500) return "bad_request"; + if (status === 503) return "unavailable"; + return "internal"; +} + +function isApiError(value: unknown): value is ApiError { + return typeof value === "object" && value !== null && "code" in value && "message" in value; +} + +/** The headers of a request: JSON when it has a body, and the change header on all but GET. */ +function headersFor(method: Method, body: unknown): Record { + const headers: Record = {}; + if (body !== undefined) headers["Content-Type"] = "application/json"; + if (method !== "GET") headers[CHANGE_HEADER] = CHANGE_HEADER_VALUE; + return headers; +} + +/** A body as JSON, or `null` when there is none or it isn't JSON (a proxy's error page). */ +function parseBody(text: string): unknown { + try { + return text ? JSON.parse(text) : null; + } catch { + return null; + } +} + +/** The error a 4xx or 5xx answer carries, or one made from its status when its body isn't an `ApiError`. */ +const errorOf = (response: Response, parsed: unknown): ApiError => + isApiError(parsed) ? parsed : { code: codeForStatus(response.status), message: response.statusText || `HTTP ${response.status}` }; + +/** What the HTTP layer hands to the app: losing the sign-in, and confirming it's the user. */ +export interface HttpHooks { + /** The sign-in is gone (401 `unauthorized`). A wrong password is a 401 too, but not this. */ + onUnauthorized?: () => void; + /** + * A change needs a recent re-authentication (403 `reauth_required`): settles once the user + * confirmed it's them, and the request is then sent once more; rejects when they declined. + */ + reauthenticate?: () => Promise; +} + +/** + * JSON over fetch with the session cookie. Every state-changing request carries the page's + * Origin (the browser adds it) and `X-RedShell: 1`, which the server checks: a page of another + * site can't add that header without a CORS preflight. A change refused for want of a recent + * re-authentication is retried here, once, after `hooks.reauthenticate`, so no screen handles + * `reauth_required` itself. Returns the parsed body; responses are trusted to match the + * server's types, as they are generated from the same source. + */ +export function createHttp(fetchFn: FetchFn, hooks: HttpHooks = {}) { + async function request(method: Method, path: string, body?: unknown, retried = false): Promise { + let response: Response; + try { + response = await fetchFn(path, { + method, + credentials: "same-origin", + headers: headersFor(method, body), + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch (cause) { + throw new NetworkError(cause); + } + const parsed = parseBody(await response.text()); + if (response.ok) return parsed as T; + const error = errorOf(response, parsed); + if (error.code === "unauthorized") hooks.onUnauthorized?.(); + if (error.code === "reauth_required" && hooks.reauthenticate && !retried) { + await hooks.reauthenticate(); + return request(method, path, body, true); + } + throw new ApiRequestError(response.status, error); + } + + return { + get: (path: string) => request("GET", path), + post: (path: string, body?: unknown) => request("POST", path, body ?? {}), + put: (path: string, body: unknown) => request("PUT", path, body), + patch: (path: string, body: unknown) => request("PATCH", path, body), + delete: (path: string, body?: unknown) => request("DELETE", path, body), + }; +} + +export type Http = ReturnType; diff --git a/web/src/api/mock/data.ts b/web/src/api/mock/data.ts new file mode 100644 index 0000000..4e87da3 --- /dev/null +++ b/web/src/api/mock/data.ts @@ -0,0 +1,406 @@ +import type { Approval, BrowserSession, Device, Passkey, Profile, PushSubscriptionInfo, SessionInfo, SshHost } from "../types"; +import { + asked, + claudeScreen, + codexScreen, + dim, + fail, + opencodeScreen, + pass, + result, + said, + type Screen, + shellScreen, + tool, +} from "./screens"; + +export const HOME = "/home/andy"; +const PROFILE_NAMES: Record = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode" }; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; + +export interface Seed { + sessions: SessionInfo[]; + screens: Map; + approvals: Approval[]; +} + +function session(fields: Partial & Pick, now: number): SessionInfo { + return { + name: null, + profile: null, + agent: null, + agent_state: null, + last_message: null, + cwd: null, + profile_name: null, + command: null, + start_cwd: null, + cols: 47, + rows: 39, + created_at: now - DAY, + active_at: now, + last_line: null, + exit: null, + pending_approvals: 0, + ...fields, + }; +} + +function bashApproval(now: number, approvalTimeoutMs: number): Approval { + return { + id: "ap-npm-ci", + session: "aurora", + tool: "Bash", + input: { command: "rm -rf node_modules && npm ci", description: "Reinstall dependencies from scratch" }, + summary: "rm -rf node_modules && npm ci", + description: "Reinstall dependencies from scratch", + permission_suggestions: [ + { type: "addRules", rules: [{ toolName: "Bash", ruleContent: "npm ci:*" }], behavior: "allow", destination: "localSettings" }, + ], + created_at: now - 2 * MINUTE, + expires_at: now - 2 * MINUTE + approvalTimeoutMs, + }; +} + +function editApproval(now: number): Approval { + return { + id: "ap-edit-feed", + session: "aurora", + tool: "Edit", + input: { + file_path: "/home/andy/src/aurora/src/lib/feed.ts", + old_string: [ + "/** The release feed for the home page, newest first. */", + "export async function loadFeed(params: URLSearchParams) {", + " const limit = Number(params.get(\"limit\") ?? 20)", + " const releases = await getReleases()", + " return releases.slice(0, limit)", + "}", + "", + "export const prerender = false", + ].join("\n"), + new_string: [ + "/** The release feed for the home page, newest first. */", + "export async function loadFeed(params: URLSearchParams) {", + " const limit = Number(params.get(\"limit\") ?? 20)", + " const range = parseRange(params)", + " const releases = await getReleases({ range })", + " return releases.slice(0, limit)", + "}", + "", + "export const prerender = false", + ].join("\n"), + }, + summary: "src/lib/feed.ts", + description: null, + permission_suggestions: [ + { type: "addRules", rules: [{ toolName: "Edit", ruleContent: "src/**" }], behavior: "allow", destination: "localSettings" }, + ], + created_at: now - 12_000, + expires_at: now + 588_000, + }; +} + +/** A new file longer than a landscape sheet shows: the preview clips, fades and offers Show all. */ +function writeApproval(now: number): Approval { + const content = [ + 'import { describe, expect, it } from "vitest";', + 'import { parseRange } from "./range";', + "", + 'describe("parseRange", () => {', + ' it("defaults to the last 30 days", () => {', + ' expect(parseRange(new URLSearchParams())).toEqual({ days: 30 });', + " });", + "", + ' it("reads ?days", () => {', + ' expect(parseRange(new URLSearchParams("days=7"))).toEqual({ days: 7 });', + " });", + "", + ' it("ignores a range that is not a number", () => {', + ' expect(parseRange(new URLSearchParams("days=soon"))).toEqual({ days: 30 });', + " });", + "});", + ].join("\n"); + return { + id: "ap-write-range-test", + session: "aurora", + tool: "Write", + input: { file_path: "/home/andy/src/aurora/src/lib/range.test.ts", content }, + summary: "src/lib/range.test.ts", + description: null, + permission_suggestions: null, + created_at: now - 8_000, + expires_at: now + 592_000, + }; +} + +function fetchApproval(now: number): Approval { + return { + id: "ap-fetch", + session: "aurora", + tool: "WebFetch", + input: { + url: "https://docs.npmjs.com/cli/v10/commands/npm-ci", + prompt: "Summarise when npm ci refuses to run and what it does with an existing node_modules folder.", + }, + summary: "docs.npmjs.com", + description: null, + permission_suggestions: null, + created_at: now - 30_000, + expires_at: now + 570_000, + }; +} + +/** An agent session started from its profile in a folder under the home. */ +function agentSession( + id: string, + agent: string, + state: SessionInfo["agent_state"], + age: number, + fields: Partial, + now: number, +): SessionInfo { + return session( + { id, title: id, kind: "agent", profile: `agent:${agent}`, agent, agent_state: state, cwd: `${HOME}/src/${id}`, start_cwd: `${HOME}/src/${id}`, profile_name: PROFILE_NAMES[agent] ?? agent, active_at: now - age, ...fields }, + now, + ); +} + +function seedSessions(now: number, pending: number): SessionInfo[] { + return [ + agentSession("aurora", "claude", "needs_approval", 2 * MINUTE, { last_line: "Waiting for permission…", pending_approvals: pending }, now), + agentSession( + "api-gateway", + "codex", + "needs_input", + 14 * MINUTE, + { + last_message: "Which port should the gateway listen on? 8080 is taken by the dashboard.", + last_line: "Which port should the gateway listen on?", + }, + now, + ), + agentSession("aurora-web", "opencode", "working", 5_000, { last_line: "Reading src/routes/+page.svelte" }, now), + agentSession("docs", "claude", "finished", HOUR + 4 * MINUTE, { last_message: "Updated REMOTE.md and the endpoint table.", last_line: "Updated REMOTE.md and the endpoint table." }, now), + agentSession("scratch", "claude", "idle", 2 * HOUR + 10 * MINUTE, { last_line: "> " }, now), + session({ id: "shell-aurora", title: "~/src/aurora", kind: "shell", profile: "shell", profile_name: "zsh", cwd: `${HOME}/src/aurora`, start_cwd: `${HOME}/src/aurora`, active_at: now - 3 * HOUR, last_line: "andy@pi:~/src/aurora$" }, now), + session( + { + id: "build", + title: "make release", + kind: "shell", + profile: "shell", + profile_name: "zsh", + cwd: `${HOME}/src/redshell`, + start_cwd: `${HOME}/src/redshell`, + active_at: now - 5 * HOUR, + last_line: "Finished release [optimized] target(s) in 4m 12s", + exit: { code: 0, at: now - 5 * HOUR }, + }, + now, + ), + session( + { + id: "prod-api", + title: "prod-api", + kind: "ssh", + profile: "ssh:prod-api", + profile_name: "prod-api", + active_at: now - 4 * DAY, + last_line: "Connection closed by 10.0.4.12 port 22", + exit: { code: 255, at: now - 4 * DAY }, + }, + now, + ), + ]; +} + +function seedScreens(): Map { + const prodApi = shellScreen("deploy", "prod-api", "~", [["sudo systemctl restart api", []]]); + return new Map([ + [ + "aurora", + claudeScreen([ + asked("Run the tests and fix anything that fails"), + "", + said("I'll run the test suite first."), + "", + tool("Bash", "npm run test -- --watch=false"), + ...result(pass("src/lib/feed.test.ts", 14), pass("src/routes/api.test.ts", 9), fail("src/lib/install.test.ts")), + "", + said("The lockfile no longer matches package.json. I'll reinstall from scratch."), + "", + tool("Bash", "rm -rf node_modules && npm ci"), + ...result(dim("Waiting for permission…")), + ]), + ], + [ + "api-gateway", + codexScreen([ + asked("Add a health check endpoint to the gateway"), + "", + "• Added GET /healthz in src/server.ts", + "• Wired it into the readiness probe.", + "", + "• Which port should the gateway listen on?", + " 8080 is taken by the dashboard.", + ]), + ], + [ + "aurora-web", + opencodeScreen([ + asked("Move the release list to the new feed API"), + "", + `${dim("│")} Read src/lib/api.ts`, + `${dim("│")} Read src/routes/+page.ts`, + `${dim("│")} Reading src/routes/+page.svelte`, + ]), + ], + [ + "docs", + claudeScreen([ + asked("Document the new endpoints in REMOTE.md"), + "", + tool("Update", "docs/REMOTE.md"), + ...result(`Updated docs/REMOTE.md with ${dim("42 additions")}`), + "", + said("Updated REMOTE.md and the endpoint table."), + ]), + ], + ["scratch", claudeScreen([])], + [ + "shell-aurora", + shellScreen("andy", "pi", "~/src/aurora", [ + ["git status", ["On branch main", "Your branch is up to date with 'origin/main'.", "", "nothing to commit, working tree clean"]], + ]), + ], + [ + "build", + shellScreen("andy", "pi", "~/src/redshell", [ + ["make release", [" Compiling redshell-server v0.0.3", " Finished release [optimized] target(s) in 4m 12s"]], + ]), + ], + [ + "prod-api", + { ...prodApi, text: `${prodApi.text}client_loop: send disconnect: Broken pipe\r\nConnection closed by 10.0.4.12 port 22\r\n` }, + ], + ]); +} + +/** The sessions, screens and approvals a scenario starts with. */ +export function seed(scenario: string, now: number): Seed { + if (scenario === "empty") return { sessions: [], screens: new Map(), approvals: [] }; + + const approvalTimeout = scenario === "expiring" ? 2 * MINUTE + 45_000 : 10 * MINUTE; + const queue: Record = { + diff: [editApproval(now)], + other: [fetchApproval(now)], + write: [writeApproval(now)], + }; + const approvals = queue[scenario] ?? [bashApproval(now, approvalTimeout), editApproval(now)]; + return { sessions: seedSessions(now, approvals.length), screens: seedScreens(), approvals }; +} + +export const profiles: Profile[] = [ + { id: "agent:claude", name: "Claude Code", kind: "agent", description: "claude", available: true, group: null }, + { id: "agent:codex", name: "Codex", kind: "agent", description: "codex", available: true, group: null }, + { id: "agent:opencode", name: "OpenCode", kind: "agent", description: "opencode", available: false, group: null }, + { id: "shell", name: "zsh", kind: "shell", description: "/usr/bin/zsh", available: true, group: null }, + { id: "shell:bash", name: "bash", kind: "shell", description: "/bin/bash", available: true, group: null }, + { id: "ssh:prod-api", name: "prod-api", kind: "ssh", description: "deploy@10.0.4.12", available: true, group: "Production" }, + { id: "ssh:staging", name: "staging", kind: "ssh", description: "andy@staging.internal", available: true, group: "Production" }, + { id: "ssh:nas", name: "nas", kind: "ssh", description: "andy@nas.local", available: true, group: null }, + { id: "ssh:gpu-box", name: "gpu-box", kind: "ssh", description: "andy@192.168.1.40", available: true, group: "From ~/.ssh/config" }, +]; + +export const hosts: SshHost[] = [ + { + name: "prod-api", + host: "10.0.4.12", + user: "deploy", + group: "Production", + forward_agent: true, + forwards: [ + { kind: "local", bind_port: 5432, target_host: "db.internal", target_port: 5432, label: "Postgres", auto_start: true }, + { kind: "dynamic", bind_port: 1080 }, + ], + origin: "redshell", + }, + { name: "staging", host: "staging.internal", user: "andy", group: "Production", startup_command: "cd /srv/app", origin: "redshell" }, + { name: "nas", host: "nas.local", user: "andy", origin: "redshell" }, + { name: "gpu-box", host: "192.168.1.40", user: "andy", identity_file: "~/.ssh/id_ed25519", origin: "ssh_config" }, +]; + +/** A folder as the server reads one: `~` is the home, and a trailing slash doesn't matter. */ +export function folder(path: string): string { + const expanded = path === "~" || path.startsWith("~/") ? HOME + path.slice(1) : path; + return expanded.length > 1 ? expanded.replace(/\/+$/, "") : expanded; +} + +/** A small folder tree for "Other folder…" completion (`GET /api/fs/folders`). */ +export const folderTree: Record = { + "/": ["bin", "etc", "home", "opt", "srv", "usr", "var"], + "/home": ["andy"], + [HOME]: [".config", "Downloads", "notes", "src"], + [`${HOME}/src`]: ["api-gateway", "aurora", "aurora-web", "docs", "redshell", "scratch"], + [`${HOME}/src/aurora`]: ["scripts", "src", "tests"], +}; + +export function passkeys(now: number, scenario: string): Passkey[] { + if (scenario === "no-passkeys") return []; + return [ + { id: 1, name: "iPhone", created_at: Date.parse("2026-03-03T10:00:00Z"), last_used_at: now - HOUR }, + { id: 2, name: "MacBook Pro", created_at: Date.parse("2026-03-12T10:00:00Z"), last_used_at: now - 2 * DAY }, + ]; +} + +export function devices(now: number): Device[] { + return [ + { id: 1, name: "MacBook Pro", created_at: now - 30 * DAY, last_seen_at: now - 5 * MINUTE, last_ip: "100.64.0.2", current: false }, + { id: 2, name: "Workstation", created_at: now - 60 * DAY, last_seen_at: now - 3 * DAY, last_ip: "100.64.0.7", current: false }, + ]; +} + +export function browsers(now: number): BrowserSession[] { + return [ + { + id: 10, + name: "Safari on iPhone", + created_at: now - 3 * DAY, + last_seen_at: now, + expires_at: now + 27 * DAY, + last_ip: "100.64.0.9", + user_agent: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 Version/18.2 Mobile/15E148 Safari/604.1", + current: true, + }, + { + id: 11, + name: "Chrome on Windows", + created_at: now - 9 * DAY, + last_seen_at: now - 6 * HOUR, + expires_at: now + 21 * DAY, + last_ip: "100.64.0.2", + user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36", + current: false, + }, + ]; +} + +/** The account's push subscriptions: another browser's, and this one's at `current` when given. */ +export function pushSubscriptions(now: number, current: string | null): PushSubscriptionInfo[] { + const mine: PushSubscriptionInfo[] = current + ? [{ endpoint: current, events: ["approval_requested", "needs_input", "finished", "failed"], created_at: now - 3 * DAY, current: true }] + : []; + return [ + ...mine, + { + endpoint: "https://fcm.googleapis.com/fcm/send/mock-workstation", + events: ["approval_requested", "needs_input", "failed"], + created_at: now - 9 * DAY, + current: false, + }, + ]; +} diff --git a/web/src/api/mock/index.ts b/web/src/api/mock/index.ts new file mode 100644 index 0000000..df1af3e --- /dev/null +++ b/web/src/api/mock/index.ts @@ -0,0 +1,736 @@ +// An in-browser fake of redshell-server, for developing and screenshotting every screen +// without one. It speaks the same REST and WebSocket protocol as the real server, so the +// whole client layer (HTTP, framing, reconnects) runs for real against it. +// +// Scenarios (`?mock=`): default, empty, loading, error, signed-out, rate-limited, +// unreachable, setup, setup-expired, reconnecting, diff, write, other, expiring, answer-fails, +// remote-answer, arrival, no-passkeys, passkey-only, passkeys-off, push-on. +// +// A signed-in scenario starts without a recent re-authentication, as after a sign-in long ago: +// the changes that need one answer `reauth_required` until "Confirm it's you" (any password of +// 10 characters or more, or the passkey sheet) or a sign-in. + +import { PROTOCOL_VERSION } from "../../protocol/index.ts"; +import type { Transport } from "../client"; +import { MOCK_ENDPOINT, mockWebAuthn, mockWebPush } from "./platform"; +import { MockSocket, type SocketHost } from "./socket"; +import type { + Account, + Approval, + ApprovalAnswer, + ApprovalDecision, + ApiError, + ClientMessage, + Modes, + PairingInfo, + PasskeyChallenge, + PushEvent, + PushSubscriptionInfo, + ServerInfo, + ServerMessage, + SessionInfo, + SshHost, + User, +} from "../types"; +import * as data from "./data"; +import { asked, claudeScreen, dim, render, result, said, type Screen, shellScreen, tool } from "./screens"; + +const LATENCY_MS = 140; +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const USER: User = { id: 1, username: "andy", created_at: Date.parse("2026-03-03T10:00:00Z") }; + +const MODES: Modes = { + alt_screen: false, + app_cursor: false, + app_keypad: false, + bracketed_paste: true, + mouse_tracking: null, + mouse_encoding: "normal", + focus_reporting: false, + cursor_visible: true, + cursor_shape: "block", + cursor_blinking: false, + title: null, +}; + +const WORK = [ + "Read src/lib/feed.ts", + "Edit src/routes/+page.svelte", + "Bash npm run check", + "Read src/lib/components/ReleaseList.svelte", + "Edit src/lib/components/ReleaseList.svelte", + "Bash npm run test -- --run", +]; + +type Reply = { status: number; body?: unknown } | "hang"; + +const ok = (body?: unknown): Reply => ({ status: body === undefined ? 204 : 200, body }); +const fail = (status: number, code: ApiError["code"], message: string, extra: Partial = {}): Reply => ({ + status, + body: { code, message, ...extra } satisfies ApiError, +}); + +function field(body: unknown, key: string): unknown { + return typeof body === "object" && body !== null && key in body ? (body as Record)[key] : undefined; +} +const text = (body: unknown, key: string) => { + const value = field(body, key); + return typeof value === "string" ? value : ""; +}; + +/** Enough of a check for the mock: the real server validates every field. */ +function isSshHost(body: unknown): body is SshHost { + return typeof field(body, "name") === "string"; +} + +/** The one pairing code the mock knows, typed as `KX7-4MP`. */ +const PAIRING_CODE = "KX74MP"; + +const PUSH_EVENTS: readonly PushEvent[] = ["approval_requested", "needs_input", "finished", "failed", "notification"]; + +/** How long a re-authentication holds, as on the server. */ +const REAUTH_MS = 5 * 60_000; + +const REAUTH_REQUIRED = fail(403, "reauth_required", "Confirm it's you before this change."); + +class MockBackend implements SocketHost { + private readonly scenario: string; + private signedIn: boolean; + private passkeyOnly: boolean; + /** Until when the last re-authentication holds. */ + private reauthUntil: number | null = null; + private readonly sessions: Map; + private readonly screens: Map; + private approvals: Approval[]; + private passkeys; + private devices; + private browsers; + private hosts: SshHost[] = [...data.hosts]; + private pushSubscriptions: PushSubscriptionInfo[]; + private readonly sockets = new Set(); + private nextChannel = 1; + private nextId = 1; + private socketsOpened = 0; + /** `loading` and `error` show the REST states, so the socket must not deliver the list. */ + private refuseSockets: boolean; + private workStep = 0; + + constructor(scenario: string) { + const now = Date.now(); + const seed = data.seed(scenario, now); + this.scenario = scenario; + this.signedIn = !["signed-out", "rate-limited", "unreachable", "setup", "setup-expired", "passkeys-off"].includes(scenario); + this.passkeyOnly = scenario === "passkey-only"; + this.refuseSockets = scenario === "loading" || scenario === "error"; + this.sessions = new Map(seed.sessions.map((s) => [s.id, s])); + this.screens = seed.screens; + this.approvals = seed.approvals; + this.passkeys = data.passkeys(now, scenario); + this.devices = data.devices(now); + this.browsers = data.browsers(now); + this.pushSubscriptions = data.pushSubscriptions(now, scenario === "push-on" ? MOCK_ENDPOINT : null); + setInterval(() => { + this.work(); + }, 2600); + } + + connect(): MockSocket { + this.socketsOpened += 1; + const socket = new MockSocket(this, this.refuseSockets || !this.signedIn); + this.sockets.add(socket); + return socket; + } + + disconnect(socket: MockSocket): void { + this.sockets.delete(socket); + } + + async fetch(input: string, init: RequestInit): Promise { + if (this.scenario === "unreachable") { + await delay(400); + throw new TypeError("Failed to fetch"); + } + await delay(LATENCY_MS); + const url = new URL(input, location.origin); + const body: unknown = typeof init.body === "string" ? JSON.parse(init.body) : null; + const reply = this.route(init.method ?? "GET", url.pathname, url.searchParams, body); + if (reply === "hang") return new Promise(() => undefined); + const payload = reply.body === undefined ? null : JSON.stringify(reply.body); + return new Response(payload, { status: reply.status, headers: { "Content-Type": "application/json" } }); + } + + // REST + + private route(method: string, path: string, query: URLSearchParams, body: unknown): Reply { + const key = `${method} ${path}`; + const open = this.publicRoute(key, body); + if (open) return open; + if (!this.signedIn) return fail(401, "unauthorized", "Sign in first."); + return this.accountRoute(key, path, method, body) ?? this.sessionRoute(key, path, method, query, body) ?? fail(404, "not_found", `No route for ${key}`); + } + + private publicRoute(key: string, body: unknown): Reply | null { + switch (key) { + case "GET /api/auth/info": + return ok({ + version: "0.0.3", + protocol_version: PROTOCOL_VERSION, + setup_required: this.scenario === "setup", + min_password_length: 10, + passkeys: this.passkeysAvailable, + } satisfies ServerInfo); + case "GET /api/auth/me": + return this.signedIn ? ok(USER) : fail(401, "unauthorized", "Sign in first."); + case "POST /api/auth/sign-in": + if (this.scenario === "rate-limited") { + return fail(429, "rate_limited", "Too many attempts.", { retry_after_secs: 42 }); + } + if (text(body, "username") !== USER.username || text(body, "password").length < 10) { + return fail(401, "invalid_credentials", "Wrong username or password."); + } + if (this.passkeyOnly) return fail(403, "passkey_required", "This account signs in with a passkey."); + return this.signIn(); + case "POST /api/setup": + if (text(body, "code") === "expired") return fail(403, "forbidden", "This setup link has expired."); + return this.signIn(); + case "POST /api/auth/passkey/begin": + if (!this.passkeysAvailable) return fail(503, "unavailable", "Passkeys need an https public_url."); + return ok({ + ceremony: "mock-sign-in", + options: { publicKey: { challenge: "bW9jay1jaGFsbGVuZ2U", rpId: location.hostname, timeout: 60_000, userVerification: "required" } }, + } satisfies PasskeyChallenge); + case "POST /api/auth/passkey/finish": + return this.signIn(); + default: + return null; + } + } + + private get passkeysAvailable(): boolean { + return this.scenario !== "passkeys-off"; + } + + private account(): Account { + return { + ...USER, + passkey_only: this.passkeyOnly, + passkeys: this.passkeys.length, + passkeys_available: this.passkeysAvailable, + reauth_expires_at: this.reauthHolds ? (this.reauthUntil ?? undefined) : undefined, + }; + } + + private get reauthHolds(): boolean { + return (this.reauthUntil ?? 0) > Date.now(); + } + + /** A sign-in or "Confirm it's you": changes that need a re-authentication go through for a while. */ + private reauthenticated(): number { + this.reauthUntil = Date.now() + REAUTH_MS; + return this.reauthUntil; + } + + private signIn(): Reply { + this.signedIn = true; + this.reauthenticated(); + return ok({ user: USER, device_token: null }); + } + + /** `POST /api/auth/reauth`: the password unless passkey-only, or the mock passkey sheet's answer. */ + private reauth(body: unknown): Reply { + if (text(body, "method") === "passkey") { + if (text(body, "ceremony") !== "mock-reauth") return fail(401, "invalid_credentials", "That passkey was not accepted."); + } else if (this.passkeyOnly) { + return fail(403, "passkey_required", "This account signs in with a passkey."); + } else if (text(body, "password").length < 10 || text(body, "password") === "wrong-password") { + return fail(401, "invalid_credentials", "Wrong password."); + } + return ok({ reauth_expires_at: this.reauthenticated() }); + } + + /** Turning passkey-only on signs out the other sign-ins, all of which the mock takes for password ones. */ + private setPasskeyOnly(enabled: boolean): Reply { + if (enabled && this.passkeys.length === 0) return fail(409, "conflict", "Add a passkey first."); + this.passkeyOnly = enabled; + if (enabled) { + this.devices = this.devices.filter((d) => d.current); + this.browsers = this.browsers.filter((b) => b.current); + } + return ok(this.account()); + } + + private accountRoute(key: string, path: string, method: string, body: unknown): Reply | null { + switch (key) { + case "POST /api/auth/sign-out": + this.signedIn = false; + for (const socket of this.sockets) socket.close(4001); + return ok({}); + case "POST /api/auth/reauth": + return this.reauth(body); + case "POST /api/auth/reauth/passkey/begin": + if (!this.passkeysAvailable) return fail(503, "unavailable", "Passkeys need an https public_url."); + if (this.passkeys.length === 0) return fail(409, "conflict", "This account has no passkey; use the password."); + return ok({ + ceremony: "mock-reauth", + options: { publicKey: { challenge: "bW9jay1yZWF1dGg", rpId: location.hostname, timeout: 60_000, userVerification: "required" } }, + } satisfies PasskeyChallenge); + case "GET /api/account": + return ok(this.account()); + case "POST /api/account/password": + if (this.passkeyOnly && !this.reauthHolds) return REAUTH_REQUIRED; + return text(body, "current_password") === "wrong-password" + ? fail(401, "invalid_credentials", "Wrong password.") + : ok({}); + case "PUT /api/account/passkey-only": + return this.reauthHolds ? this.setPasskeyOnly(field(body, "enabled") === true) : REAUTH_REQUIRED; + case "GET /api/account/passkeys": + return ok(this.passkeys); + case "POST /api/account/passkeys/begin": + if (!this.reauthHolds) return REAUTH_REQUIRED; + return ok({ + ceremony: "mock-register", + options: { + publicKey: { + challenge: "bW9jay1yZWdpc3Rlcg", + rp: { name: "RedShell", id: location.hostname }, + user: { id: "dXNlci0x", name: USER.username, displayName: USER.username }, + pubKeyCredParams: [{ type: "public-key", alg: -7 }], + authenticatorSelection: { residentKey: "required", requireResidentKey: true, userVerification: "required" }, + }, + }, + } satisfies PasskeyChallenge); + case "POST /api/account/passkeys/finish": { + const passkey = { id: Date.now(), name: text(body, "name") || "Passkey", created_at: Date.now(), last_used_at: null }; + this.passkeys = [...this.passkeys, passkey]; + return ok(passkey); + } + case "GET /api/account/devices": + return ok(this.devices); + case "GET /api/account/sessions": + return ok(this.browsers); + default: + break; + } + + const passkey = /^\/api\/account\/passkeys\/(\d+)$/.exec(path); + if (passkey) { + const id = Number(passkey[1]); + if (method === "DELETE") { + if (!this.reauthHolds) return REAUTH_REQUIRED; + if (this.passkeyOnly && this.passkeys.length === 1) { + return fail(409, "conflict", "Turn off passkey-only sign-in before removing your last passkey."); + } + this.passkeys = this.passkeys.filter((p) => p.id !== id); + return ok(); + } + this.passkeys = this.passkeys.map((p) => (p.id === id ? { ...p, name: text(body, "name") } : p)); + return ok(this.passkeys.find((p) => p.id === id)); + } + const device = /^\/api\/account\/(devices|sessions)\/(\d+)$/.exec(path); + if (device && method === "DELETE") { + if (!this.reauthHolds) return REAUTH_REQUIRED; + const id = Number(device[2]); + if (device[1] === "devices") this.devices = this.devices.filter((d) => d.id !== id); + else this.browsers = this.browsers.filter((b) => b.id !== id); + return ok(); + } + const pairing = /^\/api\/pair\/([^/]+)(\/approve|\/reject)?$/.exec(path); + if (pairing) { + const code = decodeURIComponent(pairing[1] ?? "").replace("-", "").toUpperCase(); + if (code !== PAIRING_CODE) return fail(404, "not_found", "No such pairing request."); + if (pairing[2] === "/approve" && !this.reauthHolds) return REAUTH_REQUIRED; + const now = Date.now(); + return ok({ + code: "KX7-4MP", + device_name: "MacBook Pro", + platform: "macOS", + ip: "100.64.0.2", + // Another network than this browser's, so the page shows its warning. + same_address: false, + created_at: now - 2 * 60_000, + expires_at: now + 8 * 60_000, + } satisfies PairingInfo); + } + return null; + } + + private sessionRoute(key: string, path: string, method: string, query: URLSearchParams, body: unknown): Reply | null { + switch (key) { + case "GET /api/sessions": + if (this.scenario === "loading") return "hang"; + if (this.scenario === "error") return fail(500, "internal", "The session store is unavailable."); + return ok([...this.sessions.values()]); + case "POST /api/sessions": + return this.create(text(body, "profile"), text(body, "cwd")); + case "GET /api/approvals": + return ok(this.approvals); + case "GET /api/profiles": + return ok(data.profiles); + case "GET /api/fs/folders": { + // Like the server: `~` is the home, and the listing names the folder as it was asked for. + const path = query.get("path") ?? ""; + const folder = data.folder(path); + if (!folder.startsWith("/")) return fail(400, "bad_request", "the folder must be an absolute path"); + const folders = data.folderTree[folder]; + return folders ? ok({ path, folders, truncated: false }) : fail(403, "forbidden", `${folder}: No such file or directory`); + } + case "GET /api/push/key": + return ok({ vapid_public_key: "BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U" }); + case "GET /api/hosts": + return ok(this.hosts); + case "POST /api/hosts": + return this.saveHost(body, null); + case "GET /api/push/subscriptions": + return ok(this.pushSubscriptions); + case "POST /api/push/subscriptions": { + const subscription = { endpoint: text(body, "endpoint"), events: [...PUSH_EVENTS], created_at: Date.now(), current: true }; + this.pushSubscriptions = [...this.pushSubscriptions.filter((sub) => !sub.current), subscription]; + return ok({}); + } + case "PUT /api/push/subscriptions": { + const events = field(body, "events"); + const chosen = PUSH_EVENTS.filter((event) => Array.isArray(events) && events.includes(event)); + this.pushSubscriptions = this.pushSubscriptions.map((sub) => + sub.endpoint === text(body, "endpoint") ? { ...sub, events: chosen } : sub, + ); + return ok({}); + } + case "DELETE /api/push/subscriptions": + this.pushSubscriptions = this.pushSubscriptions.filter((sub) => sub.endpoint !== text(body, "endpoint")); + return ok({}); + case "POST /api/push/test": + return ok({}); + default: + break; + } + + const session = /^\/api\/sessions\/([^/]+)$/.exec(path); + if (session) { + const id = decodeURIComponent(session[1] ?? ""); + if (method === "DELETE") { + this.kill(id); + return ok(); + } + const name = field(body, "name"); + this.update(id, { name: typeof name === "string" && name ? name : null }); + return ok(this.sessions.get(id)); + } + const approval = /^\/api\/approvals\/([^/]+)$/.exec(path); + if (approval) { + if (this.scenario === "answer-fails") return fail(502, "internal", "Bad gateway"); + const decision = text(body, "decision"); + if (decision !== "allow" && decision !== "allow_always" && decision !== "deny" && decision !== "terminal") { + return fail(400, "bad_request", "Unknown decision."); + } + this.answer(decodeURIComponent(approval[1] ?? ""), { decision }, "browser"); + return ok({}); + } + const host = /^\/api\/hosts\/([^/]+)$/.exec(path); + if (host) { + const name = decodeURIComponent(host[1] ?? ""); + if (method === "DELETE") { + this.hosts = this.hosts.filter((h) => h.name !== name); + return ok(); + } + return this.saveHost(body, name); + } + return null; + } + + private saveHost(body: unknown, previous: string | null): Reply { + if (!isSshHost(body) || !body.name) return fail(400, "bad_request", "A host needs a name."); + const saved: SshHost = { ...body, origin: "redshell" }; + this.hosts = [...this.hosts.filter((h) => h.name !== previous && h.name !== saved.name), saved]; + return ok(saved); + } + + // Sessions + + private create(profileId: string, cwd: string): Reply { + const profile = data.profiles.find((p) => p.id === profileId); + if (!profile) return fail(400, "bad_request", "Unknown profile."); + if (!profile.available) { + return fail(400, "bad_request", `\`${profile.description}\` was not found on the server.`); + } + const folder = cwd ? data.folder(cwd) : data.HOME; + if (profile.kind !== "ssh" && !data.folderTree[folder]) return fail(400, "bad_request", `${folder} is not a folder`); + const id = `s${this.nextId++}`; + const now = Date.now(); + const isAgent = profile.kind === "agent"; + const info: SessionInfo = { + id, + name: null, + title: profile.kind === "ssh" ? profile.name : (folder.split("/").pop() ?? folder), + kind: profile.kind, + profile: profile.id, + profile_name: profile.name, + command: null, + start_cwd: profile.kind === "ssh" ? null : folder, + agent: isAgent ? profile.id.replace("agent:", "") : null, + agent_state: isAgent ? "idle" : null, + last_message: null, + cwd: profile.kind === "ssh" ? null : folder, + cols: 47, + rows: 39, + created_at: now, + active_at: now, + last_line: null, + exit: null, + pending_approvals: 0, + }; + this.sessions.set(id, info); + const [user, address] = profile.kind === "ssh" ? profile.description.split("@") : ["andy", "pi"]; + this.screens.set(id, isAgent ? claudeScreen([]) : shellScreen(user ?? "andy", profile.kind === "ssh" ? profile.name : (address ?? "pi"), profile.kind === "ssh" ? "~" : folder.replace(data.HOME, "~"), [])); + this.broadcast({ type: "session_updated", session: info }); + return ok(info); + } + + private update(id: string, fields: Partial): void { + const current = this.sessions.get(id); + if (!current) return; + const next = { ...current, ...fields }; + this.sessions.set(id, next); + this.broadcast({ type: "session_updated", session: next }); + } + + private kill(id: string): void { + this.sessions.delete(id); + this.approvals = this.approvals.filter((a) => a.session !== id); + for (const socket of this.sockets) { + for (const [channel, session] of socket.channels) { + if (session === id) { + socket.channels.delete(channel); + socket.deliver({ type: "detached", channel }); + } + } + } + this.broadcast({ type: "session_removed", id }); + } + + private answer(id: string, answer: ApprovalAnswer, by: string | null): void { + const approval = this.approvals.find((a) => a.id === id); + if (!approval) return; + this.approvals = this.approvals.filter((a) => a.id !== id); + const outcomes = { allow: "allowed", allow_always: "allowed", deny: "denied", terminal: "terminal" } as const satisfies Record< + ApprovalDecision, + string + >; + this.broadcast({ type: "approval_resolved", id, session: approval.session, outcome: outcomes[answer.decision], answered_by: by }); + const remaining = this.approvals.filter((a) => a.session === approval.session).length; + const screen = this.screens.get(approval.session); + const allowed = answer.decision === "allow" || answer.decision === "allow_always"; + if (screen?.kind === "agent" && answer.decision !== "terminal") { + screen.transcript.splice(-1, 1, ...result(allowed ? "Done" : dim("Denied by user"))); + if (allowed) screen.transcript.push("", said("Running the tests again.")); + this.redraw(approval.session); + } + this.update(approval.session, { + pending_approvals: remaining, + agent_state: remaining > 0 ? "needs_approval" : "working", + active_at: Date.now(), + last_line: allowed ? "Running the tests again." : "Denied by user", + }); + } + + private request(approval: Approval): void { + this.approvals = [...this.approvals, approval]; + this.broadcast({ type: "approval_requested", approval }); + this.broadcast({ + type: "event", + event: { session: approval.session, kind: "approval_requested", title: null, body: approval.summary, at: Date.now() }, + }); + const session = this.sessions.get(approval.session); + if (session) { + this.update(session.id, { + agent_state: "needs_approval", + pending_approvals: session.pending_approvals + 1, + active_at: Date.now(), + }); + } + } + + /** Moves every working agent one step along, like an agent reading and editing files. */ + private work(): void { + for (const session of this.sessions.values()) { + const screen = this.screens.get(session.id); + if (session.agent_state !== "working" || screen?.kind !== "agent") continue; + const step = WORK[this.workStep % WORK.length] ?? ""; + const [verb = "", ...rest] = step.split(" "); + screen.transcript.push(tool(verb, rest.join(" "))); + if (screen.transcript.length > 60) screen.transcript.splice(3, 2); + this.redraw(session.id); + this.update(session.id, { last_line: step, active_at: Date.now() }); + } + this.workStep += 1; + } + + // WebSocket + + receive(socket: MockSocket, message: ClientMessage): void { + switch (message.type) { + case "subscribe": + this.subscribed(socket); + break; + case "attach": { + const session = this.sessions.get(message.session); + const screen = this.screens.get(message.session); + if (!session || !screen) { + socket.deliver({ type: "error", code: "not_found", message: "No such session." }); + return; + } + const channel = this.nextChannel++; + socket.channels.set(channel, session.id); + this.sessions.set(session.id, { ...session, cols: message.cols, rows: message.rows }); + socket.deliver({ + type: "attached", + channel, + session, + snapshot: { cols: message.cols, rows: message.rows, data: render(screen, message.cols, message.rows), modes: MODES }, + }); + if (this.scenario === "remote-answer" && session.id === "aurora") { + setTimeout(() => { + const first = this.approvals.find((a) => a.session === "aurora"); + if (first) this.answer(first.id, { decision: "allow" }, "MacBook Pro"); + }, 4000); + } + break; + } + case "detach": + socket.channels.delete(message.channel); + socket.deliver({ type: "detached", channel: message.channel }); + break; + case "resize": { + const id = socket.channels.get(message.channel); + if (id) { + const session = this.sessions.get(id); + if (session) this.sessions.set(id, { ...session, cols: message.cols, rows: message.rows }); + this.redraw(id); + } + break; + } + case "input": { + const id = socket.channels.get(message.channel); + if (id) this.type(id, message.data); + break; + } + case "rename": + this.update(message.session, { name: message.name }); + break; + case "approve": + this.answer(message.approval, { decision: message.decision }, "browser"); + break; + } + } + + private subscribed(socket: MockSocket): void { + socket.deliver({ type: "hello", protocol_version: PROTOCOL_VERSION, user: USER }); + socket.deliver({ type: "sessions", sessions: [...this.sessions.values()] }); + socket.deliver({ type: "approvals", approvals: this.approvals }); + if (this.scenario === "reconnecting" && this.socketsOpened === 1) { + setTimeout(() => { + this.refuseSockets = true; + socket.close(1006); + }, 1500); + } + if (this.scenario === "arrival" && this.socketsOpened === 1) { + setTimeout(() => { + this.request({ + id: "ap-check", + session: "aurora-web", + tool: "Bash", + input: { command: "npm run check" }, + summary: "npm run check", + description: "Type-check the Svelte project", + permission_suggestions: [{ type: "addRules", rules: [{ toolName: "Bash", ruleContent: "npm run check:*" }] }], + created_at: Date.now(), + expires_at: Date.now() + 600_000, + }); + }, 2500); + } + } + + /** Input from a client: a shell echoes and runs lines; an agent edits its input box. */ + private type(id: string, input: string): void { + const screen = this.screens.get(id); + if (!screen) return; + // Escape sequences (arrows, Shift+Tab) move nothing in the fake. + // eslint-disable-next-line no-control-regex -- stripping escape sequences is the point + const keys = input.replace(/\x1b\[[0-9;]*[A-Za-z~]|\x1b./g, ""); + if (screen.kind === "shell") { + this.typeShell(id, screen, keys); + return; + } + for (const key of keys) { + if (key === "\r") { + if (!screen.input) continue; + screen.transcript.push("", asked(screen.input)); + screen.input = ""; + this.update(id, { agent_state: "working", active_at: Date.now() }); + } else if (key === "\x7f") { + screen.input = screen.input.slice(0, -1); + } else if (key >= " ") { + screen.input += key; + } + } + this.redraw(id); + } + + private typeShell(id: string, screen: Extract, keys: string): void { + let echo = ""; + for (const key of keys) { + if (key === "\r") { + const command = screen.input.trim(); + const output = command === "" ? "" : command === "ls" ? "README.md package.json src tests\r\n" : `zsh: command not found: ${command.split(" ")[0] ?? ""}\r\n`; + echo += `\r\n${output}${screen.prompt}`; + screen.text += screen.input + `\r\n${output}${screen.prompt}`; + screen.input = ""; + if (command) this.update(id, { last_line: command, active_at: Date.now() }); + } else if (key === "\x7f") { + if (screen.input) { + screen.input = screen.input.slice(0, -1); + echo += "\b \b"; + } + } else if (key >= " ") { + screen.input += key; + echo += key; + } + } + this.output(id, echo); + } + + private redraw(id: string): void { + const screen = this.screens.get(id); + if (screen?.kind !== "agent") return; + for (const socket of this.sockets) { + for (const [channel, session] of socket.channels) { + if (session !== id) continue; + const info = this.sessions.get(id); + socket.deliverOutput(channel, render(screen, info?.cols ?? 47, info?.rows ?? 39)); + } + } + } + + private output(id: string, output: string): void { + if (!output) return; + for (const socket of this.sockets) { + for (const [channel, session] of socket.channels) if (session === id) socket.deliverOutput(channel, output); + } + } + + private broadcast(message: ServerMessage): void { + for (const socket of this.sockets) socket.deliver(message); + } +} + +export function createMockTransport(scenario: string): Transport { + const backend = new MockBackend(scenario); + return { + fetch: (input, init) => backend.fetch(input, init), + createSocket: () => backend.connect(), + socketUrl: "mock://pi/api/ws", + host: "pi.tail9c2.ts.net", + webauthn: mockWebAuthn, + webPush: mockWebPush(scenario === "push-on"), + }; +} diff --git a/web/src/api/mock/platform.ts b/web/src/api/mock/platform.ts new file mode 100644 index 0000000..9f7cb5b --- /dev/null +++ b/web/src/api/mock/platform.ts @@ -0,0 +1,51 @@ +// The browser's own side of the mock: a passkey sheet that always succeeds, and a push service +// that subscribes at once. The backend (./index.ts) keeps what the server would. + +import type { AuthenticationResponseJSON, RegistrationResponseJSON } from "@simplewebauthn/browser"; +import type { WebAuthn, WebPush } from "../client"; + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** The endpoint this browser has with its push service, in the scenarios where it is subscribed. */ +export const MOCK_ENDPOINT = "https://web.push.apple.com/mock-this-device"; + +const fakeCredential = { + id: "bW9jay1jcmVkZW50aWFs", + rawId: "bW9jay1jcmVkZW50aWFs", + type: "public-key", + clientExtensionResults: {}, +} as const; + +export const mockWebAuthn: WebAuthn = { + authenticate: async (): Promise => { + await delay(900); + return { + ...fakeCredential, + response: { clientDataJSON: "e30", authenticatorData: "AA", signature: "AA", userHandle: "dXNlci0x" }, + }; + }, + register: async (): Promise => { + await delay(900); + return { ...fakeCredential, response: { clientDataJSON: "e30", attestationObject: "AA", transports: ["internal"] } }; + }, + supportsAutofill: () => Promise.resolve(false), + cancel: () => undefined, +}; + +/** Push that is allowed at once; `subscribed` starts it with a subscription. */ +export function mockWebPush(subscribed: boolean): WebPush { + let endpoint = subscribed ? MOCK_ENDPOINT : null; + return { + blocker: () => null, + endpoint: () => Promise.resolve(endpoint), + allow: () => Promise.resolve(true), + subscribe: () => { + endpoint = MOCK_ENDPOINT; + return Promise.resolve({ endpoint, keys: { p256dh: "BMock", auth: "mock" } }); + }, + unsubscribe: () => { + endpoint = null; + return Promise.resolve(); + }, + }; +} diff --git a/web/src/api/mock/screens.ts b/web/src/api/mock/screens.ts new file mode 100644 index 0000000..e6539f7 --- /dev/null +++ b/web/src/api/mock/screens.ts @@ -0,0 +1,116 @@ +// Terminal screens of the mock backend, rendered as ANSI for the size a client attaches with. +// Agents redraw the whole screen with their input box at the bottom, like Claude Code; +// shells append, like a shell. + +const ESC = "\x1b["; +export const sgr = (codes: string, text: string) => `${ESC}${codes}m${text}${ESC}0m`; +export const dim = (text: string) => sgr("2", text); +export const bold = (text: string) => sgr("1", text); + +// eslint-disable-next-line no-control-regex -- matching escape sequences is the point +const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g; +const visibleLength = (line: string) => Array.from(line.replace(ANSI, "")).length; + +export interface AgentScreen { + kind: "agent"; + accent: string; + transcript: string[]; + input: string; + footer: string; +} + +export interface ShellScreen { + kind: "shell"; + /** Everything printed so far, including the prompt of the current line. */ + text: string; + prompt: string; + input: string; +} + +export type Screen = AgentScreen | ShellScreen; + +function rowsOf(line: string, cols: number): number { + return Math.max(1, Math.ceil(visibleLength(line) / cols)); +} + +function clip(text: string, width: number): string { + const chars = Array.from(text); + return chars.length <= width ? text : `${chars.slice(0, Math.max(0, width - 1)).join("")}…`; +} + +/** The whole screen: transcript, padding, then the input box and footer on the last four rows. */ +function renderAgent(screen: AgentScreen, cols: number, rows: number): string { + const inner = Math.max(4, cols - 2); + const field = clip(screen.input, inner - 3); + const box = [ + dim(`╭${"─".repeat(inner)}╮`), + `${dim("│")} ${sgr(screen.accent, ">")} ${field}${" ".repeat(Math.max(0, inner - 3 - visibleLength(field)))}${dim("│")}`, + dim(`╰${"─".repeat(inner)}╯`), + dim(clip(` ${screen.footer}`, cols)), + ]; + const used = screen.transcript.reduce((sum, line) => sum + rowsOf(line, cols), 0); + const padding = Math.max(0, rows - box.length - used); + const lines = [...screen.transcript, ...Array(padding).fill(""), ...box]; + const cursorRow = rows - 2; + const cursorCol = 5 + visibleLength(field); + return `${ESC}H${ESC}2J${lines.join("\r\n")}${ESC}${cursorRow};${cursorCol}H`; +} + +export function render(screen: Screen, cols: number, rows: number): string { + return screen.kind === "agent" ? renderAgent(screen, cols, rows) : screen.text + screen.input; +} + +const CLAUDE = "38;5;209"; +const CODEX = "38;5;250"; +const OPENCODE = "38;5;214"; + +export function claudeScreen(transcript: string[]): AgentScreen { + return { + kind: "agent", + accent: CLAUDE, + input: "", + footer: "⏵⏵ accept edits on (shift+tab to cycle)", + transcript: [ + `${sgr(CLAUDE, "✻")} Welcome to ${bold("Claude Code")}!`, + dim(" /help for help, /status for your setup"), + "", + ...transcript, + ], + }; +} + +export function codexScreen(transcript: string[]): AgentScreen { + return { + kind: "agent", + accent: CODEX, + input: "", + footer: "⏎ send ⌃J newline ⌃C quit", + transcript: [`${bold(">_ OpenAI Codex")} ${dim("(v0.63.0)")}`, dim(" model: gpt-5-codex high"), "", ...transcript], + }; +} + +export function opencodeScreen(transcript: string[]): AgentScreen { + return { + kind: "agent", + accent: OPENCODE, + input: "", + footer: "build claude-sonnet-4 ctrl+p commands", + transcript: [`${sgr(OPENCODE, "opencode")} ${dim("v1.0.12")}`, "", ...transcript], + }; +} + +export const tool = (name: string, arg: string) => `${sgr("38;5;114", "⏺")} ${bold(name)}(${arg})`; +export const said = (text: string) => `${sgr("37", "⏺")} ${text}`; +export const result = (first: string, ...rest: string[]) => [ + ` ${dim("⎿")} ${first}`, + ...rest.map((line) => ` ${line}`), +]; +export const asked = (text: string) => `${dim(">")} ${text}`; +export const pass = (file: string, tests: number) => `${sgr("30;42", " PASS ")} ${file} ${dim(`(${tests} tests)`)}`; +export const fail = (file: string) => `${sgr("30;41", " FAIL ")} ${file}`; + +export function shellScreen(user: string, host: string, cwd: string, history: [string, string[]][]): ShellScreen { + const prompt = `${sgr("1;32", `${user}@${host}`)}:${sgr("1;34", cwd)}$ `; + const text = history.map(([command, output]) => [prompt + command, ...output].join("\r\n")).join("\r\n"); + return { kind: "shell", prompt, input: "", text: (text ? `${text}\r\n` : "") + prompt }; +} diff --git a/web/src/api/mock/socket.ts b/web/src/api/mock/socket.ts new file mode 100644 index 0000000..8513a12 --- /dev/null +++ b/web/src/api/mock/socket.ts @@ -0,0 +1,57 @@ +import { frame } from "../framing"; +import type { SocketLike } from "../socket"; +import type { ClientMessage, ServerMessage } from "../types"; + +/** The mock server's end of a socket. */ +export interface SocketHost { + receive(socket: MockSocket, message: ClientMessage): void; + disconnect(socket: MockSocket): void; +} + +const encoder = new TextEncoder(); + +/** A WebSocket to the mock backend. Messages are delivered on later tasks, in order, like a real one. */ +export class MockSocket implements SocketLike { + binaryType: BinaryType = "blob"; + onopen: ((event: Event) => void) | null = null; + onclose: ((event: CloseEvent) => void) | null = null; + onmessage: ((event: MessageEvent) => void) | null = null; + onerror: ((event: Event) => void) | null = null; + /** channel → session id */ + readonly channels = new Map(); + private closed = false; + private readonly host: SocketHost; + + constructor(host: SocketHost, refuse: boolean) { + this.host = host; + setTimeout(() => { + if (refuse) this.close(1006); + else this.onopen?.(new Event("open")); + }, 80); + } + + send(payload: string | Uint8Array): void { + if (this.closed) return; + if (typeof payload === "string") this.host.receive(this, JSON.parse(payload) as ClientMessage); + } + + close(code = 1000): void { + if (this.closed) return; + this.closed = true; + this.host.disconnect(this); + setTimeout(() => this.onclose?.(new CloseEvent("close", { code })), 0); + } + + deliver(message: ServerMessage): void { + setTimeout(() => { + if (!this.closed) this.onmessage?.(new MessageEvent("message", { data: JSON.stringify(message) })); + }, 0); + } + + deliverOutput(channel: number, output: string): void { + const bytes = frame(channel, encoder.encode(output)); + setTimeout(() => { + if (!this.closed) this.onmessage?.(new MessageEvent("message", { data: bytes.buffer })); + }, 0); + } +} diff --git a/web/src/api/queries.ts b/web/src/api/queries.ts new file mode 100644 index 0000000..a1b0f2b --- /dev/null +++ b/web/src/api/queries.ts @@ -0,0 +1,109 @@ +import { createContext, use } from "react"; +import { useQuery } from "@tanstack/react-query"; +import type { Api } from "./client"; +import { ApiRequestError } from "./http"; + +export const ApiContext = createContext(null); + +export function useApi(): Api { + const api = use(ApiContext); + if (!api) throw new Error("useApi needs an ApiContext provider"); + return api; +} + +export const keys = { + info: ["info"], + me: ["me"], + account: ["account"], + sessions: ["sessions"], + approvals: ["approvals"], + profiles: ["profiles"], + folders: (path: string) => ["folders", path], + hosts: ["hosts"], + passkeys: ["passkeys"], + devices: ["devices"], + browsers: ["browsers"], + pairing: (code: string) => ["pairing", code], + push: ["push"], +} as const; + +/** Server info: open to everyone, needed before sign-in. */ +export function useInfo() { + const api = useApi(); + return useQuery({ queryKey: keys.info, queryFn: api.info, staleTime: 5 * 60_000 }); +} + +/** The signed-in user, or `null` when signed out. */ +export function useMe() { + const api = useApi(); + return useQuery({ + queryKey: keys.me, + queryFn: async () => { + try { + return await api.auth.me(); + } catch (error) { + if (error instanceof ApiRequestError && error.status === 401) return null; + throw error; + } + }, + staleTime: Infinity, + }); +} + +/** + * The session list; the WebSocket keeps it current (src/state/live.ts), so it never goes stale. + * A failure is shown after one retry a second later, not after the default backoff. + */ +export function useSessions() { + const api = useApi(); + return useQuery({ queryKey: keys.sessions, queryFn: api.sessions.list, staleTime: Infinity, retry: 1, retryDelay: 1000 }); +} + +/** Approvals waiting for an answer, kept current by the WebSocket like the sessions. */ +export function useApprovals() { + const api = useApi(); + return useQuery({ queryKey: keys.approvals, queryFn: api.approvals.list, staleTime: Infinity }); +} + +/** The account: passkey-only sign-in, how many passkeys, and whether the server offers them. */ +export function useAccount() { + const api = useApi(); + return useQuery({ queryKey: keys.account, queryFn: api.account.get }); +} + +export function usePasskeys() { + const api = useApi(); + return useQuery({ queryKey: keys.passkeys, queryFn: api.passkeys.list }); +} + +export function useDevices() { + const api = useApi(); + return useQuery({ queryKey: keys.devices, queryFn: api.account.devices }); +} + +export function useBrowsers() { + const api = useApi(); + return useQuery({ queryKey: keys.browsers, queryFn: api.account.browsers }); +} + +export function useProfiles() { + const api = useApi(); + return useQuery({ queryKey: keys.profiles, queryFn: api.profiles, staleTime: 60_000 }); +} + +/** The subfolders of a folder on the server: absolute, or `~` and below (the server user's home). */ +export function useFolders(path: string) { + const api = useApi(); + return useQuery({ + queryKey: keys.folders(path), + queryFn: () => api.folders(path), + enabled: path.startsWith("/") || path === "~" || path.startsWith("~/"), + staleTime: 30_000, + }); +} + +/** The server's `[[ssh.hosts]]`, then the hosts only in its `~/.ssh/config`. */ +export function useHosts() { + const api = useApi(); + return useQuery({ queryKey: keys.hosts, queryFn: api.hosts.list }); +} diff --git a/web/src/api/socket.test.ts b/web/src/api/socket.test.ts new file mode 100644 index 0000000..25d9046 --- /dev/null +++ b/web/src/api/socket.test.ts @@ -0,0 +1,249 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { frame, unframe } from "./framing"; +import { backoffDelay, CLOSE_UNAUTHORIZED, Connection, type SocketLike, type TerminalSink } from "./socket"; +import type { ClientMessage, ServerMessage, SessionInfo, Snapshot } from "./types"; + +/** A socket the test drives: it records what the client sends and plays the server. */ +class FakeSocket implements SocketLike { + binaryType: BinaryType = "blob"; + onopen: ((event: Event) => void) | null = null; + onclose: ((event: CloseEvent) => void) | null = null; + onmessage: ((event: MessageEvent) => void) | null = null; + onerror: ((event: Event) => void) | null = null; + readonly sent: (ClientMessage | Uint8Array)[] = []; + + send(data: string | Uint8Array): void { + this.sent.push(typeof data === "string" ? (JSON.parse(data) as ClientMessage) : data); + } + + close(): void { + this.drop(1000); + } + + open(): void { + this.onopen?.(new Event("open")); + } + + receive(message: ServerMessage): void { + this.onmessage?.(new MessageEvent("message", { data: JSON.stringify(message) })); + } + + receiveBytes(channel: number, text: string): void { + this.onmessage?.(new MessageEvent("message", { data: frame(channel, new TextEncoder().encode(text)).buffer })); + } + + drop(code: number): void { + this.onclose?.(new CloseEvent("close", { code })); + } + + messages(): ClientMessage[] { + return this.sent.filter((m): m is ClientMessage => !(m instanceof Uint8Array)); + } +} + +const SNAPSHOT: Snapshot = { + cols: 80, + rows: 24, + data: "$ ", + modes: { + alt_screen: false, + app_cursor: false, + app_keypad: false, + bracketed_paste: true, + mouse_tracking: null, + mouse_encoding: "normal", + focus_reporting: false, + cursor_visible: true, + cursor_shape: "block", + cursor_blinking: false, + title: null, + }, +}; + +const session = (id: string) => ({ id }) as SessionInfo; + +const hello: ServerMessage = { type: "hello", protocol_version: 1, user: { id: 1, username: "andy", created_at: 0 } }; + +function sink() { + return { + snapshot: vi.fn<(snapshot: Snapshot) => void>(), + output: vi.fn<(bytes: Uint8Array) => void>(), + resized: vi.fn<(cols: number, rows: number) => void>(), + detached: vi.fn<() => void>(), + } satisfies TerminalSink; +} + +describe("framing", () => { + it("puts a big-endian channel before the bytes, like the server", () => { + const framed = frame(0x0102, new TextEncoder().encode("hi")); + expect([...framed]).toEqual([1, 2, 104, 105]); + const decoded = unframe(framed.buffer); + expect(decoded?.channel).toBe(0x0102); + expect(new TextDecoder().decode(decoded?.bytes)).toBe("hi"); + }); + + it("rejects frames too short for a channel", () => { + expect(unframe(new Uint8Array([7]))).toBeNull(); + expect(unframe(new Uint8Array([0, 7]))?.bytes.length).toBe(0); + }); +}); + +describe("backoffDelay", () => { + it("doubles from 500ms up to 10s, with jitter in the upper half", () => { + expect(backoffDelay(0, () => 0)).toBe(250); + expect(backoffDelay(0, () => 1)).toBe(500); + expect(backoffDelay(3, () => 1)).toBe(4000); + expect(backoffDelay(10, () => 1)).toBe(10_000); + }); +}); + +describe("Connection", () => { + let sockets: FakeSocket[]; + let connection: Connection; + const latest = () => sockets[sockets.length - 1] ?? new FakeSocket(); + + beforeEach(() => { + vi.useFakeTimers(); + sockets = []; + connection = new Connection( + "ws://test/api/ws", + () => { + const socket = new FakeSocket(); + sockets.push(socket); + return socket; + }, + () => 1, + ); + }); + + afterEach(() => { + connection.stop(); + vi.useRealTimers(); + }); + + it("subscribes on open and is open once the server says hello", () => { + connection.start(); + expect(connection.status).toBe("connecting"); + latest().open(); + expect(latest().messages()).toEqual([{ type: "subscribe", sessions: true, events: true }]); + latest().receive(hello); + expect(connection.status).toBe("open"); + }); + + it("routes binary frames to the attached session and sends input on its channel", () => { + connection.start(); + latest().open(); + latest().receive(hello); + const terminal = sink(); + const attachment = connection.attach("s1", 47, 39, terminal); + expect(latest().messages()).toContainEqual({ type: "attach", session: "s1", cols: 47, rows: 39 }); + + latest().receive({ type: "attached", channel: 3, session: session("s1"), snapshot: { ...SNAPSHOT, cols: 47, rows: 39 } }); + expect(terminal.snapshot).toHaveBeenCalledOnce(); + latest().receiveBytes(3, "out"); + latest().receiveBytes(9, "someone else's"); + expect(terminal.output).toHaveBeenCalledOnce(); + + attachment.input("ls\r"); + expect(latest().messages()).toContainEqual({ type: "input", channel: 3, data: "ls\r" }); + }); + + it("asks for its own size when the session was another size at attach", () => { + connection.start(); + latest().open(); + latest().receive(hello); + connection.attach("s1", 47, 39, sink()); + latest().receive({ type: "attached", channel: 1, session: session("s1"), snapshot: SNAPSHOT }); + expect(latest().messages()).toContainEqual({ type: "resize", channel: 1, cols: 47, rows: 39 }); + }); + + it("reconnects with backoff, then resubscribes and re-attaches with a fresh snapshot", () => { + connection.start(); + latest().open(); + latest().receive(hello); + const terminal = sink(); + const attachment = connection.attach("s1", 47, 39, terminal); + latest().receive({ type: "attached", channel: 1, session: session("s1"), snapshot: SNAPSHOT }); + + latest().drop(1006); + expect(connection.status).toBe("reconnecting"); + attachment.input("lost"); + expect(sockets).toHaveLength(1); + + vi.advanceTimersByTime(500); + expect(sockets).toHaveLength(2); + latest().open(); + latest().receive(hello); + expect(connection.status).toBe("open"); + expect(latest().messages()).toEqual([ + { type: "subscribe", sessions: true, events: true }, + { type: "attach", session: "s1", cols: 47, rows: 39 }, + ]); + + latest().receive({ type: "attached", channel: 5, session: session("s1"), snapshot: { ...SNAPSHOT, cols: 47, rows: 39 } }); + expect(terminal.snapshot).toHaveBeenCalledTimes(2); + attachment.input("back"); + expect(latest().messages()).toContainEqual({ type: "input", channel: 5, data: "back" }); + }); + + it("backs off longer after each failed attempt and resets after a hello", () => { + connection.start(); + latest().drop(1006); + vi.advanceTimersByTime(500); + expect(sockets).toHaveLength(2); + latest().drop(1006); + vi.advanceTimersByTime(999); + expect(sockets).toHaveLength(2); + vi.advanceTimersByTime(1); + expect(sockets).toHaveLength(3); + latest().open(); + latest().receive(hello); + latest().drop(1006); + vi.advanceTimersByTime(500); + expect(sockets).toHaveLength(4); + }); + + it("retries at once when asked, instead of waiting out the backoff", () => { + connection.start(); + latest().drop(1006); + connection.retryNow(); + expect(sockets).toHaveLength(2); + }); + + it("stops retrying when the server closes for a revoked sign-in", () => { + connection.start(); + latest().open(); + latest().receive(hello); + latest().drop(CLOSE_UNAUTHORIZED); + expect(connection.status).toBe("unauthorized"); + vi.advanceTimersByTime(60_000); + expect(sockets).toHaveLength(1); + }); + + it("tells the terminal when its session is killed, and detaches when asked", () => { + connection.start(); + latest().open(); + latest().receive(hello); + const terminal = sink(); + const attachment = connection.attach("s1", 47, 39, terminal); + latest().receive({ type: "attached", channel: 2, session: session("s1"), snapshot: SNAPSHOT }); + latest().receive({ type: "detached", channel: 2 }); + expect(terminal.detached).toHaveBeenCalledOnce(); + + const other = connection.attach("s2", 47, 39, sink()); + latest().receive({ type: "attached", channel: 4, session: session("s2"), snapshot: SNAPSHOT }); + other.detach(); + expect(latest().messages()).toContainEqual({ type: "detach", channel: 4 }); + attachment.input("nothing"); + expect(latest().messages()).not.toContainEqual({ type: "input", channel: 2, data: "nothing" }); + }); + + it("detaches an attach that was cancelled while in flight", () => { + connection.start(); + latest().open(); + latest().receive(hello); + connection.attach("s1", 47, 39, sink()).detach(); + latest().receive({ type: "attached", channel: 7, session: session("s1"), snapshot: SNAPSHOT }); + expect(latest().messages()).toContainEqual({ type: "detach", channel: 7 }); + }); +}); diff --git a/web/src/api/socket.ts b/web/src/api/socket.ts new file mode 100644 index 0000000..9ad9915 --- /dev/null +++ b/web/src/api/socket.ts @@ -0,0 +1,259 @@ +import { frame, unframe } from "./framing"; +import type { ClientMessage, ServerMessage, Snapshot } from "./types"; + +/** The part of `WebSocket` the connection uses, so the mock backend can stand in for it. */ +export interface SocketLike { + binaryType: BinaryType; + send(data: string | Uint8Array): void; + close(code?: number): void; + onopen: ((event: Event) => void) | null; + onclose: ((event: CloseEvent) => void) | null; + onmessage: ((event: MessageEvent) => void) | null; + onerror: ((event: Event) => void) | null; +} + +export type SocketFactory = (url: string) => SocketLike; + +/** + * `connecting`: the first attempt. `open`: the server said hello. `reconnecting`: the socket + * dropped and a retry is scheduled or running. `unauthorized`: the server closed it with 4001, + * so retrying is pointless until the user signs in again. `closed`: stopped on purpose. + */ +export type ConnectionStatus = "connecting" | "open" | "reconnecting" | "unauthorized" | "closed"; + +/** The close code the server uses when the cookie or token was revoked. */ +export const CLOSE_UNAUTHORIZED = 4001; + +/** Where an attached session's terminal output goes. PTY bytes never pass through React. */ +export interface TerminalSink { + /** Reset the terminal to `cols` × `rows` and redraw it from the snapshot. */ + snapshot(snapshot: Snapshot): void; + output(bytes: Uint8Array): void; + /** The session took another size (another client typed). */ + resized(cols: number, rows: number): void; + /** The server closed the channel: the session was killed. */ + detached(): void; +} + +/** A session attached to this connection. It survives reconnects: the connection re-attaches it. */ +export interface Attachment { + input(data: string): void; + inputBytes(bytes: Uint8Array): void; + resize(cols: number, rows: number): void; + detach(): void; +} + +interface AttachmentState { + session: string; + cols: number; + rows: number; + channel: number | null; + sink: TerminalSink; +} + +const MAX_DELAY_MS = 10_000; +const BASE_DELAY_MS = 500; + +/** Exponential backoff with jitter: 250–500ms, 500–1000ms, … up to 5–10s. */ +export function backoffDelay(attempt: number, random: () => number = Math.random): number { + const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt); + return Math.round(ceiling / 2 + (random() * ceiling) / 2); +} + +/** + * The one WebSocket of the app (`/api/ws`). It subscribes to the session list and agent events, + * multiplexes attached sessions over binary channels, and reconnects with backoff. After every + * reconnect it subscribes again (the server answers with the full session and approval lists) + * and re-attaches every attached session (each answers with a fresh snapshot). + */ +export class Connection { + status: ConnectionStatus = "closed"; + + private socket: SocketLike | null = null; + private attempt = 0; + private retryTimer: ReturnType | undefined; + private readonly attachments = new Map(); + private readonly channels = new Map(); + private readonly messageListeners = new Set<(message: ServerMessage) => void>(); + private readonly statusListeners = new Set<(status: ConnectionStatus) => void>(); + private readonly url: string; + private readonly createSocket: SocketFactory; + private readonly random: () => number; + + constructor(url: string, createSocket: SocketFactory, random: () => number = Math.random) { + this.url = url; + this.createSocket = createSocket; + this.random = random; + } + + start(): void { + if (this.status !== "closed" && this.status !== "unauthorized") return; + this.attempt = 0; + this.open("connecting"); + } + + stop(): void { + clearTimeout(this.retryTimer); + const socket = this.socket; + this.socket = null; + this.channels.clear(); + socket?.close(1000); + this.setStatus("closed"); + } + + /** Retry at once instead of waiting out the backoff: the network came back, or the app did. */ + retryNow(): void { + if (this.status !== "reconnecting" || this.socket) return; + clearTimeout(this.retryTimer); + this.open("reconnecting"); + } + + onMessage(listener: (message: ServerMessage) => void): () => void { + this.messageListeners.add(listener); + return () => this.messageListeners.delete(listener); + } + + onStatus(listener: (status: ConnectionStatus) => void): () => void { + this.statusListeners.add(listener); + return () => this.statusListeners.delete(listener); + } + + send(message: ClientMessage): boolean { + if (this.status !== "open" || !this.socket) return false; + this.socket.send(JSON.stringify(message)); + return true; + } + + /** Streams `session` into `sink` at `cols` × `rows` until `detach()`. */ + attach(session: string, cols: number, rows: number, sink: TerminalSink): Attachment { + this.attachments.get(session)?.sink.detached(); + const state: AttachmentState = { session, cols, rows, channel: null, sink }; + this.attachments.set(session, state); + this.send({ type: "attach", session, cols, rows }); + + return { + input: (data) => { + if (state.channel !== null) this.send({ type: "input", channel: state.channel, data }); + }, + inputBytes: (bytes) => { + if (state.channel !== null && this.status === "open") this.socket?.send(frame(state.channel, bytes)); + }, + resize: (nextCols, nextRows) => { + if (nextCols === state.cols && nextRows === state.rows) return; + state.cols = nextCols; + state.rows = nextRows; + if (state.channel !== null) { + this.send({ type: "resize", channel: state.channel, cols: nextCols, rows: nextRows }); + } + }, + detach: () => { + if (this.attachments.get(session) !== state) return; + this.attachments.delete(session); + if (state.channel !== null) { + this.channels.delete(state.channel); + this.send({ type: "detach", channel: state.channel }); + state.channel = null; + } + }, + }; + } + + private open(status: "connecting" | "reconnecting"): void { + this.setStatus(status); + const socket = this.createSocket(this.url); + socket.binaryType = "arraybuffer"; + this.socket = socket; + socket.onopen = () => { + socket.send(JSON.stringify({ type: "subscribe", sessions: true, events: true } satisfies ClientMessage)); + }; + socket.onmessage = (event) => { + if (socket === this.socket) this.receive(event.data); + }; + socket.onclose = (event) => { + this.closed(socket, event.code); + }; + } + + private receive(data: unknown): void { + if (data instanceof ArrayBuffer) { + const decoded = unframe(data); + if (decoded) this.channels.get(decoded.channel)?.sink.output(decoded.bytes); + return; + } + if (typeof data !== "string") return; + // Messages come from our own server, generated from the same protocol crate. + const message = JSON.parse(data) as ServerMessage; + this.route(message); + for (const listener of this.messageListeners) listener(message); + } + + private route(message: ServerMessage): void { + switch (message.type) { + case "hello": + this.attempt = 0; + this.setStatus("open"); + for (const state of this.attachments.values()) { + state.channel = null; + this.send({ type: "attach", session: state.session, cols: state.cols, rows: state.rows }); + } + break; + case "attached": { + const state = this.attachments.get(message.session.id); + if (!state) { + // Detached while the attach was in flight. + this.send({ type: "detach", channel: message.channel }); + return; + } + state.channel = message.channel; + this.channels.set(message.channel, state); + state.sink.snapshot(message.snapshot); + // The client's size may have changed while the attach was in flight. + if (state.cols !== message.snapshot.cols || state.rows !== message.snapshot.rows) { + this.send({ type: "resize", channel: message.channel, cols: state.cols, rows: state.rows }); + } + break; + } + case "snapshot": + this.channels.get(message.channel)?.sink.snapshot(message.snapshot); + break; + case "resized": + this.channels.get(message.channel)?.sink.resized(message.cols, message.rows); + break; + case "detached": { + const state = this.channels.get(message.channel); + this.channels.delete(message.channel); + if (state && this.attachments.get(state.session) === state) { + state.channel = null; + this.attachments.delete(state.session); + state.sink.detached(); + } + break; + } + default: + break; + } + } + + private closed(socket: SocketLike, code: number): void { + if (socket !== this.socket) return; + this.socket = null; + this.channels.clear(); + for (const state of this.attachments.values()) state.channel = null; + if (code === CLOSE_UNAUTHORIZED) { + this.setStatus("unauthorized"); + return; + } + this.setStatus("reconnecting"); + const delay = backoffDelay(this.attempt, this.random); + this.attempt += 1; + this.retryTimer = setTimeout(() => { + this.open("reconnecting"); + }, delay); + } + + private setStatus(status: ConnectionStatus): void { + if (status === this.status) return; + this.status = status; + for (const listener of this.statusListeners) listener(status); + } +} diff --git a/web/src/api/types.ts b/web/src/api/types.ts new file mode 100644 index 0000000..81591fb --- /dev/null +++ b/web/src/api/types.ts @@ -0,0 +1,5 @@ +// The wire types of redshell-server, generated from crates/redshell-protocol into src/protocol/ +// (never edit those files). + +export type * from "../protocol"; +export type { JsonValue } from "../protocol/serde_json/JsonValue"; diff --git a/web/src/app/AppLayout.tsx b/web/src/app/AppLayout.tsx new file mode 100644 index 0000000..0dab9e8 --- /dev/null +++ b/web/src/app/AppLayout.tsx @@ -0,0 +1,110 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { lazy, Suspense, useEffect, ViewTransition } from "react"; +import { matchPath, Navigate, Outlet, useLocation, useMatch } from "react-router"; +import { Terminal } from "lucide-react"; +import { keys, useApi, useMe } from "../api/queries"; +import { Button } from "../components/Button"; +import { EmptyState } from "../components/EmptyState"; +import { BannerHost, UpdateToast } from "../components/Overlays"; +import { Unreachable } from "../features/auth/Unreachable"; +import { Inbox, Sidebar } from "../features/inbox/Inbox"; +import { useWide, WIDE_QUERY } from "../lib/hooks"; +import { NAV_BACK, NAV_FORWARD } from "../lib/nav"; +import { useAppBadge } from "../pwa/badge"; +import { bindConnection } from "../state/connection"; +import { bindLive } from "../state/live"; +import { useUi } from "../state/ui"; + +const NewSessionSheet = lazy(() => import("../features/new-session/NewSessionSheet")); + +/** + * A banner is for attention the screen doesn't already show: not on the inbox, not in the wide + * layout (its sidebar is the inbox, always on screen), and not in the session itself. + */ +function wantsBanner(sessionId: string): boolean { + const path = window.location.pathname; + if (path === "/" || window.matchMedia(WIDE_QUERY).matches) return false; + return matchPath("/s/:id", path)?.params.id !== sessionId; +} + +/** Starts the WebSocket for a signed-in user and wires it into the stores; the one long-lived effect. */ +function useLiveConnection() { + const api = useApi(); + const client = useQueryClient(); + useEffect(() => { + const offConnection = bindConnection(api.connection); + const offLive = bindLive(api, client, wantsBanner); + const offStatus = api.connection.onStatus((status) => { + if (status === "unauthorized") client.setQueryData(keys.me, null); + }); + api.connection.start(); + return () => { + offStatus(); + offLive(); + offConnection(); + api.connection.stop(); + }; + }, [api, client]); +} + +function SignedIn() { + useLiveConnection(); + useAppBadge(); + const wide = useWide(); + const session = useMatch("/s/:id")?.params.id; + const home = useMatch("/") !== null; + const newSessionOpen = useUi((state) => state.newSessionOpen); + return ( + <> + {wide ? ( +
+ +
+ +
+
+ ) : ( + // Phone navigation slides by the type useNav gives it; anything else changes in place. + + + + )} + {newSessionOpen && ( + + + + )} + {!home && !wide && } + {home && } + + ); +} + +/** Everything behind sign-in: redirects to /signin when signed out, keeping where the user was going. */ +export function AppLayout() { + const me = useMe(); + const location = useLocation(); + if (me.isPending) return null; + if (me.isError) return void me.refetch()} />; + if (me.data === null) { + const next = location.pathname === "/" ? "" : `?next=${encodeURIComponent(location.pathname)}`; + return ; + } + return ; +} + +/** `/`: the inbox on phones; in the wide layout the sidebar is the inbox, and the pane invites a pick. */ +export function Home() { + const wide = useWide(); + const openNewSession = useUi((state) => state.setNewSessionOpen); + if (!wide) return ; + return ( +
+ } title="No session open" body="Pick a session, or start a new one."> + + +
+ ); +} diff --git a/web/src/app/router.tsx b/web/src/app/router.tsx new file mode 100644 index 0000000..7d76754 --- /dev/null +++ b/web/src/app/router.tsx @@ -0,0 +1,48 @@ +import { createBrowserRouter, Navigate } from "react-router"; +import { SignIn } from "../features/auth/SignIn"; +import { AppLayout, Home } from "./AppLayout"; + +/** + * Routes. The inbox and sign-in are in the main chunk; everything else loads on first visit, + * the terminal (xterm.js) above all. + */ +export const router = createBrowserRouter([ + { path: "/signin", element: }, + { path: "/setup", lazy: async () => ({ Component: (await import("../features/auth/Setup")).Setup }) }, + { + element: , + children: [ + { index: true, element: }, + { path: "s/:id", lazy: async () => ({ Component: (await import("../features/session/SessionView")).SessionView }) }, + { path: "pair", lazy: async () => ({ Component: (await import("../features/auth/Pair")).Pair }) }, + { + path: "settings", + lazy: async () => ({ Component: (await import("../features/settings/Settings")).Settings }), + }, + { + path: "settings/passkeys", + lazy: async () => ({ Component: (await import("../features/settings/Passkeys")).Passkeys }), + }, + { + path: "settings/password", + lazy: async () => ({ Component: (await import("../features/settings/Password")).Password }), + }, + { + path: "settings/devices", + lazy: async () => ({ Component: (await import("../features/settings/Devices")).Devices }), + }, + { + path: "settings/devices/:kind/:id", + lazy: async () => ({ Component: (await import("../features/settings/Devices")).DeviceDetail }), + }, + { + path: "settings/notifications", + lazy: async () => ({ Component: (await import("../features/settings/Notifications")).Notifications }), + }, + { path: "hosts", lazy: async () => ({ Component: (await import("../features/hosts/Hosts")).Hosts }) }, + { path: "hosts/new", lazy: async () => ({ Component: (await import("../features/hosts/HostDetail")).NewHost }) }, + { path: "hosts/:name", lazy: async () => ({ Component: (await import("../features/hosts/HostDetail")).HostDetail }) }, + ], + }, + { path: "*", element: }, +]); diff --git a/web/src/components/Button.tsx b/web/src/components/Button.tsx new file mode 100644 index 0000000..8c77724 --- /dev/null +++ b/web/src/components/Button.tsx @@ -0,0 +1,46 @@ +import type { ComponentProps, ReactNode } from "react"; +import { cx } from "../lib/platform"; +import { buttonClass, type ButtonSize, type ButtonVariant } from "./styles"; +import { Spinner } from "./Spinner"; + +type ButtonProps = ComponentProps<"button"> & { + variant?: ButtonVariant; + size?: ButtonSize; + /** A request is running: a spinner replaces the label (or the icon, with `keepLabel`), keeping the width. */ + pending?: boolean; + keepLabel?: boolean; + icon?: ReactNode; +}; + +/** Buttons of §3.1. One primary per screen or sheet. */ +export function Button({ + variant = "secondary", + size = "default", + pending = false, + keepLabel = false, + icon, + className, + children, + type = "button", + disabled, + ...props +}: ButtonProps) { + const hideLabel = pending && !keepLabel; + return ( + + ); +} diff --git a/web/src/components/Dialog.tsx b/web/src/components/Dialog.tsx new file mode 100644 index 0000000..1916840 --- /dev/null +++ b/web/src/components/Dialog.tsx @@ -0,0 +1,75 @@ +import { type ReactNode, useId } from "react"; +import { cx } from "../lib/platform"; +import { Button } from "./Button"; +import { InlineError } from "./InlineError"; +import type { ButtonVariant } from "./styles"; + +const showModal = (dialog: HTMLDialogElement | null) => { + if (dialog && !dialog.open) dialog.showModal(); +}; + +interface DialogProps { + title: string; + children?: ReactNode; + onClose: () => void; + className?: string; +} + +/** A centred dialog on the native ``: focus trap, Esc and the top layer come free. */ +export function Dialog({ title, children, onClose, className }: DialogProps) { + const titleId = useId(); + return ( + { + event.preventDefault(); + onClose(); + }} + onClick={(event) => { + if (event.target === event.currentTarget) onClose(); + }} + className={cx( + "m-auto w-[calc(100%-2rem)] max-w-[22rem] animate-[dialog-in_var(--dur-base)_var(--ease-out)_both] rounded-xl border border-border bg-popover p-0 text-foreground shadow-dialog", + "backdrop:bg-(--scrim-dialog)", + className, + )} + > +
+

+ {title} +

+ {children} +
+
+ ); +} + +interface ConfirmProps { + title: string; + body?: ReactNode; + confirmLabel: string; + confirmVariant?: Extract; + pending?: boolean; + error?: string | null; + onConfirm: () => void; + onCancel: () => void; +} + +/** "Sign out of pi?" with Cancel and the action. */ +export function Confirm({ title, body, confirmLabel, confirmVariant = "destructive", pending, error, onConfirm, onCancel }: ConfirmProps) { + return ( + + {body &&

{body}

} + {error && {error}} +
+ + +
+
+ ); +} diff --git a/web/src/components/EmptyState.tsx b/web/src/components/EmptyState.tsx new file mode 100644 index 0000000..671a234 --- /dev/null +++ b/web/src/components/EmptyState.tsx @@ -0,0 +1,31 @@ +import type { ReactNode } from "react"; +import { cx } from "../lib/platform"; + +interface EmptyStateProps { + /** A Lucide glyph; it is drawn at 40px in `--muted-foreground`. */ + icon: ReactNode; + title: string; + body?: ReactNode; + /** The action (or a command block), 16px under the text. */ + children?: ReactNode; + /** `h1` when the state is the whole page, without a header of its own. */ + heading?: "h1" | "h2"; + className?: string; +} + +/** + * The one template for empty and error screens (§3.13): glyph, heading, muted body, action. + * Callers place it (centred in the page, or 18vh down a screen with a header). + */ +export function EmptyState({ icon, title, body, children, heading: Heading = "h2", className }: EmptyStateProps) { + return ( +
+ + {icon} + + {title} + {body &&

{body}

} + {children &&
{children}
} +
+ ); +} diff --git a/web/src/components/Field.tsx b/web/src/components/Field.tsx new file mode 100644 index 0000000..19da399 --- /dev/null +++ b/web/src/components/Field.tsx @@ -0,0 +1,73 @@ +import { Eye, EyeOff } from "lucide-react"; +import { type ComponentProps, type ReactNode, useId, useState } from "react"; +import { cx } from "../lib/platform"; +import { InlineError } from "./InlineError"; +import { inputClass } from "./styles"; + +type FieldProps = ComponentProps<"input"> & { + label: string; + helper?: ReactNode; + error?: ReactNode; + /** Hostnames and paths: mono, still 16px so iOS never zooms. */ + mono?: boolean; + trailing?: ReactNode; +}; + +/** A labelled input (§3.2): label above, helper or error below, linked by aria-describedby. */ +export function Field({ label, helper, error, mono = false, trailing, className, id, ...props }: FieldProps) { + const fallbackId = useId(); + const inputId = id ?? fallbackId; + const noteId = `${inputId}-note`; + const note = error ?? helper; + return ( +
+ +
+ + {trailing &&
{trailing}
} +
+ {error ? ( + {error} + ) : ( + helper && ( +

+ {helper} +

+ ) + )} +
+ ); +} + +/** A password field with the 44px eye toggle inside it. */ +export function PasswordField(props: Omit) { + const [visible, setVisible] = useState(false); + return ( + setVisible((v) => !v)} + > + {visible ? : } + + } + /> + ); +} diff --git a/web/src/components/InlineError.tsx b/web/src/components/InlineError.tsx new file mode 100644 index 0000000..d9689a6 --- /dev/null +++ b/web/src/components/InlineError.tsx @@ -0,0 +1,21 @@ +import { CircleAlert } from "lucide-react"; +import type { ReactNode } from "react"; +import { cx } from "../lib/platform"; + +interface InlineErrorProps { + children: ReactNode; + id?: string; + /** Announced as it appears: for errors that answer a tap rather than sit under a field. */ + alert?: boolean; + className?: string; +} + +/** An inline error (§3.2): a footnote in `--destructive` after a 14px `circle-alert`. */ +export function InlineError({ children, id, alert = false, className }: InlineErrorProps) { + return ( +

+ + {children} +

+ ); +} diff --git a/web/src/components/List.tsx b/web/src/components/List.tsx new file mode 100644 index 0000000..af05c30 --- /dev/null +++ b/web/src/components/List.tsx @@ -0,0 +1,159 @@ +import { ChevronRight } from "lucide-react"; +import { type ComponentProps, type ReactNode, useId } from "react"; +import { Link } from "react-router"; +import { cx } from "../lib/platform"; + +/** A section header: sentence case, footnote 500, muted, with an optional count. */ +export function SectionHeader({ children, count, id }: { children: ReactNode; count?: number; id?: string }) { + return ( +

+ {children} + {count !== undefined && {count}} +

+ ); +} + +/** Explanations live under groups, not in rows. */ +export function Footnote({ children, className, id }: { children: ReactNode; className?: string; id?: string }) { + return ( +

+ {children} +

+ ); +} + +type FieldRowProps = Omit, "className"> & { + label: string; + /** Hosts, ports and paths: mono, still 16px so iOS never zooms. */ + mono?: boolean; +}; + +/** + * An editable single-line row (§3.4): the label on the left and the value as a right-aligned + * input, as a read-only row shows it. The row tints while its field has focus. Helpers and + * errors go under the group, linked with `aria-describedby`. + */ +export function FieldRow({ label, mono = false, ...input }: FieldRowProps) { + const id = useId(); + return ( +
+ + +
+ ); +} + +/** A list group (§3.4): card, hairline, 14px radius, inset 16px; rows separated by inset hairlines. */ +export function Group({ children, className, ...props }: ComponentProps<"div">) { + return ( +
*+*]:relative [&>*+*]:before:absolute [&>*+*]:before:top-0 [&>*+*]:before:right-0 [&>*+*]:before:left-(--row-inset,1rem) [&>*+*]:before:h-px [&>*+*]:before:bg-border", + className, + )} + {...props} + > + {children} +
+ ); +} + +/** A labelled block of the settings screens: header, group, footnote; groups are 24px apart. */ +export function Section({ title, footnote, children, className }: { title?: ReactNode; footnote?: ReactNode; children: ReactNode; className?: string }) { + return ( +
+ {title && {title}} + {children} + {footnote && {footnote}} +
+ ); +} + +interface RowContent { + /** A 20px glyph for action rows (Add port forward). */ + icon?: ReactNode; + /** The 32px agent tile that leads the rows of things (sessions, hosts). */ + tile?: ReactNode; + label: ReactNode; + subtitle?: ReactNode; + /** Mono subtitle for hosts and paths. */ + monoSubtitle?: boolean; + value?: ReactNode; + /** Detail rows end in a chevron; action rows don't. */ + chevron?: boolean; + trailing?: ReactNode; + tone?: "default" | "destructive"; +} + +const rowClass = (interactive: boolean, twoLine: boolean) => + cx( + "flex w-full items-center gap-3 px-4 text-left", + twoLine ? "min-h-15 py-2.5" : "min-h-12 py-2", + interactive && "transition-colors duration-(--dur-press) pressed:bg-accent hover:bg-accent", + ); + +function RowBody({ icon, tile, label, subtitle, monoSubtitle, value, chevron, trailing, tone = "default" }: RowContent) { + return ( + <> + {tile} + {icon && {icon}} + + {label} + {subtitle && ( + {subtitle} + )} + + {value !== undefined && {value}} + {trailing} + {chevron && } + + ); +} + +/** A row that navigates. */ +export function LinkRow({ to, ...content }: RowContent & { to: string }) { + return ( +
+ + + +
+ ); +} + +/** A row that does something on tap. */ +export function ButtonRow({ onClick, disabled, ...content }: RowContent & { onClick: () => void; disabled?: boolean }) { + return ( +
+ +
+ ); +} + +/** A row that only shows a value, or holds a control (a whole-row `