diff --git a/README.md b/README.md index 72539796a..74629ad29 100644 --- a/README.md +++ b/README.md @@ -353,6 +353,7 @@ The common ones: | `CODETRIAL_MAX_CONCURRENT_INTERVIEWS` | `16` | Interviews one `web` process hosts agents for | | `CODETRIAL_ALLOWED_HOSTS` | empty | Comma-separated `Host` values the server answers; any other is refused with 421. Empty answers every name, but a value that names no host is refused at startup. `--allowed-hosts` sets it from the command line | | `CODETRIAL_EXIT_WITH_STDIN` | unset | For a program that starts the server as its child: exit when standard input reaches end of file, so the server does not outlive a launcher that crashed. Read from the process environment even under `--data-dir` | +| `CODETRIAL_CHANGE_KEYS_CODE` | unset | For a program that starts the server as its child: the Change keys code, at least 24 letters and digits, which the server then never prints. Read from the process environment even under `--data-dir`; ignored by a launch from a terminal, which makes and prints its own | Two more matter in production. `SESSION_SECRET` signs the session cookie, and its built-in default is a string published in this repository, so the server diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock index 8507eb850..9bf0ad789 100644 --- a/desktop/Cargo.lock +++ b/desktop/Cargo.lock @@ -476,6 +476,7 @@ dependencies = [ name = "codetrial-desktop" version = "0.1.0" dependencies = [ + "getrandom 0.3.4", "open", "tauri", "tauri-build", diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index 39d25e7fe..fb7131cc6 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -27,6 +27,8 @@ all = "deny" tauri-build = { version = "=2.7.4", features = [] } [dependencies] +# Already in the tree through tauri; the Change keys code is read from it. +getrandom = "=0.3.4" open = { version = "=5.4.4", features = ["shellexecute-on-windows"] } tauri = { version = "=2.12.5", features = [] } tauri-plugin-dialog = "=2.8.4" diff --git a/desktop/src/main.rs b/desktop/src/main.rs index d7c532ecb..4a60a5a28 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -18,11 +18,13 @@ use std::path::Path; use std::sync::{LazyLock, Mutex, mpsc}; use std::time::Duration; -use tauri::webview::{DownloadEvent, NewWindowResponse, PermissionKind, PermissionResponse}; +use tauri::webview::{ + DownloadEvent, NewWindowResponse, PageLoadEvent, PermissionKind, PermissionResponse, +}; use tauri::{AppHandle, Manager, RunEvent, Url, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; -use navigation::{Ask, Verdict}; +use navigation::{Ask, ChangeKeysCode, Verdict}; const WINDOW: &str = "main"; @@ -89,6 +91,8 @@ enum Close { struct Shell { server: Mutex>, + /// The running server's Change keys code, shown or filled in this window. + change_keys_code: Mutex>, phase: Mutex, close: Mutex, } @@ -113,6 +117,7 @@ fn main() { .plugin(tauri_plugin_dialog::init()) .manage(Shell { server: Mutex::new(None), + change_keys_code: Mutex::new(None), phase: Mutex::new(Phase::Starting { server_ready: false, webrtc: None, @@ -208,6 +213,27 @@ fn open_window(app: &AppHandle) -> tauri::Result<()> { Verdict::Refuse => false, } }) + // Change keys asks for the code the server would print to a terminal, + // and this server has none. With the interview in this window the code + // is filled into the server's own Setup page and no other; with it in + // the browser, the start page left here shows it, as a terminal would. + // Never in a URL, where history would keep it. + .on_page_load(|webview, payload| { + if payload.event() != PageLoadEvent::Finished { + return; + } + let script = + match navigation::change_keys_code_for(payload.url(), &SERVER_URL, &START_PAGE) { + Some(ChangeKeysCode::Fill) => fill_change_keys_code, + Some(ChangeKeysCode::Show) => show_change_keys_code, + None => return, + }; + let shell = webview.app_handle().state::(); + let code = shell.change_keys_code.lock().expect("code lock").clone(); + if let Some(code) = code { + let _ = webview.eval(script(&code)); + } + }) // `target="_blank"` and `window.open`. A second webview would be a // second window into the same origin with none of the rules above, so a // web page goes to the browser and nothing opens here. @@ -300,6 +326,7 @@ fn launch(app: &AppHandle) { std::fs::create_dir_all(&data_dir) .map_err(|error| format!("cannot create {}: {error}", data_dir.display()))?; Ok(server::Launch { + change_keys_code: server::change_keys_code()?, program: server::program_path()?, data_dir, addr: SERVER_ADDR.to_string(), @@ -313,6 +340,10 @@ fn launch(app: &AppHandle) { Err(message) => return show_failure(app, &message, None), }; + *app.state::() + .change_keys_code + .lock() + .expect("code lock") = Some(launch.change_keys_code.clone()); let data_dir = launch.data_dir.clone(); let reporter = app.clone(); let started = server::start(&launch, move |status| { @@ -342,6 +373,25 @@ fn launch(app: &AppHandle) { } } +/// The script that puts `code`, hex digits only, into the Setup page's code +/// field. The page shows and enables that field itself once `/api/setup` +/// answers, which keeps the value, so the field appears already filled. +fn fill_change_keys_code(code: &str) -> String { + format!( + "(() => {{ const field = document.getElementById('code'); \ + if (field) field.value = '{code}'; }})()" + ) +} + +/// The script that shows `code`, hex digits only, on the start page when the +/// interview runs in the browser, where nothing here can fill it in. +fn show_change_keys_code(code: &str) -> String { + format!( + "(() => {{ document.getElementById('change-keys-code').textContent = '{code}'; \ + document.getElementById('change-keys').hidden = false; }})()" + ) +} + /// Shows the server in this window, or in the default browser when this /// window has no WebRTC, once both halves are known: the server is ready and /// the starting page has said what it has. Called as each arrives, in either diff --git a/desktop/src/navigation.rs b/desktop/src/navigation.rs index eaf166546..7c6777fdb 100644 --- a/desktop/src/navigation.rs +++ b/desktop/src/navigation.rs @@ -54,6 +54,29 @@ pub fn judge(url: &Url, server: &Url, start_page: &Url) -> Verdict { } } +/// What a page the window finished loading is handed of the Change keys code. +#[derive(Debug, PartialEq, Eq)] +pub enum ChangeKeysCode { + /// Filled into the code field of the server's own Setup page. + Fill, + /// Shown on the start page left in the window while the interview runs in + /// the browser, where nothing here can fill a field. + Show, +} + +/// Which pages get the code, and no other: a mistake here either hides Change +/// keys or hands the code to a page that is not the server's Setup page. Built +/// on `judge`, so a page the window may not show never gets it. +pub fn change_keys_code_for(url: &Url, server: &Url, start_page: &Url) -> Option { + match judge(url, server, start_page) { + Verdict::Server if url.path() == "/setup" => Some(ChangeKeysCode::Fill), + Verdict::StartPage(Ask::Nothing) if url.query_pairs().any(|(key, _)| key == "browser") => { + Some(ChangeKeysCode::Show) + } + _ => None, + } +} + /// Where the window's start page loads, `http_scheme` being true on Windows /// and Android. Tauri serves `WebviewUrl::App("index.html")` at the root of /// its own origin, `http://tauri.localhost/` there and `tauri://localhost/` diff --git a/desktop/src/server.rs b/desktop/src/server.rs index df11e29e7..ffb655844 100644 --- a/desktop/src/server.rs +++ b/desktop/src/server.rs @@ -39,6 +39,19 @@ pub struct Launch { /// A CLI config whose keys Setup offers to use on a first launch. The /// server decides what is offered and what using it writes. pub import_config: Option, + /// What Change keys asks for, new on every launch. The server has no + /// terminal to print one to, so the app makes it, hands it over in the + /// environment, and shows or fills it in its own window. + pub change_keys_code: String, +} + +/// A code for `Launch::change_keys_code`: 32 hex digits from the operating +/// system's generator. +pub fn change_keys_code() -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes) + .map_err(|error| format!("cannot make a Change keys code: {error}"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) } /// The CLI config in `start`: the CLI's own two places there and nowhere else. @@ -116,6 +129,7 @@ fn command(launch: &Launch) -> Command { // data folder is the one place it can sensibly mean. .current_dir(&launch.data_dir) .env("CODETRIAL_EXIT_WITH_STDIN", "1") + .env("CODETRIAL_CHANGE_KEYS_CODE", &launch.change_keys_code) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); diff --git a/desktop/tests/unit/navigation.rs b/desktop/tests/unit/navigation.rs index 9ef61c20b..e29bc3cf4 100644 --- a/desktop/tests/unit/navigation.rs +++ b/desktop/tests/unit/navigation.rs @@ -176,3 +176,47 @@ fn a_download_keeps_its_name_and_never_overwrites() { let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn only_the_servers_setup_page_and_the_browser_start_page_get_the_code() { + let server = url("http://127.0.0.1:3101/"); + for start in [ + "tauri://localhost/index.html", + "http://tauri.localhost/index.html", + ] { + let start = url(start); + let code_for = |page: &str| change_keys_code_for(&url(page), &server, &start); + assert_eq!( + code_for("http://127.0.0.1:3101/setup"), + Some(ChangeKeysCode::Fill) + ); + + // `show_start_page` loads the root with the query, which serves + // `index.html`; the named file is the same page. + for shown in ["/?browser=", "index.html?browser="] { + assert_eq!( + code_for(start.join(shown).unwrap().as_str()), + Some(ChangeKeysCode::Show), + "{shown}" + ); + } + + // The server's own `?browser` is just a server page, and only its Setup + // page has the field: not another path, not another port, not the start + // page while it is starting, failing or asking. + for nothing in [ + "http://127.0.0.1:3101/?browser=", + "http://127.0.0.1:3101/", + "http://127.0.0.1:3101/setup/x", + "http://127.0.0.1:3102/setup", + "http://localhost:3101/setup", + ] { + assert_eq!(code_for(nothing), None, "{nothing}"); + } + for query in ["", "?error=x", "?webrtc=no", "?reopen", "?browser=&reopen"] { + let page = start.join(&format!("index.html{query}")).unwrap(); + assert_eq!(code_for(page.as_str()), None, "{page}"); + } + assert_eq!(code_for(start.join("setup").unwrap().as_str()), None); + } +} diff --git a/desktop/tests/unit/server.rs b/desktop/tests/unit/server.rs index a379b1327..6ae787039 100644 --- a/desktop/tests/unit/server.rs +++ b/desktop/tests/unit/server.rs @@ -3,6 +3,8 @@ use std::sync::mpsc; use super::*; +const CODE: &str = "0123456789abcdef0123456789abcdef"; + fn temp_dir(label: &str) -> PathBuf { static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = std::env::temp_dir().join(format!( @@ -22,6 +24,7 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() { data_dir: PathBuf::from("/data"), addr: "127.0.0.1:3101".to_string(), import_config: None, + change_keys_code: CODE.to_string(), }; let command = command(&launch); let args = command @@ -43,8 +46,8 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() { ); assert_eq!(command.get_current_dir(), Some(Path::new("/data"))); - // The pipe is the one thing it is told through the environment, which a - // `--data-dir` launch reads no configuration from. + // The pipe and the Change keys code are the two things it is told through + // the environment, which a `--data-dir` launch reads no configuration from. let env = |key: &str| { command .get_envs() @@ -52,8 +55,9 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() { .and_then(|(_, value)| value) .map(|value| value.to_string_lossy().into_owned()) }; - assert_eq!(command.get_envs().count(), 1); + assert_eq!(command.get_envs().count(), 2); assert_eq!(env("CODETRIAL_EXIT_WITH_STDIN").as_deref(), Some("1")); + assert_eq!(env("CODETRIAL_CHANGE_KEYS_CODE").as_deref(), Some(CODE)); } #[test] @@ -63,6 +67,7 @@ fn a_cli_config_found_is_offered_to_the_server_to_import() { data_dir: PathBuf::from("/data"), addr: "127.0.0.1:3101".to_string(), import_config: Some(PathBuf::from("/checkout/config/codetrial.env.local")), + change_keys_code: CODE.to_string(), }; let args = command(&launch) .get_args() @@ -144,6 +149,7 @@ fn launch_of(dir: &Path, program: PathBuf, addr: String) -> Launch { data_dir: dir.to_path_buf(), addr, import_config: None, + change_keys_code: CODE.to_string(), } } @@ -218,3 +224,13 @@ fn a_server_is_ready_once_bound_and_stops_when_its_stdin_closes() { assert!(received.recv_timeout(Duration::from_millis(500)).is_err()); let _ = std::fs::remove_dir_all(&dir); } + +/// Strong enough for the server to take: it ignores a code shorter than 24 +/// letters and digits. +#[test] +fn a_change_keys_code_is_new_hex_on_every_launch() { + let first = change_keys_code().unwrap(); + assert_eq!(first.len(), 32); + assert!(first.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_ne!(first, change_keys_code().unwrap()); +} diff --git a/desktop/ui/index.html b/desktop/ui/index.html index 318a47594..1e647c1ea 100644 --- a/desktop/ui/index.html +++ b/desktop/ui/index.html @@ -23,6 +23,11 @@

CodeTrial

Keep this window open while you practise. Closing it stops CodeTrial.

+