From 282b061c76996f548262b1341523f0cb79403c7f Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Wed, 18 Nov 2026 22:39:35 +0700 Subject: [PATCH 01/32] style(dash): call observability's request logs just logs --- dash/src/components/shell/AppShell.tsx | 2 +- dash/src/components/shell/nav.ts | 2 +- dash/src/routes/_app/$team/observability.tsx | 2 +- dash/src/routes/_app/$team/observability/logs.tsx | 4 ++-- dash/src/routes/_app/_settings/observability.tsx | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/dash/src/components/shell/AppShell.tsx b/dash/src/components/shell/AppShell.tsx index fe3993c..5c802d8 100644 --- a/dash/src/components/shell/AppShell.tsx +++ b/dash/src/components/shell/AppShell.tsx @@ -649,7 +649,7 @@ export function crumbsFor(pathname: string, s: PyoState): Crumb[] { // Observability's logs are the gateway's request logs, not a service's. if (b) out.push({ - label: a === "observability" && b === "logs" ? "Request logs" : (TAB_LABELS[b] ?? b), + label: a === "observability" && b === "logs" ? "Logs" : (TAB_LABELS[b] ?? b), href: pathname, }); } diff --git a/dash/src/components/shell/nav.ts b/dash/src/components/shell/nav.ts index 19fcdc1..55d204c 100644 --- a/dash/src/components/shell/nav.ts +++ b/dash/src/components/shell/nav.ts @@ -76,7 +76,7 @@ export const NAV_GROUPS: { label?: string; items: NavItem[] }[] = [ icon: PulseIcon, children: [ { label: "Analytics", href: "/observability/analytics", match: ["/observability"] }, - { label: "Request logs", href: "/observability/logs" }, + { label: "Logs", href: "/observability/logs" }, { label: "Activity", href: "/activity" }, ], }, diff --git a/dash/src/routes/_app/$team/observability.tsx b/dash/src/routes/_app/$team/observability.tsx index 05222cc..5f2b3d6 100644 --- a/dash/src/routes/_app/$team/observability.tsx +++ b/dash/src/routes/_app/$team/observability.tsx @@ -19,7 +19,7 @@ function ObservabilityLayout() { - {pathname === "/observability/logs" ? "Request logs" : "Analytics"} + {pathname === "/observability/logs" ? "Logs" : "Analytics"} diff --git a/dash/src/routes/_app/$team/observability/logs.tsx b/dash/src/routes/_app/$team/observability/logs.tsx index 25c4031..a15ebfa 100644 --- a/dash/src/routes/_app/$team/observability/logs.tsx +++ b/dash/src/routes/_app/$team/observability/logs.tsx @@ -47,7 +47,7 @@ export const Route = createFileRoute("/_app/$team/observability/logs")({ method: z.string().optional(), q: z.string().optional(), }), - head: () => ({ meta: seo({ title: "Request logs" }) }), + head: () => ({ meta: seo({ title: "Logs" }) }), component: LogsPage, }); @@ -429,7 +429,7 @@ function Tail({ setZoomed(false)} - label="Request logs" + label="Logs" >
diff --git a/dash/src/routes/_app/_settings/observability.tsx b/dash/src/routes/_app/_settings/observability.tsx index bb1ef5d..8c73014 100644 --- a/dash/src/routes/_app/_settings/observability.tsx +++ b/dash/src/routes/_app/_settings/observability.tsx @@ -4,7 +4,7 @@ import { SettingsSection } from "../_settings"; export const Route = createFileRoute("/_app/_settings/observability")({ component: () => ( - + ), From 5a2b0b1137d20efdcd10d5abd1b6a90643c8125a Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Wed, 18 Nov 2026 23:21:16 +0700 Subject: [PATCH 02/32] feat(api): set up tailscale from one api access token An admin pastes a short-lived Tailscale API access token and Pyo does the tailnet setup itself. planTailscaleSetup reads the tailnet and says what's missing without changing anything. setUpTailscale then turns on MagicDNS and HTTPS certificates, adds tag:pyo to the policy (and a grant or autoApprovers when needed), creates Pyo's own OAuth client with the scopes the manual path asks for, saves it like a pasted one, and deletes the token last. The policy is HuJSON and is edited in place with jsonc-parser's CST, so comments and formatting stay. It's validated, then written with If-Match, and read again once on a 412. A policy managed in Git is never written: the plan returns the lines to add. A tailnet that's already set up gets no changes. The token is kept in memory for the one request: it's never stored, logged or put in an error. Both operations are for admins in the dashboard only, so API keys and MCP can't run them. --- Cargo.lock | 1 + crates/pyo-api/Cargo.toml | 2 + crates/pyo-api/src/lib.rs | 1 + crates/pyo-api/src/ops.rs | 34 + crates/pyo-api/src/tailscale.rs | 8 +- crates/pyo-api/src/tailscale_setup.rs | 965 ++++++++++++++++++++ crates/pyo-api/src/tailscale_setup/tests.rs | 957 +++++++++++++++++++ 7 files changed, 1964 insertions(+), 4 deletions(-) create mode 100644 crates/pyo-api/src/tailscale_setup.rs create mode 100644 crates/pyo-api/src/tailscale_setup/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 6ae052a..a1cbfad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3393,6 +3393,7 @@ dependencies = [ "hyper-util", "instant-acme", "jiff", + "jsonc-parser", "jsonwebtoken", "lettre", "libc", diff --git a/crates/pyo-api/Cargo.toml b/crates/pyo-api/Cargo.toml index 43ab97a..3203c02 100644 --- a/crates/pyo-api/Cargo.toml +++ b/crates/pyo-api/Cargo.toml @@ -18,6 +18,8 @@ hmac = "0.13.0" hyper = { version = "1.12.0", features = ["client", "http1"] } hyper-util = { version = "0.1.21", features = ["tokio"] } jiff = "0.2.38" +# Tailscale's policy file is HuJSON: edited in place, comments kept. +jsonc-parser = { version = "0.34.0", features = ["cst", "serde"] } jsonwebtoken = { version = "11.1.0", default-features = false, features = ["use_pem", "aws_lc_rs"] } lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "hostname", "tokio1", "tokio1-rustls", "aws-lc-rs", "rustls-native-certs"] } libc = "0.2.191" diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index ec8dae4..2de4eec 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -64,6 +64,7 @@ mod sigstore; mod sites; mod snapshot; mod tailscale; +mod tailscale_setup; mod teambackup; mod template_source; mod terminal; diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 14d6161..79e31e5 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -2618,6 +2618,18 @@ pub(crate) enum Op { client_id: String, secret: Option, }, + /// See what setting up Tailscale with an API access token would change (admins only). Nothing changes yet. + PlanTailscaleSetup { + /// An API access token from the Tailscale console's Keys page. Used for this request only and never stored. + #[schema(value_type = String)] + token: crate::tailscale_setup::Token, + }, + /// Set up Tailscale with an API access token (admins only): MagicDNS, HTTPS certificates, tag:pyo in the tailnet policy, and an OAuth client of Pyo's own. Pyo deletes the token when it's done. + SetUpTailscale { + /// An API access token from the Tailscale console's Keys page. Used for this request only and never stored. + #[schema(value_type = String)] + token: crate::tailscale_setup::Token, + }, /// Check the saved Tailscale OAuth client again, scope by scope. TestTailscale {}, /// Forget the Tailscale OAuth client. Pyo's names on your tailnet are deleted. Servers stay on it. @@ -2847,6 +2859,8 @@ pub(crate) fn key_access_for(op: &Op) -> Option { | Op::GithubManifest { .. } | Op::RemoveGithubApp {} | Op::SaveTailscale { .. } + | Op::PlanTailscaleSetup { .. } + | Op::SetUpTailscale { .. } | Op::TestTailscale {} | Op::RemoveTailscale {} | Op::RenameTailscaleName { .. } @@ -2989,6 +3003,8 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::TestGitConnection { .. } | Op::RemoveGitConnection { .. } => ("Git providers", "gitc"), Op::SaveTailscale { .. } + | Op::PlanTailscaleSetup { .. } + | Op::SetUpTailscale { .. } | Op::TestTailscale {} | Op::RemoveTailscale {} | Op::RenameTailscaleName { .. } => ("Integrations", ""), @@ -7201,6 +7217,24 @@ async fn apply( log_setting(tx, user, "tailscale", "Connected Tailscale").await?; Ok(out) } + Op::PlanTailscaleSetup { token } => { + require_admin(user)?; + crate::tailscale_setup::plan(s, token).await + } + Op::SetUpTailscale { token } => { + require_admin(user)?; + let out = crate::tailscale_setup::apply(s, token).await?; + if !out.changed.is_empty() { + log_setting( + tx, + user, + "tailscale", + "Set up Tailscale with an access token", + ) + .await?; + } + Ok(serde_json::to_value(out).map_err(anyhow::Error::from)?) + } Op::TestTailscale {} => { require_admin(user)?; crate::tailscale::test_saved(s).await diff --git a/crates/pyo-api/src/tailscale.rs b/crates/pyo-api/src/tailscale.rs index 9d90622..87735f3 100644 --- a/crates/pyo-api/src/tailscale.rs +++ b/crates/pyo-api/src/tailscale.rs @@ -25,7 +25,7 @@ use sqlx::PgPool; use crate::AppState; use crate::error::{ApiError, ApiResult}; -const API: &str = "https://api.tailscale.com/api/v2"; +pub(crate) const API: &str = "https://api.tailscale.com/api/v2"; /// The tag Pyo's servers and Services carry. pub const TAG: &str = "tag:pyo"; /// Names Pyo keeps for itself: services' domains can't take them. @@ -94,7 +94,7 @@ pub fn marker(install: &str) -> String { // ── The API ───────────────────────────────────────────────────────────────── -fn http() -> &'static reqwest::Client { +pub(crate) fn http() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); C.get_or_init(|| { reqwest::Client::builder() @@ -202,7 +202,7 @@ impl std::fmt::Display for TsError { impl std::error::Error for TsError {} impl Client { - async fn access_token(&self) -> anyhow::Result { + pub(crate) async fn access_token(&self) -> anyhow::Result { if let Some((t, at)) = self.token.lock().unwrap_or_else(|e| e.into_inner()).clone() && at.elapsed() < Duration::from_secs(45 * 60) { @@ -490,7 +490,7 @@ impl Client { /// What Tailscale takes as a key's description: letters, digits, spaces, /// dashes and underscores, at most 50 characters. "Pyo: join web-1" /// becomes "Pyo join web-1". -fn key_description(s: &str) -> String { +pub(crate) fn key_description(s: &str) -> String { let kept: String = s .chars() .filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) diff --git a/crates/pyo-api/src/tailscale_setup.rs b/crates/pyo-api/src/tailscale_setup.rs new file mode 100644 index 0000000..b227f08 --- /dev/null +++ b/crates/pyo-api/src/tailscale_setup.rs @@ -0,0 +1,965 @@ +//! Setting up Tailscale from one API access token (Integrations › Tailscale). +//! +//! An admin pastes a short-lived API access token (Settings › Keys in the +//! Tailscale console). [`plan`] reads the tailnet and says what's missing, +//! changing nothing. [`apply`] then makes those changes: +//! +//! - **MagicDNS** and **HTTPS certificates** on. +//! - **The policy**: `tag:pyo` in `tagOwners`, a grant to reach it on ports +//! 80 and 443 when the policy doesn't allow that already, and +//! `autoApprovers.services` for it. The policy is HuJSON and is edited in +//! place, so its comments and formatting stay. It's validated first and +//! written with `If-Match`, so a change made meanwhile is never lost. +//! - **Pyo's own OAuth client**, with the scopes the manual path asks for, +//! saved and checked like one pasted by hand ([`crate::tailscale::save_client`]). +//! - **The pasted token is deleted** last, once nothing else needs it. +//! +//! The token lives in memory for one request only: it's never stored, +//! logged or put in an error ([`Token`], [`Api::scrub`]). A tailnet that's +//! already set up gets no changes. A policy managed in Git isn't written: +//! the lines to add come back instead. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use zeroize::Zeroize; + +use crate::AppState; +use crate::error::{ApiError, ApiResult}; +use crate::tailscale::{TAG, TsError}; + +/// The scopes Pyo's own client gets: what the manual path asks for. +const SCOPES: [&str; 3] = ["devices:core", "auth_keys", "services"]; +/// Who may apply tag:pyo by hand (Owners, Admins and Network admins can anyway). +const OWNERS: &str = "autogroup:admin"; + +const BAD_TOKEN: &str = + "Tailscale didn't accept the token. It may be wrong or expired. Generate a new one."; +const NOT_ADMIN: &str = + "That token can't change your tailnet's settings. Use a token from a tailnet Owner or Admin."; +const DELETE_TOKEN: &str = "Delete the token under Settings › Keys in the Tailscale console. It expires within a day anyway."; + +// ── The token ─────────────────────────────────────────────────────────────── + +/// A pasted API access token. It never prints, and is wiped when dropped. +#[derive(Deserialize)] +#[serde(transparent)] +pub struct Token(String); + +impl Token { + #[cfg(test)] + pub fn new(s: &str) -> Self { + Self(s.to_owned()) + } + + /// The key ID in "tskey-api--": what deletes it. + fn key_id(&self) -> Option<&str> { + let id = self.0.strip_prefix("tskey-api-")?.split('-').next()?; + (!id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric())).then_some(id) + } +} + +impl std::fmt::Debug for Token { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Token(•••)") + } +} + +impl Drop for Token { + fn drop(&mut self) { + self.0.zeroize(); + } +} + +/// The token's first check: the shape of an API access token. +fn check_shape(t: &Token) -> Result<(), String> { + let s = t.0.trim(); + if s.starts_with("tskey-client-") { + return Err("That's an OAuth client secret. Paste an API access token, or set up with an OAuth client instead.".into()); + } + if s.starts_with("tskey-auth-") { + return Err( + "That's an auth key. Paste an API access token. It starts with tskey-api-.".into(), + ); + } + if !s.starts_with("tskey-api-") || s.len() < 20 || s.contains(char::is_whitespace) { + return Err("Paste an API access token. It starts with tskey-api-.".into()); + } + Ok(()) +} + +// ── Tailscale's API, as the token's admin ─────────────────────────────────── + +/// What goes in a request. +enum Body { + None, + Json(Value), + HuJson(String), +} + +struct Reply { + text: String, + etag: Option, +} + +impl Reply { + fn json(&self) -> Value { + serde_json::from_str(&self.text).unwrap_or(Value::Null) + } +} + +/// Tailscale's API with the pasted token. +pub struct Api { + base: String, + token: Token, +} + +impl Api { + pub fn new(token: Token) -> Self { + Self::at(crate::tailscale::API, token) + } + + fn at(base: &str, mut token: Token) -> Self { + let t = token.0.trim().to_owned(); + token.0.zeroize(); + token.0 = t; + Self { + base: base.trim_end_matches('/').to_owned(), + token, + } + } + + /// `s` with the token taken out, whatever Tailscale or the network said. + fn scrub(&self, s: &str) -> String { + let mut out = s.replace(&self.token.0, "•••"); + // Its secret part alone, too. + if let Some(secret) = self.token.0.rsplit('-').next().filter(|x| x.len() >= 8) { + out = out.replace(secret, "•••"); + } + out + } + + async fn send( + &self, + method: reqwest::Method, + path: &str, + body: Body, + headers: &[(&str, &str)], + ) -> Result { + let mut req = crate::tailscale::http() + .request(method, format!("{}{path}", self.base)) + .bearer_auth(&self.token.0); + for (k, v) in headers { + req = req.header(*k, *v); + } + req = match body { + Body::None => req, + Body::Json(v) => req.json(&v), + Body::HuJson(t) => req + .header(reqwest::header::CONTENT_TYPE, "application/hujson") + .body(t), + }; + let r = req.send().await.map_err(|e| TsError { + status: 0, + message: self.scrub(&format!("Couldn't reach Tailscale: {}", e.without_url())), + })?; + let status = r.status().as_u16(); + let etag = r + .headers() + .get(reqwest::header::ETAG) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + let text = r.text().await.unwrap_or_default(); + if !(200..300).contains(&status) { + let message = serde_json::from_str::(&text) + .ok() + .and_then(|v| v["message"].as_str().map(str::to_owned)) + .unwrap_or_else(|| text.trim().chars().take(300).collect()); + return Err(TsError { + status, + message: self.scrub(&message), + }); + } + Ok(Reply { text, etag }) + } + + async fn get(&self, path: &str) -> Result { + Ok(self + .send(reqwest::Method::GET, path, Body::None, &[]) + .await? + .json()) + } + + /// The policy file as written, and its ETag. + async fn policy(&self) -> Result<(String, Option), TsError> { + let r = self + .send( + reqwest::Method::GET, + "/tailnet/-/acl", + Body::None, + &[("accept", "application/hujson")], + ) + .await?; + Ok((r.text, r.etag)) + } +} + +/// A plain sentence for what went wrong while Pyo tried `what` ("read your +/// tailnet policy"). +fn say(e: &TsError, what: &str) -> String { + match e.status { + 401 => BAD_TOKEN.into(), + 403 => NOT_ADMIN.into(), + 0 => e.message.clone(), + _ => { + let m = e.message.trim().trim_end_matches('.'); + if m.is_empty() { + format!("Couldn't {what}. Tailscale answered {}.", e.status) + } else { + format!("Couldn't {what}. Tailscale said: {m}.") + } + } + } +} + +// ── The policy ────────────────────────────────────────────────────────────── + +/// What HuJSON allows beyond JSON: comments and trailing commas. +fn hujson() -> jsonc_parser::ParseOptions { + jsonc_parser::ParseOptions { + allow_comments: true, + allow_trailing_commas: true, + allow_loose_object_property_names: false, + allow_missing_commas: false, + allow_single_quoted_strings: false, + allow_hexadecimal_numbers: false, + allow_unary_plus_numbers: false, + allow_bare_decimal_point_numbers: false, + allow_non_finite_numbers: false, + allow_extended_string_escapes: false, + } +} + +fn parse(text: &str) -> Result { + jsonc_parser::parse_to_serde_value::>(text, &hujson()) + .map_err(|e| format!("Pyo couldn't read your tailnet policy: {e}"))? + .filter(Value::is_object) + .ok_or_else(|| "Pyo couldn't read your tailnet policy: it isn't an object.".into()) +} + +/// What the policy is missing for Pyo. +#[derive(Debug, Default, Clone, Copy, PartialEq)] +pub struct Needs { + /// `tag:pyo` in `tagOwners`: needed before anything can carry the tag. + pub tag_owner: bool, + /// A grant to tag:pyo on ports 80 and 443: only when the policy doesn't + /// already let the tailnet reach it. + pub grant: bool, + /// `autoApprovers.services` for tag:pyo. Pyo approves its Services' + /// hosts through the API anyway, so this only adds resilience. + pub approver: bool, +} + +impl Needs { + fn any(&self) -> bool { + self.tag_owner || self.grant || self.approver + } + /// Without these the setup can't work. + fn required(&self) -> bool { + self.tag_owner || self.grant + } +} + +fn strs(v: &Value) -> impl Iterator { + v.as_array().into_iter().flatten().filter_map(Value::as_str) +} + +pub fn needs(p: &Value) -> Needs { + Needs { + tag_owner: p["tagOwners"].get(TAG).is_none(), + grant: reaches_pyo(p) == Some(false), + approver: !strs(&p["autoApprovers"]["services"][TAG]).any(|s| s == TAG), + } +} + +/// Whether "80", "*", "80,443" or "1-1024" takes in `port`. +fn ports_cover(ports: &str, port: u16) -> bool { + ports.split(',').map(str::trim).any(|p| { + if p == "*" { + return true; + } + match p.split_once('-') { + Some((a, b)) => matches!((a.parse::(), b.parse::()), (Ok(a), Ok(b)) if a <= port && port <= b), + None => p.parse::() == Ok(port), + } + }) +} + +/// Whether everyone on the tailnet can reach tag:pyo on ports 80 and 443, +/// by a rule that plainly says so: from "*" or autogroup:member, to "*" or +/// tag:pyo, with no posture or route conditions. None when the policy has +/// neither `acls` nor `grants`, so Pyo doesn't add the first rule there. +pub fn reaches_pyo(p: &Value) -> Option { + if p.get("acls").is_none() && p.get("grants").is_none() { + return None; + } + let everyone = |v: &Value| strs(v).any(|s| s == "*" || s == "autogroup:member"); + let plain = |r: &Value| r.get("srcPosture").is_none() && r.get("via").is_none(); + let mut open = [false, false]; + let mut take = |ports: &str| { + for (i, port) in [80, 443].into_iter().enumerate() { + open[i] |= ports_cover(ports, port); + } + }; + for r in p["acls"].as_array().into_iter().flatten() { + let tcp = match &r["proto"] { + Value::Null => true, + v => matches!(v.as_str(), Some("tcp" | "6")), + }; + if r["action"].as_str() != Some("accept") + || !(everyone(&r["src"]) || everyone(&r["users"])) + || !tcp + || !plain(r) + { + continue; + } + for d in strs(&r["dst"]).chain(strs(&r["ports"])) { + if let Some((host, ports)) = d.rsplit_once(':') + && (host == "*" || host == TAG) + { + take(ports); + } + } + } + for g in p["grants"].as_array().into_iter().flatten() { + if !everyone(&g["src"]) || !plain(g) || !strs(&g["dst"]).any(|d| d == "*" || d == TAG) { + continue; + } + for ip in strs(&g["ip"]) { + let (proto, ports) = match ip.split_once(':') { + Some(x) => x, + None if ip.bytes().next().is_some_and(|b| b.is_ascii_digit()) => ("*", ip), + None => (ip, "*"), + }; + if matches!(proto, "*" | "tcp" | "6") { + take(ports); + } + } + } + Some(open == [true, true]) +} + +fn strings(xs: &[&str]) -> jsonc_parser::cst::CstInputValue { + jsonc_parser::cst::CstInputValue::Array( + xs.iter() + .map(|s| jsonc_parser::cst::CstInputValue::String((*s).to_owned())) + .collect(), + ) +} + +/// `text` with what `needs` says added, edited in place: comments, +/// order and formatting stay as they were. +pub fn patch(text: &str, needs: &Needs) -> Result { + use jsonc_parser::cst::{CstInputValue, CstRootNode}; + let cant = |what: &str| format!("Pyo can't edit your tailnet policy: {what} isn't an object."); + let root = CstRootNode::parse(text, &hujson()) + .map_err(|e| format!("Pyo couldn't read your tailnet policy: {e}"))?; + let obj = root.object_value().ok_or_else(|| cant("the policy"))?; + if needs.tag_owner { + obj.object_value_or_create("tagOwners") + .ok_or_else(|| cant("tagOwners"))? + .append(TAG, strings(&[OWNERS])); + } + if needs.grant { + obj.array_value_or_create("grants") + .ok_or_else(|| "Pyo can't edit your tailnet policy: grants isn't a list.".to_owned())? + .append(CstInputValue::Object(vec![ + ("src".into(), strings(&["autogroup:member"])), + ("dst".into(), strings(&[TAG])), + ("ip".into(), strings(&["tcp:80", "tcp:443"])), + ])); + } + if needs.approver { + let services = obj + .object_value_or_create("autoApprovers") + .ok_or_else(|| cant("autoApprovers"))? + .object_value_or_create("services") + .ok_or_else(|| cant("autoApprovers.services"))?; + match services.get(TAG) { + None => { + services.append(TAG, strings(&[TAG])); + } + Some(_) => { + services + .array_value(TAG) + .ok_or_else(|| { + "Pyo can't edit your tailnet policy: its tag:pyo approvers aren't a list." + .to_owned() + })? + .append(CstInputValue::String(TAG.into())); + } + } + } + let out = root.to_string(); + // What it did, read back. + if needs.any() && self::needs(&parse(&out)?).required() { + return Err("Pyo couldn't edit your tailnet policy.".into()); + } + Ok(out) +} + +/// The lines `new` adds to `old` ("+ …") and the ones it changes ("- …"), +/// in order. +pub fn diff(old: &str, new: &str) -> Vec { + let a: Vec<&str> = old.lines().collect(); + let b: Vec<&str> = new.lines().collect(); + // Policy files are small. A huge one just lists what's new. + if a.len() * b.len() > 4_000_000 { + return b + .iter() + .filter(|l| !a.contains(l)) + .map(|l| format!("+ {l}")) + .collect(); + } + let (n, m) = (a.len(), b.len()); + let mut lcs = vec![vec![0u32; m + 1]; n + 1]; + for i in (0..n).rev() { + for j in (0..m).rev() { + lcs[i][j] = if a[i] == b[j] { + lcs[i + 1][j + 1] + 1 + } else { + lcs[i + 1][j].max(lcs[i][j + 1]) + }; + } + } + let (mut i, mut j, mut out) = (0, 0, vec![]); + while i < n || j < m { + if i < n && j < m && a[i] == b[j] { + i += 1; + j += 1; + } else if j < m && (i == n || lcs[i][j + 1] >= lcs[i + 1][j]) { + out.push(format!("+ {}", b[j])); + j += 1; + } else { + out.push(format!("- {}", a[i])); + i += 1; + } + } + out +} + +// ── Reading the tailnet ───────────────────────────────────────────────────── + +/// What the installation does for the setup: the AppState, or a stand-in +/// in tests. +pub(crate) trait Host { + /// It can seal a client secret (PYO_SECRET_KEY is set). + fn can_store(&self) -> bool; + /// The saved OAuth client's ID, when it signs in. + async fn working_client(&self) -> Option; + /// Saves a new client like one pasted by hand: `{ ok, checks }`. + async fn save_client(&self, id: &str, secret: &str) -> Result; +} + +impl Host for AppState { + fn can_store(&self) -> bool { + self.sealer.enabled() + } + + async fn working_client(&self) -> Option { + let (cfg, c) = crate::tailscale::saved_client(self).await.ok()??; + c.access_token().await.ok()?; + Some(cfg.client_id) + } + + async fn save_client(&self, id: &str, secret: &str) -> Result { + crate::tailscale::save_client(self, id, Some(secret)) + .await + .map_err(|e| e.message) + } +} + +/// Whether HTTPS certificates are on. The API reference names the setting +/// both `httpsEnabled` and `httpsCertificates`, so either counts. +fn https_on(settings: &Value) -> Option { + ["httpsEnabled", "httpsCertificates"] + .iter() + .find_map(|k| match &settings[*k] { + Value::Bool(b) => Some(*b), + Value::String(s) => Some(matches!(s.as_str(), "on" | "enabled" | "true")), + _ => None, + }) +} + +/// The tailnet as Pyo found it. +struct Survey { + /// The policy is managed outside the console (GitOps, Terraform). + gitops: bool, + policy: String, + etag: Option, + needs: Needs, + /// The policy with what it needs, when it needs something. + patched: Option, + magic_dns: bool, + /// None when Tailscale doesn't say. + https: Option, + /// Pyo's saved client is on this tailnet and signs in. + client: bool, +} + +async fn read_policy(api: &Api) -> Result<(String, Option, Needs, Option), String> { + let (text, etag) = api + .policy() + .await + .map_err(|e| say(&e, "read your tailnet policy"))?; + let needs = needs(&parse(&text)?); + let patched = if needs.any() { + Some(patch(&text, &needs)?) + } else { + None + }; + Ok((text, etag, needs, patched)) +} + +async fn survey(api: &Api, host: &impl Host) -> Result { + let settings = api + .get("/tailnet/-/settings") + .await + .map_err(|e| say(&e, "read your tailnet's settings"))?; + let (policy, etag, needs, patched) = read_policy(api).await?; + let dns = api + .get("/tailnet/-/dns/preferences") + .await + .map_err(|e| say(&e, "read your tailnet's DNS settings"))?; + let client = match host.working_client().await { + None => false, + // On this tailnet: Tailscale knows it by its ID. A client it can't + // show this token still counts, since it signs in. + Some(id) => match api.get(&format!("/tailnet/-/keys/{id}")).await { + Ok(k) => k["invalid"].as_bool() != Some(true), + Err(e) => e.status != 404, + }, + }; + Ok(Survey { + gitops: settings["aclsExternallyManagedOn"].as_bool() == Some(true), + policy, + etag, + needs, + patched, + magic_dns: dns["magicDNS"].as_bool() == Some(true), + https: https_on(&settings), + client, + }) +} + +const GITOPS: &str = "Your tailnet policy is managed outside the Tailscale console. Add these lines there, then check again."; + +/// What the plan says, step by step. +mod words { + pub const MAGIC_DNS: [&str; 3] = ["Turn on MagicDNS", "Turned on MagicDNS", "MagicDNS is on"]; + pub const HTTPS: [&str; 3] = [ + "Turn on HTTPS certificates", + "Turned on HTTPS certificates", + "HTTPS certificates are on", + ]; + pub const TAG_OWNER: [&str; 3] = [ + "Add tag:pyo to your policy", + "Added tag:pyo to your policy", + "Your policy has tag:pyo", + ]; + pub const GRANT: [&str; 3] = [ + "Let your tailnet reach tag:pyo on ports 80 and 443", + "Let your tailnet reach tag:pyo on ports 80 and 443", + "Your tailnet can reach tag:pyo", + ]; + pub const APPROVER: [&str; 3] = [ + "Approve Pyo's Services on tag:pyo servers by policy", + "Approved Pyo's Services on tag:pyo servers by policy", + "Your policy approves Pyo's Services", + ]; + pub const CLIENT: [&str; 3] = [ + "Create the Pyo OAuth client", + "Created the Pyo OAuth client", + "The Pyo OAuth client works", + ]; +} + +/// What [`plan`] returns. +#[derive(Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Plan { + /// What Pyo will change, in order. Empty when the tailnet is set up. + pub changes: Vec, + /// What's set up already. + pub done: Vec, + /// The policy lines added ("+ …") or changed ("- …"). + pub diff: Vec, + /// Why Pyo can't go on by itself, with `diff` as the lines to add. + pub blocked: Option, +} + +fn plan_of(s: &Survey) -> Plan { + let mut p = Plan::default(); + let mut step = |todo: bool, t: [&str; 3]| { + if todo { + p.changes.push(t[0].into()); + } else { + p.done.push(t[2].into()); + } + }; + step(!s.magic_dns, words::MAGIC_DNS); + step(s.https != Some(true), words::HTTPS); + step(s.needs.tag_owner, words::TAG_OWNER); + if s.needs.grant || reaches_pyo(&parse(&s.policy).unwrap_or_default()) == Some(true) { + step(s.needs.grant, words::GRANT); + } + // A policy in Git that has what's required is left as it is. + let writes_policy = !s.gitops || s.needs.required(); + if writes_policy || !s.needs.approver { + step(s.needs.approver, words::APPROVER); + } + step(!s.client, words::CLIENT); + if let Some(new) = &s.patched + && writes_policy + { + p.diff = diff(&s.policy, new); + } + if s.gitops && s.needs.required() { + p.blocked = Some(GITOPS.into()); + } + p +} + +/// Reads the tailnet and says what setting it up would change. Changes +/// nothing. +pub(crate) async fn plan_with(api: &Api, host: &impl Host) -> Result { + if !host.can_store() { + return Err(NO_KEY.into()); + } + let s = survey(api, host).await?; + let p = plan_of(&s); + tracing::info!( + changes = p.changes.len(), + blocked = p.blocked.is_some(), + "tailscale setup planned" + ); + Ok(p) +} + +const NO_KEY: &str = + "This installation has no PYO_SECRET_KEY, so it can't store Pyo's OAuth client."; + +// ── Making the changes ────────────────────────────────────────────────────── + +/// What [`apply`] did. +#[derive(Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Outcome { + /// Everything went through. + pub ok: bool, + /// What changed, in order. + pub changed: Vec, + /// What the admin still has to do by hand. + pub todo: Vec, + /// What stopped it, after `changed`. + pub error: Option, + /// The saved client's checks, as Test shows them. + pub checks: Vec, + /// The pasted token was deleted. + pub token_deleted: bool, +} + +enum Https { + On, + Off, + Unknown, +} + +/// Turns HTTPS certificates on, trying the setting's name in the schema +/// first and then the one in its description, and reading it back. +async fn turn_on_https(api: &Api) -> Result { + let read = async || api.get("/tailnet/-/settings").await.map(|v| https_on(&v)); + for field in ["httpsEnabled", "httpsCertificates"] { + match api + .send( + reqwest::Method::PATCH, + "/tailnet/-/settings", + Body::Json(json!({ field: true })), + &[], + ) + .await + { + Ok(r) if https_on(&r.json()) == Some(true) => return Ok(Https::On), + Ok(_) => { + if read().await? == Some(true) { + return Ok(Https::On); + } + } + // Not a setting by that name. + Err(e) if e.status == 400 => {} + Err(e) => return Err(e), + } + } + Ok(match read().await? { + Some(true) => Https::On, + Some(false) => Https::Off, + None => Https::Unknown, + }) +} + +/// Validates the new policy, without saving it. +async fn validate(api: &Api, text: &str) -> Result<(), String> { + let r = api + .send( + reqwest::Method::POST, + "/tailnet/-/acl/validate", + Body::HuJson(text.to_owned()), + &[], + ) + .await + .map_err(|e| say(&e, "check the new tailnet policy"))?; + let v = r.json(); + let errors = v["data"] + .as_array() + .into_iter() + .flatten() + .any(|d| d["errors"].as_array().is_some_and(|e| !e.is_empty())); + match v["message"].as_str().filter(|m| !m.is_empty()) { + // Warnings don't stop it. + Some(m) if errors || !m.starts_with("warning") => Err(format!( + "Tailscale wouldn't take the new policy: {}.", + api.scrub(m.trim_end_matches('.')) + )), + _ => Ok(()), + } +} + +/// The policy steps done, as the outcome lists them. +fn policy_changes(n: &Needs) -> Vec { + [ + (n.tag_owner, words::TAG_OWNER), + (n.grant, words::GRANT), + (n.approver, words::APPROVER), + ] + .into_iter() + .filter(|(on, _)| *on) + .map(|(_, t)| t[1].to_owned()) + .collect() +} + +/// Writes the policy with what it needs. If someone changed it meanwhile +/// (412), reads it again and plans once more. +async fn write_policy(api: &Api, s: &Survey) -> Result, String> { + let (mut etag, mut needs, mut patched) = (s.etag.clone(), s.needs, s.patched.clone()); + for attempt in 0..2 { + let Some(text) = patched.as_deref() else { + return Ok(vec![]); + }; + // The first one was validated before anything changed. + if attempt > 0 { + validate(api, text).await?; + } + let mut headers = vec![("accept", "application/hujson")]; + if let Some(e) = etag.as_deref() { + headers.push(("if-match", e)); + } + match api + .send( + reqwest::Method::POST, + "/tailnet/-/acl", + Body::HuJson(text.to_owned()), + &headers, + ) + .await + { + Ok(_) => { + tracing::info!("tailnet policy updated"); + return Ok(policy_changes(&needs)); + } + Err(e) if e.status == 412 && attempt == 0 => { + tracing::info!("tailnet policy changed meanwhile, planning again"); + let (_, e2, n2, p2) = read_policy(api).await?; + (etag, needs, patched) = (e2, n2, p2); + } + Err(e) if e.status == 412 => { + return Err( + "Your tailnet policy changed while Pyo was editing it. Check again.".into(), + ); + } + Err(e) => return Err(say(&e, "save your tailnet policy")), + } + } + unreachable!() +} + +/// Makes Pyo's own OAuth client and saves it: (checks). +async fn make_client(api: &Api, host: &impl Host) -> Result, String> { + let body = json!({ + "keyType": "client", + "description": crate::tailscale::key_description("Pyo"), + "scopes": SCOPES, + "tags": [TAG], + }); + let r = api + .send(reqwest::Method::POST, "/tailnet/-/keys", Body::Json(body), &[]) + .await + .map_err(|e| match e.status { + 401 => BAD_TOKEN.to_owned(), + _ => { + let m = e.message.trim().trim_end_matches('.'); + let why = if m.is_empty() { String::new() } else { format!(" It said: {m}.") }; + format!("Tailscale didn't let Pyo create its OAuth client.{why} Set up with an OAuth client instead.") + } + })?; + let v = r.json(); + let secret = v["key"].as_str().unwrap_or(""); + // The client ID is the key's ID, which its secret carries too. + let id = v["id"].as_str().map(str::to_owned).or_else(|| { + secret + .strip_prefix("tskey-client-") + .and_then(|s| s.split('-').next()) + .map(str::to_owned) + }); + let Some(id) = id.filter(|_| secret.starts_with("tskey-client-")) else { + return Err( + "Tailscale made no OAuth client for Pyo. Set up with an OAuth client instead.".into(), + ); + }; + tracing::info!(client = %id, "tailscale client made"); + match host.save_client(&id, secret).await { + Ok(out) => Ok(out["checks"].as_array().cloned().unwrap_or_default()), + Err(e) => { + // Not left behind unused. + let _ = api + .send( + reqwest::Method::DELETE, + &format!("/tailnet/-/keys/{id}"), + Body::None, + &[], + ) + .await; + Err(format!("Pyo couldn't save its OAuth client. {e}")) + } + } +} + +/// Sets the tailnet up: what [`plan_with`] says, in that order, and the +/// pasted token deleted last. Fails with nothing changed, or says what +/// changed before it stopped. +pub(crate) async fn apply_with(api: &Api, host: &impl Host) -> Result { + if !host.can_store() { + return Err(NO_KEY.into()); + } + let s = survey(api, host).await?; + if s.gitops && s.needs.required() { + return Err(GITOPS.into()); + } + let writes_policy = !s.gitops && s.patched.is_some(); + // Before anything changes. + if writes_policy && let Some(p) = &s.patched { + validate(api, p).await?; + } + let mut out = Outcome::default(); + let stop = |mut out: Outcome, e: String| { + if out.changed.is_empty() { + Err(e) + } else { + out.error = Some(e); + Ok(out) + } + }; + if !s.magic_dns { + if let Err(e) = api + .send( + reqwest::Method::POST, + "/tailnet/-/dns/preferences", + Body::Json(json!({ "magicDNS": true })), + &[], + ) + .await + { + let none = api + .get("/tailnet/-/dns/nameservers") + .await + .is_ok_and(|v| strs(&v["dns"]).next().is_none()); + return stop( + out, + if none && e.status != 401 && e.status != 403 { + "MagicDNS needs a DNS nameserver first. Add one under DNS in the Tailscale console, then try again.".into() + } else { + say(&e, "turn on MagicDNS") + }, + ); + } + out.changed.push(words::MAGIC_DNS[1].into()); + } + if s.https != Some(true) { + match turn_on_https(api).await { + Ok(Https::On) => out.changed.push(words::HTTPS[1].into()), + Ok(Https::Off) => out + .todo + .push("Turn on HTTPS Certificates under DNS in the Tailscale console.".into()), + Ok(Https::Unknown) => out.todo.push( + "Check that HTTPS Certificates is on under DNS in the Tailscale console.".into(), + ), + Err(e) => return stop(out, say(&e, "turn on HTTPS certificates")), + } + } + if writes_policy { + match write_policy(api, &s).await { + Ok(done) => out.changed.extend(done), + Err(e) => return stop(out, e), + } + } + if !s.client { + match make_client(api, host).await { + Ok(checks) => { + out.changed.push(words::CLIENT[1].into()); + out.checks = checks; + } + Err(e) => return stop(out, e), + } + } + // Last: nothing needs the token after this. + out.token_deleted = match api.token.key_id() { + Some(id) => api + .send( + reqwest::Method::DELETE, + &format!("/tailnet/-/keys/{id}"), + Body::None, + &[], + ) + .await + .is_ok(), + None => false, + }; + if !out.token_deleted { + out.todo.push(DELETE_TOKEN.into()); + } + out.ok = true; + tracing::info!( + changed = out.changed.len(), + token_deleted = out.token_deleted, + "tailscale set up" + ); + Ok(out) +} + +/// planTailscaleSetup. +pub async fn plan(s: &AppState, token: Token) -> ApiResult { + check_shape(&token).map_err(ApiError::bad_request)?; + let p = plan_with(&Api::new(token), s) + .await + .map_err(ApiError::bad_request)?; + Ok(json!({ "ok": true, "plan": p })) +} + +/// setUpTailscale. +pub async fn apply(s: &AppState, token: Token) -> ApiResult { + check_shape(&token).map_err(ApiError::bad_request)?; + apply_with(&Api::new(token), s) + .await + .map_err(ApiError::bad_request) +} + +#[cfg(test)] +mod tests; diff --git a/crates/pyo-api/src/tailscale_setup/tests.rs b/crates/pyo-api/src/tailscale_setup/tests.rs new file mode 100644 index 0000000..7244f21 --- /dev/null +++ b/crates/pyo-api/src/tailscale_setup/tests.rs @@ -0,0 +1,957 @@ +//! A mock Tailscale API, and the setup run against it. + +use super::*; +use std::sync::{Arc, Mutex}; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, Method, StatusCode, Uri}, + response::{IntoResponse, Response}, +}; + +const TOKEN: &str = "tskey-api-kTok1CNTRL-0123456789abcdefghijSECRET"; +const TOKEN_SECRET: &str = "0123456789abcdefghijSECRET"; + +/// A new tailnet's policy, as Tailscale writes it (grants, comments, +/// trailing commas, tabs). +const DEFAULT_POLICY: &str = r#"// Example/default ACLs for unrestricted connections. +{ + // Declare static groups of users. Use autogroups for all users or users with a specific role. + // "groups": { + // "group:example": ["alice@example.com", "bob@example.com"], + // }, + + // Define the tags which can be applied to devices and by which users. + // "tagOwners": { + // "tag:example": ["autogroup:admin"], + // }, + + // Define grants that govern access for users, groups, autogroups, tags, + // Tailscale IP addresses, and subnet ranges. + "grants": [ + // Allow all connections. + // Comment this section out if you want to define specific restrictions. + {"src": ["*"], "dst": ["*"], "ip": ["*"]}, + ], + + // Define users and devices that can use Tailscale SSH. + "ssh": [ + // Allow all users to SSH into their own devices in check mode. + // Comment this section out if you want to define specific restrictions. + { + "action": "check", + "src": ["autogroup:member"], + "dst": ["autogroup:self"], + "users": ["autogroup:nonroot", "root"], + }, + ], + + // Test access rules every time they're saved. + // "tests": [ + // { + // "src": "alice@example.com", + // "accept": ["tag:example"], + // "deny": ["100.101.102.103:443"], + // }, + // ], +} +"#; + +/// A restrictive policy with tag owners of its own, and comments. +const RESTRICTED_POLICY: &str = r#"{ + // Who owns which tags. + "tagOwners": { + "tag:prod": ["group:eng"], // production servers + }, + "groups": { "group:eng": ["alice@example.com"] }, + /* Only engineers, only SSH to production. */ + "acls": [ + { "action": "accept", "src": ["group:eng"], "dst": ["tag:prod:22"] }, + ], +} +"#; + +/// A policy that has everything Pyo needs. +const SET_UP_POLICY: &str = r#"{ + "tagOwners": { "tag:pyo": ["autogroup:admin"] }, + "autoApprovers": { "services": { "tag:pyo": ["tag:pyo"] } }, + "acls": [{ "action": "accept", "src": ["*"], "dst": ["*:*"] }], +} +"#; + +#[derive(Default)] +struct Mock { + policy: String, + etag: u32, + gitops: bool, + magic_dns: bool, + nameservers: Vec, + /// Stored HTTPS certificates setting. + https: bool, + /// The settings' name for it this Tailscale knows: "httpsEnabled" + /// (default) or "httpsCertificates". + https_field: Option<&'static str>, + /// Policy writes that lose to someone else's edit first. + races: u32, + refuse_client: bool, + refuse_revoke: bool, + /// Error messages carry the request's Authorization header. + echo_token: bool, + clients: Vec, + deleted: Vec, + /// "METHOD /path" of every request. + log: Vec, + /// Policy texts written. + written: Vec, +} + +type Shared = Arc>; + +/// One test against the mock at a time, so the log test sees every line +/// (tracing caches what's logged per call site, across threads). +static ONE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +fn err(m: &Mock, status: StatusCode, msg: &str, auth: &str) -> Response { + let message = if m.echo_token { + format!("{msg} (request had {auth})") + } else { + msg.to_owned() + }; + (status, axum::Json(json!({ "message": message }))).into_response() +} + +async fn handle( + State(st): State, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + let mut m = st.lock().unwrap(); + let path = uri.path().to_owned(); + m.log.push(format!("{method} {path}")); + let auth = headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_owned(); + if auth != format!("Bearer {TOKEN}") { + return err(&m, StatusCode::UNAUTHORIZED, "API token invalid", &auth); + } + let body = String::from_utf8_lossy(&body).to_string(); + let field = m.https_field.unwrap_or("httpsEnabled"); + let settings = |m: &Mock| json!({ "aclsExternallyManagedOn": m.gitops, field: m.https }); + match (method.as_str(), path.as_str()) { + ("GET", "/tailnet/-/settings") => axum::Json(settings(&m)).into_response(), + ("PATCH", "/tailnet/-/settings") => { + let v: Value = serde_json::from_str(&body).unwrap(); + for other in ["httpsEnabled", "httpsCertificates"] { + if other != field && v.get(other).is_some() { + return err(&m, StatusCode::BAD_REQUEST, "unknown field", &auth); + } + } + if let Some(b) = v[field].as_bool() { + m.https = b; + } + axum::Json(settings(&m)).into_response() + } + ("GET", "/tailnet/-/acl") => { + assert_eq!(headers["accept"], "application/hujson"); + ([("etag", format!("\"e{}\"", m.etag))], m.policy.clone()).into_response() + } + ("POST", "/tailnet/-/acl/validate") => { + assert_eq!(headers["content-type"], "application/hujson"); + match jsonc_parser::parse_to_serde_value::(&body, &hujson()) { + Ok(_) => axum::Json(json!({})).into_response(), + Err(e) => axum::Json(json!({ "message": e.to_string() })).into_response(), + } + } + ("POST", "/tailnet/-/acl") => { + assert_eq!(headers["content-type"], "application/hujson"); + if m.races > 0 { + // Someone else saves first. + m.races -= 1; + m.etag += 1; + let edited = m.policy.replacen('{', "{\n // edited meanwhile", 1); + m.policy = edited; + } + let want = format!("\"e{}\"", m.etag); + if headers.get("if-match").and_then(|v| v.to_str().ok()) != Some(want.as_str()) { + return err( + &m, + StatusCode::PRECONDITION_FAILED, + "precondition failed, invalid old hash", + &auth, + ); + } + m.etag += 1; + m.policy = body.clone(); + m.written.push(body.clone()); + body.into_response() + } + ("GET", "/tailnet/-/dns/preferences") => { + axum::Json(json!({ "magicDNS": m.magic_dns })).into_response() + } + ("POST", "/tailnet/-/dns/preferences") => { + if m.nameservers.is_empty() { + return err( + &m, + StatusCode::BAD_REQUEST, + "need at least one nameserver", + &auth, + ); + } + m.magic_dns = true; + axum::Json(json!({ "magicDNS": true })).into_response() + } + ("GET", "/tailnet/-/dns/nameservers") => { + axum::Json(json!({ "dns": m.nameservers })).into_response() + } + ("POST", "/tailnet/-/keys") => { + if m.refuse_client { + return err( + &m, + StatusCode::FORBIDDEN, + "not allowed to create OAuth clients", + &auth, + ); + } + let v: Value = serde_json::from_str(&body).unwrap(); + let id = format!("kPyo{}CNTRL", m.clients.len() + 1); + let k = json!({ + "id": id, "keyType": v["keyType"], "scopes": v["scopes"], "tags": v["tags"], + "description": v["description"], + "key": format!("tskey-client-{id}-clientsecret0123456789"), + }); + m.clients.push(k.clone()); + axum::Json(k).into_response() + } + ("GET", p) if p.starts_with("/tailnet/-/keys/") => { + let id = &p["/tailnet/-/keys/".len()..]; + match m.clients.iter().find(|k| k["id"] == id) { + Some(k) if !m.deleted.iter().any(|d| d == id) => { + axum::Json(json!({ "id": id, "keyType": "client", "scopes": k["scopes"] })) + .into_response() + } + _ => err(&m, StatusCode::NOT_FOUND, "key not found", &auth), + } + } + ("DELETE", p) if p.starts_with("/tailnet/-/keys/") => { + let id = p["/tailnet/-/keys/".len()..].to_owned(); + if m.refuse_revoke && id == "kTok1CNTRL" { + return err( + &m, + StatusCode::FORBIDDEN, + "cannot delete the key in use", + &auth, + ); + } + m.deleted.push(id); + axum::Json(json!({})).into_response() + } + _ => err(&m, StatusCode::NOT_FOUND, "no such endpoint", &auth), + } +} + +async fn serve(m: Mock) -> (String, Shared) { + let st: Shared = Arc::new(Mutex::new(m)); + let app = Router::new().fallback(handle).with_state(st.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (format!("http://{addr}"), st) +} + +/// The installation, as the setup sees it. +#[derive(Default)] +struct FakeHost { + no_key: bool, + /// The saved client that signs in. + client: Mutex>, + /// What was saved: (client ID, secret). + saved: Mutex>, + save_fails: bool, +} + +impl Host for FakeHost { + fn can_store(&self) -> bool { + !self.no_key + } + async fn working_client(&self) -> Option { + self.client.lock().unwrap().clone() + } + async fn save_client(&self, id: &str, secret: &str) -> Result { + if self.save_fails { + return Err("The client didn't sign in.".into()); + } + self.saved + .lock() + .unwrap() + .push((id.to_owned(), secret.to_owned())); + *self.client.lock().unwrap() = Some(id.to_owned()); + Ok( + json!({ "ok": true, "checks": [{ "name": "client", "ok": true, "message": "Signed in." }] }), + ) + } +} + +fn api(base: &str) -> Api { + Api::at(base, Token::new(TOKEN)) +} + +fn fresh() -> Mock { + Mock { + policy: DEFAULT_POLICY.into(), + magic_dns: true, + nameservers: vec!["1.1.1.1".into()], + ..Default::default() + } +} + +fn comments(text: &str) -> Vec<&str> { + text.lines() + .filter_map(|l| { + let l = l.trim(); + (l.starts_with("//") || l.starts_with("/*") || l.contains(" // ")) + .then_some(l.split("//").last().unwrap_or(l)) + }) + .collect() +} + +fn writes(m: &Mock) -> Vec { + m.log + .iter() + .filter(|l| !l.starts_with("GET ") && !l.ends_with("/acl/validate")) + .cloned() + .collect() +} + +// ── The policy, on its own ────────────────────────────────────────────────── + +#[test] +fn the_patch_keeps_comments_and_formatting() { + let n = needs(&parse(DEFAULT_POLICY).unwrap()); + assert_eq!( + n, + Needs { + tag_owner: true, + grant: false, + approver: true + } + ); + let out = patch(DEFAULT_POLICY, &n).unwrap(); + for c in comments(DEFAULT_POLICY) { + assert!(out.contains(c), "lost the comment {c:?}:\n{out}"); + } + // Every line it had is still there, as it was. + for l in DEFAULT_POLICY.lines() { + assert!( + out.lines().any(|o| o == l), + "changed the line {l:?}:\n{out}" + ); + } + let v = parse(&out).unwrap(); + assert_eq!(v["tagOwners"][TAG], json!(["autogroup:admin"])); + assert_eq!(v["autoApprovers"]["services"][TAG], json!([TAG])); + assert_eq!(v["grants"], parse(DEFAULT_POLICY).unwrap()["grants"]); + assert!(!needs(&v).any()); + // What the diff shows is only what's new. + let d = diff(DEFAULT_POLICY, &out); + assert!(d.iter().all(|l| l.starts_with("+ ")), "{d:?}"); + assert!( + d.iter() + .any(|l| l.contains("\"tag:pyo\": [\"autogroup:admin\"]")), + "{d:?}" + ); +} + +#[test] +fn the_patch_adds_to_tag_owners_already_there() { + let n = needs(&parse(RESTRICTED_POLICY).unwrap()); + assert_eq!( + n, + Needs { + tag_owner: true, + grant: true, + approver: true + } + ); + let out = patch(RESTRICTED_POLICY, &n).unwrap(); + for c in [ + "// Who owns which tags.", + "// production servers", + "/* Only engineers, only SSH to production. */", + ] { + assert!(out.contains(c), "lost {c:?}:\n{out}"); + } + let v = parse(&out).unwrap(); + assert_eq!(v["tagOwners"]["tag:prod"], json!(["group:eng"])); + assert_eq!(v["tagOwners"][TAG], json!(["autogroup:admin"])); + assert_eq!( + v["grants"], + json!([{ "src": ["autogroup:member"], "dst": [TAG], "ip": ["tcp:80", "tcp:443"] }]) + ); + assert_eq!(v["acls"], parse(RESTRICTED_POLICY).unwrap()["acls"]); + assert_eq!(reaches_pyo(&v), Some(true)); +} + +#[test] +fn approvers_for_tag_pyo_get_tag_pyo_added() { + let p = r#"{ "autoApprovers": { "services": { "tag:pyo": ["group:ops"] } }, "tagOwners": { "tag:pyo": [] }, "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] }"#; + let n = needs(&parse(p).unwrap()); + assert!(n.approver && !n.tag_owner && !n.grant); + let v = parse(&patch(p, &n).unwrap()).unwrap(); + assert_eq!( + v["autoApprovers"]["services"][TAG], + json!(["group:ops", TAG]) + ); +} + +#[test] +fn what_lets_the_tailnet_reach_pyo() { + let r = |p: Value| reaches_pyo(&p); + assert_eq!( + r(json!({ "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] })), + Some(true) + ); + assert_eq!( + r(json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["*:*"] }] })), + Some(true) + ); + assert_eq!( + r(json!({ "acls": [{ "action": "accept", "users": ["*"], "ports": ["*:*"] }] })), + Some(true) + ); + assert_eq!( + r( + json!({ "grants": [{ "src": ["autogroup:member"], "dst": [TAG], "ip": ["tcp:80", "443"] }] }) + ), + Some(true) + ); + assert_eq!( + r(json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["tag:pyo:80,443"] }] })), + Some(true) + ); + assert_eq!( + r(json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["tag:pyo:1-1024"] }] })), + Some(true) + ); + // Split over two rules. + assert_eq!( + r(json!({ "grants": [ + { "src": ["*"], "dst": [TAG], "ip": ["tcp:80"] }, + { "src": ["*"], "dst": ["*"], "ip": ["tcp:443"] }, + ] })), + Some(true) + ); + // Only some people, a port missing, UDP, posture: not plainly open. + assert_eq!( + r(json!({ "grants": [{ "src": ["group:eng"], "dst": ["*"], "ip": ["*"] }] })), + Some(false) + ); + assert_eq!( + r(json!({ "grants": [{ "src": ["*"], "dst": [TAG], "ip": ["tcp:443"] }] })), + Some(false) + ); + assert_eq!( + r(json!({ "grants": [{ "src": ["*"], "dst": [TAG], "ip": ["udp:*"] }] })), + Some(false) + ); + assert_eq!( + r( + json!({ "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"], "srcPosture": ["posture:x"] }] }) + ), + Some(false) + ); + assert_eq!( + r( + json!({ "acls": [{ "action": "accept", "src": ["*"], "proto": "udp", "dst": ["*:*"] }] }) + ), + Some(false) + ); + assert_eq!(r(json!({ "acls": [] })), Some(false)); + // No rules at all: Pyo doesn't write the first one. + assert_eq!(r(json!({ "tagOwners": {} })), None); +} + +#[test] +fn the_token_shape_is_checked_and_its_id_found() { + assert!(check_shape(&Token::new(TOKEN)).is_ok()); + assert!( + check_shape(&Token::new("tskey-client-k1CNTRL-abcdefabcdef")) + .unwrap_err() + .contains("OAuth client secret") + ); + assert!( + check_shape(&Token::new("tskey-auth-k1CNTRL-abcdefabcdef")) + .unwrap_err() + .contains("auth key") + ); + assert!(check_shape(&Token::new("hello")).is_err()); + assert_eq!(Token::new(TOKEN).key_id(), Some("kTok1CNTRL")); + assert_eq!(Token::new("tskey-api-").key_id(), None); + assert_eq!(format!("{:?}", Token::new(TOKEN)), "Token(•••)"); +} + +// ── Against the mock API ──────────────────────────────────────────────────── + +#[tokio::test] +async fn a_fresh_tailnet_with_the_default_policy() { + let _one = ONE.lock().await; + let (base, st) = serve(fresh()).await; + let host = FakeHost::default(); + let p = plan_with(&api(&base), &host).await.unwrap(); + assert_eq!( + p.changes, + [ + "Turn on HTTPS certificates", + "Add tag:pyo to your policy", + "Approve Pyo's Services on tag:pyo servers by policy", + "Create the Pyo OAuth client", + ] + ); + assert_eq!(p.done, ["MagicDNS is on", "Your tailnet can reach tag:pyo"]); + assert!(p.blocked.is_none()); + assert!(p.diff.iter().any(|l| l.contains("tag:pyo"))); + assert!( + writes(&st.lock().unwrap()).is_empty(), + "the plan changes nothing" + ); + + let out = apply_with(&api(&base), &host).await.unwrap(); + assert!(out.ok, "{out:?}"); + assert_eq!( + out.changed, + [ + "Turned on HTTPS certificates", + "Added tag:pyo to your policy", + "Approved Pyo's Services on tag:pyo servers by policy", + "Created the Pyo OAuth client", + ] + ); + assert!(out.token_deleted && out.todo.is_empty() && out.error.is_none()); + let m = st.lock().unwrap(); + assert!(m.https); + // The comments are all still there. + for c in comments(DEFAULT_POLICY) { + assert!(m.policy.contains(c), "lost {c:?}"); + } + // The client has exactly the scopes the manual path asks for. + assert_eq!(m.clients.len(), 1); + assert_eq!(m.clients[0]["keyType"], "client"); + assert_eq!( + m.clients[0]["scopes"], + json!(["devices:core", "auth_keys", "services"]) + ); + assert_eq!(m.clients[0]["tags"], json!([TAG])); + assert_eq!( + *host.saved.lock().unwrap(), + [( + "kPyo1CNTRL".to_owned(), + "tskey-client-kPyo1CNTRL-clientsecret0123456789".to_owned() + )] + ); + // The token went last. + assert_eq!(m.deleted, ["kTok1CNTRL"]); + assert_eq!( + writes(&m).last().unwrap(), + "DELETE /tailnet/-/keys/kTok1CNTRL" + ); +} + +#[tokio::test] +async fn a_restricted_policy_with_its_own_tag_owners() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + policy: RESTRICTED_POLICY.into(), + https: true, + ..fresh() + }) + .await; + let host = FakeHost::default(); + let p = plan_with(&api(&base), &host).await.unwrap(); + assert_eq!( + p.changes, + [ + "Add tag:pyo to your policy", + "Let your tailnet reach tag:pyo on ports 80 and 443", + "Approve Pyo's Services on tag:pyo servers by policy", + "Create the Pyo OAuth client", + ] + ); + let out = apply_with(&api(&base), &host).await.unwrap(); + assert!(out.ok, "{out:?}"); + let m = st.lock().unwrap(); + assert!( + m.policy + .contains("\"tag:prod\": [\"group:eng\"], // production servers") + ); + assert!( + m.policy + .contains("/* Only engineers, only SSH to production. */") + ); + assert_eq!( + parse(&m.policy).unwrap()["tagOwners"][TAG], + json!(["autogroup:admin"]) + ); + assert_eq!(m.written.len(), 1); +} + +#[tokio::test] +async fn an_already_set_up_tailnet_changes_nothing() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + policy: SET_UP_POLICY.into(), + https: true, + clients: vec![json!({ "id": "kOld1CNTRL", "keyType": "client", "scopes": SCOPES })], + ..fresh() + }) + .await; + let host = FakeHost { + client: Mutex::new(Some("kOld1CNTRL".into())), + ..Default::default() + }; + let p = plan_with(&api(&base), &host).await.unwrap(); + assert!(p.changes.is_empty(), "{p:?}"); + assert!(p.diff.is_empty()); + assert_eq!(p.done.len(), 6); + let out = apply_with(&api(&base), &host).await.unwrap(); + assert!( + out.ok && out.changed.is_empty() && out.token_deleted, + "{out:?}" + ); + let m = st.lock().unwrap(); + assert_eq!(writes(&m), ["DELETE /tailnet/-/keys/kTok1CNTRL"]); + assert!(host.saved.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn a_saved_client_from_another_tailnet_is_replaced() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + policy: SET_UP_POLICY.into(), + https: true, + ..fresh() + }) + .await; + let host = FakeHost { + client: Mutex::new(Some("kElsewhereCNTRL".into())), + ..Default::default() + }; + let p = plan_with(&api(&base), &host).await.unwrap(); + assert_eq!(p.changes, ["Create the Pyo OAuth client"]); + let out = apply_with(&api(&base), &host).await.unwrap(); + assert!(out.ok); + assert_eq!(st.lock().unwrap().clients.len(), 1); +} + +#[tokio::test] +async fn a_policy_managed_in_git_is_never_written() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + gitops: true, + ..fresh() + }) + .await; + let host = FakeHost::default(); + let p = plan_with(&api(&base), &host).await.unwrap(); + assert!(p.blocked.as_deref().unwrap().contains("managed outside")); + assert!( + p.diff + .iter() + .any(|l| l.contains("\"tag:pyo\": [\"autogroup:admin\"]")) + ); + let e = apply_with(&api(&base), &host).await.unwrap_err(); + assert!(e.contains("managed outside"), "{e}"); + assert!(writes(&st.lock().unwrap()).is_empty()); + + // Once Git has the lines, the rest goes on, and the policy is left alone. + let (base, st) = serve(Mock { + gitops: true, + policy: r#"{ "tagOwners": { "tag:pyo": [] }, "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] }"#.into(), + ..fresh() + }) + .await; + let p = plan_with(&api(&base), &host).await.unwrap(); + assert!(p.blocked.is_none() && p.diff.is_empty(), "{p:?}"); + assert!(!p.changes.iter().any(|c| c.contains("Approve"))); + let out = apply_with(&api(&base), &host).await.unwrap(); + assert!(out.ok, "{out:?}"); + assert!(st.lock().unwrap().written.is_empty()); +} + +#[tokio::test] +async fn a_policy_changed_meanwhile_is_read_again_once() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + races: 1, + https: true, + ..fresh() + }) + .await; + let out = apply_with(&api(&base), &FakeHost::default()).await.unwrap(); + assert!(out.ok, "{out:?}"); + let m = st.lock().unwrap(); + // The other edit is kept, under Pyo's. + assert!(m.policy.contains("// edited meanwhile")); + assert!(parse(&m.policy).unwrap()["tagOwners"].get(TAG).is_some()); + assert_eq!( + m.log.iter().filter(|l| *l == "POST /tailnet/-/acl").count(), + 2 + ); +} + +#[tokio::test] +async fn a_policy_that_keeps_changing_stops_with_what_was_done() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + races: 2, + ..fresh() + }) + .await; + let out = apply_with(&api(&base), &FakeHost::default()).await.unwrap(); + assert!(!out.ok); + assert_eq!(out.changed, ["Turned on HTTPS certificates"]); + assert!( + out.error + .unwrap() + .contains("changed while Pyo was editing it") + ); + let m = st.lock().unwrap(); + assert!(m.written.is_empty() && m.clients.is_empty() && m.deleted.is_empty()); +} + +#[tokio::test] +async fn https_under_its_other_name() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + https_field: Some("httpsCertificates"), + ..fresh() + }) + .await; + let out = apply_with(&api(&base), &FakeHost::default()).await.unwrap(); + assert!( + out.ok + && out + .changed + .contains(&"Turned on HTTPS certificates".to_owned()), + "{out:?}" + ); + let m = st.lock().unwrap(); + assert!(m.https); + assert_eq!( + m.log + .iter() + .filter(|l| *l == "PATCH /tailnet/-/settings") + .count(), + 2 + ); +} + +#[tokio::test] +async fn a_refused_client_says_what_changed() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + refuse_client: true, + https: true, + ..fresh() + }) + .await; + let host = FakeHost::default(); + let out = apply_with(&api(&base), &host).await.unwrap(); + assert!(!out.ok); + assert_eq!( + out.changed, + [ + "Added tag:pyo to your policy", + "Approved Pyo's Services on tag:pyo servers by policy", + ] + ); + let e = out.error.unwrap(); + assert!( + e.contains("didn't let Pyo create its OAuth client") && e.contains("not allowed"), + "{e}" + ); + assert!(!out.token_deleted); + assert!(host.saved.lock().unwrap().is_empty()); + // The token stays for another try. + assert!(st.lock().unwrap().deleted.is_empty()); +} + +#[tokio::test] +async fn a_client_that_cant_be_saved_is_deleted_again() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + https: true, + policy: SET_UP_POLICY.into(), + ..fresh() + }) + .await; + let host = FakeHost { + save_fails: true, + ..Default::default() + }; + let e = apply_with(&api(&base), &host).await.unwrap_err(); + assert!(e.contains("couldn't save its OAuth client"), "{e}"); + assert_eq!(st.lock().unwrap().deleted, ["kPyo1CNTRL"]); +} + +#[tokio::test] +async fn a_token_that_cant_delete_itself_is_left_to_the_admin() { + let _one = ONE.lock().await; + let (base, _) = serve(Mock { + refuse_revoke: true, + ..fresh() + }) + .await; + let out = apply_with(&api(&base), &FakeHost::default()).await.unwrap(); + assert!(out.ok && !out.token_deleted); + assert_eq!(out.todo, [DELETE_TOKEN]); +} + +#[tokio::test] +async fn magic_dns_without_nameservers_changes_nothing() { + let _one = ONE.lock().await; + let (base, st) = serve(Mock { + magic_dns: false, + nameservers: vec![], + ..fresh() + }) + .await; + let host = FakeHost::default(); + let p = plan_with(&api(&base), &host).await.unwrap(); + assert_eq!(p.changes[0], "Turn on MagicDNS"); + let e = apply_with(&api(&base), &host).await.unwrap_err(); + assert!(e.contains("needs a DNS nameserver"), "{e}"); + assert_eq!( + writes(&st.lock().unwrap()), + ["POST /tailnet/-/dns/preferences"] + ); +} + +#[tokio::test] +async fn a_wrong_token_or_no_secret_key() { + let _one = ONE.lock().await; + let (base, _) = serve(fresh()).await; + let wrong = Api::at( + &base, + Token::new("tskey-api-kOther1CNTRL-zzzzzzzzzzzzzzzzzzzz"), + ); + let e = plan_with(&wrong, &FakeHost::default()).await.unwrap_err(); + assert_eq!(e, BAD_TOKEN); + let host = FakeHost { + no_key: true, + ..Default::default() + }; + assert_eq!(plan_with(&api(&base), &host).await.unwrap_err(), NO_KEY); +} + +// ── The token never shows ─────────────────────────────────────────────────── + +#[derive(Clone, Default)] +struct Captured(Arc>>); + +impl std::io::Write for Captured { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[tokio::test] +async fn the_token_never_shows_in_logs_errors_or_saved_settings() { + let _one = ONE.lock().await; + let logs = Captured::default(); + let w = logs.clone(); + let _guard = tracing::subscriber::set_default( + tracing_subscriber::fmt() + .with_max_level(tracing::Level::TRACE) + .with_writer(move || w.clone()) + .finish(), + ); + tracing::callsite::rebuild_interest_cache(); + let leaks = |s: &str| s.contains(TOKEN) || s.contains(TOKEN_SECRET); + let mut seen = vec![]; + + // Tailscale echoing it back in its errors, on every failure path. + for m in [ + Mock { + refuse_client: true, + ..fresh() + }, + Mock { + races: 2, + ..fresh() + }, + Mock { + magic_dns: false, + nameservers: vec!["1.1.1.1".into()], + refuse_revoke: true, + ..fresh() + }, + Mock { + refuse_revoke: true, + ..fresh() + }, + ] { + let (base, _) = serve(Mock { + echo_token: true, + ..m + }) + .await; + let host = FakeHost::default(); + let p = plan_with(&api(&base), &host).await; + seen.push(format!("{p:?}")); + seen.push(serde_json::to_string(&p.ok()).unwrap()); + let out = apply_with(&api(&base), &host).await; + seen.push(format!("{out:?}")); + if let Ok(o) = &out { + seen.push(serde_json::to_string(o).unwrap()); + } + for (id, secret) in host.saved.lock().unwrap().iter() { + seen.push(format!("{id} {secret}")); + } + } + // Errors straight from Tailscale's answers. + let (base, _) = serve(Mock { + echo_token: true, + ..fresh() + }) + .await; + let a = api(&base); + let e = a.get("/nowhere").await.unwrap_err(); + assert!( + e.message.contains("•••"), + "the mock echoed it: {}", + e.message + ); + seen.push(e.to_string()); + seen.push(format!("{e:?}")); + seen.push(say(&e, "do it")); + // Unreachable Tailscale. + let e = Api::at("http://127.0.0.1:9", Token::new(TOKEN)) + .get("/x") + .await + .unwrap_err(); + seen.push(e.to_string()); + seen.push(format!( + "{:?}", + Api::at("http://x", Token::new(TOKEN)).token + )); + + for s in &seen { + assert!(!leaks(s), "the token shows in: {s}"); + } + let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap(); + assert!( + logs.contains("tailscale setup planned"), + "the logs were captured: {}", + &logs[..logs.len().min(2000)] + ); + assert!(!leaks(&logs), "the token shows in the logs"); +} From 681ec2bba69cece3a005f839677e60f3b84abe7d Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Wed, 18 Nov 2026 23:21:16 +0700 Subject: [PATCH 03/32] feat(dash): set up tailscale with an access token The Tailscale card now leads with one field for an API access token, a link to Tailscale's Keys page, and a Check step that shows what Pyo will change, with the policy lines it adds, before Set up. Making an OAuth client by hand stays as "Set up with an OAuth client instead". --- dash/src/components/pyo/Tailscale.tsx | 239 +++++++++++++++++++++++--- dash/src/lib/pyo/store.ts | 8 + dash/src/lib/pyo/types.ts | 20 +++ 3 files changed, 244 insertions(+), 23 deletions(-) diff --git a/dash/src/components/pyo/Tailscale.tsx b/dash/src/components/pyo/Tailscale.tsx index 6964d99..41782c4 100644 --- a/dash/src/components/pyo/Tailscale.tsx +++ b/dash/src/components/pyo/Tailscale.tsx @@ -1,4 +1,4 @@ -import { CheckCircleIcon, XCircleIcon } from "@phosphor-icons/react"; +import { CheckCircleIcon, WarningCircleIcon, XCircleIcon } from "@phosphor-icons/react"; import { useNavigate } from "@tanstack/react-router"; import { useState } from "react"; import { Badge } from "~/components/ui/Badge"; @@ -9,12 +9,28 @@ import { Callout } from "~/components/ui/Panel"; import { site } from "~/config/site"; import { api, usePyo } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; -import type { TailscaleCheck } from "~/lib/pyo/types"; +import type { TailscaleCheck, TailscaleSetupOutcome, TailscaleSetupPlan } from "~/lib/pyo/types"; /** Where a flow that needed Tailscale goes back to once it's saved. */ const BACK = "pyo.tailscaleBack"; const DOCS = `${site.docsUrl}/tailscale`; +const KEYS = "https://login.tailscale.com/admin/settings/keys"; + +const LINK = "font-medium text-primary hover:text-primary/80"; + +/** After saving: back to the flow that needed Tailscale, if one did. */ +function goBack(navigate: ReturnType): boolean { + let back: string | null = null; + try { + back = sessionStorage.getItem(BACK); + sessionStorage.removeItem(BACK); + } catch { + // Nowhere to go back to. + } + if (back) void navigate({ to: back as string }); + return !!back; +} /** * Shown in connect and add-server flows until Tailscale is set up: servers @@ -85,15 +101,7 @@ function ClientForm({ onDone, saved }: { onDone: () => void; saved?: string }) { setChecks(r.data.checks); if (!r.data.ok) return; toast({ title: "Tailscale saved" }); - let back: string | null = null; - try { - back = sessionStorage.getItem(BACK); - sessionStorage.removeItem(BACK); - } catch { - // Nowhere to go back to. - } - if (back) void navigate({ to: back as string }); - else onDone(); + if (!goBack(navigate)) onDone(); }} >
@@ -121,16 +129,201 @@ function ClientForm({ onDone, saved }: { onDone: () => void; saved?: string }) { - {saved ? ( -
+ + ); +} + +/** A list of short lines, each with its mark. */ +function Lines({ items, tone }: { items: string[]; tone: "done" | "todo" | "plan" }) { + if (!items.length) return null; + return ( +
    + {items.map((t) => ( +
  • + {tone === "todo" ? ( + + ) : tone === "done" ? ( + + ) : ( + + )} + {t} +
  • + ))} +
+ ); +} + +function Diff({ lines }: { lines: string[] }) { + if (!lines.length) return null; + return ( +
+      {lines.map((l, i) => (
+        
+ {l} +
+ ))} +
+ ); +} + +/** What setting up with a token did, until the card is closed. */ +export function SetupOutcome({ outcome }: { outcome: TailscaleSetupOutcome }) { + return ( +
+ {outcome.changed.length ? ( + + ) : outcome.ok ? ( +

Nothing changed on your tailnet.

+ ) : null} + {outcome.tokenDeleted ? : null} + {outcome.error ?

{outcome.error}

: null} + + {outcome.checks.some((c) => !c.ok) ? : null} +
+ ); +} + +/** The main way in: one short-lived API access token, and Pyo does the rest. */ +function TokenSetup({ onDone }: { onDone: (outcome: TailscaleSetupOutcome) => void }) { + const navigate = useNavigate(); + const [token, setToken] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [plan, setPlan] = useState(null); + const [outcome, setOutcome] = useState(null); + + const check = async () => { + setBusy(true); + setError(""); + setOutcome(null); + const r = await api.planTailscaleSetup(token); + setBusy(false); + if ("error" in r) return setError(r.error); + setPlan(r.data.plan); + }; + const apply = async () => { + setBusy(true); + setError(""); + const r = await api.setUpTailscale(token); + setBusy(false); + if ("error" in r) return setError(r.error); + if (!r.data.ok) { + // Stopped partway: what changed stays listed, and the token stays for another try. + setPlan(null); + return setOutcome(r.data); + } + setToken(""); + setPlan(null); + toast({ title: "Tailscale set up" }); + if (!goBack(navigate)) onDone(r.data); + }; + const reset = () => { + setPlan(null); + setError(""); + }; + + if (plan) + return ( +
+ {plan.blocked ? ( + {plan.blocked} + ) : plan.changes.length ? ( +
+

Pyo will

+ +
+ ) : ( +

Your tailnet is already set up.

+ )} + + + {plan.blocked ? null :

Pyo deletes the token when it's done.

} + {error ?

{error}

: null} +
+ {plan.blocked ? ( + + ) : ( + + )} + - ) : null} +
+
+ ); + + return ( +
{ + e.preventDefault(); + void check(); + }} + > +

+ Generate an API access token that expires in 1 day, and paste it here.{" "} + + Open Keys in Tailscale + +

+ {outcome ? : null} +
+ setToken(e.target.value)} + placeholder="tskey-api-…" + aria-label="API access token" + autoComplete="off" + className="h-8" + /> +
+ {error ?

{error}

: null} ); } +/** Setting up: with a token, or with an OAuth client made by hand. */ +function Setup({ saved, onDone }: { saved?: string; onDone: (outcome?: TailscaleSetupOutcome) => void }) { + const [byClient, setByClient] = useState(false); + return ( +
+ {byClient ? ( + <> +

+ An OAuth client with Devices › Core and Auth Keys (both with tag:pyo) and Services.{" "} + + How to make one + +

+ onDone()} /> + + ) : ( + + )} +
+ + {saved ? ( + + ) : null} +
+
+ ); +} + function NameRow({ kind, label }: { kind: "dashboard" | "registry" | "sandboxes"; label: string }) { const ts = usePyo().tailscale; const [editing, setEditing] = useState(false); @@ -252,6 +445,7 @@ export function TailscaleSettings() { const ts = s.tailscale; const [replacing, setReplacing] = useState(false); const [checks, setChecks] = useState([]); + const [outcome, setOutcome] = useState(null); const [testing, setTesting] = useState(false); const [removing, setRemoving] = useState(false); if (!s.user.isAdmin) @@ -271,15 +465,13 @@ export function TailscaleSettings() {
  • {!ts || replacing ? ( - <> -

    - An OAuth client with Devices › Core and Auth Keys (both with tag:pyo) and Services.{" "} - - How to make one - -

    - setReplacing(false)} /> - + { + setReplacing(false); + setOutcome(o ?? null); + }} + /> ) : ( <>
    @@ -311,6 +503,7 @@ export function TailscaleSettings() { Remove
    + {outcome ? : null} {checks.length ? : null} )} diff --git a/dash/src/lib/pyo/store.ts b/dash/src/lib/pyo/store.ts index b15f46e..b8d0de5 100644 --- a/dash/src/lib/pyo/store.ts +++ b/dash/src/lib/pyo/store.ts @@ -50,6 +50,8 @@ import type { PublicDashboard, TailscaleCheck, TailscaleInfo, + TailscaleSetupOutcome, + TailscaleSetupPlan, CloudflareAccount, GitConnection, GitConnectionCheck, @@ -2492,6 +2494,12 @@ export const api = { ...(secret?.trim() ? { secret: secret.trim() } : {}), }); }, + planTailscaleSetup(token: string) { + return attempt<{ plan: TailscaleSetupPlan }>("planTailscaleSetup", { token: token.trim() }); + }, + setUpTailscale(token: string) { + return attempt("setUpTailscale", { token: token.trim() }); + }, testTailscale() { return attempt<{ checks: TailscaleCheck[] }>("testTailscale", {}); }, diff --git a/dash/src/lib/pyo/types.ts b/dash/src/lib/pyo/types.ts index 29fc1ef..0a56567 100644 --- a/dash/src/lib/pyo/types.ts +++ b/dash/src/lib/pyo/types.ts @@ -1872,6 +1872,26 @@ export type CloudOptions = { /** One check of the Tailscale client (Test). */ export type TailscaleCheck = { name: string; ok: boolean; message: string }; +/** What setting up Tailscale with an access token would change (planTailscaleSetup). */ +export type TailscaleSetupPlan = { + changes: string[]; + done: string[]; + /** Policy lines added ("+ …") or changed ("- …"). */ + diff: string[]; + /** Why Pyo can't go on by itself. `diff` then holds the lines to add. */ + blocked: string | null; +}; + +/** What setting up Tailscale with an access token did (setUpTailscale). */ +export type TailscaleSetupOutcome = { + ok: boolean; + changed: string[]; + todo: string[]; + error: string | null; + checks: TailscaleCheck[]; + tokenDeleted: boolean; +}; + /** Pyo on the public IP (admins only). */ export type PublicDashboard = { open: boolean; From 45ca827f91c01180c13adb2c8c39f46f9878321b Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Thu, 19 Nov 2026 01:07:00 +0700 Subject: [PATCH 04/32] feat(dash): let secret fields paste from the clipboard SecretInput takes an optional onPasteText. Where the browser can read the clipboard, a paste button sits beside the show toggle. --- dash/src/components/ui/Field.tsx | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/dash/src/components/ui/Field.tsx b/dash/src/components/ui/Field.tsx index d0f2f85..cc1a162 100644 --- a/dash/src/components/ui/Field.tsx +++ b/dash/src/components/ui/Field.tsx @@ -1,6 +1,7 @@ import { Tabs } from "./Tabs"; import { CircleNotchIcon, + ClipboardTextIcon, EyeIcon, EyeSlashIcon, MinusIcon, @@ -128,6 +129,7 @@ export { Select } from "./Select"; * Masked value with an eye toggle inside. Pass `shown` and `onToggle` to * control it (e.g. fetch a stored value first); `busy` spins the eye, * `toggleDisabled` disables it with that reason as its title. + * `onPasteText` adds a paste button, where the browser can read the clipboard. */ export const SecretInput = forwardRef< HTMLInputElement, @@ -136,12 +138,17 @@ export const SecretInput = forwardRef< onToggle?: () => void; busy?: boolean; toggleDisabled?: string; + onPasteText?: (text: string) => void; } >(function SecretInput( - { className = "", shown: shownProp, onToggle, busy, toggleDisabled, ...props }, + { className = "", shown: shownProp, onToggle, busy, toggleDisabled, onPasteText, ...props }, ref, ) { const [own, setOwn] = useState(false); + const [canPaste, setCanPaste] = useState(false); + useEffect(() => { + setCanPaste(!!onPasteText && typeof navigator !== "undefined" && !!navigator.clipboard?.readText); + }, [onPasteText]); const shown = shownProp ?? own; return (
    @@ -149,9 +156,26 @@ export const SecretInput = forwardRef< ref={ref} type={shown ? "text" : "password"} autoComplete="new-password" - className={`${inputClass} pr-9 font-mono text-[12px] ${className}`} + className={`${inputClass} ${canPaste ? "pr-16" : "pr-9"} font-mono text-[12px] ${className}`} {...props} /> + {canPaste ? ( + + ) : null} - {replacing ? ( - + {admin && problems.length ? ( +
      + {problems.map((p) => ( +
    • {p}
    • + ))} +
    ) : null} - + + ) : null; + + const shell = (p: { body: ReactNode; footer?: ReactNode; onSubmit?: () => void }) => ( + + {p.body} + ); - return ( - <> -
      -
    • - - - -
      -

      Cloudflare API token

      -

      - {account - ? `${account.hint ? `Saved · ${account.hint} · ` : ""}Tested ${timeAgo(account.testedAt)}` - : admin - ? "Zone:Read and DNS:Edit, on the zones Pyo may use." - : "An owner or admin can connect Cloudflare."} -

      -
      - {!admin ? ( - account ? ( - Connected - ) : ( - Not connected - ) - ) : !account || replacing ? ( - form - ) : ( - - - - - - )} - {error ? ( -

      {error}

      - ) : null} -
    • - {account ? ( -
    • -

      - {editable.length === 1 ? "1 zone" : `${editable.length} zones`} -

      -
      - {editable.map((z) => ( - - {z.name} - - ))} - {lacking.map((z) => ( - - {z.name} - {z.missing ? ` · needs ${z.missing}` : ""} - - ))} -
      - {admin && problems.length ? ( -
        - {problems.map((p) => ( -
      • {p}
      • - ))} -
      - ) : null} -
    • + if (!admin) + return shell({ + body: ( +
      + Connected], + ["Tested", timeAgo(account.testedAt)], + ] + : [["Status", Not connected]] + } + /> + {account ? zones :

      An owner or admin can connect Cloudflare.

      } +
      + ), + footer: ( + + ), + }); + + if (!account || replacing) + return shell({ + onSubmit: () => void save(), + body: ( +
      + + {(p) => ( + setToken(e.target.value)} + onPasteText={setToken} + autoComplete="off" + /> + )} + +

      + Create a token in Cloudflare +

      +
      + ), + footer: ( + <> + + + + ), + }); + + return shell({ + body: ( +
      + + {account.hint ?? "Saved"} + + , + ], + ["Tested", timeAgo(account.testedAt)], + ]} + /> + {zones} + {confirming ? ( + setConfirming(false)} + onConfirm={() => { + setConfirming(false); + void api.removeCloudflare(); + toast({ title: "Cloudflare token removed" }); + }} + > + Records Pyo made stay in Cloudflare. + ) : null} -
    - setRemoving(false)} - title="Remove the Cloudflare token?" - description="Records Pyo made stay in Cloudflare." - confirmLabel="Remove" - onConfirm={() => { - void api.removeCloudflare(); - toast({ title: "Cloudflare token removed" }); - }} - /> - - ); +
    + ), + footer: confirming ? null : ( + <> + + + + + ), + }); } /** What to do about a new domain's DNS record in Cloudflare. */ @@ -359,7 +394,7 @@ export function DnsRecordLine({ app, d }: { app: Application; d: Domain }) { : r.proxy ? "· Proxied once the certificate is issued" : null} - {r.error ? · {r.error} : null} + {r.error ? · {r.error} : null} {(r.proxied || r.proxy) && !app.behindCdn ? ( { try { @@ -20,202 +30,365 @@ const host = (url: string) => { } }; -/** Add a connection, or replace one's token. */ -export function TokenDialog({ +const GITLAB = ; +const GITHUB = ; + +function ConnectionRow({ + c, + onReplace, +}: { + c: GitConnection; + onReplace: () => void; +}) { + const [confirming, setConfirming] = useState(false); + const [testing, setTesting] = useState(false); + const polled = c.webhooks.filter((w) => !w.active).length; + const problems = c.info.problems ?? []; + const expires = c.info.expiresAt ? `Expires ${c.info.expiresAt}` : null; + return ( + Needs attention : null} + actions={ + confirming ? null : ( + <> + + + + + ) + } + > + {problems.length ? ( +
      + {problems.map((p) => ( +
    • {p}
    • + ))} +
    + ) : null} + {confirming ? ( + setConfirming(false)} + onConfirm={async () => { + setConfirming(false); + if (await api.removeGitConnection(c.id)) toast({ title: `Removed ${c.account}` }); + }} + > + Pyo removes its webhooks. Revoke the token in GitLab too. + + ) : null} +
    + ); +} + +/** Add a GitLab, or replace one's token. */ +function TokenForm({ connection, - onClose, + url, + setUrl, + token, + setToken, + error, }: { connection?: GitConnection; - onClose: () => void; + url: string; + setUrl: (v: string) => void; + token: string; + setToken: (v: string) => void; + error: string; }) { + return ( +
    + {connection ? ( +

    + A new token for {connection.account} on{" "} + {host(connection.url)}. +

    + ) : ( + + {(p) => ( + setUrl(e.target.value)} + placeholder="https://gitlab.example.com" + /> + )} + + )} + + {(p) => ( + setToken(e.target.value)} + onPasteText={setToken} + placeholder="glpat-…" + /> + )} + +
    + ); +} + +/** + * Integrations › GitLab: the team's connections, and a form to add one or + * replace one's token. Opens on the form while there are none. + */ +export function GitlabDialog({ onClose }: { onClose: () => void }) { + const s = usePyo(); + const list = s.gitConnections.filter((c) => c.teamId === s.currentTeamId); + const [form, setForm] = useState<"add" | GitConnection | null>(list.length ? null : "add"); const [url, setUrl] = useState("https://gitlab.com"); const [token, setToken] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); + const connection = form && form !== "add" ? form : undefined; const ready = !!token.trim() && (!!connection || !!url.trim()); + const open = (f: "add" | GitConnection | null) => { + setForm(f); + setUrl("https://gitlab.com"); + setToken(""); + setError(""); + }; + const back = () => (list.length ? open(null) : onClose()); + + if (form) + return ( + { + if (!ready || busy) return; + setBusy(true); + setError(""); + const r = connection + ? await api.replaceGitConnectionToken(connection.id, token.trim()) + : await api.addGitConnection(url.trim(), token.trim()); + setBusy(false); + if ("error" in r) return setError(r.error); + toast({ + title: connection ? "Token replaced" : "GitLab connected", + ...(r.data.warning ? { tone: "error" as const, description: r.data.warning } : {}), + }); + open(null); + }} + footer={ + <> + + + + } + > + + + ); + return ( - { - if (!ready || busy) return; - setBusy(true); - setError(""); - const r = connection - ? await api.replaceGitConnectionToken(connection.id, token.trim()) - : await api.addGitConnection(url.trim(), token.trim()); - setBusy(false); - if ("error" in r) { - setError(r.error); - return; - } - toast({ - title: connection ? "Token replaced" : "GitLab connected", - ...(r.data.warning - ? { tone: "error" as const, description: r.data.warning } - : {}), - }); - onClose(); - }} footer={ <> - - } > -
    - {connection ? null : ( - - {(p) => ( - setUrl(e.target.value)} - placeholder="https://gitlab.example.com" - /> - )} - - )} - - {(p) => ( - setToken(e.target.value)} - placeholder="glpat-…" - /> - )} - -
    -
    + + {list.map((c) => ( + open(c)} /> + ))} + + ); } -function ConnectionRow({ c }: { c: GitConnection }) { - const [replacing, setReplacing] = useState(false); - const [removing, setRemoving] = useState(false); - const [testing, setTesting] = useState(false); - const polled = c.webhooks.filter((w) => !w.active).length; - const problems = c.info.problems ?? []; - const expires = c.info.expiresAt ? `Expires ${c.info.expiresAt}` : null; +function GithubRow({ g }: { g: GithubInstallation }) { + const [confirming, setConfirming] = useState(false); return ( -
  • - - - -
    -

    GitLab · {c.account}

    -

    - {[ - host(c.url), - expires, - polled ? `${polled} checked every minute` : null, - ] - .filter(Boolean) - .join(" · ")} -

    -
    - {problems.length ? Needs attention : null} - - + + ) + } + > + {confirming ? ( + setConfirming(false)} + onConfirm={async () => { + setConfirming(false); + if (await api.removeGithubInstallation(g.id)) + toast({ + title: `Disconnected ${g.account}`, + description: "Uninstall the app on GitHub too.", + }); }} > - {testing ? "Testing…" : "Test"} - - - - - {replacing ? ( - setReplacing(false)} /> + Uninstall the app on GitHub too. + ) : null} - setRemoving(false)} - onConfirm={async () => { - setRemoving(false); - if (await api.removeGitConnection(c.id)) - toast({ title: `Removed ${c.account}` }); - }} - title={`Remove ${c.account}?`} - description="Pyo removes its webhooks. Revoke the token in GitLab too." - confirmLabel="Remove" - /> -
  • + ); } -/** Integrations › Git providers: the team's GitLab connections. */ -export function GitlabRows() { +/** Integrations › GitHub: the team's GitHub accounts, through this installation's GitHub App. */ +export function GithubDialog({ onClose }: { onClose: () => void }) { const s = usePyo(); - const [adding, setAdding] = useState(false); - const list = s.gitConnections.filter((c) => c.teamId === s.currentTeamId); - return ( - <> - {list.map((c) => ( - - ))} -
  • - - - -
    -

    - {list.length ? "Another GitLab" : "GitLab"} -

    -

    - gitlab.com or your own GitLab, with an access token. -

    -
    - + + Set up + + + ) : ( + + ), + ); + + const connectLabel = busy ? Opening GitHub… : installs.length ? "Connect another" : "Connect"; + return shell( + installs.length ? ( + + {installs.map((g) => ( + + ))} + + ) : ( +

    + Install {s.github.name} and pick the repositories Pyo can see. +

    + ), + installs.length ? ( + <> + + + + ) : ( + <> + + -
  • - {adding ? setAdding(false)} /> : null} - + + ), ); } diff --git a/dash/src/components/pyo/Hetzner.tsx b/dash/src/components/pyo/Hetzner.tsx index 15ea6a1..b0735e3 100644 --- a/dash/src/components/pyo/Hetzner.tsx +++ b/dash/src/components/pyo/Hetzner.tsx @@ -4,12 +4,22 @@ import { TrashIcon, WarningCircleIcon, } from "@phosphor-icons/react"; -import { useEffect, useState } from "react"; +import { useEffect, useState, type ReactNode } from "react"; +import { siHetzner } from "simple-icons"; +import { BrandMark } from "~/components/pyo/common"; +import { + Busy, + ConfirmNote, + DialogSection, + ExternalLink, + IntegrationDialog, + Summary, +} from "~/components/pyo/IntegrationDialog"; import { useTeamAdmin } from "~/components/pyo/database/NewDatabase"; import { Badge, type Tone } from "~/components/ui/Badge"; import { Button } from "~/components/ui/Button"; import { ConfirmDialog } from "~/components/ui/Dialog"; -import { Field, Input, Select, Textarea } from "~/components/ui/Field"; +import { Field, SecretInput, Select, Textarea } from "~/components/ui/Field"; import { Callout } from "~/components/ui/Panel"; import { StatusNote } from "~/components/ui/StatusNote"; import { TailnetLockSign } from "~/components/pyo/TailnetLock"; @@ -100,34 +110,19 @@ export function DeleteCloudServerDialog({ toast({ title: `Deleting ${server.name}` }); }} title={server ? `Delete ${server.name} at Hetzner?` : ""} - description={ - server - ? server.sandboxServerId - ? `Its sandboxes end. Then it leaves your tailnet, and Hetzner deletes it. ${money(server.currency, server.monthly)} a month stops.` - : `Its services move off it first. Then it leaves the cluster and your tailnet, and Hetzner deletes it. ${money(server.currency, server.monthly)} a month stops.` - : "" - } + description={server ? deleteText(server) : ""} confirmLabel="Delete server" /> ); } -/** - * The team's Hetzner project token: paste, check and save. In Integrations, - * and inline where a server is bought before Hetzner is connected. - */ -export function HetznerConnectForm({ - onSaved, - onCancel, -}: { - onSaved?: () => void; - onCancel?: () => void; -}) { - const s = usePyo(); +/** Paste, check and save the team's Hetzner project token. */ +function useHetznerToken(onSaved?: () => void) { const [token, setToken] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const save = async () => { + if (busy || !token.trim()) return; setBusy(true); setError(""); const r = await api.saveHetzner(token); @@ -137,34 +132,34 @@ export function HetznerConnectForm({ toast({ title: "Hetzner connected" }); onSaved?.(); }; + return { token, setToken, busy, error, save }; +} + +/** + * The team's Hetzner project token, inline where a server is bought before + * Hetzner is connected. + */ +export function HetznerConnectForm({ + onSaved, + onCancel, +}: { + onSaved?: () => void; + onCancel?: () => void; +}) { + const s = usePyo(); + const { token, setToken, busy, error, save } = useHetznerToken(onSaved); return (
    { e.preventDefault(); void save(); }} > -

    - A project API token with Read & Write.{" "} - - How to make one - -

    - setToken(e.target.value)} - placeholder="API token" - aria-label="API token" - autoComplete="off" - className="h-8" - disabled={!s.tailscale} - /> - {error ?

    {error}

    : null} +
    {onCancel ? ( - - -
    - - )} - - {servers.map((c) => { - const cluster = s.clusters.find((x) => x.id === c.clusterId); - return ( -
  • + const needsTailscale = !s.tailscale ? ( + + Servers join over your tailnet. Set up{" "} + + Tailscale + {" "} + first. + + ) : null; + const serverList = servers.length ? ( + +
      + {servers.map((c) => ( +
    • +
      -

      {c.name}

      -

      - {c.sandboxServerId ? "Sandbox server" : (cluster?.name ?? "Cluster removed")} ·{" "} - {c.serverType} · {c.location} · {money(c.currency, c.monthly)}/mo -

      - {c.error ?

      {c.error}

      : null} +

      {c.name}

      +

      {serverMeta(s, c)}

      + {c.error ?

      {c.error}

      : null}
      - {admin && c.state !== "removing" ? ( - ) : null} -
    • - ); - })} +
+ {deleting === c.id ? ( + setDeleting(null)} + onConfirm={async () => { + setDeleting(null); + if (await api.deleteCloudServer(c.id)) toast({ title: `Deleting ${c.name}` }); + }} + > + {deleteText(c)} + + ) : null} + + ))} - setRemoving(false)} - onConfirm={() => { - setRemoving(false); - void api.removeHetzner(); - }} - title="Remove Hetzner?" - description="Servers Pyo made there keep running." - confirmLabel="Remove" - /> - setDeleting(null)} /> - + + ) : null; + const shell = (p: { body: ReactNode; footer?: ReactNode; onSubmit?: () => void }) => ( + + {p.body} + ); + + if (!admin) + return shell({ + body: ( +
+ {needsTailscale} + Connected], + ["Token", {conn.hint}], + ] + : [["Status", Not connected]] + } + /> + {conn ? null :

A team admin can connect it.

} + {serverList} +
+ ), + footer: ( + + ), + }); + + if (!conn || replacing) + return shell({ + onSubmit: () => void form.save(), + body: ( +
+ {needsTailscale} + + {conn ? null : serverList} +
+ ), + footer: ( + <> + + + + ), + }); + + return shell({ + body: ( +
+ {needsTailscale} + + {conn.hint} + + , + ], + ...(seen ? [["Locations", seen] as [string, string]] : []), + ]} + /> + {serverList} + {confirming ? ( + setConfirming(false)} + onConfirm={() => { + setConfirming(false); + void api.removeHetzner(); + }} + > + Servers Pyo made there keep running. + + ) : null} +
+ ), + footer: confirming ? null : ( + <> + + + + + ), + }); } /** What a new server at Hetzner is: location, type and an SSH key. */ diff --git a/dash/src/components/pyo/IntegrationCard.tsx b/dash/src/components/pyo/IntegrationCard.tsx index 96ce7b3..95478ac 100644 --- a/dash/src/components/pyo/IntegrationCard.tsx +++ b/dash/src/components/pyo/IntegrationCard.tsx @@ -1,51 +1,34 @@ -import { CaretRightIcon, DotsThreeVerticalIcon } from "@phosphor-icons/react"; import type { ReactNode } from "react"; -import { Dot, type Tone } from "~/components/ui/Badge"; -import { Button } from "~/components/ui/Button"; -import { Menu, type MenuItem } from "~/components/ui/Menu"; -import { site } from "~/config/site"; +import { Badge, Dot, type Tone } from "~/components/ui/Badge"; +import { LogoTile } from "~/components/pyo/IntegrationDialog"; -// One integration on Integrations: a header with its icon, name and -// category, a body that says what it does, and a footer with how it stands -// (connected) or its setup guide (not connected). +// One integration on Integrations, the same size as the rest: its logo, +// name and what it's for, how it stands, and one action (Set up or Manage). export type IntegrationCardProps = { id: string; name: string; - category: string; icon: ReactNode; + /** What it's for, in one short line. */ description: string; - connected: boolean; - /** One real figure, connected only. */ - stat?: { label: string; value: ReactNode } | null; - /** What it enables, not connected only. */ - /** How it stands, connected only. */ - status?: { tone: Tone; label: string } | null; - /** The docs page (pyo.dev/docs/). */ - docs?: string; - /** Not connected: the Connect button (or why there isn't one). */ - action?: ReactNode; - /** Connected: what can be done with it. */ - menu?: MenuItem[]; + /** Connected, Not set up, Needs attention, or a step under way. */ + status: { tone: Tone; label: string }; + /** One fact beside the action: the tailnet, a count, or what needs a look. */ + detail?: ReactNode; + /** Set up or Manage (or why there's no button). */ + action: ReactNode; /** Just linked to: a ring for a moment. */ highlight?: boolean; }; -/** A docs link as a plain anchor. */ -export const docsUrl = (page: string) => `${site.docsUrl}/${page}`; - export function IntegrationCard({ id, name, - category, icon, description, - connected, - stat, status, - docs, + detail, action, - menu, highlight, }: IntegrationCardProps) { return ( @@ -54,88 +37,27 @@ export function IntegrationCard({ aria-labelledby={`${id}-name`} className={`flex min-w-0 scroll-mt-4 flex-col rounded-2xl border border-frame-border bg-muted p-[5px] shadow-card transition-shadow duration-500 ${highlight ? "ring-2 ring-ring ring-offset-2 ring-offset-canvas" : ""}`} > -
- - {icon} - +
+
-

