Harden commands, plugin install and data paths #1

Open
Bonchellon wants to merge 1 commits from fix/review-hardening into main
6 changed files with 387 additions and 200 deletions
Showing only changes of commit b801588c9f - Show all commits

View File

@ -92,6 +92,95 @@ fn ensure_under_root(conn: &Conn, path: &str) -> Result<(), String> {
Ok(()) Ok(())
} }
/// Like `ensure_under_root`, but the root itself is refused: for destructive
/// operations, where the workspace folder must never be the target.
fn ensure_inside_root(conn: &Conn, path: &str) -> Result<(), String> {
ensure_under_root(conn, path)?;
let canon_root = std::fs::canonicalize(&conn.root).map_err(|e| e.to_string())?;
let canon = std::fs::canonicalize(path).map_err(|e| e.to_string())?;
if canon == canon_root {
return Err("Refusing to operate on the workspace root".into());
}
Ok(())
}
/// A build input must be a solution or project file inside the workspace: MSBuild
/// runs whatever an arbitrary project file tells it to.
fn ensure_build_input(conn: &Conn, path: &str) -> Result<(), String> {
let p = std::path::Path::new(path);
if path.is_empty() || !p.exists() {
return Ok(());
}
let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
if !["sln", "slnx", "uproject"].iter().any(|x| ext.eq_ignore_ascii_case(x)) {
return Err(format!("Not a solution or Unreal project: {path}"));
}
ensure_under_root(conn, path)
}
/// Upper bound for a blocking p4 call. Streaming transfers (sync/submit) aren't
/// subject to it: they run for as long as they keep going and can be cancelled.
const P4_TIMEOUT: Duration = Duration::from_secs(900);
/// Read a child's pipe to the end on its own thread, so a full stderr pipe can't
/// block the process while we're reading stdout.
fn read_all<R: std::io::Read + Send + 'static>(reader: Option<R>) -> std::thread::JoinHandle<Vec<u8>> {
std::thread::spawn(move || {
let mut buf = Vec::new();
if let Some(mut r) = reader {
let _ = r.read_to_end(&mut buf);
}
buf
})
}
/// Split a child's output into decoded lines. `BufRead::lines` stops at the first
/// non-UTF-8 byte, and p4 prints paths in the ANSI codepage.
fn byte_lines<R: std::io::Read>(reader: R) -> impl Iterator<Item = String> {
BufReader::new(reader)
.split(b'\n')
.map_while(Result::ok)
.map(|l| decode(&l).trim_end_matches('\r').to_string())
}
/// Deliver a child's lines over a channel, so the reader can poll a cancel flag
/// while the child prints nothing.
fn line_channel<R: std::io::Read + Send + 'static>(reader: R) -> std::sync::mpsc::Receiver<String> {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for line in byte_lines(reader) {
if tx.send(line).is_err() {
break;
}
}
});
rx
}
/// `Command::output` with a time limit: the child is killed once it runs out.
fn run_limited(cmd: &mut Command, timeout: Duration) -> std::io::Result<std::process::Output> {
let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
let out = read_all(child.stdout.take());
let err = read_all(child.stderr.take());
let started = Instant::now();
let status = loop {
if let Some(s) = child.try_wait()? {
break s;
}
if started.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "p4 timed out"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(std::process::Output {
status,
stdout: out.join().unwrap_or_default(),
stderr: err.join().unwrap_or_default(),
})
}
/// Build a `p4` command with the connection's global flags applied. /// Build a `p4` command with the connection's global flags applied.
/// On Windows we set CREATE_NO_WINDOW so no console flashes on every call. /// On Windows we set CREATE_NO_WINDOW so no console flashes on every call.
/// stdin defaults to null so a command that unexpectedly prompts (expired /// stdin defaults to null so a command that unexpectedly prompts (expired
@ -122,7 +211,7 @@ fn p4_cmd(conn: &Conn, tagged: bool) -> Command {
/// Run a tagged (JSON) p4 command and collect the objects it prints. /// Run a tagged (JSON) p4 command and collect the objects it prints.
fn run_json(conn: &Conn, args: &[&str]) -> Result<Vec<Value>, String> { fn run_json(conn: &Conn, args: &[&str]) -> Result<Vec<Value>, String> {
let out = match p4_cmd(conn, true).args(args).output() { let out = match run_limited(p4_cmd(conn, true).args(args), P4_TIMEOUT) {
Ok(o) => o, Ok(o) => o,
Err(e) => { Err(e) => {
let m = format!("Failed to start p4: {e}"); let m = format!("Failed to start p4: {e}");
@ -513,7 +602,7 @@ async fn p4_changes(state: State<'_, AppState>) -> Result<Vec<Value>, String> {
.map_or(false, |d| d.get("depotFile0").is_some()); .map_or(false, |d| d.get("depotFile0").is_some());
if shelved { if shelved {
result.push(c); result.push(c);
} else { } else if cl_is_stale(&c) {
let _ = run_text(&conn, &["change", "-d", &num]); let _ = run_text(&conn, &["change", "-d", &num]);
} }
} }
@ -521,6 +610,19 @@ async fn p4_changes(state: State<'_, AppState>) -> Result<Vec<Value>, String> {
Ok(result) Ok(result)
} }
/// Empty changelists are cleaned up only once they're a few minutes old, so a poll
/// can't delete one that a partial submit has just created.
fn cl_is_stale(change: &Value) -> bool {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
change
.get("time")
.and_then(|t| t.as_str())
.and_then(|t| t.parse::<u64>().ok())
.map_or(false, |t| now.saturating_sub(t) > 300)
}
/// Submitted history for a depot path (History tab). /// Submitted history for a depot path (History tab).
#[tauri::command] #[tauri::command]
async fn p4_history(state: State<'_, AppState>, path: String) -> Result<Vec<Value>, String> { async fn p4_history(state: State<'_, AppState>, path: String) -> Result<Vec<Value>, String> {
@ -537,7 +639,7 @@ async fn p4_disconnect(state: State<'_, AppState>) -> Result<(), String> {
/// Run a non-tagged p4 command (raw text out). Errors carry stderr. /// Run a non-tagged p4 command (raw text out). Errors carry stderr.
fn run_text(conn: &Conn, args: &[&str]) -> Result<String, String> { fn run_text(conn: &Conn, args: &[&str]) -> Result<String, String> {
let out = match p4_cmd(conn, false).args(args).output() { let out = match run_limited(p4_cmd(conn, false).args(args), P4_TIMEOUT) {
Ok(o) => o, Ok(o) => o,
Err(e) => { Err(e) => {
let m = format!("Failed to start p4: {e}"); let m = format!("Failed to start p4: {e}");
@ -588,13 +690,20 @@ fn run_stream(conn: &Conn, args: &[&str], op: &str, total: i64) -> Result<String
let mut count: i64 = 0; let mut count: i64 = 0;
let mut last = Instant::now(); let mut last = Instant::now();
let mut cancelled = false; let mut cancelled = false;
let err_reader = read_all(child.stderr.take());
if let Some(out) = child.stdout.take() { if let Some(out) = child.stdout.take() {
for line in BufReader::new(out).lines().map_while(Result::ok) { let lines = line_channel(out);
loop {
if TRANSFER_CANCEL.load(Ordering::SeqCst) { if TRANSFER_CANCEL.load(Ordering::SeqCst) {
cancelled = true; cancelled = true;
let _ = child.kill(); let _ = child.kill();
break; break;
} }
let line = match lines.recv_timeout(Duration::from_millis(200)) {
Ok(l) => l,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
};
count += 1; count += 1;
// throttle to ~25 fps regardless of file count, but always send the first few // throttle to ~25 fps regardless of file count, but always send the first few
if count <= 5 || last.elapsed().as_millis() >= 40 { if count <= 5 || last.elapsed().as_millis() >= 40 {
@ -611,15 +720,7 @@ fn run_stream(conn: &Conn, args: &[&str], op: &str, total: i64) -> Result<String
} }
} }
let status = child.wait().map_err(|e| e.to_string())?; let status = child.wait().map_err(|e| e.to_string())?;
let stderr = child let stderr = decode(&err_reader.join().unwrap_or_default()).trim().to_string();
.stderr
.take()
.map(|mut s| {
let mut buf = String::new();
let _ = std::io::Read::read_to_string(&mut s, &mut buf);
buf.trim().to_string()
})
.unwrap_or_default();
// tell the UI the transfer is finished // tell the UI the transfer is finished
if let Some(app) = APP.get() { if let Some(app) = APP.get() {
@ -632,9 +733,14 @@ fn run_stream(conn: &Conn, args: &[&str], op: &str, total: i64) -> Result<String
log_p4(args, count, false, Some("cancelled by user")); log_p4(args, count, false, Some("cancelled by user"));
return Err("Cancelled.".into()); return Err("Cancelled.".into());
} }
if !status.success() && !stderr.is_empty() { if !status.success() {
log_p4(args, 0, false, Some(&stderr)); let msg = if stderr.is_empty() {
return Err(stderr); format!("p4 {} failed", args.first().unwrap_or(&""))
} else {
stderr
};
log_p4(args, 0, false, Some(&msg));
return Err(msg);
} }
log_p4(args, count, true, None); log_p4(args, count, true, None);
Ok(collected.trim().to_string()) Ok(collected.trim().to_string())
@ -709,11 +815,7 @@ async fn p4_diff(state: State<'_, AppState>, file: String) -> Result<String, Str
#[tauri::command] #[tauri::command]
async fn p4_revert(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> { async fn p4_revert(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
let conn = current(&state)?; let conn = current(&state)?;
let mut args: Vec<&str> = vec!["revert"]; run_batched(&conn, &["revert"], &files)
for f in &files {
args.push(f.as_str());
}
run_text(&conn, &args)
} }
/// Create an empty numbered changelist with a description; returns its number. /// Create an empty numbered changelist with a description; returns its number.
@ -850,11 +952,7 @@ async fn p4_reopen_default(state: State<'_, AppState>, files: Vec<String>) -> Re
if files.is_empty() { if files.is_empty() {
return Ok(String::new()); return Ok(String::new());
} }
let mut args: Vec<&str> = vec!["reopen", "-c", "default"]; run_batched(&conn, &["reopen", "-c", "default"], &files)
for f in &files {
args.push(f.as_str());
}
run_text(&conn, &args)
} }
/// Edit the description of a pending changelist, preserving its file list. /// Edit the description of a pending changelist, preserving its file list.
@ -917,9 +1015,15 @@ async fn p4_submit(
return Err("No files selected to submit".into()); return Err("No files selected to submit".into());
} }
let n = files.len() as i64; let n = files.len() as i64;
let opened_total = run_json(&conn, &["opened"])?.len(); let opened = run_json(&conn, &["opened"])?;
// all opened files selected → submit the whole default changelist in one go let in_default: std::collections::HashSet<&str> = opened
if files.len() >= opened_total { .iter()
.filter(|v| v.get("change").and_then(|c| c.as_str()) == Some("default"))
.filter_map(|v| v.get("depotFile").and_then(|d| d.as_str()))
.collect();
let selected: std::collections::HashSet<&str> = files.iter().map(|f| f.as_str()).collect();
// exactly the default changelist selected → submit it in one go
if selected == in_default {
return run_stream(&conn, &["submit", "-d", &description], "submit", n); return run_stream(&conn, &["submit", "-d", &description], "submit", n);
} }
// partial submit → dedicated numbered changelist (batched reopen for large sets) // partial submit → dedicated numbered changelist (batched reopen for large sets)
@ -961,6 +1065,26 @@ fn file_batches(files: &[String], prefix_len: usize) -> Vec<std::ops::Range<usiz
ranges ranges
} }
/// Run `prefix <files…>` in batches that fit the Windows command line.
fn run_batched(conn: &Conn, prefix: &[&str], files: &[String]) -> Result<String, String> {
let prefix_len: usize = prefix.iter().map(|p| p.len() + 1).sum();
let mut out = String::new();
for r in file_batches(files, prefix_len) {
let mut args: Vec<&str> = prefix.to_vec();
for f in &files[r] {
args.push(f.as_str());
}
let text = run_text(conn, &args)?;
if !text.is_empty() {
if !out.is_empty() {
out.push('\n');
}
out.push_str(&text);
}
}
Ok(out)
}
fn files_cmd(conn: &Conn, cmd: &str, files: &[String]) -> Result<Vec<Value>, String> { fn files_cmd(conn: &Conn, cmd: &str, files: &[String]) -> Result<Vec<Value>, String> {
if files.is_empty() { if files.is_empty() {
return Ok(Vec::new()); return Ok(Vec::new());
@ -1045,13 +1169,20 @@ fn run_reconcile_stream(conn: &Conn, spec: &str) -> Result<i64, String> {
let mut count: i64 = 0; let mut count: i64 = 0;
let mut last = Instant::now(); let mut last = Instant::now();
let mut cancelled = false; let mut cancelled = false;
let err_reader = read_all(child.stderr.take());
if let Some(out) = child.stdout.take() { if let Some(out) = child.stdout.take() {
for line in BufReader::new(out).lines().map_while(Result::ok) { let lines = line_channel(out);
loop {
if SCAN_CANCEL.load(Ordering::SeqCst) { if SCAN_CANCEL.load(Ordering::SeqCst) {
cancelled = true; cancelled = true;
let _ = child.kill(); let _ = child.kill();
break; break;
} }
let line = match lines.recv_timeout(Duration::from_millis(200)) {
Ok(l) => l,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
};
// reconcile prints one `//depot/… - opened for add|edit|delete` per file // reconcile prints one `//depot/… - opened for add|edit|delete` per file
if !line.starts_with("//") { if !line.starts_with("//") {
continue; continue;
@ -1070,15 +1201,7 @@ fn run_reconcile_stream(conn: &Conn, spec: &str) -> Result<i64, String> {
} }
} }
let _ = child.wait(); let _ = child.wait();
let stderr = child let stderr = decode(&err_reader.join().unwrap_or_default()).trim().to_string();
.stderr
.take()
.map(|mut s| {
let mut buf = String::new();
let _ = std::io::Read::read_to_string(&mut s, &mut buf);
buf.trim().to_string()
})
.unwrap_or_default();
// final event so the UI can clear the counter / show the total // final event so the UI can clear the counter / show the total
if let Some(app) = APP.get() { if let Some(app) = APP.get() {
@ -1158,6 +1281,10 @@ async fn open_in_explorer(state: State<'_, AppState>, target: String) -> Result<
} else { } else {
target target
}; };
// touching a network path would send the user's Windows credentials to that host
if local.starts_with("\\\\") || local.starts_with("//") {
return Err("Network paths can't be opened here".into());
}
let path = std::path::Path::new(&local); let path = std::path::Path::new(&local);
if !path.exists() { if !path.exists() {
return Err(format!("Path not synced to disk yet: {local}")); return Err(format!("Path not synced to disk yet: {local}"));
@ -1324,15 +1451,8 @@ async fn open_in_editor(state: State<'_, AppState>, depot: String, editor: Strin
.ok_or_else(|| "No editor available".to_string())?; .ok_or_else(|| "No editor available".to_string())?;
if ed.exe.is_empty() { if ed.exe.is_empty() {
// system-default association via `start` // system-default association, no shell: the file name is depot data
let mut c = Command::new("cmd"); tauri_plugin_opener::open_path(&local, None::<&str>)
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
c.creation_flags(0x0800_0000);
}
c.args(["/C", "start", "", &local])
.spawn()
.map_err(|e| format!("Could not launch: {e}"))?; .map_err(|e| format!("Could not launch: {e}"))?;
} else { } else {
let mut c = Command::new(&ed.exe); let mut c = Command::new(&ed.exe);
@ -1362,14 +1482,7 @@ async fn launch_file(state: State<'_, AppState>, path: String) -> Result<(), Str
if !std::path::Path::new(&path).exists() { if !std::path::Path::new(&path).exists() {
return Err(format!("File not found: {path}")); return Err(format!("File not found: {path}"));
} }
let mut c = Command::new("cmd"); tauri_plugin_opener::open_path(&path, None::<&str>)
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
c.creation_flags(0x0800_0000);
}
c.args(["/C", "start", "", &path])
.spawn()
.map_err(|e| format!("Could not launch: {e}"))?; .map_err(|e| format!("Could not launch: {e}"))?;
Ok(()) Ok(())
} }
@ -1480,7 +1593,10 @@ fn resolve_engine_dir(uproject: &str) -> Option<String> {
/// `MSBuild <solution>` does. For a plain C++ solution it falls back to MSBuild. /// `MSBuild <solution>` does. For a plain C++ solution it falls back to MSBuild.
/// Output streams line-by-line as `build-log` events. /// Output streams line-by-line as `build-log` events.
#[tauri::command] #[tauri::command]
async fn build_sln(path: String, config: String, uproject: String) -> Result<String, String> { async fn build_sln(state: State<'_, AppState>, path: String, config: String, uproject: String) -> Result<String, String> {
let conn = current(&state)?;
ensure_build_input(&conn, &path)?;
ensure_build_input(&conn, &uproject)?;
if !std::path::Path::new(&path).exists() && uproject.is_empty() { if !std::path::Path::new(&path).exists() && uproject.is_empty() {
return Err(format!("Solution not found: {path}")); return Err(format!("Solution not found: {path}"));
} }
@ -1589,8 +1705,9 @@ async fn build_sln(path: String, config: String, uproject: String) -> Result<Str
} }
}; };
let err_reader = read_all(child.stderr.take());
if let Some(out) = child.stdout.take() { if let Some(out) = child.stdout.take() {
for line in BufReader::new(out).lines().map_while(Result::ok) { for line in byte_lines(out) {
if !line.trim().is_empty() { if !line.trim().is_empty() {
scan(&line); scan(&line);
emit(line, false, false); emit(line, false, false);
@ -1598,9 +1715,8 @@ async fn build_sln(path: String, config: String, uproject: String) -> Result<Str
} }
} }
let status = child.wait().map_err(|e| e.to_string())?; let status = child.wait().map_err(|e| e.to_string())?;
if let Some(mut se) = child.stderr.take() { {
let mut buf = String::new(); let buf = decode(&err_reader.join().unwrap_or_default());
let _ = std::io::Read::read_to_string(&mut se, &mut buf);
for line in buf.lines() { for line in buf.lines() {
if !line.trim().is_empty() { if !line.trim().is_empty() {
scan(line); scan(line);
@ -1723,14 +1839,20 @@ async fn delete_folder(state: State<'_, AppState>, path: String) -> Result<Vec<V
let conn = current(&state)?; let conn = current(&state)?;
if !path.starts_with("//") { if !path.starts_with("//") {
// local-only folder → remove on disk (confined) // local-only folder → remove on disk (confined)
ensure_under_root(&conn, &path)?; ensure_inside_root(&conn, &path)?;
std::fs::remove_dir_all(&path).map_err(|e| format!("Could not delete folder: {e}"))?; std::fs::remove_dir_all(&path).map_err(|e| format!("Could not delete folder: {e}"))?;
return Ok(Vec::new()); return Ok(Vec::new());
} }
let base = path.trim_end_matches(['/', '.']); let base = path.trim_end_matches(['/', '.']);
let spec = format!("{base}/..."); let spec = format!("{base}/...");
// un-open anything already opened under here (adds/edits/deletes) so delete is clean // open work must not disappear with the folder: it's submitted, shelved or reverted first
let _ = run_json(&conn, &["revert", &spec]); let open = run_json(&conn, &["opened", &spec]).unwrap_or_default();
if !open.is_empty() {
return Err(format!(
"{} file(s) under this folder are open. Submit, shelve or revert them first.",
open.len()
));
}
let deleted = run_json(&conn, &["delete", &spec]).or_else(|e| { let deleted = run_json(&conn, &["delete", &spec]).or_else(|e| {
let l = e.to_lowercase(); let l = e.to_lowercase();
if l.contains("no such file") || l.contains("not on client") || l.contains("no file(s)") || l.contains("empty") { if l.contains("no such file") || l.contains("not on client") || l.contains("no file(s)") || l.contains("empty") {
@ -1739,11 +1861,14 @@ async fn delete_folder(state: State<'_, AppState>, path: String) -> Result<Vec<V
Err(e) Err(e)
} }
})?; })?;
// nothing versioned here → drop the local directory outright // nothing versioned here → remove the directory only if it's already empty,
// so unversioned files are never deleted as a side effect
if deleted.is_empty() { if deleted.is_empty() {
if let Some(local) = scope_local_dir(&conn, base) { if let Some(local) = scope_local_dir(&conn, base) {
if ensure_under_root(&conn, &local).is_ok() { if std::path::Path::new(&local).is_dir() {
let _ = std::fs::remove_dir_all(&local); ensure_inside_root(&conn, &local)?;
std::fs::remove_dir(&local)
.map_err(|_| "Nothing here is versioned, but the folder still holds local files. Delete it in Explorer.".to_string())?;
} }
} }
} }
@ -1795,6 +1920,7 @@ async fn read_depot(state: State<'_, AppState>, depot: String) -> Result<tauri::
.next() .next()
.and_then(|v| v.get("path").and_then(|p| p.as_str()).map(String::from)) .and_then(|v| v.get("path").and_then(|p| p.as_str()).map(String::from))
.ok_or_else(|| "Could not resolve the file path".to_string())?; .ok_or_else(|| "Could not resolve the file path".to_string())?;
ensure_under_root(&conn, &local)?;
check_local_size(&local)?; check_local_size(&local)?;
std::fs::read(&local) std::fs::read(&local)
.map(tauri::ipc::Response::new) .map(tauri::ipc::Response::new)
@ -1836,20 +1962,45 @@ async fn print_depot(state: State<'_, AppState>, spec: String) -> Result<tauri::
Ok(tauri::ipc::Response::new(out.stdout)) Ok(tauri::ipc::Response::new(out.stdout))
} }
/// Run an arbitrary `p4` command for the built-in terminal and return combined /// What the built-in terminal refuses: commands that expose the ticket, change the
/// stdout+stderr as text. Never errors on a non-zero exit — the terminal shows /// client's settings or destroy server history, and global flags, since `-p` alone
/// the error text just like a real console would. /// would point the session at another server.
fn console_guard(args: &[String]) -> Result<(), String> {
const FLAGS: &[&str] = &["-ztag", "-Mj", "-s", "-e"];
const BLOCKED: &[&str] = &[
"admin", "configure", "login", "logout", "obliterate", "passwd", "set", "tickets", "trust",
];
let mut rest = args.iter().skip_while(|a| FLAGS.iter().any(|f| *f == a.as_str()));
let cmd = rest.next().map_or("", |s| s.as_str());
if cmd.is_empty() {
return Err("Usage: p4 <command>".into());
}
if cmd.starts_with('-') {
return Err(format!("Global flag {cmd} isn't available in this terminal"));
}
if BLOCKED.iter().any(|b| cmd.eq_ignore_ascii_case(b)) {
return Err(format!("p4 {cmd} isn't available in this terminal"));
}
if cmd.eq_ignore_ascii_case("print") && rest.any(|a| a.starts_with('-') && a.contains('o')) {
return Err("p4 print -o isn't available in this terminal".into());
}
Ok(())
}
/// Run a `p4` command for the built-in terminal and return combined stdout+stderr
/// as text. Never errors on a non-zero exit — the terminal shows the error text
/// just like a real console would.
#[tauri::command] #[tauri::command]
async fn p4_console(state: State<'_, AppState>, args: Vec<String>) -> Result<String, String> { async fn p4_console(state: State<'_, AppState>, args: Vec<String>) -> Result<String, String> {
let conn = current(&state)?; let conn = current(&state)?;
if let Err(m) = console_guard(&args) {
return Ok(m);
}
let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
// stdin is null (p4_cmd default) so prompting commands fail fast instead of // stdin is null (p4_cmd default) so prompting commands fail fast instead of
// hanging; a failing P4EDITOR aborts editor-spawning forms (change, submit // hanging; a failing P4EDITOR aborts editor-spawning forms (change, submit
// without -d, client, …) the same way. // without -d, client, …) the same way.
let out = p4_cmd(&conn, false) let out = run_limited(p4_cmd(&conn, false).env("P4EDITOR", "cmd /c exit 1").args(&refs), P4_TIMEOUT)
.env("P4EDITOR", "cmd /c exit 1")
.args(&refs)
.output()
.map_err(|e| format!("Failed to start p4: {e}"))?; .map_err(|e| format!("Failed to start p4: {e}"))?;
let mut s = decode(&out.stdout); let mut s = decode(&out.stdout);
let err = decode(&out.stderr); let err = decode(&out.stderr);
@ -1911,22 +2062,22 @@ async fn p4_opened_all(state: State<'_, AppState>, scope: String) -> Result<Vec<
#[tauri::command] #[tauri::command]
async fn p4_lock(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> { async fn p4_lock(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
let conn = current(&state)?; let conn = current(&state)?;
let mut args: Vec<&str> = vec!["lock"]; run_batched(&conn, &["lock"], &files)
for f in &files {
args.push(f.as_str());
}
run_text(&conn, &args)
} }
/// Release locks. /// Release locks.
#[tauri::command] #[tauri::command]
async fn p4_unlock(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> { async fn p4_unlock(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
let conn = current(&state)?; let conn = current(&state)?;
let mut args: Vec<&str> = vec!["unlock"]; run_batched(&conn, &["unlock"], &files)
for f in &files { }
args.push(f.as_str());
} /// Release a lock held by someone else (`p4 unlock -f`). The server allows this
run_text(&conn, &args) /// for admin and above only.
#[tauri::command]
async fn p4_unlock_force(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
let conn = current(&state)?;
run_batched(&conn, &["unlock", "-f"], &files)
} }
/// Read the server typemap as a list of "TYPE PATTERN" entries. /// Read the server typemap as a list of "TYPE PATTERN" entries.
@ -2003,11 +2154,7 @@ async fn p4_reopen_type(state: State<'_, AppState>, files: Vec<String>, filetype
if files.is_empty() { if files.is_empty() {
return Ok(String::new()); return Ok(String::new());
} }
let mut args: Vec<&str> = vec!["reopen", "-t", &filetype]; run_batched(&conn, &["reopen", "-t", &filetype], &files)
for f in &files {
args.push(f.as_str());
}
run_text(&conn, &args)
} }
/// Extract the largest embedded PNG from a byte blob — this is how an uncooked /// Extract the largest embedded PNG from a byte blob — this is how an uncooked
@ -2076,6 +2223,7 @@ async fn uasset_thumbnail(state: State<'_, AppState>, spec: String, historical:
.next() .next()
.and_then(|v| v.get("path").and_then(|p| p.as_str()).map(String::from)) .and_then(|v| v.get("path").and_then(|p| p.as_str()).map(String::from))
.ok_or_else(|| "Could not resolve the file path".to_string())?; .ok_or_else(|| "Could not resolve the file path".to_string())?;
ensure_under_root(&conn, &local)?;
if let Ok(m) = std::fs::metadata(&local) { if let Ok(m) = std::fs::metadata(&local) {
if m.len() > MAX_UASSET { if m.len() > MAX_UASSET {
return Err("Asset too large for a thumbnail".into()); return Err("Asset too large for a thumbnail".into());
@ -2312,50 +2460,12 @@ async fn p4_shelve(state: State<'_, AppState>, change: String) -> Result<String,
#[tauri::command] #[tauri::command]
async fn p4_unshelve(state: State<'_, AppState>, change: String) -> Result<String, String> { async fn p4_unshelve(state: State<'_, AppState>, change: String) -> Result<String, String> {
let conn = current(&state)?; let conn = current(&state)?;
run_text(&conn, &["unshelve", "-s", &change, "-f"]) run_text(&conn, &["unshelve", "-s", &change])
}
/// Shelve everything the user has open in their DEFAULT changelist to the server
/// in one shot: create a numbered pending changelist, move the open files into
/// it, and `shelve` it. Returns `{ change, files }`. This is the primitive the
/// team-relay plugin drives so a coordinator can push a teammate's local work to
/// the server (as a shelf — nothing is submitted). The teammate's client runs
/// this; it uses ordinary client-side p4 commands and never touches the server
/// config. Files already parked in other numbered changelists are left alone.
#[tauri::command]
async fn p4_shelve_open(state: State<'_, AppState>, description: String) -> Result<Value, String> {
let conn = current(&state)?;
let opened = run_json(&conn, &["opened", "-c", "default"])?;
let files: Vec<String> = opened
.iter()
.filter_map(|v| v.get("depotFile").and_then(|d| d.as_str()).map(String::from))
.collect();
if files.is_empty() {
return Err("No open files in the default changelist".into());
}
let desc = if description.trim().is_empty() {
"Remote shelve (Team Relay)".to_string()
} else {
description
};
let cl = create_changelist(&conn, &desc)?;
// Move the open files into the new changelist, batched so a huge default
// changelist doesn't overflow the Windows command line.
let prefix_len = "reopen -c ".len() + cl.len();
for r in file_batches(&files, prefix_len) {
let mut args: Vec<&str> = vec!["reopen", "-c", &cl];
for f in &files[r] {
args.push(f.as_str());
}
run_text(&conn, &args)?;
}
run_text(&conn, &["shelve", "-c", &cl])?;
Ok(serde_json::json!({ "change": cl, "files": files.len() }))
} }
/// The caller's maximum protection level on this server (`p4 protects -m`), /// The caller's maximum protection level on this server (`p4 protects -m`),
/// e.g. "super" / "admin" / "write". Read-only; used to gate coordinator-only /// e.g. "super" / "admin" / "write". Read-only; decides which actions the UI
/// actions in the UI (the server still enforces the real permission). /// offers (the server still enforces the real permission).
#[tauri::command] #[tauri::command]
async fn p4_protects_max(state: State<'_, AppState>) -> Result<String, String> { async fn p4_protects_max(state: State<'_, AppState>) -> Result<String, String> {
let conn = current(&state)?; let conn = current(&state)?;
@ -2440,7 +2550,11 @@ async fn p4_annotate(state: State<'_, AppState>, spec: String) -> Result<String,
let conn = current(&state)?; let conn = current(&state)?;
let mut s = run_text(&conn, &["annotate", "-c", "-u", "-q", &spec])?; let mut s = run_text(&conn, &["annotate", "-c", "-u", "-q", &spec])?;
if s.len() > 2_000_000 { if s.len() > 2_000_000 {
s.truncate(2_000_000); let mut cut = 2_000_000;
while !s.is_char_boundary(cut) {
cut -= 1;
}
s.truncate(cut);
s.push_str("\n… (truncated)"); s.push_str("\n… (truncated)");
} }
Ok(s) Ok(s)
@ -2473,11 +2587,7 @@ async fn p4_reopen_to(state: State<'_, AppState>, change: String, files: Vec<Str
if files.is_empty() { if files.is_empty() {
return Ok(String::new()); return Ok(String::new());
} }
let mut args: Vec<&str> = vec!["reopen", "-c", &change]; run_batched(&conn, &["reopen", "-c", &change], &files)
for f in &files {
args.push(f.as_str());
}
run_text(&conn, &args)
} }
/// Newest submitted changelist in the scope — cheap poll for "new submit" toasts. /// Newest submitted changelist in the scope — cheap poll for "new submit" toasts.
@ -2590,18 +2700,23 @@ async fn p4_reconcile_apply(state: State<'_, AppState>, paths: Vec<String>) -> R
if clean.is_empty() { if clean.is_empty() {
return Err("No files selected".into()); return Err("No files selected".into());
} }
let mut args: Vec<&str> = vec!["reconcile", "-e", "-a", "-d"]; let mut applied = Vec::new();
for p in &clean { for r in file_batches(&clean, "reconcile -e -a -d ".len()) {
args.push(p.as_str()); let mut args: Vec<&str> = vec!["reconcile", "-e", "-a", "-d"];
} for p in &clean[r] {
run_json(&conn, &args).or_else(|e| { args.push(p.as_str());
let l = e.to_lowercase();
if l.contains("no file") || l.contains("up-to-date") || l.contains("no differing") {
Ok(Vec::new())
} else {
Err(e)
} }
}) match run_json(&conn, &args) {
Ok(v) => applied.extend(v),
Err(e) => {
let l = e.to_lowercase();
if !(l.contains("no file") || l.contains("up-to-date") || l.contains("no differing")) {
return Err(e);
}
}
}
}
Ok(applied)
} }
/// Toggle the read-only attribute on local working files so they can be edited /// Toggle the read-only attribute on local working files so they can be edited
@ -2884,12 +2999,8 @@ async fn p4_group_member(
Ok(decode(&res.stdout).trim().to_string()) Ok(decode(&res.stdout).trim().to_string())
} }
/// OpenRouter API key baked into the binary at compile time from the /// Path to the user's OpenRouter API key, stored in the app config dir. No key
/// git-ignored file src-tauri/openrouter.key. /// ships with the build: anything inside the binary is public.
const BAKED_AI_KEY: &str = include_str!("../openrouter.key");
/// Path to the (git-ignored) OpenRouter API key, stored in the app config dir.
/// Kept as a fallback/override location for builds without a baked key.
fn ai_key_path() -> Option<std::path::PathBuf> { fn ai_key_path() -> Option<std::path::PathBuf> {
let app = APP.get()?; let app = APP.get()?;
let dir = app.path().app_config_dir().ok()?; let dir = app.path().app_config_dir().ok()?;
@ -2897,10 +3008,6 @@ fn ai_key_path() -> Option<std::path::PathBuf> {
} }
#[tauri::command] #[tauri::command]
async fn read_ai_key() -> Result<String, String> { async fn read_ai_key() -> Result<String, String> {
let baked = BAKED_AI_KEY.trim();
if !baked.is_empty() {
return Ok(baked.to_string());
}
Ok(ai_key_path() Ok(ai_key_path()
.and_then(|p| std::fs::read_to_string(p).ok()) .and_then(|p| std::fs::read_to_string(p).ok())
.map(|s| s.trim().to_string()) .map(|s| s.trim().to_string())
@ -2970,10 +3077,8 @@ async fn plugin_list() -> Result<Vec<Value>, String> {
let Ok(m) = serde_json::from_str::<Value>(&txt) else { continue }; let Ok(m) = serde_json::from_str::<Value>(&txt) else { continue };
let id = m.get("id").and_then(|v| v.as_str()).map(String::from) let id = m.get("id").and_then(|v| v.as_str()).map(String::from)
.unwrap_or_else(|| e.file_name().to_string_lossy().to_string()); .unwrap_or_else(|| e.file_name().to_string_lossy().to_string());
// off by default unless the manifest opts in (defaultEnabled) — official // off until the user turns it on; the choice persists in enabled.json
// plugins like Unreal ship on; the user's choice persists in enabled.json let enabled = *en.get(&id).unwrap_or(&false);
let default_on = m.get("defaultEnabled").and_then(|v| v.as_bool()).unwrap_or(false);
let enabled = *en.get(&id).unwrap_or(&default_on);
out.push(serde_json::json!({ out.push(serde_json::json!({
"id": id, "id": id,
"name": m.get("name").and_then(|v| v.as_str()).unwrap_or(""), "name": m.get("name").and_then(|v| v.as_str()).unwrap_or(""),
@ -3022,10 +3127,10 @@ async fn plugin_set_enabled(id: String, enabled: bool) -> Result<(), String> {
/// this only touches the confined plugins folder (id + name are path-validated). /// this only touches the confined plugins folder (id + name are path-validated).
#[tauri::command] #[tauri::command]
async fn plugin_write_file(id: String, name: String, content: String) -> Result<(), String> { async fn plugin_write_file(id: String, name: String, content: String) -> Result<(), String> {
if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') || id.contains("..") { if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') || id.contains("..") || id.starts_with('.') {
return Err("Invalid plugin id".into()); return Err("Invalid plugin id".into());
} }
if name.is_empty() || name.contains('/') || name.contains('\\') || name.contains("..") { if name.is_empty() || name.contains('/') || name.contains('\\') || name.contains(':') || name.contains("..") {
return Err("Invalid file name".into()); return Err("Invalid file name".into());
} }
let dir = plugins_dir().ok_or("No config dir")?.join(&id); let dir = plugins_dir().ok_or("No config dir")?.join(&id);
@ -3053,12 +3158,30 @@ async fn registry_http_get(url: String) -> Result<String, String> {
resp.text().await.map_err(|e| e.to_string()) resp.text().await.map_err(|e| e.to_string())
} }
/// The relay pipe only reaches this machine and private (VPN/LAN) addresses, by
/// IP, so plugin traffic can't leave for an arbitrary internet host.
fn relay_url_allowed(url: &str) -> bool {
let Ok(u) = reqwest::Url::parse(url) else {
return false;
};
if !matches!(u.scheme(), "http" | "https") {
return false;
}
match u.host_str() {
Some("localhost") => true,
Some(host) => host
.parse::<std::net::Ipv4Addr>()
.map_or(false, |ip| ip.is_private() || ip.is_loopback()),
None => false,
}
}
/// Generic HTTP pipe for plugins that talk to a self-hosted service (e.g. the /// Generic HTTP pipe for plugins that talk to a self-hosted service (e.g. the
/// team relay on the VPN). The webview can't reach arbitrary hosts — CSP pins /// team relay on the VPN). The webview can't reach arbitrary hosts — CSP pins
/// `connect-src`, and cross-origin `fetch` hits CORS — so the plugin routes its /// `connect-src`, and cross-origin `fetch` hits CORS — so the plugin routes its
/// requests through here. This is a DUMB pipe: it has no idea what the service /// requests through here. This is a DUMB pipe: it has no idea what the service
/// is, which keeps the relay URL out of the app (the plugin holds it) and lets /// is, which keeps the relay URL out of the app (the plugin holds it) and lets
/// one primitive serve any future relay-backed plugin. http/https only; an /// one primitive serve any future relay-backed plugin. Private addresses only; an
/// optional bearer token authenticates against the caller's own service. /// optional bearer token authenticates against the caller's own service.
#[tauri::command] #[tauri::command]
async fn relay_http( async fn relay_http(
@ -3067,12 +3190,13 @@ async fn relay_http(
body: Option<String>, body: Option<String>,
token: Option<String>, token: Option<String>,
) -> Result<String, String> { ) -> Result<String, String> {
if !(url.starts_with("http://") || url.starts_with("https://")) { if !relay_url_allowed(&url) {
return Err("Relay URL must be http(s)".into()); return Err("Relay URL must be http(s) on a private network address".into());
} }
let client = reqwest::Client::builder() let client = reqwest::Client::builder()
.user_agent("ExbyteDepot") .user_agent("ExbyteDepot")
.timeout(std::time::Duration::from_secs(20)) .timeout(std::time::Duration::from_secs(20))
.redirect(reqwest::redirect::Policy::none())
.build() .build()
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let mut req = match method.to_uppercase().as_str() { let mut req = match method.to_uppercase().as_str() {
@ -3256,7 +3380,6 @@ pub fn run() {
plugin_write_file, plugin_write_file,
registry_http_get, registry_http_get,
relay_http, relay_http,
p4_shelve_open,
p4_protects_max, p4_protects_max,
plugin_install, plugin_install,
plugin_remove, plugin_remove,
@ -3280,6 +3403,7 @@ pub fn run() {
p4_opened_all, p4_opened_all,
p4_lock, p4_lock,
p4_unlock, p4_unlock,
p4_unlock_force,
p4_typemap_get, p4_typemap_get,
p4_typemap_set, p4_typemap_set,
p4_reopen_type, p4_reopen_type,

View File

@ -4,7 +4,7 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
import { getCurrentWebview } from "@tauri-apps/api/webview"; import { getCurrentWebview } from "@tauri-apps/api/webview";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { isPermissionGranted, requestPermission, sendNotification } from "@tauri-apps/plugin-notification"; import { isPermissionGranted, requestPermission, sendNotification } from "@tauri-apps/plugin-notification";
import { open as openDialog } from "@tauri-apps/plugin-dialog"; import { open as openDialog, ask as askDialog } from "@tauri-apps/plugin-dialog";
import ModelViewer from "./ModelViewer"; import ModelViewer from "./ModelViewer";
import CodeView from "./CodeView"; import CodeView from "./CodeView";
import { useUpdater } from "./Updater"; import { useUpdater } from "./Updater";
@ -584,8 +584,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
const sameUser = (o.user || "").toLowerCase() === me; const sameUser = (o.user || "").toLowerCase() === me;
const sameClient = (o.client || "").toLowerCase() === myClient; const sameClient = (o.client || "").toLowerCase() === myClient;
if (sameUser && sameClient) continue; // it's my own checkout if (sameUser && sameClient) continue; // it's my own checkout
// `p4 opened -a` includes an `ourLock` field only when the file is locked const locked = isHeld(o);
const locked = (o as Record<string, unknown>).ourLock !== undefined;
map.set(dp, { user: o.user || "?", locked }); map.set(dp, { user: o.user || "?", locked });
} }
setOthers(map); setOthers(map);
@ -646,12 +645,11 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
launch: () => { void launchUE(); }, launch: () => { void launchUE(); },
readLog: (tb?: number) => p4.ueLog(uprojectRef.current, tb ?? 200_000), readLog: (tb?: number) => p4.ueLog(uprojectRef.current, tb ?? 200_000),
}, },
// Team bridge — presence + coordinator shelve tools; plugin owns the logic // Team bridge — presence; plugin owns the logic
team: { team: {
whoami: () => (info ? { user: info.userName, client: info.clientName, root: info.clientRoot } : null), whoami: () => (info ? { user: info.userName, client: info.clientName, root: info.clientRoot } : null),
maxAccess: () => p4.protectsMax().catch(() => ""), maxAccess: () => p4.protectsMax().catch(() => ""),
openCount: () => p4.opened("").then((a) => a.length).catch(() => 0), openCount: () => p4.opened("").then((a) => a.length).catch(() => 0),
shelveOpen: (desc: string) => p4.shelveOpen(desc),
submitShelved: (change: string) => p4.submitShelved(change), submitShelved: (change: string) => p4.submitShelved(change),
relay: (url: string, method: string, body?: string, token?: string) => p4.relayHttp(url, method, body, token), relay: (url: string, method: string, body?: string, token?: string) => p4.relayHttp(url, method, body, token),
}, },
@ -1029,12 +1027,20 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
// delete a folder — marks its files for delete (reviewable), removes fresh/local ones // delete a folder — marks its files for delete (reviewable), removes fresh/local ones
async function deleteFolder(path: string) { async function deleteFolder(path: string) {
const name = splitPath(path).name || path; const name = splitPath(path).name || path;
if (!(await confirm({ title: t("Delete folder “{name}”?", { name }), body: t("Every file under this folder is marked for delete. Nothing leaves the server until you Submit; freshly-added files are removed right away."), confirm: t("Delete"), danger: true }))) return; if (!(await confirm({ title: t("Delete folder “{name}”?", { name }), body: t("Every file under this folder is marked for delete. Nothing leaves the server until you Submit. A folder with open files is refused."), confirm: t("Delete"), danger: true }))) return;
try { const r = await p4.deleteFolder(path); flash(r.length ? t("Marked {n} file(s) for delete — Submit to remove the folder.", { n: r.length }) : t("Folder removed.")); await refresh(); } try { const r = await p4.deleteFolder(path); flash(r.length ? t("Marked {n} file(s) for delete — Submit to remove the folder.", { n: r.length }) : t("Folder removed.")); await refresh(); }
catch (e) { flash(String(e), true); } catch (e) { flash(String(e), true); }
} }
// right-click on a folder in the File Tree → folder operations // right-click on a folder in the File Tree → folder operations
function folderMenu(n: FsEntry, e: ReactMouseEvent) { function folderMenu(n: FsEntry, e: ReactMouseEvent) {
if (!n.isDir) {
openCtx(e, [
{ label: t("Check out"), icon: I.lock, act: () => checkOut([n.path]) },
{ label: t("Open in Explorer"), icon: I.reveal, act: () => reveal(n.path) },
{ label: t("Copy path"), icon: I.copy, act: () => copyText(n.path, t("Path")) },
]);
return;
}
const isDepot = n.path.startsWith("//"); const isDepot = n.path.startsWith("//");
openCtx(e, [ openCtx(e, [
{ label: t("New folder / project…"), icon: I.folder, act: () => newFolder(n.path) }, { label: t("New folder / project…"), icon: I.folder, act: () => newFolder(n.path) },
@ -1310,7 +1316,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
const isCode = isCodeFile(splitPath(dp).name); const isCode = isCodeFile(splitPath(dp).name);
openCtx(e, [ openCtx(e, [
{ label: targets.length > 1 ? t("Discard changes · {n} files", { n: targets.length }) : t("Discard changes"), icon: I.trash, danger: true, act: () => discard(targets) }, { label: targets.length > 1 ? t("Discard changes · {n} files", { n: targets.length }) : t("Discard changes"), icon: I.trash, danger: true, act: () => discard(targets) },
{ label: t("Lock (exclusive)"), icon: I.lock, act: () => lockFiles(dps, true) }, { label: t("Lock against submit"), icon: I.lock, act: () => lockFiles(dps, true) },
{ label: t("Unlock"), icon: I.unlock, act: () => lockFiles(dps, false) }, { label: t("Unlock"), icon: I.unlock, act: () => lockFiles(dps, false) },
{ label: t("Set exclusive-lock type (+l)"), icon: I.lock, act: () => setExclusiveType(dps) }, { label: t("Set exclusive-lock type (+l)"), icon: I.lock, act: () => setExclusiveType(dps) },
...(workOffline ? [{ label: t("Make writable (offline edit)"), icon: I.unlock, act: () => makeWritable(targets) }] : []), ...(workOffline ? [{ label: t("Make writable (offline edit)"), icon: I.unlock, act: () => makeWritable(targets) }] : []),
@ -1327,6 +1333,15 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
try { await (lock ? p4.lock(dps) : p4.unlock(dps)); flash(lock ? t("Locked {n} file(s).", { n: dps.length }) : t("Unlocked {n} file(s).", { n: dps.length })); await refresh(); } try { await (lock ? p4.lock(dps) : p4.unlock(dps)); flash(lock ? t("Locked {n} file(s).", { n: dps.length }) : t("Unlocked {n} file(s).", { n: dps.length })); await refresh(); }
catch (e) { flash(String(e), true); } catch (e) { flash(String(e), true); }
} }
// `p4 edit`; an exclusive (+l) file held elsewhere comes back without a record
async function checkOut(paths: string[]) {
try {
const r = await p4.edit(paths);
const all = r.length >= paths.length;
flash(all ? t("{n} file(s) checked out.", { n: r.length }) : t("Checked out {n} of {total}. The rest are held by someone else.", { n: r.length, total: paths.length }), !all);
await refresh();
} catch (e) { flash(String(e), true); }
}
// switch opened files to an exclusive-lock file type (+l) so only one person edits them // switch opened files to an exclusive-lock file type (+l) so only one person edits them
async function setExclusiveType(dps: string[]) { async function setExclusiveType(dps: string[]) {
if (!dps.length) return; if (!dps.length) return;
@ -1389,6 +1404,16 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
const showBlame = (spec: string, name: string) => setModal({ kind: "blame", spec, name }); const showBlame = (spec: string, name: string) => setModal({ kind: "blame", spec, name });
async function doResolve(mode: "am" | "ay" | "at", file = "") { async function doResolve(mode: "am" | "ay" | "at", file = "") {
if (mode !== "am") {
const name = file ? splitPath(file).name : t("{n} files", { n: needResolve.length });
const theirs = mode === "at";
if (!(await confirm({
title: theirs ? t("Accept theirs for {name}?", { name }) : t("Accept yours for {name}?", { name }),
body: theirs ? t("Your local changes in these files are replaced by the server version.") : t("Changes made on the server are dropped and your version wins."),
confirm: theirs ? t("Accept theirs") : t("Accept yours"),
danger: true,
}))) return;
}
try { try {
await p4.resolveFile(file, mode); await p4.resolveFile(file, mode);
const rest = await p4.resolveList(); const rest = await p4.resolveList();
@ -2552,6 +2577,12 @@ function SearchModal({ scope, onClose, onOpenEditor, onReveal, onCopy }: { scope
} }
/* ---------------- file locks viewer — who has what locked/open across the depot ---------------- */ /* ---------------- file locks viewer — who has what locked/open across the depot ---------------- */
// held by someone: a `p4 lock`, or an open of an exclusive (+l) file type
function isHeld(f: OpenedFile): boolean {
const r = f as Record<string, unknown>;
return r.ourLock !== undefined || /\+\w*l/.test(String(r.type || ""));
}
// the File Locks list (bar + rows), reused by the modal AND the dockable panel // the File Locks list (bar + rows), reused by the modal AND the dockable panel
function LocksPanel({ me, onReveal, onFlash, onUnlock }: { me: string; onReveal: (dp: string) => void; onFlash: (t: string, e?: boolean) => void; onUnlock: (dp: string) => void }) { function LocksPanel({ me, onReveal, onFlash, onUnlock }: { me: string; onReveal: (dp: string) => void; onFlash: (t: string, e?: boolean) => void; onUnlock: (dp: string) => void }) {
const [files, setFiles] = useState<OpenedFile[]>([]); const [files, setFiles] = useState<OpenedFile[]>([]);
@ -2559,8 +2590,9 @@ function LocksPanel({ me, onReveal, onFlash, onUnlock }: { me: string; onReveal:
const [q, setQ] = useState(""); const [q, setQ] = useState("");
const [lockedOnly, setLockedOnly] = useState(true); const [lockedOnly, setLockedOnly] = useState(true);
const load = () => { setBusy(true); p4.openedAll("").then(setFiles).catch((e) => { onFlash(String(e), true); setFiles([]); }).finally(() => setBusy(false)); }; const load = () => { setBusy(true); p4.openedAll("").then(setFiles).catch((e) => { onFlash(String(e), true); setFiles([]); }).finally(() => setBusy(false)); };
useEffect(() => { load(); }, []); // eslint-disable-line const [admin, setAdmin] = useState(false);
const isLocked = (f: OpenedFile) => (f as Record<string, unknown>).ourLock !== undefined; useEffect(() => { load(); p4.protectsMax().then((a) => setAdmin(/^(admin|super)$/i.test(a))).catch(() => {}); }, []); // eslint-disable-line
const isLocked = isHeld;
const s = q.trim().toLowerCase(); const s = q.trim().toLowerCase();
const rows = files.filter((f) => (!lockedOnly || isLocked(f)) && (!s || (f.depotFile || "").toLowerCase().includes(s) || (f.user || "").toLowerCase().includes(s))); const rows = files.filter((f) => (!lockedOnly || isLocked(f)) && (!s || (f.depotFile || "").toLowerCase().includes(s) || (f.user || "").toLowerCase().includes(s)));
return ( return (
@ -2578,12 +2610,14 @@ function LocksPanel({ me, onReveal, onFlash, onUnlock }: { me: string; onReveal:
const sp = splitPath(dp); const sp = splitPath(dp);
const locked = isLocked(f); const locked = isLocked(f);
const mine = (f.user || "").toLowerCase() === me.toLowerCase(); const mine = (f.user || "").toLowerCase() === me.toLowerCase();
const hasLock = (f as Record<string, unknown>).ourLock !== undefined; // `p4 unlock` can't release a +l open
return ( return (
<div key={dp + (f.client || "")} className="srch-row"> <div key={dp + (f.client || "")} className="srch-row">
<span className={"held" + (locked ? " locked" : "")} style={{ marginRight: 4 }}>{locked ? I.lock : I.unlock}</span> <span className={"held" + (locked ? " locked" : "")} style={{ marginRight: 4 }}>{locked ? I.lock : I.unlock}</span>
<span className="srch-body"><span className="n">{sp.name}</span><span className="p">{sp.dir}</span></span> <span className="srch-body"><span className="n">{sp.name}</span><span className="p">{sp.dir}</span></span>
<span className="lk-who">{f.user}{mine ? " · " + t("you") : ""}<span className="lk-client">{f.client}</span></span> <span className="lk-who">{f.user}{mine ? " · " + t("you") : ""}<span className="lk-client">{f.client}</span></span>
{locked && mine && <button className="rslv-act" title={t("Unlock")} onClick={() => { onUnlock(dp); setTimeout(load, 400); }}>{t("Unlock")}</button>} {hasLock && mine && <button className="rslv-act" title={t("Unlock")} onClick={() => { onUnlock(dp); setTimeout(load, 400); }}>{t("Unlock")}</button>}
{hasLock && !mine && admin && <button className="rslv-act" title={t("Force unlock")} onClick={() => { p4.unlockForce([dp]).then(load).catch((e) => onFlash(String(e), true)); }}>{t("Force unlock")}</button>}
<button className="srch-act" title={t("Open in Explorer")} onClick={() => onReveal(dp)}>{I.folder}</button> <button className="srch-act" title={t("Open in Explorer")} onClick={() => onReveal(dp)}>{I.folder}</button>
</div> </div>
); );
@ -2832,7 +2866,7 @@ function ExpNode({ node, depth, load, max, onReveal, onFlash, onOpen, onMenu }:
const childMax = Math.max(1, ...(kids || []).map((k) => k.size)); const childMax = Math.max(1, ...(kids || []).map((k) => k.size));
return ( return (
<div className="exp-node"> <div className="exp-node">
<div className={"exp-row" + (node.isDir || onOpen ? " dir" : "")} style={{ paddingLeft: 10 + depth * 15 }} onClick={activate} onContextMenu={(e) => { if (node.isDir && onMenu) { e.preventDefault(); e.stopPropagation(); onMenu(node, e); } }} title={node.path}> <div className={"exp-row" + (node.isDir || onOpen ? " dir" : "")} style={{ paddingLeft: 10 + depth * 15 }} onClick={activate} onContextMenu={(e) => { if (onMenu) { e.preventDefault(); e.stopPropagation(); onMenu(node, e); } }} title={node.path}>
<span className="exp-caret">{node.isDir ? (busy ? <span className="ldr sm" /> : <span className={"chevi" + (open ? " open" : "")}>{I.chevron}</span>) : null}</span> <span className="exp-caret">{node.isDir ? (busy ? <span className="ldr sm" /> : <span className={"chevi" + (open ? " open" : "")}>{I.chevron}</span>) : null}</span>
<span className="exp-ic">{node.isDir ? I.folder : FILE_GLYPH}</span> <span className="exp-ic">{node.isDir ? I.folder : FILE_GLYPH}</span>
<span className="exp-name">{node.name}</span> <span className="exp-name">{node.name}</span>
@ -3391,8 +3425,10 @@ function PluginsModal({ onClose, onReload, onFlash, embedded }: { onClose?: () =
const loadReg = () => { setRegBusy(true); setRegErr(""); fetchRegistry().then(setReg).catch((e) => setRegErr(String(e))).finally(() => setRegBusy(false)); }; const loadReg = () => { setRegBusy(true); setRegErr(""); fetchRegistry().then(setReg).catch((e) => setRegErr(String(e))).finally(() => setRegBusy(false)); };
useEffect(() => { load(); loadReg(); p4.pluginsDirPath().then(setDir).catch(() => {}); const k = (e: KeyboardEvent) => e.key === "Escape" && onClose?.(); document.addEventListener("keydown", k); return () => document.removeEventListener("keydown", k); }, []); // eslint-disable-line useEffect(() => { load(); loadReg(); p4.pluginsDirPath().then(setDir).catch(() => {}); const k = (e: KeyboardEvent) => e.key === "Escape" && onClose?.(); document.addEventListener("keydown", k); return () => document.removeEventListener("keydown", k); }, []); // eslint-disable-line
async function installReg(entry: RegistryEntry) { async function installReg(entry: RegistryEntry) {
const perms = (entry.permissions || []).join(", ") || "—";
if (!(await askDialog(t("A plugin runs with full access to this app, including your Perforce session. Declared permissions: {perms}.", { perms }), { title: t("Install plugin “{name}”?", { name: entry.name }), kind: "warning" }))) return;
setInstalling(entry.id); setInstalling(entry.id);
try { await installFromRegistry(entry); load(); await onReload(); onFlash(t("Installed plugin “{id}”.", { id: entry.name })); } try { await installFromRegistry(entry); await p4.pluginSetEnabled(entry.id, true); load(); await onReload(); onFlash(t("Installed plugin “{id}”.", { id: entry.name })); }
catch (e) { onFlash(String(e), true); } catch (e) { onFlash(String(e), true); }
finally { setInstalling(""); } finally { setInstalling(""); }
} }

View File

@ -9,7 +9,7 @@ function langName(): string { return LANG_NAMES[LANG] || "English"; }
// fixed model — no user-facing AI settings // fixed model — no user-facing AI settings
export const DEFAULT_MODEL = "openai/gpt-4o-mini"; export const DEFAULT_MODEL = "openai/gpt-4o-mini";
// the key is baked into the binary at build time (src-tauri/openrouter.key) // the key lives in the app config dir (openrouter.key); none ships with the build
export async function resolveKey(): Promise<string> { export async function resolveKey(): Promise<string> {
try { return (await p4.readAiKey()) || ""; } catch { return ""; } try { return (await p4.readAiKey()) || ""; } catch { return ""; }
} }
@ -17,7 +17,7 @@ export async function resolveKey(): Promise<string> {
// generate a commit summary + description from the changed files // generate a commit summary + description from the changed files
export async function aiSummary(files: OpenedFile[]): Promise<{ summary: string; description: string }> { export async function aiSummary(files: OpenedFile[]): Promise<{ summary: string; description: string }> {
const key = await resolveKey(); const key = await resolveKey();
if (!key) throw new Error("No OpenRouter API key baked into this build"); if (!key) throw new Error("No OpenRouter API key configured");
const list = files.slice(0, 200).map((f) => `${statusOf(f.action).ch} ${f.depotFile || ""}`).join("\n"); const list = files.slice(0, 200).map((f) => `${statusOf(f.action).ch} ${f.depotFile || ""}`).join("\n");
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", { const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST", method: "POST",
@ -48,7 +48,7 @@ export async function aiSummary(files: OpenedFile[]): Promise<{ summary: string;
// briefly explain what a source file does (2–4 sentences, plain text) // briefly explain what a source file does (2–4 sentences, plain text)
export async function aiExplainCode(name: string, code: string): Promise<string> { export async function aiExplainCode(name: string, code: string): Promise<string> {
const key = await resolveKey(); const key = await resolveKey();
if (!key) throw new Error("No OpenRouter API key baked into this build"); if (!key) throw new Error("No OpenRouter API key configured");
const snippet = code.slice(0, 14000); // cap the payload const snippet = code.slice(0, 14000); // cap the payload
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", { const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST", method: "POST",

View File

@ -403,6 +403,20 @@ const D: Record<string, Tr> = {
// collaboration / advanced perforce // collaboration / advanced perforce
"Lock (exclusive)": { ru: "Заблокировать (эксклюзивно)", de: "Sperren (exklusiv)", fr: "Verrouiller (exclusif)", es: "Bloquear (exclusivo)" }, "Lock (exclusive)": { ru: "Заблокировать (эксклюзивно)", de: "Sperren (exklusiv)", fr: "Verrouiller (exclusif)", es: "Bloquear (exclusivo)" },
"Unlock": { ru: "Разблокировать", de: "Entsperren", fr: "Déverrouiller", es: "Desbloquear" }, "Unlock": { ru: "Разблокировать", de: "Entsperren", fr: "Déverrouiller", es: "Desbloquear" },
"Force unlock": { ru: "Снять чужую блокировку", de: "Entsperren erzwingen", fr: "Forcer le déverrouillage", es: "Forzar desbloqueo" },
"Lock against submit": { ru: "Запретить submit другим", de: "Submit für andere sperren", fr: "Bloquer le submit des autres", es: "Bloquear el submit de otros" },
"Check out": { ru: "Взять в работу", de: "Auschecken", fr: "Extraire", es: "Extraer" },
"{n} file(s) checked out.": { ru: "Взято в работу файлов: {n}.", de: "{n} Datei(en) ausgecheckt.", fr: "{n} fichier(s) extrait(s).", es: "{n} archivo(s) extraído(s)." },
"Checked out {n} of {total}. The rest are held by someone else.": { ru: "Взято в работу {n} из {total}. Остальные заняты другими.", de: "{n} von {total} ausgecheckt. Der Rest ist von anderen belegt.", fr: "{n} sur {total} extraits. Le reste est tenu par d'autres.", es: "{n} de {total} extraídos. El resto lo tienen otros." },
"Accept theirs for {name}?": { ru: "Принять серверную версию: {name}?", de: "Server-Version für {name} übernehmen?", fr: "Accepter la version serveur pour {name} ?", es: "¿Aceptar la versión del servidor para {name}?" },
"Accept yours for {name}?": { ru: "Оставить свою версию: {name}?", de: "Eigene Version für {name} behalten?", fr: "Garder votre version pour {name} ?", es: "¿Conservar tu versión para {name}?" },
"Your local changes in these files are replaced by the server version.": { ru: "Ваши локальные правки в этих файлах будут заменены серверной версией.", de: "Ihre lokalen Änderungen werden durch die Server-Version ersetzt.", fr: "Vos modifications locales sont remplacées par la version serveur.", es: "Tus cambios locales se sustituyen por la versión del servidor." },
"Changes made on the server are dropped and your version wins.": { ru: "Изменения с сервера будут отброшены, останется ваша версия.", de: "Änderungen vom Server werden verworfen, Ihre Version bleibt.", fr: "Les modifications du serveur sont ignorées, votre version l'emporte.", es: "Los cambios del servidor se descartan y prevalece tu versión." },
"Accept theirs": { ru: "Принять серверную", de: "Server-Version übernehmen", fr: "Accepter le serveur", es: "Aceptar servidor" },
"Accept yours": { ru: "Оставить свою", de: "Eigene behalten", fr: "Garder la vôtre", es: "Conservar la tuya" },
"Every file under this folder is marked for delete. Nothing leaves the server until you Submit. A folder with open files is refused.": { ru: "Все файлы в этой папке будут помечены на удаление. С сервера ничего не исчезнет до Submit. Папку с открытыми файлами удалить нельзя.", de: "Alle Dateien im Ordner werden zum Löschen markiert. Vor dem Submit verschwindet nichts vom Server. Ordner mit geöffneten Dateien werden abgelehnt.", fr: "Tous les fichiers du dossier sont marqués pour suppression. Rien ne quitte le serveur avant le Submit. Un dossier avec des fichiers ouverts est refusé.", es: "Todos los archivos de la carpeta se marcan para eliminar. Nada sale del servidor hasta el Submit. Una carpeta con archivos abiertos se rechaza." },
"Install plugin “{name}”?": { ru: "Установить плагин «{name}»?", de: "Plugin „{name}“ installieren?", fr: "Installer le plugin « {name} » ?", es: "¿Instalar el plugin «{name}»?" },
"A plugin runs with full access to this app, including your Perforce session. Declared permissions: {perms}.": { ru: "Плагин работает с полным доступом к приложению, включая вашу сессию Perforce. Заявленные разрешения: {perms}.", de: "Ein Plugin läuft mit vollem Zugriff auf diese App, auch auf Ihre Perforce-Sitzung. Angegebene Berechtigungen: {perms}.", fr: "Un plugin s'exécute avec un accès complet à l'application, y compris votre session Perforce. Autorisations déclarées : {perms}.", es: "Un plugin se ejecuta con acceso total a la app, incluida tu sesión de Perforce. Permisos declarados: {perms}." },
"Locked {n} file(s).": { ru: "Заблокировано файлов: {n}.", de: "{n} Datei(en) gesperrt.", fr: "{n} fichier(s) verrouillé(s).", es: "{n} archivo(s) bloqueado(s)." }, "Locked {n} file(s).": { ru: "Заблокировано файлов: {n}.", de: "{n} Datei(en) gesperrt.", fr: "{n} fichier(s) verrouillé(s).", es: "{n} archivo(s) bloqueado(s)." },
"Unlocked {n} file(s).": { ru: "Разблокировано файлов: {n}.", de: "{n} Datei(en) entsperrt.", fr: "{n} fichier(s) déverrouillé(s).", es: "{n} archivo(s) desbloqueado(s)." }, "Unlocked {n} file(s).": { ru: "Разблокировано файлов: {n}.", de: "{n} Datei(en) entsperrt.", fr: "{n} fichier(s) déverrouillé(s).", es: "{n} archivo(s) desbloqueado(s)." },
"Locked by {u}": { ru: "Заблокировал {u}", de: "Gesperrt von {u}", fr: "Verrouillé par {u}", es: "Bloqueado por {u}" }, "Locked by {u}": { ru: "Заблокировал {u}", de: "Gesperrt von {u}", fr: "Verrouillé par {u}", es: "Bloqueado por {u}" },

View File

@ -144,8 +144,6 @@ export const p4 = {
relayHttp: (url: string, method: string, body?: string, token?: string) => relayHttp: (url: string, method: string, body?: string, token?: string) =>
invoke<string>("relay_http", { url, method, body, token }), invoke<string>("relay_http", { url, method, body, token }),
// shelve everything open in the default changelist → { change, files } // shelve everything open in the default changelist → { change, files }
shelveOpen: (description: string) =>
invoke<{ change: string; files: number }>("p4_shelve_open", { description }),
// caller's max protection level on the server (super/admin/write/…) // caller's max protection level on the server (super/admin/write/…)
protectsMax: () => invoke<string>("p4_protects_max"), protectsMax: () => invoke<string>("p4_protects_max"),
pluginInstall: (src: string) => invoke<string>("plugin_install", { src }), pluginInstall: (src: string) => invoke<string>("plugin_install", { src }),
@ -194,6 +192,7 @@ export const p4 = {
openedAll: (scope = "") => invoke<OpenedFile[]>("p4_opened_all", { scope }), openedAll: (scope = "") => invoke<OpenedFile[]>("p4_opened_all", { scope }),
lock: (files: string[]) => invoke<string>("p4_lock", { files }), lock: (files: string[]) => invoke<string>("p4_lock", { files }),
unlock: (files: string[]) => invoke<string>("p4_unlock", { files }), unlock: (files: string[]) => invoke<string>("p4_unlock", { files }),
unlockForce: (files: string[]) => invoke<string>("p4_unlock_force", { files }),
typemapGet: () => invoke<string[]>("p4_typemap_get"), typemapGet: () => invoke<string[]>("p4_typemap_get"),
typemapSet: (entries: string[]) => invoke<string>("p4_typemap_set", { entries }), typemapSet: (entries: string[]) => invoke<string>("p4_typemap_set", { entries }),
reopenType: (files: string[], filetype: string) => invoke<string>("p4_reopen_type", { files, filetype }), reopenType: (files: string[], filetype: string) => invoke<string>("p4_reopen_type", { files, filetype }),

View File

@ -51,7 +51,6 @@ export interface TeamBridge {
whoami: () => { user?: string; client?: string; root?: string } | null; whoami: () => { user?: string; client?: string; root?: string } | null;
maxAccess: () => Promise<string>; // "super" | "admin" | "write" | … maxAccess: () => Promise<string>; // "super" | "admin" | "write" | …
openCount: () => Promise<number>; // files open in this workspace openCount: () => Promise<number>; // files open in this workspace
shelveOpen: (desc: string) => Promise<{ change: string; files: number }>;
submitShelved: (change: string) => Promise<string>; submitShelved: (change: string) => Promise<string>;
// dumb HTTP pipe to the configured relay (backend does the request; no CORS) // dumb HTTP pipe to the configured relay (backend does the request; no CORS)
relay: (url: string, method: string, body?: string, token?: string) => Promise<string>; relay: (url: string, method: string, body?: string, token?: string) => Promise<string>;
@ -191,37 +190,52 @@ export async function runSubmitHooks(files: { depotFile?: string }[]): Promise<S
// then hands each file to the backend to write into the plugins folder. // then hands each file to the backend to write into the plugins folder.
export const REGISTRY_URL = "https://gitea.exbytestudios.com/ExbytePublicServices/exbyte-depot-plugins/raw/branch/main/registry.json"; export const REGISTRY_URL = "https://gitea.exbytestudios.com/ExbytePublicServices/exbyte-depot-plugins/raw/branch/main/registry.json";
// Ed25519 key that signs registry.json (published as registry.json.sig). The registry
// pins every plugin file by SHA-256, so the branch alone can't change what gets installed.
const REGISTRY_PUBKEY = "xFys0cQSGc06fZ8LfwsZAjLgmVYqW4nQxkJhXVmUEoM=";
const fromB64 = (s: string) => Uint8Array.from(atob(s.trim()), (c) => c.charCodeAt(0));
async function verifyRegistry(text: string, signature: string): Promise<void> {
const key = await crypto.subtle.importKey("raw", fromB64(REGISTRY_PUBKEY), { name: "Ed25519" }, false, ["verify"]);
const ok = await crypto.subtle.verify({ name: "Ed25519" }, key, fromB64(signature), new TextEncoder().encode(text));
if (!ok) throw new Error("Plugin registry signature is invalid");
}
async function sha256Hex(text: string): Promise<string> {
const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
}
export interface RegistryEntry { export interface RegistryEntry {
id: string; name: string; version: string; author?: string; description?: string; id: string; name: string; version: string; author?: string; description?: string;
permissions?: string[]; minAppVersion?: string; official?: boolean; autoInstall?: boolean; permissions?: string[]; minAppVersion?: string; official?: boolean; autoInstall?: boolean;
files: string[]; baseUrl: string; files: string[]; baseUrl: string; sha256?: Record<string, string>;
} }
// All registry HTTP goes through the Rust backend (registryHttpGet): the webview // All registry HTTP goes through the Rust backend (registryHttpGet): the webview
// `fetch()` is blocked by CORS because Gitea's raw endpoint sends no ACAO header. // `fetch()` is blocked by CORS because Gitea's raw endpoint sends no ACAO header.
export async function fetchRegistry(): Promise<RegistryEntry[]> { export async function fetchRegistry(): Promise<RegistryEntry[]> {
const txt = await p4.registryHttpGet(REGISTRY_URL); const [txt, sig] = await Promise.all([p4.registryHttpGet(REGISTRY_URL), p4.registryHttpGet(REGISTRY_URL + ".sig")]);
await verifyRegistry(txt, sig);
const j = JSON.parse(txt); const j = JSON.parse(txt);
return Array.isArray(j.plugins) ? (j.plugins as RegistryEntry[]).filter((p) => p && p.id && Array.isArray(p.files)) : []; return Array.isArray(j.plugins) ? (j.plugins as RegistryEntry[]).filter((p) => p && p.id && Array.isArray(p.files)) : [];
} }
/** Download a registry plugin's files (backend HTTPS) and write them into the plugins folder. */ /** Download a registry plugin's files (backend HTTPS) and write them into the plugins folder. */
export async function installFromRegistry(entry: RegistryEntry): Promise<void> { export async function installFromRegistry(entry: RegistryEntry): Promise<void> {
// nothing is written until every file matches the signed registry
const files: [string, string][] = [];
for (const f of entry.files) { for (const f of entry.files) {
const text = await p4.registryHttpGet(entry.baseUrl + f); const text = await p4.registryHttpGet(entry.baseUrl + f);
await p4.pluginWriteFile(entry.id, f, text); const pinned = entry.sha256?.[f];
if (!pinned || (await sha256Hex(text)) !== pinned) throw new Error(`${f} doesn't match the signed registry`);
files.push([f, text]);
} }
} // the catalog shows entry.permissions, so the manifest that takes effect must agree with it
const manifest = JSON.parse(files.find(([f]) => f === "plugin.json")?.[1] ?? "{}");
/** Install any official plugins marked autoInstall that aren't installed yet. Silent on network failure. */ const declared = [...(manifest.permissions || [])].sort().join();
export async function autoInstallOfficial(installedIds: Set<string>): Promise<string[]> { if (manifest.id !== entry.id || declared !== [...(entry.permissions || [])].sort().join()) {
let reg: RegistryEntry[] = []; throw new Error("plugin.json doesn't match the registry entry");
try { reg = await fetchRegistry(); } catch { return []; }
const done: string[] = [];
for (const e of reg) {
if (e.autoInstall && !installedIds.has(e.id)) {
try { await installFromRegistry(e); done.push(e.id); } catch { /* offline / transient — try next launch */ }
}
} }
return done; for (const [f, text] of files) await p4.pluginWriteFile(entry.id, f, text);
} }