// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // The Tailscale option (config.ts ?tailscale=1; Settings, Network): the // guest joins a tailnet through the SDK's NetSpec.tailscale, a Tailscale node // on the page's thread in both modes (in worker mode the SDK bridges its // packets to the worker's NetStack), beside the Wisp network. Its code is a // chunk of its own: this module imports only its types and the SDK's // loadTailscale(), which boot.ts runs only when the option is on, before the // boot, so a chunk that does not load leaves the boot without Tailscale // instead of failing it. // // The secrets are not settings: the node's keys (the SDK's "state" event: // machine, node and disco private keys and the registration) and an auth // key typed in Settings live in localStorage TAILSCALE_KEY only, never in // kw.settings, the URL (Reboot's fallback where localStorage refuses carries // settings only), the logs, the diagnostics or a suspended session (the // guest never sees them: the node runs on the page, and a snapshot is the // guest's memory and devices). Each is kept for the login server it belongs // to (its origin, config.ts tailscaleServerOrigin(); "" is Tailscale's) and // given only to that server: a node per server (another server gets a node // of its own, and the others stay), one auth key for one server. Reboot // saves a typed auth key only with Tailscale on, for the server chosen then, // and drops a saved one when Tailscale is off or the server changes; a login // drops it too. Log out (forgetDevice()) expires the node key at the login // server where the node runs, and clears that server's node and key. // // The exit node (Settings' Exit node, the top bar panel's list): a peer that // takes all the guest's internet traffic instead of Wisp (the SDK's // TailscaleSpec.exitNode). Not a setting either, so no URL sets it: the // choice is kept in TAILSCALE_KEY per login server (a name belongs to one // tailnet), given to that server's node at boot, and changed at once on a // running node (setExitNode(), which saves it); for another server, or with // no node this load, Settings' choice is saved by Reboot. Log out keeps it. // While it is chosen but not usable (offline, not found, not connected...) // the guest's internet traffic is refused rather than sent through Wisp: // the top bar's item needs attention then (tailscaleKind()) and a toast says // so once. // // The URL alone does not turn Tailscale on or change its server // (config.ts tailscaleAsk): such a load starts no node at all, and the // status line and a toast offer "Enable and reboot", which names the server // and asks before it saves the URL's Tailscale settings and reboots. // // The login: without an auth key or a saved login, the SDK's "authurl" // event gives the URL the user must open (http or https only; another is // ignored and said); Settings shows it as a link, and a toast offers it (its // button is a click, so the new tab is not blocked; nothing opens it by // itself). The status events (no polling) drive the store's `tailscale` // (store.ts TailscaleView). import { KW } from "./kw.ts"; import { tailscaleServerOrigin, type Config } from "./config.ts"; import { loadTailscale, type KernelHandle, type TailscaleClient, type TailscaleControlState, type TailscaleEvent, type TailscaleExitNodeStatus, type TailscaleSpec, type TailscaleStatus } from "./sdk.ts"; import { ui$, type Options, type TailscaleView } from "./store.ts"; import { openSection } from "./sysapps.ts"; /** localStorage: the Tailscale secrets and the exit node, a JSON object { nodes?: { : state }, authKey?: { server, key }, exitNodes?: { : choice } } (the top of this file). */ export const TAILSCALE_KEY = "kw.tailscale"; interface Saved { /** Per login server (its origin): the SDK's ControlState, the node's private keys and its registration. */ nodes: Record; /** An auth key for the next login, with the login server (origin) it was typed for. */ authKey?: { server: string; key: string }; /** Per login server (its origin): the exit node chosen (Options.tsexit; never ""). */ exitNodes: Record; } const PRIVKEY = /^privkey:[0-9a-f]{64}$/i; /** A ControlState whose keys the SDK accepts (its ControlClient throws on others). */ function validState(x: unknown): x is TailscaleControlState { if (!x || typeof x !== "object") return false; const s = x as Record; return [s.machineKey, s.nodeKey, s.discoKey].every((k) => typeof k === "string" && PRIVKEY.test(k)) && (s.oldNodeKey === undefined || (typeof s.oldNodeKey === "string" && PRIVKEY.test(s.oldNodeKey))); } /** The saved secrets (none where they do not parse or localStorage refuses); `invalid`: servers whose node was not valid. */ function readSaved(): Saved & { invalid: string[] } { const out: Saved & { invalid: string[] } = { nodes: {}, exitNodes: {}, invalid: [] }; try { const v: unknown = JSON.parse(localStorage.getItem(TAILSCALE_KEY) ?? "{}"); if (!v || typeof v !== "object") return out; const o = v as { nodes?: unknown; authKey?: unknown; exitNodes?: unknown }; if (o.nodes && typeof o.nodes === "object") { for (const [server, state] of Object.entries(o.nodes as Record)) { if (validState(state)) out.nodes[server] = state; else out.invalid.push(server); } } const a = o.authKey as { server?: unknown; key?: unknown } | undefined; if (a && typeof a.server === "string" && typeof a.key === "string" && a.key) out.authKey = { server: a.server, key: a.key }; if (o.exitNodes && typeof o.exitNodes === "object") { for (const [server, choice] of Object.entries(o.exitNodes as Record)) if (typeof choice === "string" && choice.trim()) out.exitNodes[server] = choice.trim(); } } catch {} return out; } /** Saves the secrets (none: removes the key); false where localStorage refuses. */ function writeSaved(s: Saved): boolean { try { const out = { ...(Object.keys(s.nodes).length ? { nodes: s.nodes } : {}), ...(s.authKey ? { authKey: s.authKey } : {}), ...(Object.keys(s.exitNodes).length ? { exitNodes: s.exitNodes } : {}), }; if (Object.keys(out).length) localStorage.setItem(TAILSCALE_KEY, JSON.stringify(out)); else localStorage.removeItem(TAILSCALE_KEY); return true; } catch { return false; } } /** Changes the saved secrets; false where localStorage refuses. */ const updateSaved = (f: (s: Saved) => void): boolean => { const s = readSaved(); f(s); return writeSaved({ nodes: s.nodes, exitNodes: s.exitNodes, ...(s.authKey ? { authKey: s.authKey } : {}) }); }; /** A node identity is saved for this login server (?tsserver= value; "" is Tailscale's). */ export const hasSavedNode = (server: string): boolean => !!readSaved().nodes[tailscaleServerOrigin(server)]; /** An auth key is saved for the next login at this login server. */ export const hasSavedAuthKey = (server: string): boolean => readSaved().authKey?.server === tailscaleServerOrigin(server); /** The exit node saved for this login server ("": none). */ export const savedExitNode = (server: string): string => readSaved().exitNodes[tailscaleServerOrigin(server)] ?? ""; /** Settings' exit node is not the one saved for the server chosen there: Reboot saves it (ui.ts optionsChanged()). */ export const exitPending = (o: Options): boolean => o.tsexit.trim() !== savedExitNode(o.tsserver); /** * Reboot (ui.ts), with the Tailscale options it saves: a typed auth key is * kept only with Tailscale on, for that login server; a saved one goes when * Tailscale is off or another server is chosen. The exit node is saved for * that server, Tailscale on or off ("": none). */ export function rebootTailscale(o: { on: boolean; server: string; authKey: string; exitNode: string }): void { const server = tailscaleServerOrigin(o.server); const exit = o.exitNode.trim(); updateSaved((s) => { if (o.on && o.authKey) s.authKey = { server, key: o.authKey }; else if (!o.on || s.authKey?.server !== server) delete s.authKey; if (exit) s.exitNodes[server] = exit; else delete s.exitNodes[server]; }); } /** The login server's name as shown: Tailscale, or the host of ?tsserver=. */ export function serverName(server: string): string { if (!server) return "Tailscale"; try { return new URL(server).host || server; } catch { return server; } } /** The login server (origin) this load's node belongs to: the saved Tailscale settings'. */ let origin = ""; let cfgRef: Config | undefined; /** The view this load starts with (ui.ts, before anything renders). */ export function initialView(cfg: Config): TailscaleView { cfgRef = cfg; origin = tailscaleServerOrigin(cfg.tsServer); const ask = cfg.tailscaleAsk; return { state: ask ? "ask" : cfg.tailscale ? "loading" : cfg.tailscaleParam ? "blocked" : "off", name: "", addresses: [], relay: "", peers: 0, online: 0, devices: [], server: serverName(cfg.tsServer), ...(ask ? { askServer: serverName(ask.server) } : {}), ...(cfg.tailscaleWhy ? { error: cfg.tailscaleWhy } : {}), saved: hasSavedNode(cfg.tsServer), exitNodes: [], exitNode: null, }; } const set = (p: Partial) => ui$().set((s) => ({ tailscale: { ...s.tailscale, ...p } })); let client: TailscaleClient | undefined; /** Log out ran: the node's later "state" events are not saved again. */ let forgotten = false; let shownAuthURL = ""; let wasLogin = false; /** The blocked exit node last seen ("choice reason", "" while none) and its toast's timer (showStatus()). */ let blockedKey = ""; let blockedTimer: ReturnType | undefined; /** * The `net.tailscale` spec of this load (with this server's saved node and * auth key), once the client's module has loaded; null where the option is * off or blocked, or the module did not load (the view and `log` say why: * the boot goes on with the Wisp network only). */ export async function tailscaleSpec(cfg: Config, log: (m: string) => void): Promise { const ts = cfg.tailscale; if (!ts) return null; try { await loadTailscale(); } catch (e) { const why = `its module did not load (${(e as Error)?.message ?? e})`; log(`[host] tailscale: left out: ${why}`); set({ state: "failed", error: why }); return null; } const saved = readSaved(); if (saved.invalid.includes(origin)) log("[host] tailscale: the saved node's keys are not valid: this boot makes a new node"); const state = saved.nodes[origin]; const authKey = saved.authKey?.server === origin ? saved.authKey.key : undefined; // Logged in already: the auth key is not needed (and is not kept). const loggedIn = !!state?.authorized; if (loggedIn && authKey) updateSaved((s) => { delete s.authKey; }); const exitNode = saved.exitNodes[origin]; if (exitNode) log(`[host] tailscale: exit node ${exitNode}: the guest's internet traffic goes through it, or nowhere while it cannot`); return { ...ts, ...(state ? { state } : {}), ...(!loggedIn && authKey ? { authKey } : {}), ...(exitNode ? { exitNode } : {}) }; } /** A login URL the page may link to and open: http or https only (`new URL`), else null. */ export function loginURL(url: string): string | null { try { const u = new URL(url); return u.protocol === "http:" || u.protocol === "https:" ? u.href : null; } catch { return null; } } const BAD_LOGIN = "the login server sent a login link that is not an http(s) URL: ignored"; /** createKernel's onTailscale: saves the node's state, offers the login, shows the status. */ export function onTailscaleEvent(e: TailscaleEvent): void { if (e.type === "state") { if (forgotten) return; updateSaved((s) => { s.nodes[origin] = e.state; // Logged in: the auth key has done its job. if (e.state.authorized && s.authKey?.server === origin) delete s.authKey; }); set({ saved: true }); } else if (e.type === "authurl") { const url = loginURL(e.url); if (!url) { set({ authURL: undefined, error: BAD_LOGIN }); return; } set({ authURL: url }); if (url === shownAuthURL) return; shownAuthURL = url; wasLogin = true; // A toast with a button: the click is the user gesture a new tab needs. KW.ui?.toast("Tailscale: log in to add this device to your tailnet", { action: "Log in", run: () => openLogin(url), ms: 30000 }); } else showStatus(e.status); } /** Opens the login URL in a new tab (from a click: Settings' link, or the toast's button); http(s) only. */ export function openLogin(url: string): void { const u = loginURL(url); if (u) window.open(u, "_blank", "noopener,noreferrer"); } function showStatus(st: TailscaleStatus): void { if (forgotten && st.state !== "stopped" && st.state !== "logged-out") return; const region = st.homeDERP ? client?.netmap?.derpMap?.Regions[String(st.homeDERP)] : undefined; const waiting = st.state === "needs-login" || st.state === "starting"; const link = waiting ? (st.authURL !== undefined ? loginURL(st.authURL) : ui$().get().tailscale.authURL ?? null) : null; set({ state: st.state, authURL: link ?? undefined, name: st.name, addresses: st.addresses, relay: region ? region.RegionName || region.RegionCode : st.homeDERP ? `region ${st.homeDERP}` : "", peers: st.peers.length, online: st.peers.filter((p) => p.online).length, devices: st.peers.map((p) => ({ id: p.id, name: p.name, address: p.addresses.find((a) => !a.includes(":")) ?? p.addresses[0] ?? "", online: p.online, routes: p.routes ?? [], exitNode: !!p.exitNode })) .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.id - b.id)), error: st.error ?? (waiting && st.authURL !== undefined && !link ? BAD_LOGIN : undefined), exitNodes: st.exitNodes ?? [], exitNode: st.exitNode ?? null, }); if (st.state === "running" && wasLogin) { wasLogin = false; KW.ui?.toast(`Tailscale: logged in${st.name ? ` as ${st.name}` : ""}`); } // Connected, but the exit node cannot be used: the guest's internet is blocked; said once (after 2 s, so a passing state is not). const v = ui$().get().tailscale; const key = v.state === "running" && exitBlocked(v) ? `${v.exitNode!.selected} ${v.exitNode!.reason ?? ""}` : ""; if (key !== blockedKey) { blockedKey = key; clearTimeout(blockedTimer); if (key) blockedTimer = setTimeout(() => { const now = ui$().get().tailscale; if (exitBlocked(now)) KW.ui?.toast(`Tailscale: exit node ${exitName(now)}: ${exitLine(now)}`, { action: "Exit node…", run: () => openExitSettings(), ms: 15000 }); }, 2000); } } /** Settings, Network, at the Tailscale section's exit node. */ export function openExitSettings(): void { openSection("network"); requestAnimationFrame(() => document.getElementById("opt-tsexit")?.scrollIntoView({ block: "nearest" })); } /** This load's node runs (or is starting): an exit node choice applies to it at once. */ const exitLive = (): boolean => { const st = ui$().get().tailscale.state; return !!client && !forgotten && st !== "stopped" && st !== "logged-out" && st !== "failed"; }; /** * Changes the running node's exit node ("": none) and saves the choice for * this load's login server (the top bar panel, Settings): from now on, and * at the next boot. Settings' field follows where it names the same server. */ export function setExitNode(choice: string): void { const c = choice.trim(); if (!client || !exitLive()) return; client.setExitNode(c || null); updateSaved((s) => { if (c) s.exitNodes[origin] = c; else delete s.exitNodes[origin]; }); if (tailscaleServerOrigin(ui$().get().options.tsserver) === origin) KW.ui?.setOption("tsexit", c); showStatus(client.status()); } /** * Settings' exit node chosen ("": none): applied at once (and saved) when * this load's node runs at the server chosen there, else kept in the * options for Reboot to save (rebootTailscale()). */ export function chooseExitNode(choice: string): void { const c = choice.trim(); const o = ui$().get().options; if (exitLive() && o.tailscale === "on" && tailscaleServerOrigin(o.tsserver) === origin) setExitNode(c); else KW.ui?.setOption("tsexit", c); } /** Whether the choice from Settings applies at once (exitLive() at the server chosen there), for its note. */ export const exitAppliesNow = (o: Options): boolean => exitLive() && o.tailscale === "on" && tailscaleServerOrigin(o.tsserver) === origin; /** An exit node as listed: its MagicDNS name's first label (an address as it is). */ export function exitShort(n: TailscaleExitNodeStatus): string { return /^\d+(\.\d+){3}$/.test(n.name) ? n.name : n.name.split(".")[0] || n.name; } /** What choosing a listed exit node saves: its MagicDNS name (its address when it has none). */ export const exitValue = (n: TailscaleExitNodeStatus): string => (/^\d+$/.test(n.name) && n.address ? n.address : n.name); /** The listed exit node a choice names (as the SDK finds it: the running choice's peer, else by address, name, its first label, host name), or undefined. */ export function exitCandidate(v: TailscaleView, choice: string): TailscaleExitNodeStatus | undefined { const c = choice.trim().toLowerCase().replace(/\.$/, ""); if (!c) return undefined; if (v.exitNode?.peer && v.exitNode.selected.trim().toLowerCase().replace(/\.$/, "") === c) return v.exitNodes.find((n) => n.id === v.exitNode!.peer!.id); return v.exitNodes.find((n) => n.address === c) ?? v.exitNodes.find((n) => n.name.toLowerCase() === c) ?? v.exitNodes.find((n) => n.name.toLowerCase().split(".")[0] === c) ?? v.exitNodes.find((n) => n.hostname.toLowerCase() === c); } /** A live node has an exit node chosen that it cannot use: the guest's internet traffic is refused (fail closed). */ export function exitBlocked(v: TailscaleView): boolean { return !!v.exitNode && !v.exitNode.usable && !["off", "blocked", "ask", "loading", "failed", "stopped", "logged-out"].includes(v.state); } /** The chosen exit node's name as listed (exitShort()), else the choice as typed; "" with none. */ export const exitName = (v: TailscaleView): string => (v.exitNode ? (v.exitNode.peer ? exitShort(v.exitNode.peer) : v.exitNode.selected) : ""); /** * The exit node's state, said plainly and without its name (Settings and the * panel show it next to the choice; exitName() for elsewhere), starting with * the state's word: in use, or why not and that internet traffic is blocked; * "" with none chosen. */ export function exitLine(v: TailscaleView): string { const x = v.exitNode; if (!x) return ""; if (x.usable) return `in use: internet traffic goes through it${x.peer?.address ? ` (${x.peer.address})` : ""}`; if (!exitBlocked(v)) return "not in use while the node does not run: the guest's internet goes through Wisp"; switch (x.reason) { case "offline": return "offline: internet traffic is blocked"; case "not found": return "no such device in the tailnet: internet traffic is blocked"; case "not an exit node": return "not an exit node (it does not offer itself, or that is not approved): internet traffic is blocked"; case "expired": return "its key has expired: internet traffic is blocked"; default: return "waiting for the connection: internet traffic is blocked until then"; } } /** Once the kernel runs (boot.ts): its node (vm.tailscale), for its status and Log out; or the URL's Tailscale settings to offer. */ export function attachTailscale(vm: KernelHandle, cfg: Config): void { if (cfg.tailscaleAsk) { KW.ui?.toast(`This link asks to turn on Tailscale with ${serverName(cfg.tailscaleAsk.server)}: off this boot`, { action: "Enable and reboot", run: () => void acceptTailscaleLink(), ms: 30000 }); return; } if (!cfg.tailscale || ui$().get().tailscale.state === "failed") return; client = vm.tailscale; if (!client) { set({ state: "failed", error: "the SDK started no Tailscale node" }); return; } showStatus(client.status()); } /** * "Enable and reboot" (the toast, Settings): asks, naming the login server, * then sets the Tailscale options to the URL's and reboots, which saves them. */ export async function acceptTailscaleLink(): Promise { const ask = cfgRef?.tailscaleAsk; const ui = KW.ui; if (!ask || !ui) return; if (!await ui.ask({ title: "tailscale", msg: `Turn on Tailscale with the login server ${serverName(ask.server)} and reboot? The guest joins the tailnet you log in to there, whose members and access rules can then reach the guest's servers. The running system and its unsaved state are lost.`, url: ask.server || undefined, ok: "Enable and reboot", danger: true, })) return; ui.setOption("tailscale", ask.settings.tailscale === "1" ? "on" : "off"); ui.setOption("tsserver", ask.settings.tsserver ?? ""); ui.setOption("tsserverkey", ask.settings.tsserverkey ?? ""); if (ask.settings.tshost !== undefined) ui.setOption("tshost", ask.settings.tshost); ui.reboot(); } /** Ignore the link's Tailscale settings (Settings): the prompt goes; this load stays on the saved settings. */ export function ignoreTailscaleLink(): void { const cfg = cfgRef; if (!cfg) return; set(cfg.tailscaleParam ? { state: "blocked", askServer: undefined, error: "the link's Tailscale settings were ignored; Reboot starts it with the saved ones" } : { state: "off", askServer: undefined }); KW.ui?.toastHide(); } /** What a TailscaleView's state says, as the status line starts. */ export function tailscaleLine(v: TailscaleView): string { switch (v.state) { case "off": return "Off this boot."; case "blocked": return `Off this boot: ${v.error ?? "it cannot start"}.`; case "ask": return `Off this boot: the page's link asks to turn on Tailscale with the login server ${v.askServer ?? "?"}. Joining a tailnet lets its members reach the guest's servers, so it is not applied without you.`; case "failed": return `Not started: ${v.error ?? "unknown error"}. The guest's network works without it.`; case "loading": case "idle": case "starting": case "connecting": return v.error && v.state !== "loading" ? `Cannot reach ${v.server} yet; trying again…` : `Connecting to ${v.server}…`; case "needs-login": return "Needs login: open the link and log in to add this device to your tailnet."; case "needs-machine-auth": return "Logged in; waiting for an admin to approve this device."; case "running": return "Connected."; case "stopped": return "Stopped."; case "logged-out": return "Logged out: this device's keys are forgotten. Reboot to log in again."; } } /** Once running: the facts Settings lists (no secrets; server-supplied strings, shown as text). The exit node is its control's. */ export function tailscaleFacts(v: TailscaleView): [string, string][] { if (v.state !== "running") return []; const tailnet = v.name.includes(".") ? v.name.slice(v.name.indexOf(".") + 1) : ""; return ([ ["Name", v.name], ["Address", v.addresses.join(", ")], ["Tailnet", tailnet], ["Peers", `${v.peers} (${v.online} online)`], ["Home relay", v.relay], ["Login server", v.server], ] as [string, string][]).filter(([, x]) => x); } /** The state in a word or two (the panel's pill, Settings' status); an exit node it cannot use is the caller's to add. */ export function tailscaleWord(v: TailscaleView): string { return ({ running: "Connected", "needs-login": "Needs login", "needs-machine-auth": "Waiting for approval", ask: "Link asks to enable", failed: "Not started", blocked: "Off this boot", off: "Off", stopped: "Stopped", "logged-out": "Logged out", } as Partial>)[v.state] ?? (tailscaleKind(v) === "error" ? "Cannot reach server" : "Connecting"); } /** * What of Settings' Tailscale options differs from this boot's and so waits * for a reboot, as Settings names it ([]: nothing): turning it on or off, the * login server, its key, the host name, a typed auth key, and an exit node * that could not be applied at once (exitPending()). */ export function tailscalePending(o: Options): string[] { const cfg = cfgRef; if (!cfg) return []; const out: string[] = []; if ((o.tailscale === "on") !== cfg.tailscaleParam) out.push(o.tailscale === "on" ? "Tailscale on" : "Tailscale off"); if (o.tsserver.trim().replace(/\/+$/, "") !== cfg.tsServer) out.push("login server"); if (o.tsserverkey.trim() !== cfg.tsServerKey) out.push("login server key"); if (o.tshost.trim() !== cfg.tsHost) out.push("host name"); if (o.tsauthkey.trim()) out.push("auth key"); if (exitPending(o)) out.push("exit node"); return out; } /** * How the top bar's item draws a state (applets/Network.tsx NetworkItem): "ok" * connected; "pending" starting or connecting; "attention" needs login, * waiting for approval, a link asks to turn it on, or connected with an * exit node it cannot use (internet blocked); "error" not started or * cannot reach its login server; "off" off this boot, stopped, logged out. */ export type TailscaleKind = "ok" | "pending" | "attention" | "error" | "off"; export function tailscaleKind(v: TailscaleView): TailscaleKind { switch (v.state) { case "running": return exitBlocked(v) ? "attention" : "ok"; case "needs-login": case "needs-machine-auth": case "ask": return "attention"; case "failed": return "error"; case "loading": case "idle": case "starting": case "connecting": return v.error && v.state !== "loading" ? "error" : "pending"; default: return "off"; } } /** The item's short state, for its tooltip and accessible name. */ export function tailscaleShort(v: TailscaleView): string { switch (v.state) { case "running": return exitBlocked(v) ? `connected; exit node ${exitName(v)}: ${exitLine(v)}` : `connected${v.addresses[0] ? `, ${v.addresses[0]}` : ""}${v.exitNode?.usable ? `, exit node ${exitName(v)}` : ""}`; case "needs-login": return "needs login"; case "needs-machine-auth": return "waiting for approval"; case "ask": return `a link asks to turn it on (${v.askServer ?? "?"})`; case "failed": return "not started"; case "blocked": case "off": return "off this boot"; case "stopped": return "stopped"; case "logged-out": return "logged out"; default: return tailscaleKind(v) === "error" ? `cannot reach ${v.server}` : "connecting"; } } /** The Environment row (boot.ts): what the node is doing, for System and Copy diagnostics (no secrets). */ export function tailscaleCheck(v: TailscaleView): { r: "pass" | "warn" | "info" | "fail"; value: string; note: string } { const where = `login server ${v.server}`; switch (v.state) { case "running": return { r: exitBlocked(v) ? "warn" : "pass", value: `${v.addresses[0] ?? "running"}`, note: `${v.name}; home relay ${v.relay || "?"}; ${v.peers} peers (${v.online} online)${v.exitNode ? `; exit node ${v.exitNode.selected}: ${v.exitNode.usable ? "in use" : `not usable (${v.exitNode.reason ?? "?"}), internet traffic blocked`}` : ""}; ${where}`, }; case "failed": return { r: "fail", value: "not started", note: v.error ?? "" }; case "blocked": return { r: "warn", value: "off this boot", note: v.error ?? "" }; case "ask": return { r: "warn", value: "off this boot", note: `the page's URL asks to turn it on with login server ${v.askServer ?? "?"}; not applied without the user (Settings, Network)` }; case "needs-login": return { r: "info", value: "needs login", note: `the link is in Settings, Network; ${where}` }; case "needs-machine-auth": return { r: "info", value: "waiting for approval", note: `an admin must approve this device; ${where}` }; default: return { r: v.error ? "warn" : "info", value: v.state, note: `${where}${v.error ? `; ${v.error}` : ""}` }; } } /** * Log out (Settings): asks, then expires the node key at the login server * where the node is logged in (logout()), or just stops it, and clears that * server's saved node and auth key. Without a node this load, forgets the * one saved for the saved settings' server. */ export async function forgetDevice(): Promise { const ui = KW.ui!; const st = client?.status().state; const live = !!client && st !== "stopped" && st !== "logged-out"; const loggedIn = live && (st === "running" || st === "connecting" || st === "needs-machine-auth"); if (!await ui.ask({ title: "tailscale", msg: loggedIn ? "Log out of the tailnet and forget this device's Tailscale keys? The guest loses its tailnet addresses until you reboot and log in again." : `Forget this device's saved Tailscale keys for ${ui$().get().tailscale.server}? ${live ? "This boot's node stops; the" : "The"} next boot with Tailscale logs in as a new device.`, ok: loggedIn ? "Log out" : "Forget", danger: true, })) return; forgotten = true; let why = ""; if (live) { try { if (loggedIn) await Promise.race([client!.logout(), new Promise((_, no) => setTimeout(() => no(new Error("no answer in 10 s")), 10000))]); else await client!.close(); } catch (e) { why = (e as Error)?.message ?? String(e); await client!.close().catch(() => {}); } } updateSaved((s) => { delete s.nodes[origin]; if (s.authKey?.server === origin) delete s.authKey; }); set({ saved: false, authURL: undefined, ...(live ? { state: "logged-out", name: "", addresses: [], relay: "", peers: 0, online: 0, devices: [], exitNodes: [], exitNode: null } : {}) }); ui.toast(why ? `Forgotten in this browser, but the login server was not told (${why}): remove the device in its admin console` : loggedIn ? "Logged out of Tailscale: this device's keys are forgotten" : "This device's Tailscale keys are forgotten"); }