- {name} -

-

- {category} -

-
- {connected ? ( - - - Connected - - ) : ( - {action} - )} - {menu?.length && connected ? ( - ( - - )} - /> - ) : null} -
-
-
- {/* Two lines for the description and one for the stat, always, - so every card is the same height. */} -

+

+

+ {name} +

+ + + {status.label} + +
+

{description}

-

- {connected && stat ? stat.label : "\u00a0"} - - {connected && stat ? stat.value : null} - -

-
- {connected ? ( - status ? ( - <> - {/* The header's pill already says connected: a dot only when - something needs a look or is under way. */} - {status.tone !== "success" ? : null} - {status.label} - - ) : null - ) : null} - {!connected && docs ? ( - - Setup guide - - - ) : null} -
+
+ {detail} + {action} +
); } diff --git a/dash/src/components/pyo/IntegrationDialog.tsx b/dash/src/components/pyo/IntegrationDialog.tsx new file mode 100644 index 0000000..0803bdf --- /dev/null +++ b/dash/src/components/pyo/IntegrationDialog.tsx @@ -0,0 +1,264 @@ +import { + ArrowSquareOutIcon, + CheckIcon, + CircleNotchIcon, +} from "@phosphor-icons/react"; +import { useEffect, useRef, type FormEvent, type ReactNode } from "react"; +import { Button } from "~/components/ui/Button"; +import { Dialog } from "~/components/ui/Dialog"; +import { site } from "~/config/site"; + +// One pattern for every integration's dialog: its logo and name, one short +// sentence with the guide, the fields or what's connected, then Cancel and +// one primary action. Disconnecting asks inline, in the dialog itself. + +/** A docs link as a plain anchor. */ +export const docsUrl = (page: string) => `${site.docsUrl}/${page}`; + +/** The logo on a small tile, as on the card. */ +export function LogoTile({ icon, size = "md" }: { icon: ReactNode; size?: "sm" | "md" }) { + return ( + + {icon} + + ); +} + +export function IntegrationDialog({ + icon, + name, + description, + docs, + onClose, + onSubmit, + footer, + children, +}: { + icon: ReactNode; + name: string; + /** One short sentence. */ + description?: ReactNode; + /** The docs page, linked after the description. */ + docs?: string; + onClose: () => void; + /** The body is a form: Enter submits. */ + onSubmit?: (e: FormEvent) => void; + footer?: ReactNode; + children: ReactNode; +}) { + return ( + + + {name} + + } + description={ + description || docs ? ( + <> + {description} + {description && docs ? " " : null} + {docs ? Guide : null} + + ) : undefined + } + footer={footer} + > + {children} + + ); +} + +/** A link out of Pyo, marked as one. */ +export function ExternalLink({ + href, + children, + className = "", +}: { + href: string; + children: ReactNode; + className?: string; +}) { + return ( + + {children} + + (opens in a new tab) + + ); +} + +/** A small text button, for a second way in ("Use an OAuth client instead"). */ +export function TextButton({ onClick, children }: { onClick: () => void; children: ReactNode }) { + return ( + + ); +} + +/** A button's label while it works: a spinner and the label. */ +export function Busy({ children }: { children: ReactNode }) { + return ( + <> + + {children} + + ); +} + +/** Where a flow is: done steps get a check, the current one is marked. */ +export function Steps({ steps, at }: { steps: string[]; at: number }) { + return ( +
    + {steps.map((label, i) => ( +
  1. + + {i < at ? : i + 1} + + + {label} + + {i < steps.length - 1 ? : null} +
  2. + ))} +
