diff --git a/.github/workflows/containers.yml b/.github/workflows/containers.yml index 442f90e..9a747ce 100644 --- a/.github/workflows/containers.yml +++ b/.github/workflows/containers.yml @@ -13,7 +13,6 @@ permissions: contents: read jobs: build: - if: github.ref == 'refs/heads/main' strategy: fail-fast: false matrix: diff --git a/.gitignore b/.gitignore index d38248f..fa34975 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,11 @@ __pycache__/ docker/config/ docker/.updates/ docker/.setup-*/ + +# Private Linux assistant state +docker/backups/ +docker/.webcaller.lock +docker/.env.new +docker/.previous-config/ +docker/.restore-*/ +docker/.planned-settings.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 7eab708..54d625c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 0.20.0 — Guided Linux server edition — 2026-10-30 + +- Anchor the app and credit footer inside the usable screen area. Resize the chat above mobile keyboards, account for safe areas and focus panning, and restore the page after keyboard dismissal without moving an older-message scroll position. Preserve pinch zoom and independent message/dialog scrolling. +- Publish matching Linux x86-64/ARM64 app, setup and coturn images with a digest-pinned installation bundle. Keep the native/source option independent. +- Add a numbered maintenance menu, four-part setup with validated answers, contextual DNS/port/proxy instructions, local/public HTTPS checks and stable Docker-release discovery. +- Add credential-preserving reconfiguration, per-installation Compose identities, local-engine/Linux checks, occupied-port detection, maintenance locking and consistent private server snapshots. +- Add allowlisted backup verification, trusted snapshot restore on the same/replacement server and backup-first updates with matching bundle/config/data recovery on startup failure. Keep protocol-boundary guards and manual migration requirements. +- Update the Linux/beginner/operations/security documentation and show actual mobile/desktop interfaces with synthetic data in the README. Preserve artwork attribution; describe stickers without pack inventories. +- Keep libsignal, application encryption, live media encryption, SAS and adaptive voice/video policies unchanged. This release does not convert existing native services to Docker. + ## 0.19.0 — Stickers, reactions and reliable sending — 2026-10-28 This is a source/native release; no new prebuilt Docker image or Docker bundle is published. diff --git a/README.md b/README.md index 6f84d47..deafe98 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,15 @@ **A Signal-like WebRTC phone for Android, iPhone and desktop.** High-quality adaptive voice/video, end-to-end encrypted messages and media, simple invitations and optional calling codes. No SIM card, phone number or account password is required. The phone runs in your browser; you host the server. -[Install on your server](docs/INSTALL.md) · [Download v0.19.0](https://github.com/adlererik/WebCaller/releases/tag/v0.19.0) · [All features](docs/FEATURES.md) · [How to use it](docs/USER_GUIDE.md) · [Security explained](docs/SECURITY.md) +[Install on your server](docs/INSTALL.md) · [Download v0.20.0](https://github.com/adlererik/WebCaller/releases/tag/v0.20.0) · [All features](docs/FEATURES.md) · [How to use it](docs/USER_GUIDE.md) · [Security explained](docs/SECURITY.md) -**v0.19.0 adds stickers and fixes sticker sending, emoji reactions and disappearing-message countdowns.** This is a normal source/native release; the last prebuilt Docker release remains [v0.18.0](https://github.com/adlererik/WebCaller/releases/tag/v0.18.0). The official libsignal core, PQXDH and Triple Ratchet introduced in v0.18.0 remain in use. The cryptographic core is upstream Signal code; its browser binding, storage integration and optional call-verification exchange are WebCaller code and remain unaudited. This is an independent project, not an official Signal client. It cannot call Signal or WhatsApp users, and using the same core does not give it Signal's overall security assurance. Earlier Olm installations need a planned migration, not an ordinary overwrite. [Upgrade guide](docs/APPROVED_CUTOVER.md). +![WebCaller on desktop and mobile](docs/images/overview.jpg) + +**v0.20.0 brings the guided Linux server edition:** setup, connection checks, reconfiguration, consistent backups, restore and backup-first updates. Prebuilt images support Linux x86-64 and ARM64. A native installation remains available; existing native servers are not converted to Docker. [Start the guided install](docker/README.md). + +Desktop chat and mobile dark appearance use the actual interface with fictional contacts/messages and an original illustration. These screenshots contain no real conversations, phone identities or deployment addresses. [Mobile contacts](docs/images/mobile-home.jpg) · [Mobile chat](docs/images/mobile-chat.jpg) · [Desktop chat](docs/images/desktop-chat.jpg). + +The official libsignal core, PQXDH and Triple Ratchet introduced in v0.18.0 remain in use. The cryptographic core is upstream Signal code; its browser binding, storage integration and optional call-verification exchange are WebCaller code and remain unaudited. This is an independent project, not an official Signal client. It cannot call Signal or WhatsApp users, and using the same core does not give it Signal's overall security assurance. Earlier Olm installations need a planned migration, not an ordinary overwrite. [Upgrade guide](docs/APPROVED_CUTOVER.md). ## Why I built it this way @@ -39,7 +45,7 @@ WebCaller supports stickers with one-tap sending, Favorites, Recent and borderle | Disappearing messages | One-hour default for new conversations; Off, presets and custom number/unit wheels through four weeks. Separate sender/send and recipient/first-view countdowns. | | Call and message alerts | Neutral message notifications open the intended chat. Web Push requests call sound and Answer/Decline where supported. Optional self-hosted ntfy priority-5 alerts avoid duplicate browser call pushes, with failure fallback. | | Appearance and privacy controls | System/light/dark appearance, configurable local page title, settings behind a cog, no plaintext message content in notifications, no application asset cache in the service worker. | -| Self-hosting | Native Node/SQLite, source-built containers or the previous v0.18.0 prebuilt Docker bundle; HTTPS/WSS, STUN/ICE, authenticated TURN and optional Cloudflare Tunnel. Configurable paths and safe retirement of previous routes. | +| Self-hosting | Guided Linux Docker edition, native Node/SQLite or source-built containers; HTTPS/WSS, STUN/ICE, authenticated TURN and optional Cloudflare Tunnel. Configurable paths and safe retirement of previous routes. | [Complete feature reference](docs/FEATURES.md). Browser restrictions still matter: a website cannot guarantee ringing after the OS suspends it, force an unexposed earpiece, prevent every screenshot or erase browser/OS history. iPhone browser call alerts require a Home Screen web app. Optional ntfy requires its client; stock iPhone ntfy wake-up also uses platform push infrastructure. [Alerts](docs/CALL_ALERTS.md) · [ntfy](docs/EXTRA_RINGING.md). @@ -73,7 +79,7 @@ SAS is fresh per accepted media context, survives ordinary ICE handovers and is ### How it compares with Signal -| Property | WebCaller v0.19.0 | Signal | +| Property | WebCaller v0.20.0 | Signal | |---|---|---| | Protocol core | Pinned official libsignal through a custom WASM/storage adapter | Official maintained clients and protocol integration | | Message forward secrecy/PQ | PQXDH + Double/Triple Ratchet; persistence, history and recovery limits apply | Maintained protocol with supported clients and much wider scrutiny | @@ -96,17 +102,31 @@ High compression leaves more bandwidth for a clear picture, but software encodin ## Get it running -**For the latest v0.19.0 features, use the source/native release.** It includes the complete source, bundled browser crypto, sticker artwork and beginner setup guides. No Docker image or prebuilt Docker bundle is published for v0.19.0. +Choose the installation that fits your server: + +| Installation | Best for | +|---|---| +| **[Guided Linux Docker edition](docker/README.md)** | A ready-made server package: no Node, npm or Rust installation. Four-part setup, HTTPS/relay options, private QR, diagnostics, settings changes, backups and update recovery. Linux x86-64/ARM64 only. | +| **[Native Debian/source](docs/INSTALL_NATIVE.md)** | Operators who want regular system services without Docker. Existing native installations can stay native. | +| **[Build from source](docs/DEVELOPMENT.md)** | Developers who want to inspect, modify or build the project themselves. | -Choose **one** installation method: +Download the uploaded `WebCaller-Docker-v0.20.0.tar.gz` and `SHA256SUMS.txt`, check the checksum, extract into a new empty folder and run: -- **Previous prebuilt Docker release (v0.18.0):** download `WebCaller-Docker-v0.18.0.tar.gz` from [that release](https://github.com/adlererik/WebCaller/releases/tag/v0.18.0), extract it, then run `./webcaller setup`, `./webcaller start` and `./webcaller qr`. The wizard configures the optional HTTPS/TURN/ntfy services. [Step-by-step guide](docker/README.md). -- **Native Debian, no Docker:** use the complete [native guide](docs/INSTALL_NATIVE.md) for Node, private configuration, HTTPS, boot service, TURN and the private first-phone QR. -- **Build from source (v0.19.0):** download the uploaded `WebCaller-v0.19.0.tar.gz`/`.zip` or recursively clone the tagged release, install dependencies, generate private setup keys and retain the included source offer (or build it from the Git checkout). The root Compose file can also build a container locally. [Installation choices](docs/INSTALL.md). +```sh +./webcaller setup +``` -You need a server, a domain/HTTPS address and a reachable TURN relay for reliable calls across difficult networks. A Cloudflare Tunnel can carry the website and WebSockets; it cannot relay WebRTC media. CGNAT usually requires a separate public TURN server. A successful relay allocation is useful but not a complete call test. +The assistant explains each choice and prints the DNS/ports/proxy checklist for your answers. You still need a server, a hostname and a reachable call relay; it does not buy a domain, bypass CGNAT or replace another website. [Step-by-step Linux guide](docker/README.md). + +After setup, `./webcaller` opens a numbered menu. `./webcaller check-update` finds stable Docker releases; `./webcaller update` downloads first, makes a consistent private snapshot and restores the matching prior state if startup fails. `./webcaller configure`, `backup`, `restore`, `doctor` and `instructions` make everyday maintenance approachable. Backups contain credentials, are not password-encrypted and belong on protected storage. Updates and restores interrupt calls; phone private keys remain on the phones. + +Complete source TAR/ZIP downloads include the pinned upstream source and matching source offer. GitHub's automatic Source code archives omit submodules; use the uploaded release assets. [All install choices and checksums](docs/INSTALL.md). + +| Mobile contacts | Mobile chat · dark appearance | +|---|---| +| ![Mobile contacts, example data](docs/images/mobile-home.jpg) | ![Mobile chat, example data](docs/images/mobile-chat.jpg) | -Scan the private owner QR with the first phone. Other people use invitations or an optional calling code; **never send them server passwords or owner setup credentials**. On iPhone follow Add to Home Screen and use that icon for calls/alerts. Then test messages, a call both ways, all four words, a photo during a call, locked-screen alerts and a Wi-Fi/cellular transition. +![Desktop chat with encrypted media, reactions and disappearing timers; example data](docs/images/desktop-chat.jpg) ## Documentation and verification diff --git a/deploy/Dockerfile.setup b/deploy/Dockerfile.setup index 324cdbe..dcbf058 100644 --- a/deploy/Dockerfile.setup +++ b/deploy/Dockerfile.setup @@ -18,7 +18,7 @@ RUN case "$TARGETARCH" in \ WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --omit=dev --ignore-scripts -COPY scripts/docker-setup.py scripts/docker-ntfy-init.mjs ./scripts/ +COPY scripts/docker-setup.py scripts/docker_backup.py scripts/docker-ntfy-init.mjs ./scripts/ COPY docker/VERSION ./VERSION USER node ENTRYPOINT ["/opt/qr/bin/python", "/app/scripts/docker-setup.py"] diff --git a/docker/README.md b/docker/README.md index 21c40a5..a2ab1e9 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,94 +1,183 @@ -# Guided Docker installation — WebCaller v0.18.0 +# WebCaller for Linux — guided server edition v0.20.0 -**Version note:** this guide and the prebuilt images remain at v0.18.0. The v0.19.0 sticker release is source/native only and does not include a Docker update bundle. Use the [native/source guide](../docs/INSTALL.md) for those features; do not pass v0.19.0 to this prebuilt updater. +Your people open a link. You keep control of the server. This download guides you through installing WebCaller, HTTPS, a call relay and optional extra ringing, then gives you simple maintenance commands. -This small download installs the **libsignal/PQXDH v0.18.0** application. It pulls matching prebuilt images from GitHub Container Registry (GHCR); you do not need Node, npm or Rust on the host. Native amd64/arm64 images support Linux servers, including common x86 VPSs and 64-bit ARM servers. +**Linux x86-64 and ARM64 only.** Use Docker Engine directly on Linux, Python 3.10+ and Docker Compose 2.20+. Docker Desktop, Windows, macOS, remote Docker contexts and 32-bit ARM are not supported by this installer. Phones still use an ordinary browser; they do not need Docker. -The bundle includes the phone, setup wizard/private QR and optional coturn, ntfy, Caddy HTTPS and Cloudflare connector. You still supply a server, domain, network access and any required router/DNS configuration. It does not register domains or replace another website automatically. +Already have a native WebCaller service? Keep it. This package is an alternative installation in its own empty folder; it does not migrate or modify a native installation, another website or another Docker project. Earlier Olm versions need the separate [migration guide](../docs/APPROVED_CUTOVER.md). -**Existing Olm v0.17.x or earlier:** use [upgrade planning](../docs/APPROVED_CUTOVER.md). This protocol boundary is bundle format 2; do not point it at old volumes or bypass an updater's migration refusal. New installations use a fresh empty folder. This does not change a separate native installation. +## What you need before starting -## 1. Install Docker +- A Linux server you can log into by SSH. A public VPS is the simplest networking arrangement. A modest 64-bit server is sufficient for a small installation; allow room for container images, backups and retained files. +- A hostname under a domain you control, such as `phone.example.com`. The wizard does not buy a domain or change your DNS account. +- Docker Engine, the Compose plugin and Python 3.10+. You do not need Node, npm, Rust or to compile anything. +- Either a public IPv4 for the included TURN call relay, router forwarding to it, or an existing reachable TURN REST relay elsewhere. -Use the official [Docker Engine on Debian](https://docs.docker.com/engine/install/debian/) guide (or your distribution's supported instructions), including the **Docker Compose plugin**. Check: +**Website access and call connectivity are different.** A Cloudflare HTTP Tunnel can expose the website without router forwarding, but cannot carry TURN media. A home server behind CGNAT normally needs a public relay elsewhere. The wizard explains this and lets you configure the website first without pretending calls have been verified. + +### Install Docker once + +Follow the official instructions for your Linux distribution: [Debian](https://docs.docker.com/engine/install/debian/), [Ubuntu](https://docs.docker.com/engine/install/ubuntu/), [Fedora](https://docs.docker.com/engine/install/fedora/) or [other supported Linux distributions](https://docs.docker.com/engine/install/). Include the **Docker Compose plugin**. Install Python 3 using your distribution's package manager if it is missing. + +Check: ```sh -docker --version +python3 --version +docker version docker compose version ``` -If your account is not allowed to use Docker, follow the vendor's instructions or use `sudo` consistently for these commands. Docker access grants substantial host privileges; keep its socket private. Preserve any existing containers/volumes. +If Docker says permission denied, follow its installation guide or run WebCaller commands consistently with `sudo`. Do not remove existing containers or replace another site's configuration to make this installer work. Docker access is powerful: keep its socket private. -## 2. Download and check the bundle +## 1. Download into a new folder -On the server, in a new empty directory: +In your SSH terminal: ```sh -mkdir WebCaller-install -cd WebCaller-install -curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.18.0/WebCaller-Docker-v0.18.0.tar.gz -curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.18.0/SHA256SUMS.txt +mkdir WebCaller-download +cd WebCaller-download +curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.20.0/WebCaller-Docker-v0.20.0.tar.gz +curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.20.0/SHA256SUMS.txt sha256sum --ignore-missing -c SHA256SUMS.txt ``` -Continue only when the Docker archive reports **OK**. The checksum file also lists source assets, which are intentionally absent here. The download is a small installation bundle, not an offline copy of all images. Image references in the uploaded bundle are versioned **and digest-pinned**; `docker/images.env` in source is the editable build reference. +Continue when the Docker archive says **OK**. Other entries in the checksum file are source downloads you have not downloaded. If the check fails, download again; do not proceed with that file. ```sh -tar -xzf WebCaller-Docker-v0.18.0.tar.gz -cd WebCaller-Docker-v0.18.0 +tar -xzf WebCaller-Docker-v0.20.0.tar.gz +cd WebCaller-Docker-v0.20.0 ./webcaller setup ``` -## 3. Answer the setup questions +This is a small online installer: it downloads release-matched, digest-pinned images from GitHub Container Registry. It is not an offline copy of every image. Each installation gets its own persistent Docker project name, configuration and data volumes. Keep this folder after setup; it is your server's control panel. + +If you run `./webcaller` without a command in an interactive terminal, it displays a numbered menu. + +## 2. Follow the four-part wizard -- **Hostname:** your own HTTPS hostname, for example `phone.example.com`. The initial app URL is `https://phone.example.com/calls/`. -- **HTTPS:** choose automatic Caddy only if ports 80/443 are available and reach this server. If another website/proxy or Tunnel already runs here, choose the existing proxy/Tunnel option and add a route to the selected loopback app port. Keep other routes. -- **TURN:** self-host if the relay/router has a publicly reachable IPv4 and you can open its ports; otherwise supply an existing TURN REST relay. Behind CGNAT, use a public relay elsewhere. Configure-later is useful for setup, but not reliable cross-network calling. -- **Optional ntfy:** choose it only if you want extra ringing for people who can install its app. Give it a separate hostname. The iPhone option uses the described ntfy.sh wake-up metadata relay; encrypted conversations remain in WebCaller. +**Your website:** enter a hostname such as `phone.example.com`, without `https://` or a path. The default phone address is `https://phone.example.com/calls/`. -The wizard creates private `config/` files and credentials, plus persistent Docker volumes. It will not overwrite an existing setup. Do not publish `config/`, `.env`, tunnel tokens, private QR output or volume backups. Do not use `docker compose down -v` on a real installation: it removes persistent data. +**Secure access:** choose one: -For a home relay forward **TCP/UDP 3478** and **UDP 49160–49260** to it; public VPS firewalls need equivalent rules. HTTPS Caddy needs TCP80/443 separately. TURN-TLS/certificate setup is additional; a Cloudflare HTTP Tunnel does not relay TURN media. [Networking and CGNAT](../docs/NETWORKING.md). +| Choice | Use it when | What you must do | +|---|---|---| +| Automatic HTTPS | A fresh server can use ports 80 and 443 | Point DNS at the server/router's public IP; allow TCP 80/443. Caddy obtains and renews certificates. | +| Existing website/proxy/Tunnel | You already have HTTPS or another site uses those ports | Add a new hostname route to the shown loopback app port; preserve existing routes and WebSocket upgrades. | +| Containerized Cloudflare connector | You have a Cloudflare account, domain and tunnel token | Paste its token privately; add the shown hostname routes in your existing account. No domain or Cloudflare account is created. | -For an existing proxy/Tunnel, target the app's selected port on loopback (default `127.0.0.1:8080`) and preserve WebSocket upgrades. With the containerized Tunnel option, the connector uses Docker-network service names such as `webcaller:8080`; its loopback is not the host's loopback. A separate ntfy route targets its chosen loopback port or `ntfy:8094` inside that Docker network. No Cloudflare account/domain is created by the wizard. +**Reliable calls:** choose the included self-hosted relay, an existing TURN REST relay, or configure later. For the self-hosted option, the wizard can suggest the public IP seen by a STUN server; this is a suggestion, not proof of a public inbound route. At home, compare it with the router's WAN address. If they differ, or the WAN address is private/CGNAT, read [networking](../docs/NETWORKING.md) before relying on this relay. Rootless Docker needs an external relay; the bundled host-network TURN recipe requires standard Docker Engine networking. -## 4. Start and enroll the first phone +An existing relay must use REST shared-secret credentials. An ordinary fixed username/password account is not interchangeable with that option. Secrets are entered without echoing them. + +**Extra ringing:** optionally add a self-hosted ntfy server under a separate hostname. Only people who install its phone client use this extra channel. Browser alerts remain available. Stock iPhone ntfy wake-up additionally uses ntfy.sh/Apple metadata infrastructure, which the wizard explains before you enable it. [Alerts and limitations](../docs/EXTRA_RINGING.md). + +The wizard shows a summary and asks before saving. It generates unique owner, VAPID and relay credentials; it does not overwrite an existing installation. You can then start the stack immediately or finish the networking steps first. + +## 3. Follow your connection checklist ```sh +./webcaller instructions ./webcaller start -./webcaller status +./webcaller doctor +``` + +`instructions` prints routes and ports for **your chosen configuration**. `doctor` checks the local application and public HTTPS without turning off certificate validation. A WAIT result means setup is unfinished; it is not an instruction to create a new identity. + +For a self-hosted home TURN relay, forward: + +| Traffic | Destination | +|---|---| +| TCP and UDP 3478 | This Linux server, port 3478 | +| UDP 49160–49260 | The same ports on this Linux server | +| TCP 80 and 443 | This server only if you chose automatic HTTPS | + +Equivalent VPS firewall rules are needed on a public server. Docker's published ports can interact with host firewalls; follow Docker's distribution-specific guidance. Do not expose the app's raw HTTP port as a substitute for HTTPS. + +For an existing proxy/Tunnel running on the host, target `127.0.0.1:8080` by default. A containerized connector targets `webcaller:8080`, because its loopback address is not the host's. Optional ntfy similarly uses its selected loopback port on the host, or `ntfy:8094` inside the Docker network. The printed checklist gives the exact values. + +### Restricted networks and TURN-TLS + +The included relay starts with authenticated UDP/TCP TURN on 3478. This already carries **end-to-end encrypted WebRTC media**. Some restricted networks need TURN over TLS as an additional transport. + +For TURN-TLS, copy a valid certificate and private key for your relay hostname into `config/certs/fullchain.pem` and `config/certs/privkey.pem` (real files, not symlinks), arrange certificate renewal, allow TCP 5349 and append `turns:relay.example.com:5349?transport=tcp` to `TURN_URLS` in private `config/app.env`. Recreate the service containers after a manual file change with `./webcaller stop` then `./webcaller start`. Certificates and renewal are additional setup; the wizard does not claim to have provisioned TURN-TLS. An existing HTTPS site already using 443 cannot also share that port with coturn without a separately designed proxy/IP arrangement. + +A successful local health check or TURN allocation is not proof that two remote phones can exchange media. Test one phone on Wi-Fi and the other on cellular. + +## 4. Set up the first phone + +```sh ./webcaller qr ``` -The services should report running/healthy. Scan the private first-phone QR with the phone camera and choose a display name. **Invite someone** connects other people; they do not need owner/server credentials. Keep the first-phone QR private. iPhone users follow Add to Home Screen and use that icon for calls/alerts. [Phone instructions](../docs/USER_GUIDE.md). +Scan this **private first-phone QR** with the phone camera, then choose a name. Use **Invite someone** on that phone for other people; do not send them owner/server credentials. Calling codes are optional. -Test messages, calls both ways, four matching SAS words, a photo while talking, different networks, locked-screen sound and Wi-Fi/cellular recovery. Settings → Check calling connection only proves relay allocation, not complete media delivery. Alert delivery depends on phone permissions and OS policy. +On iPhone, follow the Add to Home Screen instructions and continue using that icon. Enable browser call alerts, test the sound while locked, then test calls in both directions. A website cannot force continuous ringing if the OS suspends it. Optional ntfy requires its own app. [Phone guide](../docs/USER_GUIDE.md). ## Everyday commands +| Command | Purpose | +|---|---| +| `./webcaller status` | Version and service state | +| `./webcaller doctor` | Local/public HTTPS checks and next steps | +| `./webcaller instructions` | Your DNS/proxy/port checklist | +| `./webcaller qr` | Private first-phone setup QR | +| `./webcaller logs` | Recent diagnostics; inspect before sharing | +| `./webcaller stop` / `start` | Stop/start this installation without deleting data | +| `./webcaller configure` | Guided changes with a safety snapshot | +| `./webcaller check-update` | Find a newer stable release with a Docker bundle | +| `./webcaller update` | Review and install that newer Docker release | +| `./webcaller backup` | Consistent private server snapshot | +| `./webcaller restore backups/FILE.tar.gz` | Restore a trusted snapshot after explicit confirmation | + +## Change settings later + ```sh -./webcaller status -./webcaller logs -./webcaller stop -./webcaller start +./webcaller configure +``` + +The wizard starts with the existing answers; Enter retains them. It briefly stops **this Docker installation**, makes a consistent safety snapshot, and recreates the selected services. Owner/VAPID credentials, persistent volumes and the Docker project identity are preserved. Extra application settings are retained where they are not explicitly controlled by the wizard. A failed/cancelled change restores the safety snapshot and restarts the previous stack if it was running. + +Changing a hostname changes the browser origin. Browser identity/history is not automatically moved to a different website; phones need setup at the new address. Restoring server data also cannot recover keys that were erased from a phone. Finish calls before maintenance. + +## Back up and restore + +```sh +./webcaller backup ``` -Logs are diagnostics, not material to post publicly without checking for identifiers. The generated configuration and named volumes preserve identity/mailbox/ntfy state across normal restart. Phone private keys are held by the browser, not recoverable from a server backup. +Confirm the brief interruption. The command stops this installation's services, snapshots matching bundle files, private configuration and its existing named volumes, then resumes the stack if it was running. It prints a filename under `backups/`. Copy that archive to protected storage away from the server. -## Update and recovery +**Backups contain credentials and are not password-encrypted.** They are created with private file permissions. Use encrypted storage for an off-server copy. Never upload these files, `config/`, `.env` or private QR output to GitHub. Never run `docker compose down -v` on an installation you want to keep. -Read release notes first, finish calls and make a consistent private backup of the installation/configuration and persistent volumes. Use an explicit newer **libsignal** version: +To restore on the same installation: ```sh -./webcaller update vX.Y.Z +./webcaller restore backups/YOUR-BACKUP.tar.gz ``` -Replace `vX.Y.Z` with the actual release. The updater checks bundle checksum, allowed files, version order and image namespace/digests, pulls before replacement, preserves private configuration/volumes and checks startup. Updates are deliberate, not unattended. Existing explicit configuration wins over new defaults. A protocol/database migration is not an ordinary update; downgrades and Olm cutovers require manual review. Source-only package changes do not alter a running native service. +Use the actual filename printed by Backup. The assistant verifies file hashes, allowed paths and the installation identity before changing data. It takes a safety backup and asks you to type **RESTORE**. Restoration replaces matching bundle/configuration/data with the snapshot; server changes after that time are lost. Only use backups you trust: they contain executable installer files too. + +To recover on a replacement Linux server, install Docker/Compose/Python, extract a fresh release bundle into an empty folder, copy your private backup there, then run `./webcaller restore /absolute/path/to/YOUR-BACKUP.tar.gz` **before setup**. The assistant recovers the saved configuration and data without generating replacement keys. It refuses to create a second copy of that project where its containers/volumes already exist. Update DNS/router settings if the server address changed and run Doctor again. Private keys and conversations retained only on a phone remain that phone's responsibility. + +Snapshots support regular files/directories, not symlinks or special files; copy TLS files into `config/certs`. The verifier rejects corruption, unexpected paths, links, duplicate entries and excessive archive sizes/counts. Hash checks detect corruption, not who made an untrusted archive. Keep enough free disk space for a full copy and retain the required prior images for offline recovery. + +## Updates and recovery + +```sh +./webcaller check-update +./webcaller update +``` + +The assistant offers a published stable release **with an actual Docker bundle**, shows its release-notes link and asks for confirmation. It checks the archive checksum/allowed files, requires the expected image namespaces/digests, downloads images before stopping services, then takes a full safety snapshot. Private configuration is retained. Startup failure triggers restoration of the previous matching bundle, configuration and server data. If automatic recovery itself fails, the assistant keeps the backup and gives its location for manual recovery. It never changes a separate native installation. + +You may choose an explicit newer release with `./webcaller update vX.Y.Z`. Replace the placeholder with a real release. Updates interrupt calls; they are deliberate, not unattended. Protocol boundaries and incompatible bundle formats require a reviewed migration. A rollback restores server state at the snapshot, not phone/browser state or later messages; do not clear phones' site data as a repair step. + +**Coming from the older v0.18.0 Docker launcher:** its own updater predates automatic snapshots. First stop that installation and make a consistent private copy of its installation folder/configuration and named volumes using [Docker's volume backup procedure](https://docs.docker.com/engine/storage/volumes/#back-up-restore-or-migrate-data-volumes). Then use its documented `./webcaller update v0.20.0`. It preserves its existing project/configuration; future maintenance uses the new assistant. The older updater does not retroactively gain automatic recovery for that first upgrade. Existing Olm installations require the separate migration guide. -The updater is not an automatic database rollback mechanism. Keep a matching prior bundle/images/configuration/database backup until tested, and restore with services stopped. Do not restore a database over a running application or clear phones' browser data to repair connectivity. [Operations and backups](../docs/OPERATIONS.md). +## Included software and security -## What is downloaded and licensed +WebCaller, setup helper and coturn images are published at `ghcr.io/adlererik/webcaller` with x86-64/ARM64 variants and release-specific app, `-setup` and `-turn` tags. The downloadable bundle pins project and supporting ntfy/Caddy/cloudflared images by digest. Docker Engine itself remains a host prerequisite maintained through your Linux package manager. -The application/setup/relay images are published under `ghcr.io/adlererik/webcaller`, with release-specific app, `-setup` and `-turn` tags plus amd64/arm64 variants. Supporting ntfy/Caddy/cloudflared images are separately pinned. Download size varies by architecture and registry layer cache; this bundle is only the launcher, not an offline appliance. +Chat/signaling use official libsignal PQXDH/Triple Ratchet with application Ed25519 signatures; files use fresh AES-256-GCM keys. Voice/video use browser DTLS-SRTP, with optional media-bound SAS words and a full identity fingerprint. The custom browser integration remains unaudited. Read [security and encryption](../docs/SECURITY.md), [all features](../docs/FEATURES.md) and [licensing](../LICENSING.md). -The combined application links AGPL-3.0-only libsignal. The app image includes notices and the matching corresponding-source download; release source archives include full pinned upstream source. Preserve that source offer if you modify or host it. [Licensing](../LICENSING.md) · [Security](../docs/SECURITY.md). +The combined distribution links AGPL-3.0-only libsignal. Images include notices and matching corresponding source; release source archives include the pinned upstream source. Preserve this source offer when hosting or modifying the project. Sticker artwork has separate attribution/rights records. diff --git a/docker/VERSION b/docker/VERSION index 6633391..5a03fb7 100644 --- a/docker/VERSION +++ b/docker/VERSION @@ -1 +1 @@ -0.18.0 +0.20.0 diff --git a/docker/images.env b/docker/images.env index 6b50e94..d302a1b 100644 --- a/docker/images.env +++ b/docker/images.env @@ -1,8 +1,8 @@ # Release-specific image references. Published Docker bundles pin project images by digest too. BUNDLE_FORMAT=2 -WEBCALLER_IMAGE=ghcr.io/adlererik/webcaller:0.18.0 -SETUP_IMAGE=ghcr.io/adlererik/webcaller:0.18.0-setup -TURN_IMAGE=ghcr.io/adlererik/webcaller:0.18.0-turn +WEBCALLER_IMAGE=ghcr.io/adlererik/webcaller:0.20.0 +SETUP_IMAGE=ghcr.io/adlererik/webcaller:0.20.0-setup +TURN_IMAGE=ghcr.io/adlererik/webcaller:0.20.0-turn NTFY_IMAGE=binwiederhier/ntfy:v2.31.1@sha256:91bb7fa607b02006c119bb4a31032923b414a713a032ecb40f0c5d6bfd5b7e40 CADDY_IMAGE=caddy:2-alpine@sha256:d8542f48d34a9cf4e4c11a478865229840e87e4c96ea3f439101f31a5d35f75f TUNNEL_IMAGE=cloudflare/cloudflared:latest@sha256:a15a3b50b8dabd57ac2090e9484c0247dba9dfa1f0df4d298d4317f9d69eb2d5 diff --git a/docker/webcaller b/docker/webcaller index 1207c00..6c346b5 100755 --- a/docker/webcaller +++ b/docker/webcaller @@ -1,33 +1,281 @@ -#!/bin/sh -set -eu -bundle_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) -cd "$bundle_dir" -image_value() { sed -n "s/^$1=//p" images.env; } -setup_image=$(image_value SETUP_IMAGE) -if test -z "$setup_image"; then echo 'Missing images.env. Extract the complete Docker bundle.' >&2; exit 1; fi -compose() { docker compose --project-directory "$bundle_dir" --env-file images.env --env-file .env -f compose.yaml "$@"; } -helper() { - if test -t 0; then tty_arg=-it; else tty_arg=-i; fi - docker run --rm "$tty_arg" --user "$(id -u):$(id -g)" --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges:true --mount "type=bind,src=$bundle_dir,dst=/bundle" "$setup_image" "$@" -} -need_setup() { test -f .env && test -f config/app.env || { echo 'Run ./webcaller setup first.' >&2; exit 1; }; } -case "${1:-help}" in - setup) test "$(uname -s)" = Linux || { echo 'The complete relay stack supports Linux amd64/arm64.'; exit 1; }; helper init ;; - qr) need_setup; helper qr ;; - start) need_setup; compose up -d --wait --wait-timeout 180 ;; - stop) need_setup; compose stop ;; - status) need_setup; compose ps ;; - logs) need_setup; compose logs --tail=100 ;; - update) - need_setup - version=${2:-};case "$version" in v[0-9]*.[0-9]*.[0-9]*) ;; *) echo 'Usage: ./webcaller update vX.Y.Z [--yes]'; exit 1 ;; esac - echo 'Read the release notes and make any private backup you need first. Updating can interrupt calls. Database rollback is not automatic.' - if test "${3:-}" != --yes; then printf 'Continue? [y/N] '; read -r answer; case "$answer" in y|Y|yes) ;; *) exit 0 ;; esac; fi - helper prepare-update "$version" - docker compose --project-directory "$bundle_dir" --env-file ".updates/$version/images.env" --env-file .env -f ".updates/$version/compose.yaml" pull - helper apply-update "$version" - compose up -d --wait --wait-timeout 180 - echo 'Containers are running/healthy. Test the public page, a call and locked-phone alerts.' - ;; - *) echo 'WebCaller: setup | start | qr | status | logs | stop | update vX.Y.Z [--yes]';; -esac +#!/usr/bin/env python3 +"""WebCaller Linux server assistant. Requires Python 3 and Docker Engine + Compose.""" +import contextlib,fcntl,json,os,pathlib,platform,re,socket,subprocess,sys,urllib.parse,urllib.request +from datetime import datetime,timezone +ROOT=pathlib.Path(__file__).resolve().parent +VOLUMES={'app_data','ntfy_state','publisher','caddy_data','caddy_config'} +class FriendlyError(Exception):pass + +def env(path): + try:return dict(l.split('=',1) for l in pathlib.Path(path).read_text().splitlines() if '=' in l and not l.startswith('#')) + except OSError:raise FriendlyError('An installation file is missing. Extract the complete WebCaller Docker bundle first.') +def image():return env(ROOT/'images.env')['SETUP_IMAGE'] +def configured():return (ROOT/'.env').is_file() and (ROOT/'config/app.env').is_file() +def project(): + value=env(ROOT/'.env').get('COMPOSE_PROJECT_NAME','webcaller-prebuilt') + if not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,62}',value):raise FriendlyError('Invalid installation project name. Restore your private configuration.') + return value + +def run(args,capture=False,input=None,check=True,timeout=600): + try: + r=subprocess.run(args,cwd=ROOT,input=input,text=True,stdout=subprocess.PIPE if capture else None,stderr=subprocess.PIPE if capture else None,timeout=timeout) + except FileNotFoundError:raise FriendlyError('Docker was not found. Install Docker Engine and its Compose plugin using https://docs.docker.com/engine/install/ then run this command again.') + except subprocess.TimeoutExpired:raise FriendlyError('The command timed out. Your saved configuration is still present; use status or doctor to inspect it.') + if check and r.returncode:raise FriendlyError('A Docker command failed. Follow the explanation above, then run ./webcaller doctor. Your settings have not been regenerated.') + return r.stdout if capture and check else r + +def docker(*args,**kw):return run(['docker',*args],**kw) +def compose(*args,stage=None,**kw):return docker('compose','--ansi','never','--project-name',project(),'--project-directory',str(ROOT),'--env-file',str((stage or ROOT)/'images.env'),'--env-file',str(ROOT/'.env'),'-f',str((stage or ROOT)/'compose.yaml'),*args,**kw) +def helper(action,*args,root=False,volumes=None,archive=None,capture=False,setup_image=None,input=None): + cmd=['run','--rm','-i'] + if input is None and not capture and sys.stdin.isatty():cmd+=['-t'] + cmd+=['--user','0:0' if root else str(os.getuid())+':'+str(os.getgid()),'--read-only','--tmpfs','/tmp','--cap-drop','ALL','--security-opt','no-new-privileges:true'] + if root: + for cap in ['CHOWN','DAC_OVERRIDE','FOWNER']:cmd+=['--cap-add',cap] + if action in ['snapshot','backup-info','restore','restore-seed','qr']:cmd+=['--network','none'] + cmd+=['--env','WEBCALLER_OWNER_UID='+str(os.getuid()),'--env','WEBCALLER_OWNER_GID='+str(os.getgid()),'--mount','type=bind,src='+str(ROOT)+',dst=/bundle'] + if archive:cmd+=['--mount','type=bind,src='+str(archive.parent)+',dst=/backup'+(',readonly' if action!='snapshot' else '')] + for key,value in (volumes or {}).items(): + if key not in VOLUMES or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]+',value):raise FriendlyError('Unexpected volume mapping. Nothing was restored.') + cmd+=['--mount','type=volume,src='+value+',dst=/volumes/'+key+(',readonly' if action=='snapshot' else '')] + cmd+=[setup_image or image(),action,*args] + if archive:cmd+=['--archive','/backup/'+archive.name] + if volumes is not None:cmd+=['--volumes',json.dumps({k:'/volumes/'+k for k in volumes})] + return docker(*cmd,capture=capture,input=input,timeout=1800) + +def preflight(): + if platform.system()!='Linux':raise FriendlyError('This complete installer supports Linux only. Use a Linux server or virtual machine, not Docker Desktop on Windows/macOS.') + if platform.machine() not in ['x86_64','aarch64','arm64']:raise FriendlyError('Use a 64-bit x86-64 or ARM64 Linux server. This release does not support 32-bit ARM.') + if sys.version_info<(3,10):raise FriendlyError('Use Python 3.10 or newer. Install it with your Linux distribution package manager.') + version=docker('compose','version','--short',capture=True).strip().lstrip('v');match=re.match(r'(\d+)\.(\d+)',version) + if not match or tuple(map(int,match.groups()))<(2,20):raise FriendlyError('Update the Docker Compose plugin to version 2.20 or newer.') + info=json.loads(docker('info','--format','{{json .}}',capture=True)) + endpoint=os.environ.get('DOCKER_HOST') or json.loads(docker('context','inspect','--format','{{json .Endpoints.docker.Host}}',capture=True)) + if not endpoint.startswith('unix://'):raise FriendlyError('Use Docker Engine on this Linux server. Remote Docker contexts and Docker Desktop are not supported by the local-folder installer.') + if 'Docker Desktop' in str(info.get('OperatingSystem','')):raise FriendlyError('Use Docker Engine directly on Linux; this relay recipe does not support Docker Desktop.') + if configured(): + dirs=docker('ps','-a','--filter','label=com.docker.compose.project='+project(),'--format','{{.Label "com.docker.compose.project.working_dir"}}',capture=True).splitlines() + if any(p and pathlib.Path(p).resolve()!=ROOT for p in dirs):raise FriendlyError('This project is already attached to another installation folder. Do not start a copied installation on the same server; use its original folder.') + return info + +def need_setup(): + if not configured():raise FriendlyError('Run ./webcaller setup first. For a saved installation, restore its private config folder and .env; do not create new phone keys.') +def confirm(text,token=None,default=False): + if not sys.stdin.isatty():raise FriendlyError('This action needs an interactive terminal for confirmation.') + answer=input(text+(' Type '+token+': ' if token else ' [Y/n]: ' if default else ' [y/N]: ')).strip() + return answer==token if token else (default if not answer else answer.lower() in ['y','yes']) +def ports(): + s=env(ROOT/'.env');profiles=s.get('COMPOSE_PROFILES','').split(',');used=[] + for port in ([80,443] if 'https' in profiles else [])+[int(s.get('APP_PORT',8080))]+([int(s.get('NTFY_PORT',8094))] if 'ntfy' in profiles else []): + with socket.socket() as sock: + try:sock.bind(('0.0.0.0',port)) + except PermissionError:continue + except OSError:used.append(str(port)) + if 'turn' in profiles: + for kind in [socket.SOCK_STREAM,socket.SOCK_DGRAM]: + with socket.socket(socket.AF_INET,kind) as sock: + try:sock.bind(('0.0.0.0',3478)) + except OSError:used.append('3478') + if used:raise FriendlyError('Ports already in use: '+', '.join(sorted(set(used)))+'. Existing services were not changed. Run ./webcaller configure to select different local ports or your existing HTTPS proxy.') + +def running():return bool(compose('ps','--services','--status','running',capture=True).strip()) +def start(check_ports=False): + if 'turn' in env(ROOT/'.env').get('COMPOSE_PROFILES','').split(','): + info=json.loads(docker('info','--format','{{json .}}',capture=True)) + if 'rootless' in str(info.get('SecurityOptions','')):raise FriendlyError('Rootless Docker cannot use this host-network TURN recipe. Use configure to select an external relay, or use standard Docker Engine.') + if check_ports:ports() + compose('config','--quiet');compose('up','-d','--remove-orphans','--wait','--wait-timeout','180') + +def mappings(create=False,names=None): + config=json.loads(compose('--profile','*','config','--format','json',capture=True));result={} + for key in sorted(names if names is not None else VOLUMES): + if key not in VOLUMES or key not in config['volumes']:raise FriendlyError('The backup contains an unsupported volume.') + name=config['volumes'][key]['name'] + r=docker('volume','inspect',name,capture=True,check=False) + if r.returncode: + if not create:continue + docker('volume','create','--label','com.docker.compose.project='+project(),'--label','com.docker.compose.volume='+key,name,capture=True) + else: + labels=json.loads(r.stdout)[0].get('Labels') or {} + if labels.get('com.docker.compose.project')!=project() or labels.get('com.docker.compose.volume')!=key:raise FriendlyError('A volume belongs to another installation. It was not modified.') + result[key]=name + return result + +def snapshot(stopped=False): + was_running=running();folder=ROOT/'backups';folder.mkdir(mode=0o700,exist_ok=True) + archive=folder/('WebCaller-'+(ROOT/'VERSION').read_text().strip()+'-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')+'.tar.gz') + if not stopped:compose('stop') + try:helper('snapshot',root=True,volumes=mappings(),archive=archive) + finally: + if was_running and not stopped:start() + print('Private backup: '+str(archive)+'\nIt contains credentials. Keep it on protected storage; this archive is not password-encrypted.') + return archive + +def restore_snapshot(archive,setup_image=None): + metadata=json.loads(helper('backup-info',archive=archive,capture=True,setup_image=setup_image)) + if metadata['project']!=project():raise FriendlyError('This backup belongs to a different installation. Restore it into its matching folder/server, not over this project.') + helper('restore',root=True,volumes=mappings(create=True,names=metadata['volumes']),archive=archive,setup_image=setup_image) + +def request_json(url): + with urllib.request.urlopen(urllib.request.Request(url,headers={'User-Agent':'WebCaller-Linux-installer','Accept':'application/vnd.github+json'}),timeout=15) as r: + data=r.read(2*1024*1024+1) + if len(data)>2*1024*1024:raise FriendlyError('The update response is unexpectedly large.') + return json.loads(data) +def updates(): + current=tuple(map(int,(ROOT/'VERSION').read_text().strip().split('.')));releases=request_json('https://api.github.com/repos/adlererik/WebCaller/releases?per_page=20');available=[] + for r in releases: + tag=r.get('tag_name','') + if r.get('draft') or r.get('prerelease') or not re.fullmatch(r'v\d+\.\d+\.\d+',tag):continue + if tuple(map(int,tag[1:].split('.')))<=current:continue + if any(a.get('name')=='WebCaller-Docker-'+tag+'.tar.gz' for a in r.get('assets',[])):available.append(tag) + return max(available,key=lambda v:tuple(map(int,v[1:].split('.')))) if available else None + +def doctor(): + print('\nWEBCALLER · CONNECTION CHECK\nOnly this Docker installation is inspected.') + compose('ps');app=env(ROOT/'config/app.env');s=env(ROOT/'.env');path=urllib.parse.urlsplit(app['PUBLIC_URL']).path.rstrip('/');failures=0 + for label,url in [('Local app','http://127.0.0.1:'+s.get('APP_PORT','8080')+path+'/health'),('Public HTTPS',app['PUBLIC_URL'].rstrip('/')+'/health')]: + try: + r=request_json(url) + if r.get('ok') is not True:raise ValueError() + print(' OK '+label) + except (OSError,ValueError): + failures+=1;print(' WAIT '+label+' — check DNS, your HTTPS route and firewall. Run ./webcaller instructions for exact routes.') + if app.get('TURN_URLS'): + print(' INFO TURN relay addresses are configured. A browser call across two networks is still required to prove media delivery.') + else:print(' WAIT No call relay configured. Run ./webcaller configure before relying on calls between different networks.');failures+=1 + print(' INFO Phone alerts depend on permissions and OS settings. Test with the phone locked.\n Next: ./webcaller instructions | ./webcaller qr') + return failures + +def instructions(): + s=env(ROOT/'.env');app=env(ROOT/'config/app.env');profiles=s.get('COMPOSE_PROFILES','').split(',');host=urllib.parse.urlsplit(app['PUBLIC_URL']).hostname + print('\nYOUR SETUP CHECKLIST\nWebsite: '+app['PUBLIC_URL']+'/') + if 'https' in profiles:print('1. Point the hostname DNS at your server’s public IP. Allow TCP 80 and 443 through the server firewall/router. Caddy obtains and renews HTTPS certificates automatically.') + else: + target='webcaller:8080' if 'tunnel' in profiles else '127.0.0.1:'+s.get('APP_PORT','8080') + print('1. In your existing HTTPS proxy/Tunnel add hostname '+host+' → HTTP '+target+'. Allow WebSocket upgrades; preserve other websites and routes.') + if 'turn' in profiles:print('2. Allow TCP/UDP 3478 and UDP 49160–49260. Behind a home router, forward them to this Linux server. An HTTP Tunnel does not carry TURN. TURN-TLS on 5349 needs separate certificates/forwarding; see the guide for restricted networks.') + elif app.get('TURN_URLS'):print('2. Your existing TURN REST relay is configured. Confirm its public endpoints are reachable.') + else:print('2. Add a reachable TURN relay with ./webcaller configure. A website behind CGNAT needs a public relay elsewhere.') + if 'ntfy' in profiles: + target='ntfy:8094' if 'tunnel' in profiles else '127.0.0.1:'+s.get('NTFY_PORT','8094') + print('3. Extra ringing: '+app['NTFY_PUBLIC_URL']+' → HTTP '+target+'. '+('Caddy manages this hostname too.' if 'https' in profiles else 'Add this separate HTTPS route as well.')) + print('Then run ./webcaller doctor. Scan ./webcaller qr for the first phone; invite other people from that phone. Test messages, calls both ways and a call across Wi-Fi/mobile data.\nGuide: https://github.com/adlererik/WebCaller/blob/main/docker/README.md') + +HELP='''WebCaller · Linux server assistant + + ./webcaller setup Guided first installation + ./webcaller start Start this installation + ./webcaller status Show services and version + ./webcaller doctor Check local/public HTTPS + ./webcaller instructions Your DNS, port and proxy checklist + ./webcaller qr Private first-phone QR + ./webcaller configure Change settings with a safety backup + ./webcaller check-update Look for a newer Docker release + ./webcaller update [vX.Y.Z] Back up and install a reviewed release + ./webcaller backup Consistent private snapshot + ./webcaller restore backups/FILE Restore matching bundle/config/data + ./webcaller stop Stop this installation; retain data + ./webcaller logs Recent diagnostics + +Requires Linux x86-64/ARM64, Python 3, Docker Engine and Compose v2.20+. +No Docker Desktop, remote Docker contexts or Windows/macOS support. +''' + +def main(argv=None): + args=list(sys.argv[1:] if argv is None else argv) + if not args: + if not sys.stdin.isatty():print(HELP);return + print(HELP);options=['setup','start','status','doctor','instructions','qr','configure','check-update','update','backup','restore','stop','logs'] + print('\n'+ '\n'.join(str(i)+'. '+v for i,v in enumerate(options,1))) + selected=input('Choose a number (Enter to exit): ').strip() + if not selected:return + if not selected.isdigit() or not 1<=int(selected)<=len(options):raise FriendlyError('Choose one of the displayed numbers.') + args=[options[int(selected)-1]] + command=args[0] + if command in ['help','--help','-h']:print(HELP);return + if command=='version':print((ROOT/'VERSION').read_text().strip());return + if command not in ['setup','start','status','doctor','instructions','qr','configure','check-update','update','backup','restore','stop','logs']:raise FriendlyError('Unknown command. Run ./webcaller help.') + fresh_restore=command=='restore' and not configured() + if command!='setup' and not fresh_restore:need_setup() + info=preflight() + if fresh_restore: + value=args[1] if len(args)>1 else input('Path to your private backup archive: ').strip();archive=pathlib.Path(value).expanduser().resolve() + if not archive.is_file():raise FriendlyError('Backup file not found.') + old_image=image();meta=json.loads(helper('backup-info',archive=archive,capture=True)) + if docker('ps','-a','--filter','label=com.docker.compose.project='+meta['project'],'--format','{{.ID}}',capture=True).strip() or docker('volume','ls','--filter','label=com.docker.compose.project='+meta['project'],'-q',capture=True).strip():raise FriendlyError('That installation already exists on this server. Use its original folder instead of creating a second copy.') + print('Recover version '+meta['version']+' from '+meta['created']+'. Only use a private backup you trust. No phone keys will be generated.') + if not confirm('Restore this installation onto this Linux server?',token='RESTORE'):return + helper('restore-seed',root=True,archive=archive,setup_image=old_image) + restore_snapshot(archive,setup_image=old_image);ports();start() + print('Recovered. Run ./webcaller doctor and keep existing phone browser data. The backup cannot recover private keys lost from a phone.') + return + if command=='setup': + if configured():raise FriendlyError('Already set up. Use configure to change settings or start to start it; do not regenerate credentials.') + helper('init') + print('\nConfiguration saved. Checking local ports…') + ports() + if 'turn' in env(ROOT/'.env').get('COMPOSE_PROFILES','') and 'rootless' in str(info.get('SecurityOptions','')):raise FriendlyError('Rootless Docker cannot use this host-network TURN recipe. Use configure to choose an external relay, or install standard Docker Engine.') + if confirm('Start WebCaller now?',default=True): + start(check_ports=True);doctor();instructions();helper('qr') + else:instructions();print('When ready, run ./webcaller start.') + elif command=='start': + start(check_ports=not running());print('WebCaller started. Run ./webcaller doctor, then ./webcaller qr.') + elif command=='status':print('WebCaller '+(ROOT/'VERSION').read_text().strip());compose('ps') + elif command=='logs':print('Check logs for identifiers before sharing them. Press Ctrl+C to leave.');compose('logs','--tail=80') + elif command=='stop':compose('stop');print('Stopped. Saved data and settings remain. Start again with ./webcaller start.') + elif command=='qr':helper('qr') + elif command=='instructions':instructions() + elif command=='doctor':return 1 if doctor() else 0 + elif command=='check-update': + new=updates();print('New Docker release: '+new+'\nRead: https://github.com/adlererik/WebCaller/releases/tag/'+new+'\nInstall: ./webcaller update '+new if new else 'You have the newest published stable Docker bundle. Source-only releases are not Docker updates.') + elif command=='backup': + if confirm('A consistent backup briefly stops this installation and interrupts calls. Continue?'):snapshot() + elif command in ['configure','update','restore']: + if command=='configure':helper('plan-configure') + if command=='update': + version=args[1] if len(args)>1 else updates() + if not version:print('No newer stable Docker release is available.');return + if not re.fullmatch(r'v\d+\.\d+\.\d+',version):raise FriendlyError('Use an actual release version, such as v0.20.0.') + print('Release notes: https://github.com/adlererik/WebCaller/releases/tag/'+version) + helper('prepare-update',version);stage=ROOT/'.updates'/version;compose('pull',stage=stage) + archive=None + if command=='restore': + value=args[1] if len(args)>1 else input('Path to your private backup archive: ').strip();archive=pathlib.Path(value).expanduser();archive=(ROOT/archive).resolve() if not archive.is_absolute() else archive.resolve() + if not archive.is_file():raise FriendlyError('Backup file not found.') + meta=json.loads(helper('backup-info',archive=archive,capture=True)) + if meta['project']!=project():raise FriendlyError('This backup belongs to another installation. Use the matching installation folder.') + print('Restore version '+meta['version']+' from '+meta['created']+'. Only use a backup you trust. Restoring discards server changes made since that snapshot.') + if not confirm('This briefly stops WebCaller. A safety backup is made first. Continue?',token='RESTORE' if command=='restore' else None):return + old_image=image();was_running=running();compose('stop') + try:backup=snapshot(stopped=True) + except BaseException: + if was_running:start() + raise + try: + if command=='update':helper('apply-update',version) + elif command=='configure':helper('configure','--settings','/bundle/.planned-settings.json');ports() + else:restore_snapshot(archive) + if was_running:start() + except BaseException: + print('The change did not complete. Restoring the safety snapshot…') + try: + compose('stop');restore_snapshot(backup,setup_image=old_image) + if was_running:start() + except BaseException:raise FriendlyError('Automatic recovery needs attention. Keep the private backup at '+str(backup)+' and follow the restore guide. No other installation was modified.') + raise FriendlyError('The change failed or was cancelled. Previous bundle, settings and data were restored. Backup: '+str(backup)) + print('Completed. Phone identities were not regenerated. Refresh WebCaller without clearing browser site data.') + if command=='configure':instructions() + return 0 + +if __name__=='__main__': + try: + ROOT.mkdir(exist_ok=True) + if len(sys.argv)>1 and sys.argv[1] in ['--help','-h','help','version']:sys.exit(main() or 0) + with (ROOT/'.webcaller.lock').open('a') as lock: + try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError:raise FriendlyError('Another WebCaller maintenance command is running. Let it finish first.') + try:sys.exit(main() or 0) + finally:(ROOT/'.planned-settings.json').unlink(missing_ok=True) + except KeyboardInterrupt:print('\nCancelled. Check ./webcaller status before trying again.');sys.exit(1) + except (FriendlyError,OSError,ValueError,KeyError) as e: + print('\n'+('ACTION NEEDED: '+str(e) if isinstance(e,FriendlyError) else 'The operation could not complete. Check Docker access, your connection and ./webcaller doctor. Credentials were not printed.'),file=sys.stderr);sys.exit(1) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 82b45fa..7ba94c4 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -66,3 +66,7 @@ The [Docker bundle](../docker/README.md) separates release-pinned `images.env` f The per-file maximum is **200 MiB (209,715,200 bytes)**, shown as 200 MB in the UI. Fresh defaults reserve 1024 MiB per sender and 4096 MiB globally; these are totals across pending and committed files, not extra capacity per conversation. Disk use also includes ciphertext tags, database pages and journal overhead. Set limits for your available disk. A lower existing configured quota is preserved and may prevent a 200 MB file from being accepted. When upgrading an older source installation whose private `.env` explicitly says `ATTACHMENT_USER_QUOTA_MB=100`, change it to `1024` (or another suitable value at least `200`) if you want full-sized files. The global quota must also have enough free reservation. For the prebuilt stack edit `config/app.env`, then run `./webcaller start` to recreate the app with the new environment. For native systemd, restart the existing service after changing `.env`. Preserve all owner, push, TURN and ntfy credentials. No change to proxy upload limits is needed for the app's small chunk requests; each HTTP body remains at most 65,552 bytes. + +## Guided Docker configuration + +For v0.20.0 Linux bundles, prefer `./webcaller configure` to hand-editing files. The private `.env` stores the persistent `COMPOSE_PROJECT_NAME`, service profiles and host-side loopback ports; `config/app.env`, `turn.env`, `ntfy.yml`, `Caddyfile` and `tunnel-token` hold the generated configuration. The helper preserves owner/VAPID credentials and project identity when reconfiguring; it does not reset phone identities. Configuration, snapshots and tokens must not be committed or copied into a public source tree. Changing a hostname changes the browser origin and may require phone setup again. [Linux guide](../docker/README.md). diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index a32c804..56dc9e6 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -33,4 +33,10 @@ Original WebCaller source keeps its MIT notice; the combined libsignal distribut ## Source-only releases -The application package and the last published prebuilt Docker bundle may have different versions. v0.19.0 publishes source/native archives; `docker/VERSION` and `docker/images.env` remain pinned to the published v0.18.0 images. Do not label an older image as the new source release. `node scripts/package-release.mjs v0.19.0` creates the complete source TAR/ZIP and checksums without a Docker bundle. Supplying image digests additionally requires a matching Docker bundle version. Container publishing remains an explicit workflow dispatch, separate from ordinary CI builds. +The source package and prebuilt bundle must agree for a Docker release. v0.19.0 was source-only; v0.20.0 refreshes the matching Linux bundle/images. The packager refuses a mismatched optional Docker bundle. Container publishing remains an explicit workflow dispatch, separate from ordinary CI builds. + +## Linux release and screenshot development (v0.20.0) + +The source package, `docker/VERSION` and project image tags match at v0.20.0. Publish reviewed x86-64/ARM64 images through the explicit prebuilt workflow after CI and the release tag are ready, then supply their manifest digests to `node scripts/package-release.mjs v0.20.0 IMAGE-DIGESTS.json`. The generated Docker TAR/ZIP pins project/supporting images; no deployment configuration is packaged. Build the complete source offer before container/release assembly. Never overwrite a published version tag/image. + +`node scripts/preview-release.mjs` serves synthetic screenshot fixtures only on loopback. It strips application startup and uses the shipped styles/icons/message renderer without API requests, real accounts, keys, service worker or notifications. Browser-capture desktop 1280×820 and mobile 390×844 views, then the overview composition. See [image provenance](images/README.md). These scripts are development previews, not a server installation. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 7b7378a..d803515 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -1,4 +1,4 @@ -# WebCaller feature reference — v0.19.0 +# WebCaller feature reference — v0.20.0 A browser phone for one-to-one calls and conversations on Android, iPhone and desktop. The UI follows familiar Signal-style patterns; it is not an official Signal client. [User guide](USER_GUIDE.md) · [Security](SECURITY.md). @@ -83,3 +83,9 @@ STUN/ICE selects direct media when possible; TURN carries encrypted media when n ## Not included Groups/federation, native mobile call integration, calls to Signal/WhatsApp accounts, compulsory phone numbers, automatic key transparency, Sealed Sender, traffic-analysis anonymity, guaranteed background ringing, universal earpiece/screenshot control, guaranteed zero traces or independent security certification. This is a one-to-one self-hosted browser phone. [Verification](VERIFICATION.md). + +## Guided Linux server edition (v0.20.0) + +Release-matched x86-64/ARM64 Docker images and a digest-pinned installer provide a four-part setup wizard, numbered maintenance menu, local-engine/Linux/port checks, per-installation Compose identities and a DNS/proxy/firewall checklist. Optional Caddy HTTPS, coturn, ntfy and Cloudflare connector are chosen explicitly. No domain/DNS account is created or existing website replaced. Native services remain a separate installation option. + +The assistant supports credential-preserving reconfiguration, local/public HTTPS diagnostics, consistent private snapshots, trusted snapshot restore and stable Docker-release discovery. Updates pull first, snapshot matching configuration/data/bundle files and recover that state if startup fails. Snapshots are private but not password-encrypted; phone private keys remain on the phones. Rootless Docker requires an external relay. TURN-TLS certificates/renewal and real two-network call/locked-phone tests remain additional steps. [Linux walkthrough](../docker/README.md). diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 8625bc2..796ce2d 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -1,78 +1,78 @@ -# Install WebCaller v0.19.0 +# Install WebCaller v0.20.0 -**v0.19.0 is a source/native release.** It includes stickers and the latest sending/timer fixes. No new prebuilt Docker image or Docker bundle is published. The previous [v0.18.0 Docker release](https://github.com/adlererik/WebCaller/releases/tag/v0.18.0) remains available, with its own matching guide and images. +WebCaller has two installation paths. Both run the same browser phone and encryption; choose the one that fits your server. -Phone users open your website; they do not install a WebCaller phone app. iPhone background browser alerts require adding the website to the Home Screen. Optional ntfy alerts require the separate ntfy client. The source server can run natively or be built into a container by an operator; neither requires a new prebuilt Docker release. +| Choice | What you need | Guide | +|---|---|---| +| **Guided Linux Docker edition** | Linux x86-64/ARM64, Docker Engine + Compose, Python 3.10+ | [Start here](../docker/README.md) — ready-made images, setup questions, diagnostics, backups, settings changes and updates. | +| **Native Debian/source** | Debian 12/13, Node 24, Python 3; Git for a source checkout | [Native instructions](INSTALL_NATIVE.md) — regular system services without Docker. Existing native installations can stay native. | -## Before you start - -You need a server, an HTTPS hostname under your control and a reachable TURN relay for calls across difficult networks. Debian 12/13 is the documented native target. A home server behind CGNAT can host the website through a Tunnel but normally needs a public TURN relay elsewhere. A Tunnel does not relay WebRTC media. +Phone users open your website. They do not need Docker, an account password, a SIM or a WebCaller phone app. iPhone background browser alerts require Add to Home Screen. Optional ntfy extra ringing requires its separate client. [Phone guide](USER_GUIDE.md). -The native guide uses Node 24, Python 3 and Git. Browser crypto/WASM is bundled, so you do not need Rust or a paid sticker API. Use a current phone browser supporting Web Crypto Ed25519. The ready-made sticker artwork is served by your installation, with no sticker-provider login or bot token. +## Before you start -For a fresh installation, use a separate directory and hostname if another app already exists. A different path on the same hostname does not isolate browser keys. If upgrading an existing libsignal v0.18.0 installation, use the normal [backed-up source update](OPERATIONS.md#native-libsignal-updates), preserve its configuration and reload both phones once. No account/history reset is needed. v0.17.1 and older use Olm and need the separate [migration procedure](APPROVED_CUTOVER.md). +You need a server, an HTTPS hostname you control and a reachable TURN call relay for difficult networks. A fresh public Linux VPS is the simplest complete Docker arrangement. A home server can expose its website through an HTTPS Tunnel but may need a public relay elsewhere if behind CGNAT. An HTTP Tunnel does not relay WebRTC media. -## Recommended: native Debian, no Docker +The installer does not register domains, change your DNS account, bypass CGNAT or replace an existing website. The wizard explains each choice and prints the routes and ports for your answers. Networking that requires your router/DNS account still needs your action. -Follow [Native installation](INSTALL_NATIVE.md) from start to finish. It covers prerequisites, an isolated Node runtime, the source, private configuration, a boot service, HTTPS and the private first-phone QR. It avoids changing system Node or another website. For TURN use an existing REST relay or the native coturn instructions in [Networking](NETWORKING.md). Optional ntfy has its own [native installer](EXTRA_RINGING.md). +## Recommended: guided Linux download -Choose one way to get the source: +Use the uploaded **WebCaller-Docker-v0.20.0.tar.gz** from the [release](https://github.com/adlererik/WebCaller/releases/tag/v0.20.0), plus **SHA256SUMS.txt**. The small archive downloads matching images from GitHub Container Registry. It is not an offline image bundle. -- **Uploaded release archive:** download **WebCaller-v0.19.0.tar.gz** or **WebCaller-v0.19.0.zip** from the [release](https://github.com/adlererik/WebCaller/releases/tag/v0.19.0), together with **SHA256SUMS.txt**. These include the exact upstream source and a matching corresponding-source download. Extract into a new empty directory. They contain no private configuration, so setup generates your own secrets. -- **Git checkout:** recursively clone the tagged release. GitHub's automatic **Source code** ZIP/TAR downloads omit the upstream submodule; use the uploaded assets above or this command: +In a new empty folder on your Linux server: ```sh -git clone --recurse-submodules --branch v0.19.0 https://github.com/adlererik/WebCaller.git WebCaller -cd WebCaller +curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.20.0/WebCaller-Docker-v0.20.0.tar.gz +curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.20.0/SHA256SUMS.txt +sha256sum --ignore-missing -c SHA256SUMS.txt ``` -For an uploaded TAR archive on Linux, run these in a new download folder after installing `curl` as shown in the native guide: +Continue when the Docker archive reports **OK**: ```sh -curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.19.0/WebCaller-v0.19.0.tar.gz -curl -fLO https://github.com/adlererik/WebCaller/releases/download/v0.19.0/SHA256SUMS.txt -sha256sum --ignore-missing -c SHA256SUMS.txt -tar -xzf WebCaller-v0.19.0.tar.gz -cd WebCaller-v0.19.0 +tar -xzf WebCaller-Docker-v0.20.0.tar.gz +cd WebCaller-Docker-v0.20.0 +./webcaller setup ``` -Continue only after the checksum says **OK**. Use this extracted folder as the project folder, or use the native guide's `/opt/webcaller` location consistently. Do not mix commands between two different copies. +The wizard covers your website, HTTPS access, call relay and optional extra ringing. It generates private credentials, checks ports and can start the stack. Then run `./webcaller doctor` and scan `./webcaller qr` with the first phone. Invite other people from that phone. Run `./webcaller` without arguments for a numbered menu. -On a system where Node 24 is already installed, the application steps are: +Linux x86-64/ARM64 only: this launcher does not support Docker Desktop, Windows/macOS, remote Docker contexts or 32-bit ARM. Docker Engine itself is installed/updated through your distribution's supported instructions. Rootless Docker needs an external relay; the included TURN host-network recipe requires standard Engine networking. [Complete walkthrough, troubleshooting and recovery](../docker/README.md). -```sh -npm ci --ignore-scripts -npm run setup -``` +## Source/native download -For a **Git checkout**, also run `npm run prepare:source`. The uploaded release archive already contains `public/preview-source.tar.gz`; do not run that Git-based packaging command in an extracted archive without `.git` metadata. Preserve the supplied source offer/licenses. [Licensing](../LICENSING.md). +The uploaded **WebCaller-v0.20.0.tar.gz** and **WebCaller-v0.20.0.zip** contain complete application source, browser WASM, the exact pinned upstream source and matching corresponding-source offer. They do not contain server credentials, configuration, conversations or phone identities. -Edit `.env` for your own HTTPS hostname, listening address/port and relay. Keep `WEBCALLER_CRYPTO_ENGINE=libsignal-pqxdh-v1` and the generated owner/VAPID secrets. Run `npm start` for an initial foreground check, then follow the native guide for your boot service, HTTPS and first-phone setup. The overview commands alone do not configure a public certificate, proxy, firewall or TURN server for you. +Check the chosen archive against the release's **SHA256SUMS.txt**, extract it into an empty folder and follow [Native Debian installation](INSTALL_NATIVE.md). Rust is not needed to run the bundled browser crypto. Use the uploaded complete release assets; GitHub's automatic Source code ZIP/TAR omits submodules. -## Optional alternatives +For a developer checkout: -For the **previous prebuilt v0.18.0 Docker stack**, use [its matching guide](../docker/README.md) and `WebCaller-Docker-v0.18.0.tar.gz` from that release. Its launcher pulls the published digest-pinned images; it does not include v0.19.0 stickers/fixes. Do not ask its updater for a v0.19.0 bundle that does not exist. +```sh +git clone --recurse-submodules --branch v0.20.0 https://github.com/adlererik/WebCaller.git +cd WebCaller +npm ci --ignore-scripts +npm run setup +npm run prepare:source +``` -Operators who want the current source in a container can review the root source-build Compose recipe and run `docker compose up -d --build`. This builds locally; it does not pull a v0.19.0 prebuilt image or require changing a working native installation. Do not start native and container listeners on the same port. Networking/HTTPS requirements still apply. +These commands assume Node 24. `prepare:source` is for a Git checkout; skip it in an unchanged extracted release archive without `.git`, because that archive already includes the source offer. [Development and rebuilding](DEVELOPMENT.md). -## Set up the first phone +## Updates without losing your setup -Generate the private setup QR using the native guide. Scan it with the first phone's camera; the long owner code fills automatically. Choose a display name. Keep this QR private: it grants first-phone setup access. +For a v0.20.0 Docker installation, use `./webcaller check-update` and `./webcaller update`. The assistant discovers actual stable Docker bundles, downloads first, makes a consistent private snapshot and preserves configuration. Failed startup triggers matching prior bundle/configuration/server-data recovery. Use `configure`, `backup` and `restore` for guided maintenance. Read the [full update/restore instructions](../docker/README.md#updates-and-recovery), including the older v0.18.0 launcher caveat. -Then choose **Invite someone**. Send that invitation through a channel you trust; the invitee accepts and chooses a name. They do not need SSH, a server password, owner code or publishing token. Alternatively choose your own calling code in Settings and let someone dial it. Codes are addresses, not secrets or proof of identity. +Native installations use the [native update procedure](OPERATIONS.md#native-libsignal-updates), retaining their service, `.env`, data and existing networking. Installing or downloading a Docker release never converts a native installation. -On **iPhone**, follow Add to Home Screen and use that icon for calls/alerts. Safari and Home Screen profiles can differ, including when ntfy opens a link. If an alert says to open your usual phone, use the existing Home Screen icon rather than creating another identity. If the first phone is an iPhone, add the site before enrollment and open the owner setup there, or enroll a desktop first and invite it. +Earlier **Olm v0.17.x or older** needs an explicit [backed-up migration](APPROVED_CUTOVER.md), not an ordinary update. Do not clear browser site data or regenerate secrets to fix a connection issue. -On **Android**, accept in the browser you intend to keep using and allow microphone/camera and notifications when requested. In Settings, send the alert test, lock the screen, tap the notice and confirm only if you actually heard it. Optional ntfy has its own guided test. No push urgency bypasses OS restrictions. +Server backups contain credentials and are not password-encrypted. Keep them on protected storage. They cannot recover private identities/history erased from phones. Updates/restores interrupt calls; a restore returns server state to the snapshot rather than preserving later changes. -## Check it before relying on it +## Check the first two phones -1. Send a message each way, refresh and confirm contacts/history remain. -2. Tap the folded-corner sticker icon, choose a pack and tap a sticker. Try Favorites and both Cutouts/All views. -3. Call both ways and compare all four SAS words. Tap the chat name/header to compare the full safety fingerprint through a trusted channel. -4. Send a photo during the call and confirm speech stays clear. -5. Test on different networks, including TURN allocation and actual media delivery. -6. Test locked-screen sound, notification opening/answering, front/back cameras and audio output on each phone. -7. Walk from Wi-Fi to cellular and back during a call; confirm recovery without redialing. A short radio gap remains possible. +1. Enroll the first phone with the private QR; send an invitation to the second phone. +2. Exchange a text, a sticker and a photo. Reopen the chat to check retained media. +3. Call both ways, compare all four SAS words and try front/back cameras. Tap the chat name to compare the full fingerprint through a trusted channel. +4. Test one phone on Wi-Fi and one on cellular. A local health check or TURN allocation is not proof of complete media delivery. +5. Test locked-screen alerts, notification opening/answering and Wi-Fi/cellular recovery. Phone permissions and OS policy still apply. -Keep browser site data: it contains the identity, keys and saved conversations. Reloading after an update is different from clearing that data. [User guide](USER_GUIDE.md) · [Troubleshooting](OPERATIONS.md) · [Security](SECURITY.md). +Keep using the same browser/Home Screen icon. Refresh after an app update; do not clear site data. [All features](FEATURES.md) · [Security](SECURITY.md) · [Troubleshooting](OPERATIONS.md). diff --git a/docs/INSTALL_NATIVE.md b/docs/INSTALL_NATIVE.md index a255cf5..b8fed8d 100644 --- a/docs/INSTALL_NATIVE.md +++ b/docs/INSTALL_NATIVE.md @@ -9,11 +9,11 @@ sudo apt update sudo apt install -y git ca-certificates curl xz-utils nano python3 python3-venv if sudo test -e /opt/webcaller; then echo 'Stop: the target directory already exists.'; exit 1; fi sudo install -d -m 755 -o "$(id -un)" -g "$(id -gn)" /opt/webcaller -git clone --recurse-submodules --branch v0.19.0 https://github.com/adlererik/WebCaller.git /opt/webcaller +git clone --recurse-submodules --branch v0.20.0 https://github.com/adlererik/WebCaller.git /opt/webcaller cd /opt/webcaller ``` -**Release archive alternative:** instead of the `git clone` command, extract the uploaded `WebCaller-v0.19.0.tar.gz`/`.zip` into the empty `/opt/webcaller` folder. Use the uploaded release asset rather than GitHub's automatic Source code archive, and check its SHA-256 against the release's `SHA256SUMS.txt`. The uploaded asset includes pinned upstream source and `public/preview-source.tar.gz`. Skip `npm run prepare:source` below when using an extracted archive without `.git`; it is a Git-checkout build step. [Download choices](INSTALL.md). +**Release archive alternative:** instead of the `git clone` command, extract the uploaded `WebCaller-v0.20.0.tar.gz`/`.zip` into the empty `/opt/webcaller` folder. Use the uploaded release asset rather than GitHub's automatic Source code archive, and check its SHA-256 against the release's `SHA256SUMS.txt`. The uploaded asset includes pinned upstream source and `public/preview-source.tar.gz`. Skip `npm run prepare:source` below when using an extracted archive without `.git`; it is a Git-checkout build step. [Download choices](INSTALL.md). Run each command only after the previous succeeds. If the existence check fails, stop: review the existing directory rather than overwriting it. For an existing Olm deployment, stop here and read [the migration guide](APPROVED_CUTOVER.md). Use a different new folder if needed and substitute that path throughout this guide. GitHub ZIPs omit source submodules; the recursive clone includes the exact official source needed for the source offer. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index d58a03c..931f6a3 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -40,11 +40,11 @@ Replace the version placeholder with a reviewed actual tag. Preserve any local m For Docker, use its explicit-version updater and [volume/config backup guidance](../docker/README.md). The new bundle format deliberately blocks the old Olm updater from blindly applying this protocol change. `down -v` deletes volumes; do not use it as a restart command. -## Update to v0.19.0 +## Update to v0.20.0 -For existing v0.18.0 libsignal installations, this is a normal backed-up source/native update: preserve `.env`, the database, browser site data, identities, service/proxy, TURN and ntfy configuration. No conversation purge or new phone enrollment is required. Reload both browsers once after the code update so they understand the shared-chat sticker context. Old per-file stickers remain readable. +For existing v0.18.0/v0.19.0 libsignal installations, this is a normal backed-up source/native update: preserve `.env`, the database, browser site data, identities, service/proxy, TURN and ntfy configuration. No conversation purge or new phone enrollment is required. Reload both browsers once after the code update so they understand the shared-chat sticker context. Old per-file stickers remain readable. -There is no v0.19.0 prebuilt Docker bundle or image. The v0.18.0 Docker release remains available; its updater cannot apply a source-only release. A native source update does not require switching to Docker. +v0.20.0 adds a matching guided Linux Docker bundle and images. Existing native services can stay native; a source update does not require Docker. Existing v0.18.0 Docker users must make a consistent private manual backup before their first upgrade to the new assistant; see the [first-upgrade instructions](../docker/README.md#updates-and-recovery). v0.19.0 was source-only. ### Sticker sending or reactions @@ -95,3 +95,13 @@ A randomly generated path reduces blind discovery, not endpoint/traffic exposure New conversation defaults are one-hour disappearing messages; Off retains until deletion. Sender countdown starts at send, recipient countdown at first view, so unread encrypted recipient copies can remain longer. Cached ciphertext is reused until its participant deadline/deletion or browser eviction. The server applies quotas and expiration; phones physically purge only when running. Downloads/screenshots/backups remain outside recall. Keep only installations you need enabled. Stopping an optional test service does not require deleting its data or changing production routes. Do not run native and Docker instances against the same SQLite path/port, or restore state while a process still uses it. + +## Guided Linux Docker maintenance (v0.20.0) + +The [Linux assistant](../docker/README.md) handles only its own Docker project. `./webcaller` opens its menu; `status`, `doctor` and `instructions` explain current state and networking. `configure` starts with current answers, preserves credentials and takes a full safety snapshot before recreating services. Changing the hostname changes the phone browser origin and can require re-enrollment. + +`backup` briefly stops services for a consistent snapshot of bundle files, private config and existing named volumes, then resumes a previously running stack. The resulting archive contains credentials, is mode 0600 and is not password-encrypted. Copy it to protected off-server storage. `restore backups/FILE.tar.gz` verifies hashes, paths and project identity, takes a safety snapshot and requires an explicit RESTORE confirmation. A fresh replacement server can restore a trusted snapshot into an unconfigured bundle before setup; duplicate project resources are refused. + +`check-update` discovers stable releases with actual Docker bundles; `update` downloads/verifies images before downtime, snapshots the complete matching server state and recovers it on failed startup. No automatic downgrade across an unreviewed protocol/bundle boundary is supported. Recovery restores server state at the snapshot; it does not roll back phone ratchets or preserve later server changes. If recovery also fails, keep the backup and follow the full restore guide. Existing native services are never changed. + +The old v0.18.0 launcher predates automatic snapshots: make a consistent private manual backup before using its updater to reach v0.20.0. Do not claim the new safeguards apply retroactively to that first upgrade. Keep prior images available for offline recovery, enough disk for snapshots and the same browser site data on phones. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index e6cfd0e..09f26c9 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1,6 +1,6 @@ # WebCaller security and encryption -This is the security model for **v0.19.0**, which uses official libsignal **0.105.1**, pinned to commit `1738ead8a12ffe539f6309958123dadb16dc3b95`. It supersedes descriptions of the earlier Olm message transport. The upstream protocol source is unmodified. WebCaller's WASM adapter, storage, application signatures, call handling and SAS composition remain **unaudited**. This document describes mechanisms and boundaries, not a security certification. +This is the security model for **v0.20.0**, which uses official libsignal **0.105.1**, pinned to commit `1738ead8a12ffe539f6309958123dadb16dc3b95`. It supersedes descriptions of the earlier Olm message transport. The upstream protocol source is unmodified. WebCaller's WASM adapter, storage, application signatures, call handling and SAS composition remain **unaudited**. This document describes mechanisms and boundaries, not a security certification. ## What end-to-end encryption means here @@ -110,3 +110,11 @@ Stickers reuse authenticated AES-256-GCM attachment chunks and Signal-ratcheted Sticker manifests now use the existing chat ratchet rather than consuming a new one-time PQXDH bundle for each image. Each sticker still has its own random AES-256-GCM attachment key. Auxiliary sticker-link and file-progress streams are separate per-contact ratchets; authenticated payloads retain their call/transfer identifiers and receivers reject mismatched contexts. Old per-file manifests and per-attempt control envelopes remain readable. Reconnect/resume schedules bounded publication retries without resetting identity pins, reusing claimed prekeys or falling back to plaintext. Starting a genuinely new session with no authenticated starter material still fails closed. This application-session change does not alter libsignal, its WASM binding, media encryption or SAS. Both browsers must load the updated client to receive the new shared-session sticker format. + +## Linux installer and recovery boundary + +v0.20.0 adds a Linux-only Docker assistant without changing the cryptographic core, browser binding, media protocol or SAS. Release bundles pin image digests; updater downloads are bounded/allowlisted, checked against release checksums and limited to expected image namespaces/bundle format. Checksums/digests identify downloaded bytes; they are not independent proof that an authorized publisher is trustworthy. Docker Engine and its socket are a privileged host trust boundary; the helper does not receive the Docker socket, and its archive commands run without container networking. + +Each new installation has a persistent random Compose project name. Maintenance locks and local-engine/project-folder/volume-label checks reduce accidental cross-installation changes. Consistent snapshots stop this project's services and include matching bundle/configuration/server-volume data. They contain secrets, are private by filesystem permissions and are **not password-encrypted**. A restore is an operator-authorized replacement of server state, not a phone-key backup. Archive verification rejects corruption, path escapes, links, special files, duplicates and excessive counts/sizes before restoring volumes. Only restore trusted snapshots: saved bundle files include executable code. + +Automatic startup recovery restores the prior server snapshot and resumes a previously running stack; it cannot restore browser ratchet/identity state or promise retention of later messages. Keep private independent backups and test recovery. Host networking, router/DNS/firewall configuration, certificate renewal for optional TURN-TLS, browser suspension and actual cross-network media tests remain operational responsibilities. Native services are not migrated by downloading or running this installer in a separate folder. diff --git a/docs/SECURITY_REVIEW.md b/docs/SECURITY_REVIEW.md index 374fbf9..fc2d7f6 100644 --- a/docs/SECURITY_REVIEW.md +++ b/docs/SECURITY_REVIEW.md @@ -1,6 +1,6 @@ # Source review and limits -Reviewed against the libsignal/PQXDH integration, Ed25519 application signatures and v0.19.0 release changes through 28 October 2026. This is a maintainer-assisted implementation review and test record, **not an independent audit, proof or Signal endorsement**. Historical stable Olm reviews do not certify this adapter. +Reviewed against the libsignal/PQXDH integration, Ed25519 application signatures and v0.20.0 release changes through 29 October 2026. This is a maintainer-assisted implementation review and test record, **not an independent audit, proof or Signal endorsement**. Historical stable Olm reviews do not certify this adapter. ## Protections checked @@ -29,3 +29,7 @@ Release-matched Docker bundles explicitly select the libsignal engine and use a The sticker update additionally checks authenticated AES-GCM/Signal manifests, bounded encrypted data-channel frames and cache acknowledgements; zero-unused-prekey sending through an established chat; backwards reading of old file-scoped stickers; rejected context substitutions without committing state; automatic publication retries without identity replacement/prekey resurrection; and fail-closed wording for a genuinely new session without starter material. Physical-phone acceptance and an independent composition audit remain separate from these checks. + +## Linux assistant review additions + +Added checks cover credential-preserving configuration changes, persistent installation identities, matching snapshot round trips/fresh-folder seeding, rejection of archive traversal/links/special files/duplicates/corruption, maintenance recovery on failed changes and refusal of unsupported hosts/remote engines. Disposable Linux container tests exercise setup, relay/alert configuration, persistence and backup/restore with synthetic identities. This is implementation testing, not an independent audit; backups remain sensitive plaintext archives protected by filesystem permissions and external storage policy. diff --git a/docs/STICKERS.md b/docs/STICKERS.md index f93d785..4a7b946 100644 --- a/docs/STICKERS.md +++ b/docs/STICKERS.md @@ -31,4 +31,4 @@ Put appropriately authorized WebP files under `public/stickers// diff --git a/docs/images/desktop-chat.jpg b/docs/images/desktop-chat.jpg new file mode 100644 index 0000000..cbb5223 Binary files /dev/null and b/docs/images/desktop-chat.jpg differ diff --git a/docs/images/mobile-chat.jpg b/docs/images/mobile-chat.jpg new file mode 100644 index 0000000..4a3b201 Binary files /dev/null and b/docs/images/mobile-chat.jpg differ diff --git a/docs/images/mobile-home.jpg b/docs/images/mobile-home.jpg new file mode 100644 index 0000000..b907391 Binary files /dev/null and b/docs/images/mobile-home.jpg differ diff --git a/docs/images/overview.jpg b/docs/images/overview.jpg new file mode 100644 index 0000000..f0020fa Binary files /dev/null and b/docs/images/overview.jpg differ diff --git a/package-lock.json b/package-lock.json index 39eb836..8b601cc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "webcaller", - "version": "0.19.0", + "version": "0.20.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "webcaller", - "version": "0.19.0", + "version": "0.20.0", "license": "AGPL-3.0-only", "dependencies": { "web-push": "3.6.7", diff --git a/package.json b/package.json index b927eec..0763161 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "webcaller", - "version": "0.19.0", + "version": "0.20.0", "private": true, "type": "module", "engines": { diff --git a/public/index.html b/public/index.html index 68416a4..2492522 100644 --- a/public/index.html +++ b/public/index.html @@ -20,6 +20,8 @@ + + diff --git a/public/viewport.css b/public/viewport.css new file mode 100644 index 0000000..c230d72 --- /dev/null +++ b/public/viewport.css @@ -0,0 +1,22 @@ +/* Only the conversation and contact list scroll; the document is an app shell. + VisualViewport supplies the keyboard's usable area on iOS and Android. */ +html { height:100%; overflow:hidden; overscroll-behavior:none; } +body { + position:fixed; top:var(--app-viewport-top,0px); left:0; width:100%; + height:100vh; height:var(--app-viewport-height,100dvh); + display:flex; flex-direction:column; overflow:hidden; + padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); +} +.app { flex:1; width:100%; height:auto; min-height:0; overflow:hidden; } +.main,.conversation,.messages { min-height:0; } +.conversation { overflow:hidden; } +.chat-header,.privacy-strip,.selection-bar { flex-shrink:0; } +.empty { height:100%; overflow-y:auto; } +.preview-disclosure { flex:none; padding:3px 10px 5px; text-align:center; font-size:10px; line-height:1.5; background:var(--surface,#fafbfe); } +.preview-disclosure a { color:var(--soft-ink,#69727e); text-decoration:none; } +.preview-disclosure a:hover { text-decoration:underline; } +/* The shell already reserves the home indicator inset. */ +:root .composer-note { padding-bottom:8px; } +@media(max-width:760px) { + :root .sidebar { padding-bottom:18px; overflow-y:auto; overscroll-behavior:contain; } +} diff --git a/public/viewport.js b/public/viewport.js new file mode 100644 index 0000000..62c4278 --- /dev/null +++ b/public/viewport.js @@ -0,0 +1,64 @@ +// Mobile keyboards resize the visual viewport, not always the layout viewport. +// Keep its offset/height out of document flow so focus cannot strand a scrolled +// header. No touch interception: scrolling messages, dialogs and zoom still work. +export function appViewport({window:win,document:doc}) { + const viewport=win.visualViewport,style=doc.documentElement.style; + let frame=null,disposed=false,keyboardWasOpen=false;const timers=new Set(),listeners=[]; + const unzoomed=()=>!viewport||Math.abs(viewport.scale-1)<0.01; + const editing=()=>!!doc.activeElement?.matches('textarea,input:not([type=button]):not([type=submit]):not([type=checkbox]):not([type=radio]),[contenteditable="true"]'); + const keyboardOpen=()=>!!viewport&&editing()&&Math.max(doc.documentElement.clientHeight||0,win.innerHeight||0)-viewport.height>100; + function restoreRoot() { + if(win.scrollX||win.scrollY)win.scrollTo({left:0,top:0,behavior:'instant'}); + } + function update() { + frame=null;if(disposed||!unzoomed())return; + const keyboard=keyboardOpen(); + // Android's Back/keyboard-dismiss button can leave the textarea focused. + // Restore the root when the usable height recovers in that case too. + if(keyboardWasOpen&&!keyboard)restoreRoot(); + keyboardWasOpen=keyboard; + const messages=doc.getElementById('messages'); + const atEnd=messages&&messages.scrollHeight-messages.clientHeight-messages.scrollTop<32; + if(viewport&&Number.isFinite(viewport.height)&&viewport.height>0) { + style.setProperty('--app-viewport-height',`${viewport.height}px`); + style.setProperty('--app-viewport-top',`${Math.max(0,viewport.offsetTop||0)}px`); + } + // Read after the shell resizes. Preserve an older-message scroll position. + if(atEnd)messages.scrollTop=messages.scrollHeight; + } + function schedule() { + if(!disposed&&frame===null)frame=win.requestAnimationFrame(update); + } + function settle() { + if(disposed||!unzoomed())return; + // iOS can retain a root scroll offset after focus ends. Never reset an + // inner scroller, a live input's focus pan, or a user's pinch zoom. + if(!editing()||!keyboardOpen())restoreRoot(); + schedule(); + } + function focusChanged() { + schedule(); + for(const id of timers)win.clearTimeout(id);timers.clear(); + // Cover browsers which report their final keyboard-close geometry late. + for(const ms of [100,350,700]) { + const id=win.setTimeout(()=>{timers.delete(id);settle();},ms);timers.add(id); + } + } + function listen(target,event,handler) { + target?.addEventListener(event,handler,{passive:true});listeners.push([target,event,handler]); + } + listen(viewport,'resize',schedule);listen(viewport,'scroll',schedule); + listen(win,'resize',schedule);listen(win,'orientationchange',focusChanged); + listen(win,'pageshow',focusChanged); + listen(doc,'focusin',focusChanged);listen(doc,'focusout',focusChanged); + listen(doc,'visibilitychange',()=>{if(doc.visibilityState==='visible')focusChanged();}); + update(); + return {dispose(){ + disposed=true;if(frame!==null)win.cancelAnimationFrame(frame); + for(const id of timers)win.clearTimeout(id); + for(const [target,event,handler]of listeners)target?.removeEventListener(event,handler); + style.removeProperty('--app-viewport-height');style.removeProperty('--app-viewport-top'); + }}; +} + +if(typeof window!=='undefined'&&typeof document!=='undefined')appViewport({window,document}); diff --git a/scripts/docker-setup.py b/scripts/docker-setup.py index e6a9e04..8cc07f6 100644 --- a/scripts/docker-setup.py +++ b/scripts/docker-setup.py @@ -1,16 +1,18 @@ -"""First-run configuration, private QR and reviewed bundle updates. Runs inside Docker.""" -import argparse,contextlib,getpass,hashlib,ipaddress,json,os,pathlib,re,secrets,shutil,subprocess,sys,tarfile,tempfile,urllib.parse,urllib.request +"""Guided Linux configuration and verified updates. Runs inside the setup image.""" +import argparse,contextlib,getpass,hashlib,ipaddress,json,os,pathlib,re,secrets,shutil,socket,struct,subprocess,sys,tarfile,tempfile,urllib.parse,urllib.request FILES={'compose.yaml','images.env','webcaller','README.md','VERSION','LICENSE','LICENSE-MIT','LICENSING.md','THIRD_PARTY_NOTICES.md'} def hostname(value): value=value.lower().strip() - if not re.fullmatch(r'(?=.{1,253}$)[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?',value) or '.' not in value or '..' in value:raise ValueError('Use a domain name without a scheme, port or path.') - if any(not label or len(label)>63 or label.startswith('-') or label.endswith('-') for label in value.split('.')):raise ValueError('Invalid DNS hostname.') + if not re.fullmatch(r'(?=.{1,253}$)[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?',value) or '.' not in value or '..' in value:raise ValueError('Enter a domain name such as phone.example.com, without https:// or a path.') + if any(not label or len(label)>63 or label.startswith('-') or label.endswith('-') for label in value.split('.')):raise ValueError('Check the spelling of the domain name.') return value def validate(s): s=dict(s);s['host']=hostname(s['host']) - if s.get('mode') not in ['proxy','https','tunnel']:raise ValueError('Choose proxy, https or tunnel.') - if s.get('relay') not in ['self','existing','none']:raise ValueError('Choose self, existing or none for TURN.') + if s.get('mode') not in ['proxy','https','tunnel']:raise ValueError('Choose automatic HTTPS, existing proxy or Tunnel.') + if s.get('relay') not in ['self','existing','none']:raise ValueError('Choose self-hosted TURN, an existing relay or configure later.') + s['appPath']=s.get('appPath','/calls').rstrip('/') + if not re.fullmatch(r'/[a-zA-Z0-9][a-zA-Z0-9/_-]{0,99}',s['appPath']) or '//' in s['appPath']:raise ValueError('Use a simple application path such as /calls.') for key,default in [('appPort',8080),('ntfyPort',8094)]: s[key]=int(s.get(key,default)) if not 1024<=s[key]<=65535:raise ValueError('Local ports must be 1024–65535.') @@ -18,68 +20,154 @@ def validate(s): for key in ['publicIP','lanIP']: if s.get(key): ip=ipaddress.ip_address(s[key]) - if ip.version!=4 or (key=='publicIP' and not ip.is_global):raise ValueError('The relay needs a globally routable IPv4; LAN IPv4 is separate.') - if s['relay']=='self' and not s.get('publicIP'):raise ValueError('Enter the relay public IPv4.') + if ip.version!=4 or (key=='publicIP' and not ip.is_global):raise ValueError('The relay needs a public IPv4. A private/router address cannot receive calls from the internet.') + if s['relay']=='self' and not s.get('publicIP'):raise ValueError('Enter the TURN relay’s public IPv4 address.') if s['relay']=='existing': - urls=s.get('turnURLs','').split(',');secret=s.get('turnSecret','') - if not urls or any(not re.fullmatch(r'turns?:[a-zA-Z0-9.-]+(?::[0-9]{1,5})?(?:\?transport=(?:udp|tcp))?',v) for v in urls):raise ValueError('Use comma-separated TURN URLs without embedded credentials.') - if not re.fullmatch(r'[A-Za-z0-9_-]{32,256}',secret):raise ValueError('Use the existing relay REST shared secret, at least 32 characters.') + urls=[u.strip() for u in s.get('turnURLs','').split(',')];secret=s.get('turnSecret','') + if not urls or any(not re.fullmatch(r'turns?:[a-zA-Z0-9.-]+(?::[0-9]{1,5})?(?:\?transport=(?:udp|tcp))?',v) for v in urls):raise ValueError('Use TURN addresses such as turn:relay.example.com:3478?transport=udp, without embedded passwords.') + if not re.fullmatch(r'[A-Za-z0-9_-]{32,256}',secret):raise ValueError('This relay option needs its REST shared secret, at least 32 letters/digits/_/-. Ordinary account passwords are different.') + s['turnURLs']=','.join(urls) if s.get('ntfy'): s['ntfyHost']=hostname(s['ntfyHost']) - if s['host']==s['ntfyHost']:raise ValueError('ntfy needs a separate hostname.') - if s['mode']=='tunnel' and not re.fullmatch(r'[A-Za-z0-9+/=_-]{20,4096}',s.get('tunnelToken','')):raise ValueError('Paste the tunnel connector token privately, without spaces.') + if s['host']==s['ntfyHost']:raise ValueError('Use a different hostname for ntfy, such as notify.example.com.') + if s['mode']=='tunnel' and not re.fullmatch(r'[A-Za-z0-9+/=_-]{20,4096}',s.get('tunnelToken','')):raise ValueError('Paste the Cloudflare connector token privately, without spaces.') if any('\n' in str(v) or '\r' in str(v) for v in s.values()):raise ValueError('Configuration values must be single-line.') return s -def write(path,text,mode=0o600): - path.write_text(text);path.chmod(mode) +def write(path,text,mode=0o600):path.write_text(text);path.chmod(mode) def envtext(values):return ''.join(k+'='+str(v)+'\n' for k,v in values.items()) -def install(settings,bundle,vapid=None): - s=validate(settings);bundle=pathlib.Path(bundle) - if (bundle/'.env').exists() or (bundle/'config').exists():raise ValueError('Already configured or partial setup found. Keep the private files; use start/update rather than regenerating keys.') - if vapid is None: - r=subprocess.run(['node','--input-type=module','-e',"import p from 'web-push';process.stdout.write(JSON.stringify(p.generateVAPIDKeys()))"],cwd='/app',capture_output=True,text=True,check=True) - vapid=json.loads(r.stdout) +def readenv(path):return dict(l.split('=',1) for l in pathlib.Path(path).read_text().splitlines() if '=' in l and not l.startswith('#')) +def current(bundle): + app=readenv(bundle/'config/app.env');env=readenv(bundle/'.env');profiles=env.get('COMPOSE_PROFILES','').split(',');url=urllib.parse.urlsplit(app['PUBLIC_URL']) + turn=readenv(bundle/'config/turn.env') + return {'host':url.hostname,'appPath':url.path,'mode':'https' if 'https' in profiles else 'tunnel' if 'tunnel' in profiles else 'proxy','relay':'self' if 'turn' in profiles else 'existing' if app.get('TURN_URLS') else 'none','publicIP':turn.get('TURN_PUBLIC_IP',''),'lanIP':turn.get('TURN_LAN_IP',''),'turnURLs':app.get('TURN_URLS',''),'turnSecret':app.get('TURN_SECRET',''),'appPort':int(env.get('APP_PORT',8080)),'ntfyPort':int(env.get('NTFY_PORT',8094)),'ntfy':'ntfy' in profiles,'ntfyHost':urllib.parse.urlsplit(app.get('NTFY_PUBLIC_URL','')).hostname or '','ios':app.get('NTFY_IOS_UPSTREAM')=='true','tunnelToken':(bundle/'config/tunnel-token').read_text().strip()} + +def install(settings,bundle,vapid=None,replace=False): + s=validate(settings);bundle=pathlib.Path(bundle);existing=(bundle/'.env').exists() or (bundle/'config').exists() + if existing and not replace:raise ValueError('Already configured. Use ./webcaller configure to change settings, or ./webcaller start to start it. Your keys have not been replaced.') + if replace and not ((bundle/'.env').is_file() and (bundle/'config/app.env').is_file()):raise ValueError('The existing configuration is incomplete. Restore a backup before reconfiguring.') + prior=readenv(bundle/'config/app.env') if replace else {};env=readenv(bundle/'.env') if replace else {} + if not replace and vapid is None: + r=subprocess.run(['node','--input-type=module','-e',"import p from 'web-push';process.stdout.write(JSON.stringify(p.generateVAPIDKeys()))"],cwd='/app',capture_output=True,text=True,check=True);vapid=json.loads(r.stdout) profiles=[] if s['mode'] in ['https','tunnel']:profiles.append(s['mode']) if s['relay']=='self':profiles.append('turn') if s.get('ntfy'):profiles.append('ntfy') - secret=s.get('turnSecret') if s['relay']=='existing' else secrets.token_hex(32) + old=current(bundle) if replace else {} + secret=s.get('turnSecret') if s['relay']=='existing' else prior.get('TURN_SECRET') or secrets.token_hex(32) urls=s.get('turnURLs','') if s['relay']=='existing' else (f"turn:{s['publicIP']}:3478?transport=udp,turn:{s['publicIP']}:3478?transport=tcp" if s['relay']=='self' else '') - app={'WEBCALLER_CRYPTO_ENGINE':'libsignal-pqxdh-v1','PUBLIC_URL':'https://'+s['host']+'/calls','BOOTSTRAP_TOKEN':secrets.token_urlsafe(24),'VAPID_PUBLIC_KEY':vapid['publicKey'],'VAPID_PRIVATE_KEY':vapid['privateKey'],'VAPID_SUBJECT':'https://'+s['host'],'TURN_URLS':urls,'TURN_SECRET':secret} + if s['relay']=='self' and old.get('relay')=='self': + extra=[u for u in prior.get('TURN_URLS','').split(',') if u.startswith('turns:')] + if extra:urls+=','+','.join(extra) + app=dict(prior) + if not replace:app.update(BOOTSTRAP_TOKEN=secrets.token_urlsafe(24),VAPID_PUBLIC_KEY=vapid['publicKey'],VAPID_PRIVATE_KEY=vapid['privateKey'],VAPID_SUBJECT='https://'+s['host']) + if replace and old.get('appPath')!=s['appPath']:app.setdefault('APP_MANIFEST_ID',old['appPath'].rstrip('/')+'/') + app.update(WEBCALLER_CRYPTO_ENGINE='libsignal-pqxdh-v1',PUBLIC_URL='https://'+s['host']+s['appPath'],TURN_URLS=urls,TURN_SECRET=secret) + if replace and old.get('relay')!=s['relay']: + app.pop('CF_TURN_KEY_ID',None);app.pop('CF_TURN_API_TOKEN',None) + for k in ['NTFY_PUBLIC_URL','NTFY_PUBLISH_URL','NTFY_PUBLISH_TOKEN_FILE','NTFY_ALLOW_DOCKER_HTTP','NTFY_IOS_UPSTREAM']:app.pop(k,None) if s.get('ntfy'):app.update(NTFY_PUBLIC_URL='https://'+s['ntfyHost'],NTFY_PUBLISH_URL='http://ntfy:8094',NTFY_PUBLISH_TOKEN_FILE='/run/webcaller-ntfy/publisher.token',NTFY_ALLOW_DOCKER_HTTP='true',NTFY_IOS_UPSTREAM=str(bool(s.get('ios'))).lower()) config=pathlib.Path(tempfile.mkdtemp(prefix='.setup-',dir=bundle));config.chmod(0o700) + previous=None try: write(config/'app.env',envtext(app));write(config/'turn.env',envtext({'TURN_PUBLIC_IP':s.get('publicIP',''),'TURN_LAN_IP':s.get('lanIP',''),'TURN_SECRET':secret,'TURN_REALM':'webcaller'})) ntfy={'base-url':'https://'+s.get('ntfyHost','ntfy.example.com'),'listen-http':':8094','auth-file':'/var/lib/ntfy/auth.db','auth-default-access':'deny-all','cache-duration':'2m','manager-interval':'10s','web-root':'disable','log-level':'warn','upstream-base-url':'https://ntfy.sh' if s.get('ios') and s.get('ntfy') else ''} write(config/'ntfy.yml',''.join(k+': '+json.dumps(v)+'\n' for k,v in ntfy.items()),0o644) - caddy=s['host']+' {\n @phone path /calls /calls/*\n reverse_proxy @phone webcaller:8080\n respond "Not found" 404\n}\n' + caddy=s['host']+' {\n @phone path '+s['appPath']+' '+s['appPath']+'/*\n reverse_proxy @phone webcaller:8080\n respond "Not found" 404\n}\n' if s.get('ntfy'):caddy+='\n'+s['ntfyHost']+' {\n reverse_proxy ntfy:8094 {\n flush_interval -1\n }\n}\n' - write(config/'Caddyfile',caddy,0o644);write(config/'tunnel-token',s.get('tunnelToken','')+'\n');(config/'certs').mkdir(mode=0o700) + write(config/'Caddyfile',caddy,0o644);write(config/'tunnel-token',s.get('tunnelToken','')+'\n') + if replace and (bundle/'config/certs').is_dir():shutil.copytree(bundle/'config/certs',config/'certs') + else:(config/'certs').mkdir(mode=0o700) + settings={k:v for k,v in s.items() if k not in ['turnSecret','tunnelToken']};write(config/'setup.json',json.dumps(settings,indent=2)+'\n') + if replace: + previous=bundle/'.previous-config' + if previous.exists():raise ValueError('A previous configuration recovery is pending. Use restore before trying again.') + os.rename(bundle/'config',previous) os.rename(config,bundle/'config') - write(bundle/'.env',envtext({'COMPOSE_PROFILES':','.join(profiles),'APP_PORT':s['appPort'],'NTFY_PORT':s['ntfyPort'],'NTFY_ENABLED':str(bool(s.get('ntfy'))).lower(),'SETUP_UID':os.getuid(),'SETUP_GID':os.getgid()})) + env.update(COMPOSE_PROFILES=','.join(profiles),APP_PORT=s['appPort'],NTFY_PORT=s['ntfyPort'],NTFY_ENABLED=str(bool(s.get('ntfy'))).lower(),SETUP_UID=os.getuid(),SETUP_GID=os.getgid()) + env.setdefault('COMPOSE_PROJECT_NAME','webcaller-prebuilt' if replace else 'webcaller-'+secrets.token_hex(4)) + temp=bundle/'.env.new';write(temp,envtext(env));os.replace(temp,bundle/'.env') + if previous:shutil.rmtree(previous) except BaseException: if config.exists():shutil.rmtree(config) + if previous and previous.exists(): + if (bundle/'config').exists():shutil.rmtree(bundle/'config') + os.rename(previous,bundle/'config') raise return {'profiles':profiles,'url':app['PUBLIC_URL']} -def wizard(): - print('WebCaller first setup. Keep this terminal private. Existing sites/routes are not changed.') - host=input('Calls hostname (for example calls.example.com): ').strip() - mode={'1':'https','2':'proxy','3':'tunnel'}[input('HTTPS: 1 automatic Caddy, 2 existing proxy/Tunnel, 3 new containerized Tunnel connector [2]: ').strip() or '2'] - token=getpass.getpass('Existing Cloudflare tunnel connector token (hidden): ') if mode=='tunnel' else '' - relay={'1':'self','2':'existing','3':'none'}[input('TURN: 1 self-hosted, 2 existing REST relay, 3 configure later [1]: ').strip() or '1'] - s={'host':host,'mode':mode,'relay':relay,'tunnelToken':token} - if relay=='self': - s['publicIP']=input('Globally routable IPv4 of relay/router: ').strip();s['lanIP']=input('Fixed server LAN IPv4 behind home router (empty on a public VPS): ').strip() - if relay=='existing':s.update(turnURLs=input('Comma-separated TURN URLs: ').strip(),turnSecret=getpass.getpass('REST shared secret (hidden): ')) - if relay=='none':print('Configure a reachable TURN relay before relying on calls across networks.') - s['ntfy']=input('Enable optional ntfy extra ringing? [y/N]: ').strip().lower() in ['y','yes'] +def ask(label,default='',check=None,secret=False): + while True: + suffix=' [Enter to keep]' if secret and default else ' ['+str(default)+']' if str(default) else '' + value=(getpass.getpass if secret else input)(label+suffix+': ').strip() or default + try:return check(value) if check else value + except (ValueError,TypeError):print(' Please check that answer and try again. Use the format in the explanation above.') +def localport(v): + value=int(v) + if not 1024<=value<=65535:raise ValueError('Use a local port from 1024 to 65535.') + return value +def public4(v): + ip=ipaddress.IPv4Address(v) + if not ip.is_global:raise ValueError('A public IPv4 is needed; choose an external relay for CGNAT.') + return str(ip) +def secret_value(v,pattern): + if not re.fullmatch(pattern,v):raise ValueError('Check the secret format.') + return v +def choice(label,options,default): + print('\n'+label) + for i,(key,text) in enumerate(options,1):print(' '+str(i)+'. '+text) + return ask('Choose a number',str(next(i for i,(k,_) in enumerate(options,1) if k==default)),lambda v:dict((str(i),k) for i,(k,_) in enumerate(options,1))[v] if v in [str(i) for i in range(1,len(options)+1)] else (_ for _ in ()).throw(ValueError())) +def yes(label,default=False):return ask(label,'yes' if default else 'no',lambda v:v.lower() in ['y','yes'] if v.lower() in ['y','yes','n','no'] else (_ for _ in ()).throw(ValueError())) +def public_ip(): + try: + transaction=secrets.token_bytes(12) + with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as s: + s.settimeout(2);s.sendto(struct.pack('!HHI',1,0,0x2112a442)+transaction,('stun.cloudflare.com',3478));data=s.recv(2048) + if data[8:20]!=transaction:return '' + pos=20 + while pos+4<=len(data): + kind,n=struct.unpack('!HH',data[pos:pos+4]);v=data[pos+4:pos+4+n];pos+=4+((n+3)//4)*4 + if kind==0x20 and len(v)>=8 and v[1]==1:return str(ipaddress.IPv4Address(bytes(a^b for a,b in zip(v[4:8],bytes.fromhex('2112a442'))))) + except (OSError,ValueError):pass + return '' +def wizard(prior=None): + old=prior or {};s=dict(old) + print('\nWEBCALLER · '+('CHANGE SETTINGS' if prior else 'WELCOME')) + print('A browser phone, hosted by you. This wizard keeps passwords and phone setup keys private.') + print('\n1 OF 4 · YOUR WEBSITE') + print('Use a hostname you own, for example phone.example.com. No domain is bought by this installer.') + s['host']=ask('Website hostname',old.get('host',''),hostname) + if prior and s['host']!=old['host']:print('A different hostname uses different browser storage. Existing phones will need setup at the new address; saved phone keys are not moved by changing DNS.') + print('\n2 OF 4 · SECURE ACCESS') + print('Automatic HTTPS suits a fresh public server. If a website or Tunnel already uses this server, keep that setup and choose option 2.') + s['mode']=choice('How should people reach the website?',[('https','Automatic HTTPS for a fresh server (ports 80 and 443)'),('proxy','I already have an HTTPS website, reverse proxy or Tunnel'),('tunnel','Use my existing Cloudflare account with a new connector')],old.get('mode','https')) + if s['mode']=='tunnel': + print('Create the connector in Cloudflare, then paste its token here. This does not register a domain or change existing routes.') + s['tunnelToken']=ask('Connector token',old.get('tunnelToken',''),lambda v:secret_value(v,r'[A-Za-z0-9+/=_-]{20,4096}'),secret=True) + s['appPort']=ask('Local website port (keep the default unless it is busy)',old.get('appPort',8080),localport) + print('\n3 OF 4 · RELIABLE CALLS') + print('TURN is a relay that helps phones on different networks connect. It cannot be replaced by an ordinary website Tunnel.') + s['relay']=choice('Where should the call relay run?',[('self','On this Linux server (public IPv4 or router forwarding required)'),('existing','Use a TURN REST relay I already have'),('none','Set up the website first; configure the relay later')],old.get('relay','self')) + if s['relay']=='self': + print('At home: forward TCP/UDP 3478 and UDP 49160–49260 to this server. Compare your router WAN address with the suggested public IP. If they differ or the WAN address is private/100.64–100.127, you may have CGNAT; use a public relay instead. Do not use a Cloudflare proxy IP.') + s['publicIP']=ask('Public IPv4 of the relay/router',old.get('publicIP') or public_ip(),public4) + print('On a public VPS leave the next answer empty. Behind a home router enter this server’s fixed LAN address.') + s['lanIP']=ask('Fixed LAN IPv4 (optional)',old.get('lanIP',''),lambda v:str(ipaddress.IPv4Address(v)) if v else '') + elif s['relay']=='existing': + print('Use the relay’s TURN URLs and REST shared secret. A normal username/password account is not the same thing.') + s['turnURLs']=ask('TURN URLs (comma separated)',old.get('turnURLs',''));s['turnSecret']=ask('REST shared secret',old.get('turnSecret',''),lambda v:secret_value(v,r'[A-Za-z0-9_-]{32,256}'),secret=True) + print('\n4 OF 4 · OPTIONAL EXTRA RINGING') + print('Browser alerts are included. ntfy is an optional extra for people able to install its phone app; it is not needed for chat/calls.') + s['ntfy']=yes('Add a self-hosted ntfy alert server?',old.get('ntfy',False)) if s['ntfy']: - s['ntfyHost']=input('Separate ntfy hostname (for example ntfy.example.com): ').strip() - s['ios']=input('Support iPhone ntfy wake-up via ntfy.sh metadata relay? [Y/n]: ').strip().lower() not in ['n','no'] + s['ntfyHost']=ask('Separate alert hostname (for example notify.example.com)',old.get('ntfyHost',''),hostname) + s['ntfyPort']=ask('Local alert port',old.get('ntfyPort',8094),localport) + print('Stock iPhone ntfy needs a wake-up metadata relay through ntfy.sh and Apple. Message/call contents and keys are not sent there.') + s['ios']=yes('Enable that optional iPhone ntfy wake-up?',old.get('ios',False)) + s=validate(s) + print('\nREADY TO SAVE\n Website: https://'+s['host']+s['appPath']+'/\n Access: '+s['mode']+'\n Call relay: '+s['relay']+'\n Extra ringing: '+('enabled' if s['ntfy'] else 'off')) + if not yes('Save these settings?',True):raise KeyboardInterrupt() return s - def qr(bundle): import qrcode values=dict(line.split('=',1) for line in (bundle/'config/app.env').read_text().splitlines() if '=' in line) @@ -133,20 +221,25 @@ def apply_update(bundle,version): print('Bundle updated. Private configuration and data volumes were preserved; no database rollback is attempted.') def main(): - p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=['init','qr','prepare-update','apply-update']);p.add_argument('version',nargs='?');p.add_argument('--bundle',type=pathlib.Path,default=pathlib.Path('/bundle'));p.add_argument('--settings',type=pathlib.Path) + p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=['init','configure','plan-configure','qr','prepare-update','apply-update','snapshot','backup-info','restore','restore-seed']);p.add_argument('version',nargs='?');p.add_argument('--bundle',type=pathlib.Path,default=pathlib.Path('/bundle'));p.add_argument('--settings',type=pathlib.Path);p.add_argument('--archive',type=pathlib.Path);p.add_argument('--volumes',default='{}') a=p.parse_args();os.umask(0o077) - if a.action=='init': - result=install(json.loads(a.settings.read_text()) if a.settings else wizard(),a.bundle) - print('Private configuration created. Start with ./webcaller start, then ./webcaller qr.');print('Phone address: '+result['url']) + if a.action=='plan-configure': + settings=wizard(current(a.bundle));write(a.bundle/'.planned-settings.json',json.dumps(settings)+'\n');print('Choices prepared. The current services have not been stopped yet.') + elif a.action in ['init','configure']: + s=json.loads(a.settings.read_text()) if a.settings else wizard(current(a.bundle) if a.action=='configure' else None) + result=install(s,a.bundle,replace=a.action=='configure');print('Settings saved. Phone address: '+result['url']+'/') elif a.action=='qr':qr(a.bundle) elif a.action=='prepare-update':prepare_update(a.bundle,a.version or '') elif a.action=='apply-update':apply_update(a.bundle,a.version or '') + else: + import docker_backup + volumes=json.loads(a.volumes);owner=(int(os.environ.get('WEBCALLER_OWNER_UID','1000')),int(os.environ.get('WEBCALLER_OWNER_GID','1000'))) + if a.action=='snapshot':m=docker_backup.create(a.bundle,a.archive,volumes,owner);print('Consistent private backup saved.') + elif a.action=='backup-info':m=docker_backup.verify(a.archive);print(json.dumps({k:m[k] for k in ['version','project','created','volumes']})) + elif a.action=='restore-seed':docker_backup.seed(a.bundle,a.archive,owner);print('Matching installation settings recovered; data restore follows.') + else:docker_backup.restore(a.bundle,a.archive,volumes,owner);print('Matching bundle, configuration and data restored.') if __name__=='__main__': try:main() - except (EOFError,KeyboardInterrupt): - print('Setup cancelled. Keep any existing private configuration.',file=sys.stderr);sys.exit(1) + except (EOFError,KeyboardInterrupt):print('\nCancelled. Existing phone keys were not regenerated.',file=sys.stderr);sys.exit(1) except (ValueError,KeyError,OSError,subprocess.SubprocessError) as e: - # Do not echo URLs, credentials, source JSON or subprocess output in errors. - if isinstance(e,ValueError):print(str(e),file=sys.stderr) - else:print('Setup/update failed. Check the private configuration, network and Docker permissions. Existing secrets were not printed.',file=sys.stderr) - sys.exit(1) + print(str(e) if isinstance(e,ValueError) else 'Setup/update failed. Check the private configuration and network. Credentials were not printed.',file=sys.stderr);sys.exit(1) diff --git a/scripts/docker-smoke.mjs b/scripts/docker-smoke.mjs index d666bd4..0b3d2bc 100644 --- a/scripts/docker-smoke.mjs +++ b/scripts/docker-smoke.mjs @@ -13,8 +13,10 @@ const project='webcaller-ci-'+randomBytes(6).toString('hex'); const docker=(...args)=>execFileSync('docker',args,{cwd:dir,encoding:'utf8',maxBuffer:8*1024*1024,timeout:240000}); const compose=(...args)=>docker('compose','--project-name',project,'--project-directory',dir,'--env-file','images.env','--env-file','.env','-f','compose.yaml',...args); const settings={host:'calls.example.test',mode:'proxy',relay:'self',publicIP:'1.1.1.1',appPort:18180,ntfyPort:18194,ntfy:true,ntfyHost:'notify.example.test',ios:false}; +let phase='setup'; try{ execFileSync('docker',['run','--rm','-i','--user',`${process.getuid()}:${process.getgid()}`,'--mount',`type=bind,src=${dir},dst=/bundle`,'webcaller-ci:setup','init','--settings','/dev/stdin'],{input:JSON.stringify(settings),encoding:'utf8',stdio:['pipe','pipe','pipe']}); + writeFileSync(join(dir,'.env'),readFileSync(join(dir,'.env'),'utf8').replace(/^COMPOSE_PROJECT_NAME=.*$/m,'COMPOSE_PROJECT_NAME='+project)); compose('config','--quiet'); const upstream=Object.fromEntries(images.split('\n').filter(v=>v.includes('=')&&!v.startsWith('#')).map(v=>v.split(/=(.*)/s).slice(0,2))); docker('run','--rm','--mount',`type=bind,src=${dir}/config/Caddyfile,dst=/etc/caddy/Caddyfile,readonly`,upstream.CADDY_IMAGE,'caddy','validate','--config','/etc/caddy/Caddyfile'); @@ -27,7 +29,7 @@ try{ const env=Object.fromEntries(readFileSync(join(dir,'config/app.env'),'utf8').trim().split('\n').map(v=>v.split(/=(.*)/s).slice(0,2))); const keys=()=>generateKeyPairSync('ec',{namedCurve:'prime256v1'}).publicKey.export({format:'jwk'}); let token; - const api=async(path,body)=>{const r=await fetch(base+'/api'+path,{method:body?'POST':'GET',headers:{Origin:origin,'Content-Type':'application/json',...(token?{Authorization:'Bearer '+token}:{})},...(body?{body:JSON.stringify(body)}:{})});assert.ok(r.ok,'API '+path+' status '+r.status);return r.json();}; + const api=async(path,body)=>{const r=await fetch(base+'/api'+path,{method:body?'POST':'GET',headers:{Origin:origin,'Content-Type':'application/json',Connection:'close',...(token?{Authorization:'Bearer '+token}:{})},...(body?{body:JSON.stringify(body)}:{})});assert.ok(r.ok,'API '+path+' status '+r.status);return r.json();}; token=(await api('/register',{name:'CI fixture',keys:{dh:keys(),sign:keys()},setupCode:env.BOOTSTRAP_TOKEN})).token; const topic=(await api('/ntfy',{})).topic; const ntfy='http://127.0.0.1:18194'; @@ -46,8 +48,23 @@ try{ compose('down');compose('up','-d','--wait','--wait-timeout','180'); const after=compose('exec','-T','webcaller','node','-e',"process.stdout.write(require('fs').readFileSync('/run/webcaller-ntfy/publisher.token'))");assert.equal(after,before); assert.equal((await api('/ntfy')).topic,topic);assert.equal((await api('/ntfy')).confirmed,true);assert.equal((await(await fetch(base+'/api/config')).json()).bootstrap,false); - console.log('PASS disposable Docker stack: setup, health, no-store, WebSocket auth, ntfy ACL/priority delivery, TURN allocation, private QR and restart persistence.'); + // Exercise the shipped assistant and an actual consistent backup/restore. + phase='assistant status';console.log('Checking assistant status'); + execFileSync(join(dir,'webcaller'),['status'],{cwd:dir,encoding:'utf8',timeout:10000}); + phase='consistent backup';console.log('Checking consistent backup'); + execFileSync('script',['-q','-e','-c','./webcaller backup','/dev/null'],{cwd:dir,input:'y\n',encoding:'utf8',timeout:180000}); + const backupFiles=(await import('node:fs')).readdirSync(join(dir,'backups')).filter(f=>f.endsWith('.tar.gz'));assert.equal(backupFiles.length,1); + compose('exec','-T','webcaller','node','-e',"require('fs').writeFileSync('/app/data/after-backup-fixture','later')"); + compose('stop'); + phase='snapshot restore';console.log('Checking snapshot restore'); + execFileSync('python3',['-c',"import importlib.machinery,importlib.util,pathlib; loader=importlib.machinery.SourceFileLoader('assistant','webcaller'); spec=importlib.util.spec_from_loader('assistant',loader); m=importlib.util.module_from_spec(spec); loader.exec_module(m); m.restore_snapshot(pathlib.Path('backups').resolve()/"+JSON.stringify(backupFiles[0])+"); m.start()"],{cwd:dir,encoding:'utf8',timeout:180000}); + assert.equal(compose('exec','-T','webcaller','node','-e',"process.stdout.write(String(require('fs').existsSync('/app/data/after-backup-fixture'))) ").trim(),'false'); + assert.equal((await api('/ntfy')).topic,topic);assert.equal((await api('/ntfy')).confirmed,true); + const restored=compose('exec','-T','webcaller','node','-e',"process.stdout.write(require('fs').readFileSync('/run/webcaller-ntfy/publisher.token'))");assert.equal(restored,before); + console.log('PASS disposable Linux stack: setup, HTTPS config, WS auth, ntfy ACL/priority, TURN allocation, private QR, restart persistence and consistent backup/restore preserving credentials and registrations.'); }catch(error){ + console.error('Failed phase: '+phase+'; error type: '+error.name+'; status: '+error.status+'; cause: '+(error.cause?.code||'none')); + if(['assistant status','consistent backup','snapshot restore'].includes(phase))for(const stream of [error.stdout,error.stderr])if(stream)console.error(String(stream).replace(/tk_[a-z0-9]+/g,'[redacted]').replace(/wc_[A-Za-z0-9_-]+/g,'[redacted]')); console.error('Disposable Docker smoke failed. Inspect synthetic container status below; credentials are omitted.'); // Synthetic fixture only; never output config, tokens, QR, topic IDs or command buffers. try{const ps=compose('ps');console.error(ps);const logs=compose('logs','--tail=30','ntfy-init','webcaller','ntfy');console.error(logs.replace(/tk_[a-z0-9]+/g,'[redacted]').replace(/wc_[A-Za-z0-9_-]+/g,'[redacted]'));}catch{} diff --git a/scripts/docker_backup.py b/scripts/docker_backup.py new file mode 100644 index 0000000..89fa717 --- /dev/null +++ b/scripts/docker_backup.py @@ -0,0 +1,141 @@ +"""Versioned, allowlisted Docker snapshots. No Docker socket is mounted here.""" +import hashlib,json,os,pathlib,shutil,tarfile,tempfile +from datetime import datetime,timezone +FILES={'compose.yaml','images.env','webcaller','README.md','VERSION','LICENSE','LICENSE-MIT','LICENSING.md','THIRD_PARTY_NOTICES.md'} +VOLUMES={'app_data','ntfy_state','publisher','caddy_data','caddy_config'} +LIMIT=100*1024**3 + +def allowed(name): + p=pathlib.PurePosixPath(name) + if p.is_absolute() or '..' in p.parts or str(p)!=name or '\\' in name:return False + return name=='BACKUP.json' or (len(p.parts)>=2 and p.parts[0]=='bundle' and (p.parts[1] in FILES|{'.env'} and len(p.parts)==2 or p.parts[1]=='config')) or (len(p.parts)>=2 and p.parts[0]=='volumes' and p.parts[1] in VOLUMES) + +def digest(path): + h=hashlib.sha256() + with path.open('rb') as f: + for b in iter(lambda:f.read(1024*1024),b''):h.update(b) + return h.hexdigest() + +def create(bundle,archive,volumes,owner=None): + bundle=pathlib.Path(bundle);archive=pathlib.Path(archive) + if archive.exists():raise ValueError('That backup file already exists. Choose a new filename.') + manifest={'format':1,'version':(bundle/'VERSION').read_text().strip(),'project':env(bundle/'.env').get('COMPOSE_PROJECT_NAME','webcaller-prebuilt'),'created':datetime.now(timezone.utc).isoformat(),'volumes':sorted(volumes),'files':{}} + if not set(volumes)<=VOLUMES:raise ValueError('Unexpected backup volume.') + paths=[] + for n in sorted(FILES|{'.env'}): + p=bundle/n + if not p.is_file() or p.is_symlink():raise ValueError('Installation bundle is incomplete or contains a symlink.') + paths.append(('bundle/'+n,p)) + paths.append(('bundle/config',bundle/'config')) + paths += [('volumes/'+n,pathlib.Path(p)) for n,p in sorted(volumes.items())] + temporary=archive.with_name(archive.name+'.partial') + try: + with temporary.open('xb') as raw: + os.chmod(temporary,0o600) + with tarfile.open(fileobj=raw,mode='w:gz',dereference=False) as tar: + def add(name,path): + if not allowed(name) or path.is_symlink() or not (path.is_file() or path.is_dir()):raise ValueError('Backups require regular files/directories; replace symbolic links with copied files.') + if path.is_file():manifest['files'][name]=digest(path) + tar.add(path,arcname=name,recursive=False) + if path.is_dir(): + for child in sorted(path.iterdir()):add(name+'/'+child.name,child) + for name,path in paths:add(name,path) + import io + data=(json.dumps(manifest,sort_keys=True)+'\n').encode();item=tarfile.TarInfo('BACKUP.json');item.size=len(data);item.mode=0o600;tar.addfile(item,io.BytesIO(data)) + if owner:os.chown(temporary,*owner) + os.replace(temporary,archive) + except BaseException: + temporary.unlink(missing_ok=True);raise + return manifest + +def env(path):return dict(l.split('=',1) for l in pathlib.Path(path).read_text().splitlines() if '=' in l and not l.startswith('#')) + +def verify(archive): + seen=set();dirs=set();hashes={};small={};manifest=None;total=0 + with tarfile.open(archive,'r:gz') as tar: + for member in tar: + name=member.name + if not allowed(name) or name in seen or not (member.isfile() or member.isdir()):raise ValueError('Unsafe or duplicate backup entry.') + if len(seen)>=200000 or member.size<0 or member.size>LIMIT or total+member.size>LIMIT:raise ValueError('Backup exceeds the supported size/count limit.') + seen.add(name);total+=member.size + if not (0<=member.uid<2**31 and 0<=member.gid<2**31):raise ValueError('Invalid backup file ownership.') + if member.isdir():dirs.add(name);continue + h=hashlib.sha256() + f=tar.extractfile(member) + if name in ['bundle/.env','bundle/VERSION']: + if member.size>65536:raise ValueError('Backup configuration is too large.') + data=f.read();small[name]=data.decode();h.update(data);hashes[name]=h.hexdigest();continue + if name=='BACKUP.json': + if member.size>16*1024*1024:raise ValueError('Backup manifest is too large.') + manifest=json.loads(f.read());continue + for b in iter(lambda:f.read(1024*1024),b''):h.update(b) + hashes[name]=h.hexdigest() + if not manifest or manifest.get('format')!=1 or hashes!=manifest.get('files'):raise ValueError('Backup integrity check failed.') + import re + if not re.fullmatch(r'\d+\.\d+\.\d+',manifest.get('version','')) or not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,62}',manifest.get('project','')) or not set(manifest.get('volumes',[]))<=VOLUMES:raise ValueError('Invalid backup metadata.') + if any('bundle/'+n not in hashes for n in FILES|{'.env'}) or 'bundle/config/app.env' not in hashes:raise ValueError('Backup is missing required configuration.') + if 'bundle/config' not in dirs:raise ValueError('Missing configuration directory.') + if small.get('bundle/VERSION','').strip()!=manifest['version']:raise ValueError('Backup version mismatch.') + values=dict(l.split('=',1) for l in small['bundle/.env'].splitlines() if '=' in l and not l.startswith('#')) + if values.get('COMPOSE_PROJECT_NAME','webcaller-prebuilt')!=manifest['project']:raise ValueError('Backup project mismatch.') + actual_volumes={pathlib.PurePosixPath(n).parts[1] for n in seen if n.startswith('volumes/')} + if actual_volumes!=set(manifest['volumes']):raise ValueError('Backup volume entries do not match the manifest.') + for n in manifest['volumes']: + if 'volumes/'+n not in dirs:raise ValueError('Missing backup volume.') + # Reject paths nested beneath a regular file before changing any destination. + for name in seen: + for parent in pathlib.PurePosixPath(name).parents: + if str(parent) in hashes:raise ValueError('A backup file is used as a directory.') + return manifest + +def restore(bundle,archive,volumes,owner): + bundle=pathlib.Path(bundle);m=verify(archive) + if set(volumes)!=set(m['volumes']):raise ValueError('Backup volume mapping does not match.') + for root in volumes.values(): + root=pathlib.Path(root) + if root.is_symlink() or not root.is_dir():raise ValueError('Invalid restore volume mount.') + # The caller stops this installation first and takes a safety backup. + stage=pathlib.Path(tempfile.mkdtemp(prefix='.restore-',dir=bundle));stage.chmod(0o700) + try: + for root in volumes.values(): + for p in pathlib.Path(root).iterdir(): + if p.is_dir() and not p.is_symlink():shutil.rmtree(p) + else:p.unlink() + with tarfile.open(archive,'r:gz') as tar: + for item in tar: + if item.name=='BACKUP.json':continue + parts=pathlib.PurePosixPath(item.name).parts + root=stage if parts[0]=='bundle' else pathlib.Path(volumes[parts[1]]) + tail=parts[1:] if parts[0]=='bundle' else parts[2:] + dest=root.joinpath(*tail) + dest.parent.mkdir(parents=True,exist_ok=True) + if item.isdir():dest.mkdir(exist_ok=True) + else: + with dest.open('xb') as f:shutil.copyfileobj(tar.extractfile(item),f,1024*1024) + os.chmod(dest,item.mode&0o777) + os.chown(dest,*(owner if parts[0]=='bundle' else (item.uid,item.gid))) + # Verify identity-bearing settings agree with the manifest before replacement. + if env(stage/'.env').get('COMPOSE_PROJECT_NAME','webcaller-prebuilt')!=m['project'] or (stage/'VERSION').read_text().strip()!=m['version']:raise ValueError('Backup identity/version mismatch.') + old=bundle/'config' + if old.exists():shutil.rmtree(old) + os.replace(stage/'config',old) + for n in FILES|{'.env'}:os.replace(stage/n,bundle/n) + finally:shutil.rmtree(stage,ignore_errors=True) + return m + + +def seed(bundle,archive,owner): + bundle=pathlib.Path(bundle);verify(archive) + if (bundle/'.env').exists() or (bundle/'config').exists():raise ValueError('Restore into an empty installation folder, or use normal restore for the existing installation.') + stage=pathlib.Path(tempfile.mkdtemp(prefix='.restore-',dir=bundle));stage.chmod(0o700) + try: + with tarfile.open(archive,'r:gz') as tar: + for item in tar: + if not item.name.startswith('bundle/'):continue + dest=stage.joinpath(*pathlib.PurePosixPath(item.name).parts[1:]);dest.parent.mkdir(parents=True,exist_ok=True) + if item.isdir():dest.mkdir(exist_ok=True) + else: + with dest.open('xb') as f:shutil.copyfileobj(tar.extractfile(item),f,1024*1024) + os.chmod(dest,item.mode&0o777);os.chown(dest,*owner) + for n in FILES|{'.env','config'}:os.replace(stage/n,bundle/n) + finally:shutil.rmtree(stage,ignore_errors=True) diff --git a/scripts/preview-release.mjs b/scripts/preview-release.mjs new file mode 100644 index 0000000..59c1e97 --- /dev/null +++ b/scripts/preview-release.mjs @@ -0,0 +1,22 @@ +// Run only on loopback for documentation screenshots; never a real deployment. +import {createServer} from 'node:http'; +import {readFileSync,existsSync} from 'node:fs'; +import {resolve,extname} from 'node:path'; +const root=resolve('public'),images=resolve('docs/images'); +const mime={'.html':'text/html','.js':'text/javascript','.css':'text/css','.svg':'image/svg+xml','.png':'image/png','.webp':'image/webp','.woff2':'font/woff2'}; +createServer((req,res)=>{ + const url=new URL(req.url,'http://localhost');let body,type='text/html'; + if(url.pathname==='/')body=readFileSync(root+'/index.html','utf8').replace(/]*>.*?<\/script>/gs,'').replace('','').replace('','').replace('',''); + else if(url.pathname==='/preview.js'){body=readFileSync('scripts/release-preview.js');type='text/javascript';} + else if(url.pathname==='/preview-icons.js'){body='export '+readFileSync(root+'/app.js','utf8').match(/const icons=\{[\s\S]*?\n\};/)[0];type='text/javascript';} + else if(url.pathname==='/example.svg'){body=readFileSync(images+'/demo-landscape.svg');type='image/svg+xml';} + else if(url.pathname==='/overview'){body=readFileSync('scripts/release-overview.html');} + else { + const prefix=url.pathname.startsWith('/ui/')?'/ui/':url.pathname.startsWith('/shots/')?'/shots/':null; + if(!prefix){res.writeHead(404);return res.end();} + const base=prefix==='/ui/'?root:images,file=resolve(base,decodeURIComponent(url.pathname.slice(prefix.length))); + if(!file.startsWith(base+'/')||!existsSync(file)){res.writeHead(404);return res.end();} + body=readFileSync(file);type=mime[extname(file)]||'application/octet-stream'; + } + res.setHeader('Content-Type',type);res.setHeader('Cache-Control','no-store');res.end(body); +}).listen(8196,'127.0.0.1',()=>console.log('Synthetic release preview: http://localhost:8196/')); diff --git a/scripts/release-overview.html b/scripts/release-overview.html new file mode 100644 index 0000000..1866a34 --- /dev/null +++ b/scripts/release-overview.html @@ -0,0 +1,3 @@ +WebCaller · Your people. Your server.
WebCaller
Self hosted · Linux server edition

