mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-17 11:49:33 +01:00
merge feat/desktop-app (the PR #763 review fixes) into the graphical installer branch
Both branches changed the connect page and three Rust files. How the conflicts were settled: - Layout (connect.html): both sides fixed the page being cut off above a small window. One layout is kept, the one that also holds the header still: a fixed top margin on `main`. The wizard's own top margin is dropped, since the page is anchored from the top in every state now and a second margin would move the header when the wizard opens. `#elsewhere` is a child of the card since the status line moved above it, so the wizard hides it too. - State (connect.html): `gui` from the installer next to `askedFrom`, `reopen` and the starting-server counters from the review. - setup.rs: `running_install` for the port, `install_in_app` for the flag. - local_server.rs: `login_environment` and `in_home` both stay. - README: the installer's This Mac row with the sentence about a starting server; both new paragraphs. test/desktop-connect-page.browser.test.ts reaches the Terminal install the way the page now offers it (Install, a failed preparation, "Install in Terminal instead"), since Install opens the graphical install here. Checked on the merged tree: 138 Rust unit tests, clippy and fmt on the Mac mini; test/desktop-connect-install.test.ts (jsdom) and test/desktop-connect-page.browser.test.ts (Chromium) both pass. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
commit
c04955ca68
13 files changed
+2910
-217
No files matched your search
@@ -282,6 +282,28 @@ mod tests {
|
||||
assert!(!HOST_SHIM.contains("decodeURIComponent"));
|
||||
}
|
||||
|
||||
/// The connect page refuses what the app would drop without an answer, so
|
||||
/// its two limits have to be the app's own.
|
||||
#[test]
|
||||
fn connect_page_keeps_the_message_limits() {
|
||||
let page = String::from_utf8_lossy(CONNECT_HTML);
|
||||
for needle in [
|
||||
format!("var MAX_URL = {};", crate::policy::MAX_URL_LEN),
|
||||
format!("var MAX_FIELD = {};", crate::policy::MAX_FIELD_LEN),
|
||||
] {
|
||||
assert!(page.contains(&needle), "{needle}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy puts setup::INSTALL_ONE_LINER on the clipboard, and the page shows
|
||||
/// the command as text of its own: the two have to be the same command.
|
||||
#[test]
|
||||
fn connect_page_shows_the_command_that_copy_copies() {
|
||||
let page = String::from_utf8_lossy(CONNECT_HTML);
|
||||
let shown = format!("<code id=\"oneliner\">{}</code>", crate::setup::INSTALL_ONE_LINER);
|
||||
assert!(page.contains(&shown), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toast_escapes_file_names() {
|
||||
let js = download_toast_script("a\"); alert(1); (\".txt", true);
|
||||
|
||||
@@ -25,10 +25,14 @@ 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.
|
||||
/// bounds, so the menu bar and the Dock are inside them.
|
||||
const FIT_MARGIN_X: f64 = 40.0;
|
||||
const FIT_MARGIN_Y: f64 = 80.0;
|
||||
/// Room a first-run window leaves above its content (the menu bar, taller on
|
||||
/// a display with a notch, and its own title bar) and below it (a Dock of the
|
||||
/// default size): `Rect` is the whole display, so neither is taken off yet.
|
||||
const FIRST_RUN_ROOM_ABOVE: f64 = 66.0;
|
||||
const FIRST_RUN_ROOM_BELOW: f64 = 90.0;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -39,9 +43,17 @@ pub struct Config {
|
||||
pub auto_connect: bool,
|
||||
/// Always open in full screen (otherwise the last state is restored).
|
||||
pub start_fullscreen: bool,
|
||||
/// Anything that is not a whole frame reads as None: a bad frame must not
|
||||
/// make the whole file unreadable, which would cost the server list.
|
||||
#[serde(deserialize_with = "lenient_window")]
|
||||
pub window: Option<WindowFrame>,
|
||||
}
|
||||
|
||||
fn lenient_window<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<WindowFrame>, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(serde_json::from_value(value).ok())
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
@@ -92,6 +104,23 @@ pub struct Rect {
|
||||
}
|
||||
|
||||
impl WindowFrame {
|
||||
/// The frame of a first-run window on `screen`: `size` or what fits, never
|
||||
/// less than `min`, centred across and in the height between the menu bar
|
||||
/// and the Dock. Centring in the whole display put the bottom of a window
|
||||
/// under the Dock on a 900 pt high one.
|
||||
pub fn first_run(screen: &Rect, size: (f64, f64), min: (f64, f64)) -> WindowFrame {
|
||||
let width = size.0.min(screen.width - FIT_MARGIN_X).max(min.0);
|
||||
let room = screen.height - FIRST_RUN_ROOM_ABOVE - FIRST_RUN_ROOM_BELOW;
|
||||
let height = size.1.min(room).max(min.1);
|
||||
WindowFrame {
|
||||
x: screen.x + (screen.width - width) / 2.0,
|
||||
y: screen.y + FIRST_RUN_ROOM_ABOVE + ((room - height) / 2.0).max(0.0),
|
||||
width,
|
||||
height,
|
||||
fullscreen: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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];
|
||||
@@ -626,6 +655,77 @@ mod tests {
|
||||
assert_eq!(c.servers[0].username, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_window_frame_keeps_the_servers() {
|
||||
for (name, window) in [
|
||||
("missing-height", r#"{"x":1,"y":2,"width":3}"#),
|
||||
("not-a-frame", r#""maximized""#),
|
||||
("null-number", r#"{"x":null,"y":2,"width":3,"height":4}"#),
|
||||
] {
|
||||
let dir = tmp_dir(&format!("bad-window-{name}"));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("desktop.json");
|
||||
fs::write(
|
||||
&path,
|
||||
format!(r#"{{"servers":[{{"url":"http://a/"}}],"autoConnect":false,"window":{window}}}"#),
|
||||
)
|
||||
.unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert!(can_save, "{name}");
|
||||
assert_eq!(c.servers.len(), 1, "{name}");
|
||||
assert!(!c.auto_connect, "{name}");
|
||||
assert_eq!(c.window, None, "{name}");
|
||||
// The file was read, so it stays where it is.
|
||||
assert!(path.is_file(), "{name}");
|
||||
assert!(!path.with_extension("json.corrupt").exists(), "{name}");
|
||||
}
|
||||
// A whole frame and an absent one read as before.
|
||||
let c: Config =
|
||||
serde_json::from_str(r#"{"window":{"x":1,"y":2,"width":900,"height":600,"fullscreen":true}}"#).unwrap();
|
||||
assert_eq!(c.window.map(|f| (f.width, f.fullscreen)), Some((900.0, true)));
|
||||
assert_eq!(serde_json::from_str::<Config>("{}").unwrap().window, None);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Config>(r#"{"window":null}"#).unwrap().window,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_run_window_sits_between_the_menu_bar_and_the_dock() {
|
||||
let screen = |width: f64, height: f64| Rect {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
let size = (1280.0, 820.0);
|
||||
let min = (480.0, 360.0);
|
||||
// A 13 inch MacBook: the window is shortened, and ends above the Dock.
|
||||
let f = WindowFrame::first_run(&screen(1440.0, 900.0), size, min);
|
||||
assert_eq!((f.width, f.height), (1280.0, 744.0));
|
||||
assert_eq!((f.x, f.y), (80.0, 66.0));
|
||||
assert!(f.y + f.height <= 900.0 - 90.0);
|
||||
// A large display: the full size, centred across and in the free height.
|
||||
let f = WindowFrame::first_run(&screen(2560.0, 1440.0), size, min);
|
||||
assert_eq!((f.width, f.height), (1280.0, 820.0));
|
||||
assert_eq!(f.x, 640.0);
|
||||
assert_eq!(f.y - 66.0, 1440.0 - 90.0 - (f.y + f.height));
|
||||
// A second display to the left of the first.
|
||||
let left = Rect {
|
||||
x: -1920.0,
|
||||
y: 120.0,
|
||||
width: 1920.0,
|
||||
height: 1080.0,
|
||||
};
|
||||
let f = WindowFrame::first_run(&left, size, min);
|
||||
assert_eq!(f.x, -1920.0 + 320.0);
|
||||
assert!(f.y >= 120.0 + 66.0 && f.y + f.height <= 120.0 + 1080.0 - 90.0);
|
||||
// Never smaller than the minimum, on a display too small for it too.
|
||||
let f = WindowFrame::first_run(&screen(500.0, 400.0), size, min);
|
||||
assert_eq!((f.width, f.height), min);
|
||||
assert!(!f.fullscreen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_sanitizing_and_reachability() {
|
||||
assert!(frame(f64::NAN, 0.0, 800.0, 600.0).sanitized().is_none());
|
||||
|
||||
@@ -189,9 +189,11 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Keychain on an in-memory store, for these tests and for the tests of the
|
||||
/// code that uses a Keychain (main.rs).
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{start, Backend, Job, Keychain};
|
||||
pub(crate) mod memory {
|
||||
use super::{start, Backend, Keychain};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
@@ -200,7 +202,7 @@ mod tests {
|
||||
/// 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 {
|
||||
pub(crate) struct Memory {
|
||||
items: Arc<Mutex<HashMap<String, String>>>,
|
||||
log: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
@@ -209,7 +211,8 @@ mod tests {
|
||||
fn note(&self, entry: String) {
|
||||
self.log.lock().unwrap().push(entry);
|
||||
}
|
||||
fn log(&self) -> Vec<String> {
|
||||
/// The jobs the store ran, in order.
|
||||
pub(crate) fn log(&self) -> Vec<String> {
|
||||
self.log.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
@@ -234,6 +237,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A worker on a fresh store, and the store to look into.
|
||||
pub(crate) 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)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::memory::{keychain, Memory};
|
||||
use super::{start, Backend, Job, Keychain};
|
||||
|
||||
/// A store whose load fails the way a crashed worker would.
|
||||
struct Crashes;
|
||||
|
||||
@@ -247,13 +264,6 @@ mod tests {
|
||||
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!(
|
||||
|
||||
@@ -107,6 +107,10 @@ impl From<Output> for Run {
|
||||
fn from(out: Output) -> Self {
|
||||
let mut output = out.stdout;
|
||||
if !out.stderr.trim().is_empty() {
|
||||
// On a line of its own, also when stdout ended without a newline.
|
||||
if !output.is_empty() && !output.ends_with('\n') {
|
||||
output.push('\n');
|
||||
}
|
||||
output.push_str(&out.stderr);
|
||||
}
|
||||
Run {
|
||||
@@ -161,10 +165,16 @@ pub fn exec_bounded(mut cmd: Command, deadline: Instant, timed_out: &str) -> Res
|
||||
pump(child.stdout.take(), 0, tx.clone());
|
||||
pump(child.stderr.take(), 1, tx);
|
||||
|
||||
// A login shell usually answers within tens of milliseconds: look often
|
||||
// at first, then back off.
|
||||
let mut nap = Duration::from_millis(5);
|
||||
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) if Instant::now() < deadline => {
|
||||
std::thread::sleep(nap);
|
||||
nap = (nap * 2).min(Duration::from_millis(100));
|
||||
}
|
||||
Ok(None) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
@@ -286,6 +296,16 @@ pub fn login_environment() -> Option<Vec<(String, String)>> {
|
||||
capture_env(&shell, flags, Instant::now() + FIND_TIMEOUT).ok()?.ok()
|
||||
}
|
||||
|
||||
/// Run `cmd` in the home folder, where a terminal and the LaunchAgent start
|
||||
/// Codeman too. The server keeps the directory it was started in and uses it
|
||||
/// as the default for a session that names none; an app opened from the Finder
|
||||
/// or the Dock runs in `/`.
|
||||
fn in_home(cmd: &mut Command) {
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
cmd.current_dir(home);
|
||||
}
|
||||
}
|
||||
|
||||
/// `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.
|
||||
@@ -293,6 +313,7 @@ fn run_with_env(script: &str, env: &[(String, String)], args: &[String], deadlin
|
||||
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)));
|
||||
in_home(&mut cmd);
|
||||
exec(cmd, deadline).map(Run::from)
|
||||
}
|
||||
|
||||
@@ -310,6 +331,7 @@ fn run_in_shell(
|
||||
cmd.arg("-i");
|
||||
}
|
||||
cmd.arg("-c").arg(script).arg("codeman-desktop").args(args);
|
||||
in_home(&mut cmd);
|
||||
exec(cmd, deadline).map(Run::from)
|
||||
}
|
||||
|
||||
@@ -421,6 +443,26 @@ mod tests {
|
||||
assert_eq!(last_lines("", 3), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stderr_starts_on_a_line_of_its_own() {
|
||||
let said = |stdout: &str, stderr: &str| {
|
||||
Run::from(Output {
|
||||
code: Some(1),
|
||||
stdout: stdout.into(),
|
||||
stderr: stderr.into(),
|
||||
})
|
||||
.output
|
||||
};
|
||||
// stdout that ended without a newline used to be glued to stderr.
|
||||
assert_eq!(
|
||||
said("Starting Codeman", "Error: port 3000 is in use\n"),
|
||||
"Starting Codeman\nError: port 3000 is in use"
|
||||
);
|
||||
assert_eq!(said("Starting\n", "Error\n"), "Starting\nError");
|
||||
assert_eq!(said("", "Error\n"), "Error");
|
||||
assert_eq!(said("Started\n", " \n"), "Started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_non_local_or_https() {
|
||||
assert!(start(&Url::parse("https://127.0.0.1:3000/").unwrap()).is_err());
|
||||
|
||||
@@ -161,14 +161,17 @@ fn origin_label(host: &str, port: i64) -> Option<String> {
|
||||
}
|
||||
|
||||
/// The bold first line of a dialog, like Safari's, so a frame cannot pass its
|
||||
/// text off as the app's own. `embedded` is a sandboxed frame (an HTML file
|
||||
/// preview, an untrusted web tab): its origin is opaque, so `origin` is only
|
||||
/// the server it was loaded from, and it must not read as Codeman speaking.
|
||||
fn dialog_title(origin: &str, embedded: bool) -> String {
|
||||
if embedded {
|
||||
format!("An embedded page on {origin} says:")
|
||||
} else {
|
||||
format!("The page at {origin} says:")
|
||||
/// text off as the app's own: the page's text always goes below it. `frame` is
|
||||
/// the host that names the frame and whether it is embedded, which a sandboxed
|
||||
/// frame is (an HTML file preview, an untrusted web tab): its origin is opaque,
|
||||
/// so the host is only the server it was loaded from, and it must not read as
|
||||
/// Codeman speaking. `None` is a frame nothing names: an opaque origin whose
|
||||
/// document has no host either (`about:srcdoc`, a `data:` or `blob:` URL).
|
||||
fn dialog_title(frame: Option<(&str, bool)>) -> String {
|
||||
match frame {
|
||||
Some((origin, false)) => format!("The page at {origin} says:"),
|
||||
Some((origin, true)) => format!("An embedded page on {origin} says:"),
|
||||
None => "An embedded page says:".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -574,13 +577,11 @@ mod imp {
|
||||
Some(message) => clipped(message),
|
||||
None => NSString::from_str(""),
|
||||
};
|
||||
match frame.and_then(frame_origin) {
|
||||
Some((origin, embedded)) => {
|
||||
alert.setMessageText(&NSString::from_str(&dialog_title(&origin, embedded)));
|
||||
alert.setInformativeText(&body);
|
||||
}
|
||||
None => alert.setMessageText(&body),
|
||||
}
|
||||
// The bold line is always the app's own; the page's text goes below.
|
||||
let named = frame.and_then(frame_origin);
|
||||
let title = dialog_title(named.as_ref().map(|(origin, embedded)| (origin.as_str(), *embedded)));
|
||||
alert.setMessageText(&NSString::from_str(&title));
|
||||
alert.setInformativeText(&body);
|
||||
let _ = alert.addButtonWithTitle(&NSString::from_str("OK"));
|
||||
if panel != Panel::Alert {
|
||||
let _ = alert.addButtonWithTitle(&NSString::from_str("Cancel"));
|
||||
@@ -623,16 +624,18 @@ mod imp {
|
||||
}
|
||||
|
||||
/// The host (and port) of the frame that opened a dialog: its security
|
||||
/// origin, else its request URL's host. The flag is set when the origin is
|
||||
/// opaque (a sandboxed frame), where only the URL names a host.
|
||||
/// origin, else its request URL's host. The flag says "embedded". It is
|
||||
/// set for every sub-frame, whatever its origin (a trusted web tab is
|
||||
/// proxied under Codeman's own origin and would read as Codeman
|
||||
/// otherwise), and whenever the origin names no host, which is an opaque
|
||||
/// origin (a sandboxed frame) or no origin at all: a frame the app is
|
||||
/// unsure about never speaks as the page.
|
||||
fn frame_origin(frame: &WKFrameInfo) -> Option<(String, bool)> {
|
||||
autoreleasepool(|_| {
|
||||
// SAFETY (every read here): property reads on objects WebKit handed
|
||||
// us, with nil handled by the `Option` return types.
|
||||
let sub_frame = !unsafe { frame.isMainFrame() };
|
||||
let origin: Option<Retained<WKSecurityOrigin>> = unsafe { msg_send![frame, securityOrigin] };
|
||||
// An origin without a host is opaque; when unsure, say "embedded"
|
||||
// rather than let a frame speak as the page.
|
||||
let opaque = origin.is_some();
|
||||
if let Some(origin) = origin {
|
||||
let host: Option<Retained<NSString>> = unsafe { msg_send![&*origin, host] };
|
||||
let port: NSInteger = unsafe { msg_send![&*origin, port] };
|
||||
@@ -641,7 +644,7 @@ mod imp {
|
||||
.and_then(rust_string)
|
||||
.and_then(|h| origin_label(&h, port as i64))
|
||||
{
|
||||
return Some((label, false));
|
||||
return Some((label, sub_frame));
|
||||
}
|
||||
}
|
||||
let request: Option<Retained<NSURLRequest>> = unsafe { msg_send![frame, request] };
|
||||
@@ -650,7 +653,7 @@ mod imp {
|
||||
let url = url?;
|
||||
let host: Option<Retained<NSString>> = unsafe { msg_send![&*url, host] };
|
||||
let host = host?;
|
||||
Some((origin_label(&rust_string(&host)?, 0)?, opaque))
|
||||
Some((origin_label(&rust_string(&host)?, 0)?, true))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1042,12 +1045,15 @@ mod tests {
|
||||
assert_eq!(origin_label("::1", 3000).as_deref(), Some("[::1]:3000"));
|
||||
assert_eq!(origin_label(" ", 3000), None);
|
||||
assert_eq!(
|
||||
dialog_title("localhost:3000", false),
|
||||
dialog_title(Some(("localhost:3000", false))),
|
||||
"The page at localhost:3000 says:"
|
||||
);
|
||||
assert_eq!(
|
||||
dialog_title("localhost:3000", true),
|
||||
dialog_title(Some(("localhost:3000", true))),
|
||||
"An embedded page on localhost:3000 says:"
|
||||
);
|
||||
// A frame nothing names (about:srcdoc under an opaque origin) still
|
||||
// gets a first line of the app's own, never its own text in bold.
|
||||
assert_eq!(dialog_title(None), "An embedded page says:");
|
||||
}
|
||||
}
|
||||
+331
-56
@@ -53,7 +53,7 @@ use wry::{NewWindowResponse, PageLoadEvent, PermissionResponse, WebView, WebView
|
||||
|
||||
use config::{Config, Rect, WindowFrame};
|
||||
use credentials::Keychain;
|
||||
use policy::{ConnectCmd, HostCmd, Ipc, Navigation, NewWindow, OpenBudget, Phase, Via};
|
||||
use policy::{ConnectCmd, HostCmd, Ipc, Navigation, NewWindow, OpenBudget, Phase, Recovery, Via};
|
||||
use probe::ProbeOutcome;
|
||||
|
||||
const APP_NAME: &str = "Codeman";
|
||||
@@ -62,6 +62,9 @@ const DEFAULT_SIZE: (f64, f64) = (1280.0, 820.0);
|
||||
const POPOUT_SIZE: (f64, f64) = (960.0, 680.0);
|
||||
const MIN_SIZE: (f64, f64) = (480.0, 360.0);
|
||||
const MAX_POPOUTS: usize = 24;
|
||||
/// How far a pop-out opens down and to the right of the window in use, per
|
||||
/// pop-out already open (it starts over after eight).
|
||||
const POPOUT_STEP: f64 = 28.0;
|
||||
const SAVE_DEBOUNCE: Duration = Duration::from_secs(1);
|
||||
/// How long a server load may take to commit before the app gives up on it
|
||||
/// and brings the connect page back.
|
||||
@@ -70,6 +73,10 @@ const LOAD_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
/// page reported that its session is gone, so a login the server keeps
|
||||
/// refusing can never turn into a reload loop.
|
||||
const SESSION_RELOAD_COOLDOWN: Duration = Duration::from_secs(60);
|
||||
/// A window loads its page again at most once in this long after its web
|
||||
/// content process ended, so a page that cannot stay up never becomes a reload
|
||||
/// loop.
|
||||
const CRASH_RELOAD_COOLDOWN: Duration = Duration::from_secs(30);
|
||||
/// When the app first looks whether the main window made it into the full
|
||||
/// screen it asked for at launch, how often it asks again, and how many times.
|
||||
/// tao retries a failed entry only for a window BUILT in full screen, which
|
||||
@@ -90,6 +97,7 @@ const AUTH_REJECTED: &str = "The server did not accept the saved login. Enter th
|
||||
const AUTH_RATE_LIMITED: &str = "Too many failed logins from this address. The saved password may be wrong: \
|
||||
enter it again (a single-user Codeman accepts the right password at once), or wait up to 15 minutes.";
|
||||
const KEYCHAIN_UNREADABLE: &str = "The saved password could not be read from the Keychain. Enter it again.";
|
||||
const PAGE_KEEPS_STOPPING: &str = "Codeman's page stopped twice in a row, so it was closed. Connect again.";
|
||||
const START_REFUSED: &str = "Codeman can only be started here for an http://127.0.0.1 or http://localhost address.";
|
||||
|
||||
mod menu_id {
|
||||
@@ -159,6 +167,12 @@ enum UserEvent {
|
||||
/// The challenge handler sent its login and got challenged again (macOS).
|
||||
/// Not trusted on its own: recheck_login asks the server first.
|
||||
AuthRejected,
|
||||
/// The web content process of a window ended (macOS): a crash, or the
|
||||
/// system taking it back under memory pressure. The window is blank until
|
||||
/// something loads in it again (on_content_process_gone).
|
||||
ContentProcessGone {
|
||||
window: WindowId,
|
||||
},
|
||||
/// A background step for the connect page finished (This Mac status, an
|
||||
/// install opened in Terminal, the install command copied): the message
|
||||
/// goes to the page if it is still the one choosing a server.
|
||||
@@ -213,6 +227,8 @@ struct AppWindow {
|
||||
committed: Option<Url>,
|
||||
/// When the window last reloaded itself because its session expired.
|
||||
session_reload_at: Option<Instant>,
|
||||
/// When the window's web content process last ended.
|
||||
content_process_gone_at: Option<Instant>,
|
||||
}
|
||||
|
||||
struct AppMenu {
|
||||
@@ -234,7 +250,10 @@ struct App {
|
||||
/// aside, in which case it must not be overwritten.
|
||||
config_path: Option<PathBuf>,
|
||||
config_dirty: bool,
|
||||
last_save: Instant,
|
||||
/// The settings are written SAVE_DEBOUNCE after this: the last write, or
|
||||
/// the last move or resize of the main window, so a drag writes the file
|
||||
/// once when it ends, not once a second while it goes on.
|
||||
save_held_since: Instant,
|
||||
/// Where the main window is in reaching a server. Shared with the web view
|
||||
/// handlers, which run on this same thread.
|
||||
phase: Rc<RefCell<Phase>>,
|
||||
@@ -313,7 +332,7 @@ fn main() {
|
||||
|
||||
let (window, wants_fullscreen) =
|
||||
create_main_window(&event_loop, &config).unwrap_or_else(|e| fatal(&format!("Could not open a window: {e}")));
|
||||
let webview = build_webview(&window, true, Load::ConnectPage { manual: false }, &proxy, &phase)
|
||||
let webview = build_webview(&window, true, true, Load::ConnectPage { manual: false }, &proxy, &phase)
|
||||
.unwrap_or_else(|e| fatal(&format!("Could not create the web view: {e}")));
|
||||
#[cfg(target_os = "macos")]
|
||||
macos::install(&webview);
|
||||
@@ -328,6 +347,7 @@ fn main() {
|
||||
kind: Kind::Main,
|
||||
committed: None,
|
||||
session_reload_at: None,
|
||||
content_process_gone_at: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -336,7 +356,7 @@ fn main() {
|
||||
config,
|
||||
config_path,
|
||||
config_dirty: false,
|
||||
last_save: Instant::now(),
|
||||
save_held_since: Instant::now(),
|
||||
phase,
|
||||
loading_deadline: None,
|
||||
auth: None,
|
||||
@@ -473,21 +493,21 @@ fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A display's whole area in points (the menu bar and the Dock are inside it).
|
||||
fn display_rect(monitor: &tao::monitor::MonitorHandle) -> Rect {
|
||||
let sf = monitor.scale_factor();
|
||||
let p = monitor.position().to_logical::<f64>(sf);
|
||||
let s = monitor.size().to_logical::<f64>(sf);
|
||||
Rect {
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
width: s.width,
|
||||
height: s.height,
|
||||
}
|
||||
}
|
||||
|
||||
fn monitors(target: &EventLoopWindowTarget<UserEvent>) -> Vec<Rect> {
|
||||
target
|
||||
.available_monitors()
|
||||
.map(|m| {
|
||||
let sf = m.scale_factor();
|
||||
let p = m.position().to_logical::<f64>(sf);
|
||||
let s = m.size().to_logical::<f64>(sf);
|
||||
Rect {
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
width: s.width,
|
||||
height: s.height,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
target.available_monitors().map(|m| display_rect(&m)).collect()
|
||||
}
|
||||
|
||||
/// The main window, and whether it was asked into full screen (App's
|
||||
@@ -510,17 +530,10 @@ fn create_main_window(
|
||||
None => {
|
||||
builder = builder.with_inner_size(LogicalSize::new(DEFAULT_SIZE.0, DEFAULT_SIZE.1));
|
||||
if let Some(m) = target.primary_monitor() {
|
||||
let sf = m.scale_factor();
|
||||
let p = m.position().to_logical::<f64>(sf);
|
||||
let s = m.size().to_logical::<f64>(sf);
|
||||
let w = DEFAULT_SIZE.0.min(s.width - 40.0);
|
||||
let h = DEFAULT_SIZE.1.min(s.height - 80.0);
|
||||
let f = WindowFrame::first_run(&display_rect(&m), DEFAULT_SIZE, MIN_SIZE);
|
||||
builder = builder
|
||||
.with_inner_size(LogicalSize::new(w.max(MIN_SIZE.0), h.max(MIN_SIZE.1)))
|
||||
.with_position(LogicalPosition::new(
|
||||
p.x + (s.width - w) / 2.0,
|
||||
p.y + (s.height - h) / 2.0,
|
||||
));
|
||||
.with_inner_size(LogicalSize::new(f.width, f.height))
|
||||
.with_position(LogicalPosition::new(f.x, f.y));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -601,9 +614,13 @@ fn loaded_on_commit(phase: &Phase, committed: &str) -> Option<Phase> {
|
||||
policy::same_origin(&url, server).then(|| Phase::Loaded(server.clone()))
|
||||
}
|
||||
|
||||
/// `focused`: the web view takes the keyboard and brings the app to the front
|
||||
/// (wry's default). False for a window a script opened: it comes up without
|
||||
/// pulling the user out of the app they are typing in.
|
||||
fn build_webview(
|
||||
window: &Window,
|
||||
is_main: bool,
|
||||
focused: bool,
|
||||
load: Load<'_>,
|
||||
proxy: &EventLoopProxy<UserEvent>,
|
||||
phase: &Rc<RefCell<Phase>>,
|
||||
@@ -612,6 +629,7 @@ fn build_webview(
|
||||
let mut builder = WebViewBuilder::new()
|
||||
.with_initialization_script(assets::HOST_SHIM)
|
||||
.with_devtools(true)
|
||||
.with_focused(focused)
|
||||
.with_accept_first_mouse(true)
|
||||
.with_back_forward_navigation_gestures(false)
|
||||
// false = let WebKit take the drop, so Codeman's own HTML5 drop
|
||||
@@ -719,6 +737,17 @@ fn build_webview(
|
||||
});
|
||||
});
|
||||
|
||||
// wry answers WebKit's "web content process ended" notice itself, which
|
||||
// turns WebKit's own reload off: without a handler the window stays blank.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use wry::WebViewBuilderExtDarwin;
|
||||
let gone_proxy = proxy.clone();
|
||||
builder = builder.with_on_web_content_process_terminate_handler(move || {
|
||||
let _ = gone_proxy.send_event(UserEvent::ContentProcessGone { window: id });
|
||||
});
|
||||
}
|
||||
|
||||
builder = match load {
|
||||
Load::ConnectPage { manual: false } => builder.with_url(policy::CONNECT_PAGE),
|
||||
Load::ConnectPage { manual: true } => builder.with_url(format!("{}?manual=1", policy::CONNECT_PAGE)),
|
||||
@@ -767,7 +796,7 @@ impl App {
|
||||
/// so it is only decided here, never reset per event.
|
||||
fn on_events_cleared(&mut self, control_flow: &mut ControlFlow) {
|
||||
let now = Instant::now();
|
||||
if self.config_dirty && now >= self.last_save + SAVE_DEBOUNCE {
|
||||
if self.config_dirty && now >= self.save_held_since + SAVE_DEBOUNCE {
|
||||
self.save_config();
|
||||
}
|
||||
let loading = matches!(*self.phase.borrow(), Phase::Loading(_));
|
||||
@@ -782,7 +811,7 @@ impl App {
|
||||
if matches!(*control_flow, ControlFlow::ExitWithCode(_)) {
|
||||
return;
|
||||
}
|
||||
let save_due = self.config_dirty.then(|| self.last_save + SAVE_DEBOUNCE);
|
||||
let save_due = self.config_dirty.then(|| self.save_held_since + SAVE_DEBOUNCE);
|
||||
let fullscreen_due = self.fullscreen_retry.map(|(due, _)| due);
|
||||
*control_flow = match [save_due, self.loading_deadline, fullscreen_due]
|
||||
.into_iter()
|
||||
@@ -978,6 +1007,45 @@ impl App {
|
||||
}
|
||||
}
|
||||
UserEvent::AuthRejected => self.recheck_login(),
|
||||
UserEvent::ContentProcessGone { window } => self.on_content_process_gone(window),
|
||||
}
|
||||
}
|
||||
|
||||
/// The web content process of `window` ended, so the window is blank
|
||||
/// (policy::recovery decides what it does about it). A second end within
|
||||
/// CRASH_RELOAD_COOLDOWN counts as the same page failing again.
|
||||
fn on_content_process_gone(&mut self, window: WindowId) {
|
||||
let now = Instant::now();
|
||||
let Some(w) = self.windows.get_mut(&window) else {
|
||||
return;
|
||||
};
|
||||
// A pop-out hidden for its download shows no page, and the download
|
||||
// does not run in that process: loading again would fetch it twice.
|
||||
if matches!(
|
||||
w.kind,
|
||||
Kind::Popout {
|
||||
hidden_for_download: true,
|
||||
..
|
||||
}
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let again = w
|
||||
.content_process_gone_at
|
||||
.is_some_and(|at| now.saturating_duration_since(at) < CRASH_RELOAD_COOLDOWN);
|
||||
w.content_process_gone_at = Some(now);
|
||||
let on_server = self.phase.borrow().loaded().is_some();
|
||||
match policy::recovery(window == self.main_id, on_server, again) {
|
||||
Recovery::Reload => {
|
||||
if let Some((url, with_auth)) = self.reload_target(window) {
|
||||
self.load_in(window, &url, with_auth);
|
||||
}
|
||||
}
|
||||
Recovery::ConnectPage { gave_up } => {
|
||||
self.show_connect_page(gave_up.then(|| PAGE_KEEPS_STOPPING.to_string()), false);
|
||||
}
|
||||
Recovery::Close => self.remove_window(window),
|
||||
Recovery::Nothing => eprintln!("codeman-desktop: a page stopped again and was left as it is"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1328,25 +1396,8 @@ impl App {
|
||||
.as_ref()
|
||||
.and_then(|u| keychain.load_blocking(&credentials::account(&key, u))),
|
||||
};
|
||||
let (user, password, source) = match typed_password {
|
||||
Some(p) => (user, Some(p), PasswordSource::Typed),
|
||||
None => match saved {
|
||||
Some(p) => (user, Some(p), PasswordSource::Keychain),
|
||||
// The Codeman on this Mac keeps its login where Codeman's
|
||||
// own clients find it (setup::local_login: its launchd
|
||||
// job, then ~/.codeman/.env), and only answers it at its
|
||||
// own loopback address. Used when nothing was typed and
|
||||
// the Keychain has nothing for this server, for the same
|
||||
// username only, and never saved anywhere.
|
||||
None if !expect_saved => match setup::local_login(&url) {
|
||||
Some((u, p)) if user.as_deref().is_none_or(|current| current == u) => {
|
||||
(Some(u), Some(p), PasswordSource::LocalServer)
|
||||
}
|
||||
_ => (user, None, PasswordSource::Absent),
|
||||
},
|
||||
None => (user, None, PasswordSource::Absent),
|
||||
},
|
||||
};
|
||||
let (user, password, source) =
|
||||
choose_login(user, typed_password, saved, expect_saved, || setup::local_login(&url));
|
||||
// Codeman's default username when only a password was given.
|
||||
let username = password
|
||||
.as_ref()
|
||||
@@ -1633,14 +1684,33 @@ impl App {
|
||||
}
|
||||
let opened_url = policy::webkit_safe_url(url);
|
||||
let auth = self.auth.clone().filter(|_| policy::within_base(url, &server));
|
||||
let window = match WindowBuilder::new()
|
||||
// tao centres a window that is given no position, so every pop-out
|
||||
// would open exactly on top of the one before. Each one steps off the
|
||||
// window in use instead.
|
||||
let position = self
|
||||
.focused_window_id()
|
||||
.or(Some(self.main_id))
|
||||
.and_then(|id| self.windows.get(&id))
|
||||
.and_then(|w| {
|
||||
// The corner tao's with_position places (see record_main_frame).
|
||||
#[cfg(target_os = "macos")]
|
||||
let corner = w.window.inner_position();
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let corner = w.window.outer_position();
|
||||
let p = corner.ok()?.to_logical::<f64>(w.window.scale_factor());
|
||||
let step = POPOUT_STEP * (1 + popouts % 8) as f64;
|
||||
Some(LogicalPosition::new(p.x + step, p.y + step))
|
||||
});
|
||||
let mut builder = WindowBuilder::new()
|
||||
.with_title(APP_NAME)
|
||||
.with_theme(Some(Theme::Dark))
|
||||
.with_inner_size(LogicalSize::new(POPOUT_SIZE.0, POPOUT_SIZE.1))
|
||||
.with_min_inner_size(LogicalSize::new(MIN_SIZE.0, MIN_SIZE.1))
|
||||
.with_focused(focused)
|
||||
.build(target)
|
||||
{
|
||||
.with_focused(focused);
|
||||
if let Some(position) = position {
|
||||
builder = builder.with_position(position);
|
||||
}
|
||||
let window = match builder.build(target) {
|
||||
Ok(window) => window,
|
||||
Err(e) => {
|
||||
eprintln!("codeman-desktop: could not open a window: {e}");
|
||||
@@ -1651,8 +1721,15 @@ impl App {
|
||||
url: &opened_url,
|
||||
auth: auth.as_deref(),
|
||||
};
|
||||
let webview = match build_webview(&window, false, load, &self.proxy, &self.phase) {
|
||||
Ok(webview) => webview,
|
||||
let webview = match build_webview(&window, false, focused, load, &self.proxy, &self.phase) {
|
||||
Ok(webview) => {
|
||||
// Still the one that takes the keys once the user comes to
|
||||
// this window: first responder in its own window only.
|
||||
if !focused {
|
||||
let _ = webview.focus();
|
||||
}
|
||||
webview
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("codeman-desktop: could not create a web view: {e}");
|
||||
return false;
|
||||
@@ -1671,6 +1748,7 @@ impl App {
|
||||
},
|
||||
committed: None,
|
||||
session_reload_at: None,
|
||||
content_process_gone_at: None,
|
||||
},
|
||||
);
|
||||
true
|
||||
@@ -1791,11 +1869,12 @@ impl App {
|
||||
if self.config.window != Some(frame) {
|
||||
self.config.window = Some(frame);
|
||||
self.config_dirty = true;
|
||||
self.save_held_since = Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
fn save_config(&mut self) {
|
||||
self.last_save = Instant::now();
|
||||
self.save_held_since = Instant::now();
|
||||
self.config_dirty = false;
|
||||
if let Some(path) = &self.config_path {
|
||||
if let Err(e) = self.config.save_to(path) {
|
||||
@@ -1825,6 +1904,38 @@ impl App {
|
||||
}
|
||||
|
||||
/// A login the probe just tried, and what the user asked for it.
|
||||
/// The login a connect goes out with, and where its password came from. A
|
||||
/// typed password wins, then the one the Keychain holds for this user. Last
|
||||
/// comes the login of the Codeman on this Mac, which keeps it where its own
|
||||
/// clients find it (setup::local_login: its launchd job, then
|
||||
/// ~/.codeman/.env) and only answers it at its own loopback address. That one
|
||||
/// is used only when the config expected no password in the Keychain
|
||||
/// (`expect_saved`: one that should be there and is not is reported, not
|
||||
/// papered over), only for the username in use when there is one, and it is
|
||||
/// never saved anywhere. `local` is asked only then: it runs processes.
|
||||
fn choose_login(
|
||||
user: Option<String>,
|
||||
typed_password: Option<String>,
|
||||
saved: Option<String>,
|
||||
expect_saved: bool,
|
||||
local: impl FnOnce() -> Option<(String, String)>,
|
||||
) -> (Option<String>, Option<String>, PasswordSource) {
|
||||
if let Some(password) = typed_password {
|
||||
return (user, Some(password), PasswordSource::Typed);
|
||||
}
|
||||
if let Some(password) = saved {
|
||||
return (user, Some(password), PasswordSource::Keychain);
|
||||
}
|
||||
if !expect_saved {
|
||||
if let Some((local_user, password)) = local() {
|
||||
if user.as_deref().is_none_or(|current| current == local_user) {
|
||||
return (Some(local_user), Some(password), PasswordSource::LocalServer);
|
||||
}
|
||||
}
|
||||
}
|
||||
(user, None, PasswordSource::Absent)
|
||||
}
|
||||
|
||||
struct ProbedLogin<'a> {
|
||||
/// The server, as the config and the Keychain accounts key it.
|
||||
server: &'a str,
|
||||
@@ -1904,3 +2015,167 @@ fn update_keychain(keychain: &Keychain, outcome: &ProbeOutcome, login: &ProbedLo
|
||||
update.saved = saved;
|
||||
update
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::credentials::memory;
|
||||
|
||||
fn none() -> Option<(String, String)> {
|
||||
panic!("the local login must not be looked up here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_login_a_connect_uses() {
|
||||
let s = |v: &str| Some(v.to_string());
|
||||
let local = || Some(("admin".to_string(), "from-this-mac".to_string()));
|
||||
|
||||
// A typed password wins over everything, and nothing else is asked.
|
||||
assert_eq!(
|
||||
choose_login(s("kay"), s("typed"), s("kept"), true, none),
|
||||
(s("kay"), s("typed"), PasswordSource::Typed)
|
||||
);
|
||||
// Then the Keychain's.
|
||||
assert_eq!(
|
||||
choose_login(s("kay"), None, s("kept"), true, none),
|
||||
(s("kay"), s("kept"), PasswordSource::Keychain)
|
||||
);
|
||||
// The Keychain should hold one and does not: reported as absent, the
|
||||
// local login is not tried in its place.
|
||||
assert_eq!(
|
||||
choose_login(s("kay"), None, None, true, none),
|
||||
(s("kay"), None, PasswordSource::Absent)
|
||||
);
|
||||
// Nothing typed, nothing expected: the Codeman on this Mac's own
|
||||
// login, for no username or the same one.
|
||||
assert_eq!(
|
||||
choose_login(None, None, None, false, local),
|
||||
(s("admin"), s("from-this-mac"), PasswordSource::LocalServer)
|
||||
);
|
||||
assert_eq!(
|
||||
choose_login(s("admin"), None, None, false, local),
|
||||
(s("admin"), s("from-this-mac"), PasswordSource::LocalServer)
|
||||
);
|
||||
// Never for another user: the names are compared exactly.
|
||||
assert_eq!(
|
||||
choose_login(s("kay"), None, None, false, local),
|
||||
(s("kay"), None, PasswordSource::Absent)
|
||||
);
|
||||
assert_eq!(
|
||||
choose_login(s("Admin"), None, None, false, local),
|
||||
(s("Admin"), None, PasswordSource::Absent)
|
||||
);
|
||||
// No local login either.
|
||||
assert_eq!(
|
||||
choose_login(None, None, None, false, || None),
|
||||
(None, None, PasswordSource::Absent)
|
||||
);
|
||||
}
|
||||
|
||||
/// update_keychain for one probe answer; the log is what the Keychain did,
|
||||
/// in order (the last load only waits for the queue to drain).
|
||||
fn keychain_after(outcome: ProbeOutcome, login: ProbedLogin<'_>) -> (KeychainUpdate, Vec<String>) {
|
||||
let (keychain, store) = memory::keychain();
|
||||
let update = update_keychain(&keychain, &outcome, &login);
|
||||
keychain.load_blocking("done");
|
||||
let mut log = store.log();
|
||||
assert_eq!(log.pop().as_deref(), Some("load done"));
|
||||
(update, log)
|
||||
}
|
||||
|
||||
fn login<'a>(
|
||||
previous_user: Option<&'a str>,
|
||||
username: Option<&'a str>,
|
||||
source: PasswordSource,
|
||||
remember: bool,
|
||||
) -> ProbedLogin<'a> {
|
||||
ProbedLogin {
|
||||
server: "http://a/",
|
||||
previous_user,
|
||||
username,
|
||||
password: (source != PasswordSource::Absent).then_some("secret"),
|
||||
source,
|
||||
remember,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_keychain_keeps_after_a_connect() {
|
||||
let ok = || ProbeOutcome::Ok {
|
||||
version: "1.48.0".into(),
|
||||
};
|
||||
let item = |user: &str| credentials::account("http://a/", user);
|
||||
|
||||
// A typed password is saved when Remember is on, deleted when it is off.
|
||||
let (update, log) = keychain_after(ok(), login(Some("kay"), Some("kay"), PasswordSource::Typed, true));
|
||||
assert!(update.saved && update.deleted.is_empty());
|
||||
assert_eq!(log, [format!("save {}", item("kay"))]);
|
||||
let (update, log) = keychain_after(ok(), login(Some("kay"), Some("kay"), PasswordSource::Typed, false));
|
||||
assert!(!update.saved);
|
||||
assert_eq!(update.deleted, ["kay"]);
|
||||
assert_eq!(log, [format!("delete {}", item("kay"))]);
|
||||
|
||||
// One that came from the Keychain is there already: nothing is written.
|
||||
let (update, log) = keychain_after(ok(), login(Some("kay"), Some("kay"), PasswordSource::Keychain, true));
|
||||
assert!(update.saved && log.is_empty());
|
||||
|
||||
// The local Codeman's own login never gets a copy, Remember or not.
|
||||
let (update, log) = keychain_after(ok(), login(None, Some("admin"), PasswordSource::LocalServer, true));
|
||||
assert!(!update.saved && update.deleted.is_empty() && log.is_empty());
|
||||
|
||||
// Another user than before: the old user's item goes FIRST, then the save.
|
||||
let (update, log) = keychain_after(ok(), login(Some("old"), Some("new"), PasswordSource::Typed, true));
|
||||
assert!(update.saved);
|
||||
assert_eq!(update.deleted, ["old"]);
|
||||
assert_eq!(
|
||||
log,
|
||||
[format!("delete {}", item("old")), format!("save {}", item("new"))]
|
||||
);
|
||||
|
||||
// A password the server wants changed is never kept.
|
||||
let (update, log) = keychain_after(
|
||||
ProbeOutcome::PasswordChangeRequired,
|
||||
login(Some("kay"), Some("kay"), PasswordSource::Typed, true),
|
||||
);
|
||||
assert!(!update.saved);
|
||||
assert_eq!(update.deleted, ["kay"]);
|
||||
assert_eq!(log, [format!("delete {}", item("kay"))]);
|
||||
|
||||
// A login the server did not accept changes nothing.
|
||||
for refused in [
|
||||
ProbeOutcome::BadCredentials,
|
||||
ProbeOutcome::NeedsLogin,
|
||||
ProbeOutcome::Refused,
|
||||
ProbeOutcome::Timeout,
|
||||
] {
|
||||
let (update, log) = keychain_after(refused, login(Some("old"), Some("new"), PasswordSource::Typed, true));
|
||||
assert!(!update.saved && update.deleted.is_empty() && log.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_commit_from_the_loading_server_is_the_loaded_page() {
|
||||
let server = Url::parse("https://box.ts.net/codeman/").unwrap();
|
||||
let loading = Phase::Loading(server.clone());
|
||||
assert_eq!(
|
||||
loaded_on_commit(&loading, "https://box.ts.net/codeman/"),
|
||||
Some(Phase::Loaded(server.clone()))
|
||||
);
|
||||
// Any page of that origin counts: the server may redirect within it.
|
||||
assert_eq!(
|
||||
loaded_on_commit(&loading, "https://box.ts.net/codeman/session/abc"),
|
||||
Some(Phase::Loaded(server.clone()))
|
||||
);
|
||||
// Another origin, the connect page, or junk: still loading.
|
||||
assert_eq!(loaded_on_commit(&loading, "https://other.ts.net/codeman/"), None);
|
||||
assert_eq!(loaded_on_commit(&loading, "http://box.ts.net/codeman/"), None);
|
||||
assert_eq!(loaded_on_commit(&loading, policy::CONNECT_PAGE), None);
|
||||
assert_eq!(loaded_on_commit(&loading, "not a url"), None);
|
||||
// Only a load under way can finish.
|
||||
assert_eq!(loaded_on_commit(&Phase::Connect, "https://box.ts.net/codeman/"), None);
|
||||
assert_eq!(
|
||||
loaded_on_commit(&Phase::Loaded(server), "https://box.ts.net/codeman/"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
+134
-15
@@ -19,8 +19,8 @@ pub const APP_SCHEME: &str = "codemanapp";
|
||||
pub const CONNECT_PAGE: &str = "codemanapp://localhost/index.html";
|
||||
|
||||
/// Caps on what a page may hand the native side.
|
||||
const MAX_URL_LEN: usize = 4096;
|
||||
const MAX_FIELD_LEN: usize = 1024;
|
||||
pub const MAX_URL_LEN: usize = 4096;
|
||||
pub const MAX_FIELD_LEN: usize = 1024;
|
||||
|
||||
/// Where the main window is in reaching a server. The gates below take it
|
||||
/// instead of "is a server set", because what may talk to the native side
|
||||
@@ -61,9 +61,14 @@ impl Phase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn what the user typed into a server URL: scheme added when missing
|
||||
/// (`https` for a tailnet `.ts.net` name, `http` otherwise), query and fragment
|
||||
/// dropped, and the path ending in `/` so `api/status` joins below a base path.
|
||||
/// Turn what the user typed into a server URL: scheme added when missing,
|
||||
/// query and fragment dropped, and the path ending in `/` so `api/status`
|
||||
/// joins below a base path. The scheme is `https` for a tailnet `.ts.net`
|
||||
/// name on its own, which is `tailscale serve`, and `http` otherwise. A
|
||||
/// `.ts.net` name with a port is Codeman's own listener, which speaks plain
|
||||
/// http: guessing https there ended in a TLS error with no way forward, while
|
||||
/// the other mistake (http to an https port) gets a button for the https
|
||||
/// address (ProbeOutcome::MaybeHttps).
|
||||
pub fn normalize_server_url(input: &str) -> Result<Url, String> {
|
||||
let s = input.trim();
|
||||
if s.is_empty() {
|
||||
@@ -75,8 +80,8 @@ pub fn normalize_server_url(input: &str) -> Result<Url, String> {
|
||||
let with_scheme = if s.contains("://") {
|
||||
s.to_string()
|
||||
} else {
|
||||
let host = s.split(['/', ':']).next().unwrap_or("");
|
||||
let scheme = if host.to_ascii_lowercase().ends_with(".ts.net") {
|
||||
let (host, rest) = s.split_at(s.find(['/', ':']).unwrap_or(s.len()));
|
||||
let scheme = if host.to_ascii_lowercase().ends_with(".ts.net") && !rest.starts_with(':') {
|
||||
"https"
|
||||
} else {
|
||||
"http"
|
||||
@@ -112,9 +117,15 @@ pub fn same_origin(a: &Url, b: &Url) -> bool {
|
||||
/// Basic `Authorization` header goes only to such URLs, so another app sharing
|
||||
/// the origin (`/grafana/` next to `/codeman/`) never receives the password.
|
||||
/// `server.path()` always ends in `/` (normalize_server_url), so `/codemanx/`
|
||||
/// is not below `/codeman/`.
|
||||
/// is not below `/codeman/`. The part below the base is decoded once, as
|
||||
/// is_popout_target does, and may hold no `.` or `..` segment: the url crate
|
||||
/// resolves a literal `..`, but `..%2Fgrafana/` reaches a proxy that decodes
|
||||
/// before it routes as a way out of the base. A path that does not decode is
|
||||
/// not below it either (fail closed).
|
||||
pub fn within_base(url: &Url, server: &Url) -> bool {
|
||||
same_origin(url, server) && url.path().starts_with(server.path())
|
||||
same_origin(url, server)
|
||||
&& below_base_decoded(url, server)
|
||||
.is_some_and(|rest| !rest.split(['/', '\\']).any(|segment| segment == "." || segment == ".."))
|
||||
}
|
||||
|
||||
/// A server on this machine: `localhost`, `127.0.0.0/8` or `::1`.
|
||||
@@ -186,8 +197,9 @@ pub fn trusted_frame(frame: &Url, server: &Url) -> bool {
|
||||
/// (`session/<id>`), a rendered HTML file (`html-view/...`, served with a
|
||||
/// sandbox CSP), a detached file preview or attachment (`api/sessions/<id>/`
|
||||
/// `file-raw`, `file-preview`, `attachments/<id>/raw|preview`,
|
||||
/// `folders/<id>/files/...`) and a download (`api/download`). A script's
|
||||
/// `window.open` gets only the last two kinds (new_window, Via::Script).
|
||||
/// `folders/<id>/files/...`, and the path picker's `api/filesystem/preview`)
|
||||
/// and a download (`api/download`). A script's `window.open` gets only the
|
||||
/// last two kinds (new_window, Via::Script).
|
||||
///
|
||||
/// Everything else on the origin is refused, a proxied dashboard under
|
||||
/// `webview/` above all. A browser keeps the opener frame's sandbox on a popup;
|
||||
@@ -222,8 +234,8 @@ enum Popout {
|
||||
Session(String),
|
||||
/// `html-view/...`: a rendered HTML file.
|
||||
HtmlView,
|
||||
/// A detached file preview, an attachment, a file in a granted folder, or
|
||||
/// a download (`api/download`).
|
||||
/// A detached file preview, an attachment, a file in a granted folder,
|
||||
/// the path picker's preview, or a download (`api/download`).
|
||||
File,
|
||||
}
|
||||
|
||||
@@ -245,14 +257,14 @@ fn popout_kind(url: &Url, server: &Url) -> Option<Popout> {
|
||||
}
|
||||
match segments.as_slice() {
|
||||
["session", id] if !id.is_empty() => Some(Popout::Session((*id).to_string())),
|
||||
["api", "download"] => Some(Popout::File),
|
||||
["api", "download"] | ["api", "filesystem", "preview"] => Some(Popout::File),
|
||||
["api", "sessions", id, "file-raw" | "file-preview"] if !id.is_empty() => Some(Popout::File),
|
||||
["api", "sessions", id, "attachments", attachment, "raw" | "preview"]
|
||||
if !id.is_empty() && !attachment.is_empty() =>
|
||||
{
|
||||
Some(Popout::File)
|
||||
}
|
||||
["api", "sessions", id, "folders", folder, "files", name, ..]
|
||||
["api", "sessions", id, "folders", folder, "files", name, "raw" | "preview"]
|
||||
if !id.is_empty() && !folder.is_empty() && !name.is_empty() =>
|
||||
{
|
||||
Some(Popout::File)
|
||||
@@ -414,6 +426,38 @@ impl Default for OpenBudget {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a window does once its web content process has ended: a crash, or the
|
||||
/// system taking the process back under memory pressure. The window is blank
|
||||
/// from then on, since nothing reloads it by itself.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Recovery {
|
||||
/// Load the window's page again.
|
||||
Reload,
|
||||
/// Show the connect page: with the reason, when a server page was given up.
|
||||
ConnectPage { gave_up: bool },
|
||||
/// Close the pop-out.
|
||||
Close,
|
||||
/// Leave the window as it is.
|
||||
Nothing,
|
||||
}
|
||||
|
||||
/// How a window recovers from the end of its web content process. `on_server`:
|
||||
/// a server page is the main window's document (pop-outs only exist then).
|
||||
/// `again`: the same window lost its process a moment ago already, so its page
|
||||
/// cannot stay up and loading it once more would only repeat that.
|
||||
pub fn recovery(is_main: bool, on_server: bool, again: bool) -> Recovery {
|
||||
match (is_main, on_server, again) {
|
||||
(_, true, false) => Recovery::Reload,
|
||||
(true, true, true) => Recovery::ConnectPage { gave_up: true },
|
||||
// The connect page itself, or a server load that had not committed.
|
||||
(true, false, false) => Recovery::ConnectPage { gave_up: false },
|
||||
(true, false, true) => Recovery::Nothing,
|
||||
(false, _, true) => Recovery::Close,
|
||||
// A pop-out with no server page behind it is on its way out anyway.
|
||||
(false, false, false) => Recovery::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Navigation {
|
||||
Allow,
|
||||
@@ -794,6 +838,26 @@ mod tests {
|
||||
normalize_server_url("box.tailf80371.ts.net").unwrap().as_str(),
|
||||
"https://box.tailf80371.ts.net/"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_server_url("Box.Tailf80371.TS.NET/codeman").unwrap().as_str(),
|
||||
"https://box.tailf80371.ts.net/codeman/"
|
||||
);
|
||||
// With a port it is Codeman's own listener, not tailscale serve.
|
||||
assert_eq!(
|
||||
normalize_server_url("box.tailf80371.ts.net:3000").unwrap().as_str(),
|
||||
"http://box.tailf80371.ts.net:3000/"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_server_url("box.tailf80371.ts.net:8443/x").unwrap().as_str(),
|
||||
"http://box.tailf80371.ts.net:8443/x/"
|
||||
);
|
||||
// A scheme that was typed is never second-guessed.
|
||||
assert_eq!(
|
||||
normalize_server_url("https://box.tailf80371.ts.net:8443")
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"https://box.tailf80371.ts.net:8443/"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_server_url("https://host/codeman").unwrap().as_str(),
|
||||
"https://host/codeman/"
|
||||
@@ -979,6 +1043,7 @@ mod tests {
|
||||
"http://127.0.0.1:3000/api/sessions/s1/folders/f1/files/a.png/raw",
|
||||
"http://127.0.0.1:3000/api/sessions/s1/folders/f1/files/my%20notes.md/preview",
|
||||
"http://127.0.0.1:3000/api/download?path=x",
|
||||
"http://127.0.0.1:3000/api/filesystem/preview?path=%2Fhome%2Fu%2Fa.md",
|
||||
] {
|
||||
assert_eq!(script(s), NewWindow::AppWindow(u(s)), "{s}");
|
||||
assert_eq!(host(s), NewWindow::AppWindow(u(s)), "{s}");
|
||||
@@ -1154,6 +1219,10 @@ mod tests {
|
||||
"http://127.0.0.1:3000/api/sessions/s1/folders/f1/files/my%20notes.md/preview"
|
||||
));
|
||||
assert!(ok("http://127.0.0.1:3000/api/download?path=x"));
|
||||
// The path picker's preview, which its Open link shows in a window.
|
||||
assert!(ok(
|
||||
"http://127.0.0.1:3000/api/filesystem/preview?path=%2Fhome%2Fu%2Fa.md&sessionId=s1"
|
||||
));
|
||||
// A single decode is how the server's router sees the path.
|
||||
assert!(ok("http://127.0.0.1:3000/%73ession/abc"));
|
||||
|
||||
@@ -1186,7 +1255,18 @@ mod tests {
|
||||
assert!(!ok("http://127.0.0.1:3000/api/sessions//file-raw"));
|
||||
assert!(!ok("http://127.0.0.1:3000/api/sessions/s1/attachments/att1/delete"));
|
||||
assert!(!ok("http://127.0.0.1:3000/api/sessions/s1/folders/f1/files/"));
|
||||
assert!(!ok("http://127.0.0.1:3000/api/sessions/s1/folders/f1/files/a.png"));
|
||||
assert!(!ok(
|
||||
"http://127.0.0.1:3000/api/sessions/s1/folders/f1/files/a.png/thumbnail"
|
||||
));
|
||||
assert!(!ok(
|
||||
"http://127.0.0.1:3000/api/sessions/s1/folders/f1/files/a.png/raw/x"
|
||||
));
|
||||
assert!(!ok("http://127.0.0.1:3000/api/download/x"));
|
||||
// The picker's other routes list and create folders: never a window.
|
||||
assert!(!ok("http://127.0.0.1:3000/api/filesystem/browse?path=%2F"));
|
||||
assert!(!ok("http://127.0.0.1:3000/api/filesystem/mkdir"));
|
||||
assert!(!ok("http://127.0.0.1:3000/api/filesystem/preview/x"));
|
||||
assert!(!ok("http://127.0.0.1:3000/api/status"));
|
||||
// Other origins and userinfo.
|
||||
assert!(!ok("http://127.0.0.1:3001/session/abc"));
|
||||
@@ -1259,6 +1339,27 @@ mod tests {
|
||||
assert!(!within_base(&u("https://host/grafana/"), &srv));
|
||||
assert!(!within_base(&u("https://host/"), &srv));
|
||||
assert!(!within_base(&u("https://host/codeman/../grafana/"), &srv));
|
||||
// The same way out, spelled so that only a decoder sees it.
|
||||
for escape in [
|
||||
"https://host/codeman/..%2Fgrafana/",
|
||||
"https://host/codeman/..%2fgrafana/x",
|
||||
"https://host/codeman/%2e%2e%2Fgrafana/",
|
||||
"https://host/codeman/..%5Cgrafana/",
|
||||
"https://host/codeman/a/%2E%2E%2F%2E%2E%2Fgrafana/",
|
||||
"https://host/codeman/session/a%zz",
|
||||
] {
|
||||
assert!(!within_base(&u(escape), &srv), "{escape}");
|
||||
assert!(!challenge_in_scope(&u(escape), &srv), "{escape}");
|
||||
}
|
||||
// Encoded characters that are part of a name stay inside.
|
||||
for inside in [
|
||||
"https://host/codeman/api/sessions/s1/folders/f1/files/50%25.txt/raw",
|
||||
"https://host/codeman/api/sessions/s1/file-raw?path=..%2Fx",
|
||||
"https://host/codeman/session/a%20b",
|
||||
"https://host/codeman/a..b/c",
|
||||
] {
|
||||
assert!(within_base(&u(inside), &srv), "{inside}");
|
||||
}
|
||||
assert!(!within_base(&u("http://host/codeman/"), &srv));
|
||||
assert!(!within_base(&u("https://other/codeman/"), &srv));
|
||||
let root = u("http://127.0.0.1:3000/");
|
||||
@@ -1323,6 +1424,24 @@ mod tests {
|
||||
assert!(!b.allow(later));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_recovers_from_a_lost_content_process_once() {
|
||||
// The first time, every window that shows a server page loads it again.
|
||||
assert_eq!(recovery(true, true, false), Recovery::Reload);
|
||||
assert_eq!(recovery(false, true, false), Recovery::Reload);
|
||||
// The connect page is shown anew, which also ends a load under way.
|
||||
assert_eq!(recovery(true, false, false), Recovery::ConnectPage { gave_up: false });
|
||||
// A second time in a row never reloads: that would loop.
|
||||
assert_eq!(recovery(true, true, true), Recovery::ConnectPage { gave_up: true });
|
||||
assert_eq!(recovery(false, true, true), Recovery::Close);
|
||||
assert_eq!(recovery(true, false, true), Recovery::Nothing);
|
||||
for is_main in [true, false] {
|
||||
for on_server in [true, false] {
|
||||
assert_ne!(recovery(is_main, on_server, true), Recovery::Reload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_auth() {
|
||||
assert_eq!(basic_auth_header("admin", "secret"), "Basic YWRtaW46c2VjcmV0");
|
||||
|
||||
@@ -228,6 +228,11 @@ fn transport_error(err: &ureq::Error, plain_http: bool) -> TransportError {
|
||||
|
||||
/// Ask the server. Blocking: call it from a worker thread.
|
||||
pub fn probe(server: &Url, authorization: Option<&str>) -> ProbeOutcome {
|
||||
probe_within(server, authorization, TIMEOUT)
|
||||
}
|
||||
|
||||
/// `probe` with the time the whole exchange may take.
|
||||
fn probe_within(server: &Url, authorization: Option<&str>, timeout: Duration) -> ProbeOutcome {
|
||||
let status_url = match server.join(STATUS_PATH) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return ProbeOutcome::Failed { detail: e.to_string() },
|
||||
@@ -236,7 +241,7 @@ pub fn probe(server: &Url, authorization: Option<&str>) -> ProbeOutcome {
|
||||
.root_certs(ureq::tls::RootCerts::PlatformVerifier)
|
||||
.build();
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(TIMEOUT))
|
||||
.timeout_global(Some(timeout))
|
||||
.http_status_as_error(false)
|
||||
// Never follow: a 3xx comes back as an answer and is explained.
|
||||
.max_redirects(0)
|
||||
@@ -259,12 +264,16 @@ pub fn probe(server: &Url, authorization: Option<&str>) -> ProbeOutcome {
|
||||
};
|
||||
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();
|
||||
let body = match resp.body_mut().with_config().limit(MAX_BODY).read_to_string() {
|
||||
Ok(body) => body,
|
||||
// The answer began but did not finish in time. Where the body
|
||||
// decides what answered (200, 403), that is a timeout, not
|
||||
// "something else answers here".
|
||||
Err(e) if matches!(status, 200 | 403) && transport_error(&e, false) == TransportError::Timeout => {
|
||||
return ProbeOutcome::Timeout;
|
||||
}
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
classify_response(
|
||||
&status_url,
|
||||
status,
|
||||
@@ -724,4 +733,38 @@ mod tests {
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{p}/")).unwrap();
|
||||
assert_eq!(probe(&url, None), ProbeOutcome::MaybeHttps);
|
||||
}
|
||||
|
||||
/// A Codeman that sends its status headers and then stalls (a blocked
|
||||
/// event loop, a lossy link) did not answer in time. It is not "something
|
||||
/// else on this port", which is what an empty body read as before.
|
||||
#[test]
|
||||
fn a_body_that_stalls_is_a_timeout() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
/// Send `head` and the start of a body, then hold the connection open.
|
||||
fn serve_stalling(status_line: &'static str) -> 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() {
|
||||
let mut buf = [0u8; 4096];
|
||||
let _ = s.read(&mut buf);
|
||||
let _ = s.write_all(
|
||||
format!("HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: 4096\r\n\r\n{{\"success\":true,").as_bytes(),
|
||||
);
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
}
|
||||
});
|
||||
port
|
||||
}
|
||||
let short = Duration::from_millis(400);
|
||||
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{}/", serve_stalling("200 OK"))).unwrap();
|
||||
assert_eq!(probe_within(&url, None, short), ProbeOutcome::Timeout);
|
||||
|
||||
// A 401 has said all it needs to with its status line.
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{}/", serve_stalling("401 Unauthorized"))).unwrap();
|
||||
assert_eq!(probe_within(&url, None, short), ProbeOutcome::NeedsLogin);
|
||||
}
|
||||
}
|
||||
+144
-29
@@ -326,16 +326,17 @@ fn parse_ps(text: &str) -> Vec<(u32, String)> {
|
||||
/// `src/index.ts web`), not one of its short-lived control commands.
|
||||
pub fn is_codeman_server(command: &str) -> bool {
|
||||
let words: Vec<&str> = command.split_whitespace().collect();
|
||||
let entry = words.iter().position(|w| {
|
||||
let is_entry = |w: &str| {
|
||||
let name = w.rsplit('/').next().unwrap_or(w);
|
||||
w.ends_with("dist/index.js") || w.ends_with("src/index.ts") || name == "codeman" || name == "aicodeman"
|
||||
});
|
||||
match entry {
|
||||
Some(i) => {
|
||||
words.get(i + 1) == Some(&"web") && !words[i + 1..].iter().any(|w| matches!(*w, "--stop" | "--status"))
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
};
|
||||
// Any entry word that `web` follows: an earlier word may only look like
|
||||
// one (a folder named codeman in `tsx watch --cwd ~/codeman src/index.ts web`).
|
||||
(0..words.len()).any(|i| {
|
||||
is_entry(words[i])
|
||||
&& words.get(i + 1) == Some(&"web")
|
||||
&& !words[i + 1..].iter().any(|w| matches!(*w, "--stop" | "--status"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a command line is an install the app started on this Mac (the
|
||||
@@ -378,6 +379,16 @@ fn codeman_servers(procs: &[(u32, String)]) -> Vec<u32> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The install the app started on this Mac, if one runs, with the port it
|
||||
/// asked for as soon as one of its processes names it. The Terminal script
|
||||
/// that wraps the installer names none and is the older process, so the first
|
||||
/// match alone would report no port for the whole install.
|
||||
fn running_install(procs: &[(u32, String)]) -> Option<Option<u16>> {
|
||||
let mut installs = procs.iter().filter_map(|(_, c)| install_in_progress(c)).peekable();
|
||||
installs.peek()?;
|
||||
Some(installs.flatten().next())
|
||||
}
|
||||
|
||||
/// A listening TCP socket: its pid, address (`*`, `127.0.0.1`, `[::1]`, a
|
||||
/// specific IP) and port.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -440,9 +451,8 @@ fn serves_loopback_port(found: &[Listener], port: u16) -> bool {
|
||||
/// all-interfaces bind, else its own address.
|
||||
fn listener_url(l: &Listener) -> Option<Url> {
|
||||
let host = match l.host.as_str() {
|
||||
"*" | "0.0.0.0" | "127.0.0.1" => "127.0.0.1".to_string(),
|
||||
h if h.starts_with('[') => h.to_string(),
|
||||
h => h.to_string(),
|
||||
"*" | "0.0.0.0" => "127.0.0.1",
|
||||
h => h,
|
||||
};
|
||||
Url::parse(&format!("http://{host}:{}/", l.port)).ok()
|
||||
}
|
||||
@@ -455,6 +465,9 @@ pub enum LocalState {
|
||||
Running,
|
||||
/// Codeman answers but wants a login the app does not have.
|
||||
NeedsLogin,
|
||||
/// A Codeman server of this user runs but listens nowhere yet: it is
|
||||
/// still starting (the LaunchAgent at login, a restart).
|
||||
Starting,
|
||||
/// A Codeman server of this user runs, but not at an address the app can
|
||||
/// open (bound to one network address, say): see `elsewhere`.
|
||||
RunningElsewhere,
|
||||
@@ -497,6 +510,33 @@ pub struct LocalStatus {
|
||||
pub outcome: ProbeOutcome,
|
||||
}
|
||||
|
||||
/// Whether the probe got an answer from a Codeman server, logged in or not.
|
||||
fn answers(outcome: &ProbeOutcome) -> bool {
|
||||
matches!(
|
||||
outcome,
|
||||
ProbeOutcome::Ok { .. }
|
||||
| ProbeOutcome::PasswordChangeRequired
|
||||
| ProbeOutcome::NeedsLogin
|
||||
| ProbeOutcome::BadCredentials
|
||||
| ProbeOutcome::RateLimited { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// What the This Mac tab shows for what `inspect` found. `server_runs`: one of
|
||||
/// this user's Codeman server processes exists. `server_listens`: one of them
|
||||
/// has a listening socket. `installed`: Codeman is on this Mac.
|
||||
fn local_state(outcome: &ProbeOutcome, server_runs: bool, server_listens: bool, installed: bool) -> LocalState {
|
||||
match outcome {
|
||||
ProbeOutcome::Ok { .. } | ProbeOutcome::PasswordChangeRequired => LocalState::Running,
|
||||
_ if answers(outcome) => LocalState::NeedsLogin,
|
||||
ProbeOutcome::Refused if server_runs && !server_listens => LocalState::Starting,
|
||||
ProbeOutcome::Refused if server_runs => LocalState::RunningElsewhere,
|
||||
ProbeOutcome::Refused if installed => LocalState::Stopped,
|
||||
ProbeOutcome::Refused => LocalState::NotInstalled,
|
||||
_ => LocalState::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// How hard `inspect` looks for an installed Codeman when nothing answers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Depth {
|
||||
@@ -516,7 +556,7 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
let procs = list_processes();
|
||||
let servers = codeman_servers(&procs);
|
||||
let found = listeners(&servers);
|
||||
let install = procs.iter().find_map(|(_, c)| install_in_progress(c));
|
||||
let install = running_install(&procs);
|
||||
let install_in_app = procs.iter().any(|(_, c)| gui_install::is_install_run(c));
|
||||
|
||||
// The login goes only to this user's own Codeman on that port.
|
||||
@@ -565,20 +605,13 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
|
||||
let app = home.join(".codeman/app");
|
||||
let install_complete = app.join(".install-complete").is_file();
|
||||
let answering = match &outcome {
|
||||
ProbeOutcome::Ok { .. } | ProbeOutcome::PasswordChangeRequired => Some(LocalState::Running),
|
||||
ProbeOutcome::NeedsLogin | ProbeOutcome::BadCredentials | ProbeOutcome::RateLimited { .. } => {
|
||||
Some(LocalState::NeedsLogin)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// Something else on Codeman's port (a dev server on 3000, say) says
|
||||
// nothing about whether Codeman is installed, so look either way.
|
||||
let on_disk = install_complete
|
||||
|| app.join("dist/index.js").is_file()
|
||||
|| agent_path(&home).is_file()
|
||||
|| daemon_path().is_file();
|
||||
let installed = answering.is_some()
|
||||
let installed = answers(&outcome)
|
||||
|| !servers.is_empty()
|
||||
|| on_disk
|
||||
|| match depth {
|
||||
@@ -586,13 +619,7 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
Depth::Login => local_server::installed(false),
|
||||
Depth::Interactive => local_server::installed(true),
|
||||
};
|
||||
let state = match (answering, &outcome) {
|
||||
(Some(state), _) => state,
|
||||
(None, ProbeOutcome::Refused) if !servers.is_empty() => LocalState::RunningElsewhere,
|
||||
(None, ProbeOutcome::Refused) if installed => LocalState::Stopped,
|
||||
(None, ProbeOutcome::Refused) => LocalState::NotInstalled,
|
||||
(None, _) => LocalState::Other,
|
||||
};
|
||||
let state = local_state(&outcome, !servers.is_empty(), !found.is_empty(), installed);
|
||||
if state != LocalState::RunningElsewhere {
|
||||
elsewhere.clear();
|
||||
}
|
||||
@@ -636,6 +663,15 @@ pub fn already_running() -> Option<String> {
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether `url` is where the launchd job `service` answers: its scheme and
|
||||
/// port on this Mac, under `localhost` as much as 127.0.0.1. The path is left
|
||||
/// out: a job with a base path answers below `/` too, and a second server on
|
||||
/// its port would run without the job's settings.
|
||||
fn served_by(service: &ServiceConfig, url: &Url) -> bool {
|
||||
let at = local_url(Some(service));
|
||||
policy::is_loopback(url) && url.scheme() == at.scheme() && url.port_or_known_default() == at.port_or_known_default()
|
||||
}
|
||||
|
||||
/// Start the Codeman on this Mac for `url`. A LaunchAgent that serves that
|
||||
/// address is started through launchd, so it runs with its own settings
|
||||
/// (host, password) and stays supervised; anything else gets `codeman web -d`
|
||||
@@ -645,7 +681,7 @@ pub fn start_local(url: &Url) -> Result<String, String> {
|
||||
return Err(why);
|
||||
}
|
||||
match read_service() {
|
||||
Some(s) if local_url(Some(&s)) == *url => {
|
||||
Some(s) if served_by(&s, url) => {
|
||||
if s.daemon {
|
||||
return Err(format!(
|
||||
"A system LaunchDaemon runs Codeman on this Mac; an administrator starts it: sudo launchctl kickstart -k system/{SERVICE_LABEL}"
|
||||
@@ -701,7 +737,7 @@ fn start_launch_agent(port: u16) -> Result<String, String> {
|
||||
if !port_free(port) {
|
||||
return Ok(format!("launchd started Codeman ({SERVICE_LABEL})."));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
Err("launchd started Codeman, but it did not answer within 30 seconds. Its log is /tmp/codeman.log for an install.sh setup.".into())
|
||||
}
|
||||
@@ -1242,6 +1278,71 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_goes_to_the_launchd_job_that_serves_the_address() {
|
||||
let job = parse_service(&json!({
|
||||
"ProgramArguments": ["node", "i.js", "web"],
|
||||
"EnvironmentVariables": { "CODEMAN_PORT": "3001", "CODEMAN_BASE_URL": "/codeman" }
|
||||
}));
|
||||
// The app's own address for it, and what a user types for the same server.
|
||||
assert!(served_by(&job, &u("http://127.0.0.1:3001/codeman/")));
|
||||
assert!(served_by(&job, &u("http://localhost:3001/codeman/")));
|
||||
assert!(served_by(&job, &u("http://LOCALHOST:3001/")));
|
||||
// Another port, scheme or machine is not this job's server.
|
||||
assert!(!served_by(&job, &u("http://127.0.0.1:3000/codeman/")));
|
||||
assert!(!served_by(&job, &u("https://127.0.0.1:3001/codeman/")));
|
||||
assert!(!served_by(&job, &u("http://192.168.1.5:3001/codeman/")));
|
||||
assert!(!served_by(&job, &u("http://localhost.example.com:3001/")));
|
||||
|
||||
let https = parse_service(&json!({ "ProgramArguments": ["node", "i.js", "web", "--https"] }));
|
||||
assert!(served_by(&https, &u("https://localhost:3000/")));
|
||||
assert!(!served_by(&https, &u("http://localhost:3000/")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_mac_state_for_what_was_found() {
|
||||
let ok = ProbeOutcome::Ok {
|
||||
version: "1.48.0".into(),
|
||||
};
|
||||
// Whatever else is true, a Codeman that answers is what the tab shows.
|
||||
for (runs, listens, installed) in [(false, false, false), (true, true, true), (true, false, false)] {
|
||||
assert_eq!(local_state(&ok, runs, listens, installed), LocalState::Running);
|
||||
assert_eq!(
|
||||
local_state(&ProbeOutcome::PasswordChangeRequired, runs, listens, installed),
|
||||
LocalState::Running
|
||||
);
|
||||
for login in [
|
||||
ProbeOutcome::NeedsLogin,
|
||||
ProbeOutcome::BadCredentials,
|
||||
ProbeOutcome::RateLimited {
|
||||
sent_credentials: false,
|
||||
retry_after_secs: None,
|
||||
},
|
||||
] {
|
||||
assert_eq!(local_state(&login, runs, listens, installed), LocalState::NeedsLogin);
|
||||
}
|
||||
}
|
||||
// Nothing answers. A server process with no socket yet is starting,
|
||||
// which comes before "runs somewhere else": the app must not send the
|
||||
// user to another address for a server that is two seconds from up.
|
||||
let refused = ProbeOutcome::Refused;
|
||||
assert_eq!(local_state(&refused, true, false, true), LocalState::Starting);
|
||||
assert_eq!(local_state(&refused, true, false, false), LocalState::Starting);
|
||||
assert_eq!(local_state(&refused, true, true, true), LocalState::RunningElsewhere);
|
||||
assert_eq!(local_state(&refused, false, false, true), LocalState::Stopped);
|
||||
assert_eq!(local_state(&refused, false, false, false), LocalState::NotInstalled);
|
||||
// Something else holds the port, or the look itself failed.
|
||||
for other in [
|
||||
ProbeOutcome::NotCodeman { status: 404 },
|
||||
ProbeOutcome::Timeout,
|
||||
ProbeOutcome::MaybeHttps,
|
||||
] {
|
||||
assert_eq!(local_state(&other, true, true, true), LocalState::Other);
|
||||
assert_eq!(local_state(&other, false, false, false), LocalState::Other);
|
||||
}
|
||||
assert!(answers(&ProbeOutcome::BadCredentials) && !answers(&refused));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processes_and_listeners() {
|
||||
let ps = " 101 /opt/homebrew/bin/node /Users/k/.codeman/app/dist/index.js web\n\
|
||||
@@ -1255,6 +1356,15 @@ mod tests {
|
||||
909 bash /var/folders/x/T/codeman-install.Ab12Cd --local --service --port 3001\n\
|
||||
1001 /bin/bash /var/folders/x/T/install-codeman-remote-55-1.command\n\
|
||||
garbage line\n";
|
||||
// A folder named like the command comes before the real entry point.
|
||||
assert!(is_codeman_server(
|
||||
"node /x/tsx/cli.mjs watch --cwd /Users/k/codeman src/index.ts web"
|
||||
));
|
||||
assert!(is_codeman_server(
|
||||
"node --watch-path /Users/k/codeman /Users/k/codeman/src/index.ts web --port 3001"
|
||||
));
|
||||
assert!(!is_codeman_server("node /Users/k/codeman/scripts/build.mjs web"));
|
||||
assert!(!is_codeman_server("/opt/homebrew/bin/codeman attach web"));
|
||||
let procs = parse_ps(ps);
|
||||
assert_eq!(
|
||||
procs[0],
|
||||
@@ -1266,6 +1376,11 @@ mod tests {
|
||||
assert_eq!(codeman_servers(&procs), [101, 202, 303]);
|
||||
let installs: Vec<Option<u16>> = procs.iter().filter_map(|(_, c)| install_in_progress(c)).collect();
|
||||
assert_eq!(installs, [None, Some(3001)]);
|
||||
// The Terminal script comes first and names no port: the installer's wins.
|
||||
assert_eq!(running_install(&procs), Some(Some(3001)));
|
||||
// Before the installer is downloaded, only the script runs.
|
||||
assert_eq!(running_install(&procs[..8]), Some(None));
|
||||
assert_eq!(running_install(&procs[..7]), None);
|
||||
|
||||
let lsof = "p101\nf21\nn127.0.0.1:3000\nf22\nn172.17.0.1:3999\np202\nf9\nn*:4000\np303\nn[::1]:5000\nnbogus\n";
|
||||
let found = parse_lsof(lsof);
|
||||
|
||||
Reference in new issue
Block a user