+ ); +} + +/** A row in a dialog's list: icon, name, one line about it, and its actions. */ +export function DialogRow({ + icon, + title, + meta, + badge, + actions, + children, +}: { + icon?: ReactNode; + title: ReactNode; + meta?: ReactNode; + badge?: ReactNode; + actions?: ReactNode; + /** Under the row: an inline confirm, an error. */ + children?: ReactNode; +}) { + return ( +
  • +
    + {icon ? ( + + {icon} + + ) : null} +
    +

    {title}

    + {meta ?

    {meta}

    : null} +
    + {badge} + {actions ? {actions} : null} +
    + {children} +
  • + ); +} + +/** Rows that run edge to edge in the dialog's card. */ +export function DialogRows({ children }: { children: ReactNode }) { + return
      {children}
    ; +} + +/** + * Confirm a destructive action in place (no second dialog): what happens, + * then Cancel and the action. Focus moves to Cancel when it shows. + */ +export function ConfirmNote({ + title, + children, + confirmLabel, + busy, + onConfirm, + onCancel, +}: { + title: string; + children?: ReactNode; + confirmLabel: string; + busy?: boolean; + onConfirm: () => void; + onCancel: () => void; +}) { + const cancel = useRef(null); + useEffect(() => { + cancel.current?.focus(); + cancel.current?.scrollIntoView({ block: "nearest" }); + }, []); + return ( +
    +

    {title}

    + {children ?

    {children}

    : null} +
    + + +
    +
    + ); +} + +/** What's connected, as label and value rows in a box. */ +export function Summary({ items }: { items: [ReactNode, ReactNode][] }) { + return ( +
    + {items.map(([k, v], i) => ( +
    +
    {k}
    +
    {v}
    +
    + ))} +
    + ); +} + +/** A section's small heading inside a dialog. */ +export function DialogSection({ title, children }: { title: string; children: ReactNode }) { + return ( +
    +

    {title}

    + {children} +
    + ); +} diff --git a/dash/src/components/pyo/RegistryLogins.tsx b/dash/src/components/pyo/RegistryLogins.tsx index 10f9051..fbff12e 100644 --- a/dash/src/components/pyo/RegistryLogins.tsx +++ b/dash/src/components/pyo/RegistryLogins.tsx @@ -1,11 +1,17 @@ import { PackageIcon, PlusIcon, TrashIcon } from "@phosphor-icons/react"; import { useState } from "react"; -import { BrandMark } from "~/components/pyo/common"; +import { BrandMark, DOCKER_LOGO } from "~/components/pyo/common"; +import { + Busy, + ConfirmNote, + DialogRow, + DialogRows, + IntegrationDialog, +} from "~/components/pyo/IntegrationDialog"; import { AppLink } from "~/components/ui/AppLink"; import { registryIcon } from "~/components/pyo/ProjectCard"; import { Badge } from "~/components/ui/Badge"; import { Button } from "~/components/ui/Button"; -import { ConfirmDialog, Dialog } from "~/components/ui/Dialog"; import { Field, Input, SecretInput, Select } from "~/components/ui/Field"; import { timeAgo } from "~/lib/pyo/format"; import { api, usePyo } from "~/lib/pyo/store"; @@ -44,104 +50,57 @@ const PRESETS = [ const preset = (host: string) => PRESETS.find((p) => p.host === host); -/** Integrations › Registries: the built-in registry and the team's logins. */ -export function RegistryLoginsSettings() { - const s = usePyo(); - const logins = s.registryLogins.filter((l) => l.teamId === s.currentTeamId); - const [adding, setAdding] = useState(false); - const [removing, setRemoving] = useState(null); +const ICON = ; + +function LoginRow({ l }: { l: RegistryLogin }) { + const [confirming, setConfirming] = useState(false); + const p = preset(l.host); + const icon = registryIcon(l.host); return ( - <> -
      -
    • - - - -
      -

      Pyo registry (built in)

      -

      Images Pyo builds from Git.

      -
      - - Open - -
    • -
    - {logins.length ? ( -
      - {logins.map((l) => { - const p = preset(l.host); - const icon = registryIcon(l.host); - return ( -
    • - - {icon ? ( - - ) : ( - - )} - -
      -

      {p?.name ?? l.host}

      -

      - {l.username} ·{" "} - {l.lastUsedAt - ? `used ${timeAgo(l.lastUsedAt)}` - : "not used yet"} -

      -
      - {l.verified ? ( - Logged in - ) : ( - Not checked - )} - -
    • - ); - })} -
    - ) : ( -

    - No logins yet. Public images don't need one. -

    - )} -
    - -
    - setAdding(false)} /> - setRemoving(null)} - title={`Remove the login for ${removing?.host}?`} - description="Its private images can't redeploy until you add a login." - confirmLabel="Remove login" - onConfirm={async () => { - if (removing && (await api.removeRegistryLogin(removing.id))) - toast({ title: `Removed the login for ${removing.host}` }); - }} - /> - + : } + title={p?.name ?? l.host} + meta={`${l.username} · ${l.lastUsedAt ? `used ${timeAgo(l.lastUsedAt)}` : "not used yet"}`} + badge={l.verified ? Logged in : Not checked} + actions={ + confirming ? null : ( + + ) + } + > + {confirming ? ( + setConfirming(false)} + onConfirm={async () => { + setConfirming(false); + if (await api.removeRegistryLogin(l.id)) toast({ title: `Removed the login for ${l.host}` }); + }} + > + Its private images can't redeploy until you add a login. + + ) : null} + ); } -export function AddLoginDialog({ - open, - onClose, -}: { - open: boolean; - onClose: () => void; -}) { +/** + * Integrations › Container registries: the built-in registry, the team's + * logins, and a form to add one. Opens on the form while there are none. + */ +export function RegistriesDialog({ onClose }: { onClose: () => void }) { + const s = usePyo(); + const logins = s.registryLogins.filter((l) => l.teamId === s.currentTeamId); + const [adding, setAdding] = useState(!logins.length); const [kind, setKind] = useState("ghcr.io"); const [other, setOther] = useState(""); const [username, setUsername] = useState(""); @@ -149,107 +108,132 @@ export function AddLoginDialog({ const [saving, setSaving] = useState(false); const p = preset(kind); const host = kind === "other" ? other.trim() : kind; - const close = () => { + const ready = !!host && !!username.trim() && !!password; + const toList = () => { setUsername(""); setPassword(""); setOther(""); - onClose(); + setAdding(false); }; + const back = () => (logins.length ? toList() : onClose()); + + if (adding) + return ( + { + if (!ready || saving) return; + setSaving(true); + const r = await api.saveRegistryLogin({ host, username: username.trim(), password }); + setSaving(false); + if (!r) return; + toast({ + title: `Saved the login for ${r.host}`, + description: r.verified + ? "The registry accepted it." + : "Couldn't reach the registry to check it. It's used on the next deploy.", + }); + toList(); + }} + footer={ + <> + + + + } + > +
    + + {(f) => ( + + )} + + {kind === "other" ? ( + + {(f) => ( + setOther(e.target.value)} + placeholder="registry.example.com" + /> + )} + + ) : null} + + {(f) => ( + setUsername(e.target.value)} + placeholder={p?.user ?? "Username"} + autoComplete="off" + /> + )} + + + {(f) => ( + setPassword(e.target.value)} + onPasteText={setPassword} + /> + )} + +
    +
    + ); + return ( - { - if (!host || !username.trim() || !password || saving) return; - setSaving(true); - const r = await api.saveRegistryLogin({ - host, - username: username.trim(), - password, - }); - setSaving(false); - if (!r) return; - toast({ - title: `Saved the login for ${r.host}`, - description: r.verified - ? "The registry accepted it." - : "Couldn't reach the registry to check it. It's used on the next deploy.", - }); - close(); - }} + - - } > -
    - - {(f) => ( - - )} - - {kind === "other" ? ( - - {(f) => ( - setOther(e.target.value)} - placeholder="registry.example.com" - /> - )} - - ) : null} - - {(f) => ( - setUsername(e.target.value)} - placeholder={p?.user ?? "Username"} - autoComplete="off" - /> - )} - - - {(f) => ( - setPassword(e.target.value)} - /> - )} - -
    -
    + + } + title="Pyo registry (built in)" + meta="Images Pyo builds from Git." + actions={ + + Open + + } + /> + {logins.map((l) => ( + + ))} + + ); } diff --git a/dash/src/components/pyo/SecretStores.tsx b/dash/src/components/pyo/SecretStores.tsx index 1c7270b..954a349 100644 --- a/dash/src/components/pyo/SecretStores.tsx +++ b/dash/src/components/pyo/SecretStores.tsx @@ -1,9 +1,17 @@ import { KeyIcon, PlusIcon, TrashIcon } from "@phosphor-icons/react"; import { useState } from "react"; +import { siVault } from "simple-icons"; +import { BrandMark } from "~/components/pyo/common"; +import { + Busy, + ConfirmNote, + DialogRow, + DialogRows, + IntegrationDialog, +} from "~/components/pyo/IntegrationDialog"; import { Badge } from "~/components/ui/Badge"; import { Button } from "~/components/ui/Button"; -import { ConfirmDialog, Dialog } from "~/components/ui/Dialog"; -import { Field, Input, Select, Textarea } from "~/components/ui/Field"; +import { Field, Input, SecretInput, Select, Textarea } from "~/components/ui/Field"; import { Panel } from "~/components/ui/Panel"; import { api, usePyo } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; @@ -114,12 +122,19 @@ function optionsOf(f: Form): Record { } } +const ICON = ; +const ABOUT = "Services import secrets from your store on each deploy."; + /** Connect a store, or change one. Its credential is never shown again. */ -export function StoreDialog({ +function StoreForm({ store, + onDone, + onCancel, onClose, }: { store?: SecretStore; + onDone: () => void; + onCancel: () => void; onClose: () => void; }) { const s = usePyo(); @@ -165,24 +180,35 @@ export function StoreDialog({ extra: { password?: boolean; hint?: string; optional?: boolean } = {}, ) => ( - {(p) => ( - set({ [key]: e.target.value })} - placeholder={placeholder} - /> - )} + {(p) => + extra.password ? ( + set({ [key]: e.target.value })} + onPasteText={(t) => set({ [key]: t })} + placeholder={placeholder} + /> + ) : ( + set({ [key]: e.target.value })} + placeholder={placeholder} + /> + ) + } ); return ( - { if (!ready || busy) return; setBusy(true); @@ -198,21 +224,21 @@ export function StoreDialog({ setBusy(false); if (!ok) return; toast({ title: store ? "Saved" : `Connected ${form.name.trim()}` }); - onClose(); + onDone(); }} footer={ <> - } >
    -
    +
    {(p) => ( setId(e.target.value)} - placeholder="Client ID" - aria-label="Client ID" - autoComplete="off" - className="h-8" - /> - setSecret(e.target.value)} - placeholder="tskey-client-…" - aria-label="Client secret" - autoComplete="off" - className="h-8" - /> -
    - {error ?

    {error}

    : null} - {checks.length ? : null} -
    - -
    - - ); -} - /** A list of short lines, each with its mark. */ function Lines({ items, tone }: { items: string[]; tone: "done" | "todo" | "plan" }) { if (!items.length) return null; return ( -
      +
        {items.map((t) => (
      • {tone === "todo" ? ( @@ -146,7 +103,7 @@ function Lines({ items, tone }: { items: string[]; tone: "done" | "todo" | "plan ) : tone === "done" ? ( ) : ( - + )} {t}
      • @@ -168,162 +125,23 @@ function Diff({ lines }: { lines: string[] }) { ); } -/** What setting up with a token did, until the card is closed. */ +/** What setting up with a token did. */ export function SetupOutcome({ outcome }: { outcome: TailscaleSetupOutcome }) { return (
        {outcome.changed.length ? ( ) : outcome.ok ? ( -

        Nothing changed on your tailnet.

        +

        Nothing changed on your tailnet.

        ) : null} {outcome.tokenDeleted ? : null} - {outcome.error ?

        {outcome.error}

        : null} + {outcome.error ?

        {outcome.error}

        : null} {outcome.checks.some((c) => !c.ok) ? : null}
        ); } -/** The main way in: one short-lived API access token, and Pyo does the rest. */ -function TokenSetup({ onDone }: { onDone: (outcome: TailscaleSetupOutcome) => void }) { - const navigate = useNavigate(); - const [token, setToken] = useState(""); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(""); - const [plan, setPlan] = useState(null); - const [outcome, setOutcome] = useState(null); - - const check = async () => { - setBusy(true); - setError(""); - setOutcome(null); - const r = await api.planTailscaleSetup(token); - setBusy(false); - if ("error" in r) return setError(r.error); - setPlan(r.data.plan); - }; - const apply = async () => { - setBusy(true); - setError(""); - const r = await api.setUpTailscale(token); - setBusy(false); - if ("error" in r) return setError(r.error); - if (!r.data.ok) { - // Stopped partway: what changed stays listed, and the token stays for another try. - setPlan(null); - return setOutcome(r.data); - } - setToken(""); - setPlan(null); - toast({ title: "Tailscale set up" }); - if (!goBack(navigate)) onDone(r.data); - }; - const reset = () => { - setPlan(null); - setError(""); - }; - - if (plan) - return ( -
        - {plan.blocked ? ( - {plan.blocked} - ) : plan.changes.length ? ( -
        -

        Pyo will

        - -
        - ) : ( -

        Your tailnet is already set up.

        - )} - - - {plan.blocked ? null :

        Pyo deletes the token when it's done.

        } - {error ?

        {error}

        : null} -
        - {plan.blocked ? ( - - ) : ( - - )} - -
        -
        - ); - - return ( -
        { - e.preventDefault(); - void check(); - }} - > -

        - Generate an API access token that expires in 1 day, and paste it here.{" "} - - Open Keys in Tailscale - -

        - {outcome ? : null} -
        - setToken(e.target.value)} - placeholder="tskey-api-…" - aria-label="API access token" - autoComplete="off" - className="h-8" - /> - -
        - {error ?

        {error}

        : null} - - ); -} - -/** Setting up: with a token, or with an OAuth client made by hand. */ -function Setup({ saved, onDone }: { saved?: string; onDone: (outcome?: TailscaleSetupOutcome) => void }) { - const [byClient, setByClient] = useState(false); - return ( -
        - {byClient ? ( - <> -

        - An OAuth client with Devices › Core and Auth Keys (both with tag:pyo) and Services.{" "} - - How to make one - -

        - onDone()} /> - - ) : ( - - )} -
        - - {saved ? ( - - ) : null} -
        -
        - ); -} - function NameRow({ kind, label }: { kind: "dashboard" | "registry" | "sandboxes"; label: string }) { const ts = usePyo().tailscale; const [editing, setEditing] = useState(false); @@ -335,30 +153,44 @@ function NameRow({ kind, label }: { kind: "dashboard" | "registry" | "sandboxes" const ready = { dashboard: ts.dashboard, registry: ts.registry, sandboxes: ts.sandboxes }[kind]; if (!current) return null; return ( -
      • -
        -

        {label}

        -

        - {current}.{ts.suffix} -

        - {error ?

        {error}

        : null} +
      • +
        +
        +

        {label}

        +

        + {current}.{ts.suffix} +

        +
        + {problem ? ( + {problem} + ) : ready ? ( + Ready + ) : ( + + {ts.hostMove?.state === "moving" + ? "Moving server" + : ts.onTailnet + ? "Getting certificate" + : "Joining tailnet"} + + )} + {editing ? null : ( + + )}
        - {problem ? ( - {problem} - ) : ready ? ( - Ready - ) : ( - - {ts.hostMove?.state === "moving" - ? "Moving server" - : ts.onTailnet - ? "Getting certificate" - : "Joining tailnet"} - - )} {editing ? (
        { e.preventDefault(); const r = await api.renameTailscaleName(kind, name); @@ -367,40 +199,31 @@ function NameRow({ kind, label }: { kind: "dashboard" | "registry" | "sandboxes" setEditing(false); }} > - setName(e.target.value)} - aria-label={`${label} name`} - className="h-8 w-40" - /> - + + {(p) => setName(e.target.value)} className="h-8" />} + +
        + + +
        - ) : ( - - )} + ) : null}
      • ); } -function PublicDashboardRow() { +function PublicDashboard() { const s = usePyo(); const pd = s.publicDashboard; if (!pd) return null; const onTailnet = !!s.tailscale?.dashboard; const locked = pd.possible && pd.open && !onTailnet; return ( -
      • +
        -
      • +
    ); } @@ -426,109 +249,359 @@ function PublicDashboardRow() { function HostMove() { const move = usePyo().tailscale?.hostMove; if (!move) return null; - return ( -
  • - {move.state === "moving" ? ( - Moving this server to your tailnet… - ) : ( - - This server couldn't move to your tailnet. {move.error ?? ""} Pyo tries again tomorrow. - - )} -
  • + return move.state === "moving" ? ( + Moving this server to your tailnet… + ) : ( + + This server couldn't move to your tailnet. {move.error ?? ""} Pyo tries again tomorrow. + ); } -/** Integrations › Tailscale: the OAuth client for the whole Pyo (admins). */ -export function TailscaleSettings() { +const ICON = ; +const ABOUT = "For the whole Pyo. Servers join your tailnet with it."; +const STEPS = ["Token", "Review", "Done"]; + +/** + * Integrations › Tailscale (admins set it up, everyone sees it). Set up with + * one short-lived API access token: paste, check, review what Pyo will + * change, set up. Or with an OAuth client made by hand. Once set up: what's + * connected, the names on the tailnet, Test and Disconnect. + */ +export function TailscaleDialog({ onClose }: { onClose: () => void }) { const s = usePyo(); const ts = s.tailscale; - const [replacing, setReplacing] = useState(false); + const navigate = useNavigate(); + const [view, setView] = useState<"manage" | "token" | "client">(ts ? "manage" : "token"); + + // With a token. + const [token, setToken] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [plan, setPlan] = useState(null); + const [stopped, setStopped] = useState(null); + const [done, setDone] = useState(null); + + // With an OAuth client. + const [clientId, setClientId] = useState(ts?.clientId ?? ""); + const [secret, setSecret] = useState(""); + const [clientChecks, setClientChecks] = useState([]); + + // Set up. const [checks, setChecks] = useState([]); - const [outcome, setOutcome] = useState(null); const [testing, setTesting] = useState(false); - const [removing, setRemoving] = useState(false); + const [confirming, setConfirming] = useState(false); + + const setup = !ts || view !== "manage"; + const method = view === "client" ? "client" : "token"; + const toManage = () => { + setView("manage"); + setPlan(null); + setError(""); + setDone(null); + }; + const cancel = ts ? toManage : onClose; + + const check = async () => { + if (!token.trim() || busy) return; + setBusy(true); + setError(""); + setStopped(null); + const r = await api.planTailscaleSetup(token); + setBusy(false); + if ("error" in r) return setError(r.error); + setPlan(r.data.plan); + }; + const apply = async () => { + setBusy(true); + setError(""); + const r = await api.setUpTailscale(token); + setBusy(false); + if ("error" in r) return setError(r.error); + if (!r.data.ok) { + // Stopped partway: what changed stays listed, and the token stays for another try. + setPlan(null); + return setStopped(r.data); + } + setToken(""); + setPlan(null); + toast({ title: "Tailscale set up" }); + if (!goBack(navigate)) setDone(r.data); + }; + const saveClient = async () => { + if (busy || !clientId.trim() || (!ts?.clientId && !secret.trim())) return; + setBusy(true); + setError(""); + const r = await api.saveTailscale(clientId, secret); + setBusy(false); + if ("error" in r) return setError(r.error); + setClientChecks(r.data.checks); + if (!r.data.ok) return; + setSecret(""); + toast({ title: "Tailscale saved" }); + if (!goBack(navigate)) toManage(); + }; + const test = async () => { + setTesting(true); + const r = await api.testTailscale(); + setTesting(false); + if ("error" in r) toast({ tone: "error", title: r.error }); + else setChecks(r.data.checks); + }; + + const shell = (p: { + body: ReactNode; + footer?: ReactNode; + onSubmit?: () => void; + }) => ( + + {p.body} + + ); + if (!s.user.isAdmin) - return ( -
      -
    • - - {ts ? `On ${ts.suffix ?? "your tailnet"}` : "An installation admin can set it up."} - - {ts ? Set up : Not set up} -
    • - -
    - ); - return ( - <> -
      -
    • - {!ts || replacing ? ( - { - setReplacing(false); - setOutcome(o ?? null); - }} - /> + return shell({ + body: ( +
      + Set up], + ["Tailnet", {ts.suffix ?? "Not seen yet"}], + ] + : [["Status", Not set up]] + } + /> + {ts ? null :

      An installation admin can set it up.

      } + +
      + ), + footer: , + }); + + // Done: what setting up did. + if (done) + return shell({ + body: ( +
      + + } title="Tailscale is set up" /> + +
      + ), + footer: , + }); + + // Review: what Pyo will change. + if (setup && method === "token" && plan) + return shell({ + body: ( +
      + + {plan.blocked ? ( + {plan.blocked} + ) : plan.changes.length ? ( + + + ) : ( - <> -
      -
      -

      {ts.clientId}

      -

      - Secret {ts.hint} - {ts.suffix ? ` · ${ts.suffix}` : ""} -

      -
      - -
      + ), + footer: ( + <> + + {plan.blocked ? ( + + ) : ( + + )} + + ), + }); + + // Token: paste and check. + if (setup && method === "token") + return shell({ + onSubmit: () => void check(), + body: ( +
      + + {stopped ? ( + } title="Setup stopped partway"> + + + ) : null} +
      + + {(p) => ( + setToken(e.target.value)} + onPasteText={setToken} + placeholder="tskey-api-…" + autoComplete="off" + /> + )} + +
      + Open Keys in Tailscale + { setView("client"); setError(""); }}> + Set up with an OAuth client instead + +
      +
      + {ts ? null : } +
      + ), + footer: ( + <> + + + + ), + }); + + // OAuth client, made by hand. + if (setup) + return shell({ + onSubmit: () => void saveClient(), + body: ( +
      +

      + An OAuth client with Devices › Core and Auth Keys (both with tag:pyo) and Services. +

      +
      + + {(p) => ( + setClientId(e.target.value)} autoComplete="off" /> + )} + + + {(p) => ( + setSecret(e.target.value)} + onPasteText={setSecret} + placeholder={ts?.clientId ? "Unchanged" : "tskey-client-…"} + autoComplete="off" + /> + )} + +
      + {error ?

      {error}

      : null} + {clientChecks.length ? : null} +
      + How to make one + { setView("token"); setError(""); }}> + Set up with an access token instead + +
      + {ts ? null : } +
      + ), + footer: ( + <> + + + + ), + }); + + // Set up: what's connected. + return shell({ + body: ( +
      + + {ts.suffix ?? "Not seen yet"}], + ["OAuth client", {ts.clientId}], + [ + "Secret", + <> + {ts.hint} + - -
      - {outcome ? : null} - {checks.length ? : null} - - )} -
    • - {ts && !replacing ? ( - <> - - - - + , + ], + ]} + /> + {checks.length ? : null} + {ts.suffix && (ts.dashboardName || ts.registryName || ts.sandboxesName) ? ( + +
        + + + +
      +
      ) : null} - - -
    - setRemoving(false)} - onConfirm={() => { - setRemoving(false); - void api.removeTailscale(); - }} - title="Remove Tailscale?" - description="Pyo's names on your tailnet are deleted. Servers stay on it. The public dashboard opens again." - confirmLabel="Remove" - /> - - ); + + {confirming ? ( + setConfirming(false)} + onConfirm={() => { + setConfirming(false); + void api.removeTailscale(); + }} + > + Pyo's names on your tailnet are deleted. Servers stay on it. The public dashboard opens again. + + ) : null} +
    + ), + footer: confirming ? null : ( + <> + + + + + ), + }); } diff --git a/dash/src/routes/_app/$team/integrations.tsx b/dash/src/routes/_app/$team/integrations.tsx index a442913..cd27866 100644 --- a/dash/src/routes/_app/$team/integrations.tsx +++ b/dash/src/routes/_app/$team/integrations.tsx @@ -1,33 +1,25 @@ -import { createFileRoute, Link } from "@tanstack/react-router"; +import { createFileRoute } from "@tanstack/react-router"; import { siGitlab, siHetzner, siTailscale, siVault } from "simple-icons"; import { useCallback, useEffect, useState, type ReactNode } from "react"; import { z } from "zod"; import { IntegrationCard, - docsUrl, type IntegrationCardProps, } from "~/components/pyo/IntegrationCard"; -import { - AddLoginDialog, - RegistryLoginsSettings, -} from "~/components/pyo/RegistryLogins"; -import { SecretStoresSettings, StoreDialog } from "~/components/pyo/SecretStores"; -import { CloudflareSettings } from "~/components/pyo/Cloudflare"; -import { TailscaleSettings } from "~/components/pyo/Tailscale"; -import { GitlabRows, TokenDialog } from "~/components/pyo/GitConnections"; -import { HetznerSettings, hetznerOf } from "~/components/pyo/Hetzner"; +import { RegistriesDialog } from "~/components/pyo/RegistryLogins"; +import { SecretStoresDialog } from "~/components/pyo/SecretStores"; +import { CloudflareDialog } from "~/components/pyo/Cloudflare"; +import { TailscaleDialog } from "~/components/pyo/Tailscale"; +import { GithubDialog, GitlabDialog } from "~/components/pyo/GitConnections"; +import { HetznerDialog, hetznerOf } from "~/components/pyo/Hetzner"; import { useTeamAdmin } from "~/components/pyo/database/NewDatabase"; -import { Badge, type Tone } from "~/components/ui/Badge"; -import { Button, buttonClass } from "~/components/ui/Button"; -import { ConfirmDialog, Dialog } from "~/components/ui/Dialog"; -import type { MenuItem } from "~/components/ui/Menu"; +import type { Tone } from "~/components/ui/Badge"; +import { Button } from "~/components/ui/Button"; import { Page, PageHeader, NoMatches } from "~/components/ui/Panel"; import { SearchInput } from "~/components/ui/Table"; import { Tabs } from "~/components/ui/Tabs"; -import { timeAgo } from "~/lib/pyo/format"; import { seo } from "~/lib/seo"; import { - api, cloudflareIn, roleIn, usePyo, @@ -37,8 +29,8 @@ import { toast } from "~/lib/pyo/toast"; import { BrandMark, CLOUDFLARE_LOGO, DOCKER_LOGO, GITHUB_LOGO } from "~/components/pyo/common"; // Everything Pyo connects to, as cards: a filter by category, a search, and -// each card's settings in a dialog. "/integrations#" scrolls to a card -// and opens its settings. Notification channels live in Settings. +// each card's dialog to set it up or manage it. "/integrations#" scrolls +// to a card and opens its dialog. Notification channels live in Settings. export const Route = createFileRoute("/_app/$team/integrations")({ // ?github=: back from GitHub (see useGithubReturn). validateSearch: z.object({ github: z.string().optional().catch(undefined) }), @@ -56,20 +48,22 @@ const CATEGORIES = [ ] as const; type Category = (typeof CATEGORIES)[number]; -type Integration = Omit & { +type Id = "tailscale" | "hetzner" | "github" | "gitlab" | "cloudflare" | "registries" | "secrets"; + +type Integration = Omit & { + id: Id; category: Category; - /** Its settings, in a dialog from the menu or a link to the card. */ - settings?: { title: string; description?: string; body: ReactNode }; + connected: boolean; + /** Set up: what needs a look, or a step under way. */ + problem?: { tone: Tone; label: string; detail?: string } | null; + /** Not set up: whether this user can set it up. */ + canSetUp: boolean; + dialog: (onClose: () => void) => ReactNode; }; -type Removing = "tailscale" | "hetzner" | "cloudflare" | null; - const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; -const oldest = (xs: { createdAt: number }[]) => - Math.min(...xs.map((x) => x.createdAt)); - /** Repositories the team's services deploy from, through a connection. */ function reposLinked(s: PyoState, linked: (src: { installationId?: number; gitConnectionId?: string }) => boolean) { const repos = new Set(); @@ -80,6 +74,8 @@ function reposLinked(s: PyoState, linked: (src: { installationId?: number; gitCo return repos.size; } +const ATTENTION = "Needs attention"; + function Integrations() { const s = usePyo(); const teamAdmin = useTeamAdmin(); @@ -87,8 +83,6 @@ function Integrations() { const [filter, setFilter] = useState("all"); const [q, setQ] = useState(""); const [open, setOpen] = useState(null); - const [adding, setAdding] = useState<"gitlab" | "registries" | "secrets" | null>(null); - const [removing, setRemoving] = useState(null); const [highlight, setHighlight] = useState(null); useGithubReturn(() => setOpen("github")); @@ -103,53 +97,13 @@ function Integrations() { const logins = s.registryLogins.filter((l) => l.teamId === team); const stores = s.secretStores.filter((x) => x.teamId === team); - const connect = (label = "Connect", onClick?: () => void, disabled = false) => ( - - ); - const askAdmin = Ask an admin; - const settingsItem = (id: string, label = "Settings"): MenuItem => ({ - label, - onSelect: () => setOpen(id), - }); - const guideItem = (page: string): MenuItem => ({ - label: "Setup guide", - href: docsUrl(page), - }); - - const test = { - tailscale: async () => { - const r = await api.testTailscale(); - if ("error" in r) return toast({ tone: "error", title: r.error }); - const bad = r.data.checks.filter((c) => !c.ok); - toast( - bad.length - ? { tone: "error", title: "Tailscale has problems", description: bad.map((c) => c.message).join(" ") } - : { title: "Tailscale works" }, - ); - }, - hetzner: async () => { - const r = await api.testHetzner(); - if ("error" in r) return toast({ tone: "error", title: r.error }); - toast({ title: "Hetzner works", description: r.data.locations.map((l) => l.city).join(", ") }); - }, - cloudflare: async () => { - const r = await api.testCloudflare(); - if (!r) return; - toast( - r.problems?.length - ? { tone: "error", title: "Cloudflare has problems", description: r.problems.join(" ") } - : { title: "Cloudflare token works" }, - ); - }, - }; - - const tsStatus = (): { tone: Tone; label: string } | null => { + const tsProblem = (): Integration["problem"] => { if (!ts) return null; - if (ts.hostMove?.state === "failed") return { tone: "danger", label: "This server couldn't move" }; + if (ts.hostMove?.state === "failed") + return { tone: "danger", label: ATTENTION, detail: "This server couldn't move" }; if (ts.hostMove?.state === "moving") return { tone: "progress", label: "Moving this server" }; - if (ts.dashboardError || ts.registryError) return { tone: "warning", label: "Needs attention" }; + if (ts.dashboardError || ts.registryError) + return { tone: "warning", label: ATTENTION, detail: ts.dashboardError ?? ts.registryError ?? undefined }; if (!ts.onTailnet) return { tone: "progress", label: "Joining tailnet" }; if (ts.dashboardName && !ts.dashboard) return { tone: "progress", label: "Getting certificate" }; return null; @@ -159,10 +113,11 @@ function Integrations() { const gitlabProjects = gitlab.reduce((n, c) => n + (c.info.projects ?? 0), 0); const gitlabProblems = gitlab.some((c) => c.info.problems?.length); const cfLacking = cf?.zones.filter((z) => !z.canEdit).length ?? 0; - const lastUsed = Math.max(0, ...logins.map((l) => l.lastUsedAt ?? 0)); const storeUses = s.services.filter( (a) => a.teamId === team && a.secretImports?.some((i) => stores.some((x) => x.id === i.storeId)), ).length; + const githubRepos = reposLinked(s, (src) => installs.some((g) => g.id === src.installationId)); + const gitlabRepos = reposLinked(s, (src) => gitlab.some((c) => c.id === src.gitConnectionId)); const all: Integration[] = [ { @@ -172,164 +127,83 @@ function Integrations() { icon: , description: "Servers join your tailnet with it.", connected: !!ts, - stat: ts?.suffix ? { label: "Tailnet", value: {ts.suffix} } : null, - status: tsStatus(), - docs: "tailscale", - action: s.user.isAdmin ? connect("Connect", () => setOpen("tailscale")) : askAdmin, - menu: [ - settingsItem("tailscale"), - ...(s.user.isAdmin - ? [ - { label: "Test", onSelect: () => void test.tailscale() }, - guideItem("tailscale"), - { type: "separator" as const }, - { label: "Remove", danger: true, onSelect: () => setRemoving("tailscale") }, - ] - : [guideItem("tailscale")]), - ], - settings: { title: "Tailscale", description: "For the whole Pyo. Servers join your tailnet with it.", body: }, + detail: ts?.suffix ? {ts.suffix} : null, + problem: tsProblem(), + canSetUp: !!s.user.isAdmin, + dialog: (onClose) => , }, { id: "hetzner", name: "Hetzner", category: "Servers", icon: , - description: "Pyo makes servers in your Hetzner project.", + description: "Pyo makes servers at Hetzner.", connected: !!hetzner, - stat: hetzner ? { label: "Servers made", value: cloudServers.length } : null, - status: hetzner - ? failedServers - ? { tone: "danger", label: `${plural(failedServers, "server")} failed` } - : { tone: "success", label: `Added ${timeAgo(hetzner.createdAt)}` } + detail: `${plural(cloudServers.length, "server")} made`, + problem: failedServers + ? { tone: "danger", label: ATTENTION, detail: `${plural(failedServers, "server")} failed` } : null, - docs: "hetzner", - action: teamAdmin ? connect("Connect", () => setOpen("hetzner")) : askAdmin, - menu: [ - settingsItem("hetzner"), - ...(teamAdmin - ? [ - { label: "Test", onSelect: () => void test.hetzner() }, - guideItem("hetzner"), - { type: "separator" as const }, - { label: "Remove", danger: true, onSelect: () => setRemoving("hetzner") }, - ] - : [guideItem("hetzner")]), - ], - settings: { title: "Hetzner", description: "For this team. Pyo makes servers in your Hetzner project.", body: }, + canSetUp: teamAdmin, + dialog: (onClose) => , }, { id: "github", name: "GitHub", category: "Git", icon: , - description: "Private repos, and a deploy on every push.", + description: "Private repos. Deploys on every push.", connected: !!s.github && installs.length > 0, - stat: { label: "Repos linked", value: reposLinked(s, (src) => installs.some((g) => g.id === src.installationId)) }, - status: installs.length - ? { tone: "success", label: `Added ${timeAgo(oldest(installs))}` } - : null, - docs: "github", - action: s.github - ? connect("Connect", () => setOpen("github")) - : s.user.isAdmin - ? connect("Set up", () => setOpen("github")) - : askAdmin, - menu: [settingsItem("github", "Accounts"), guideItem("github")], - settings: { title: "GitHub", body:
    }, + detail: `${plural(githubRepos, "repo")} linked`, + canSetUp: !!s.github || !!s.user.isAdmin, + dialog: (onClose) => , }, { id: "gitlab", name: "GitLab", category: "Git", icon: , - description: "gitlab.com or your own GitLab, with an access token.", + description: "gitlab.com or your own GitLab.", connected: gitlab.length > 0, - stat: gitlabProjects - ? { label: "Projects", value: gitlabProjects } - : { label: "Repos linked", value: reposLinked(s, (src) => gitlab.some((c) => c.id === src.gitConnectionId)) }, - status: gitlab.length - ? gitlabProblems - ? { tone: "warning", label: "Needs attention" } - : { tone: "success", label: `Added ${timeAgo(oldest(gitlab))}` } - : null, - docs: "gitlab", - action: connect("Connect", () => setAdding("gitlab")), - menu: [ - settingsItem("gitlab", "Connections"), - { label: "Connect another GitLab", onSelect: () => setAdding("gitlab") }, - guideItem("gitlab"), - ], - settings: { title: "GitLab", body:
    }, + detail: gitlabProjects ? plural(gitlabProjects, "project") : `${plural(gitlabRepos, "repo")} linked`, + problem: gitlabProblems ? { tone: "warning", label: ATTENTION } : null, + canSetUp: true, + dialog: (onClose) => , }, { id: "cloudflare", name: "Cloudflare", category: "DNS", icon: , - description: "Creates DNS records for domains in your zones.", + description: "Creates DNS records in your zones.", connected: !!cf, - stat: cf ? { label: "Zones", value: cf.zones.length - cfLacking } : null, - status: cf - ? cfLacking - ? { tone: "warning", label: `${plural(cfLacking, "zone")} lack access` } - : { tone: "success", label: `Tested ${timeAgo(cf.testedAt)}` } + detail: cf ? plural(cf.zones.length - cfLacking, "zone") : null, + problem: cfLacking + ? { tone: "warning", label: ATTENTION, detail: `${plural(cfLacking, "zone")} ${cfLacking === 1 ? "lacks" : "lack"} access` } : null, - docs: "cloudflare", - action: cfAdmin ? connect("Connect", () => setOpen("cloudflare")) : askAdmin, - menu: [ - settingsItem("cloudflare"), - ...(cfAdmin - ? [ - { label: "Test", onSelect: () => void test.cloudflare() }, - guideItem("cloudflare"), - { type: "separator" as const }, - { label: "Remove", danger: true, onSelect: () => setRemoving("cloudflare") }, - ] - : [guideItem("cloudflare")]), - ], - settings: { title: "Cloudflare", description: "Creates DNS records for domains in your zones.", body: }, + canSetUp: cfAdmin, + dialog: (onClose) => , }, { id: "registries", name: "Container registries", category: "Registries", icon: , - description: "Logins for private images. Services pull with them.", + description: "Logins for private images.", connected: logins.length > 0, - stat: { label: "Logins", value: logins.length }, - status: logins.length - ? lastUsed - ? { tone: "success", label: `Used ${timeAgo(lastUsed)}` } - : { tone: "neutral", label: "Not used yet" } - : null, - docs: "registries", - action: connect("Add login", () => setAdding("registries")), - menu: [ - settingsItem("registries", "Logins"), - { label: "Add login", onSelect: () => setAdding("registries") }, - guideItem("registries"), - ], - settings: { title: "Container registries", body: }, + detail: plural(logins.length, "login"), + canSetUp: true, + dialog: (onClose) => , }, { id: "secrets", name: "Secret stores", category: "Secrets", icon: , - description: "Services import secrets from your store on each deploy.", + description: "Services import secrets on deploy.", connected: stores.length > 0, - stat: { label: "Services importing", value: storeUses }, - status: stores.length - ? { tone: "success", label: `Added ${timeAgo(oldest(stores))}` } - : null, - docs: "external-secrets", - action: connect("Connect", () => setAdding("secrets")), - menu: [ - settingsItem("secrets", "Stores"), - { label: "Connect another store", onSelect: () => setAdding("secrets") }, - guideItem("external-secrets"), - ], - settings: { title: "Secret stores", body: }, + detail: storeUses ? `${plural(storeUses, "service")} importing` : "Not used yet", + canSetUp: true, + dialog: (onClose) => , }, ]; @@ -345,7 +219,7 @@ function Integrations() { [x.name, x.category, x.description].some((t) => t.toLowerCase().includes(needle))), ); - // "/integrations#tailscale": show the card, ring it, open its settings. + // "/integrations#tailscale": show the card, ring it, open its dialog. const ids = all.map((x) => x.id).join(","); const reveal = useCallback(() => { const id = window.location.hash.slice(1); @@ -362,14 +236,44 @@ function Integrations() { window.addEventListener("hashchange", reveal); return () => window.removeEventListener("hashchange", reveal); }, [reveal]); - const close = () => { + const close = useCallback(() => { setOpen(null); if (window.location.hash) window.history.replaceState(window.history.state, "", window.location.pathname + window.location.search); - }; + }, []); const current = all.find((x) => x.id === open); + const card = (x: Integration): IntegrationCardProps => { + const status: IntegrationCardProps["status"] = !x.connected + ? { tone: "neutral", label: "Not set up" } + : x.problem + ? { tone: x.problem.tone, label: x.problem.label } + : { tone: "success", label: "Connected" }; + return { + id: x.id, + name: x.name, + icon: x.icon, + description: x.description, + status, + detail: x.connected ? (x.problem?.detail ?? x.detail) : null, + action: + x.connected || x.canSetUp ? ( + + ) : ( + Ask an admin + ), + highlight: highlight === x.id, + }; + }; + return ( @@ -401,9 +305,9 @@ function Integrations() {
    {shown.length ? ( -
    - {shown.map(({ settings: _settings, ...x }) => ( - +
    + {shown.map((x) => ( + ))}
    ) : ( @@ -417,52 +321,7 @@ function Integrations() { /> )}
    - -
    {current?.settings?.body}
    -
    - {adding === "gitlab" ? setAdding(null)} /> : null} - setAdding(null)} /> - {adding === "secrets" ? setAdding(null)} /> : null} - setRemoving(null)} - onConfirm={() => { - setRemoving(null); - void api.removeTailscale(); - }} - title="Remove Tailscale?" - description="Pyo's names on your tailnet are deleted. Servers stay on it. The public dashboard opens again." - confirmLabel="Remove" - /> - setRemoving(null)} - onConfirm={() => { - setRemoving(null); - void api.removeHetzner(); - }} - title="Remove Hetzner?" - description="Servers Pyo made there keep running." - confirmLabel="Remove" - /> - setRemoving(null)} - onConfirm={() => { - setRemoving(null); - void api.removeCloudflare(); - toast({ title: "Cloudflare token removed" }); - }} - title="Remove the Cloudflare token?" - description="Records Pyo made stay in Cloudflare." - confirmLabel="Remove" - /> + {current ? current.dialog(close) : null} ); } @@ -498,113 +357,3 @@ function useGithubReturn(open: () => void) { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); } - -function Row({ - icon, - title, - body, - right, -}: { - icon: ReactNode; - title: ReactNode; - body: ReactNode; - right: ReactNode; -}) { - return ( -
  • - - {icon} - -
    -

    {title}

    -

    {body}

    -
    - {right} -
  • - ); -} - -/** The team's GitHub accounts, through this installation's GitHub App. */ -function GithubRows() { - const s = usePyo(); - const [busy, setBusy] = useState(false); - const installs = s.githubInstallations.filter( - (g) => g.teamId === s.currentTeamId, - ); - const connect = async () => { - setBusy(true); - const r = await api.githubInstallUrl(); - if (r) window.location.assign(r.url); - else setBusy(false); - }; - // No GitHub App yet: the installation admin creates it in Settings. - if (!s.github) - return ( - } - title="GitHub" - body={ - s.user.isAdmin - ? "Set up the GitHub App first." - : "Ask an installation admin to set up GitHub." - } - right={ - s.user.isAdmin ? ( - - Set up - - ) : ( - Not set up - ) - } - /> - ); - return ( - <> - {installs.map((g) => ( - } - title={`GitHub · ${g.account}`} - body={`${g.accountType === "Organization" ? "Organization" : "Account"} · ${g.repositorySelection === "all" ? "all repositories" : "selected repositories"}`} - right={ - - - Repositories - - - - } - /> - ))} - } - title={installs.length ? "Another GitHub account" : "GitHub"} - body={`Install ${s.github.name} and pick the repositories Pyo can see.`} - right={ - - } - /> - - ); -} From 9cfb8ddb7422016aa567ee76e1d678447804f794 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Thu, 19 Nov 2026 21:49:07 +0700 Subject: [PATCH 06/32] style(dash): drop the paste button from secret fields --- dash/src/components/pyo/Cloudflare.tsx | 1 - dash/src/components/pyo/GitConnections.tsx | 1 - dash/src/components/pyo/Hetzner.tsx | 1 - dash/src/components/pyo/RegistryLogins.tsx | 1 - dash/src/components/pyo/SecretStores.tsx | 1 - dash/src/components/pyo/Tailscale.tsx | 2 -- dash/src/components/ui/Field.tsx | 28 ++-------------------- 7 files changed, 2 insertions(+), 33 deletions(-) diff --git a/dash/src/components/pyo/Cloudflare.tsx b/dash/src/components/pyo/Cloudflare.tsx index d14981e..3e7ce01 100644 --- a/dash/src/components/pyo/Cloudflare.tsx +++ b/dash/src/components/pyo/Cloudflare.tsx @@ -149,7 +149,6 @@ export function CloudflareDialog({ onClose }: { onClose: () => void }) { {...p} value={token} onChange={(e) => setToken(e.target.value)} - onPasteText={setToken} autoComplete="off" /> )} diff --git a/dash/src/components/pyo/GitConnections.tsx b/dash/src/components/pyo/GitConnections.tsx index 2265525..1a52821 100644 --- a/dash/src/components/pyo/GitConnections.tsx +++ b/dash/src/components/pyo/GitConnections.tsx @@ -162,7 +162,6 @@ function TokenForm({ autoComplete="off" value={token} onChange={(e) => setToken(e.target.value)} - onPasteText={setToken} placeholder="glpat-…" /> )} diff --git a/dash/src/components/pyo/Hetzner.tsx b/dash/src/components/pyo/Hetzner.tsx index b0735e3..d84b63d 100644 --- a/dash/src/components/pyo/Hetzner.tsx +++ b/dash/src/components/pyo/Hetzner.tsx @@ -190,7 +190,6 @@ function TokenField({ {...p} value={token} onChange={(e) => setToken(e.target.value)} - onPasteText={setToken} autoComplete="off" disabled={disabled} /> diff --git a/dash/src/components/pyo/RegistryLogins.tsx b/dash/src/components/pyo/RegistryLogins.tsx index fbff12e..e60f44a 100644 --- a/dash/src/components/pyo/RegistryLogins.tsx +++ b/dash/src/components/pyo/RegistryLogins.tsx @@ -193,7 +193,6 @@ export function RegistriesDialog({ onClose }: { onClose: () => void }) { {...f} value={password} onChange={(e) => setPassword(e.target.value)} - onPasteText={setPassword} /> )} diff --git a/dash/src/components/pyo/SecretStores.tsx b/dash/src/components/pyo/SecretStores.tsx index 954a349..9a1baea 100644 --- a/dash/src/components/pyo/SecretStores.tsx +++ b/dash/src/components/pyo/SecretStores.tsx @@ -187,7 +187,6 @@ function StoreForm({ autoComplete="off" value={form[key]} onChange={(e) => set({ [key]: e.target.value })} - onPasteText={(t) => set({ [key]: t })} placeholder={placeholder} /> ) : ( diff --git a/dash/src/components/pyo/Tailscale.tsx b/dash/src/components/pyo/Tailscale.tsx index 8688a7c..cb31d1c 100644 --- a/dash/src/components/pyo/Tailscale.tsx +++ b/dash/src/components/pyo/Tailscale.tsx @@ -465,7 +465,6 @@ export function TailscaleDialog({ onClose }: { onClose: () => void }) { {...p} value={token} onChange={(e) => setToken(e.target.value)} - onPasteText={setToken} placeholder="tskey-api-…" autoComplete="off" /> @@ -514,7 +513,6 @@ export function TailscaleDialog({ onClose }: { onClose: () => void }) { {...p} value={secret} onChange={(e) => setSecret(e.target.value)} - onPasteText={setSecret} placeholder={ts?.clientId ? "Unchanged" : "tskey-client-…"} autoComplete="off" /> diff --git a/dash/src/components/ui/Field.tsx b/dash/src/components/ui/Field.tsx index cc1a162..d0f2f85 100644 --- a/dash/src/components/ui/Field.tsx +++ b/dash/src/components/ui/Field.tsx @@ -1,7 +1,6 @@ import { Tabs } from "./Tabs"; import { CircleNotchIcon, - ClipboardTextIcon, EyeIcon, EyeSlashIcon, MinusIcon, @@ -129,7 +128,6 @@ export { Select } from "./Select"; * Masked value with an eye toggle inside. Pass `shown` and `onToggle` to * control it (e.g. fetch a stored value first); `busy` spins the eye, * `toggleDisabled` disables it with that reason as its title. - * `onPasteText` adds a paste button, where the browser can read the clipboard. */ export const SecretInput = forwardRef< HTMLInputElement, @@ -138,17 +136,12 @@ export const SecretInput = forwardRef< onToggle?: () => void; busy?: boolean; toggleDisabled?: string; - onPasteText?: (text: string) => void; } >(function SecretInput( - { className = "", shown: shownProp, onToggle, busy, toggleDisabled, onPasteText, ...props }, + { className = "", shown: shownProp, onToggle, busy, toggleDisabled, ...props }, ref, ) { const [own, setOwn] = useState(false); - const [canPaste, setCanPaste] = useState(false); - useEffect(() => { - setCanPaste(!!onPasteText && typeof navigator !== "undefined" && !!navigator.clipboard?.readText); - }, [onPasteText]); const shown = shownProp ?? own; return (
    @@ -156,26 +149,9 @@ export const SecretInput = forwardRef< ref={ref} type={shown ? "text" : "password"} autoComplete="new-password" - className={`${inputClass} ${canPaste ? "pr-16" : "pr-9"} font-mono text-[12px] ${className}`} + className={`${inputClass} pr-9 font-mono text-[12px] ${className}`} {...props} /> - {canPaste ? ( - - ) : null} , From 5916d401c5791c12089fabd4f25fb773e625352b Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Fri, 20 Nov 2026 04:45:36 +0700 Subject: [PATCH 11/32] refactor(api): send tailscale setup requests through the shared client path The setup's Api::send repeated Client::call's request and error handling. Both now go through tailscale::send, and the setup keeps only its own token, headers and scrubbing. --- crates/pyo-api/src/tailscale.rs | 41 ++++++++++++++----- crates/pyo-api/src/tailscale_setup.rs | 57 +++++++++------------------ 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/crates/pyo-api/src/tailscale.rs b/crates/pyo-api/src/tailscale.rs index 87735f3..d3b64c1 100644 --- a/crates/pyo-api/src/tailscale.rs +++ b/crates/pyo-api/src/tailscale.rs @@ -201,6 +201,36 @@ impl std::fmt::Display for TsError { impl std::error::Error for TsError {} +/// What Tailscale answered: its body, and the ETag when there's one. +pub(crate) struct Reply { + pub text: String, + pub etag: Option, +} + +/// Sends a request to Tailscale's API. Anything but a 2xx is a [`TsError`] +/// with Tailscale's own message, and status 0 when it couldn't be reached. +pub(crate) async fn send(req: reqwest::RequestBuilder) -> Result { + let r = req.send().await.map_err(|e| TsError { + status: 0, + message: format!("Couldn't reach Tailscale: {}", e.without_url()), + })?; + let status = r.status().as_u16(); + let etag = r + .headers() + .get(reqwest::header::ETAG) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + let text = r.text().await.unwrap_or_default(); + if !(200..300).contains(&status) { + let message = serde_json::from_str::(&text) + .ok() + .and_then(|v| v["message"].as_str().map(str::to_owned)) + .unwrap_or_else(|| text.trim().chars().take(300).collect()); + return Err(TsError { status, message }); + } + Ok(Reply { text, etag }) +} + impl Client { pub(crate) async fn access_token(&self) -> anyhow::Result { if let Some((t, at)) = self.token.lock().unwrap_or_else(|e| e.into_inner()).clone() @@ -260,16 +290,7 @@ impl Client { if let Some(b) = body { req = req.json(b); } - let r = req.send().await?; - let status = r.status().as_u16(); - let text = r.text().await.unwrap_or_default(); - if !(200..300).contains(&status) { - let message = serde_json::from_str::(&text) - .ok() - .and_then(|v| v["message"].as_str().map(str::to_owned)) - .unwrap_or_else(|| text.trim().chars().take(300).collect()); - return Err(TsError { status, message }.into()); - } + let text = send(req).await?.text; Ok(if text.trim().is_empty() { Value::Null } else { diff --git a/crates/pyo-api/src/tailscale_setup.rs b/crates/pyo-api/src/tailscale_setup.rs index b227f08..c5a6f89 100644 --- a/crates/pyo-api/src/tailscale_setup.rs +++ b/crates/pyo-api/src/tailscale_setup.rs @@ -25,7 +25,7 @@ use zeroize::Zeroize; use crate::AppState; use crate::error::{ApiError, ApiResult}; -use crate::tailscale::{TAG, TsError}; +use crate::tailscale::{Reply, TAG, TsError}; /// The scopes Pyo's own client gets: what the manual path asks for. const SCOPES: [&str; 3] = ["devices:core", "auth_keys", "services"]; @@ -96,15 +96,9 @@ enum Body { HuJson(String), } -struct Reply { - text: String, - etag: Option, -} - -impl Reply { - fn json(&self) -> Value { - serde_json::from_str(&self.text).unwrap_or(Value::Null) - } +/// The answer's body as JSON (Null when it isn't). +fn json_of(r: &Reply) -> Value { + serde_json::from_str(&r.text).unwrap_or(Value::Null) } /// Tailscale's API with the pasted token. @@ -138,6 +132,8 @@ impl Api { out } + /// A request with the token, through the same path as Pyo's own client + /// ([`crate::tailscale::send`]), with the token scrubbed from any error. async fn send( &self, method: reqwest::Method, @@ -158,35 +154,18 @@ impl Api { .header(reqwest::header::CONTENT_TYPE, "application/hujson") .body(t), }; - let r = req.send().await.map_err(|e| TsError { - status: 0, - message: self.scrub(&format!("Couldn't reach Tailscale: {}", e.without_url())), - })?; - let status = r.status().as_u16(); - let etag = r - .headers() - .get(reqwest::header::ETAG) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let text = r.text().await.unwrap_or_default(); - if !(200..300).contains(&status) { - let message = serde_json::from_str::(&text) - .ok() - .and_then(|v| v["message"].as_str().map(str::to_owned)) - .unwrap_or_else(|| text.trim().chars().take(300).collect()); - return Err(TsError { - status, - message: self.scrub(&message), - }); - } - Ok(Reply { text, etag }) + crate::tailscale::send(req).await.map_err(|e| TsError { + status: e.status, + message: self.scrub(&e.message), + }) } async fn get(&self, path: &str) -> Result { - Ok(self - .send(reqwest::Method::GET, path, Body::None, &[]) - .await? - .json()) + Ok(json_of( + &self + .send(reqwest::Method::GET, path, Body::None, &[]) + .await?, + )) } /// The policy file as written, and its ETag. @@ -688,7 +667,7 @@ async fn turn_on_https(api: &Api) -> Result { ) .await { - Ok(r) if https_on(&r.json()) == Some(true) => return Ok(Https::On), + Ok(r) if https_on(&json_of(&r)) == Some(true) => return Ok(Https::On), Ok(_) => { if read().await? == Some(true) { return Ok(Https::On); @@ -717,7 +696,7 @@ async fn validate(api: &Api, text: &str) -> Result<(), String> { ) .await .map_err(|e| say(&e, "check the new tailnet policy"))?; - let v = r.json(); + let v = json_of(&r); let errors = v["data"] .as_array() .into_iter() @@ -810,7 +789,7 @@ async fn make_client(api: &Api, host: &impl Host) -> Result, String> format!("Tailscale didn't let Pyo create its OAuth client.{why} Set up with an OAuth client instead.") } })?; - let v = r.json(); + let v = json_of(&r); let secret = v["key"].as_str().unwrap_or(""); // The client ID is the key's ID, which its secret carries too. let id = v["id"].as_str().map(str::to_owned).or_else(|| { From e47d938ba3a6fcb9a78b499e3ff6ecc0ef0b0817 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Fri, 20 Nov 2026 04:45:46 +0700 Subject: [PATCH 12/32] perf(api): read the tailnet's settings, policy, dns and client at once survey() read them one after another. They don't depend on each other, so they now run together with try_join. --- crates/pyo-api/src/tailscale_setup.rs | 40 +++++++++++++++------------ 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/crates/pyo-api/src/tailscale_setup.rs b/crates/pyo-api/src/tailscale_setup.rs index c5a6f89..67f7e4a 100644 --- a/crates/pyo-api/src/tailscale_setup.rs +++ b/crates/pyo-api/src/tailscale_setup.rs @@ -500,24 +500,30 @@ async fn read_policy(api: &Api) -> Result<(String, Option, Needs, Option } async fn survey(api: &Api, host: &impl Host) -> Result { - let settings = api - .get("/tailnet/-/settings") - .await - .map_err(|e| say(&e, "read your tailnet's settings"))?; - let (policy, etag, needs, patched) = read_policy(api).await?; - let dns = api - .get("/tailnet/-/dns/preferences") - .await - .map_err(|e| say(&e, "read your tailnet's DNS settings"))?; - let client = match host.working_client().await { - None => false, - // On this tailnet: Tailscale knows it by its ID. A client it can't - // show this token still counts, since it signs in. - Some(id) => match api.get(&format!("/tailnet/-/keys/{id}")).await { - Ok(k) => k["invalid"].as_bool() != Some(true), - Err(e) => e.status != 404, - }, + // Nothing here depends on anything else, so it's all read at once. + let settings = async { + api.get("/tailnet/-/settings") + .await + .map_err(|e| say(&e, "read your tailnet's settings")) + }; + let dns = async { + api.get("/tailnet/-/dns/preferences") + .await + .map_err(|e| say(&e, "read your tailnet's DNS settings")) + }; + let client = async { + Ok::<_, String>(match host.working_client().await { + None => false, + // On this tailnet: Tailscale knows it by its ID. A client it can't + // show this token still counts, since it signs in. + Some(id) => match api.get(&format!("/tailnet/-/keys/{id}")).await { + Ok(k) => k["invalid"].as_bool() != Some(true), + Err(e) => e.status != 404, + }, + }) }; + let (settings, (policy, etag, needs, patched), dns, client) = + tokio::try_join!(settings, read_policy(api), dns, client)?; Ok(Survey { gitops: settings["aclsExternallyManagedOn"].as_bool() == Some(true), policy, From e8e9b9c19feb99ef639114ec3bbbc069870ce697 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Fri, 20 Nov 2026 04:46:20 +0700 Subject: [PATCH 13/32] refactor(api): parse the tailnet policy once for the setup plan plan_of parsed the policy text again to see whether the tailnet reaches tag:pyo, and turned a parse error into an empty policy. The policy is now parsed once when it's read, and what the plan needs comes with it. --- crates/pyo-api/src/tailscale_setup.rs | 70 +++++++++++++-------- crates/pyo-api/src/tailscale_setup/tests.rs | 37 +++++++++++ 2 files changed, 80 insertions(+), 27 deletions(-) diff --git a/crates/pyo-api/src/tailscale_setup.rs b/crates/pyo-api/src/tailscale_setup.rs index 67f7e4a..52b705d 100644 --- a/crates/pyo-api/src/tailscale_setup.rs +++ b/crates/pyo-api/src/tailscale_setup.rs @@ -469,15 +469,22 @@ fn https_on(settings: &Value) -> Option { }) } -/// The tailnet as Pyo found it. -struct Survey { - /// The policy is managed outside the console (GitOps, Terraform). - gitops: bool, - policy: String, +/// The tailnet policy as Pyo read it, parsed once. +struct Policy { + text: String, etag: Option, needs: Needs, + /// What [`reaches_pyo`] says of it. + reaches: Option, /// The policy with what it needs, when it needs something. patched: Option, +} + +/// The tailnet as Pyo found it. +struct Survey { + /// The policy is managed outside the console (GitOps, Terraform). + gitops: bool, + policy: Policy, magic_dns: bool, /// None when Tailscale doesn't say. https: Option, @@ -485,18 +492,25 @@ struct Survey { client: bool, } -async fn read_policy(api: &Api) -> Result<(String, Option, Needs, Option), String> { +async fn read_policy(api: &Api) -> Result { let (text, etag) = api .policy() .await .map_err(|e| say(&e, "read your tailnet policy"))?; - let needs = needs(&parse(&text)?); + let parsed = parse(&text)?; + let needs = needs(&parsed); let patched = if needs.any() { Some(patch(&text, &needs)?) } else { None }; - Ok((text, etag, needs, patched)) + Ok(Policy { + reaches: reaches_pyo(&parsed), + text, + etag, + needs, + patched, + }) } async fn survey(api: &Api, host: &impl Host) -> Result { @@ -522,14 +536,11 @@ async fn survey(api: &Api, host: &impl Host) -> Result { }, }) }; - let (settings, (policy, etag, needs, patched), dns, client) = + let (settings, policy, dns, client) = tokio::try_join!(settings, read_policy(api), dns, client)?; Ok(Survey { gitops: settings["aclsExternallyManagedOn"].as_bool() == Some(true), policy, - etag, - needs, - patched, magic_dns: dns["magicDNS"].as_bool() == Some(true), https: https_on(&settings), client, @@ -583,6 +594,7 @@ pub struct Plan { } fn plan_of(s: &Survey) -> Plan { + let n = &s.policy.needs; let mut p = Plan::default(); let mut step = |todo: bool, t: [&str; 3]| { if todo { @@ -593,22 +605,22 @@ fn plan_of(s: &Survey) -> Plan { }; step(!s.magic_dns, words::MAGIC_DNS); step(s.https != Some(true), words::HTTPS); - step(s.needs.tag_owner, words::TAG_OWNER); - if s.needs.grant || reaches_pyo(&parse(&s.policy).unwrap_or_default()) == Some(true) { - step(s.needs.grant, words::GRANT); + step(n.tag_owner, words::TAG_OWNER); + if n.grant || s.policy.reaches == Some(true) { + step(n.grant, words::GRANT); } // A policy in Git that has what's required is left as it is. - let writes_policy = !s.gitops || s.needs.required(); - if writes_policy || !s.needs.approver { - step(s.needs.approver, words::APPROVER); + let writes_policy = !s.gitops || n.required(); + if writes_policy || !n.approver { + step(n.approver, words::APPROVER); } step(!s.client, words::CLIENT); - if let Some(new) = &s.patched + if let Some(new) = &s.policy.patched && writes_policy { - p.diff = diff(&s.policy, new); + p.diff = diff(&s.policy.text, new); } - if s.gitops && s.needs.required() { + if s.gitops && n.required() { p.blocked = Some(GITOPS.into()); } p @@ -734,7 +746,11 @@ fn policy_changes(n: &Needs) -> Vec { /// Writes the policy with what it needs. If someone changed it meanwhile /// (412), reads it again and plans once more. async fn write_policy(api: &Api, s: &Survey) -> Result, String> { - let (mut etag, mut needs, mut patched) = (s.etag.clone(), s.needs, s.patched.clone()); + let (mut etag, mut needs, mut patched) = ( + s.policy.etag.clone(), + s.policy.needs, + s.policy.patched.clone(), + ); for attempt in 0..2 { let Some(text) = patched.as_deref() else { return Ok(vec![]); @@ -762,8 +778,8 @@ async fn write_policy(api: &Api, s: &Survey) -> Result, String> { } Err(e) if e.status == 412 && attempt == 0 => { tracing::info!("tailnet policy changed meanwhile, planning again"); - let (_, e2, n2, p2) = read_policy(api).await?; - (etag, needs, patched) = (e2, n2, p2); + let p = read_policy(api).await?; + (etag, needs, patched) = (p.etag, p.needs, p.patched); } Err(e) if e.status == 412 => { return Err( @@ -835,12 +851,12 @@ pub(crate) async fn apply_with(api: &Api, host: &impl Host) -> Result Date: Fri, 20 Nov 2026 04:48:02 +0700 Subject: [PATCH 14/32] fix(api): never widen tailnet access when adding pyo's grant Access limited to a group or a posture counted as not reaching tag:pyo, so the setup added a grant for autogroup:member and widened it. Any accept rule to tag:pyo now counts as the admin's choice. Pyo only adds the missing ports for those same sources, with their posture, and uses autogroup:member only when no rule reaches tag:pyo at all. --- crates/pyo-api/src/tailscale_setup.rs | 162 ++++++++++++++------ crates/pyo-api/src/tailscale_setup/tests.rs | 132 +++++++++------- 2 files changed, 193 insertions(+), 101 deletions(-) diff --git a/crates/pyo-api/src/tailscale_setup.rs b/crates/pyo-api/src/tailscale_setup.rs index 52b705d..a8477d9 100644 --- a/crates/pyo-api/src/tailscale_setup.rs +++ b/crates/pyo-api/src/tailscale_setup.rs @@ -6,7 +6,8 @@ //! //! - **MagicDNS** and **HTTPS certificates** on. //! - **The policy**: `tag:pyo` in `tagOwners`, a grant to reach it on ports -//! 80 and 443 when the policy doesn't allow that already, and +//! 80 and 443 when no one can yet (for the sources the policy already +//! lets reach it, so access is never widened), and //! `autoApprovers.services` for it. The policy is HuJSON and is edited in //! place, so its comments and formatting stay. It's validated first and //! written with `If-Match`, so a change made meanwhile is never lost. @@ -226,25 +227,61 @@ fn parse(text: &str) -> Result { } /// What the policy is missing for Pyo. -#[derive(Debug, Default, Clone, Copy, PartialEq)] +#[derive(Debug, Default, Clone, PartialEq)] pub struct Needs { /// `tag:pyo` in `tagOwners`: needed before anything can carry the tag. pub tag_owner: bool, - /// A grant to tag:pyo on ports 80 and 443: only when the policy doesn't - /// already let the tailnet reach it. - pub grant: bool, + /// Who the policy lets reach tag:pyo now. Pyo adds a grant on ports 80 + /// and 443 only when nobody reaches it on both. + pub reach: Reach, /// `autoApprovers.services` for tag:pyo. Pyo approves its Services' /// hosts through the API anyway, so this only adds resilience. pub approver: bool, } +/// Who the policy lets reach tag:pyo. +#[derive(Debug, Default, Clone, PartialEq)] +pub enum Reach { + /// Neither `acls` nor `grants`: Pyo doesn't add the first rule there. + #[default] + NoRules, + /// Someone reaches it on ports 80 and 443. Left as it is, whoever that is. + Yes, + /// Rules reach it, but no one on both ports. Pyo adds the ports for + /// exactly these sources, with their posture, and no one else. + Partly(Vec), + /// No rule reaches it at all. + No, +} + +/// Sources of a rule that reaches tag:pyo, and the posture it asks of them. +#[derive(Debug, Clone, PartialEq)] +pub struct Source { + pub src: Vec, + pub posture: Vec, +} + +/// Who gets access when no rule reaches tag:pyo at all. +const MEMBERS: &str = "autogroup:member"; + impl Needs { + /// The grants to add for tag:pyo on ports 80 and 443, if any. + fn grant(&self) -> Option> { + match &self.reach { + Reach::NoRules | Reach::Yes => None, + Reach::Partly(s) => Some(s.clone()), + Reach::No => Some(vec![Source { + src: vec![MEMBERS.into()], + posture: vec![], + }]), + } + } fn any(&self) -> bool { - self.tag_owner || self.grant || self.approver + self.tag_owner || self.grant().is_some() || self.approver } /// Without these the setup can't work. fn required(&self) -> bool { - self.tag_owner || self.grant + self.tag_owner || self.grant().is_some() } } @@ -255,7 +292,7 @@ fn strs(v: &Value) -> impl Iterator { pub fn needs(p: &Value) -> Needs { Needs { tag_owner: p["tagOwners"].get(TAG).is_none(), - grant: reaches_pyo(p) == Some(false), + reach: reach(p), approver: !strs(&p["autoApprovers"]["services"][TAG]).any(|s| s == TAG), } } @@ -273,46 +310,58 @@ fn ports_cover(ports: &str, port: u16) -> bool { }) } -/// Whether everyone on the tailnet can reach tag:pyo on ports 80 and 443, -/// by a rule that plainly says so: from "*" or autogroup:member, to "*" or -/// tag:pyo, with no posture or route conditions. None when the policy has -/// neither `acls` nor `grants`, so Pyo doesn't add the first rule there. -pub fn reaches_pyo(p: &Value) -> Option { +/// Who the policy lets reach tag:pyo: every accept rule to "*" or tag:pyo +/// counts, whatever its sources, protocol or posture, so Pyo never gives +/// anyone access the admin's rules don't already give them on some port. +/// Rules routed `via` a router don't reach the servers themselves. +pub fn reach(p: &Value) -> Reach { if p.get("acls").is_none() && p.get("grants").is_none() { - return None; - } - let everyone = |v: &Value| strs(v).any(|s| s == "*" || s == "autogroup:member"); - let plain = |r: &Value| r.get("srcPosture").is_none() && r.get("via").is_none(); - let mut open = [false, false]; - let mut take = |ports: &str| { - for (i, port) in [80, 443].into_iter().enumerate() { - open[i] |= ports_cover(ports, port); + return Reach::NoRules; + } + // Each rule that reaches tag:pyo, and whether it covers 80 and 443 over TCP. + let mut rules: Vec<(Source, [bool; 2])> = vec![]; + let mut note = |src: Vec, posture: &Value, open: [bool; 2]| { + if src.is_empty() { + return; + } + let source = Source { + src, + posture: strs(posture).map(str::to_owned).collect(), + }; + match rules.iter_mut().find(|(s, _)| *s == source) { + Some((_, o)) => *o = [o[0] | open[0], o[1] | open[1]], + None => rules.push((source, open)), } }; + let covers = |ports: &str| [ports_cover(ports, 80), ports_cover(ports, 443)]; + let or = |a: [bool; 2], b: [bool; 2]| [a[0] | b[0], a[1] | b[1]]; for r in p["acls"].as_array().into_iter().flatten() { + if r["action"].as_str() != Some("accept") || r.get("via").is_some() { + continue; + } let tcp = match &r["proto"] { Value::Null => true, v => matches!(v.as_str(), Some("tcp" | "6")), }; - if r["action"].as_str() != Some("accept") - || !(everyone(&r["src"]) || everyone(&r["users"])) - || !tcp - || !plain(r) - { - continue; - } + let mut open = None; for d in strs(&r["dst"]).chain(strs(&r["ports"])) { if let Some((host, ports)) = d.rsplit_once(':') && (host == "*" || host == TAG) { - take(ports); + let o = if tcp { covers(ports) } else { [false, false] }; + open = Some(or(open.unwrap_or_default(), o)); } } + if let Some(o) = open { + let src = strs(&r["src"]).chain(strs(&r["users"])).map(str::to_owned).collect(); + note(src, &r["srcPosture"], o); + } } for g in p["grants"].as_array().into_iter().flatten() { - if !everyone(&g["src"]) || !plain(g) || !strs(&g["dst"]).any(|d| d == "*" || d == TAG) { + if g.get("via").is_some() || !strs(&g["dst"]).any(|d| d == "*" || d == TAG) { continue; } + let mut open = [false, false]; for ip in strs(&g["ip"]) { let (proto, ports) = match ip.split_once(':') { Some(x) => x, @@ -320,11 +369,28 @@ pub fn reaches_pyo(p: &Value) -> Option { None => (ip, "*"), }; if matches!(proto, "*" | "tcp" | "6") { - take(ports); + open = or(open, covers(ports)); } } + note(strs(&g["src"]).map(str::to_owned).collect(), &g["srcPosture"], open); + } + // Any one source on both ports, over all its rules. + let mut by_src: Vec<(&str, [bool; 2])> = vec![]; + for (s, o) in &rules { + for src in &s.src { + match by_src.iter_mut().find(|(x, _)| x == src) { + Some((_, b)) => *b = or(*b, *o), + None => by_src.push((src, *o)), + } + } + } + if by_src.iter().any(|(_, o)| *o == [true, true]) { + Reach::Yes + } else if rules.is_empty() { + Reach::No + } else { + Reach::Partly(rules.into_iter().map(|(s, _)| s).collect()) } - Some(open == [true, true]) } fn strings(xs: &[&str]) -> jsonc_parser::cst::CstInputValue { @@ -348,14 +414,23 @@ pub fn patch(text: &str, needs: &Needs) -> Result { .ok_or_else(|| cant("tagOwners"))? .append(TAG, strings(&[OWNERS])); } - if needs.grant { - obj.array_value_or_create("grants") - .ok_or_else(|| "Pyo can't edit your tailnet policy: grants isn't a list.".to_owned())? - .append(CstInputValue::Object(vec![ - ("src".into(), strings(&["autogroup:member"])), + if let Some(sources) = needs.grant() { + let grants = obj + .array_value_or_create("grants") + .ok_or_else(|| "Pyo can't edit your tailnet policy: grants isn't a list.".to_owned())?; + for s in sources { + let src: Vec<&str> = s.src.iter().map(String::as_str).collect(); + let mut grant = vec![ + ("src".into(), strings(&src)), ("dst".into(), strings(&[TAG])), ("ip".into(), strings(&["tcp:80", "tcp:443"])), - ])); + ]; + if !s.posture.is_empty() { + let posture: Vec<&str> = s.posture.iter().map(String::as_str).collect(); + grant.push(("srcPosture".into(), strings(&posture))); + } + grants.append(CstInputValue::Object(grant)); + } } if needs.approver { let services = obj @@ -474,8 +549,6 @@ struct Policy { text: String, etag: Option, needs: Needs, - /// What [`reaches_pyo`] says of it. - reaches: Option, /// The policy with what it needs, when it needs something. patched: Option, } @@ -505,7 +578,6 @@ async fn read_policy(api: &Api) -> Result { None }; Ok(Policy { - reaches: reaches_pyo(&parsed), text, etag, needs, @@ -606,8 +678,8 @@ fn plan_of(s: &Survey) -> Plan { step(!s.magic_dns, words::MAGIC_DNS); step(s.https != Some(true), words::HTTPS); step(n.tag_owner, words::TAG_OWNER); - if n.grant || s.policy.reaches == Some(true) { - step(n.grant, words::GRANT); + if n.reach != Reach::NoRules { + step(n.grant().is_some(), words::GRANT); } // A policy in Git that has what's required is left as it is. let writes_policy = !s.gitops || n.required(); @@ -734,7 +806,7 @@ async fn validate(api: &Api, text: &str) -> Result<(), String> { fn policy_changes(n: &Needs) -> Vec { [ (n.tag_owner, words::TAG_OWNER), - (n.grant, words::GRANT), + (n.grant().is_some(), words::GRANT), (n.approver, words::APPROVER), ] .into_iter() @@ -748,7 +820,7 @@ fn policy_changes(n: &Needs) -> Vec { async fn write_policy(api: &Api, s: &Survey) -> Result, String> { let (mut etag, mut needs, mut patched) = ( s.policy.etag.clone(), - s.policy.needs, + s.policy.needs.clone(), s.policy.patched.clone(), ); for attempt in 0..2 { diff --git a/crates/pyo-api/src/tailscale_setup/tests.rs b/crates/pyo-api/src/tailscale_setup/tests.rs index fa2dde9..bb2edf3 100644 --- a/crates/pyo-api/src/tailscale_setup/tests.rs +++ b/crates/pyo-api/src/tailscale_setup/tests.rs @@ -337,7 +337,7 @@ fn the_patch_keeps_comments_and_formatting() { n, Needs { tag_owner: true, - grant: false, + reach: Reach::Yes, approver: true } ); @@ -374,7 +374,7 @@ fn the_patch_adds_to_tag_owners_already_there() { n, Needs { tag_owner: true, - grant: true, + reach: Reach::No, approver: true } ); @@ -394,14 +394,14 @@ fn the_patch_adds_to_tag_owners_already_there() { json!([{ "src": ["autogroup:member"], "dst": [TAG], "ip": ["tcp:80", "tcp:443"] }]) ); assert_eq!(v["acls"], parse(RESTRICTED_POLICY).unwrap()["acls"]); - assert_eq!(reaches_pyo(&v), Some(true)); + assert_eq!(reach(&v), Reach::Yes); } #[test] fn approvers_for_tag_pyo_get_tag_pyo_added() { let p = r#"{ "autoApprovers": { "services": { "tag:pyo": ["group:ops"] } }, "tagOwners": { "tag:pyo": [] }, "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] }"#; let n = needs(&parse(p).unwrap()); - assert!(n.approver && !n.tag_owner && !n.grant); + assert!(n.approver && !n.tag_owner && n.grant().is_none()); let v = parse(&patch(p, &n).unwrap()).unwrap(); assert_eq!( v["autoApprovers"]["services"][TAG], @@ -409,71 +409,89 @@ fn approvers_for_tag_pyo_get_tag_pyo_added() { ); } +fn src(src: &[&str], posture: &[&str]) -> Source { + Source { + src: src.iter().map(|s| (*s).to_owned()).collect(), + posture: posture.iter().map(|s| (*s).to_owned()).collect(), + } +} + #[test] fn what_lets_the_tailnet_reach_pyo() { - let r = |p: Value| reaches_pyo(&p); - assert_eq!( - r(json!({ "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] })), - Some(true) - ); - assert_eq!( - r(json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["*:*"] }] })), - Some(true) - ); - assert_eq!( - r(json!({ "acls": [{ "action": "accept", "users": ["*"], "ports": ["*:*"] }] })), - Some(true) - ); - assert_eq!( - r( - json!({ "grants": [{ "src": ["autogroup:member"], "dst": [TAG], "ip": ["tcp:80", "443"] }] }) - ), - Some(true) - ); - assert_eq!( - r(json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["tag:pyo:80,443"] }] })), - Some(true) - ); - assert_eq!( - r(json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["tag:pyo:1-1024"] }] })), - Some(true) - ); - // Split over two rules. - assert_eq!( - r(json!({ "grants": [ + let r = |p: Value| reach(&p); + for yes in [ + json!({ "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] }), + json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["*:*"] }] }), + json!({ "acls": [{ "action": "accept", "users": ["*"], "ports": ["*:*"] }] }), + json!({ "grants": [{ "src": ["autogroup:member"], "dst": [TAG], "ip": ["tcp:80", "443"] }] }), + json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["tag:pyo:80,443"] }] }), + json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["tag:pyo:1-1024"] }] }), + // Split over two rules. + json!({ "grants": [ { "src": ["*"], "dst": [TAG], "ip": ["tcp:80"] }, { "src": ["*"], "dst": ["*"], "ip": ["tcp:443"] }, - ] })), - Some(true) + ] }), + // Only some people, or only with a posture: the admin's choice, kept. + json!({ "grants": [{ "src": ["group:eng"], "dst": ["*"], "ip": ["*"] }] }), + json!({ "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"], "srcPosture": ["posture:x"] }] }), + ] { + assert_eq!(r(yes.clone()), Reach::Yes, "{yes}"); + } + // A port missing, or UDP only: those same sources, and no one else. + assert_eq!( + r(json!({ "grants": [{ "src": ["group:eng"], "dst": [TAG], "ip": ["tcp:443"] }] })), + Reach::Partly(vec![src(&["group:eng"], &[])]) ); - // Only some people, a port missing, UDP, posture: not plainly open. assert_eq!( - r(json!({ "grants": [{ "src": ["group:eng"], "dst": ["*"], "ip": ["*"] }] })), - Some(false) + r(json!({ "grants": [{ "src": ["*"], "dst": [TAG], "ip": ["udp:*"] }] })), + Reach::Partly(vec![src(&["*"], &[])]) ); assert_eq!( - r(json!({ "grants": [{ "src": ["*"], "dst": [TAG], "ip": ["tcp:443"] }] })), - Some(false) + r(json!({ "acls": [{ "action": "accept", "src": ["*"], "proto": "udp", "dst": ["*:*"] }] })), + Reach::Partly(vec![src(&["*"], &[])]) ); assert_eq!( - r(json!({ "grants": [{ "src": ["*"], "dst": [TAG], "ip": ["udp:*"] }] })), - Some(false) + r(json!({ "acls": [{ "action": "accept", "src": ["group:eng"], "srcPosture": ["posture:x"], "dst": ["*:22"] }] })), + Reach::Partly(vec![src(&["group:eng"], &["posture:x"])]) ); + // Nothing reaches tag:pyo, or there are no rules yet. assert_eq!( - r( - json!({ "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"], "srcPosture": ["posture:x"] }] }) - ), - Some(false) + r(json!({ "acls": [{ "action": "accept", "src": ["group:eng"], "dst": ["tag:prod:22"] }] })), + Reach::No ); + assert_eq!(r(json!({ "acls": [] })), Reach::No); + assert_eq!(r(json!({ "tagOwners": {} })), Reach::NoRules); +} + +#[test] +fn access_limited_to_a_group_is_never_widened() { + // The group reaches everything: nothing to add, and no grant at all. + let p = r#"{ "tagOwners": { "tag:pyo": [] }, "grants": [{ "src": ["group:eng"], "dst": ["*"], "ip": ["*"] }] }"#; + let n = needs(&parse(p).unwrap()); + assert_eq!(n.reach, Reach::Yes); + let out = patch(p, &Needs { approver: true, ..n }).unwrap(); + assert_eq!(parse(&out).unwrap()["grants"], parse(p).unwrap()["grants"]); + assert!(!out.contains(MEMBERS), "{out}"); + + // The group reaches tag:pyo on 443 only: 80 is added for that group, + // with its posture, and never for anyone else. + let p = r#"{ + "tagOwners": { "tag:pyo": [] }, + "grants": [ + { "src": ["group:eng"], "dst": ["tag:pyo"], "ip": ["tcp:443"], "srcPosture": ["posture:latest"] }, + ], +}"#; + let n = needs(&parse(p).unwrap()); + assert!(n.required()); + let out = patch(p, &n).unwrap(); + let v = parse(&out).unwrap(); assert_eq!( - r( - json!({ "acls": [{ "action": "accept", "src": ["*"], "proto": "udp", "dst": ["*:*"] }] }) - ), - Some(false) + v["grants"][1], + json!({ "src": ["group:eng"], "dst": [TAG], "ip": ["tcp:80", "tcp:443"], "srcPosture": ["posture:latest"] }) ); - assert_eq!(r(json!({ "acls": [] })), Some(false)); - // No rules at all: Pyo doesn't write the first one. - assert_eq!(r(json!({ "tagOwners": {} })), None); + assert_eq!(v["grants"].as_array().unwrap().len(), 2); + assert!(!out.contains(MEMBERS), "{out}"); + assert_eq!(reach(&v), Reach::Yes); } #[test] @@ -504,8 +522,10 @@ fn the_plan_uses_the_policy_as_parsed_once() { policy: Policy { text: "not a policy".into(), etag: None, - needs: Needs::default(), - reaches: Some(true), + needs: Needs { + reach: Reach::Yes, + ..Default::default() + }, patched: None, }, magic_dns: true, From 3ec85dfcd9da7c49d2188008616d24086d7c3f61 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Fri, 20 Nov 2026 04:51:36 +0700 Subject: [PATCH 15/32] feat(dash): show a dismissable update notice in the sidebar When a newer Pyo is out, the installation's admin sees its version, the release notes, a link to Updates and the install command that updates Pyo. Dismissed per version in localStorage. Hidden on hosted Pyo and while an update runs. --- dash/src/components/pyo/UpdateNotice.tsx | 98 ++++++++++++++++++++++++ dash/src/components/shell/AppShell.tsx | 5 ++ 2 files changed, 103 insertions(+) create mode 100644 dash/src/components/pyo/UpdateNotice.tsx diff --git a/dash/src/components/pyo/UpdateNotice.tsx b/dash/src/components/pyo/UpdateNotice.tsx new file mode 100644 index 0000000..e156c9c --- /dev/null +++ b/dash/src/components/pyo/UpdateNotice.tsx @@ -0,0 +1,98 @@ +import { ArrowSquareOutIcon, CloudArrowUpIcon, XIcon } from "@phosphor-icons/react"; +import { Link } from "@tanstack/react-router"; +import { useState } from "react"; +import { CopyButton } from "~/components/ui/Table"; +import { usePyo } from "~/lib/pyo/store"; + +// A quiet note at the foot of the sidebar when a newer Pyo is out: the +// version, its release notes, the Updates page and the install command +// (running it again updates Pyo). For the installation's admin, until they +// dismiss that version. + +/** Running the installer again updates Pyo to the latest release (README, Updating). */ +export const UPDATE_COMMAND = "curl -fsSL https://pyo.dev/install.sh | bash"; + +const DISMISSED_KEY = "pyo:update-dismissed"; + +function loadDismissed() { + try { + return localStorage.getItem(DISMISSED_KEY); + } catch { + return null; + } +} + +export function UpdateNotice({ managed }: { managed: boolean }) { + const s = usePyo(); + const u = s.updates; + const [dismissed, setDismissed] = useState(loadDismissed); + const latest = u?.latest; + if ( + managed || + !s.user.isAdmin || + !u || + !latest || + !u.plan?.pyo.needed || + u.active || + dismissed === latest.version + ) + return null; + const dismiss = () => { + setDismissed(latest.version); + try { + localStorage.setItem(DISMISSED_KEY, latest.version); + } catch { + // Private windows: hidden until the next load. + } + }; + return ( + + ); +} diff --git a/dash/src/components/shell/AppShell.tsx b/dash/src/components/shell/AppShell.tsx index 5c802d8..336d1a8 100644 --- a/dash/src/components/shell/AppShell.tsx +++ b/dash/src/components/shell/AppShell.tsx @@ -43,6 +43,7 @@ import { NewButton } from "~/components/ui/NewButton"; import { InviteDialog } from "~/components/pyo/InviteDialog"; import { NewDomainDialog } from "~/components/pyo/NewDomainDialog"; import { useUpdateAvailable } from "~/components/pyo/UpdateSettings"; +import { UpdateNotice } from "~/components/pyo/UpdateNotice"; import { Toaster } from "~/components/ui/Toaster"; import { timeAgo } from "~/lib/pyo/format"; import { auth } from "~/lib/pyo/backend"; @@ -371,6 +372,10 @@ function Sidebar({
    )} + {/* Nothing until the API says whether Pyo is hosted (updates are ours there). */} + ); } From e5825d624a6062ba220804120fb01e6cfba64324 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Fri, 20 Nov 2026 04:51:36 +0700 Subject: [PATCH 16/32] feat(dash): add a setup checklist to the overview Connect Git, deploy a service, add a domain, turn on backups and set up Tailscale. Each step ticks itself off from the snapshot and links to its page. Backups show for team admins with a backup store, and Tailscale for the installation's admin. The card hides once done or dismissed. --- dash/src/components/pyo/FirstRunChecklist.tsx | 159 ++++++++++++++++++ dash/src/routes/_app/$team/index.tsx | 2 + 2 files changed, 161 insertions(+) create mode 100644 dash/src/components/pyo/FirstRunChecklist.tsx diff --git a/dash/src/components/pyo/FirstRunChecklist.tsx b/dash/src/components/pyo/FirstRunChecklist.tsx new file mode 100644 index 0000000..202718d --- /dev/null +++ b/dash/src/components/pyo/FirstRunChecklist.tsx @@ -0,0 +1,159 @@ +import { + ArrowRightIcon, + CheckCircleIcon, + CircleIcon, + XIcon, +} from "@phosphor-icons/react"; +import { useState } from "react"; +import { AppLink } from "~/components/ui/AppLink"; +import { Layered } from "~/components/ui/Layered"; +import { isFreeDomain } from "~/lib/pyo/freeDomain"; +import { + deploymentsWhere, + roleIn, + servicesIn, + type PyoState, +} from "~/lib/pyo/store"; + +// The first things to do on a new Pyo, on the team's Overview. Each step +// ticks itself off from the snapshot and links to where it's done. The card +// goes once every step is done, or when it's dismissed. + +const DISMISSED_KEY = "pyo:checklist-dismissed"; + +type Step = { label: string; href: string; done: boolean }; + +function steps(s: PyoState): Step[] { + const team = s.currentTeamId; + const role = roleIn(s); + const teamAdmin = role === "owner" || role === "admin"; + const services = servicesIn(s); + const backups = s.teamBackups.find((t) => t.teamId === team); + const out: (Step | null)[] = [ + { + label: "Connect GitHub or GitLab", + href: "/integrations", + done: + (!!s.github && s.githubInstallations.some((g) => g.teamId === team)) || + s.gitConnections.some((c) => c.teamId === team), + }, + { + label: "Deploy your first service", + href: "/deploy/new", + done: + services.some((a) => a.currentDeploymentId) || + deploymentsWhere(s, { teamId: team }).some( + (d) => d.status === "succeeded", + ), + }, + { + label: "Add a domain", + href: "/domains", + done: services.some((a) => + a.domains.some((d) => !isFreeDomain(d.hostname)), + ), + }, + // Only where there's a store to back up to, for whoever can turn it on. + teamAdmin && backups?.settings + ? { + label: "Turn on backups", + href: "/backups", + done: + backups.settings.enabled || + backups.databases.some((d) => d.enabled), + } + : null, + // Tailscale is the installation's, set up by its admin. + s.user.isAdmin + ? { + label: "Set up Tailscale", + href: "/integrations#tailscale", + done: !!s.tailscale, + } + : null, + ]; + return out.filter((x): x is Step => !!x); +} + +function loadDismissed() { + try { + return localStorage.getItem(DISMISSED_KEY) === "1"; + } catch { + return false; + } +} + +export function FirstRunChecklist({ s }: { s: PyoState }) { + const [dismissed, setDismissed] = useState(loadDismissed); + const list = steps(s); + const done = list.filter((x) => x.done).length; + if (dismissed || done === list.length) return null; + const dismiss = () => { + setDismissed(true); + try { + localStorage.setItem(DISMISSED_KEY, "1"); + } catch { + // Private windows: hidden until the next load. + } + }; + return ( + + + {done} of {list.length} + + + + } + > +
      + {list.map((st) => + st.done ? ( +
    • + + {st.label} +
    • + ) : ( +
    • + + + {st.label} + + +
    • + ), + )} +
    +
    + ); +} diff --git a/dash/src/routes/_app/$team/index.tsx b/dash/src/routes/_app/$team/index.tsx index 30f29fe..ca16fa6 100644 --- a/dash/src/routes/_app/$team/index.tsx +++ b/dash/src/routes/_app/$team/index.tsx @@ -13,6 +13,7 @@ import { import { ProjectIcon } from "~/components/ui/ProjectIcon"; import { useState } from "react"; import { DeploymentList } from "~/components/pyo/lists"; +import { FirstRunChecklist } from "~/components/pyo/FirstRunChecklist"; import { RemoteAccessNote } from "~/components/pyo/RemoteAccess"; import { DomainStatus } from "~/components/pyo/DomainState"; import { ProjectCard } from "~/components/pyo/ProjectCard"; @@ -247,6 +248,7 @@ function OverviewPage() {