mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-05 06:59:33 +01:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ba5134174 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
target/
|
||||
dist/
|
||||
Generated
+3134
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,87 @@
|
||||
[package]
|
||||
name = "codeman-desktop"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.90"
|
||||
description = "Codeman Desktop: a small native window for a Codeman server"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "codeman-desktop"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# Window + event loop (tao), the system web view (wry: WKWebView on macOS,
|
||||
# WebView2 on Windows, WebKitGTK on Linux) and native menus (muda). Tauri is
|
||||
# built on these three; using them directly keeps the app small and gives us
|
||||
# `load_url_with_headers`, which Tauri's navigate() does not have (see README).
|
||||
tao = "0.37"
|
||||
wry = { version = "0.57", features = ["devtools"] }
|
||||
muda = "0.21"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
url = "2"
|
||||
base64 = "0.22"
|
||||
dirs = "6"
|
||||
# The reachability probe. platform-verifier = the OS trust store, the same one
|
||||
# WKWebView uses, so the probe and the window agree on which certificates pass.
|
||||
ureq = { version = "3", features = ["platform-verifier"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
security-framework = "3"
|
||||
# JavaScript dialogs, HTTP Basic challenges, clearing cookies and the window's
|
||||
# content size (src/macos.rs). The versions wry already pulls in, so no new
|
||||
# crate is added.
|
||||
objc2 = { version = "0.6.5", default-features = false, features = ["std"] }
|
||||
block2 = { version = "0.6.2", default-features = false, features = ["std"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"block2",
|
||||
"NSDate",
|
||||
"NSGeometry",
|
||||
"NSObject",
|
||||
"NSOperation",
|
||||
"NSRange",
|
||||
"NSSet",
|
||||
"NSString",
|
||||
"NSURL",
|
||||
"NSURLAuthenticationChallenge",
|
||||
"NSURLCredential",
|
||||
"NSURLProtectionSpace",
|
||||
"NSURLRequest",
|
||||
"NSURLResponse",
|
||||
"NSURLSession",
|
||||
] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"NSAlert",
|
||||
"NSApplication",
|
||||
"NSButton",
|
||||
"NSControl",
|
||||
"NSResponder",
|
||||
"NSTextField",
|
||||
"NSView",
|
||||
"NSWindow",
|
||||
] }
|
||||
objc2-web-kit = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"block2",
|
||||
"objc2-app-kit",
|
||||
"WKFrameInfo",
|
||||
"WKNavigationDelegate",
|
||||
"WKSecurityOrigin",
|
||||
"WKUIDelegate",
|
||||
"WKWebView",
|
||||
"WKWebsiteDataRecord",
|
||||
"WKWebsiteDataStore",
|
||||
] }
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
strip = true
|
||||
panic = "abort"
|
||||
@@ -0,0 +1,272 @@
|
||||
# Codeman Desktop
|
||||
|
||||
A small native app that opens Codeman in its own window. Double-click it, and
|
||||
it runs Codeman on this Mac (installing it first if it is not there) or
|
||||
connects to Codeman on another machine (installing it there over SSH if
|
||||
needed), and Codeman fills the window. `⌃⌘F` puts it in full screen.
|
||||
|
||||
macOS first: the app runs on 11.3 or later, and Codeman's own page needs the
|
||||
WebKit of Safari 16.4 (see Known limits). The same code is meant to build for
|
||||
Windows and Linux later.
|
||||
|
||||
- **Size:** 4.6 MB for the universal `Codeman.app` (Apple Silicon + Intel), 3 MB as a `.dmg` (measured on the first build).
|
||||
- **Stack:** Rust with [tao](https://crates.io/crates/tao) (window and event loop),
|
||||
[wry](https://crates.io/crates/wry) (the system web view: WKWebView on macOS) and
|
||||
[muda](https://crates.io/crates/muda) (native menus), plus [objc2](https://crates.io/crates/objc2)
|
||||
for the two things wry leaves out on macOS (JavaScript dialogs, HTTP Basic login).
|
||||
No bundled browser and no Node in the app.
|
||||
- **Server:** unchanged. The app is a client of Codeman's web UI, like a browser tab.
|
||||
|
||||
## Why it is cheap
|
||||
|
||||
Codeman is already a web app, so the desktop app is a native window around the
|
||||
operating system's own web view. An Electron build of the same thing would ship
|
||||
a whole Chromium (around 150 MB). The native side only adds what a browser tab
|
||||
cannot do.
|
||||
|
||||
## What it does (v0.1)
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **This Mac** | The connect screen's first tab looks for Codeman on this Mac and offers what fits: *Open Codeman* when it runs, *Start Codeman* when it is installed but stopped, *Install Codeman on this Mac* when it is not there. The address comes from Codeman's LaunchAgent (port, sub-path, HTTPS). When nothing answers there but one of your own Codeman servers runs (found with `ps` and `lsof`: a `codeman web --port 4000` in a terminal, say), the tab opens that one, or says where it listens; it never offers to start a second server, which would take over the first one's sessions, and Start refuses while one runs. Start asks launchd to run the LaunchAgent (`kickstart`, or `bootstrap` when it is not loaded), so the server keeps its own settings and supervision; without a LaunchAgent it runs `codeman web -d`. The login comes from where Codeman keeps it: the LaunchAgent's `CODEMAN_USERNAME`/`CODEMAN_PASSWORD`, else `~/.codeman/.env` (what Codeman's command-line clients read), `admin` by default. It goes only to `127.0.0.1` on that Codeman's port, only while one of your own Codeman processes holds that port, is never saved to the Keychain, and never reaches the page. Whether Codeman is installed is looked up in its files and processes, then the login shell; the interactive profile (nvm in `.zshrc`, say) only on *Check again*. Install opens Terminal with Codeman's installer (`install.sh --local --service --port N`): it may ask for the Mac password (Homebrew, Node.js, tmux) and which AI coding tools to set up, then Codeman runs as a LaunchAgent, so it keeps running when the app quits and starts at login. *Also reach it from my phone and other computers* drops `--local`, and the installer asks how (Tailscale, or the local network with a password). Port 3000 is used unless something else answers there, then the next free one. While the installer runs, the app looks every 3 seconds and opens Codeman as soon as it answers; it stops looking after the first answer, after 30 minutes, or 90 seconds after a finished install whose server never answered (then it offers Start). An install still running in Terminal is recognized by its process, so the tab waits for it instead of offering Install twice. |
|
||||
| **Another machine** | The second tab connects to a server by address (below). *Codeman is not installed there yet?* opens Terminal, connects with `ssh -t` and runs Codeman's installer on that machine, which asks its questions there; the app then suggests `http://<host>:3000` and the installer prints the real address at the end. The SSH login is checked to the characters of a user and host name (no option can be slipped in) and may carry a `:port`. The remote command runs under `bash -o pipefail`, so a failed download fails the install instead of reporting success. The same tab shows the one-line install command, with a Copy button, to run on a machine by hand. |
|
||||
| **Connect screen** | Server address, recent servers, a login for password-protected servers (password kept in the macOS Keychain), auto-connect at launch. It explains each failure: nothing listening; wrong password; too many failed logins (the password field stays open, since a single-user Codeman accepts the right password even then); unknown host name; an address this Mac cannot reach (with a pointer to the Local Network setting); an `http://` address on a port that only speaks HTTPS; an untrusted certificate; a redirect, with a button for the suggested `https://` address; not a Codeman server. A multi-user account that must change its password connects, and Codeman's own dialog asks for the new one. If the server page has not started showing within 15 seconds, or you press Cancel while it opens, the connect screen comes back with a notice. On a Mac whose WebKit is too old for Codeman it says so and Connect stays off (see Known limits). |
|
||||
| **Start Codeman** | On the This Mac tab, and when `http://127.0.0.1:<port>` or `http://localhost:<port>` answers nothing, one click runs `codeman web -d` (or `~/.codeman/app`) with your login shell's environment, so the server gets your real PATH (Homebrew, nvm) for the agents it spawns. zsh, bash and other POSIX shells run the start themselves; fish, nu, xonsh, tcsh and other shells only report their environment, and the start runs under `/bin/sh` with it. Offered for those two addresses only: `codeman web -d` listens on 127.0.0.1. |
|
||||
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected with, so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears the app's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
|
||||
| **Dialogs** | Codeman's `confirm()`, `prompt()` and `alert()` (Delete case, Kill all sessions, Update Codeman, discarding unsaved edits, ...) show as native macOS dialogs. wry implements none of them, and without them WKWebView answers Cancel without showing anything. |
|
||||
| **Full screen** | `⌃⌘F` or the green button. The last state is restored at launch; *Always Open in Full Screen* forces it. Leaving full screen returns to the saved window size and position. |
|
||||
| **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Switch Server `⇧⌘O`, Developer Tools `⌥⌘I`. The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. |
|
||||
| **Pop-outs** | Implements Codeman's existing native-wrapper bridge, `window.CodemanHost` (`openInHostWindow` in `src/web/public/app.js`), so popping out a session or a file preview opens a real app window, and the pop-out icon is on by default. Session and rendered-HTML pop-outs come only from Codeman's own pop-out button. A `window.open` from page script opens only Codeman's file and download windows, without taking keyboard focus, at most 3 at once and then 1 per second. Only Codeman's own pop-out pages become app windows (see Decisions); when the app refuses one, Codeman shows a toast. A web tab's *Open in new tab* opens the dashboard in your default browser, as it would from a browser tab. |
|
||||
| **Links** | On Codeman's own pages (the dashboard and session windows), a link to another site opens in your default browser, also on `⌘`-click or a middle click. Pages can send at most 3 links to the browser at once, then 1 per second. Links to other sites inside rendered HTML previews and web tabs do not open (see Known limits). |
|
||||
| **Downloads** | Codeman's Download links, and downloads Codeman opens in a new window, save the file to `~/Downloads` whatever its type, and a toast in Codeman names the file. Files the web view cannot display are saved the same way. |
|
||||
| **Window** | Size, position and full-screen state are remembered. A saved window that hangs off the screen it opens on (it was last on a larger display that is gone, say) is pulled back on and shrunk to fit; one whose title bar is on no screen at all opens at the default size instead. Clicking the Dock icon brings back a minimized window. |
|
||||
|
||||
## Build (on a Mac)
|
||||
|
||||
Needs Rust 1.90 or newer ([rustup](https://rustup.rs); `rustup update` for an older
|
||||
toolchain) and the Xcode Command Line Tools (`xcode-select --install`).
|
||||
|
||||
```bash
|
||||
cd packages/desktop
|
||||
cargo test # unit tests
|
||||
./scripts/bundle-macos.sh # dist/Codeman.app for this Mac's architecture
|
||||
./scripts/bundle-macos.sh --universal --dmg # Apple Silicon + Intel, plus dist/Codeman-<version>.dmg
|
||||
open dist/Codeman.app
|
||||
```
|
||||
|
||||
The script builds with `--locked` against the committed `Cargo.lock`, targets
|
||||
the macOS version in `macos/Info.plist` (`LSMinimumSystemVersion`, 11.3), and
|
||||
takes the binary from where cargo says it wrote it, so `CARGO_TARGET_DIR` and a
|
||||
cargo config's `build.target-dir` work.
|
||||
|
||||
Settings live in `~/Library/Application Support/Codeman/desktop.json`; passwords
|
||||
in the Keychain under *Codeman Desktop*, one item per username and server. A
|
||||
`desktop.json` the app cannot read or parse is moved aside, never overwritten:
|
||||
to `desktop.json.corrupt`, or to the first free name of `desktop.json.corrupt.1`
|
||||
to `.corrupt.9` when that one is taken, so an earlier copy is kept. If all ten
|
||||
names are taken, or the file cannot be moved, the app starts with default
|
||||
settings and saves nothing, which leaves the file where it is. When a server's
|
||||
username changes (a change of letter case counts), or a server drops off the
|
||||
recent list (it keeps 8), the Keychain item of the old username is deleted.
|
||||
|
||||
## Decisions, and why
|
||||
|
||||
**tao + wry + muda directly, not Tauri.** Tauri is built on the same three crates.
|
||||
The deciding detail is login: Codeman's password protection is HTTP Basic, and
|
||||
a WKWebView shows no login dialog of its own (wry 0.57 implements no
|
||||
authentication-challenge handler). So the app sends the `Authorization` header
|
||||
itself on the first load, with wry's `load_url_with_headers` (Tauri 2.12's
|
||||
`navigate()` takes only a URL), and from then on answers the HTTP Basic
|
||||
challenges of Codeman's own pages with the current login. Codeman keeps its
|
||||
session cookies in memory, so after a server restart that answer is what keeps
|
||||
the page logged in. Using the crates directly is also smaller.
|
||||
|
||||
**What wry leaves out is added at runtime, not patched in.** `src/macos.rs` adds
|
||||
the JavaScript dialog methods and the authentication-challenge method to the
|
||||
classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
|
||||
|
||||
**What a page may ask of the app** (all in `src/policy.rs`, unit-tested):
|
||||
|
||||
- Codeman shows content it did not write on its own origin: rendered HTML files
|
||||
(`/html-view/`) and proxied dashboards (`/webview/`). Only Codeman's own app
|
||||
shell (the dashboard and a session pop-out) may use `window.CodemanHost`.
|
||||
That is an allowlist on the raw path, and a path holding any `%` fails it, so
|
||||
an encoded spelling or a route Codeman adds later stays out.
|
||||
- An app window opens only for Codeman's own pop-out pages under the server's
|
||||
base path, checked after decoding the path once, and which ones depends on
|
||||
who asks. `window.CodemanHost` (the app shell only) may open sessions,
|
||||
rendered HTML views, the raw, preview, attachment and folder file routes, and
|
||||
`api/download`. A `window.open` or `target=_blank` link, which WebKit passes
|
||||
on from any frame without saying which, gets only the file routes and
|
||||
`api/download`, the pages Codeman itself opens that way; otherwise a rendered
|
||||
HTML file could open copies of itself as top-level windows that pass for the
|
||||
app's own. Such a window does not take keyboard focus, and these windows
|
||||
have a budget of their own (3 at once, then 1 per second), apart from the
|
||||
one links draw on. Any other page on the server's origin is refused rather
|
||||
than sent to the browser: a top-level `/webview/` load would escape the web
|
||||
tab's iframe sandbox in either place, so it never opens anywhere.
|
||||
`window.open('')` is refused too, since WebKit's blank window carries none of
|
||||
the app's handlers.
|
||||
- wry's navigation handler sees every frame and does not say which one. So a
|
||||
navigation to another site is blocked rather than opened in the browser;
|
||||
otherwise a page full of external iframes could open browser tabs. A real
|
||||
link click is sent out by the injected script in the main frame only.
|
||||
- Only `http(s)` URLs ever reach the default browser, at most 3 at once and
|
||||
then 1 per second. macOS lets a page call `window.open` without a click, so
|
||||
this keeps a script from opening a browser tab for every call.
|
||||
- The `Authorization` header is only sent to URLs under the server's base path.
|
||||
The login answers a Basic challenge only when it is Codeman's own: the
|
||||
server's scheme, host and port (never a proxy's), a URL below the base path,
|
||||
and not a web tab (`webview/`) or a rendered HTML file (`html-view/`), which
|
||||
relay 401s from content Codeman did not write. Only such a challenge can
|
||||
send the user back to the connect screen. WebKit is handed the login without
|
||||
persistence, so it keeps no copy: every challenge gets the current login,
|
||||
and one from before a Switch Server is never replayed.
|
||||
- Each connect starts by clearing the app's cookies (never local storage).
|
||||
Codeman checks its session cookie before the `Authorization` header, so an
|
||||
earlier user's cookie would otherwise win over the new login.
|
||||
- Microphone and camera requests prompt per page. wry's default without a
|
||||
handler is to grant them to every frame, sandboxed previews included.
|
||||
- The bundled connect page keeps working until a server page commits in the
|
||||
main window (it is still the live page while the server loads), and only
|
||||
the main window may talk to it.
|
||||
- `codeman web -d` gets the port and base path as separate arguments, never as
|
||||
shell text.
|
||||
|
||||
**The installer runs in Terminal, not inside the app.** `install.sh` asks for
|
||||
the administrator password on a terminal (Homebrew, its sudo keep-alive), the
|
||||
Xcode tools arrive as a system dialog, and ssh asks about host keys and
|
||||
passwords on a terminal too, so an install without one fails on the first
|
||||
fresh Mac. The app writes a short script to the per-user temporary folder
|
||||
(mode 0700, created fresh, deleted by the script as it starts) and opens it
|
||||
with `open -b com.apple.Terminal`, which needs no permission; scripting
|
||||
Terminal with osascript would ask for Automation access. The script prints
|
||||
what it runs. A This Mac install downloads the installer to a temporary file
|
||||
and runs it from there, so the installer's input is the terminal. Everything in
|
||||
the scripts is built and unit-tested in `src/setup.rs`; the page sends only
|
||||
which install it wants, whether other devices should reach it, and the SSH
|
||||
login, which is checked before it is quoted.
|
||||
|
||||
**This Mac's own login comes from where Codeman keeps it.** A Codeman
|
||||
installed with a password keeps it in its LaunchAgent (`install.sh`) or in
|
||||
`~/.codeman/.env` (what `codeman attach`, `codeman tui` and `codeman agent`
|
||||
read). The app reads the same places, so a password-protected Codeman on this
|
||||
Mac opens without typing the password. The username and password always come
|
||||
from the same place, since the server reads its username from its own
|
||||
environment. The login goes only to `127.0.0.1` on that Codeman's port, and
|
||||
only while `lsof` shows one of your own Codeman processes holding that port:
|
||||
with Codeman stopped, whatever else listens there never gets it.
|
||||
|
||||
**Never a second server on the same sessions.** Two Codeman servers on one
|
||||
data directory and tmux socket attach to each other's live sessions, and
|
||||
`codeman web -d` only notices a server it started itself or one at the same
|
||||
address. So the app looks for running Codeman servers of this user (`ps`)
|
||||
before it offers or runs a start, and opens the one it finds instead.
|
||||
|
||||
**Closing the main window quits the app.** Codeman's sessions keep running on
|
||||
the server, so nothing is lost, and reopening takes about a second.
|
||||
|
||||
**One reachability probe per user action, and one to check a refused login.**
|
||||
Codeman counts a request without valid credentials against its login rate
|
||||
limit (10 per IP, 15 minutes; a successful login resets the count), so the app
|
||||
never retries in a loop. Once the server refuses the login in a challenge, the
|
||||
app sends it only once more, in the single probe that checks the refusal. If
|
||||
that probe is refused or rate limited, the connect screen comes back; the
|
||||
app does not send the refused login again. Keeping no copy of the login in WebKit has a cost here: after a server
|
||||
restart, each request that arrives without a cookie gets a 401 before the
|
||||
login goes out, and those count until one succeeds. Many windows reconnecting
|
||||
at once can push a request past 10, and that request then fails with a 429
|
||||
instead of being answered. A refusal that lands while you are in another app
|
||||
does not bring Codeman forward: the connect screen loads where the window is,
|
||||
and the Dock icon bounces.
|
||||
|
||||
## Known limits
|
||||
|
||||
- **Self-signed HTTPS is refused.** A server started with `codeman web --https`
|
||||
uses a self-signed certificate, and WKWebView rejects it (wry has no trust
|
||||
override). Use `http://127.0.0.1:3000` for a server on this Mac. For another
|
||||
machine, serve Codeman through `tailscale serve`
|
||||
(`https://<machine>.<tailnet>.ts.net` has a real certificate) or a reverse
|
||||
proxy with a real certificate. Marking the certificate as trusted in
|
||||
Keychain Access can only help at `https://localhost` or `https://127.0.0.1`,
|
||||
the only names Codeman's certificate carries, and may not work even there.
|
||||
The connect screen says so when it happens.
|
||||
- **Keychain prompt after every rebuild of an ad-hoc build.** The Keychain
|
||||
knows the app that saved a password by its code signature, and an ad-hoc
|
||||
signature changes with every build and update. So each new build asks once
|
||||
for access to the saved passwords: choose *Always Allow*. All Keychain work
|
||||
runs on one background thread, so the prompt does not freeze the window
|
||||
while it waits for an answer. To keep one identity across builds, sign with
|
||||
`SIGN_IDENTITY` (a self-made code-signing certificate from Keychain Access
|
||||
is enough). Microphone and camera permissions are asked again for the same
|
||||
reason.
|
||||
- **Gatekeeper.** Without a Developer ID the app is signed ad hoc. A build you
|
||||
made yourself opens normally; a copy that arrived by download or AirDrop is
|
||||
quarantined. On macOS 15 and later, try to open it once, then click *Open
|
||||
Anyway* in System Settings > Privacy & Security (it asks for an administrator
|
||||
password). On macOS 14 and earlier, right-click it and choose *Open* once.
|
||||
Either way, `xattr -dr com.apple.quarantine /Applications/Codeman.app` on the
|
||||
copy in Applications works too. Shipping it to other people needs a Developer
|
||||
ID signature and notarization:
|
||||
`SIGN_IDENTITY="Developer ID Application: ..." ./scripts/bundle-macos.sh --dmg`,
|
||||
then `xcrun notarytool submit` and `xcrun stapler staple`.
|
||||
- **Local Network permission (macOS 15 and later).** The first connection to an
|
||||
address on the local network (a LAN IP, a `.local` name) makes macOS ask
|
||||
whether Codeman may use the local network, and that first attempt can fail
|
||||
while the question is open: connect again after answering. If it was denied,
|
||||
turn Codeman on in System Settings > Privacy & Security > Local Network. A
|
||||
server started with *Start Codeman on this Mac* counts as part of the app
|
||||
here, so the same answer covers what it reaches on the local network (ssh to
|
||||
LAN hosts, Wake-on-LAN, web tabs pointing at LAN dashboards), also after the
|
||||
app quits.
|
||||
- **Subagent transcript windows do not open in the app.** Codeman writes that
|
||||
view into a blank `window.open('')` window, which the app refuses (see
|
||||
Decisions), and shows a toast instead. A Codeman without the null check in
|
||||
`viewSubagentTranscript` (`src/web/public/panels-ui.js`) reports *Failed to
|
||||
load transcript* there. Open the transcript from a browser tab.
|
||||
- **Dialogs are app-modal.** While a JavaScript dialog is open, every Codeman
|
||||
window waits for it. A page that calls `alert()` in a loop (a rendered HTML
|
||||
preview or a web tab can) leaves no way out but Force Quit (`⌥⌘⎋`).
|
||||
- **Codeman needs the WebKit of Safari 16.4.** The app itself runs on macOS
|
||||
11.3 or later (downloads go through WKDownload, which arrived in 11.3), but
|
||||
Codeman's terminal (xterm.js 6 uses class static blocks) needs the WebKit
|
||||
that came with Safari 16.4: macOS 13.3, or macOS 11 or 12 with Safari 16.4
|
||||
or later installed. On an older WebKit the connect screen says so and does
|
||||
not connect. Session pop-outs also need BroadcastChannel (Safari 15.4),
|
||||
which the same requirement covers.
|
||||
- **Links in rendered HTML and web tabs do not open.** A link to another site
|
||||
inside a rendered HTML preview or a web tab does nothing, in the preview
|
||||
overlay, and for a rendered HTML file in its pop-out window too. The app
|
||||
sends links out only from Codeman's own pages, and blocks navigation to
|
||||
other sites in every frame (see Decisions).
|
||||
- **No login dialog for a web tab's own HTTP Basic login.** The app answers
|
||||
only Codeman's own login, and WebKit shows no dialog for any other, so a
|
||||
dashboard in a web tab that asks for HTTP Basic shows its 401 page.
|
||||
- **Downloads from previews and web tabs are saved without asking.** Rendered
|
||||
HTML files and web tabs are allowed to start downloads, and the app saves
|
||||
every download to `~/Downloads` without a prompt. Asking first for those
|
||||
frames is not done yet.
|
||||
- **No desktop notifications yet.** WKWebView has no Web Notification API.
|
||||
Native notifications are the first item on the list below.
|
||||
- **No service worker.** Codeman works without it; it is only an offline cache.
|
||||
- **Installing from the app is macOS only so far**, and installing on another
|
||||
machine needs ssh access to it and `curl` or `wget` there. The app does not
|
||||
know when a remote install is done or which address it chose: the installer
|
||||
prints the address, and you connect to it under Another machine.
|
||||
- **A This Mac install always sets Codeman up as a LaunchAgent** that starts
|
||||
at login. To stop it: `launchctl unload ~/Library/LaunchAgents/com.codeman.web.plist`;
|
||||
to remove Codeman: `curl -fsSL https://getcodeman.com/install | bash -s -- uninstall`.
|
||||
- **Windows and Linux** need their menu hookup (`init_for_hwnd`, GTK), a
|
||||
credential store (Credential Manager, Secret Service) and installers. The
|
||||
rest of the code is platform-neutral.
|
||||
|
||||
## Ideas for next
|
||||
|
||||
- Native notifications and a Dock badge with the number of sessions waiting
|
||||
for you (tao has `set_badge_label`; Codeman already tracks which sessions need input).
|
||||
- A global hotkey that brings Codeman to the front from anywhere.
|
||||
- A menu bar icon showing session states.
|
||||
- Trusting a self-signed server certificate by its fingerprint.
|
||||
- Asking before a download that a rendered HTML file or a web tab starts.
|
||||
- A way out of a page that keeps opening dialogs (a "block further dialogs" option).
|
||||
- Windows and Linux builds, a CI job that builds the `.dmg`, notarization, auto-update.
|
||||
@@ -0,0 +1,897 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Codeman</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0a0a0a;
|
||||
--panel: #121316;
|
||||
--line: #23252b;
|
||||
--line-strong: #30333b;
|
||||
--text: #e8eaed;
|
||||
--muted: #8b9099;
|
||||
--accent: #60a5fa;
|
||||
--accent-2: #3b82f6;
|
||||
--bad: #f87171;
|
||||
--warn: #fbbf24;
|
||||
--ok: #4ade80;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height: 100%; margin: 0; }
|
||||
body {
|
||||
background: radial-gradient(1200px 600px at 50% -10%, #111a2b 0%, var(--bg) 60%) fixed, var(--bg);
|
||||
color: var(--text);
|
||||
font: 14px/1.45 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
-webkit-user-select: none; user-select: none;
|
||||
}
|
||||
main { width: min(440px, calc(100vw - 48px)); }
|
||||
header { text-align: center; margin-bottom: 26px; }
|
||||
header img { width: 76px; height: 76px; display: block; margin: 0 auto 12px; }
|
||||
h1 { font-size: 24px; font-weight: 650; letter-spacing: -0.01em; margin: 0; }
|
||||
header p { margin: 4px 0 0; color: var(--muted); }
|
||||
.card {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: 14px;
|
||||
padding: 20px; box-shadow: 0 20px 60px rgba(0,0,0,0.45);
|
||||
}
|
||||
label.field { display: block; font-size: 12px; color: var(--muted); margin: 0 0 6px; }
|
||||
input[type=text], input[type=password], input[type=url] {
|
||||
width: 100%; height: 38px; padding: 0 12px; border-radius: 9px;
|
||||
border: 1px solid var(--line-strong); background: #0c0d10; color: var(--text);
|
||||
font: inherit; outline: none; -webkit-user-select: text; user-select: text;
|
||||
}
|
||||
input:focus { border-color: var(--accent-2); box-shadow: 0 0 0 3px rgba(59,130,246,0.25); }
|
||||
.row { display: flex; gap: 10px; }
|
||||
.row > * { flex: 1; }
|
||||
.gap { height: 14px; }
|
||||
#recent { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
|
||||
#recent:empty { display: none; }
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: 2px; max-width: 100%;
|
||||
border: 1px solid var(--line-strong); border-radius: 999px; background: #0f1013;
|
||||
color: var(--text); font-size: 12px;
|
||||
}
|
||||
.chip button { all: unset; cursor: default; padding: 4px 4px 4px 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 300px; }
|
||||
.chip button.x { padding: 4px 9px 4px 4px; color: var(--muted); }
|
||||
.chip button.x:hover { color: var(--bad); }
|
||||
.chip:hover { border-color: var(--accent-2); }
|
||||
.chip button:disabled { opacity: 0.5; }
|
||||
#login[hidden] { display: none; }
|
||||
#login { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--line); }
|
||||
.check { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 13px; margin-top: 10px; }
|
||||
.check input { accent-color: var(--accent-2); margin: 0; }
|
||||
.actions { display: flex; gap: 10px; margin-top: 18px; }
|
||||
button.primary, button.secondary {
|
||||
height: 38px; border-radius: 9px; font: inherit; font-weight: 600; padding: 0 16px; cursor: default;
|
||||
}
|
||||
button.primary { flex: 1; border: 0; color: white; background: linear-gradient(180deg, var(--accent) 0%, var(--accent-2) 100%); }
|
||||
button.primary:disabled { opacity: 0.55; }
|
||||
button.secondary { border: 1px solid var(--line-strong); background: #16181d; color: var(--text); }
|
||||
button.secondary:hover { border-color: var(--accent-2); }
|
||||
button.secondary:disabled { opacity: 0.55; }
|
||||
button[hidden] { display: none; }
|
||||
#status { min-height: 20px; margin-top: 14px; font-size: 13px; color: var(--muted); display: flex; gap: 8px; align-items: flex-start; }
|
||||
#status.bad { color: var(--bad); }
|
||||
#status.warn { color: var(--warn); }
|
||||
#status.ok { color: var(--ok); }
|
||||
#status .detail { display: block; color: var(--muted); font-size: 12px; margin-top: 4px; white-space: pre-wrap; -webkit-user-select: text; user-select: text; }
|
||||
#suggest { display: block; max-width: 100%; margin-top: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#suggest[hidden] { display: none; }
|
||||
#webkit { margin: 0 0 14px; padding: 10px 12px; border: 1px solid rgba(251,191,36,0.4); border-radius: 9px; background: rgba(251,191,36,0.08); color: var(--warn); font-size: 13px; -webkit-user-select: text; user-select: text; }
|
||||
#webkit[hidden] { display: none; }
|
||||
.spinner { width: 14px; height: 14px; flex: none; margin-top: 2px; border-radius: 50%; border: 2px solid rgba(96,165,250,0.25); border-top-color: var(--accent); animation: spin 0.8s linear infinite; }
|
||||
.spinner[hidden] { display: none; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 2.4s; } }
|
||||
.prefs { margin-top: 16px; }
|
||||
.tabs { display: flex; gap: 4px; padding: 4px; margin: 0 0 18px; background: #0c0d10; border: 1px solid var(--line); border-radius: 11px; }
|
||||
.tabs button { all: unset; flex: 1; text-align: center; height: 30px; line-height: 30px; border-radius: 8px; font-weight: 600; font-size: 13px; color: var(--muted); cursor: default; }
|
||||
.tabs button:hover { color: var(--text); }
|
||||
.tabs button[aria-selected="true"] { background: #1c1f26; color: var(--text); box-shadow: inset 0 1px 0 rgba(255,255,255,0.04), 0 1px 3px rgba(0,0,0,0.45); }
|
||||
.tabs button:focus-visible { outline: 2px solid var(--accent-2); outline-offset: 1px; }
|
||||
[role=tabpanel][hidden] { display: none; }
|
||||
.local { display: flex; gap: 12px; align-items: flex-start; min-height: 42px; }
|
||||
.dot { width: 10px; height: 10px; border-radius: 50%; margin-top: 5px; flex: none; background: #4b5059; }
|
||||
.dot.ok { background: var(--ok); box-shadow: 0 0 0 4px rgba(74,222,128,0.14); }
|
||||
.dot.warn { background: var(--warn); }
|
||||
.dot.busy { background: var(--accent); animation: pulse 1.2s ease-in-out infinite; }
|
||||
@keyframes pulse { 50% { opacity: 0.35; } }
|
||||
@media (prefers-reduced-motion: reduce) { .dot.busy { animation: none; } }
|
||||
#local-title { font-weight: 600; }
|
||||
.sub { color: var(--muted); font-size: 12px; margin-top: 3px; -webkit-user-select: text; user-select: text; overflow-wrap: anywhere; }
|
||||
#local-network-row[hidden] { display: none; }
|
||||
#elsewhere { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); }
|
||||
#elsewhere summary { color: var(--muted); font-size: 13px; cursor: default; list-style: none; }
|
||||
#elsewhere summary::-webkit-details-marker { display: none; }
|
||||
#elsewhere summary::before { content: '\25B8'; display: inline-block; width: 14px; transition: transform 0.15s; }
|
||||
#elsewhere[open] summary::before { transform: rotate(90deg); }
|
||||
#elsewhere summary:hover { color: var(--text); }
|
||||
#elsewhere .field { margin-top: 12px; }
|
||||
.inline { display: flex; gap: 8px; align-items: center; }
|
||||
.inline > input { flex: 1; min-width: 0; }
|
||||
.inline > button { flex: none; }
|
||||
.oneliner { display: flex; gap: 8px; align-items: center; margin-top: 8px; }
|
||||
.oneliner code { flex: 1; min-width: 0; font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; background: #0c0d10; border: 1px solid var(--line-strong); border-radius: 8px; padding: 9px 10px; color: #c9d1d9; -webkit-user-select: all; user-select: all; overflow-x: auto; white-space: nowrap; }
|
||||
.statusrow { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.statusrow #status { flex: 1; }
|
||||
.statusrow #cancel { margin-top: 10px; }
|
||||
footer { margin-top: 18px; text-align: center; color: #5d626b; font-size: 12px; }
|
||||
footer a { color: #7c8491; text-decoration: none; cursor: default; }
|
||||
footer a:hover { color: var(--accent); }
|
||||
kbd { font: 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace; border: 1px solid var(--line-strong); border-bottom-width: 2px; border-radius: 4px; padding: 2px 4px; color: #9aa1ab; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<img src="icon.png" alt="">
|
||||
<h1>Codeman</h1>
|
||||
<p>Run Codeman on this Mac, or connect to another machine</p>
|
||||
</header>
|
||||
|
||||
<div class="card">
|
||||
<div class="tabs" role="tablist" aria-label="Where Codeman runs">
|
||||
<button type="button" role="tab" id="tab-local" aria-controls="pane-local" aria-selected="true">This Mac</button>
|
||||
<button type="button" role="tab" id="tab-remote" aria-controls="form" aria-selected="false" tabindex="-1">Another machine</button>
|
||||
</div>
|
||||
|
||||
<p id="webkit" role="alert" hidden>Codeman needs a newer WebKit than this Mac has: macOS 13.3 or later, or Safari 16.4 or later on macOS 11 and 12.</p>
|
||||
|
||||
<section id="pane-local" role="tabpanel" aria-labelledby="tab-local">
|
||||
<div class="local">
|
||||
<span class="dot busy" id="local-dot"></span>
|
||||
<div>
|
||||
<div id="local-title">Looking for Codeman on this Mac…</div>
|
||||
<div class="sub" id="local-detail"></div>
|
||||
</div>
|
||||
</div>
|
||||
<label class="check" id="local-network-row" hidden><input id="local-network" type="checkbox"> Also reach it from my phone and other computers (the installer asks how)</label>
|
||||
<div class="actions">
|
||||
<button class="primary" id="local-open" type="button" hidden>Open Codeman</button>
|
||||
<button class="primary" id="local-start" type="button" hidden>Start Codeman</button>
|
||||
<button class="primary" id="local-install" type="button" hidden>Install Codeman on this Mac</button>
|
||||
<button class="secondary" id="local-stop" type="button" hidden>Stop waiting</button>
|
||||
<button class="secondary" id="local-check" type="button" hidden>Check again</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<form id="form" role="tabpanel" aria-labelledby="tab-remote" autocomplete="off" novalidate hidden>
|
||||
<label class="field" for="url">Server address</label>
|
||||
<input id="url" type="text" spellcheck="false" autocapitalize="off"
|
||||
placeholder="http://127.0.0.1:3000 or https://your-box.ts.net" list="recent-list">
|
||||
<datalist id="recent-list"></datalist>
|
||||
<div id="recent" aria-label="Recent servers"></div>
|
||||
|
||||
<div id="login" hidden>
|
||||
<div class="row">
|
||||
<div>
|
||||
<label class="field" for="username">Username</label>
|
||||
<input id="username" type="text" spellcheck="false" autocapitalize="off" placeholder="admin">
|
||||
</div>
|
||||
<div>
|
||||
<label class="field" for="password">Password</label>
|
||||
<input id="password" type="password" placeholder="">
|
||||
</div>
|
||||
</div>
|
||||
<label class="check"><input id="remember" type="checkbox" checked> Remember the password in the Keychain</label>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button class="primary" id="connect" type="submit">Connect</button>
|
||||
<button class="secondary" id="start" type="button" hidden>Start Codeman on this Mac</button>
|
||||
</div>
|
||||
|
||||
<details id="elsewhere">
|
||||
<summary>Codeman is not installed there yet?</summary>
|
||||
<label class="field" for="ssh">Install it over SSH</label>
|
||||
<div class="inline">
|
||||
<input id="ssh" type="text" spellcheck="false" autocapitalize="off" placeholder="you@machine, or a name from ~/.ssh/config">
|
||||
<button class="secondary" id="ssh-install" type="button">Install</button>
|
||||
</div>
|
||||
<p class="sub">Terminal opens, connects with ssh and runs Codeman’s installer there. Or run this in a terminal on that machine:</p>
|
||||
<div class="oneliner"><code id="oneliner">curl -fsSL https://getcodeman.com/install | bash</code><button class="secondary" id="copy" type="button">Copy</button></div>
|
||||
</details>
|
||||
</form>
|
||||
|
||||
<div class="statusrow">
|
||||
<div id="status" role="status" aria-live="polite"><span class="spinner" id="spinner" hidden></span><span id="status-text"></span></div>
|
||||
<button class="secondary" id="cancel" type="button" hidden>Cancel</button>
|
||||
</div>
|
||||
<button class="secondary" id="suggest" type="button" hidden></button>
|
||||
|
||||
<div class="prefs">
|
||||
<label class="check"><input id="auto" type="checkbox"> Connect automatically when the app opens</label>
|
||||
<label class="check"><input id="fullscreen" type="checkbox"> Always open in full screen <kbd>⌃⌘F</kbd></label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
<span id="version">Codeman Desktop</span> ·
|
||||
<a href="#" id="docs">Help</a>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
// Codeman's terminal (xterm 6) uses class static blocks, which WebKit parses
|
||||
// from Safari 16.4 on. An older WebKit rejects this whole script, so the flag
|
||||
// stays unset. This is its own script because the page's CSP has no
|
||||
// 'unsafe-eval', so new Function cannot run the test.
|
||||
void class { static { window.__codemanStaticBlocks = true; } };
|
||||
</script>
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
// Codeman would not load in this web view: say so, never connect, and keep
|
||||
// Connect disabled. The page still answers the app (ready, preferences).
|
||||
var tooOld = window.__codemanStaticBlocks !== true;
|
||||
var els = {
|
||||
form: $('form'), url: $('url'), list: $('recent-list'), recent: $('recent'),
|
||||
login: $('login'), username: $('username'), password: $('password'), remember: $('remember'),
|
||||
connect: $('connect'), cancel: $('cancel'), start: $('start'), suggest: $('suggest'),
|
||||
status: $('status'), spinner: $('spinner'), statusText: $('status-text'),
|
||||
auto: $('auto'), fullscreen: $('fullscreen'), version: $('version'), webkit: $('webkit'),
|
||||
tabLocal: $('tab-local'), tabRemote: $('tab-remote'), paneLocal: $('pane-local'),
|
||||
localDot: $('local-dot'), localTitle: $('local-title'), localDetail: $('local-detail'),
|
||||
localNetworkRow: $('local-network-row'), localNetwork: $('local-network'),
|
||||
localOpen: $('local-open'), localStart: $('local-start'), localInstall: $('local-install'),
|
||||
localStop: $('local-stop'), localCheck: $('local-check'),
|
||||
elsewhere: $('elsewhere'), ssh: $('ssh'), sshInstall: $('ssh-install'), copy: $('copy')
|
||||
};
|
||||
var manual = /[?&]manual=1/.test(location.search);
|
||||
// startUrl: the address the user asked to start Codeman for ('' when this
|
||||
// page did not ask, e.g. it was reloaded while a start was running).
|
||||
// suggestion: the address the suggest button connects to.
|
||||
// tab: 'local' (This Mac) or 'remote' (Another machine). local: the last
|
||||
// This Mac status from the app. wait: set while an install runs in
|
||||
// Terminal and this page polls for the server it brings up.
|
||||
var state = {
|
||||
servers: [], busy: false, lastUrl: '', startUrl: '', suggestion: '',
|
||||
tab: 'local', local: null, localChecking: false, opening: false, wait: null, waitTimer: 0,
|
||||
stoppedWaiting: false
|
||||
};
|
||||
// While an install runs: how often to look, how long a finished install may
|
||||
// take to answer before Start is offered, and when to stop looking.
|
||||
var WAIT_POLL_MS = 3000;
|
||||
var WAIT_START_GRACE_MS = 90 * 1000;
|
||||
var WAIT_MAX_MS = 30 * 60 * 1000;
|
||||
|
||||
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
|
||||
|
||||
function setStatus(kind, text, detail) {
|
||||
els.status.className = kind || '';
|
||||
els.spinner.hidden = kind !== 'busy';
|
||||
els.statusText.textContent = text || '';
|
||||
if (detail) {
|
||||
var d = document.createElement('span');
|
||||
d.className = 'detail';
|
||||
d.textContent = detail;
|
||||
els.statusText.appendChild(d);
|
||||
}
|
||||
}
|
||||
|
||||
// One request at a time: every way to start one (Connect, a recent server,
|
||||
// the suggest button) is disabled while busy, never hidden, so the second
|
||||
// click of a double click cannot land on whatever moved into its place.
|
||||
// Cancel only where the native side can really cancel: a probe or a page
|
||||
// load, never a server start.
|
||||
function setBusy(busy, cancellable) {
|
||||
state.busy = busy;
|
||||
els.connect.disabled = busy || tooOld;
|
||||
els.suggest.disabled = busy || tooOld;
|
||||
els.cancel.hidden = !(busy && cancellable !== false);
|
||||
if (busy) els.start.hidden = true;
|
||||
disableChips();
|
||||
syncLocalButtons();
|
||||
}
|
||||
|
||||
// Forgetting a server stays possible when the WebKit is too old; connecting
|
||||
// to one does not.
|
||||
function disableChips() {
|
||||
Array.prototype.forEach.call(els.recent.querySelectorAll('button'), function (b) {
|
||||
b.disabled = state.busy || (tooOld && !b.classList.contains('x'));
|
||||
});
|
||||
}
|
||||
|
||||
// Nothing to suggest when this WebKit cannot open Codeman at any address.
|
||||
function suggest(url) {
|
||||
if (tooOld) return;
|
||||
state.suggestion = url;
|
||||
els.suggest.textContent = 'Use ' + url;
|
||||
els.suggest.title = 'Connect to ' + url;
|
||||
els.suggest.hidden = false;
|
||||
}
|
||||
|
||||
function hideSuggestion() {
|
||||
state.suggestion = '';
|
||||
els.suggest.hidden = true;
|
||||
}
|
||||
|
||||
function host(url) {
|
||||
try { var u = new URL(url); return u.host + (u.pathname === '/' ? '' : u.pathname.replace(/\/$/, '')); } catch (e) { return url; }
|
||||
}
|
||||
|
||||
// The address as the app normalizes it (policy::normalize_server_url):
|
||||
// http:// by default, https:// for a .ts.net name, no query or fragment, a
|
||||
// trailing slash. Only used to tell whether two addresses are one server.
|
||||
function normalize(raw) {
|
||||
var s = String(raw || '').trim();
|
||||
if (!s) return '';
|
||||
if (s.indexOf('://') < 0) {
|
||||
var name = s.split(/[\/:]/)[0].toLowerCase();
|
||||
s = (/\.ts\.net$/.test(name) ? 'https' : 'http') + '://' + s;
|
||||
}
|
||||
try {
|
||||
var u = new URL(s);
|
||||
u.search = '';
|
||||
u.hash = '';
|
||||
if (!/\/$/.test(u.pathname)) u.pathname += '/';
|
||||
return u.href;
|
||||
} catch (e) { return ''; }
|
||||
}
|
||||
|
||||
function sameServer(a, b) {
|
||||
var na = normalize(a);
|
||||
return na !== '' && na === normalize(b);
|
||||
}
|
||||
|
||||
function renderRecent() {
|
||||
els.recent.textContent = '';
|
||||
els.list.textContent = '';
|
||||
state.servers.forEach(function (s) {
|
||||
var opt = document.createElement('option');
|
||||
opt.value = s.url;
|
||||
els.list.appendChild(opt);
|
||||
|
||||
var chip = document.createElement('span');
|
||||
chip.className = 'chip';
|
||||
var pick = document.createElement('button');
|
||||
pick.type = 'button';
|
||||
pick.textContent = host(s.url) + (s.username ? ' (' + s.username + ')' : '');
|
||||
pick.title = 'Connect to ' + s.url;
|
||||
pick.addEventListener('click', function () {
|
||||
if (state.busy) return;
|
||||
choose(s);
|
||||
connect();
|
||||
});
|
||||
var x = document.createElement('button');
|
||||
x.type = 'button';
|
||||
x.className = 'x';
|
||||
x.textContent = '×';
|
||||
x.title = 'Forget this server' + (s.hasSavedPassword ? ' and its saved password' : '');
|
||||
x.addEventListener('click', function () { if (!state.busy) post({ cmd: 'forget', url: s.url }); });
|
||||
chip.appendChild(pick);
|
||||
chip.appendChild(x);
|
||||
els.recent.appendChild(chip);
|
||||
});
|
||||
disableChips();
|
||||
}
|
||||
|
||||
function choose(s) {
|
||||
els.url.value = s.url;
|
||||
els.username.value = s.username || '';
|
||||
els.password.value = '';
|
||||
els.password.placeholder = s.hasSavedPassword ? 'saved in Keychain' : '';
|
||||
els.login.hidden = !s.username;
|
||||
}
|
||||
|
||||
// The saved server the address field names, if any, with its login.
|
||||
function matchSaved() {
|
||||
var match = state.servers.filter(function (s) { return s.url === els.url.value.trim(); })[0];
|
||||
if (match) choose(match);
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (state.busy || tooOld) return;
|
||||
var url = els.url.value.trim();
|
||||
if (!url) { setStatus('bad', 'Enter the address of your Codeman server.'); els.url.focus(); return; }
|
||||
state.lastUrl = url;
|
||||
setBusy(true);
|
||||
setStatus('busy', 'Connecting to ' + url + '…');
|
||||
var msg = { cmd: 'connect', url: url, remember: els.remember.checked };
|
||||
if (!els.login.hidden) {
|
||||
if (els.username.value.trim()) msg.username = els.username.value.trim();
|
||||
if (els.password.value) msg.password = els.password.value;
|
||||
}
|
||||
post(msg);
|
||||
}
|
||||
|
||||
function showLogin() {
|
||||
els.login.hidden = false;
|
||||
if (!els.username.value) els.username.value = 'admin';
|
||||
els.password.focus();
|
||||
}
|
||||
|
||||
function hostName(url) {
|
||||
try { return new URL(url).hostname.toLowerCase(); } catch (e) { return ''; }
|
||||
}
|
||||
|
||||
var LOCAL_NETWORK = 'On macOS 15 and later the app may also need Local Network access: System Settings > Privacy & Security > Local Network, then turn on Codeman.';
|
||||
|
||||
var explain = {
|
||||
needsLogin: ['warn', 'This server asks for a login.', 'Codeman’s default username is admin; the password is CODEMAN_PASSWORD on the server.'],
|
||||
badCredentials: ['bad', 'Wrong username or password.', 'After 10 failed attempts Codeman locks logins from this address for 15 minutes.'],
|
||||
rateLimited: ['bad', 'Too many failed logins from this address.', 'If you know the password, enter it and connect: a single-user Codeman accepts the right password even now. Otherwise, or on a multi-user server, wait up to 15 minutes and try again.'],
|
||||
hostNotAllowed: ['bad', 'Codeman refused this host name.', 'Codeman only answers names it knows. Add this one to CODEMAN_ALLOWED_HOSTS on the server, or use its tailnet name or 127.0.0.1.'],
|
||||
refused: ['bad', 'Nothing is answering at this address.', ''],
|
||||
timeout: ['bad', 'The server did not answer within 5 seconds.', 'Check that the machine is awake and reachable (Tailscale connected, same network).'],
|
||||
unreachable: ['bad', 'This Mac cannot reach that address.', 'Check that the machine is on and on the same network (or that Tailscale is connected). ' + LOCAL_NETWORK],
|
||||
unresolvable: ['bad', 'That host name could not be found.', 'Check the spelling, or that Tailscale is connected for a .ts.net name.'],
|
||||
maybeHttps: ['bad', 'The server closed the connection without answering.', 'The port may be serving HTTPS: a Codeman started with --https only answers https://. Try the https:// address, or your tailnet name (https://….ts.net). Codeman’s own self-signed certificate names only localhost and 127.0.0.1, so the app cannot accept it at this address: serve Codeman through tailscale serve (a real ts.net certificate) or a reverse proxy with a real certificate.'],
|
||||
tlsUntrusted: ['bad', 'The server’s HTTPS certificate is not trusted.', 'This is usually Codeman’s self-signed certificate (codeman web --https). It names only localhost and 127.0.0.1, so the app cannot accept it at this address. Serve Codeman through tailscale serve (a real https://….ts.net certificate) or a reverse proxy with a real certificate. For a server on this Mac, run Codeman without --https and use http://127.0.0.1:PORT.'],
|
||||
passwordChangeRequired: ['warn', 'Codeman asks for a new password for this account.', 'Open it in a browser to set one, then connect with the new password.']
|
||||
};
|
||||
|
||||
// The same two at localhost or 127.0.0.1, the only names Codeman's
|
||||
// self-signed certificate carries, so the only ones where trusting it in
|
||||
// Keychain Access can help.
|
||||
var explainLoopback = {
|
||||
maybeHttps: 'The port may be serving HTTPS: a Codeman started with --https only answers https://. Try the https:// address. The app’s web view refuses Codeman’s self-signed certificate, though: marking it as trusted in Keychain Access may work, or run Codeman without --https.',
|
||||
tlsUntrusted: 'This is usually Codeman’s self-signed certificate (codeman web --https), which the app’s web view refuses. Run Codeman without --https and use http://127.0.0.1:PORT instead. Marking the certificate as trusted in Keychain Access may also work.'
|
||||
};
|
||||
|
||||
function loopbackName(url) {
|
||||
var h = hostName(url);
|
||||
return h === 'localhost' || h === '127.0.0.1';
|
||||
}
|
||||
|
||||
function onProbeResult(msg) {
|
||||
setBusy(false);
|
||||
hideSuggestion();
|
||||
var o = msg.outcome || {};
|
||||
var e = explain[o.kind];
|
||||
if (o.kind === 'needsLogin' || o.kind === 'badCredentials' || o.kind === 'rateLimited') {
|
||||
// The login fields live on the Another machine tab.
|
||||
selectTab('remote');
|
||||
showLogin();
|
||||
} else if (state.tab === 'local') {
|
||||
// Opening the Codeman on this Mac failed: look at it again.
|
||||
checkLocal('login');
|
||||
}
|
||||
if (o.kind === 'notCodeman') {
|
||||
setStatus('bad', 'Something answered, but it is not a Codeman server (HTTP ' + o.status + ').', 'Check the port and, behind a proxy, the path Codeman is mounted under.');
|
||||
} else if (o.kind === 'redirect') {
|
||||
var where = o.location ? 'It points to ' + o.location + '.' : '';
|
||||
if (o.suggested) {
|
||||
setStatus('warn', 'This address redirects to another one.', where + '\nCodeman seems to answer at ' + o.suggested + '.');
|
||||
suggest(o.suggested);
|
||||
} else {
|
||||
setStatus('bad', 'This address redirects somewhere else.', where + '\nThe app connects only to the address Codeman itself answers on. Check the address and, behind a proxy, the path Codeman is mounted under.');
|
||||
}
|
||||
} else if (o.kind === 'failed') {
|
||||
setStatus('bad', 'Could not connect.', o.detail || '');
|
||||
} else if (e) {
|
||||
var detail = e[2];
|
||||
if (o.kind === 'refused' && msg.canStart) detail = 'Codeman is not running on this Mac. Start it here, or check the port.';
|
||||
if (o.kind === 'rateLimited' && o.sentCredentials) detail = 'The saved or typed password may be wrong. ' + detail;
|
||||
if (o.kind === 'unresolvable' && /\.local\.?$/.test(hostName(msg.url))) {
|
||||
detail = 'Check the spelling, and that the machine is on and on the same network. ' + LOCAL_NETWORK;
|
||||
}
|
||||
if (explainLoopback[o.kind] && loopbackName(msg.url)) detail = explainLoopback[o.kind];
|
||||
if (o.kind === 'tlsUntrusted' && o.detail) detail += '\n(' + o.detail + ')';
|
||||
setStatus(e[0], e[1], detail);
|
||||
if (o.kind === 'maybeHttps' && /^http:/i.test(msg.url || '')) suggest(String(msg.url).replace(/^http:/i, 'https:'));
|
||||
} else {
|
||||
setStatus('bad', 'Could not connect.');
|
||||
}
|
||||
els.start.hidden = !(o.kind === 'refused' && msg.canStart);
|
||||
}
|
||||
|
||||
function onStartResult(msg) {
|
||||
setBusy(false);
|
||||
// Connect only to the server this page asked to start; after a reload
|
||||
// mid-start, only to the one the address field shows.
|
||||
var asked = state.startUrl || els.url.value;
|
||||
state.startUrl = '';
|
||||
if (!msg.ok) { setStatus('bad', 'Codeman did not start.', msg.output || ''); return; }
|
||||
setStatus('ok', 'Codeman started.', msg.output || '');
|
||||
if (!msg.url || !sameServer(msg.url, asked)) return;
|
||||
if (!sameServer(msg.url, els.url.value)) { els.url.value = msg.url; matchSaved(); }
|
||||
connect();
|
||||
}
|
||||
|
||||
function isLocalUrl(url) {
|
||||
var h = hostName(normalize(url));
|
||||
return h === 'localhost' || /^127\./.test(h) || h === '[::1]';
|
||||
}
|
||||
|
||||
function selectTab(tab) {
|
||||
if (tab !== 'local' && tab !== 'remote') return;
|
||||
var changed = state.tab !== tab;
|
||||
state.tab = tab;
|
||||
var local = tab === 'local';
|
||||
els.tabLocal.setAttribute('aria-selected', String(local));
|
||||
els.tabRemote.setAttribute('aria-selected', String(!local));
|
||||
els.tabLocal.tabIndex = local ? 0 : -1;
|
||||
els.tabRemote.tabIndex = local ? -1 : 0;
|
||||
els.paneLocal.hidden = !local;
|
||||
els.form.hidden = local;
|
||||
if (changed && !state.busy) {
|
||||
setStatus('', '');
|
||||
hideSuggestion();
|
||||
}
|
||||
if (local && !state.local && !state.localChecking) checkLocal('login');
|
||||
}
|
||||
|
||||
// quick: skip the login shell (used while an install runs, when only
|
||||
// "does it answer yet" matters).
|
||||
// How hard to look: 'quick' (files and processes, while an install runs),
|
||||
// 'login' (also the login shell; every automatic look) or 'deep' (also the
|
||||
// interactive profile, only on Check again).
|
||||
function checkLocal(how) {
|
||||
if (how !== 'quick') {
|
||||
state.localChecking = true;
|
||||
renderLocal();
|
||||
}
|
||||
var msg = { cmd: 'localStatus', quick: how === 'quick' };
|
||||
if (how === 'deep') msg.deep = true;
|
||||
post(msg);
|
||||
}
|
||||
|
||||
function syncLocalButtons() {
|
||||
els.localOpen.disabled = state.busy || tooOld;
|
||||
els.localStart.disabled = state.busy || tooOld;
|
||||
els.localInstall.disabled = state.busy || tooOld || state.opening;
|
||||
els.localCheck.disabled = state.busy || state.localChecking;
|
||||
els.sshInstall.disabled = state.busy || state.opening;
|
||||
}
|
||||
|
||||
function renderLocal() {
|
||||
var s = state.local;
|
||||
var show = { open: false, start: false, install: false, stop: false, check: false, network: false };
|
||||
var dot = '';
|
||||
var title = '';
|
||||
var detail = '';
|
||||
if (state.wait) {
|
||||
dot = 'busy';
|
||||
title = 'Installing Codeman in Terminal…';
|
||||
detail = 'Answer the installer’s questions there. This window opens Codeman when it is done.';
|
||||
show.stop = true;
|
||||
} else if (state.localChecking || !s) {
|
||||
dot = 'busy';
|
||||
title = 'Looking for Codeman on this Mac…';
|
||||
} else if (s.installRunning && s.state !== 'running' && s.state !== 'needsLogin') {
|
||||
dot = 'busy';
|
||||
title = 'Codeman is being installed in Terminal.';
|
||||
detail = 'Finish the installer there, then Check again.';
|
||||
show.check = true;
|
||||
} else if (s.state === 'runningElsewhere') {
|
||||
dot = 'warn';
|
||||
title = 'A Codeman server is already running on this Mac.';
|
||||
detail = 'It listens at ' + (s.elsewhere || []).join(', ') + ', which this app cannot open as ' + s.url +
|
||||
'. Connect to its address under Another machine. Starting another server here would take over its sessions.';
|
||||
show.check = true;
|
||||
} else if (s.state === 'running') {
|
||||
dot = 'ok';
|
||||
title = 'Codeman is running on this Mac.';
|
||||
detail = s.url + (s.version ? ' · version ' + s.version : '');
|
||||
show.open = true;
|
||||
} else if (s.state === 'needsLogin') {
|
||||
dot = 'ok';
|
||||
title = 'Codeman is running on this Mac.';
|
||||
detail = s.url + ' asks for a login: Open asks for the password.';
|
||||
show.open = true;
|
||||
} else if (s.state === 'stopped') {
|
||||
title = 'Codeman is installed on this Mac, but not running.';
|
||||
if (s.daemon) {
|
||||
detail = 'A system LaunchDaemon runs it, which an administrator starts: sudo launchctl kickstart -k system/com.codeman.web';
|
||||
} else if (/^https:/i.test(s.url)) {
|
||||
detail = 'It is set up with HTTPS (codeman web --https), whose self-signed certificate this app refuses. Run it without --https to open it here.';
|
||||
} else {
|
||||
detail = s.service
|
||||
? 'It is set up to start when you log in, but nothing answers at ' + s.url + '. Start asks launchd to run it now.'
|
||||
: 'Start runs it in the background at ' + s.url + '.';
|
||||
show.start = true;
|
||||
}
|
||||
show.check = true;
|
||||
} else if (s.state === 'notInstalled') {
|
||||
title = 'Codeman is not installed on this Mac.';
|
||||
detail = 'Install runs Codeman’s installer in Terminal: a few minutes, and it may ask for your Mac password. ' +
|
||||
'Codeman then runs in the background and starts when you log in, so your sessions keep running when this app is closed.';
|
||||
show.install = true;
|
||||
show.network = true;
|
||||
show.check = true;
|
||||
} else if (!s.installed) {
|
||||
// Something else holds Codeman's port; a fresh install takes the next free one.
|
||||
var other = s.outcome || {};
|
||||
title = 'Codeman is not installed on this Mac.';
|
||||
detail = 'Something else answers at ' + s.url + (other.kind === 'notCodeman' ? ' (HTTP ' + other.status + ')' : '') +
|
||||
', so Install sets Codeman up on the next free port. It runs Codeman’s installer in Terminal: a few minutes, and it may ask for your Mac password.';
|
||||
show.install = true;
|
||||
show.network = true;
|
||||
show.check = true;
|
||||
} else {
|
||||
var o = s.outcome || {};
|
||||
dot = 'warn';
|
||||
if (o.kind === 'notCodeman') {
|
||||
title = 'Something else answers at ' + s.url;
|
||||
detail = 'It is not Codeman (HTTP ' + o.status + '). Stop what runs on that port, or connect to Codeman’s real address under Another machine.';
|
||||
} else {
|
||||
var e = explain[o.kind];
|
||||
title = e ? e[1] : 'Could not reach Codeman on this Mac.';
|
||||
detail = (explainLoopback[o.kind]) || (e ? e[2] : (o.detail || ''));
|
||||
}
|
||||
show.check = true;
|
||||
}
|
||||
els.localDot.className = 'dot' + (dot ? ' ' + dot : '');
|
||||
els.localTitle.textContent = title;
|
||||
els.localDetail.textContent = detail;
|
||||
els.localOpen.hidden = !show.open;
|
||||
els.localStart.hidden = !show.start;
|
||||
els.localInstall.hidden = !show.install;
|
||||
els.localStop.hidden = !show.stop;
|
||||
els.localCheck.hidden = !show.check;
|
||||
els.localNetworkRow.hidden = !show.network;
|
||||
syncLocalButtons();
|
||||
}
|
||||
|
||||
function onLocalStatus(s) {
|
||||
state.localChecking = false;
|
||||
state.local = s || null;
|
||||
// An install from this app is still running (this page was shown again
|
||||
// while it ran): wait for it, unless the user stopped waiting.
|
||||
if (!state.wait && s && s.installRunning && !state.stoppedWaiting && s.state !== 'running' && s.state !== 'needsLogin') {
|
||||
state.wait = { since: Date.now(), finishedAt: 0, port: s.installPort || 3000 };
|
||||
renderLocal();
|
||||
scheduleWait();
|
||||
}
|
||||
if (state.wait) {
|
||||
onWaitStatus(state.local || {});
|
||||
return;
|
||||
}
|
||||
renderLocal();
|
||||
}
|
||||
|
||||
// Point the Another machine form at `url` with only the login saved for it:
|
||||
// never the username or a typed password of the server the form showed
|
||||
// before, which connect() would otherwise send along.
|
||||
function useAddress(url) {
|
||||
els.url.value = url || '';
|
||||
els.login.hidden = true;
|
||||
els.username.value = '';
|
||||
els.password.value = '';
|
||||
els.password.placeholder = '';
|
||||
matchSaved();
|
||||
}
|
||||
|
||||
function openLocal() {
|
||||
if (state.busy || tooOld || !state.local) return;
|
||||
useAddress(state.local.url);
|
||||
connect();
|
||||
}
|
||||
|
||||
function startLocal() {
|
||||
if (state.busy || tooOld || !state.local) return;
|
||||
useAddress(state.local.url);
|
||||
state.startUrl = state.local.url;
|
||||
post({ cmd: 'startServer', url: state.startUrl });
|
||||
}
|
||||
|
||||
function installLocal() {
|
||||
if (state.busy || tooOld || state.opening) return;
|
||||
state.opening = true;
|
||||
syncLocalButtons();
|
||||
setStatus('busy', 'Opening Terminal…');
|
||||
post({ cmd: 'installLocal', network: els.localNetwork.checked });
|
||||
}
|
||||
|
||||
function scheduleWait() {
|
||||
clearTimeout(state.waitTimer);
|
||||
state.waitTimer = setTimeout(function () { if (state.wait) checkLocal('quick'); }, WAIT_POLL_MS);
|
||||
}
|
||||
|
||||
function endWait() {
|
||||
clearTimeout(state.waitTimer);
|
||||
state.wait = null;
|
||||
}
|
||||
|
||||
// One answer while an install runs. It stops at the first answer from a
|
||||
// server: a password-protected one counts every unauthenticated look as a
|
||||
// failed login.
|
||||
function portOf(url) {
|
||||
try {
|
||||
var u = new URL(url);
|
||||
return Number(u.port || (u.protocol === 'https:' ? 443 : 80));
|
||||
} catch (e) { return 0; }
|
||||
}
|
||||
|
||||
function onWaitStatus(s) {
|
||||
var w = state.wait;
|
||||
var now = Date.now();
|
||||
if (s.installPort) w.port = s.installPort;
|
||||
// Until the installer writes its LaunchAgent, the app looks at port 3000,
|
||||
// where something else may answer when the install took another port.
|
||||
var ours = portOf(s.url) === w.port;
|
||||
if (ours && (s.state === 'running' || s.state === 'needsLogin')) {
|
||||
endWait();
|
||||
selectTab('local');
|
||||
renderLocal();
|
||||
openLocal();
|
||||
return;
|
||||
}
|
||||
if (ours && s.state === 'other') {
|
||||
// Something answers that is not a working Codeman: say what.
|
||||
endWait();
|
||||
renderLocal();
|
||||
return;
|
||||
}
|
||||
if (s.installComplete && (s.state === 'stopped' || !ours)) {
|
||||
if (!w.finishedAt) {
|
||||
w.finishedAt = now;
|
||||
} else if (now - w.finishedAt > WAIT_START_GRACE_MS) {
|
||||
endWait();
|
||||
renderLocal();
|
||||
setStatus('warn', 'The install finished, but Codeman is not answering.', 'Start runs it now. If the installer reported a problem, its log is ~/.codeman/install.log.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (now - w.since > WAIT_MAX_MS) {
|
||||
endWait();
|
||||
renderLocal();
|
||||
setStatus('warn', 'Stopped waiting for the install.', 'Check again once the installer in Terminal is done.');
|
||||
return;
|
||||
}
|
||||
scheduleWait();
|
||||
}
|
||||
|
||||
function installRemote() {
|
||||
if (state.busy || state.opening) return;
|
||||
var target = els.ssh.value.trim();
|
||||
if (!target) {
|
||||
setStatus('bad', 'Enter the machine to install Codeman on, as user@host.');
|
||||
els.ssh.focus();
|
||||
return;
|
||||
}
|
||||
state.opening = true;
|
||||
syncLocalButtons();
|
||||
setStatus('busy', 'Opening Terminal…');
|
||||
post({ cmd: 'installRemote', target: target });
|
||||
}
|
||||
|
||||
window.__codemanDesktop = {
|
||||
onNative: function (msg) {
|
||||
switch (msg.type) {
|
||||
case 'init':
|
||||
state.servers = msg.servers || [];
|
||||
state.startUrl = '';
|
||||
setBusy(false);
|
||||
hideSuggestion();
|
||||
setStatus('', '');
|
||||
els.start.hidden = true;
|
||||
els.auto.checked = !!msg.autoConnect;
|
||||
els.fullscreen.checked = !!msg.startFullscreen;
|
||||
els.version.textContent = 'Codeman Desktop ' + (msg.version || '');
|
||||
renderRecent();
|
||||
if (state.servers[0]) choose(state.servers[0]);
|
||||
// The tab of the server used last; This Mac on a first run.
|
||||
selectTab(state.servers[0] && !isLocalUrl(state.servers[0].url) ? 'remote' : 'local');
|
||||
if (msg.starting) {
|
||||
setBusy(true, false);
|
||||
setStatus('busy', 'Starting Codeman on this Mac…', msg.notice || '');
|
||||
} else if (msg.notice) {
|
||||
setStatus('warn', msg.notice);
|
||||
}
|
||||
if (msg.autoConnect && !manual && !tooOld && !msg.starting && !msg.notice && state.servers[0]) connect();
|
||||
else if (state.tab === 'remote') els.url.focus();
|
||||
break;
|
||||
case 'servers':
|
||||
state.servers = msg.servers || [];
|
||||
renderRecent();
|
||||
break;
|
||||
case 'prefs':
|
||||
if (typeof msg.startFullscreen === 'boolean') els.fullscreen.checked = msg.startFullscreen;
|
||||
if (typeof msg.autoConnect === 'boolean') els.auto.checked = msg.autoConnect;
|
||||
break;
|
||||
case 'probeResult':
|
||||
onProbeResult(msg);
|
||||
break;
|
||||
case 'opening':
|
||||
// Still busy: Cancel abandons the load and brings this page back.
|
||||
if (msg.passwordChange) {
|
||||
setStatus('ok', 'Opening Codeman…', 'Codeman will ask you for a new password for this account. Connect with the new password next time.');
|
||||
} else {
|
||||
setStatus('ok', msg.version ? 'Opening Codeman ' + msg.version + '…' : 'Opening Codeman…');
|
||||
}
|
||||
break;
|
||||
case 'error':
|
||||
setBusy(false);
|
||||
setStatus('bad', msg.message || 'Something went wrong.');
|
||||
if (msg.needsPassword) {
|
||||
selectTab('remote');
|
||||
showLogin();
|
||||
}
|
||||
break;
|
||||
case 'serverStarting':
|
||||
setBusy(true, false);
|
||||
setStatus('busy', 'Starting Codeman on this Mac…');
|
||||
break;
|
||||
case 'serverStartResult':
|
||||
onStartResult(msg);
|
||||
break;
|
||||
case 'localStatus':
|
||||
onLocalStatus(msg.status);
|
||||
break;
|
||||
case 'installStarted':
|
||||
state.opening = false;
|
||||
setStatus('', '');
|
||||
state.wait = { since: Date.now(), finishedAt: 0, port: Number(msg.port) || 3000 };
|
||||
selectTab('local');
|
||||
renderLocal();
|
||||
scheduleWait();
|
||||
break;
|
||||
case 'remoteInstallStarted':
|
||||
state.opening = false;
|
||||
syncLocalButtons();
|
||||
selectTab('remote');
|
||||
useAddress(msg.url);
|
||||
setStatus('ok', 'Terminal is installing Codeman on ' + msg.host + '.',
|
||||
'Answer the installer’s questions there. At the end it prints the address of Codeman on that machine: enter it above and connect (' + msg.url + ' is the usual one).');
|
||||
break;
|
||||
case 'installFailed':
|
||||
state.opening = false;
|
||||
syncLocalButtons();
|
||||
setStatus('bad', msg.message || 'Could not open Terminal.');
|
||||
break;
|
||||
case 'copied':
|
||||
setStatus('ok', 'Copied.', 'Paste it into a terminal on the other machine.');
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
els.form.addEventListener('submit', function (ev) { ev.preventDefault(); connect(); });
|
||||
els.cancel.addEventListener('click', function () { post({ cmd: 'cancel' }); setBusy(false); setStatus('', ''); });
|
||||
els.start.addEventListener('click', function () {
|
||||
if (state.busy) return;
|
||||
state.startUrl = state.lastUrl || els.url.value.trim();
|
||||
post({ cmd: 'startServer', url: state.startUrl });
|
||||
});
|
||||
els.suggest.addEventListener('click', function () {
|
||||
if (state.busy || !state.suggestion) return;
|
||||
els.url.value = state.suggestion;
|
||||
matchSaved();
|
||||
connect();
|
||||
});
|
||||
els.auto.addEventListener('change', function () { post({ cmd: 'setAutoConnect', value: els.auto.checked }); });
|
||||
els.fullscreen.addEventListener('change', function () { post({ cmd: 'setStartFullscreen', value: els.fullscreen.checked }); });
|
||||
els.url.addEventListener('input', function () {
|
||||
matchSaved();
|
||||
els.start.hidden = true;
|
||||
hideSuggestion();
|
||||
});
|
||||
els.tabLocal.addEventListener('click', function () { selectTab('local'); });
|
||||
els.tabRemote.addEventListener('click', function () { selectTab('remote'); });
|
||||
[els.tabLocal, els.tabRemote].forEach(function (tab) {
|
||||
tab.addEventListener('keydown', function (ev) {
|
||||
if (ev.key !== 'ArrowLeft' && ev.key !== 'ArrowRight') return;
|
||||
ev.preventDefault();
|
||||
var next = state.tab === 'local' ? 'remote' : 'local';
|
||||
selectTab(next);
|
||||
(next === 'local' ? els.tabLocal : els.tabRemote).focus();
|
||||
});
|
||||
});
|
||||
els.localOpen.addEventListener('click', openLocal);
|
||||
els.localStart.addEventListener('click', startLocal);
|
||||
els.localInstall.addEventListener('click', installLocal);
|
||||
els.localStop.addEventListener('click', function () { state.stoppedWaiting = true; endWait(); checkLocal('login'); });
|
||||
els.localCheck.addEventListener('click', function () { if (!state.busy && !state.localChecking) checkLocal('deep'); });
|
||||
els.sshInstall.addEventListener('click', installRemote);
|
||||
// Enter in the SSH field installs; it must not submit the form (Connect).
|
||||
els.ssh.addEventListener('keydown', function (ev) {
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); installRemote(); }
|
||||
});
|
||||
els.copy.addEventListener('click', function () { post({ cmd: 'copyInstallCommand' }); });
|
||||
$('docs').addEventListener('click', function (ev) { ev.preventDefault(); post({ cmd: 'openExternal', url: 'https://github.com/Ark0N/Codeman/wiki' }); });
|
||||
|
||||
if (tooOld) {
|
||||
els.webkit.hidden = false;
|
||||
setBusy(false);
|
||||
}
|
||||
post({ cmd: 'ready' });
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleName</key>
|
||||
<string>Codeman</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Codeman</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.getcodeman.desktop</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>__VERSION__</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>__VERSION__</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>codeman-desktop</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>Codeman</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<!-- 11.3 is where WKDownload arrived; wry saves files through it. Below
|
||||
that a Download link replaces the window or saves nothing.
|
||||
scripts/bundle-macos.sh builds for this version too. -->
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>11.3</string>
|
||||
<key>LSApplicationCategoryType</key>
|
||||
<string>public.app-category.developer-tools</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<true/>
|
||||
<key>NSSupportsAutomaticGraphicsSwitching</key>
|
||||
<true/>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>MIT License, Codeman Contributors</string>
|
||||
<!-- Voice dictation and gesture control ask for these; without the
|
||||
strings macOS kills the app the first time a page requests them. -->
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Codeman uses the microphone for voice dictation when you turn it on.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Codeman uses the camera for hand-gesture control when you turn it on.</string>
|
||||
<!-- macOS 15 asks before an app reaches the local network (a LAN address,
|
||||
a .local name), and shows this text in that question. A process the
|
||||
app starts counts as the app (Apple TN3179), so a server started with
|
||||
"Start Codeman on this Mac" runs under the same answer. -->
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>Codeman connects to Codeman servers on your local network. A Codeman server you start from this app uses the same permission for what it reaches on the network.</string>
|
||||
<!-- App Transport Security would block plain http:// to a host NAME
|
||||
(my-mac.local, a LAN box). IP literals are exempt, which is why
|
||||
http://127.0.0.1 works without this. -->
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
<key>NSAllowsArbitraryLoadsInWebContent</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- Only used with a Developer ID (SIGN_IDENTITY=...), which turns on the
|
||||
hardened runtime; there, microphone and camera need these. -->
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.camera</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1 @@
|
||||
max_width = 120
|
||||
Executable
+110
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build Codeman.app (and optionally a .dmg) from packages/desktop, on macOS.
|
||||
#
|
||||
# packages/desktop/scripts/bundle-macos.sh # this Mac's architecture
|
||||
# packages/desktop/scripts/bundle-macos.sh --universal --dmg
|
||||
# SIGN_IDENTITY="Developer ID Application: ..." packages/desktop/scripts/bundle-macos.sh --dmg
|
||||
#
|
||||
# Without SIGN_IDENTITY the app is signed ad hoc: it runs on the Mac that built
|
||||
# it, and a copy downloaded on another Mac is stopped by Gatekeeper. On macOS 15
|
||||
# and later, try to open it once, then click Open Anyway in System Settings >
|
||||
# Privacy & Security; on macOS 14 and earlier, right-click it and choose Open.
|
||||
# Or run `xattr -dr com.apple.quarantine /Applications/Codeman.app` on the copy
|
||||
# in /Applications. A Developer ID signature + notarization avoids all of this.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
[ "$(uname -s)" = Darwin ] || { echo "bundle-macos.sh runs on macOS only" >&2; exit 1; }
|
||||
|
||||
UNIVERSAL=0
|
||||
DMG=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--universal) UNIVERSAL=1 ;;
|
||||
--dmg) DMG=1 ;;
|
||||
*) echo "unknown option: $arg" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
VERSION=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1)
|
||||
[ -n "$VERSION" ] || { echo "could not read the version from Cargo.toml" >&2; exit 1; }
|
||||
|
||||
# The binary targets the same macOS as LSMinimumSystemVersion in Info.plist,
|
||||
# so the two cannot disagree.
|
||||
MACOSX_DEPLOYMENT_TARGET=$(/usr/libexec/PlistBuddy -c 'Print :LSMinimumSystemVersion' macos/Info.plist)
|
||||
[ -n "$MACOSX_DEPLOYMENT_TARGET" ] || { echo "could not read LSMinimumSystemVersion from macos/Info.plist" >&2; exit 1; }
|
||||
export MACOSX_DEPLOYMENT_TARGET
|
||||
|
||||
WORK=$(mktemp -d)
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
# Build with cargo and set BUILT to the executable cargo reports for
|
||||
# codeman-desktop. Asking cargo, rather than assuming ./target, keeps
|
||||
# CARGO_TARGET_DIR, build.target-dir and build.target from a cargo config
|
||||
# working, and a stale binary from an older build is never bundled.
|
||||
cargo_build() {
|
||||
local json
|
||||
json=$(cargo build --locked --release "$@" --message-format=json-render-diagnostics)
|
||||
BUILT=$(printf '%s\n' "$json" | awk '
|
||||
index($0, "\"reason\":\"compiler-artifact\"") &&
|
||||
index($0, "\"kind\":[\"bin\"]") &&
|
||||
index($0, "\"name\":\"codeman-desktop\"") &&
|
||||
match($0, /"executable":"[^"]*"/) { path = substr($0, RSTART + 14, RLENGTH - 15) }
|
||||
END { print path }')
|
||||
if [ -z "$BUILT" ] || [ ! -x "$BUILT" ]; then
|
||||
echo "cargo did not report a codeman-desktop executable${BUILT:+ (it named $BUILT)}" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
if [ "$UNIVERSAL" = 1 ]; then
|
||||
rustup target add aarch64-apple-darwin x86_64-apple-darwin >/dev/null
|
||||
cargo_build --target aarch64-apple-darwin
|
||||
ARM_BIN=$BUILT
|
||||
cargo_build --target x86_64-apple-darwin
|
||||
INTEL_BIN=$BUILT
|
||||
BIN="$WORK/codeman-desktop-universal"
|
||||
lipo -create -output "$BIN" "$ARM_BIN" "$INTEL_BIN"
|
||||
else
|
||||
cargo_build
|
||||
BIN=$BUILT
|
||||
fi
|
||||
|
||||
APP=dist/Codeman.app
|
||||
rm -rf "$APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
cp "$BIN" "$APP/Contents/MacOS/codeman-desktop"
|
||||
sed "s/__VERSION__/$VERSION/g" macos/Info.plist > "$APP/Contents/Info.plist"
|
||||
plutil -lint "$APP/Contents/Info.plist" >/dev/null
|
||||
printf 'APPL????' > "$APP/Contents/PkgInfo"
|
||||
|
||||
# assets/icon.png (1024x1024, already on Apple's icon grid) -> Codeman.icns
|
||||
ICONSET="$WORK/Codeman.iconset"
|
||||
mkdir -p "$ICONSET"
|
||||
for size in 16 32 128 256 512; do
|
||||
sips -z "$size" "$size" assets/icon.png --out "$ICONSET/icon_${size}x${size}.png" >/dev/null
|
||||
double=$((size * 2))
|
||||
sips -z "$double" "$double" assets/icon.png --out "$ICONSET/icon_${size}x${size}@2x.png" >/dev/null
|
||||
done
|
||||
iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/Codeman.icns"
|
||||
|
||||
if [ -n "${SIGN_IDENTITY:-}" ]; then
|
||||
codesign --force --options runtime --timestamp \
|
||||
--entitlements macos/entitlements.plist --sign "$SIGN_IDENTITY" "$APP"
|
||||
else
|
||||
codesign --force --sign - "$APP"
|
||||
fi
|
||||
codesign --verify --strict "$APP"
|
||||
|
||||
echo "Built $(pwd)/$APP ($(du -sh "$APP" | cut -f1), version $VERSION, macOS $MACOSX_DEPLOYMENT_TARGET or later)"
|
||||
|
||||
if [ "$DMG" = 1 ]; then
|
||||
STAGE="$WORK/dmg"
|
||||
mkdir -p "$STAGE"
|
||||
cp -R "$APP" "$STAGE/"
|
||||
ln -s /Applications "$STAGE/Applications"
|
||||
DMG_PATH="dist/Codeman-$VERSION.dmg"
|
||||
rm -f "$DMG_PATH"
|
||||
hdiutil create -quiet -volname "Codeman" -srcfolder "$STAGE" -ov -format UDZO "$DMG_PATH"
|
||||
echo "Built $(pwd)/$DMG_PATH ($(du -sh "$DMG_PATH" | cut -f1))"
|
||||
fi
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Files bundled into the binary: the connect page, its icon, and the script
|
||||
//! injected into every Codeman page (`window.CodemanHost`).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use wry::http::{header::CONTENT_TYPE, Request, Response, StatusCode};
|
||||
|
||||
const CONNECT_HTML: &[u8] = include_bytes!("../assets/connect.html");
|
||||
const ICON_PNG: &[u8] = include_bytes!("../assets/icon.png");
|
||||
|
||||
/// The connect page loads nothing from outside the app.
|
||||
const CSP: &str = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src codemanapp:";
|
||||
|
||||
/// Serve `codemanapp://localhost/<path>`.
|
||||
pub fn respond(request: Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> {
|
||||
let (body, mime): (&'static [u8], &str) = match request.uri().path() {
|
||||
"/" | "/index.html" => (CONNECT_HTML, "text/html; charset=utf-8"),
|
||||
"/icon.png" => (ICON_PNG, "image/png"),
|
||||
_ => {
|
||||
return Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(Cow::Borrowed(&b"not found"[..]))
|
||||
.expect("static response");
|
||||
}
|
||||
};
|
||||
Response::builder()
|
||||
.header(CONTENT_TYPE, mime)
|
||||
.header("Content-Security-Policy", CSP)
|
||||
.header("Cache-Control", "no-store")
|
||||
.body(Cow::Borrowed(body))
|
||||
.expect("static response")
|
||||
}
|
||||
|
||||
/// Injected at document start into the MAIN frame of every page (wry's
|
||||
/// default), where it does nothing unless the page is http(s). It provides the
|
||||
/// native-wrapper bridge Codeman's frontend already looks for
|
||||
/// (`window.CodemanHost.openWindow/closeWindow/focusWindow`, see
|
||||
/// `openInHostWindow` in src/web/public/app.js), so pop-outs become real app
|
||||
/// windows. `openWindow` answers false, posting nothing, for a URL the native
|
||||
/// side would drop (not http(s), or longer than its 4096-byte cap), so
|
||||
/// Codeman shows its own error instead of marking a session detached with no
|
||||
/// window behind it. Besides that it:
|
||||
///
|
||||
/// - turns a click on a same-origin download link (`download=true`, or a path
|
||||
/// ending in `/download`) into a real download by giving the link a
|
||||
/// `download` attribute. Codeman's file tree and attachment cards link to
|
||||
/// `file-raw?download=true` without one, and the server sends a type WebKit
|
||||
/// can show (png, pdf, txt), so WebKit would otherwise replace the Codeman
|
||||
/// window with the file, with no way back. This runs in the capture phase,
|
||||
/// before the file tree's own `stopPropagation`.
|
||||
/// - does the same for `window.open` of such a `download=true` URL (the
|
||||
/// attachment history), returning null instead of a window.
|
||||
/// - sends clicks on links to other sites to the default browser, after
|
||||
/// Codeman's own handlers have had their turn (bubble phase, skipped when
|
||||
/// one of them called preventDefault). Middle clicks and modifier clicks
|
||||
/// count too: a bare WKWebView has no new-tab gesture of its own, so they
|
||||
/// would do nothing.
|
||||
/// - reports the first same-origin 401 a `fetch` gets (`sessionExpired`),
|
||||
/// once per page load: the session cookie is gone, usually because the
|
||||
/// server restarted, and nothing in the page asks for the login again.
|
||||
/// - defines `__codemanDesktopRefused(id)` (not enumerable) for
|
||||
/// [`refused_script`].
|
||||
pub const HOST_SHIM: &str = r#"(function () {
|
||||
'use strict';
|
||||
if (!/^https?:$/.test(location.protocol) || window.CodemanHost) return;
|
||||
var MAX_URL = 4096;
|
||||
var post = function (msg) {
|
||||
try { window.ipc.postMessage(JSON.stringify(msg)); return true; } catch (e) { return false; }
|
||||
};
|
||||
// An http(s) URL object, or null. fetch and window.open resolve against
|
||||
// the document base (Codeman sets <base href>), so those pass it.
|
||||
var httpUrl = function (raw, base) {
|
||||
try {
|
||||
var u = new URL(String(raw), base || location.href);
|
||||
return /^https?:$/.test(u.protocol) ? u : null;
|
||||
} catch (e) { return null; }
|
||||
};
|
||||
var sameOrigin = function (u) { return !!u && u.origin === location.origin; };
|
||||
var link = function (ev) {
|
||||
var a = ev.target && ev.target.closest ? ev.target.closest('a[href]') : null;
|
||||
return a && typeof a.href === 'string' && !a.hasAttribute('download') ? a : null;
|
||||
};
|
||||
|
||||
Object.defineProperty(window, 'CodemanHost', {
|
||||
value: Object.freeze({
|
||||
desktop: true,
|
||||
openWindow: function (url) {
|
||||
var u = httpUrl(url);
|
||||
return u && u.href.length <= MAX_URL ? post({ cmd: 'openWindow', url: u.href }) : false;
|
||||
},
|
||||
closeWindow: function () { post({ cmd: 'closeWindow' }); },
|
||||
focusWindow: function () { post({ cmd: 'focusWindow' }); }
|
||||
})
|
||||
});
|
||||
|
||||
// The native side could not open a window: say so. `id` is a string only
|
||||
// when CodemanHost.openWindow asked for that session's pop-out; that session
|
||||
// goes back to the dashboard (a fresh channel object, so this window's own
|
||||
// channel hears it too). Anything else, null included, only shows the toast.
|
||||
Object.defineProperty(window, '__codemanDesktopRefused', {
|
||||
value: function (id) {
|
||||
try {
|
||||
if (window.app && typeof window.app.showToast === 'function') {
|
||||
window.app.showToast('Could not open a new window', 'error');
|
||||
}
|
||||
} catch (e) {}
|
||||
try {
|
||||
if (typeof id === 'string' && id !== '' && typeof BroadcastChannel === 'function') {
|
||||
var ch = new BroadcastChannel('codeman-windows');
|
||||
ch.postMessage({ type: 'redocked', id: id });
|
||||
setTimeout(function () { try { ch.close(); } catch (e) {} }, 2000);
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
});
|
||||
|
||||
var markDownload = function (ev) {
|
||||
if (ev.button > 1) return;
|
||||
var a = link(ev);
|
||||
var u = a && httpUrl(a.href);
|
||||
if (sameOrigin(u) && (u.searchParams.get('download') === 'true' || /\/download$/.test(u.pathname))) {
|
||||
a.setAttribute('download', '');
|
||||
}
|
||||
};
|
||||
window.addEventListener('click', markDownload, true);
|
||||
window.addEventListener('auxclick', markDownload, true);
|
||||
|
||||
var lastMiddle = null;
|
||||
var openOutside = function (ev) {
|
||||
if (ev.defaultPrevented || ev.button > 1) return;
|
||||
var a = link(ev);
|
||||
var u = a && httpUrl(a.href);
|
||||
if (!u || sameOrigin(u)) return;
|
||||
ev.preventDefault();
|
||||
// Older WebKit sends a middle click as 'click', newer as 'auxclick'; one
|
||||
// that sent both must still open the link once.
|
||||
if (ev.button === 1) {
|
||||
if (lastMiddle && lastMiddle.a === a && ev.timeStamp - lastMiddle.t < 500) return;
|
||||
lastMiddle = { a: a, t: ev.timeStamp };
|
||||
}
|
||||
post({ cmd: 'openExternal', url: u.href });
|
||||
};
|
||||
window.addEventListener('click', openOutside, false);
|
||||
window.addEventListener('auxclick', openOutside, false);
|
||||
|
||||
var nativeOpen = window.open;
|
||||
if (typeof nativeOpen === 'function') {
|
||||
window.open = function open(url) {
|
||||
try {
|
||||
var u = arguments.length && url !== undefined ? httpUrl(url, document.baseURI) : null;
|
||||
if (sameOrigin(u) && u.searchParams.get('download') === 'true') {
|
||||
var a = document.createElement('a');
|
||||
a.href = u.href;
|
||||
a.setAttribute('download', '');
|
||||
a.click();
|
||||
return null;
|
||||
}
|
||||
} catch (e) {}
|
||||
return nativeOpen.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
|
||||
// Returns the promise fetch itself returned, so callers see exactly what
|
||||
// they saw before; the 401 check hangs off a side branch that swallows its
|
||||
// own errors and never reads the body.
|
||||
var expired = false;
|
||||
var nativeFetch = window.fetch;
|
||||
if (typeof nativeFetch === 'function') {
|
||||
var check = function (input, r) {
|
||||
if (expired || !r || r.status !== 401) return;
|
||||
var raw = r.url || (input && typeof input === 'object' && typeof input.url === 'string' ? input.url : input);
|
||||
if (!sameOrigin(httpUrl(raw, document.baseURI))) return;
|
||||
expired = true;
|
||||
post({ cmd: 'sessionExpired' });
|
||||
};
|
||||
window.fetch = function fetch(input) {
|
||||
var p = nativeFetch.apply(this, arguments);
|
||||
try {
|
||||
if (!expired && p && typeof p.then === 'function') {
|
||||
p.then(function (r) { try { check(input, r); } catch (e) {} }, function () {});
|
||||
}
|
||||
} catch (e) {}
|
||||
return p;
|
||||
};
|
||||
}
|
||||
})();"#;
|
||||
|
||||
/// A toast inside Codeman when a download finished (Codeman's own
|
||||
/// `showToast`; nothing happens on a page without it).
|
||||
pub fn download_toast_script(file_name: &str, ok: bool) -> String {
|
||||
let text = if ok {
|
||||
format!("Downloaded {file_name} to Downloads")
|
||||
} else {
|
||||
format!("Download of {file_name} failed")
|
||||
};
|
||||
let text = serde_json::to_string(&text).unwrap_or_else(|_| "\"Download finished\"".into());
|
||||
let kind = if ok { "\"success\"" } else { "\"error\"" };
|
||||
format!("try {{ window.app && window.app.showToast && window.app.showToast({text}, {kind}); }} catch (e) {{}}")
|
||||
}
|
||||
|
||||
/// Runs in the window that asked for a window the native side did not open
|
||||
/// (pop-out limit reached, policy refused it, window or web view failed to
|
||||
/// build): the page shows an error toast. Does nothing on a page without the
|
||||
/// shim.
|
||||
///
|
||||
/// `session_id` is the decoded id of a session pop-out
|
||||
/// (`policy::session_id_of`), and only for a `CodemanHost.openWindow` request,
|
||||
/// which comes from a trusted frame: that session then gets its tab back in
|
||||
/// the dashboard. Pass `None` for every other refusal, above all the ones a
|
||||
/// `window.open` or `target=_blank` from any frame caused, so a page cannot
|
||||
/// make the dashboard drop the detached state of a session that is still
|
||||
/// popped out.
|
||||
pub fn refused_script(session_id: Option<&str>) -> String {
|
||||
let id = serde_json::to_string(&session_id).unwrap_or_else(|_| "null".into());
|
||||
format!(
|
||||
"try {{ if (typeof window.__codemanDesktopRefused === 'function') window.__codemanDesktopRefused({id}); }} catch (e) {{}}"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn get(path: &str) -> Response<Cow<'static, [u8]>> {
|
||||
respond(
|
||||
Request::builder()
|
||||
.uri(format!("codemanapp://localhost{path}"))
|
||||
.body(Vec::new())
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serves_page_and_icon_only() {
|
||||
let page = get("/index.html");
|
||||
assert_eq!(page.status(), StatusCode::OK);
|
||||
assert!(page.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("text/html"));
|
||||
assert!(page.headers().contains_key("content-security-policy"));
|
||||
assert!(String::from_utf8_lossy(page.body()).contains("window.__codemanDesktop"));
|
||||
assert_eq!(get("/icon.png").status(), StatusCode::OK);
|
||||
assert_eq!(get("/../etc/passwd").status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(get("/other.js").status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_script_escapes_the_session_id() {
|
||||
let js = refused_script(Some("a'\"); alert(1); //\u{2028}\\"));
|
||||
assert!(js.starts_with("try { if (typeof window.__codemanDesktopRefused === 'function') "));
|
||||
assert!(js.contains(r#"window.__codemanDesktopRefused("a'\"); alert(1); //"#));
|
||||
assert!(js.contains("\u{2028}\\\\\"); } catch (e) {}"));
|
||||
assert!(js.ends_with(" } catch (e) {}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_script_without_a_session_passes_null() {
|
||||
assert_eq!(
|
||||
refused_script(None),
|
||||
"try { if (typeof window.__codemanDesktopRefused === 'function') window.__codemanDesktopRefused(null); } catch (e) {}"
|
||||
);
|
||||
assert!(refused_script(Some("")).contains("__codemanDesktopRefused(\"\")"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shim_keeps_its_contract() {
|
||||
for needle in [
|
||||
"Object.freeze",
|
||||
"openWindow",
|
||||
"closeWindow",
|
||||
"focusWindow",
|
||||
"__codemanDesktopRefused",
|
||||
"sessionExpired",
|
||||
"'auxclick'",
|
||||
"MAX_URL = 4096",
|
||||
"typeof id === 'string' && id !== ''",
|
||||
] {
|
||||
assert!(HOST_SHIM.contains(needle), "{needle}");
|
||||
}
|
||||
// The refused hook takes the session id the native side resolved; it
|
||||
// never parses or decodes a URL to find one.
|
||||
assert!(!HOST_SHIM.contains("decodeURIComponent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toast_escapes_file_names() {
|
||||
let js = download_toast_script("a\"); alert(1); (\".txt", true);
|
||||
assert!(js.contains(r#"Downloaded a\"); alert(1); (\".txt to Downloads"#));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
//! The app's own settings: recent servers, two preferences and the window
|
||||
//! frame. Stored as JSON next to other per-app data
|
||||
//! (`~/Library/Application Support/Codeman/desktop.json` on macOS). Passwords
|
||||
//! never go here; they live in the Keychain (see `credentials`).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MAX_SERVERS: usize = 8;
|
||||
/// How many recovery copies of an unreadable config can sit side by side:
|
||||
/// `desktop.json.corrupt`, then `desktop.json.corrupt.1` to `.9`.
|
||||
const ASIDE_SLOTS: usize = 10;
|
||||
const MIN_WIDTH: f64 = 480.0;
|
||||
const MIN_HEIGHT: f64 = 360.0;
|
||||
const MAX_EDGE: f64 = 20_000.0;
|
||||
|
||||
/// Height of a standard title bar, in points.
|
||||
const TITLE_BAR: f64 = 28.0;
|
||||
/// How far the outer top of the window lies above `WindowFrame::y`. On macOS
|
||||
/// `y` is the content area's top (tao's `with_position` puts the content rect
|
||||
/// there and the title bar above it); elsewhere `y` is already the outer top.
|
||||
const TITLE_ABOVE_Y: f64 = if cfg!(target_os = "macos") { TITLE_BAR } else { 0.0 };
|
||||
/// How much of the title bar must be on a screen to grab it.
|
||||
const MIN_GRIP: f64 = 80.0;
|
||||
/// Room `fitted_to` leaves when it shrinks a window. Screens are full display
|
||||
/// bounds, so the menu bar and the Dock are inside them; these are the margins
|
||||
/// main.rs uses for the centred default frame.
|
||||
const FIT_MARGIN_X: f64 = 40.0;
|
||||
const FIT_MARGIN_Y: f64 = 80.0;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Config {
|
||||
/// Most recent first.
|
||||
pub servers: Vec<ServerEntry>,
|
||||
/// Connect to the most recent server at launch.
|
||||
pub auto_connect: bool,
|
||||
/// Always open in full screen (otherwise the last state is restored).
|
||||
pub start_fullscreen: bool,
|
||||
pub window: Option<WindowFrame>,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
servers: Vec::new(),
|
||||
auto_connect: true,
|
||||
start_fullscreen: false,
|
||||
window: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ServerEntry {
|
||||
pub url: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub username: Option<String>,
|
||||
#[serde(default)]
|
||||
pub has_saved_password: bool,
|
||||
}
|
||||
|
||||
/// The main window's position and inner size, in logical (point)
|
||||
/// coordinates. `x`/`y` are where tao's `with_position` wants them: on macOS
|
||||
/// the top-left of the CONTENT area (the title bar, about 28 pt, sits above
|
||||
/// it), elsewhere the window's outer top-left. Saving the outer corner on
|
||||
/// macOS and restoring it as the content corner made the window creep up by
|
||||
/// a title bar on every launch.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WindowFrame {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
#[serde(default)]
|
||||
pub fullscreen: bool,
|
||||
}
|
||||
|
||||
/// A display's full bounds in logical coordinates, as tao reports them. This
|
||||
/// is the whole display, not the work area: the menu bar and the Dock are
|
||||
/// inside it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Rect {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
}
|
||||
|
||||
impl WindowFrame {
|
||||
/// The frame clamped to sane sizes, or None when it holds junk.
|
||||
pub fn sanitized(self) -> Option<WindowFrame> {
|
||||
let vals = [self.x, self.y, self.width, self.height];
|
||||
if vals.iter().any(|v| !v.is_finite()) || self.x.abs() > MAX_EDGE || self.y.abs() > MAX_EDGE {
|
||||
return None;
|
||||
}
|
||||
Some(WindowFrame {
|
||||
width: self.width.clamp(MIN_WIDTH, MAX_EDGE),
|
||||
height: self.height.clamp(MIN_HEIGHT, MAX_EDGE),
|
||||
..self
|
||||
})
|
||||
}
|
||||
|
||||
/// The frame made to fit the screens it will open on, or None when its
|
||||
/// title bar is on none of them (the caller then falls back to a default
|
||||
/// frame). An edge that no screen covers is pulled onto the screen that
|
||||
/// holds the title bar, shrinking the window when it is too big for it:
|
||||
/// a frame saved on an external display that is gone would otherwise
|
||||
/// open with its right edge and resize corner far off screen. An edge
|
||||
/// that lands on some screen stays put, so a window spanning two
|
||||
/// displays keeps its span. `min` is the window's minimum inner size.
|
||||
pub fn fitted_to(&self, screens: &[Rect], min: (f64, f64)) -> Option<WindowFrame> {
|
||||
let home = *self.title_screen(screens)?;
|
||||
let top = self.outer_top();
|
||||
let outer_height = TITLE_BAR + self.height;
|
||||
let (x, width) = fit_axis(
|
||||
self.x,
|
||||
self.width,
|
||||
(
|
||||
covers_x(screens, self.x, top, top + outer_height),
|
||||
covers_x(screens, self.x + self.width, top, top + outer_height),
|
||||
),
|
||||
(home.x, home.x + home.width),
|
||||
FIT_MARGIN_X,
|
||||
min.0,
|
||||
);
|
||||
let (top, outer_height) = fit_axis(
|
||||
top,
|
||||
outer_height,
|
||||
(
|
||||
covers_y(screens, top, x, x + width),
|
||||
covers_y(screens, top + outer_height, x, x + width),
|
||||
),
|
||||
(home.y, home.y + home.height),
|
||||
FIT_MARGIN_Y - TITLE_BAR,
|
||||
min.1 + TITLE_BAR,
|
||||
);
|
||||
Some(WindowFrame {
|
||||
x,
|
||||
y: top + TITLE_ABOVE_Y,
|
||||
width,
|
||||
height: outer_height - TITLE_BAR,
|
||||
..*self
|
||||
})
|
||||
}
|
||||
|
||||
fn outer_top(&self) -> f64 {
|
||||
self.y - TITLE_ABOVE_Y
|
||||
}
|
||||
|
||||
/// The screen the title bar is on, or None when no screen has enough of
|
||||
/// it to grab (a display unplugged since the last run leaves the frame off
|
||||
/// screen). The middle of the title bar must be inside the screen and at
|
||||
/// least `MIN_GRIP` of the bar's width must overlap it; when several
|
||||
/// qualify, the one holding most of the bar wins.
|
||||
fn title_screen<'a>(&self, screens: &'a [Rect]) -> Option<&'a Rect> {
|
||||
let title_y = self.outer_top() + TITLE_BAR / 2.0;
|
||||
screens
|
||||
.iter()
|
||||
.filter(|m| title_y >= m.y && title_y <= m.y + m.height)
|
||||
.map(|m| {
|
||||
let grip = (self.x + self.width).min(m.x + m.width) - self.x.max(m.x);
|
||||
(m, grip)
|
||||
})
|
||||
.filter(|(_, grip)| *grip >= MIN_GRIP)
|
||||
.max_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(m, _)| m)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether some screen holds part of the vertical edge at `x` that runs from
|
||||
/// `top` to `bottom`.
|
||||
fn covers_x(screens: &[Rect], x: f64, top: f64, bottom: f64) -> bool {
|
||||
screens
|
||||
.iter()
|
||||
.any(|m| x >= m.x && x <= m.x + m.width && top < m.y + m.height && bottom > m.y)
|
||||
}
|
||||
|
||||
/// Whether some screen holds part of the horizontal edge at `y` that runs
|
||||
/// from `left` to `right`.
|
||||
fn covers_y(screens: &[Rect], y: f64, left: f64, right: f64) -> bool {
|
||||
screens
|
||||
.iter()
|
||||
.any(|m| y >= m.y && y <= m.y + m.height && left < m.x + m.width && right > m.x)
|
||||
}
|
||||
|
||||
/// One axis of `WindowFrame::fitted_to`. The window runs from `start` for
|
||||
/// `len`; `covered` says whether some screen holds each end; `home` is the
|
||||
/// title bar screen's range on this axis. An uncovered end is pulled onto
|
||||
/// `home`, and the window shrinks (leaving `margin`, never below `min`) when
|
||||
/// it does not fit; a covered end may stay where it is, on another display.
|
||||
fn fit_axis(start: f64, len: f64, covered: (bool, bool), home: (f64, f64), margin: f64, min: f64) -> (f64, f64) {
|
||||
if covered.0 && covered.1 {
|
||||
return (start, len);
|
||||
}
|
||||
let lo = if covered.0 { start.min(home.0) } else { home.0 };
|
||||
let hi = if covered.1 { (start + len).max(home.1) } else { home.1 };
|
||||
let len = len.min(hi - lo - margin).max(min);
|
||||
// `max` last: a window still too big for the screen keeps its start (the
|
||||
// left edge, or the title bar) on screen rather than its end.
|
||||
let start = start.min(hi - len).max(lo);
|
||||
(start, len)
|
||||
}
|
||||
|
||||
/// The first name an unreadable `desktop.json` can be moved to without
|
||||
/// replacing an earlier recovery copy: `desktop.json.corrupt`, then
|
||||
/// `desktop.json.corrupt.1` to `.9`, next to it.
|
||||
/// A name is free only when nothing at all is there: a file, a directory or
|
||||
/// a dangling symlink left at it is taken, and so is a name that cannot be
|
||||
/// checked. None when every name is taken.
|
||||
fn free_aside_name(path: &Path) -> Option<PathBuf> {
|
||||
(0..ASIDE_SLOTS)
|
||||
.map(|n| match n {
|
||||
0 => path.with_extension("json.corrupt"),
|
||||
n => path.with_extension(format!("json.corrupt.{n}")),
|
||||
})
|
||||
.find(|aside| matches!(fs::symlink_metadata(aside), Err(e) if e.kind() == io::ErrorKind::NotFound))
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Where the config lives, or None if the OS has no config directory.
|
||||
pub fn default_path() -> Option<PathBuf> {
|
||||
dirs::config_dir().map(|d| d.join("Codeman").join("desktop.json"))
|
||||
}
|
||||
|
||||
/// Read the config, and say whether saving back to `path` is safe this
|
||||
/// run. A missing file is the default. A file that is there but cannot
|
||||
/// be read (not UTF-8, no permission, a directory, an I/O error) or does
|
||||
/// not parse is moved aside for recovery, and the defaults are used; it
|
||||
/// is never silently overwritten with them. It goes to the first free
|
||||
/// name of `desktop.json.corrupt`, `desktop.json.corrupt.1` to `.9`, so
|
||||
/// a second unreadable file never replaces the copy kept from the first.
|
||||
/// If every name is taken or the move fails, the answer is false: the
|
||||
/// original is still at `path`, and the save at exit must not replace it.
|
||||
pub fn load_from(path: &Path) -> (Config, bool) {
|
||||
let text = match fs::read_to_string(path) {
|
||||
Ok(text) => Some(text),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return (Config::default(), true),
|
||||
Err(_) => None,
|
||||
};
|
||||
if let Some(mut config) = text.and_then(|t| serde_json::from_str::<Config>(&t).ok()) {
|
||||
config.sanitize();
|
||||
return (config, true);
|
||||
}
|
||||
let Some(aside) = free_aside_name(path) else {
|
||||
eprintln!(
|
||||
"codeman-desktop: {} could not be read, and {} to .{} are all taken; settings will not be saved this run",
|
||||
path.display(),
|
||||
path.with_extension("json.corrupt").display(),
|
||||
ASIDE_SLOTS - 1
|
||||
);
|
||||
return (Config::default(), false);
|
||||
};
|
||||
match fs::rename(path, &aside) {
|
||||
Ok(()) => {
|
||||
eprintln!(
|
||||
"codeman-desktop: {} could not be read; moved it to {} and started with defaults",
|
||||
path.display(),
|
||||
aside.display()
|
||||
);
|
||||
(Config::default(), true)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"codeman-desktop: {} could not be read or moved aside ({e}); settings will not be saved this run",
|
||||
path.display()
|
||||
);
|
||||
(Config::default(), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write via a temp file and rename, so a crash never leaves half a file.
|
||||
pub fn save_to(&self, path: &Path) -> io::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
let text = serde_json::to_string_pretty(self).map_err(io::Error::other)?;
|
||||
fs::write(&tmp, text)?;
|
||||
fs::rename(&tmp, path)
|
||||
}
|
||||
|
||||
fn sanitize(&mut self) {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.servers.retain(|s| !s.url.is_empty() && seen.insert(s.url.clone()));
|
||||
self.servers.truncate(MAX_SERVERS);
|
||||
self.window = self.window.and_then(WindowFrame::sanitized);
|
||||
}
|
||||
|
||||
/// Move (or add) a server to the top of the recent list. Returns the
|
||||
/// Keychain accounts, as (url, username), of the entries with a username
|
||||
/// that fall off the end of the list (it keeps `MAX_SERVERS`), for the
|
||||
/// caller to delete. A different username on `url` itself is not
|
||||
/// reported: the caller deletes that account before it saves the new
|
||||
/// one, comparing the names exactly as the Keychain account string
|
||||
/// does. A delete made after the save could take the new password with
|
||||
/// it on a Keychain that treats two spellings of a name as one item.
|
||||
#[must_use = "the returned Keychain accounts must be deleted"]
|
||||
pub fn remember(&mut self, url: &str, username: Option<&str>, saved: bool) -> Vec<(String, String)> {
|
||||
self.servers.retain(|s| s.url != url);
|
||||
self.servers.insert(
|
||||
0,
|
||||
ServerEntry {
|
||||
url: url.to_string(),
|
||||
username: username.map(str::to_string),
|
||||
has_saved_password: saved,
|
||||
},
|
||||
);
|
||||
let evicted = self.servers.split_off(self.servers.len().min(MAX_SERVERS));
|
||||
evicted.into_iter().filter_map(|s| Some((s.url, s.username?))).collect()
|
||||
}
|
||||
|
||||
pub fn forget(&mut self, url: &str) -> Option<ServerEntry> {
|
||||
let idx = self.servers.iter().position(|s| s.url == url)?;
|
||||
Some(self.servers.remove(idx))
|
||||
}
|
||||
|
||||
pub fn find(&self, url: &str) -> Option<&ServerEntry> {
|
||||
self.servers.iter().find(|s| s.url == url)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tmp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("codeman-desktop-test-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
fn frame(x: f64, y: f64, width: f64, height: f64) -> WindowFrame {
|
||||
WindowFrame {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
fullscreen: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn rect(x: f64, y: f64, width: f64, height: f64) -> Rect {
|
||||
Rect { x, y, width, height }
|
||||
}
|
||||
|
||||
const MIN: (f64, f64) = (MIN_WIDTH, MIN_HEIGHT);
|
||||
|
||||
fn reachable(f: &WindowFrame, screens: &[Rect]) -> bool {
|
||||
f.title_screen(screens).is_some()
|
||||
}
|
||||
|
||||
/// The outer frame (title bar included) as left, top, right, bottom.
|
||||
fn outer(f: &WindowFrame) -> (f64, f64, f64, f64) {
|
||||
let top = f.y - TITLE_ABOVE_Y;
|
||||
(f.x, top, f.x + f.width, top + TITLE_BAR + f.height)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_file_is_default() {
|
||||
let dir = tmp_dir("missing");
|
||||
let (c, can_save) = Config::load_from(&dir.join("desktop.json"));
|
||||
assert_eq!(c, Config::default());
|
||||
assert!(c.auto_connect);
|
||||
assert!(can_save);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_and_atomic_save() {
|
||||
let dir = tmp_dir("roundtrip");
|
||||
let path = dir.join("nested").join("desktop.json");
|
||||
let mut c = Config::default();
|
||||
assert!(c.remember("http://127.0.0.1:3000/", None, false).is_empty());
|
||||
assert!(c.remember("https://box.ts.net/", Some("admin"), true).is_empty());
|
||||
c.start_fullscreen = true;
|
||||
c.window = Some(WindowFrame {
|
||||
x: 10.0,
|
||||
y: 20.0,
|
||||
width: 1200.0,
|
||||
height: 800.0,
|
||||
fullscreen: true,
|
||||
});
|
||||
c.save_to(&path).unwrap();
|
||||
assert!(!path.with_extension("json.tmp").exists());
|
||||
let (back, can_save) = Config::load_from(&path);
|
||||
assert!(can_save);
|
||||
assert_eq!(back, c);
|
||||
assert_eq!(back.servers[0].url, "https://box.ts.net/");
|
||||
let text = fs::read_to_string(&path).unwrap();
|
||||
assert!(
|
||||
!text.to_lowercase().contains("password\":\""),
|
||||
"no password values on disk"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_file_is_moved_aside() {
|
||||
let dir = tmp_dir("corrupt");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("desktop.json");
|
||||
fs::write(&path, "{ not json").unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert_eq!(c, Config::default());
|
||||
assert!(can_save);
|
||||
assert!(!path.exists());
|
||||
assert!(dir.join("desktop.json.corrupt").exists());
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_utf8_file_is_moved_aside() {
|
||||
let dir = tmp_dir("non-utf8");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("desktop.json");
|
||||
// Valid JSON apart from a Latin-1 "ü", which is not UTF-8.
|
||||
let bytes = b"{\"servers\":[{\"url\":\"http://a/\",\"username\":\"J\xfcrg\"}]}";
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert_eq!(c, Config::default());
|
||||
assert!(can_save);
|
||||
assert!(!path.exists());
|
||||
assert_eq!(fs::read(dir.join("desktop.json.corrupt")).unwrap(), bytes);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_path_is_moved_aside() {
|
||||
let dir = tmp_dir("unreadable");
|
||||
let path = dir.join("desktop.json");
|
||||
// A directory where the file should be: it exists but cannot be read.
|
||||
fs::create_dir_all(path.join("inside")).unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert_eq!(c, Config::default());
|
||||
assert!(can_save);
|
||||
assert!(!path.exists());
|
||||
assert!(dir.join("desktop.json.corrupt").join("inside").is_dir());
|
||||
c.save_to(&path).unwrap();
|
||||
assert_eq!(Config::load_from(&path), (Config::default(), true));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_corruption_keeps_the_first_copy() {
|
||||
let dir = tmp_dir("corrupt-twice");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("desktop.json");
|
||||
fs::write(&path, "{ first").unwrap();
|
||||
assert_eq!(Config::load_from(&path), (Config::default(), true));
|
||||
fs::write(&path, "{ second").unwrap();
|
||||
assert_eq!(Config::load_from(&path), (Config::default(), true));
|
||||
assert!(!path.exists());
|
||||
assert_eq!(fs::read_to_string(dir.join("desktop.json.corrupt")).unwrap(), "{ first");
|
||||
assert_eq!(
|
||||
fs::read_to_string(dir.join("desktop.json.corrupt.1")).unwrap(),
|
||||
"{ second"
|
||||
);
|
||||
// A good file written afterwards loads normally and moves nothing.
|
||||
Config::default().save_to(&path).unwrap();
|
||||
assert_eq!(Config::load_from(&path), (Config::default(), true));
|
||||
assert!(!dir.join("desktop.json.corrupt.2").exists());
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn taken_aside_names_are_skipped() {
|
||||
let dir = tmp_dir("aside-taken");
|
||||
// A directory left at the first name and a file at the second: the
|
||||
// third is the first free one.
|
||||
fs::create_dir_all(dir.join("desktop.json.corrupt")).unwrap();
|
||||
fs::write(dir.join("desktop.json.corrupt.1"), "kept").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(dir.join("nowhere"), dir.join("desktop.json.corrupt.2")).unwrap();
|
||||
let next = if cfg!(unix) {
|
||||
"desktop.json.corrupt.3"
|
||||
} else {
|
||||
"desktop.json.corrupt.2"
|
||||
};
|
||||
let path = dir.join("desktop.json");
|
||||
fs::write(&path, "{ not json").unwrap();
|
||||
assert_eq!(Config::load_from(&path), (Config::default(), true));
|
||||
assert!(!path.exists());
|
||||
assert!(dir.join("desktop.json.corrupt").is_dir());
|
||||
assert_eq!(fs::read_to_string(dir.join("desktop.json.corrupt.1")).unwrap(), "kept");
|
||||
// The dangling symlink still points nowhere and still counts as taken.
|
||||
#[cfg(unix)]
|
||||
assert!(fs::symlink_metadata(dir.join("desktop.json.corrupt.2"))
|
||||
.unwrap()
|
||||
.is_symlink());
|
||||
assert_eq!(fs::read_to_string(dir.join(next)).unwrap(), "{ not json");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_free_aside_name_disables_saving() {
|
||||
let dir = tmp_dir("aside-full");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("desktop.json");
|
||||
let names: Vec<PathBuf> = std::iter::once(dir.join("desktop.json.corrupt"))
|
||||
.chain((1..ASIDE_SLOTS).map(|n| dir.join(format!("desktop.json.corrupt.{n}"))))
|
||||
.collect();
|
||||
assert_eq!(names.len(), 10);
|
||||
for (n, name) in names.iter().enumerate() {
|
||||
fs::write(name, format!("copy {n}")).unwrap();
|
||||
}
|
||||
fs::write(&path, "{ not json").unwrap();
|
||||
assert_eq!(Config::load_from(&path), (Config::default(), false));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "{ not json");
|
||||
for (n, name) in names.iter().enumerate() {
|
||||
assert_eq!(fs::read_to_string(name).unwrap(), format!("copy {n}"));
|
||||
}
|
||||
assert!(!dir.join("desktop.json.corrupt.10").exists());
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn failed_move_aside_disables_saving() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tmp_dir("stuck");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("desktop.json");
|
||||
fs::write(&path, "{ not json").unwrap();
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
// Root ignores the read-only directory, so the rename cannot fail.
|
||||
if fs::write(dir.join("probe"), "").is_ok() {
|
||||
eprintln!("skipped: the directory is still writable (running as root?)");
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
return;
|
||||
}
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(c, Config::default());
|
||||
assert!(!can_save);
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "{ not json");
|
||||
assert!(!dir.join("desktop.json.corrupt").exists());
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_list_is_deduped_and_capped() {
|
||||
let mut c = Config::default();
|
||||
for i in 0..12 {
|
||||
assert!(c.remember(&format!("http://h{i}/"), None, false).is_empty());
|
||||
}
|
||||
assert!(c.remember("http://h5/", Some("me"), false).is_empty());
|
||||
assert_eq!(c.servers.len(), MAX_SERVERS);
|
||||
assert_eq!(c.servers[0].url, "http://h5/");
|
||||
assert_eq!(c.servers.iter().filter(|s| s.url == "http://h5/").count(), 1);
|
||||
assert_eq!(c.forget("http://h5/").unwrap().username.as_deref(), Some("me"));
|
||||
assert!(c.find("http://h5/").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remember_leaves_a_username_change_to_the_caller() {
|
||||
let url = "https://box.ts.net/";
|
||||
let mut c = Config::default();
|
||||
assert!(c.remember(url, Some("Alice"), true).is_empty());
|
||||
// Every change of the username on the same server, a case-only one,
|
||||
// another user, or none at all, returns nothing: the caller deletes
|
||||
// the old account before it saves the new one.
|
||||
for (user, saved) in [
|
||||
(Some("alice"), true),
|
||||
(Some(" alice "), true),
|
||||
(Some("bob"), true),
|
||||
(None, false),
|
||||
(None, false),
|
||||
(Some("dave"), true),
|
||||
] {
|
||||
assert!(c.remember(url, user, saved).is_empty(), "{user:?}");
|
||||
let entry = c.find(url).unwrap();
|
||||
assert_eq!((entry.username.as_deref(), entry.has_saved_password), (user, saved));
|
||||
assert_eq!(c.servers.iter().filter(|s| s.url == url).count(), 1);
|
||||
}
|
||||
assert!(c.remember("http://other/", Some("carol"), true).is_empty());
|
||||
assert!(c.remember(url, Some("erin"), true).is_empty());
|
||||
assert_eq!(c.servers.len(), 2);
|
||||
assert_eq!(c.servers[0].url, url);
|
||||
assert_eq!(c.find("http://other/").unwrap().username.as_deref(), Some("carol"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remember_returns_evicted_accounts() {
|
||||
let mut c = Config::default();
|
||||
for i in 0..MAX_SERVERS {
|
||||
let user = (i % 2 == 0).then(|| format!("u{i}"));
|
||||
assert!(c.remember(&format!("http://h{i}/"), user.as_deref(), true).is_empty());
|
||||
}
|
||||
// Moving a listed server to the top evicts nothing.
|
||||
assert!(c.remember("http://h3/", None, false).is_empty());
|
||||
assert_eq!(c.servers.len(), MAX_SERVERS);
|
||||
// A new server pushes the oldest (h0, with a username) off the end.
|
||||
assert_eq!(
|
||||
c.remember("http://new/", None, false),
|
||||
vec![("http://h0/".to_string(), "u0".to_string())]
|
||||
);
|
||||
// The next oldest is h1, which has no username: nothing to delete.
|
||||
assert!(c.remember("http://newer/", Some("x"), true).is_empty());
|
||||
assert_eq!(c.servers.len(), MAX_SERVERS);
|
||||
assert!(c.find("http://h0/").is_none() && c.find("http://h1/").is_none());
|
||||
// A username change on a listed server returns nothing; the next new
|
||||
// server evicts the oldest entry, and only that account comes back.
|
||||
let mut c = Config::default();
|
||||
for i in 0..MAX_SERVERS {
|
||||
assert!(c.remember(&format!("http://h{i}/"), Some("u"), true).is_empty());
|
||||
}
|
||||
assert!(c.remember("http://h7/", Some("v"), true).is_empty());
|
||||
assert_eq!(
|
||||
c.remember("http://h8/", Some("w"), true),
|
||||
vec![("http://h0/".to_string(), "u".to_string())]
|
||||
);
|
||||
assert_eq!(c.find("http://h7/").unwrap().username.as_deref(), Some("v"));
|
||||
assert_eq!(c.servers.len(), MAX_SERVERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_and_missing_fields_tolerated() {
|
||||
let c: Config = serde_json::from_str(r#"{"servers":[{"url":"http://a/"}],"future":1}"#).unwrap();
|
||||
assert!(c.auto_connect);
|
||||
assert_eq!(c.servers[0].username, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_sanitizing_and_reachability() {
|
||||
assert!(frame(f64::NAN, 0.0, 800.0, 600.0).sanitized().is_none());
|
||||
let small = frame(0.0, 0.0, 10.0, 10.0).sanitized().unwrap();
|
||||
assert_eq!((small.width, small.height), (MIN_WIDTH, MIN_HEIGHT));
|
||||
let screen = [rect(0.0, 0.0, 1512.0, 982.0)];
|
||||
let on = frame(100.0, 50.0, 1200.0, 800.0);
|
||||
assert!(reachable(&on, &screen));
|
||||
assert_eq!(on.fitted_to(&screen, MIN), Some(on));
|
||||
let off = frame(3000.0, 50.0, 1200.0, 800.0);
|
||||
assert!(!reachable(&off, &screen));
|
||||
assert_eq!(off.fitted_to(&screen, MIN), None);
|
||||
let above = frame(100.0, -900.0, 1200.0, 800.0);
|
||||
assert!(!reachable(&above, &screen));
|
||||
assert_eq!(above.fitted_to(&screen, MIN), None);
|
||||
// Only a sliver of the title bar on screen is not enough to grab.
|
||||
let sliver = frame(-1150.0, 50.0, 1200.0, 800.0);
|
||||
assert!(!reachable(&sliver, &screen));
|
||||
assert_eq!(sliver.fitted_to(&screen, MIN), None);
|
||||
// No screens at all (none reported): nothing is reachable.
|
||||
assert_eq!(on.fitted_to(&[], MIN), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_bar_is_above_y_on_macos() {
|
||||
let screen = [rect(0.0, 0.0, 1512.0, 982.0)];
|
||||
// On macOS the title bar of a content top at y = 10 is at -18..10,
|
||||
// mostly above the screen; elsewhere it is at 10..38.
|
||||
let high = frame(100.0, 10.0, 1200.0, 800.0);
|
||||
assert_eq!(reachable(&high, &screen), !cfg!(target_os = "macos"));
|
||||
// Half the bar above the top edge: still grabbable, and fitting
|
||||
// brings all of it onto the screen.
|
||||
let straddling = frame(100.0, TITLE_ABOVE_Y - 10.0, 1200.0, 800.0);
|
||||
assert!(reachable(&straddling, &screen));
|
||||
let fitted = straddling.fitted_to(&screen, MIN).unwrap();
|
||||
assert_eq!(outer(&fitted).1, 0.0);
|
||||
assert_eq!((fitted.x, fitted.width, fitted.height), (100.0, 1200.0, 800.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_from_an_unplugged_ultrawide_is_fitted() {
|
||||
// Saved on a 3440x1440 display at the origin, restored on a laptop.
|
||||
let laptop = [rect(0.0, 0.0, 1512.0, 982.0)];
|
||||
let wide = frame(0.0, 30.0, 3300.0, 1300.0);
|
||||
let fitted = wide.fitted_to(&laptop, MIN).unwrap();
|
||||
assert_eq!(
|
||||
(fitted.x, fitted.y, fitted.width, fitted.height),
|
||||
(0.0, 30.0, 1512.0 - FIT_MARGIN_X, 982.0 - FIT_MARGIN_Y)
|
||||
);
|
||||
let (left, top, right, bottom) = outer(&fitted);
|
||||
assert!(left >= 0.0 && top >= 0.0 && right <= 1512.0 && bottom <= 982.0);
|
||||
// Hanging off the right of the laptop by a bit: shifted, not shrunk.
|
||||
let fitted = frame(500.0, 100.0, 1200.0, 700.0).fitted_to(&laptop, MIN).unwrap();
|
||||
assert_eq!(
|
||||
(fitted.x, fitted.y, fitted.width, fitted.height),
|
||||
(312.0, 100.0, 1200.0, 700.0)
|
||||
);
|
||||
// Hanging off the left: shifted right.
|
||||
let fitted = frame(-1000.0, 100.0, 1200.0, 700.0).fitted_to(&laptop, MIN).unwrap();
|
||||
assert_eq!((fitted.x, fitted.width), (0.0, 1200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_spanning_two_displays_is_left_alone() {
|
||||
let screens = [rect(0.0, 0.0, 1512.0, 982.0), rect(1512.0, -200.0, 2560.0, 1440.0)];
|
||||
let span = frame(1000.0, 100.0, 1500.0, 700.0);
|
||||
assert_eq!(span.fitted_to(&screens, MIN), Some(span));
|
||||
// Only the edge that lands on no display moves: the left edge stays
|
||||
// on the laptop, the right edge comes back onto the external one.
|
||||
let past = frame(1000.0, 100.0, 3500.0, 700.0);
|
||||
let fitted = past.fitted_to(&screens, MIN).unwrap();
|
||||
assert_eq!(fitted.x, 1000.0);
|
||||
assert_eq!(fitted.x + fitted.width, 1512.0 + 2560.0 - FIT_MARGIN_X);
|
||||
assert_eq!((fitted.y, fitted.height), (100.0, 700.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fitted_frame_keeps_the_minimum_size() {
|
||||
let tiny = [rect(0.0, 0.0, 400.0, 300.0)];
|
||||
let fitted = frame(0.0, 40.0, 1200.0, 800.0).fitted_to(&tiny, MIN).unwrap();
|
||||
assert_eq!((fitted.width, fitted.height), MIN);
|
||||
// Too big for the screen even at the minimum: the left edge and the
|
||||
// title bar stay on it.
|
||||
let (left, top, _, _) = outer(&fitted);
|
||||
assert_eq!((left, top), (0.0, 0.0));
|
||||
assert!(reachable(&fitted, &tiny));
|
||||
// The fullscreen flag rides along.
|
||||
let full = WindowFrame {
|
||||
fullscreen: true,
|
||||
..frame(0.0, 40.0, 1200.0, 800.0)
|
||||
};
|
||||
assert!(full.fitted_to(&tiny, MIN).unwrap().fullscreen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Saved passwords, in the macOS Keychain (service "Codeman Desktop", one item
|
||||
//! per username + server). Nothing secret is ever written to the config file.
|
||||
//! Windows and Linux get their stores when those builds land.
|
||||
//!
|
||||
//! Every Keychain call runs on ONE long-lived worker thread, never on the
|
||||
//! event loop: any of them can bring up the system's access prompt (an
|
||||
//! ad-hoc build's items name the previous build), and the window must keep
|
||||
//! running while it is up. One serial worker rather than a thread per call,
|
||||
//! because jobs must run in the order they were asked for: a delete from
|
||||
//! Forget that ran after a later save of the same account would remove the
|
||||
//! password that was just saved.
|
||||
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
pub const SERVICE: &str = "Codeman Desktop";
|
||||
|
||||
/// What a job reports when the worker thread is gone.
|
||||
const WORKER_GONE: &str = "The Keychain could not be reached.";
|
||||
|
||||
/// The Keychain account name for a username on a server.
|
||||
pub fn account(server_url: &str, username: &str) -> String {
|
||||
format!("{username} @ {server_url}")
|
||||
}
|
||||
|
||||
/// The password store the worker runs jobs against: the Keychain on macOS,
|
||||
/// a stub elsewhere, an in-memory map in the tests.
|
||||
trait Backend: Send {
|
||||
fn load(&mut self, account: &str) -> Option<String>;
|
||||
fn save(&mut self, account: &str, password: &str) -> Result<(), String>;
|
||||
fn delete(&mut self, account: &str);
|
||||
}
|
||||
|
||||
enum Job {
|
||||
Load {
|
||||
account: String,
|
||||
reply: Sender<Option<String>>,
|
||||
},
|
||||
Save {
|
||||
account: String,
|
||||
password: String,
|
||||
reply: Sender<Result<(), String>>,
|
||||
},
|
||||
Delete {
|
||||
account: String,
|
||||
},
|
||||
/// Ends the worker, so the tests can check what callers see after it.
|
||||
#[cfg(test)]
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// A handle on the Keychain worker. Start it once with [`Keychain::spawn`]
|
||||
/// and clone the handle: every clone feeds the same queue, which is what
|
||||
/// keeps jobs in order. The worker ends when the last handle is dropped.
|
||||
#[derive(Clone)]
|
||||
pub struct Keychain {
|
||||
jobs: Sender<Job>,
|
||||
}
|
||||
|
||||
impl Keychain {
|
||||
/// Starts the worker. If the thread cannot be started, the handle still
|
||||
/// works and every call fails soft (no password, save refused).
|
||||
pub fn spawn() -> Keychain {
|
||||
start(Box::new(imp::System)).0
|
||||
}
|
||||
|
||||
/// The saved password for an account. Blocks until every job queued
|
||||
/// before it has run and the Keychain has answered, which can mean
|
||||
/// waiting on the access prompt, so call it from a worker thread.
|
||||
/// `None` when nothing is saved, the item is unreadable or the worker
|
||||
/// is gone.
|
||||
pub fn load_blocking(&self, account: &str) -> Option<String> {
|
||||
let (reply, answer) = mpsc::channel();
|
||||
let job = Job::Load {
|
||||
account: account.to_owned(),
|
||||
reply,
|
||||
};
|
||||
self.jobs.send(job).ok()?;
|
||||
answer.recv().ok().flatten()
|
||||
}
|
||||
|
||||
/// Saves a password, replacing any saved before. Blocks like
|
||||
/// [`Keychain::load_blocking`]; the result is the Keychain's own.
|
||||
pub fn save_blocking(&self, account: &str, password: &str) -> Result<(), String> {
|
||||
let (reply, answer) = mpsc::channel();
|
||||
let job = Job::Save {
|
||||
account: account.to_owned(),
|
||||
password: password.to_owned(),
|
||||
reply,
|
||||
};
|
||||
if self.jobs.send(job).is_err() {
|
||||
return Err(WORKER_GONE.into());
|
||||
}
|
||||
answer.recv().unwrap_or_else(|_| Err(WORKER_GONE.into()))
|
||||
}
|
||||
|
||||
/// Queues the removal of an account's password and returns at once.
|
||||
/// Jobs queued after it see the account gone. Nothing happens when the
|
||||
/// worker is gone.
|
||||
pub fn delete(&self, account: &str) {
|
||||
let _ = self.jobs.send(Job::Delete {
|
||||
account: account.to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a worker on `backend`. The join handle is for the tests; `None`
|
||||
/// when the thread could not be started, in which case the receiver went
|
||||
/// down with the closure and every send fails.
|
||||
fn start(backend: Box<dyn Backend>) -> (Keychain, Option<JoinHandle<()>>) {
|
||||
let (jobs, queue) = mpsc::channel();
|
||||
let worker = thread::Builder::new()
|
||||
.name("keychain".into())
|
||||
.spawn(move || run(backend, queue))
|
||||
.ok();
|
||||
(Keychain { jobs }, worker)
|
||||
}
|
||||
|
||||
/// The worker loop: one job at a time, in the order they were sent, until
|
||||
/// every handle is gone. A reply nobody waits for any more is dropped.
|
||||
fn run(mut backend: Box<dyn Backend>, queue: Receiver<Job>) {
|
||||
for job in queue {
|
||||
match job {
|
||||
Job::Load { account, reply } => {
|
||||
let _ = reply.send(backend.load(&account));
|
||||
}
|
||||
Job::Save {
|
||||
account,
|
||||
password,
|
||||
reply,
|
||||
} => {
|
||||
let _ = reply.send(backend.save(&account, &password));
|
||||
}
|
||||
Job::Delete { account } => backend.delete(&account),
|
||||
#[cfg(test)]
|
||||
Job::Stop => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use super::{Backend, SERVICE};
|
||||
use objc2::rc::autoreleasepool;
|
||||
use security_framework::passwords::{delete_generic_password, get_generic_password, set_generic_password};
|
||||
|
||||
/// The login Keychain, through security-framework. The worker lives as
|
||||
/// long as the app and a thread's implicit autorelease pool drains only
|
||||
/// when the thread ends, so each call gets its own pool and whatever
|
||||
/// Security autoreleases is freed with the job.
|
||||
pub struct System;
|
||||
|
||||
impl Backend for System {
|
||||
fn load(&mut self, account: &str) -> Option<String> {
|
||||
autoreleasepool(|_| {
|
||||
get_generic_password(SERVICE, account)
|
||||
.ok()
|
||||
.and_then(|b| String::from_utf8(b).ok())
|
||||
})
|
||||
}
|
||||
|
||||
fn save(&mut self, account: &str, password: &str) -> Result<(), String> {
|
||||
autoreleasepool(|_| set_generic_password(SERVICE, account, password.as_bytes()).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
fn delete(&mut self, account: &str) {
|
||||
autoreleasepool(|_| {
|
||||
let _ = delete_generic_password(SERVICE, account);
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
mod imp {
|
||||
use super::Backend;
|
||||
|
||||
/// No password store yet on this platform.
|
||||
pub struct System;
|
||||
|
||||
impl Backend for System {
|
||||
fn load(&mut self, _account: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn save(&mut self, _account: &str, _password: &str) -> Result<(), String> {
|
||||
Err("Saving passwords is not supported on this platform yet.".into())
|
||||
}
|
||||
fn delete(&mut self, _account: &str) {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{start, Backend, Job, Keychain};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
/// An in-memory store that logs every job it runs. Its delete is slow on
|
||||
/// purpose: a queue that did not keep order would let the next job
|
||||
/// overtake it, and the tests would see that.
|
||||
#[derive(Clone, Default)]
|
||||
struct Memory {
|
||||
items: Arc<Mutex<HashMap<String, String>>>,
|
||||
log: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
fn note(&self, entry: String) {
|
||||
self.log.lock().unwrap().push(entry);
|
||||
}
|
||||
fn log(&self) -> Vec<String> {
|
||||
self.log.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for Memory {
|
||||
fn load(&mut self, account: &str) -> Option<String> {
|
||||
self.note(format!("load {account}"));
|
||||
self.items.lock().unwrap().get(account).cloned()
|
||||
}
|
||||
fn save(&mut self, account: &str, password: &str) -> Result<(), String> {
|
||||
self.note(format!("save {account}"));
|
||||
self.items
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(account.to_owned(), password.to_owned());
|
||||
Ok(())
|
||||
}
|
||||
fn delete(&mut self, account: &str) {
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
self.note(format!("delete {account}"));
|
||||
self.items.lock().unwrap().remove(account);
|
||||
}
|
||||
}
|
||||
|
||||
/// A store whose load fails the way a crashed worker would.
|
||||
struct Crashes;
|
||||
|
||||
impl Backend for Crashes {
|
||||
fn load(&mut self, _account: &str) -> Option<String> {
|
||||
panic!("keychain worker crashed");
|
||||
}
|
||||
fn save(&mut self, _account: &str, _password: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
fn delete(&mut self, _account: &str) {}
|
||||
}
|
||||
|
||||
fn keychain() -> (Keychain, Memory) {
|
||||
let memory = Memory::default();
|
||||
let (keychain, worker) = start(Box::new(memory.clone()));
|
||||
assert!(worker.is_some(), "the worker thread starts");
|
||||
(keychain, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_names_are_per_user_and_server() {
|
||||
assert_eq!(
|
||||
super::account("http://127.0.0.1:3000/", "admin"),
|
||||
"admin @ http://127.0.0.1:3000/"
|
||||
);
|
||||
assert_ne!(
|
||||
super::account("http://a/", "admin"),
|
||||
super::account("http://b/", "admin")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_load_reads_what_a_save_wrote() {
|
||||
let (keychain, _) = keychain();
|
||||
assert_eq!(keychain.load_blocking("a"), None);
|
||||
assert_eq!(keychain.save_blocking("a", "secret"), Ok(()));
|
||||
assert_eq!(keychain.load_blocking("a").as_deref(), Some("secret"));
|
||||
assert_eq!(keychain.save_blocking("a", "changed"), Ok(()));
|
||||
assert_eq!(keychain.load_blocking("a").as_deref(), Some("changed"));
|
||||
assert_eq!(keychain.load_blocking("b"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_queued_before_a_save_never_removes_the_saved_password() {
|
||||
let (keychain, memory) = keychain();
|
||||
assert_eq!(keychain.save_blocking("a", "old"), Ok(()));
|
||||
keychain.delete("a");
|
||||
assert_eq!(keychain.save_blocking("a", "new"), Ok(()));
|
||||
assert_eq!(keychain.load_blocking("a").as_deref(), Some("new"));
|
||||
assert_eq!(memory.log(), ["save a", "delete a", "save a", "load a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_queued_after_a_save_removes_it_before_the_next_job() {
|
||||
let (keychain, memory) = keychain();
|
||||
assert_eq!(keychain.save_blocking("a", "secret"), Ok(()));
|
||||
keychain.delete("a");
|
||||
// No wait between the two: the load is queued behind the delete.
|
||||
assert_eq!(keychain.load_blocking("a"), None);
|
||||
assert_eq!(memory.log(), ["save a", "delete a", "load a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jobs_from_clones_on_other_threads_share_one_queue() {
|
||||
let (keychain, memory) = keychain();
|
||||
let other = keychain.clone();
|
||||
std::thread::spawn(move || {
|
||||
other.save_blocking("a", "secret").unwrap();
|
||||
other.delete("a");
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
assert_eq!(keychain.load_blocking("a"), None);
|
||||
assert_eq!(memory.log(), ["save a", "delete a", "load a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_call_fails_soft_once_the_worker_is_gone() {
|
||||
let memory = Memory::default();
|
||||
let (keychain, worker) = start(Box::new(memory.clone()));
|
||||
assert_eq!(keychain.save_blocking("a", "secret"), Ok(()));
|
||||
keychain.jobs.send(Job::Stop).unwrap();
|
||||
worker.unwrap().join().unwrap();
|
||||
|
||||
assert_eq!(keychain.load_blocking("a"), None);
|
||||
assert!(keychain.save_blocking("a", "secret").is_err());
|
||||
keychain.delete("a");
|
||||
keychain.clone().delete("a");
|
||||
assert_eq!(memory.log(), ["save a"]);
|
||||
}
|
||||
|
||||
#[cfg(panic = "unwind")]
|
||||
#[test]
|
||||
fn a_worker_that_dies_mid_job_answers_nothing_and_takes_no_more_jobs() {
|
||||
let (keychain, worker) = start(Box::new(Crashes));
|
||||
assert_eq!(keychain.load_blocking("a"), None);
|
||||
assert!(worker.unwrap().join().is_err(), "the worker panicked");
|
||||
assert!(keychain.save_blocking("a", "secret").is_err());
|
||||
keychain.delete("a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handle_is_send_and_sync() {
|
||||
fn send_sync_clone<T: Send + Sync + Clone + 'static>() {}
|
||||
send_sync_clone::<Keychain>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,785 @@
|
||||
//! "Start Codeman on this Mac": `codeman web -d` through the user's login shell.
|
||||
//!
|
||||
//! A double-clicked app gets launchd's bare PATH (`/usr/bin:/bin:...`), which
|
||||
//! finds neither `codeman` nor `node`, and the server inherits whatever
|
||||
//! environment it is started with: every session it spawns looks for
|
||||
//! claude/codex/tmux on that PATH and reads provider keys from it. So the
|
||||
//! command runs with the login shell's environment, picking up Homebrew and the
|
||||
//! user's profile, and falls back to the interactive profile (`-i`) for setups
|
||||
//! that only extend PATH there (nvm in `.zshrc`). The URL's port and base path
|
||||
//! are passed as separate arguments (`"$@"`), never spliced into the script text.
|
||||
//!
|
||||
//! How depends on the shell, chosen by its basename as Codeman's own
|
||||
//! `src/utils/shell-resolver.ts` does:
|
||||
//! - A POSIX shell (zsh, bash, sh, ...) runs `SCRIPT` itself:
|
||||
//! `$SHELL -l [-i] -c SCRIPT codeman-desktop <args>`.
|
||||
//! - Any other shell (fish, nu, xonsh, elvish, pwsh, tcsh) cannot parse
|
||||
//! `SCRIPT`: fish has no `then`/`fi` and refuses `$@`. It is only asked to
|
||||
//! print its environment between two markers, and `SCRIPT` then runs under
|
||||
//! `/bin/sh` with exactly that environment.
|
||||
//!
|
||||
//! `codeman web -d` refuses to start a second server on the same data dir and
|
||||
//! returns once the new one answers `/api/status`, so this is safe to call
|
||||
//! only after the probe found nothing listening.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
use url::Url;
|
||||
|
||||
use crate::policy;
|
||||
|
||||
/// For the whole start, every shell run and retry included.
|
||||
const TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// How long the pipes may stay open after the shell exited. Something the
|
||||
/// profile started in the background can inherit them and keep them open for
|
||||
/// as long as it runs; whatever arrived by then is used.
|
||||
const PIPE_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Found on PATH first, then the `install.sh` clone at `~/.codeman/app`.
|
||||
const SCRIPT: &str = r#"if command -v codeman >/dev/null 2>&1; then exec codeman "$@"; fi
|
||||
if [ -f "$HOME/.codeman/app/dist/index.js" ] && command -v node >/dev/null 2>&1; then
|
||||
exec node "$HOME/.codeman/app/dist/index.js" "$@"
|
||||
fi
|
||||
echo "Could not find the codeman command or ~/.codeman/app. Install Codeman first: https://github.com/Ark0N/Codeman#install" >&2
|
||||
exit 127"#;
|
||||
|
||||
/// Bracket the environment a non-POSIX login shell prints, so whatever its
|
||||
/// profile writes to stdout before or after cannot be read as a variable.
|
||||
const ENV_BEGIN: &str = "__CODEMAN_DESKTOP_ENV_BEGIN__";
|
||||
const ENV_END: &str = "__CODEMAN_DESKTOP_ENV_END__";
|
||||
|
||||
/// What a non-POSIX login shell runs to report its environment. The shell
|
||||
/// itself only parses a command path and one single-quoted word with no `;`,
|
||||
/// `$`, backslash or `!` in it, so fish, nu, xonsh, elvish, pwsh and tcsh have
|
||||
/// no syntax of their own to disagree on. The markers and `env` run under
|
||||
/// `/bin/sh`, which inherits everything the profile exported.
|
||||
fn capture_command() -> String {
|
||||
format!("/bin/sh -c 'echo {ENV_BEGIN}; /usr/bin/env; echo {ENV_END}'")
|
||||
}
|
||||
|
||||
fn login_shell() -> PathBuf {
|
||||
std::env::var_os("SHELL")
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute() && p.exists())
|
||||
.unwrap_or_else(|| PathBuf::from("/bin/zsh"))
|
||||
}
|
||||
|
||||
/// How the login shell takes part in a start.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Flavor {
|
||||
/// Runs `SCRIPT` itself.
|
||||
Posix,
|
||||
/// Only reports its environment. One entry per attempt, in order: a later
|
||||
/// one runs when the earlier one printed no environment or its environment
|
||||
/// had no `codeman` (exit 127).
|
||||
Capture(&'static [&'static [&'static str]]),
|
||||
}
|
||||
|
||||
fn flavor(shell: &Path) -> Flavor {
|
||||
match shell.file_name().and_then(|n| n.to_str()).unwrap_or("") {
|
||||
"sh" | "bash" | "zsh" | "dash" | "ksh" | "ash" | "ksh93" | "mksh" | "pdksh" => Flavor::Posix,
|
||||
// tcsh honors -l only when it is the ONLY flag, so a login shell that
|
||||
// also runs a command is impossible; -i at least reads all of .tcshrc
|
||||
// (csh: .cshrc), including the parts guarded by `$?prompt`.
|
||||
"csh" | "tcsh" => Flavor::Capture(&[&["-ic"]]),
|
||||
_ => Flavor::Capture(&[&["-l", "-c"], &["-l", "-i", "-c"]]),
|
||||
}
|
||||
}
|
||||
|
||||
/// What one process printed, stdout and stderr kept apart.
|
||||
struct Output {
|
||||
code: Option<i32>,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
}
|
||||
|
||||
/// What `codeman` (or `SCRIPT` failing to find it) said, for the connect page.
|
||||
struct Run {
|
||||
code: Option<i32>,
|
||||
output: String,
|
||||
}
|
||||
|
||||
impl From<Output> for Run {
|
||||
fn from(out: Output) -> Self {
|
||||
let mut output = out.stdout;
|
||||
if !out.stderr.trim().is_empty() {
|
||||
output.push_str(&out.stderr);
|
||||
}
|
||||
Run {
|
||||
code: out.code,
|
||||
output: last_lines(&output, 6),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy `pipe` into the channel as it arrives, tagged with `stream`, then send
|
||||
/// `None` once it closes.
|
||||
fn pump<R: Read + Send + 'static>(pipe: Option<R>, stream: usize, tx: mpsc::Sender<(usize, Option<Vec<u8>>)>) {
|
||||
std::thread::spawn(move || {
|
||||
if let Some(mut pipe) = pipe {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
if tx.send((stream, Some(buf[..n].to_vec()))).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = tx.send((stream, None));
|
||||
});
|
||||
}
|
||||
|
||||
/// Run `cmd` to completion with stdin closed, or kill it at `deadline`.
|
||||
fn exec(mut cmd: Command, deadline: Instant) -> Result<Output, String> {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| format!("Could not run {}: {e}", Path::new(cmd.get_program()).display()))?;
|
||||
|
||||
// Read both pipes on threads so a chatty profile cannot fill one and stall.
|
||||
let (tx, rx) = mpsc::channel();
|
||||
pump(child.stdout.take(), 0, tx.clone());
|
||||
pump(child.stderr.take(), 1, tx);
|
||||
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)),
|
||||
Ok(None) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err("Starting Codeman took longer than a minute; it was stopped.".into());
|
||||
}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
};
|
||||
|
||||
let mut bufs = [Vec::new(), Vec::new()];
|
||||
let settle = (Instant::now() + PIPE_GRACE).min(deadline);
|
||||
let mut open = 2;
|
||||
while open > 0 {
|
||||
match rx.recv_timeout(settle.saturating_duration_since(Instant::now())) {
|
||||
Ok((stream, Some(bytes))) => bufs[stream].extend_from_slice(&bytes),
|
||||
Ok((_, None)) => open -= 1,
|
||||
Err(_) => {
|
||||
// Still held open past the grace: keep what already arrived.
|
||||
for (stream, bytes) in rx.try_iter() {
|
||||
if let Some(bytes) = bytes {
|
||||
bufs[stream].extend_from_slice(&bytes);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Lossy rather than strict: one stray non-UTF-8 byte in a profile's output
|
||||
// must not cost the whole environment.
|
||||
let [out, err] = bufs;
|
||||
Ok(Output {
|
||||
code: status.code(),
|
||||
stdout: String::from_utf8_lossy(&out).into_owned(),
|
||||
stderr: String::from_utf8_lossy(&err).into_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The tail of what the command printed, for the connect page.
|
||||
fn last_lines(text: &str, n: usize) -> String {
|
||||
let lines: Vec<&str> = text
|
||||
.lines()
|
||||
.map(str::trim_end)
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.collect();
|
||||
lines[lines.len().saturating_sub(n)..].join("\n")
|
||||
}
|
||||
|
||||
/// The variables `env` printed between the markers, or None when the output
|
||||
/// does not hold both. A line that does not start with a portable variable
|
||||
/// name followed by `=` continues the previous value (a value with a newline
|
||||
/// in it); one that does starts the next variable.
|
||||
fn parse_env(output: &str) -> Option<Vec<(String, String)>> {
|
||||
let mut lines = output.split('\n');
|
||||
// ends_with: a profile line printed without its newline sits in front.
|
||||
lines.by_ref().find(|l| l.trim_end().ends_with(ENV_BEGIN))?;
|
||||
let mut vars: Vec<(String, String)> = Vec::new();
|
||||
for line in lines {
|
||||
if line.trim() == ENV_END {
|
||||
return Some(vars);
|
||||
}
|
||||
match env_entry(line) {
|
||||
Some((name, value)) => vars.push((name.to_string(), value.to_string())),
|
||||
None => {
|
||||
if let Some((_, value)) = vars.last_mut() {
|
||||
value.push('\n');
|
||||
value.push_str(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn env_entry(line: &str) -> Option<(&str, &str)> {
|
||||
let (name, value) = line.split_once('=')?;
|
||||
let mut chars = name.chars();
|
||||
let first = chars.next()?;
|
||||
let portable =
|
||||
(first.is_ascii_alphabetic() || first == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
portable.then_some((name, value))
|
||||
}
|
||||
|
||||
/// Ask `shell` for its environment with `flags`. The outer error ends the
|
||||
/// start (the shell could not be run, or time is up); the inner one means this
|
||||
/// form printed no environment and the next may be tried.
|
||||
fn capture_env(
|
||||
shell: &Path,
|
||||
flags: &[&str],
|
||||
deadline: Instant,
|
||||
) -> Result<Result<Vec<(String, String)>, String>, String> {
|
||||
let mut cmd = Command::new(shell);
|
||||
cmd.args(flags).arg(capture_command());
|
||||
let out = exec(cmd, deadline)?;
|
||||
Ok(parse_env(&out.stdout).ok_or_else(|| {
|
||||
// stderr only: stdout can hold part of the environment, API keys included.
|
||||
let said = last_lines(&out.stderr, 6);
|
||||
let mut message = format!("Could not read the environment of your login shell {}", shell.display());
|
||||
if said.is_empty() {
|
||||
let code = out
|
||||
.code
|
||||
.map_or_else(|| "a signal".to_string(), |c| format!("exit code {c}"));
|
||||
message.push_str(&format!(" (it ended with {code})."));
|
||||
} else {
|
||||
message.push_str(":\n");
|
||||
message.push_str(&said);
|
||||
}
|
||||
message
|
||||
}))
|
||||
}
|
||||
|
||||
/// `script` (SCRIPT or FIND_SCRIPT) under `/bin/sh` with exactly the captured
|
||||
/// environment, so the server gets the profile's PATH, API keys and CODEMAN_*
|
||||
/// settings and nothing of launchd's bare one.
|
||||
fn run_with_env(script: &str, env: &[(String, String)], args: &[String], deadline: Instant) -> Result<Run, String> {
|
||||
let mut cmd = Command::new("/bin/sh");
|
||||
cmd.arg("-c").arg(script).arg("codeman-desktop").args(args);
|
||||
cmd.env_clear().envs(env.iter().map(|(k, v)| (k, v)));
|
||||
exec(cmd, deadline).map(Run::from)
|
||||
}
|
||||
|
||||
/// `script` run by the POSIX login shell itself.
|
||||
fn run_in_shell(
|
||||
script: &str,
|
||||
shell: &Path,
|
||||
interactive: bool,
|
||||
args: &[String],
|
||||
deadline: Instant,
|
||||
) -> Result<Run, String> {
|
||||
let mut cmd = Command::new(shell);
|
||||
cmd.arg("-l");
|
||||
if interactive {
|
||||
cmd.arg("-i");
|
||||
}
|
||||
cmd.arg("-c").arg(script).arg("codeman-desktop").args(args);
|
||||
exec(cmd, deadline).map(Run::from)
|
||||
}
|
||||
|
||||
/// Run `script` the way the login shell allows (see the module docs). Exit
|
||||
/// 127 means "no codeman here" and moves on to the next way of asking; the
|
||||
/// interactive profile is asked only when `interactive` allows it.
|
||||
fn launch(script: &str, shell: &Path, args: &[String], deadline: Instant, interactive: bool) -> Result<Run, String> {
|
||||
let attempts = match flavor(shell) {
|
||||
Flavor::Posix => {
|
||||
let result = run_in_shell(script, shell, false, args, deadline)?;
|
||||
if result.code != Some(127) || !interactive {
|
||||
return Ok(result);
|
||||
}
|
||||
// Not on the login PATH; try the interactive profile too.
|
||||
return run_in_shell(script, shell, true, args, deadline);
|
||||
}
|
||||
Flavor::Capture(attempts) => attempts,
|
||||
};
|
||||
let mut last_run = None;
|
||||
let mut capture_error = None;
|
||||
let interactive_flag = |flags: &&&[&str]| {
|
||||
flags
|
||||
.iter()
|
||||
.any(|f| f.starts_with('-') && !f.starts_with("--") && f.contains('i'))
|
||||
};
|
||||
for flags in attempts.iter().filter(|f| interactive || !interactive_flag(f)) {
|
||||
match capture_env(shell, flags, deadline)? {
|
||||
Ok(env) => {
|
||||
let result = run_with_env(script, &env, args, deadline)?;
|
||||
if result.code != Some(127) {
|
||||
return Ok(result);
|
||||
}
|
||||
last_run = Some(result);
|
||||
}
|
||||
Err(e) => capture_error = Some(e),
|
||||
}
|
||||
}
|
||||
if let Some(result) = last_run {
|
||||
return Ok(result);
|
||||
}
|
||||
// No form printed an environment: a shell that knows neither -l nor -i
|
||||
// may still run a bare -c.
|
||||
match capture_env(shell, &["-c"], deadline)? {
|
||||
Ok(env) => run_with_env(script, &env, args, deadline),
|
||||
Err(e) => Err(capture_error.unwrap_or(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Exit 0 when SCRIPT would find Codeman (the `codeman` command or the
|
||||
/// `install.sh` clone), 127 when it would not. Same lookup, nothing started.
|
||||
const FIND_SCRIPT: &str = r#"if command -v codeman >/dev/null 2>&1; then exit 0; fi
|
||||
if [ -f "$HOME/.codeman/app/dist/index.js" ] && command -v node >/dev/null 2>&1; then exit 0; fi
|
||||
exit 127"#;
|
||||
|
||||
/// How long the This Mac tab waits for the login shell to answer whether
|
||||
/// Codeman is installed.
|
||||
const FIND_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// `installed` with the shell given, so tests need not touch `$SHELL`.
|
||||
fn installed_with(shell: &Path, interactive: bool) -> bool {
|
||||
matches!(
|
||||
launch(FIND_SCRIPT, shell, &[], Instant::now() + FIND_TIMEOUT, interactive),
|
||||
Ok(Run { code: Some(0), .. })
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether "Start Codeman on this Mac" would find Codeman: the `codeman`
|
||||
/// command on the login shell's PATH, or `~/.codeman/app` with `node`. Runs
|
||||
/// the login shell, so never on the event loop. `interactive` also asks the
|
||||
/// interactive profile (nvm in `.zshrc`, say), whose side effects only a
|
||||
/// user's own click should set off.
|
||||
pub fn installed(interactive: bool) -> bool {
|
||||
installed_with(&login_shell(), interactive)
|
||||
}
|
||||
|
||||
/// `start` with the shell given, so tests need not touch `$SHELL`.
|
||||
fn start_with(shell: &Path, args: &[String]) -> Result<String, String> {
|
||||
let result = launch(SCRIPT, shell, args, Instant::now() + TIMEOUT, true)?;
|
||||
match result.code {
|
||||
Some(0) => Ok(result.output),
|
||||
_ if result.output.is_empty() => Err("codeman web -d failed without saying why.".into()),
|
||||
_ => Err(result.output),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a detached server for `url`. Ok carries what `codeman` printed.
|
||||
pub fn start(url: &Url) -> Result<String, String> {
|
||||
if !policy::can_start_locally(url) {
|
||||
return Err("Codeman can only be started here for http://127.0.0.1 or http://localhost on this Mac.".into());
|
||||
}
|
||||
start_with(&login_shell(), &policy::start_args(url))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// One spawning test at a time. A test writes a fake executable and then
|
||||
/// runs it; a process forked by a parallel test in between can still hold
|
||||
/// the write descriptor, and the exec then fails with ETXTBSY.
|
||||
fn serial() -> std::sync::MutexGuard<'static, ()> {
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
LOCK.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tail_of_output() {
|
||||
assert_eq!(last_lines("a\n\nb\nc\n", 2), "b\nc");
|
||||
assert_eq!(last_lines("", 3), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_non_local_or_https() {
|
||||
assert!(start(&Url::parse("https://127.0.0.1:3000/").unwrap()).is_err());
|
||||
assert!(start(&Url::parse("http://192.168.1.4:3000/").unwrap()).is_err());
|
||||
}
|
||||
|
||||
/// The script passes its arguments through untouched and reports a missing
|
||||
/// `codeman` with exit 127 (run with an empty PATH and HOME so nothing is found).
|
||||
#[test]
|
||||
fn script_reports_missing_codeman() {
|
||||
let _serial = serial();
|
||||
let out = Command::new("/bin/sh")
|
||||
.arg("-c")
|
||||
.arg(SCRIPT)
|
||||
.arg("codeman-desktop")
|
||||
.args(["web", "-d", "--port", "3000"])
|
||||
.env("PATH", "/nonexistent")
|
||||
.env("HOME", "/nonexistent")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(out.status.code(), Some(127));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("Could not find the codeman command"));
|
||||
}
|
||||
|
||||
/// Arguments are data: a hostile-looking value is passed as one argv entry
|
||||
/// to a fake `codeman`, never run by the shell.
|
||||
#[test]
|
||||
fn arguments_are_not_shell_text() {
|
||||
let _serial = serial();
|
||||
let dir = std::env::temp_dir().join(format!("codeman-desktop-fake-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let fake = dir.join("codeman");
|
||||
std::fs::write(&fake, "#!/bin/sh\nfor a in \"$@\"; do printf '[%s]' \"$a\"; done\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let out = Command::new("/bin/sh")
|
||||
.arg("-c")
|
||||
.arg(SCRIPT)
|
||||
.arg("codeman-desktop")
|
||||
.args(["web", "--base-url", "/x; touch /tmp/pwned"])
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", dir.display()))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
"[web][--base-url][/x; touch /tmp/pwned]"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn pairs(vars: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
vars.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_capture_parser() {
|
||||
let out = format!(
|
||||
"Welcome to fish, the friendly interactive shell\nno newline here{ENV_BEGIN}\n\
|
||||
PATH=/opt/homebrew/bin:/usr/bin:/bin\n\
|
||||
MULTI=line one\nline two\n three = 3\n\
|
||||
EMPTY=\n\
|
||||
TRAIL=a \n\n\
|
||||
_=/usr/bin/env\n\
|
||||
{ENV_END} \nbye from the profile\nNOT_CAPTURED=1\n"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_env(&out),
|
||||
Some(pairs(&[
|
||||
("PATH", "/opt/homebrew/bin:/usr/bin:/bin"),
|
||||
("MULTI", "line one\nline two\n three = 3"),
|
||||
("EMPTY", ""),
|
||||
("TRAIL", "a \n"),
|
||||
("_", "/usr/bin/env"),
|
||||
]))
|
||||
);
|
||||
// A value may itself contain `=`; only the first one splits.
|
||||
assert_eq!(
|
||||
parse_env(&format!("{ENV_BEGIN}\nOPTS=a=b\n{ENV_END}\n")),
|
||||
Some(pairs(&[("OPTS", "a=b")]))
|
||||
);
|
||||
assert_eq!(parse_env(&format!("{ENV_BEGIN}\n{ENV_END}\n")), Some(vec![]));
|
||||
assert_eq!(parse_env(&format!("{ENV_BEGIN}\nPATH=/usr/bin\n")), None);
|
||||
assert_eq!(parse_env(&format!("PATH=/usr/bin\n{ENV_END}\n")), None);
|
||||
assert_eq!(parse_env("fish: Unknown command: then\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_flavor_by_basename() {
|
||||
for posix in [
|
||||
"/bin/zsh",
|
||||
"/bin/bash",
|
||||
"/bin/sh",
|
||||
"/bin/dash",
|
||||
"/bin/ksh",
|
||||
"/opt/homebrew/bin/bash",
|
||||
] {
|
||||
assert_eq!(flavor(Path::new(posix)), Flavor::Posix, "{posix}");
|
||||
}
|
||||
assert_eq!(flavor(Path::new("/bin/tcsh")), Flavor::Capture(&[&["-ic"]]));
|
||||
assert_eq!(flavor(Path::new("/bin/csh")), Flavor::Capture(&[&["-ic"]]));
|
||||
for other in [
|
||||
"/opt/homebrew/bin/fish",
|
||||
"/usr/local/bin/nu",
|
||||
"/opt/homebrew/bin/xonsh",
|
||||
"/usr/local/bin/pwsh",
|
||||
] {
|
||||
assert_eq!(
|
||||
flavor(Path::new(other)),
|
||||
Flavor::Capture(&[&["-l", "-c"], &["-l", "-i", "-c"]]),
|
||||
"{other}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The login shell's part avoids everything only POSIX shells read.
|
||||
#[test]
|
||||
fn capture_command_is_shell_neutral() {
|
||||
let _serial = serial();
|
||||
let cmd = capture_command();
|
||||
for bad in ["then", "fi", "$", "\\", "!", "\"", "&&"] {
|
||||
assert!(!cmd.contains(bad), "{bad} in {cmd}");
|
||||
}
|
||||
assert_eq!(cmd.matches('\'').count(), 2);
|
||||
assert!(cmd.starts_with("/bin/sh -c '"));
|
||||
// /bin/sh, as the capture runs it, prints a parsable environment.
|
||||
let out = Command::new("/bin/sh")
|
||||
.arg("-c")
|
||||
.arg(&cmd)
|
||||
.env("CODEMAN_DESKTOP_PARSER_PROBE", "two\nlines")
|
||||
.output()
|
||||
.unwrap();
|
||||
let env = parse_env(&String::from_utf8_lossy(&out.stdout)).expect("markers");
|
||||
assert!(env
|
||||
.iter()
|
||||
.any(|(k, v)| k == "CODEMAN_DESKTOP_PARSER_PROBE" && v == "two\nlines"));
|
||||
assert!(env.iter().any(|(k, _)| k == "PATH"));
|
||||
}
|
||||
|
||||
/// A scratch directory with a fake `codeman` in `bin/` that prints its
|
||||
/// arguments, the profile's marker variable and the names of everything in
|
||||
/// its environment.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(name: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("codeman-desktop-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("bin")).unwrap();
|
||||
std::fs::create_dir_all(dir.join("home")).unwrap();
|
||||
let scratch = Scratch(dir);
|
||||
scratch.exe(
|
||||
"bin/codeman",
|
||||
"#!/bin/sh\nprintf '[%s]' \"$@\"; echo\necho \"profile: $CODEMAN_DESKTOP_TEST\"\n\
|
||||
printf 'names:'; env | cut -d= -f1 | tr '\\n' ' '; echo\n",
|
||||
);
|
||||
scratch
|
||||
}
|
||||
|
||||
/// Write an executable at `rel`, with `DIR` in `body` replaced by the scratch path.
|
||||
fn exe(&self, rel: &str, body: &str) -> PathBuf {
|
||||
let path = self.0.join(rel);
|
||||
std::fs::write(&path, body.replace("DIR", &self.0.display().to_string())).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn argv_log(&self) -> String {
|
||||
std::fs::read_to_string(self.0.join("argv.log")).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
const HOSTILE_ARGS: [&str; 3] = ["web", "--base-url", "/x; touch /tmp/pwned"];
|
||||
|
||||
fn hostile_args() -> Vec<String> {
|
||||
HOSTILE_ARGS.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
/// A stand-in for fish: it refuses POSIX `then` and `$@` the way fish
|
||||
/// does, logs its flags, prints profile noise around whatever it runs, and
|
||||
/// its "profile" replaces the environment. On its interactive form only
|
||||
/// when `INTERACTIVE_ONLY` is yes, PATH reaches the fake `codeman`.
|
||||
const FAKE_FISH: &str = r#"#!/bin/sh
|
||||
args=""
|
||||
for a in "$@"; do
|
||||
case "$a" in
|
||||
*then*|*'$@'*) echo "fish: Unknown command: then" >&2; exit 127;;
|
||||
-*) args="$args$a ";;
|
||||
esac
|
||||
cmd="$a"
|
||||
done
|
||||
echo "$args" >> "DIR/argv.log"
|
||||
bin="DIR/bin"
|
||||
case "INTERACTIVE_ONLY:$args" in yes:*-i*|no:*) ;; *) bin=/nonexistent;; esac
|
||||
echo "Welcome to fish, the friendly interactive shell"
|
||||
/usr/bin/env -i PATH="$bin:/usr/bin:/bin" HOME="DIR/home" CODEMAN_DESKTOP_TEST="from the profile" /bin/sh -c "$cmd"
|
||||
echo "bye from the profile"
|
||||
"#;
|
||||
|
||||
/// SCRIPT never reaches the non-POSIX shell: it runs under /bin/sh with the
|
||||
/// environment the shell printed, and with nothing else.
|
||||
#[test]
|
||||
fn non_posix_shell_only_reports_its_environment() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("fish");
|
||||
let fish = s.exe("fish", &FAKE_FISH.replace("INTERACTIVE_ONLY", "no"));
|
||||
let out = start_with(&fish, &hostile_args()).expect("started");
|
||||
let lines: Vec<&str> = out.lines().collect();
|
||||
assert_eq!(lines[0], "[web][--base-url][/x; touch /tmp/pwned]");
|
||||
assert_eq!(lines[1], "profile: from the profile");
|
||||
assert_eq!(s.argv_log(), "-l -c \n");
|
||||
|
||||
// env_clear: a variable this process has, but the profile did not
|
||||
// export, must not reach codeman.
|
||||
let names: Vec<&str> = lines[2].trim_start_matches("names:").split_whitespace().collect();
|
||||
assert!(names.contains(&"PATH") && names.contains(&"CODEMAN_DESKTOP_TEST"));
|
||||
let captured = ["PATH", "HOME", "CODEMAN_DESKTOP_TEST", "PWD", "OLDPWD", "SHLVL", "_"];
|
||||
let leaked: Vec<String> = std::env::vars_os()
|
||||
.filter_map(|(k, _)| k.into_string().ok())
|
||||
.filter(|k| !captured.contains(&k.as_str()) && !k.starts_with("__CF"))
|
||||
.filter(|k| names.contains(&k.as_str()))
|
||||
.collect();
|
||||
assert!(leaked.is_empty(), "leaked from the app: {leaked:?}");
|
||||
}
|
||||
|
||||
/// No codeman on the login PATH (exit 127): the environment is captured
|
||||
/// again from the interactive profile, and that run finds it.
|
||||
#[test]
|
||||
fn non_posix_shell_retries_with_the_interactive_profile() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("fish-retry");
|
||||
let fish = s.exe("fish", &FAKE_FISH.replace("INTERACTIVE_ONLY", "yes"));
|
||||
let out = start_with(&fish, &hostile_args()).expect("started");
|
||||
assert!(out.starts_with("[web][--base-url][/x; touch /tmp/pwned]\n"), "{out}");
|
||||
assert_eq!(s.argv_log(), "-l -c \n-l -i -c \n");
|
||||
}
|
||||
|
||||
/// tcsh takes -l only as its only flag, so it is asked with -ic alone.
|
||||
#[test]
|
||||
fn tcsh_gets_ic_and_never_l() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("tcsh");
|
||||
let tcsh = s.exe(
|
||||
"tcsh",
|
||||
r#"#!/bin/sh
|
||||
echo "$*" >> "DIR/argv.log"
|
||||
if [ "$#" != 2 ] || [ "$1" != -ic ]; then echo "tcsh: Unknown option: $1" >&2; exit 1; fi
|
||||
/usr/bin/env -i PATH="DIR/bin:/usr/bin:/bin" HOME="DIR/home" CODEMAN_DESKTOP_TEST=tcsh /bin/sh -c "$2"
|
||||
"#,
|
||||
);
|
||||
let out = start_with(&tcsh, &hostile_args()).expect("started");
|
||||
assert!(out.contains("profile: tcsh"), "{out}");
|
||||
assert_eq!(s.argv_log().lines().count(), 1);
|
||||
assert!(s.argv_log().starts_with("-ic /bin/sh -c '"));
|
||||
}
|
||||
|
||||
/// A shell that takes neither -l nor -i still gets a bare -c.
|
||||
#[test]
|
||||
fn shell_without_login_flags_falls_back_to_plain_c() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("nolflag");
|
||||
let shell = s.exe(
|
||||
"elvish",
|
||||
r#"#!/bin/sh
|
||||
echo "$1" >> "DIR/argv.log"
|
||||
case "$1" in -l|-i) echo "flag provided but not defined: $1" >&2; exit 2;; esac
|
||||
/usr/bin/env -i PATH="DIR/bin:/usr/bin:/bin" HOME="DIR/home" CODEMAN_DESKTOP_TEST=plain /bin/sh -c "$2"
|
||||
"#,
|
||||
);
|
||||
let out = start_with(&shell, &hostile_args()).expect("started");
|
||||
assert!(out.contains("profile: plain"), "{out}");
|
||||
assert_eq!(s.argv_log(), "-l\n-l\n-c\n");
|
||||
}
|
||||
|
||||
/// A shell that never prints its environment is reported by name with what
|
||||
/// it said on stderr, never with stdout (which can carry secrets).
|
||||
#[test]
|
||||
fn capture_failure_names_the_shell() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("broken");
|
||||
let shell = s.exe(
|
||||
"weirdsh",
|
||||
"#!/bin/sh\necho 'API_KEY=sk-secret'\necho 'weirdsh: cannot start' >&2\nexit 3\n",
|
||||
);
|
||||
let err = start_with(&shell, &hostile_args()).unwrap_err();
|
||||
assert!(err.contains("Could not read the environment"), "{err}");
|
||||
assert!(err.contains("weirdsh: cannot start"), "{err}");
|
||||
assert!(!err.contains("sk-secret"), "{err}");
|
||||
}
|
||||
|
||||
/// POSIX shells keep running SCRIPT themselves: `-l -c SCRIPT codeman-desktop
|
||||
/// args`, then `-l -i -c` when the login PATH had no codeman.
|
||||
#[test]
|
||||
fn posix_shell_runs_script_itself_and_retries_interactive() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("zsh");
|
||||
let zsh = s.exe(
|
||||
"zsh",
|
||||
r#"#!/bin/sh
|
||||
[ "$1" = -l ] || exit 90
|
||||
shift
|
||||
PATH=/usr/bin:/bin
|
||||
if [ "$1" = -i ]; then shift; PATH="DIR/bin:/usr/bin:/bin"; fi
|
||||
[ "$1" = -c ] || exit 91
|
||||
shift
|
||||
echo "$2" >> "DIR/argv.log"
|
||||
HOME="DIR/home"
|
||||
export PATH HOME
|
||||
exec /bin/sh -c "$@"
|
||||
"#,
|
||||
);
|
||||
let out = start_with(&zsh, &hostile_args()).expect("started");
|
||||
assert!(out.starts_with("[web][--base-url][/x; touch /tmp/pwned]\n"), "{out}");
|
||||
// $0 of the script, once per run: login, then interactive.
|
||||
assert_eq!(s.argv_log(), "codeman-desktop\ncodeman-desktop\n");
|
||||
}
|
||||
|
||||
/// The installed check asks the same shells the same way and runs nothing:
|
||||
/// found on the interactive PATH here, after the login PATH had none.
|
||||
#[test]
|
||||
fn installed_check_finds_codeman_without_running_it() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("find-zsh");
|
||||
let zsh = s.exe(
|
||||
"zsh",
|
||||
r#"#!/bin/sh
|
||||
[ "$1" = -l ] || exit 90
|
||||
shift
|
||||
PATH=/usr/bin:/bin
|
||||
if [ "$1" = -i ]; then shift; PATH="DIR/bin:/usr/bin:/bin"; fi
|
||||
[ "$1" = -c ] || exit 91
|
||||
shift
|
||||
echo "$2" >> "DIR/argv.log"
|
||||
HOME="DIR/home"
|
||||
export PATH HOME
|
||||
exec /bin/sh -c "$@"
|
||||
"#,
|
||||
);
|
||||
// A codeman that would leave a mark if it ran.
|
||||
s.exe("bin/codeman", "#!/bin/sh\ntouch DIR/ran\n");
|
||||
// Without the interactive profile: one login-shell look, not found.
|
||||
assert!(!installed_with(&zsh, false));
|
||||
assert_eq!(s.argv_log(), "codeman-desktop\n");
|
||||
assert!(installed_with(&zsh, true));
|
||||
assert_eq!(s.argv_log(), "codeman-desktop\ncodeman-desktop\ncodeman-desktop\n");
|
||||
assert!(!s.0.join("ran").exists(), "the installed check ran codeman");
|
||||
}
|
||||
|
||||
/// Nothing on any PATH and no ~/.codeman/app: not installed. Through a
|
||||
/// non-POSIX shell too, which only reports its environment.
|
||||
#[test]
|
||||
fn installed_check_reports_missing_codeman() {
|
||||
let _serial = serial();
|
||||
let s = Scratch::new("find-fish");
|
||||
std::fs::remove_file(s.0.join("bin/codeman")).unwrap();
|
||||
let fish = s.exe("fish", &FAKE_FISH.replace("INTERACTIVE_ONLY", "no"));
|
||||
assert!(!installed_with(&fish, true));
|
||||
// The login-only look asks fish once, with -l and never -i.
|
||||
let before = s.argv_log();
|
||||
assert!(!installed_with(&fish, false));
|
||||
assert_eq!(&s.argv_log()[before.len()..], "-l -c \n");
|
||||
|
||||
// The install.sh clone counts once node is there.
|
||||
let app = s.0.join("home/.codeman/app/dist");
|
||||
std::fs::create_dir_all(&app).unwrap();
|
||||
std::fs::write(app.join("index.js"), "").unwrap();
|
||||
s.exe("bin/node", "#!/bin/sh\nexit 0\n");
|
||||
assert!(installed_with(&fish, true));
|
||||
assert!(installed_with(&fish, false));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,727 @@
|
||||
//! "Is a Codeman server answering at this address, and does it want a login?"
|
||||
//!
|
||||
//! One `GET <server>/api/status`, five seconds at most, run off the UI thread.
|
||||
//! The answer is classified into something the connect page can explain. It is
|
||||
//! asked once per user action, never in a loop: Codeman counts a request
|
||||
//! without valid credentials against the login rate limit (10 per IP).
|
||||
|
||||
use serde::Serialize;
|
||||
use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MAX_BODY: u64 = 8 * 1024 * 1024;
|
||||
|
||||
/// The path the probe asks for, relative to the server's base URL.
|
||||
const STATUS_PATH: &str = "api/status";
|
||||
|
||||
/// rustls' text for `Error::InvalidCertificate`, which is what a handshake
|
||||
/// with a certificate the OS does not trust fails with. ureq hands it over as
|
||||
/// an `io::Error` of kind `InvalidData`, so the text is all there is to match
|
||||
/// without a direct rustls dependency.
|
||||
const CERT_REJECTED_PREFIX: &str = "invalid peer certificate";
|
||||
|
||||
/// std's text for a failed `getaddrinfo`. Its kind is `Uncategorized`, which
|
||||
/// cannot be matched on stable Rust, so the prefix is the only handle. The
|
||||
/// prefix is the same on macOS and Linux; only the resolver's reason differs.
|
||||
const LOOKUP_FAILED_PREFIX: &str = "failed to lookup address information";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum ProbeOutcome {
|
||||
Ok {
|
||||
version: String,
|
||||
},
|
||||
/// 401 and we sent no credentials.
|
||||
NeedsLogin,
|
||||
/// 401 although we sent credentials.
|
||||
BadCredentials,
|
||||
/// 429: too many failed logins from this address. A single-user Codeman
|
||||
/// still accepts the right password, so the page needs to know whether
|
||||
/// this probe carried one. `retry_after_secs` is the server's
|
||||
/// `Retry-After`, when it gave one in seconds.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
RateLimited {
|
||||
sent_credentials: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
retry_after_secs: Option<u64>,
|
||||
},
|
||||
/// 403 `PASSWORD_CHANGE_REQUIRED`: the credentials are valid, but a
|
||||
/// multi-user Codeman wants this account's password changed first. Page
|
||||
/// loads are exempt, so the web UI can show its change-password dialog.
|
||||
PasswordChangeRequired,
|
||||
/// 403 from Codeman's Host guard (a name it does not know, e.g. a custom domain).
|
||||
HostNotAllowed,
|
||||
/// 3xx. `location` is the target resolved against the probed URL.
|
||||
/// `suggested` is a server address to use instead, set only when the
|
||||
/// redirect stays on the same host, only moves to https or another port,
|
||||
/// and still points at the status API. Never followed: a second request
|
||||
/// would carry the credentials to an address the user did not type.
|
||||
Redirect {
|
||||
location: String,
|
||||
suggested: Option<String>,
|
||||
},
|
||||
/// Something answered, but not Codeman's status API.
|
||||
NotCodeman {
|
||||
status: u16,
|
||||
},
|
||||
Refused,
|
||||
/// No route to the address: the machine is off or on another network,
|
||||
/// or macOS's Local Network privacy setting blocked the app.
|
||||
Unreachable,
|
||||
/// An http:// probe whose connection was closed without an answer. A
|
||||
/// Codeman started with `--https` does exactly that to plain HTTP.
|
||||
MaybeHttps,
|
||||
Timeout,
|
||||
TlsUntrusted {
|
||||
detail: String,
|
||||
},
|
||||
Unresolvable,
|
||||
Failed {
|
||||
detail: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Classify an HTTP answer to `<server>/api/status`. `request` is the URL that
|
||||
/// was asked, `location` and `retry_after` are those response headers.
|
||||
pub fn classify_response(
|
||||
request: &Url,
|
||||
status: u16,
|
||||
location: Option<&str>,
|
||||
retry_after: Option<&str>,
|
||||
sent_credentials: bool,
|
||||
body: &str,
|
||||
) -> ProbeOutcome {
|
||||
match status {
|
||||
200 => {
|
||||
let parsed: Option<serde_json::Value> = serde_json::from_str(body).ok();
|
||||
let version = parsed.as_ref().and_then(|v| {
|
||||
(v.get("success")? == &serde_json::Value::Bool(true))
|
||||
.then(|| v.get("data")?.get("version")?.as_str().map(str::to_string))
|
||||
.flatten()
|
||||
});
|
||||
match version {
|
||||
Some(version) => ProbeOutcome::Ok { version },
|
||||
None => ProbeOutcome::NotCodeman { status },
|
||||
}
|
||||
}
|
||||
300..=399 => {
|
||||
// A 3xx without a usable Location (304, a garbled header) is not a
|
||||
// redirect anyone can act on.
|
||||
match location.and_then(|l| request.join(l.trim()).ok()) {
|
||||
Some(target) => ProbeOutcome::Redirect {
|
||||
suggested: suggested_server(request, &target),
|
||||
location: target.into(),
|
||||
},
|
||||
None => ProbeOutcome::NotCodeman { status },
|
||||
}
|
||||
}
|
||||
401 if sent_credentials => ProbeOutcome::BadCredentials,
|
||||
401 => ProbeOutcome::NeedsLogin,
|
||||
403 if body.contains("host not allowed") => ProbeOutcome::HostNotAllowed,
|
||||
// Codeman only says this after the Basic credentials verified (the
|
||||
// probe sends no cookie), so without credentials it is not Codeman's
|
||||
// answer to us, and loading the page without them would not help.
|
||||
403 if sent_credentials && error_code(body).as_deref() == Some("PASSWORD_CHANGE_REQUIRED") => {
|
||||
ProbeOutcome::PasswordChangeRequired
|
||||
}
|
||||
429 => ProbeOutcome::RateLimited {
|
||||
sent_credentials,
|
||||
retry_after_secs: retry_after.and_then(|v| v.trim().parse::<u64>().ok()),
|
||||
},
|
||||
other => ProbeOutcome::NotCodeman { status: other },
|
||||
}
|
||||
}
|
||||
|
||||
/// `errorCode` of a Codeman `ApiResponse` error body.
|
||||
fn error_code(body: &str) -> Option<String> {
|
||||
let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
Some(parsed.get("errorCode")?.as_str()?.to_string())
|
||||
}
|
||||
|
||||
/// The server base URL a redirect points to, when it is the same server
|
||||
/// moved to https or another port (a reverse proxy upgrading plain HTTP, the
|
||||
/// usual case). Anything else, such as another host (a login gateway the
|
||||
/// window could not pass anyway) or a downgrade to http, gets no suggestion.
|
||||
fn suggested_server(request: &Url, target: &Url) -> Option<String> {
|
||||
let upgrade = request.scheme() == "http" && target.scheme() == "https";
|
||||
let port_change =
|
||||
request.scheme() == target.scheme() && request.port_or_known_default() != target.port_or_known_default();
|
||||
if !(upgrade || port_change) || target.host() != request.host() {
|
||||
return None;
|
||||
}
|
||||
if !target.username().is_empty() || target.password().is_some() {
|
||||
return None;
|
||||
}
|
||||
// The redirect must keep pointing at the status API (a proxy may add a
|
||||
// base path in front of it); the base is what comes before it.
|
||||
if !target.path().ends_with(request.path()) || !request.path().ends_with(STATUS_PATH) {
|
||||
return None;
|
||||
}
|
||||
let base_path = &target.path()[..target.path().len() - STATUS_PATH.len()];
|
||||
let mut base = target.clone();
|
||||
base.set_path(base_path);
|
||||
base.set_query(None);
|
||||
base.set_fragment(None);
|
||||
Some(base.into())
|
||||
}
|
||||
|
||||
/// Transport failures, reduced to what the connect page explains differently.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TransportError {
|
||||
Refused,
|
||||
Unreachable,
|
||||
ClosedWithoutAnswer,
|
||||
Timeout,
|
||||
Tls(String),
|
||||
Dns,
|
||||
Other(String),
|
||||
}
|
||||
|
||||
pub fn classify_transport(err: TransportError) -> ProbeOutcome {
|
||||
match err {
|
||||
TransportError::Refused => ProbeOutcome::Refused,
|
||||
TransportError::Unreachable => ProbeOutcome::Unreachable,
|
||||
TransportError::ClosedWithoutAnswer => ProbeOutcome::MaybeHttps,
|
||||
TransportError::Timeout => ProbeOutcome::Timeout,
|
||||
TransportError::Tls(detail) => ProbeOutcome::TlsUntrusted { detail },
|
||||
TransportError::Dns => ProbeOutcome::Unresolvable,
|
||||
TransportError::Other(detail) => ProbeOutcome::Failed { detail },
|
||||
}
|
||||
}
|
||||
|
||||
/// `plain_http`: the probe went to an http:// URL. Only there does a closed
|
||||
/// connection hint at an https-only server; over https the same close is a
|
||||
/// failed handshake with nothing more to say about it.
|
||||
fn transport_error(err: &ureq::Error, plain_http: bool) -> TransportError {
|
||||
use std::io::ErrorKind;
|
||||
match err {
|
||||
ureq::Error::Timeout(_) => TransportError::Timeout,
|
||||
ureq::Error::HostNotFound => TransportError::Dns,
|
||||
ureq::Error::ConnectionFailed => TransportError::Refused,
|
||||
// ureq passes both a rejected certificate (rustls wraps it as
|
||||
// InvalidData during the handshake) and a failed name lookup (std's
|
||||
// own error) through as plain io errors, so they are told apart here
|
||||
// before the kinds below swallow them.
|
||||
ureq::Error::Io(e) if e.kind() == ErrorKind::InvalidData && e.to_string().starts_with(CERT_REJECTED_PREFIX) => {
|
||||
TransportError::Tls(e.to_string())
|
||||
}
|
||||
ureq::Error::Io(e) if e.raw_os_error().is_none() && e.to_string().starts_with(LOOKUP_FAILED_PREFIX) => {
|
||||
TransportError::Dns
|
||||
}
|
||||
ureq::Error::Io(e) => match e.kind() {
|
||||
ErrorKind::ConnectionRefused | ErrorKind::ConnectionReset | ErrorKind::AddrNotAvailable => {
|
||||
TransportError::Refused
|
||||
}
|
||||
ErrorKind::HostUnreachable | ErrorKind::NetworkUnreachable => TransportError::Unreachable,
|
||||
ErrorKind::UnexpectedEof if plain_http => TransportError::ClosedWithoutAnswer,
|
||||
ErrorKind::TimedOut | ErrorKind::WouldBlock => TransportError::Timeout,
|
||||
_ => TransportError::Other(e.to_string()),
|
||||
},
|
||||
// ureq's own rustls errors come from setting up the TLS client (the
|
||||
// handshake's arrive as Io above); only a certificate rejection is
|
||||
// "untrusted", anything else is reported as it is.
|
||||
ureq::Error::Rustls(e) if e.to_string().starts_with(CERT_REJECTED_PREFIX) => TransportError::Tls(e.to_string()),
|
||||
other => TransportError::Other(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the server. Blocking: call it from a worker thread.
|
||||
pub fn probe(server: &Url, authorization: Option<&str>) -> ProbeOutcome {
|
||||
let status_url = match server.join(STATUS_PATH) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return ProbeOutcome::Failed { detail: e.to_string() },
|
||||
};
|
||||
let tls = ureq::tls::TlsConfig::builder()
|
||||
.root_certs(ureq::tls::RootCerts::PlatformVerifier)
|
||||
.build();
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(TIMEOUT))
|
||||
.http_status_as_error(false)
|
||||
// Never follow: a 3xx comes back as an answer and is explained.
|
||||
.max_redirects(0)
|
||||
.tls_config(tls)
|
||||
.user_agent(concat!("CodemanDesktop/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.into();
|
||||
let mut req = agent.get(status_url.as_str()).header("Accept", "application/json");
|
||||
if let Some(auth) = authorization {
|
||||
req = req.header("Authorization", auth);
|
||||
}
|
||||
match req.call() {
|
||||
Ok(mut resp) => {
|
||||
let status = resp.status().as_u16();
|
||||
let header = |name: &str| {
|
||||
resp.headers()
|
||||
.get(name)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_string)
|
||||
};
|
||||
let location = header("location");
|
||||
let retry_after = header("retry-after");
|
||||
let body = resp
|
||||
.body_mut()
|
||||
.with_config()
|
||||
.limit(MAX_BODY)
|
||||
.read_to_string()
|
||||
.unwrap_or_default();
|
||||
classify_response(
|
||||
&status_url,
|
||||
status,
|
||||
location.as_deref(),
|
||||
retry_after.as_deref(),
|
||||
authorization.is_some(),
|
||||
&body,
|
||||
)
|
||||
}
|
||||
Err(e) => classify_transport(transport_error(&e, status_url.scheme() == "http")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io;
|
||||
|
||||
fn status_url() -> Url {
|
||||
Url::parse("http://studio.lan:3000/api/status").unwrap()
|
||||
}
|
||||
|
||||
/// `classify_response` for the cases that need no headers.
|
||||
fn classify(status: u16, sent_credentials: bool, body: &str) -> ProbeOutcome {
|
||||
classify_response(&status_url(), status, None, None, sent_credentials, body)
|
||||
}
|
||||
|
||||
fn redirect(request: &str, location: &str) -> ProbeOutcome {
|
||||
classify_response(&Url::parse(request).unwrap(), 301, Some(location), None, false, "")
|
||||
}
|
||||
|
||||
fn io_outcome(kind: io::ErrorKind, message: &str, plain_http: bool) -> ProbeOutcome {
|
||||
let err = ureq::Error::Io(io::Error::new(kind, message.to_string()));
|
||||
classify_transport(transport_error(&err, plain_http))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_needs_success_and_version() {
|
||||
assert_eq!(
|
||||
classify(
|
||||
200,
|
||||
false,
|
||||
r#"{"success":true,"data":{"version":"1.47.0","sessions":[]}}"#
|
||||
),
|
||||
ProbeOutcome::Ok {
|
||||
version: "1.47.0".into()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
classify(200, false, "<html>hello</html>"),
|
||||
ProbeOutcome::NotCodeman { status: 200 }
|
||||
);
|
||||
assert_eq!(
|
||||
classify(200, false, r#"{"success":false,"data":{"version":"1"}}"#),
|
||||
ProbeOutcome::NotCodeman { status: 200 }
|
||||
);
|
||||
assert_eq!(
|
||||
classify(200, false, r#"{"success":true}"#),
|
||||
ProbeOutcome::NotCodeman { status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_and_guards() {
|
||||
assert_eq!(classify(401, false, "Unauthorized"), ProbeOutcome::NeedsLogin);
|
||||
assert_eq!(classify(401, true, "Unauthorized"), ProbeOutcome::BadCredentials);
|
||||
assert_eq!(
|
||||
classify(403, false, "Forbidden: host not allowed"),
|
||||
ProbeOutcome::HostNotAllowed
|
||||
);
|
||||
// The Host guard runs before authentication, so it wins even with credentials.
|
||||
assert_eq!(
|
||||
classify(403, true, "Forbidden: host not allowed"),
|
||||
ProbeOutcome::HostNotAllowed
|
||||
);
|
||||
assert_eq!(classify(403, false, "nope"), ProbeOutcome::NotCodeman { status: 403 });
|
||||
assert_eq!(classify(502, false, ""), ProbeOutcome::NotCodeman { status: 502 });
|
||||
}
|
||||
|
||||
/// The exact body auth.ts sends: `createErrorResponse(PASSWORD_CHANGE_REQUIRED)`.
|
||||
#[test]
|
||||
fn password_change_required_only_after_sent_credentials() {
|
||||
let body = r#"{"success":false,"error":"You must change your password before continuing","errorCode":"PASSWORD_CHANGE_REQUIRED"}"#;
|
||||
assert_eq!(classify(403, true, body), ProbeOutcome::PasswordChangeRequired);
|
||||
assert_eq!(classify(403, false, body), ProbeOutcome::NotCodeman { status: 403 });
|
||||
// Another Codeman error code, or the text without the JSON field, is not it.
|
||||
assert_eq!(
|
||||
classify(403, true, r#"{"success":false,"errorCode":"FORBIDDEN"}"#),
|
||||
ProbeOutcome::NotCodeman { status: 403 }
|
||||
);
|
||||
assert_eq!(
|
||||
classify(403, true, "PASSWORD_CHANGE_REQUIRED"),
|
||||
ProbeOutcome::NotCodeman { status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limited_says_whether_credentials_went_along() {
|
||||
let body = "Too Many Requests, try again later";
|
||||
assert_eq!(
|
||||
classify(429, false, body),
|
||||
ProbeOutcome::RateLimited {
|
||||
sent_credentials: false,
|
||||
retry_after_secs: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
classify(429, true, body),
|
||||
ProbeOutcome::RateLimited {
|
||||
sent_credentials: true,
|
||||
retry_after_secs: None
|
||||
}
|
||||
);
|
||||
// auth.ts sends Retry-After in whole seconds; an HTTP date is not parsed.
|
||||
assert_eq!(
|
||||
classify_response(&status_url(), 429, None, Some(" 742 "), true, body),
|
||||
ProbeOutcome::RateLimited {
|
||||
sent_credentials: true,
|
||||
retry_after_secs: Some(742)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
classify_response(
|
||||
&status_url(),
|
||||
429,
|
||||
None,
|
||||
Some("Wed, 21 Oct 2026 07:28:00 GMT"),
|
||||
false,
|
||||
body
|
||||
),
|
||||
ProbeOutcome::RateLimited {
|
||||
sent_credentials: false,
|
||||
retry_after_secs: None
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirect_to_https_on_the_same_host_is_suggested() {
|
||||
assert_eq!(
|
||||
redirect("http://studio.lan/api/status", "https://studio.lan/api/status"),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "https://studio.lan/api/status".into(),
|
||||
suggested: Some("https://studio.lan/".into())
|
||||
}
|
||||
);
|
||||
// A base path the proxy adds stays part of the suggestion; a query does not.
|
||||
assert_eq!(
|
||||
redirect(
|
||||
"http://studio.lan:3000/api/status",
|
||||
"https://studio.lan/codeman/api/status?from=http"
|
||||
),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "https://studio.lan/codeman/api/status?from=http".into(),
|
||||
suggested: Some("https://studio.lan/codeman/".into())
|
||||
}
|
||||
);
|
||||
// A relative Location resolves against the probed URL; another port is fine.
|
||||
assert_eq!(
|
||||
redirect(
|
||||
"http://studio.lan:3000/base/api/status",
|
||||
"//studio.lan:3001/base/api/status"
|
||||
),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "http://studio.lan:3001/base/api/status".into(),
|
||||
suggested: Some("http://studio.lan:3001/base/".into())
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_redirects_are_reported_without_a_suggestion() {
|
||||
// Another host (a login gateway, say).
|
||||
assert_eq!(
|
||||
redirect("http://studio.lan/api/status", "https://sso.example.com/login?next=x"),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "https://sso.example.com/login?next=x".into(),
|
||||
suggested: None
|
||||
}
|
||||
);
|
||||
// Same host, but no longer the status API.
|
||||
assert_eq!(
|
||||
redirect("http://studio.lan/api/status", "/login"),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "http://studio.lan/login".into(),
|
||||
suggested: None
|
||||
}
|
||||
);
|
||||
// A downgrade to plain http.
|
||||
assert_eq!(
|
||||
redirect("https://studio.lan/api/status", "http://studio.lan/api/status"),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "http://studio.lan/api/status".into(),
|
||||
suggested: None
|
||||
}
|
||||
);
|
||||
// Same scheme and port, only the path moved.
|
||||
assert_eq!(
|
||||
redirect("http://studio.lan/api/status", "/x/api/status"),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "http://studio.lan/x/api/status".into(),
|
||||
suggested: None
|
||||
}
|
||||
);
|
||||
// Credentials in the target are never suggested.
|
||||
assert_eq!(
|
||||
redirect("http://studio.lan/api/status", "https://u:p@studio.lan/api/status"),
|
||||
ProbeOutcome::Redirect {
|
||||
location: "https://u:p@studio.lan/api/status".into(),
|
||||
suggested: None
|
||||
}
|
||||
);
|
||||
// No Location (304), or one that does not parse: nothing to act on.
|
||||
assert_eq!(
|
||||
classify_response(&status_url(), 304, None, None, false, ""),
|
||||
ProbeOutcome::NotCodeman { status: 304 }
|
||||
);
|
||||
assert_eq!(
|
||||
classify_response(&status_url(), 302, Some("http://[::1"), None, false, ""),
|
||||
ProbeOutcome::NotCodeman { status: 302 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_classes() {
|
||||
assert_eq!(classify_transport(TransportError::Refused), ProbeOutcome::Refused);
|
||||
assert_eq!(classify_transport(TransportError::Timeout), ProbeOutcome::Timeout);
|
||||
assert_eq!(classify_transport(TransportError::Dns), ProbeOutcome::Unresolvable);
|
||||
assert_eq!(
|
||||
classify_transport(TransportError::Tls("bad cert".into())),
|
||||
ProbeOutcome::TlsUntrusted {
|
||||
detail: "bad cert".into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// The io errors exactly as ureq hands them over (`Error::Io`).
|
||||
#[test]
|
||||
fn io_errors_are_told_apart() {
|
||||
use io::ErrorKind;
|
||||
// rustls' certificate rejection from the handshake.
|
||||
let cert = "invalid peer certificate: UnknownIssuer";
|
||||
assert_eq!(
|
||||
io_outcome(ErrorKind::InvalidData, cert, false),
|
||||
ProbeOutcome::TlsUntrusted { detail: cert.into() }
|
||||
);
|
||||
// Any other InvalidData (a port that does not speak TLS, say) is not a certificate problem.
|
||||
assert_eq!(
|
||||
io_outcome(
|
||||
ErrorKind::InvalidData,
|
||||
"received corrupt message of type InvalidContentType",
|
||||
false
|
||||
),
|
||||
ProbeOutcome::Failed {
|
||||
detail: "received corrupt message of type InvalidContentType".into()
|
||||
}
|
||||
);
|
||||
// std's getaddrinfo failure (its real kind, Uncategorized, cannot be built on stable).
|
||||
assert_eq!(
|
||||
io_outcome(
|
||||
ErrorKind::Other,
|
||||
"failed to lookup address information: nodename nor servname provided, or not known",
|
||||
true
|
||||
),
|
||||
ProbeOutcome::Unresolvable
|
||||
);
|
||||
// The same text from the OS (an errno) is not a lookup failure.
|
||||
let os = ureq::Error::Io(io::Error::from_raw_os_error(1));
|
||||
assert!(!matches!(
|
||||
classify_transport(transport_error(&os, true)),
|
||||
ProbeOutcome::Unresolvable
|
||||
));
|
||||
// ureq's "Peer disconnected": over http a hint at https, over https just a failure.
|
||||
assert_eq!(
|
||||
io_outcome(ErrorKind::UnexpectedEof, "Peer disconnected", true),
|
||||
ProbeOutcome::MaybeHttps
|
||||
);
|
||||
assert_eq!(
|
||||
io_outcome(ErrorKind::UnexpectedEof, "Peer disconnected", false),
|
||||
ProbeOutcome::Failed {
|
||||
detail: "Peer disconnected".into()
|
||||
}
|
||||
);
|
||||
// No route: Local Network privacy, or a machine that is off.
|
||||
assert_eq!(
|
||||
io_outcome(ErrorKind::HostUnreachable, "No route to host", true),
|
||||
ProbeOutcome::Unreachable
|
||||
);
|
||||
assert_eq!(
|
||||
io_outcome(ErrorKind::NetworkUnreachable, "Network is unreachable", false),
|
||||
ProbeOutcome::Unreachable
|
||||
);
|
||||
assert_eq!(
|
||||
io_outcome(ErrorKind::ConnectionRefused, "Connection refused", true),
|
||||
ProbeOutcome::Refused
|
||||
);
|
||||
assert_eq!(
|
||||
classify_transport(transport_error(&ureq::Error::HostNotFound, true)),
|
||||
ProbeOutcome::Unresolvable
|
||||
);
|
||||
// A ureq TLS setup message is not an untrusted certificate.
|
||||
assert_eq!(
|
||||
classify_transport(transport_error(
|
||||
&ureq::Error::Tls("Rustls invalid dns name error"),
|
||||
false
|
||||
)),
|
||||
ProbeOutcome::Failed {
|
||||
detail: "Rustls invalid dns name error".into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outcome_serializes_for_the_page() {
|
||||
let json = |o: ProbeOutcome| serde_json::to_value(o).unwrap();
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::NotCodeman { status: 404 }),
|
||||
serde_json::json!({"kind":"notCodeman","status":404})
|
||||
);
|
||||
assert_eq!(json(ProbeOutcome::NeedsLogin), serde_json::json!({"kind":"needsLogin"}));
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::RateLimited {
|
||||
sent_credentials: true,
|
||||
retry_after_secs: None
|
||||
}),
|
||||
serde_json::json!({"kind":"rateLimited","sentCredentials":true})
|
||||
);
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::RateLimited {
|
||||
sent_credentials: false,
|
||||
retry_after_secs: Some(60)
|
||||
}),
|
||||
serde_json::json!({"kind":"rateLimited","sentCredentials":false,"retryAfterSecs":60})
|
||||
);
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::PasswordChangeRequired),
|
||||
serde_json::json!({"kind":"passwordChangeRequired"})
|
||||
);
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::Redirect {
|
||||
location: "https://studio.lan/api/status".into(),
|
||||
suggested: Some("https://studio.lan/".into())
|
||||
}),
|
||||
serde_json::json!({"kind":"redirect","location":"https://studio.lan/api/status","suggested":"https://studio.lan/"})
|
||||
);
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::Redirect {
|
||||
location: "https://sso.example.com/".into(),
|
||||
suggested: None
|
||||
}),
|
||||
serde_json::json!({"kind":"redirect","location":"https://sso.example.com/","suggested":null})
|
||||
);
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::Unreachable),
|
||||
serde_json::json!({"kind":"unreachable"})
|
||||
);
|
||||
assert_eq!(json(ProbeOutcome::MaybeHttps), serde_json::json!({"kind":"maybeHttps"}));
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::TlsUntrusted { detail: "x".into() }),
|
||||
serde_json::json!({"kind":"tlsUntrusted","detail":"x"})
|
||||
);
|
||||
assert_eq!(
|
||||
json(ProbeOutcome::Unresolvable),
|
||||
serde_json::json!({"kind":"unresolvable"})
|
||||
);
|
||||
}
|
||||
|
||||
/// Against real sockets: a closed port is `Refused`, a listener that
|
||||
/// speaks HTTP but not Codeman is `NotCodeman`, a fake Codeman is `Ok`,
|
||||
/// a 401 is `NeedsLogin`, a redirect is reported without being followed,
|
||||
/// and a listener that hangs up without answering is `MaybeHttps`.
|
||||
#[test]
|
||||
fn probe_against_local_sockets() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
let closed = {
|
||||
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
l.local_addr().unwrap().port()
|
||||
};
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{closed}/")).unwrap();
|
||||
assert_eq!(probe(&url, None), ProbeOutcome::Refused);
|
||||
|
||||
/// Accept one connection, read the request and send `response`
|
||||
/// (nothing, then close, for an empty one).
|
||||
fn serve_raw(response: String) -> u16 {
|
||||
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = l.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
if let Ok((mut s, _)) = l.accept() {
|
||||
// Read the whole request head (a GET has no body) so that
|
||||
// closing sends a FIN, not a reset for unread bytes.
|
||||
let mut head = Vec::new();
|
||||
let mut buf = [0u8; 4096];
|
||||
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
match s.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => head.extend_from_slice(&buf[..n]),
|
||||
}
|
||||
}
|
||||
let _ = s.write_all(response.as_bytes());
|
||||
}
|
||||
});
|
||||
port
|
||||
}
|
||||
fn serve_once(status_line: &str, extra_headers: &str, body: &str) -> u16 {
|
||||
serve_raw(format!(
|
||||
"HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n{extra_headers}Connection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
))
|
||||
}
|
||||
|
||||
let p = serve_once("200 OK", "", r#"{"success":true,"data":{"version":"9.9.9"}}"#);
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{p}/")).unwrap();
|
||||
assert_eq!(
|
||||
probe(&url, None),
|
||||
ProbeOutcome::Ok {
|
||||
version: "9.9.9".into()
|
||||
}
|
||||
);
|
||||
|
||||
let p = serve_once("404 Not Found", "", "nope");
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{p}/")).unwrap();
|
||||
assert_eq!(probe(&url, None), ProbeOutcome::NotCodeman { status: 404 });
|
||||
|
||||
let p = serve_once("401 Unauthorized", "", "Unauthorized");
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{p}/")).unwrap();
|
||||
assert_eq!(probe(&url, None), ProbeOutcome::NeedsLogin);
|
||||
|
||||
let p = serve_once("429 Too Many Requests", "Retry-After: 30\r\n", "Too Many Requests");
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{p}/")).unwrap();
|
||||
assert_eq!(
|
||||
probe(&url, Some("Basic YWRtaW46eA==")),
|
||||
ProbeOutcome::RateLimited {
|
||||
sent_credentials: true,
|
||||
retry_after_secs: Some(30)
|
||||
}
|
||||
);
|
||||
|
||||
// Nothing listens on the redirect target: had it been followed, the
|
||||
// answer would be Refused instead.
|
||||
let p = serve_once(
|
||||
"301 Moved Permanently",
|
||||
&format!("Location: https://127.0.0.1:{closed}/api/status\r\n"),
|
||||
"",
|
||||
);
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{p}/")).unwrap();
|
||||
assert_eq!(
|
||||
probe(&url, None),
|
||||
ProbeOutcome::Redirect {
|
||||
location: format!("https://127.0.0.1:{closed}/api/status"),
|
||||
suggested: Some(format!("https://127.0.0.1:{closed}/"))
|
||||
}
|
||||
);
|
||||
|
||||
let p = serve_raw(String::new());
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{p}/")).unwrap();
|
||||
assert_eq!(probe(&url, None), ProbeOutcome::MaybeHttps);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -983,6 +983,14 @@
|
||||
'Could not open a new window for this session': '无法在新窗口中打开此会话',
|
||||
'Could not open a new window for this preview': '无法在新窗口中打开此预览',
|
||||
'Could not open a new window for this dashboard': '无法在新窗口中打开此网页标签',
|
||||
// The Codeman desktop app's shim when the app would not open the window a
|
||||
// page asked for (packages/desktop/src/assets.rs).
|
||||
'Could not open a new window': '无法打开新窗口',
|
||||
// A subagent transcript or a detached preview whose window.open came back
|
||||
// null (panels-ui.js viewSubagentTranscript / detachFilePreview).
|
||||
'Could not open the transcript window: pop-up windows are blocked here': '无法打开对话记录窗口:此处已阻止弹出窗口',
|
||||
'Pop-up blocked: allow pop-ups for this site to detach previews':
|
||||
'弹出窗口已被阻止:请允许此网站的弹出窗口以分离预览',
|
||||
// Dictation whose session closed before the text was sent (voice-input.js).
|
||||
'That session has closed; dictation not sent': '该会话已关闭,语音输入未发送',
|
||||
// Terminal touch-selection bar (long-press to select). The bar is a sibling of
|
||||
@@ -1457,6 +1465,10 @@
|
||||
[/^Worktree (\S+) was kept: ([\s\S]+)$/, (_m, wt, why) => `工作树 ${wt} 已保留:${why}`],
|
||||
// A pick, drop or paste that mixed admitted files with refused ones (image-input.js).
|
||||
[/^(\d+) files? skipped: unsupported type$/, (_m, n) => `已跳过 ${n} 个不支持类型的文件`],
|
||||
// The Codeman desktop app's download toasts (packages/desktop/src/assets.rs).
|
||||
// The file name is user text: it passes through untranslated.
|
||||
[/^Downloaded (.+) to Downloads$/, (_m, name) => `已将 ${name} 下载到“下载”文件夹`],
|
||||
[/^Download of (.+) failed$/, (_m, name) => `下载 ${name} 失败`],
|
||||
// Group names are user text: they pass through untranslated.
|
||||
[/^Move to "(.+)"$/, (_m, group) => `移到“${group}”`],
|
||||
// Session names are user text too.
|
||||
|
||||
@@ -1963,7 +1963,16 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Show in a modal or new window
|
||||
const content = data.data.formatted.join('\n');
|
||||
const win = window.open('', '_blank', 'width=800,height=600');
|
||||
// This open runs after the fetch above, so a pop-up blocker that wants a
|
||||
// click can refuse it, and the Codeman desktop app always refuses an
|
||||
// empty window. Both return null; say so instead of throwing into the
|
||||
// catch below, whose 'Failed to load transcript' would be wrong.
|
||||
let win = null;
|
||||
try { win = window.open('', '_blank', 'width=800,height=600'); } catch {}
|
||||
if (!win) {
|
||||
this.showToast('Could not open the transcript window: pop-up windows are blocked here', 'error');
|
||||
return;
|
||||
}
|
||||
win.document.write(`
|
||||
<html>
|
||||
<head>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* @fileoverview zh-CN coverage for the toasts shown when a window could not be
|
||||
* opened, and for the Codeman desktop app's own toasts.
|
||||
*
|
||||
* The literals are read from their sources: the transcript and detached
|
||||
* preview toasts from panels-ui.js, and the desktop shim's toasts from
|
||||
* packages/desktop/src/assets.rs (a Rust file whose strings reach Codeman's
|
||||
* `showToast`), so a reworded toast on either side without an entry fails
|
||||
* here. The download toasts carry a file name and go through the pattern
|
||||
* rule, which must keep the name exactly as written.
|
||||
*
|
||||
* Port: N/A.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { afterAll, describe, expect, it } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const read = (f: string) => readFileSync(resolve(PUBLIC, f), 'utf8');
|
||||
const I18N = read('i18n.js');
|
||||
const PANELS_UI = read('panels-ui.js');
|
||||
const ASSETS_RS = readFileSync(resolve(import.meta.dirname, '../packages/desktop/src/assets.rs'), 'utf8');
|
||||
|
||||
type Api = { t(s: string): string; configure(o: Record<string, string>): void };
|
||||
function translator(language: string) {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
|
||||
runScripts: 'outside-only',
|
||||
url: 'http://localhost/',
|
||||
});
|
||||
vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' });
|
||||
const api = (dom.window as unknown as { CodemanI18n: Api }).CodemanI18n;
|
||||
api.configure({ language });
|
||||
return { api, dom };
|
||||
}
|
||||
const zh = translator('zh-CN');
|
||||
const en = translator('en');
|
||||
afterAll(() => {
|
||||
zh.dom.window.close();
|
||||
en.dom.window.close();
|
||||
});
|
||||
|
||||
const panelToasts = [
|
||||
...PANELS_UI.matchAll(/this\.showToast\('(Could not open the transcript window[^']*|Pop-up blocked[^']*)'/g),
|
||||
].map((m) => m[1]);
|
||||
// The shim's JavaScript may quote a literal either way.
|
||||
const shimToasts = [...ASSETS_RS.matchAll(/showToast\((['"])([^'"]+)\1/g)].map((m) => m[2]);
|
||||
const downloadTemplates = [...ASSETS_RS.matchAll(/format!\("([^"]*\{file_name\}[^"]*)"\)/g)].map((m) => m[1]);
|
||||
|
||||
// File names with spaces, dots, brackets and English words, one of them a
|
||||
// dictionary word on its own ("Settings saved"), which must not be translated.
|
||||
const FILE_NAMES = ['report v2.pdf', 'Settings saved', 'a (1).tar.gz', '数据.csv'];
|
||||
|
||||
describe('the window and desktop toasts in zh-CN', () => {
|
||||
it('finds the strings it checks (the check is not vacuous)', () => {
|
||||
expect(new Set(panelToasts)).toEqual(
|
||||
new Set([
|
||||
'Could not open the transcript window: pop-up windows are blocked here',
|
||||
'Pop-up blocked: allow pop-ups for this site to detach previews',
|
||||
])
|
||||
);
|
||||
expect(new Set(shimToasts)).toEqual(new Set(['Could not open a new window']));
|
||||
expect(new Set(downloadTemplates)).toEqual(
|
||||
new Set(['Downloaded {file_name} to Downloads', 'Download of {file_name} failed'])
|
||||
);
|
||||
});
|
||||
|
||||
it('every literal toast translates, and reads the same in English', () => {
|
||||
const bad = [...panelToasts, ...shimToasts].filter((l) => {
|
||||
const text = zh.api.t(l);
|
||||
return text === l || /[A-Za-z]/.test(text) || en.api.t(l) !== l;
|
||||
});
|
||||
expect(bad).toEqual([]);
|
||||
});
|
||||
|
||||
it('the download toasts translate around the file name, which stays as written', () => {
|
||||
for (const template of downloadTemplates) {
|
||||
for (const name of FILE_NAMES) {
|
||||
const source = template.replace('{file_name}', name);
|
||||
const text = zh.api.t(source);
|
||||
expect(text, source).not.toBe(source);
|
||||
expect(text.split(name), source).toHaveLength(2);
|
||||
expect(text.replace(name, ''), source).not.toMatch(/[A-Za-z]/);
|
||||
expect(en.api.t(source)).toBe(source);
|
||||
}
|
||||
}
|
||||
expect(zh.api.t('Downloaded report v2.pdf to Downloads')).toBe('已将 report v2.pdf 下载到“下载”文件夹');
|
||||
expect(zh.api.t('Download of report v2.pdf failed')).toBe('下载 report v2.pdf 失败');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user