feat(webui): complete remote pairing and connection recovery

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent 11889c018e
commit 192ca6e49e
52 files changed
+7313 -675

No files matched your search

+42 -1
View File
@@ -11,6 +11,17 @@ export interface RemoteProfile {
config_path: string;
runtime_user: string;
connected: boolean;
gateway_id?: string;
view_id?: string;
connection_error?: string;
paired?: boolean;
revoke_command?: string;
authorized_until?: number;
}
/** Persistent setup problems need a repair path, not an endless Retry button. */
export function needsRemoteSetup(code: string): boolean {
return /^(pair_|host_key_|ssh_auth_failed$|ssh_agent_refused$|ssh_key_permissions$|ssh_config_|local_file_not_found$|remote_auth_failed$|incompatible_gateway$|webui_disabled$|profile_not_found$)/.test(code);
}
export interface RemoteDirectory {
@@ -32,9 +43,22 @@ export interface RemoteConnection {
hostname: string;
config_path: string;
gateway_id: string;
view_id?: string;
url: string;
}
export interface RemoteLocation {
config_path: string;
runtime_user: string;
service: string;
}
export interface RemoteInspection {
hostname: string;
candidates: RemoteLocation[];
incomplete: boolean;
}
export async function readRemoteInstances(token: string): Promise<RemoteDirectory> {
const response = await fetchWithTimeout("/api/remote-instances", {
headers: { Authorization: `Bearer ${token}` },
@@ -47,7 +71,7 @@ export async function readRemoteInstances(token: string): Promise<RemoteDirector
export function remoteAction<T>(
client: WebUIMutationTransport, action: string, payload: Record<string, unknown>,
): Promise<T> {
return client.requestMutation<T>(`remote.${action}`, payload, 65_000);
return client.requestMutation<T>(`remote.${action}`, payload, action === "pick_file" ? 310_000 : 65_000);
}
/** Never let a server response navigate the shell to an arbitrary origin. */
@@ -62,6 +86,23 @@ export function validateRemoteConnection(connection: RemoteConnection): RemoteCo
export type SelectedRemote = Pick<RemoteConnection, "id" | "name" | "hostname">;
const SELECTED_REMOTE = "nanobot.remote-instance";
const RECENT_REMOTES = "nanobot.recent-remote-instances";
/** Only profile IDs are persisted, never connection URLs or credentials. */
export function readRecentRemotes(): string[] {
try {
const value: unknown = JSON.parse(window.localStorage.getItem(RECENT_REMOTES) || "[]");
return Array.isArray(value) ? [...new Set(value.filter((id): id is string =>
typeof id === "string" && /^[a-f0-9-]{36}$/.test(id)))].slice(0, 20) : [];
} catch { return []; }
}
export function rememberRecentRemote(id: string, previous: string[]): string[] {
const next = [id, ...previous.filter((item) => item !== id)].slice(0, 20);
try { window.localStorage.setItem(RECENT_REMOTES, JSON.stringify(next)); }
catch { /* Switching still works when browser storage is disabled. */ }
return next;
}
export function readSelectedRemote(): SelectedRemote | null {
try {
+51
View File
@@ -0,0 +1,51 @@
/** One-shot handoff from a trusted server console, held in memory, never storage. */
export interface PairReturn { id: string; code: string }
let pending: PairReturn | null = null;
const listeners = new Set<() => void>();
export function parsePairReturn(hash: string): PairReturn | null {
const [path, query = ""] = hash.split("?", 2);
if (path !== "#/remote") return null;
const params = new URLSearchParams(query);
if (!params.has("pairing")) return null;
const invalid = { id: "", code: "" };
const code = params.get("pairing") || "";
if (params.getAll("pairing").length !== 1 || code.length > 32768 || !/^nbpc1\.[A-Za-z0-9_-]+$/.test(code)) return invalid;
try {
const encoded = code.slice(6).replace(/-/g, "+").replace(/_/g, "/");
const envelope: unknown = JSON.parse(atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, "=")));
if (!envelope || typeof envelope !== "object" || !("id" in envelope)
|| typeof envelope.id !== "string" || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(envelope.id)) return invalid;
// The backend must decrypt and validate this. A parsed ID grants no access.
return { id: envelope.id, code };
} catch { return invalid; }
}
export function initializePairReturn(): void {
const returned = parsePairReturn(window.location.hash);
if (!returned) return;
window.history.replaceState(null, "", `${window.location.pathname}${window.location.search}#/remote`);
// A remote iframe must never become a local connection controller.
if (window.top === window && window.location.protocol === "http:"
&& ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname)) {
pending = returned;
listeners.forEach((listener) => listener());
}
}
export function readPairReturn(): PairReturn | null { return pending; }
export function subscribePairReturn(listener: () => void): () => void {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
export function clearPairReturn(): void {
pending = null;
listeners.forEach((listener) => listener());
}
export function pairingReturnOrigin(): string {
return window.top === window && window.location.protocol === "http:"
&& ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname)
? window.location.origin : "";
}
+60
View File
@@ -0,0 +1,60 @@
/** Import connection fields, never execute a pasted command or shell syntax. */
export interface SSHAddress {
host: string;
port?: number;
identity_file?: string;
ssh_config?: string;
}
export function parseSSHAddress(input: string): SSHAddress {
const text = input.trim();
const invalid = () => new Error("invalid_ssh_command");
const validHost = (host: string) => /^[a-zA-Z0-9][a-zA-Z0-9._:@-]{0,252}$/.test(host);
if (!/^ssh\s/.test(text)) {
if (!validHost(text)) throw invalid();
return { host: text };
}
// A deliberately small grammar: quoted paths (including Windows paths),
// a destination and -p/-i/-F/-l. No expansions, remote commands or flags
// that change trust, forwarding, or execute a local ProxyCommand.
if (/[;$`|&<>]/.test(text) || [...text].some((char) => char.charCodeAt(0) < 32 && char !== "\t")) throw invalid();
const token = /\s*(?:"([^"]*)"|'([^']*)'|([^\s"']+))(?:\s+|$)/gy;
const words: string[] = [];
while (token.lastIndex < text.length) {
const match = token.exec(text);
if (!match) throw invalid();
words.push(match[1] ?? match[2] ?? match[3]);
}
words.shift(); // ssh
const result: SSHAddress = { host: "" };
const seen = new Set<string>();
let user = "";
for (let index = 0; index < words.length; index++) {
const word = words[index];
if (!word.startsWith("-")) {
if (result.host || !validHost(word)) throw invalid();
result.host = word;
continue;
}
// Options after the destination are a remote command in ssh, not options.
if (result.host) throw invalid();
const flag = word.slice(0, 2);
if (!["-p", "-i", "-F", "-l"].includes(flag) || seen.has(flag)) throw invalid();
seen.add(flag);
const value = word.length > 2 ? word.slice(2) : words[++index];
if (!value || value.startsWith("-") || value.length > 2048) throw invalid();
if (flag === "-p") {
if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw invalid();
result.port = Number(value);
} else if (flag === "-i") result.identity_file = value;
else if (flag === "-F") result.ssh_config = value;
else {
if (!/^[a-zA-Z0-9_][a-zA-Z0-9._-]*$/.test(value)) throw invalid();
user = value;
}
}
if (!result.host || (user && result.host.includes("@"))) throw invalid();
if (user) result.host = `${user}@${result.host}`;
if (!validHost(result.host)) throw invalid();
return result;
}