Your people. Your server.

Clear calls. Encrypted conversations.
A familiar phone experience, right in your browser.

WebCaller · Desktop
WebCaller desktop chat with example data
WebCaller mobile chat in dark appearance with example data
Voice & videoEncrypted chat & mediaNo phone number required
Actual interface · Demonstration data
diff --git a/scripts/release-preview.js b/scripts/release-preview.js new file mode 100644 index 0000000..a089643 --- /dev/null +++ b/scripts/release-preview.js @@ -0,0 +1,30 @@ +// Synthetic screenshot fixtures using the real shipped components. No accounts, +// API calls, phone data, keys, service worker or notification registration. +import {drawMessages} from '/ui/chat-ui.js'; +import {icons} from '/preview-icons.js'; +const $=id=>document.getElementById(id),mode=new URL(location).searchParams.get('view')||'chat'; +document.documentElement.dataset.theme=mode==='mobile'?'dark':'light'; +for(const e of document.querySelectorAll('[data-icon]'))if(icons[e.dataset.icon])e.innerHTML=``; +$('dial-open').classList.remove('hidden');$('self-name').textContent='Alex';$('self-avatar').textContent='A';$('connection').textContent='Ready for conversations';$('connection').classList.add('online'); +const contacts=[['maya','Maya Chen'],['leo','Leo Martin'],['sam','Sam Rivera'],['nora','Nora Williams'],['jules','Jules Park'],['robin','Robin Ellis']]; +$('contacts').replaceChildren();$('contact-count').textContent=contacts.length; +for(const [i,[id,label]]of contacts.entries()){ + const row=document.createElement('div');row.className='person-row';const button=document.createElement('button');button.className='contact'+(id==='maya'&&mode!=='home'?' selected':'');button.type='button';button.ariaLabel='Chat with '+label; + const avatar=document.createElement('div');avatar.className='avatar';avatar.dataset.tone=String(i%5);avatar.textContent=label.split(' ').map(w=>w[0]).join('');const text=document.createElement('div');text.className='contact-text';const strong=document.createElement('strong');strong.textContent=label;text.append(strong);button.append(avatar,text); + if(mode==='home'&&i===0){const badge=document.createElement('span');badge.className='unread';badge.textContent='2';button.append(badge);} + const actions=document.createElement('div');actions.className='person-actions';for(const [kind,cls,aria]of [['video','home-call','Video call'],['more','home-contact-options','Contact options for']]){const b=document.createElement('button');b.className=cls;b.type='button';b.ariaLabel=aria+' '+label;b.innerHTML=``;actions.append(b);} + row.append(button,actions);$('contacts').append(row);button.onclick=()=>{location.href='/?view=mobile';}; +} +$('peer-name').textContent='Maya Chen';$('peer-avatar').textContent='MC'; +if(mode==='home'){$('conversation').classList.add('hidden');$('empty').classList.remove('hidden');} +else{ + document.querySelector('.app').classList.add('chat-open');$('conversation').classList.remove('hidden');$('empty').classList.add('hidden'); + const picture=new Image();picture.src='/example.svg';await picture.decode();const canvas=document.createElement('canvas');canvas.width=960;canvas.height=560;canvas.getContext('2d').drawImage(picture,0,0);const blob=await new Promise(r=>canvas.toBlob(r,'image/png')); + const now=Date.now(),self='demo-self',peer='demo-maya'; + const make=(id,from,text,minutes)=>({id,from,to:from===self?peer:self,text,createdAt:now-minutes*60000,expiresAt:now+(60-minutes)*60000,receipt:from===self?{deliveredAt:now-minutes*60000+1000,readAt:now-minutes*60000+4000}:undefined}); + const list=[make('demo-1',peer,'Made it home. How was your day?',8),make('demo-2',self,'Much better after this view ☀️',7),{...make('demo-3',self,'Found a quiet spot for our next call.',6),attachment:{id:'demo-photo',name:'Afternoon by the lake.png',type:'image/png',size:blob.size,chunks:1},blobURL:URL.createObjectURL(blob),reactions:{[peer]:'❤️'}},make('demo-4',peer,'That looks lovely. Video call in a minute?',3),make('demo-5',self,'Absolutely. I’ll call you now.',2)]; + drawMessages({container:$('messages'),list,self,options:()=>{},openMedia:()=>{},load:()=>{},save:()=>{}}); +} +$('settings').onclick=()=>{$('settings-dialog').showModal();}; +$('back').onclick=()=>{location.href='/?view=home';}; +document.body.dataset.previewReady='true'; diff --git a/tests/experimental-distribution.test.mjs b/tests/experimental-distribution.test.mjs index 7fc761f..a7fe717 100644 --- a/tests/experimental-distribution.test.mjs +++ b/tests/experimental-distribution.test.mjs @@ -13,7 +13,7 @@ test('prebuilt bundle pins its own published version independently of newer sour const images=readFileSync('docker/images.env','utf8'); for(const suffix of ['','-setup','-turn'])assert.ok(images.includes('ghcr.io/adlererik/webcaller:'+version+suffix+'\n')); assert.match(images,/BUNDLE_FORMAT=2/); - const result=spawnSync('sh',['docker/webcaller','status'],{encoding:'utf8'}); + const result=spawnSync('python3',['docker/webcaller','status'],{encoding:'utf8'}); assert.equal(result.status,1);assert.match(result.stdout+result.stderr,/Run \.\/webcaller setup first/); }); test('publishing guard accepts only the pinned official upstream gitlink and rejects substitution',t=>{ diff --git a/tests/linux-assistant.test.mjs b/tests/linux-assistant.test.mjs new file mode 100644 index 0000000..fada9fa --- /dev/null +++ b/tests/linux-assistant.test.mjs @@ -0,0 +1,43 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {resolve} from 'node:path'; +const load=`import importlib.util,importlib.machinery,pathlib,tempfile,os,json,io,tarfile\ndef load(name,path):\n spec=importlib.util.spec_from_loader(name,importlib.machinery.SourceFileLoader(name,path));m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m\ns=load('setup',${JSON.stringify(resolve('scripts/docker-setup.py'))});b=load('backup',${JSON.stringify(resolve('scripts/docker_backup.py'))});c=load('assistant',${JSON.stringify(resolve('docker/webcaller'))})\n`; +function python(code){const p=spawnSync('python3',['-c',load+code],{encoding:'utf8'});assert.equal(p.status,0,p.stderr);return p.stdout;} +const fixture=`\ntmp=tempfile.TemporaryDirectory();root=pathlib.Path(tmp.name);bundle=root/'install';bundle.mkdir();volume=root/'app-data';volume.mkdir();(volume/'saved.txt').write_text('before backup')\nfor n in b.FILES:(bundle/n).write_text('0.20.0' if n=='VERSION' else 'fixture '+n)\ns.install({'host':'phone.example.test','mode':'proxy','relay':'none'},bundle,{'publicKey':'fixture-public','privateKey':'fixture-private'})\narchive=root/'snapshot.tar.gz';owner=(os.getuid(),os.getgid())\n`; +test('reconfiguration preserves owner/VAPID credentials, instance identity and extra app settings',()=>{ + python(fixture+`before=s.readenv(bundle/'config/app.env');project=s.readenv(bundle/'.env')['COMPOSE_PROJECT_NAME'];cert=bundle/'config/certs/fullchain.pem';cert.write_text('fixture certificate')\nwith (bundle/'config/app.env').open('a') as f:f.write('EXTRA_FIXTURE=preserve\\n')\nsettings=s.current(bundle);settings.update(mode='https',relay='self',publicIP='1.1.1.1',ntfy=True,ntfyHost='notify.example.test',ios=False,appPort=18088)\ns.install(settings,bundle,replace=True)\nafter=s.readenv(bundle/'config/app.env')\nfor key in ['BOOTSTRAP_TOKEN','VAPID_PUBLIC_KEY','VAPID_PRIVATE_KEY']:assert before[key]==after[key]\nassert after['EXTRA_FIXTURE']=='preserve';assert s.readenv(bundle/'.env')['COMPOSE_PROJECT_NAME']==project;assert cert.read_text()=='fixture certificate'\nassert s.current(bundle)['mode']=='https';assert s.current(bundle)['ntfy'] is True\n`); +}); +test('consistent snapshots restore matching server data, configuration and release, including a fresh folder seed',()=>{ + python(fixture+`b.create(bundle,archive,{'app_data':str(volume)},owner);m=b.verify(archive);assert m['version']=='0.20.0';assert archive.stat().st_mode&0o777==0o600\n(volume/'saved.txt').write_text('changed after backup');(volume/'later.txt').write_text('later');original=(bundle/'config/app.env').read_bytes();(bundle/'config/app.env').write_text('changed')\nb.restore(bundle,archive,{'app_data':str(volume)},owner)\nassert (volume/'saved.txt').read_text()=='before backup';assert not (volume/'later.txt').exists();assert (bundle/'config/app.env').read_bytes()==original\nfresh=root/'fresh';fresh.mkdir();b.seed(fresh,archive,owner);assert (fresh/'config/app.env').read_bytes()==original;assert s.readenv(fresh/'.env')['COMPOSE_PROJECT_NAME']==m['project']\ntry:b.seed(fresh,archive,owner)\nexcept ValueError:pass\nelse:raise Exception('seed overwrote an installation')\n`); +}); +test('tampered snapshots fail before existing volume or configuration is touched',()=>{ + python(fixture+`b.create(bundle,archive,{'app_data':str(volume)},owner);bad=root/'bad.tar.gz'\nwith tarfile.open(archive,'r:gz') as src,tarfile.open(bad,'w:gz') as dst:\n for item in src:\n data=src.extractfile(item).read() if item.isfile() else None\n if item.name=='volumes/app_data/saved.txt':data=b'tampered';item.size=len(data)\n dst.addfile(item,io.BytesIO(data) if data is not None else None)\ntry:b.restore(bundle,bad,{'app_data':str(volume)},owner)\nexcept ValueError:pass\nelse:raise Exception('tampered snapshot restored')\nassert (volume/'saved.txt').read_text()=='before backup';assert (bundle/'config/app.env').is_file()\n`); +}); +test('backup extraction rejects traversal, links, special files, duplicates and oversized members',()=>{ + python(fixture+`for kind in ['traversal','absolute','link','device','duplicate','oversize']:\n bad=root/(kind+'.tar.gz')\n with tarfile.open(bad,'w:gz') as tar:\n item=tarfile.TarInfo('../escaped' if kind=='traversal' else '/escaped' if kind=='absolute' else 'bundle/config/fixture')\n if kind=='link':item.type=tarfile.SYMTYPE;item.linkname='/etc/passwd'\n if kind=='device':item.type=tarfile.CHRTYPE\n if kind=='oversize':item.type=tarfile.DIRTYPE;item.size=b.LIMIT+1\n tar.addfile(item)\n if kind=='duplicate':tar.addfile(item)\n try:b.verify(bad)\n except ValueError:pass\n else:raise Exception('unsafe backup accepted: '+kind)\nassert not (root/'escaped').exists()\n`); +}); +test('snapshot creation refuses symlinked secrets and never leaves a partial backup',()=>{ + python(fixture+`(volume/'link').symlink_to('/etc/passwd')\ntry:b.create(bundle,archive,{'app_data':str(volume)},owner)\nexcept ValueError:pass\nelse:raise Exception('external secret link followed')\nassert not archive.exists();assert not archive.with_name(archive.name+'.partial').exists()\n`); +}); +test('extra undeclared volume entries are rejected before restoring any existing data',()=>{ + python(fixture+`b.create(bundle,archive,{'app_data':str(volume)},owner);bad=root/'extra-volume.tar.gz'\nwith tarfile.open(archive,'r:gz') as src,tarfile.open(bad,'w:gz') as dst:\n for item in src:dst.addfile(item,src.extractfile(item) if item.isfile() else None)\n item=tarfile.TarInfo('volumes/publisher');item.type=tarfile.DIRTYPE;dst.addfile(item)\ntry:b.restore(bundle,bad,{'app_data':str(volume)},owner)\nexcept ValueError:pass\nelse:raise Exception('undeclared volume restored')\nassert (volume/'saved.txt').read_text()=='before backup'\n`); +}); +test('failed reconfiguration triggers full safety-snapshot recovery and resumes the previous service',()=>{ + python(`events=[];c.configured=lambda:True;c.preflight=lambda:{};c.confirm=lambda *a,**k:True;c.running=lambda:True;c.image=lambda:'old-setup';c.compose=lambda *a,**k:events.append(('compose',a));c.snapshot=lambda **kw:pathlib.Path('/synthetic/snapshot.tar.gz')\ndef helper(action,*a,**kw):\n if action=='configure':raise ValueError('synthetic failed configuration')\nc.helper=helper;c.restore_snapshot=lambda *a,**kw:events.append(('restore',str(a[0]),kw.get('setup_image')));c.start=lambda **kw:events.append(('started',))\ntry:c.main(['configure'])\nexcept c.FriendlyError as e:assert 'restored' in str(e)\nelse:raise Exception('failed change reported as success')\nassert ('restore','/synthetic/snapshot.tar.gz','old-setup') in events;assert events[-1]==('started',)\n`); +}); +test('Linux, local-engine and instance-folder checks prevent operating on a different installation',()=>{ + python(`c.platform.system=lambda:'Darwin'\ntry:c.preflight()\nexcept c.FriendlyError as e:assert 'Linux only' in str(e)\nelse:raise Exception('non-Linux host accepted')\nc.platform.system=lambda:'Linux';c.platform.machine=lambda:'x86_64';c.docker=lambda *a,**kw:'{}' if a[0]=='info' else json.dumps('ssh://other-server') if a[0]=='context' else '2.39.0'\ntry:c.preflight()\nexcept c.FriendlyError as e:assert 'Remote' in str(e)\nelse:raise Exception('remote daemon accepted')\n`); +}); +test('an updated stack that fails its startup check restores the old release and resumes it',()=>{ + python(`events=[];c.configured=lambda:True;c.preflight=lambda:{};c.confirm=lambda *a,**k:True;c.running=lambda:True;c.image=lambda:'cached-old-setup';c.compose=lambda *a,**k:events.append(('compose',a));c.snapshot=lambda **kw:pathlib.Path('/synthetic/snapshot.tar.gz');c.helper=lambda action,*a,**kw:events.append(('helper',action));c.restore_snapshot=lambda *a,**kw:events.append(('restore',str(a[0]),kw.get('setup_image')))\ndef start(**kw):\n events.append(('start',))\n if sum(e==('start',) for e in events)==1:raise c.FriendlyError('synthetic unhealthy new release')\nc.start=start\ntry:c.main(['update','v0.21.0'])\nexcept c.FriendlyError as e:assert 'restored' in str(e)\nelse:raise Exception('unhealthy release reported as success')\nassert ('helper','apply-update') in events;assert ('restore','/synthetic/snapshot.tar.gz','cached-old-setup') in events;assert events[-1]==('start',)\n`); +}); +test('the bundled host-network relay is refused on rootless Docker before starting services',()=>{ + python(`c.env=lambda path:{'COMPOSE_PROFILES':'turn'};c.docker=lambda *a,**kw:json.dumps({'SecurityOptions':['name=rootless']})\ntry:c.start()\nexcept c.FriendlyError as e:assert 'Rootless' in str(e)\nelse:raise Exception('unsupported relay network started')\n`); +}); +test('guided answers retry invalid choices rather than crashing or treating them as acceptance',()=>{ + python(`answers=iter(['nope','4','2']);s.input=lambda label:next(answers);assert s.choice('Choose',[('a','one'),('b','two')],'a')=='b'\nanswers=iter(['maybe','yes']);s.input=lambda label:next(answers);assert s.yes('Continue?') is True\n`); +}); +test('snapshots discover declared optional volumes even when their service profile is disabled',()=>{ + python(`import types\nc.project=lambda:'webcaller-fixture'\ndef compose(*a,**kw):\n # Compose drops inactive service volumes unless all profiles are requested.\n return json.dumps({'volumes':{k:{'name':'webcaller-fixture_'+k} for k in (c.VOLUMES if '*' in a else ['app_data'])}})\nc.compose=compose\ndef docker(*a,**kw):\n name=a[-1]\n if name.endswith('app_data'):return types.SimpleNamespace(returncode=0,stdout=json.dumps([{'Labels':{'com.docker.compose.project':'webcaller-fixture','com.docker.compose.volume':'app_data'}}]))\n return types.SimpleNamespace(returncode=1,stdout='')\nc.docker=docker\nassert c.mappings()=={'app_data':'webcaller-fixture_app_data'}\n`); +}); diff --git a/tests/viewport.test.mjs b/tests/viewport.test.mjs new file mode 100644 index 0000000..c08568c --- /dev/null +++ b/tests/viewport.test.mjs @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {appViewport} from '../public/viewport.js'; + +function fixture({visual=true}={}) { + const win=new EventTarget(),doc=new EventTarget(),viewport=new EventTarget(); + const frames=new Map(),timers=new Map(),styles=new Map();let next=0,resets=0,height=844,top=900; + const messages={scrollHeight:1500,get clientHeight(){return height-244;},get scrollTop(){return top;},set scrollTop(value){top=Math.max(0,Math.min(value,1500-this.clientHeight));}}; + Object.assign(viewport,{height:844,offsetTop:0,scale:1}); + Object.assign(win,{visualViewport:visual?viewport:undefined,innerHeight:844,scrollX:0,scrollY:0, + requestAnimationFrame:fn=>{frames.set(++next,fn);return next;},cancelAnimationFrame:id=>frames.delete(id), + setTimeout:fn=>{timers.set(++next,fn);return next;},clearTimeout:id=>timers.delete(id), + scrollTo(){resets++;win.scrollX=win.scrollY=viewport.offsetTop=0;}}); + Object.assign(doc,{activeElement:null,visibilityState:'visible',documentElement:{clientHeight:844,style:{ + setProperty(name,value){styles.set(name,value);if(name==='--app-viewport-height')height=parseFloat(value);}, + removeProperty:name=>styles.delete(name) + }},getElementById:id=>id==='messages'?messages:null}); + const controller=appViewport({window:win,document:doc}); + const emit=(target,name)=>target.dispatchEvent(new Event(name)); + const flush=()=>{const tasks=[...frames.values()];frames.clear();for(const fn of tasks)fn();}; + return {win,doc,viewport,controller,styles,messages,frames,timers,flush,resets:()=>resets, + focus(){doc.activeElement={matches:()=>true};emit(doc,'focusin');flush();}, + blur(){doc.activeElement=null;emit(doc,'focusout');}, + geometry(h,offset=0){viewport.height=h;viewport.offsetTop=offset;emit(viewport,'resize');emit(viewport,'scroll');flush();}, + settle(){const tasks=[...timers.values()];timers.clear();for(const fn of tasks)fn();flush();},emit}; +} +test('keyboard panning and repeated dismissal restore the shell and keep the latest message visible',()=>{ + const f=fixture(); + for(let i=0;i<5;i++) { + f.focus();f.geometry(510,35); + assert.equal(f.styles.get('--app-viewport-height'),'510px');assert.equal(f.styles.get('--app-viewport-top'),'35px'); + assert.equal(f.messages.scrollTop,1500-f.messages.clientHeight); + f.win.scrollY=35;f.geometry(844); // Android may keep the input focused. + assert.equal(f.win.scrollY,0);assert.equal(f.styles.get('--app-viewport-height'),'844px'); + assert.equal(f.styles.get('--app-viewport-top'),'0px');f.blur();f.settle(); + } + assert.equal(f.resets(),5);f.controller.dispose(); +}); +test('older-message scroll positions survive keyboard resizing without jumping to the end',()=>{ + const f=fixture();f.messages.scrollTop=180;f.focus();f.geometry(510,20);f.geometry(844); + assert.equal(f.messages.scrollTop,180);f.controller.dispose(); +}); +test('a late iOS root scroll after blur is corrected without scrolling the chat',()=>{ + const f=fixture();f.messages.scrollTop=180;f.focus();f.geometry(500,40);f.blur(); + f.geometry(844,40);f.win.scrollY=40;f.settle(); + assert.equal(f.win.scrollY,0);assert.equal(f.styles.get('--app-viewport-top'),'0px'); + assert.equal(f.messages.scrollTop,180);f.controller.dispose(); +}); +test('pinch zoom is left alone and layout resumes when returning to normal scale',()=>{ + const f=fixture();f.viewport.scale=2;f.win.scrollY=60;f.geometry(400,100);f.blur();f.settle(); + assert.equal(f.styles.get('--app-viewport-height'),'844px');assert.equal(f.resets(),0);assert.equal(f.win.scrollY,60); + f.viewport.scale=1;f.geometry(844);assert.equal(f.styles.get('--app-viewport-height'),'844px');f.controller.dispose(); +}); +test('rotation and resume use the current geometry; teardown removes pending work',()=>{ + const f=fixture();f.win.innerHeight=f.doc.documentElement.clientHeight=390;f.geometry(390); + assert.equal(f.styles.get('--app-viewport-height'),'390px'); + f.emit(f.win,'pageshow');f.controller.dispose();f.flush();f.settle();f.geometry(844); + assert.equal(f.styles.size,0);assert.equal(f.frames.size,0);assert.equal(f.timers.size,0); +}); +test('browsers without VisualViewport retain the CSS viewport fallback',()=>{ + const f=fixture({visual:false});f.focus();f.blur();f.settle(); + assert.equal(f.styles.size,0);f.controller.dispose(); +});