From 6d49c6a46d50d5b827cccba8165f359200823d25 Mon Sep 17 00:00:00 2001 From: 0721-art Date: Fri, 20 Nov 2026 12:34:47 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(directory-picker):=20add=20a=20Browse?= =?UTF-8?q?=E2=80=A6=20button=20that=20opens=20the=20OS=20folder=20dialog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dialog runs on the machine that serves the page, so /api/cwd/pick only answers a loopback request for the local host; /api/cwd/picker decides whether the button is offered at all. Windows uses the WinForms FolderBrowserDialog, macOS osascript, Linux zenity. Refs #540 --- app/api/cwd/pick/route.ts | 21 +++++++++++++ app/api/cwd/picker/route.ts | 9 ++++++ components/DirectoryPicker.tsx | 48 ++++++++++++++++++++++++++++- lib/cwd-picker.test.mjs | 19 ++++++++++++ lib/cwd-picker.ts | 56 ++++++++++++++++++++++++++++++++++ lib/i18n/locales/en.json | 1 + lib/i18n/locales/ja.json | 1 + lib/i18n/locales/zh-CN.json | 1 + lib/i18n/locales/zh-TW.json | 1 + server/routes.ts | 4 +++ 10 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 app/api/cwd/pick/route.ts create mode 100644 app/api/cwd/picker/route.ts create mode 100644 lib/cwd-picker.test.mjs create mode 100644 lib/cwd-picker.ts diff --git a/app/api/cwd/pick/route.ts b/app/api/cwd/pick/route.ts new file mode 100644 index 000000000..52b699c0c --- /dev/null +++ b/app/api/cwd/pick/route.ts @@ -0,0 +1,21 @@ +import { apiErrorResponse } from "@/lib/api-utils"; +import { pickDirectory } from "@/lib/cwd-picker"; +import { isLoopbackHost } from "@/lib/hosts/host-login"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; + +// POST /api/cwd/pick body: { hostId?: string } → { path } | { cancelled: true } +// Opens the OS folder dialog on this machine. A page opened from another machine has no desktop +// here, and another host's paths do not exist here either, so both cases are refused. +export async function POST(req: Request) { + try { + const body = await req.json().catch(() => ({})) as { hostId?: unknown }; + const hostId = typeof body.hostId === "string" && body.hostId ? body.hostId : LOCAL_HOST_ID; + const picked = hostId === LOCAL_HOST_ID && isLoopbackHost(new URL(req.url).hostname) ? await pickDirectory() : null; + if (!picked) { + return Response.json({ error: "The folder dialog is only available on this machine", code: "picker_unavailable" }, { status: 501 }); + } + return Response.json(picked); + } catch (error) { + return apiErrorResponse(error); + } +} diff --git a/app/api/cwd/picker/route.ts b/app/api/cwd/picker/route.ts new file mode 100644 index 000000000..c52736d34 --- /dev/null +++ b/app/api/cwd/picker/route.ts @@ -0,0 +1,9 @@ +import { pickerCommand } from "@/lib/cwd-picker"; +import { isLoopbackHost } from "@/lib/hosts/host-login"; + +// GET /api/cwd/picker → { available } — may this page open the server machine's folder dialog? +// Only a page opened on the machine itself: a remote browser has no desktop here. +export function GET(request: Request) { + const loopback = isLoopbackHost(new URL(request.url).hostname); + return Response.json({ available: loopback && pickerCommand() !== null }); +} diff --git a/components/DirectoryPicker.tsx b/components/DirectoryPicker.tsx index f15f3ad22..47c9c42fc 100644 --- a/components/DirectoryPicker.tsx +++ b/components/DirectoryPicker.tsx @@ -8,6 +8,7 @@ import { useI18n } from "@/lib/i18n"; import { formatApiError } from "@/lib/i18n/api-error"; import { appendProgress, cloneDirectoryName } from "@/lib/git-clone"; import { randomUUID as newCloneId } from "@/lib/random-uuid"; +import { LOCAL_HOST_ID } from "@/lib/project-ordering"; interface DirectoryEntry { name: string; @@ -74,6 +75,8 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, const [directories, setDirectories] = useState([]); const [drives, setDrives] = useState(null); const [loadError, setLoadError] = useState(null); + const [nativePickerAvailable, setNativePickerAvailable] = useState(false); + const [nativePickerBusy, setNativePickerBusy] = useState(false); const [profile, setProfile] = useState(""); const [advisor, setAdvisor] = useState(false); const [extraArgs, setExtraArgs] = useState(""); @@ -87,7 +90,7 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, const cloneLogRef = useRef(null); const browseAbortRef = useRef(null); const cloning = cloneId !== null; - const locked = busy || cloning; + const locked = busy || cloning || nativePickerBusy; const dialogRef = useModalDialog({ onClose: () => { if (!locked) onCancel(); }, active: portalTarget !== null, @@ -122,6 +125,35 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, return () => browseAbortRef.current?.abort(); }, [navigateTo]); + // The OS folder dialog runs on the server's desktop, so it is offered only for this machine. + useEffect(() => { + if (pool || host.id !== LOCAL_HOST_ID) return; + let active = true; + void fetch("/api/cwd/picker") + .then(async (response) => (await response.json()) as { available?: boolean }) + .then((data) => { if (active) setNativePickerAvailable(Boolean(data.available)); }) + .catch(() => {}); + return () => { active = false; }; + }, [host.id, pool]); + + const pickNativeDirectory = async () => { + if (locked) return; + setNativePickerBusy(true); + setLoadError(null); + try { + const response = await fetch("/api/cwd/pick", { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ hostId: host.id }), + }); + const data = await response.json() as { path?: string; error?: string; code?: string }; + if (!response.ok || data.error) throw new Error(formatApiError({ ...data, error: data.error ?? `HTTP ${response.status}` })); + if (data.path) await navigateTo(data.path); + } catch (cause) { + setLoadError(cause instanceof Error ? cause.message : String(cause)); + } finally { + setNativePickerBusy(false); + } + }; + useEffect(() => () => { cloneAbortRef.current?.abort(); cloneAbortRef.current = null; }, []); useEffect(() => { @@ -302,6 +334,20 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, > {t("directoryPicker.go")} + {nativePickerAvailable && !pool && ( + + )}
diff --git a/lib/cwd-picker.test.mjs b/lib/cwd-picker.test.mjs new file mode 100644 index 000000000..d525341d2 --- /dev/null +++ b/lib/cwd-picker.test.mjs @@ -0,0 +1,19 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const { pickDirectory, pickerCommand } = await import("./cwd-picker.ts"); + +test("every desktop platform gets a folder dialog, anything else gets none", () => { + const win = pickerCommand("win32"); + assert.equal(win?.file, "powershell.exe"); + assert.ok(win?.args.includes("-STA")); + assert.ok(win?.args.some((arg) => arg.includes("System.Windows.Forms.FolderBrowserDialog"))); + assert.ok(win?.args.some((arg) => arg.includes("[Console]::Out.Write"))); + assert.equal(pickerCommand("darwin")?.file, "osascript"); + assert.deepEqual(pickerCommand("linux")?.args.slice(0, 2), ["--file-selection", "--directory"]); + assert.equal(pickerCommand("freebsd"), null); +}); + +test("no chooser means no dialog and no error", async () => { + assert.equal(await pickDirectory("freebsd"), null); +}); diff --git a/lib/cwd-picker.ts b/lib/cwd-picker.ts new file mode 100644 index 000000000..86ed55d06 --- /dev/null +++ b/lib/cwd-picker.ts @@ -0,0 +1,56 @@ +// The OS folder dialog for the machine running the server. Only meaningful when the page is +// opened on that same desktop, so the /api/cwd routes gate on a loopback request. +import { spawn } from "node:child_process"; + +export type PickedDirectory = { path: string } | { cancelled: true }; + +const DIALOG_TIMEOUT_MS = 5 * 60 * 1000; + +/** The folder-dialog command for this platform, or null where we know no chooser. */ +export function pickerCommand(platform: NodeJS.Platform = process.platform): { file: string; args: string[] } | null { + if (platform === "win32") { + // ponytail: the classic WinForms dialog, not IFileOpenDialog — it works from a non-console + // parent without COM plumbing; swap in the Vista-style picker if the look ever matters. + return { + file: "powershell.exe", + args: [ + "-NoProfile", + "-STA", + "-Command", + [ + "Add-Type -AssemblyName System.Windows.Forms | Out-Null", + "$d = New-Object System.Windows.Forms.FolderBrowserDialog", + "$d.Description = 'Select a folder'", + "$d.SelectedPath = $env:USERPROFILE", + "if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($d.SelectedPath) }", + ].join("; "), + ], + }; + } + if (platform === "darwin") return { file: "osascript", args: ["-e", 'POSIX path of (choose folder with prompt "Select a folder")'] }; + if (platform === "linux") return { file: "zenity", args: ["--file-selection", "--directory", "--title", "Select a folder"] }; + return null; +} + +/** Opens the dialog and waits for it; null when this platform has no chooser. */ +export function pickDirectory(platform: NodeJS.Platform = process.platform): Promise { + const command = pickerCommand(platform); + if (!command) return Promise.resolve(null); + return new Promise((resolve, reject) => { + const child = spawn(command.file, command.args, { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + const timer = setTimeout(() => child.kill(), DIALOG_TIMEOUT_MS); + child.stdout.setEncoding("utf8").on("data", (chunk: string) => { stdout += chunk; }); + child.stderr.setEncoding("utf8").on("data", (chunk: string) => { stderr += chunk; }); + child.on("error", (cause) => { clearTimeout(timer); reject(cause); }); + child.on("close", (code) => { + clearTimeout(timer); + const path = stdout.trim(); + if (path) return resolve({ path }); + // Dismissed: zenity and osascript exit 1, the Windows dialog still exits 0 with no output. + if (code === 0 || code === 1) return resolve({ cancelled: true }); + reject(new Error(stderr.trim() || `The folder dialog exited with code ${code}`)); + }); + }); +} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 7013dc26b..4b5056479 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -669,6 +669,7 @@ "subagentTranscript.completionTruncated": "Output truncated", "codeBlock.copied": "copied", "codeBlock.copy": "copy", + "directoryPicker.browse": "Browse…", "directoryPicker.cancel": "Cancel", "directoryPicker.checking": "Checking…", "directoryPicker.close": "Close", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 93da3edf9..ab50953bc 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -653,6 +653,7 @@ "subagentTranscript.completionTruncated": "出力は切り捨てられました", "codeBlock.copied": "コピーしました", "codeBlock.copy": "コピー", + "directoryPicker.browse": "参照…", "directoryPicker.cancel": "キャンセル", "directoryPicker.checking": "確認中…", "directoryPicker.close": "閉じる", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index cf8d7e4fe..8f523f04f 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -653,6 +653,7 @@ "subagentTranscript.completionTruncated": "输出已被截断", "codeBlock.copied": "已复制", "codeBlock.copy": "复制", + "directoryPicker.browse": "浏览…", "directoryPicker.cancel": "取消", "directoryPicker.checking": "检查中…", "directoryPicker.close": "关闭", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 8ae164ba8..c29b24ad1 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -669,6 +669,7 @@ "subagentTranscript.completionTruncated": "輸出已截斷", "codeBlock.copied": "已複製", "codeBlock.copy": "複製", + "directoryPicker.browse": "瀏覽…", "directoryPicker.cancel": "取消", "directoryPicker.checking": "檢查中…", "directoryPicker.close": "關閉", diff --git a/server/routes.ts b/server/routes.ts index d6cfea353..f26703c0e 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -12,6 +12,8 @@ import * as authApiKeyProvider from "@/app/api/auth/api-key/[provider]/route"; import * as authLoginProvider from "@/app/api/auth/login/[provider]/route"; import * as authProviders from "@/app/api/auth/providers/route"; import * as cwdBrowse from "@/app/api/cwd/browse/route"; +import * as cwdPick from "@/app/api/cwd/pick/route"; +import * as cwdPicker from "@/app/api/cwd/picker/route"; import * as cwdValidate from "@/app/api/cwd/validate/route"; import * as defaultCwd from "@/app/api/default-cwd/route"; import * as events from "@/app/api/events/route"; @@ -115,6 +117,8 @@ export const ROUTE_MODULES: Record = { "auth/login/[provider]": authLoginProvider, "auth/providers": authProviders, "cwd/browse": cwdBrowse, + "cwd/pick": cwdPick, + "cwd/picker": cwdPicker, "cwd/validate": cwdValidate, "default-cwd": defaultCwd, "events": events, From f7f4bb15a13b564d67cf3b46f1ad913aebdc48e2 Mon Sep 17 00:00:00 2001 From: 0721-art Date: Fri, 20 Nov 2026 12:59:47 +0800 Subject: [PATCH 2/3] fix(cwd-picker): gate the dialog on the peer address, not on the Host header `request.url`'s host comes from the client's Host header, so a remote client could ask for the folder dialog by sending `Host: localhost`. Handle() now reads the accepted socket (server.requestIP) and passes `localPeer` into the route context; the pick routes gate on that and keep answering 501 otherwise. Also from review: report the picker as available only when its binary exists (zenity can be missing on Linux), and keep leading or trailing spaces in the chosen path by stripping only the chooser's line terminator. --- app/api/cwd/pick/route.ts | 7 +++---- app/api/cwd/picker/route.ts | 12 ++++++------ lib/cwd-picker.test.mjs | 16 ++++++++++++++-- lib/cwd-picker.ts | 20 +++++++++++++++++--- lib/hosts/host-login.test.mjs | 11 ++++++++++- lib/hosts/host-login.ts | 3 ++- server/app.ts | 12 +++++++++--- server/routes.ts | 6 ++++-- 8 files changed, 65 insertions(+), 22 deletions(-) diff --git a/app/api/cwd/pick/route.ts b/app/api/cwd/pick/route.ts index 52b699c0c..9a2db36d2 100644 --- a/app/api/cwd/pick/route.ts +++ b/app/api/cwd/pick/route.ts @@ -1,16 +1,15 @@ import { apiErrorResponse } from "@/lib/api-utils"; -import { pickDirectory } from "@/lib/cwd-picker"; -import { isLoopbackHost } from "@/lib/hosts/host-login"; +import { pickDirectory, pickerAvailable } from "@/lib/cwd-picker"; import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; // POST /api/cwd/pick body: { hostId?: string } → { path } | { cancelled: true } // Opens the OS folder dialog on this machine. A page opened from another machine has no desktop // here, and another host's paths do not exist here either, so both cases are refused. -export async function POST(req: Request) { +export async function POST(req: Request, context: { localPeer: boolean }) { try { const body = await req.json().catch(() => ({})) as { hostId?: unknown }; const hostId = typeof body.hostId === "string" && body.hostId ? body.hostId : LOCAL_HOST_ID; - const picked = hostId === LOCAL_HOST_ID && isLoopbackHost(new URL(req.url).hostname) ? await pickDirectory() : null; + const picked = hostId === LOCAL_HOST_ID && pickerAvailable(context.localPeer) ? await pickDirectory() : null; if (!picked) { return Response.json({ error: "The folder dialog is only available on this machine", code: "picker_unavailable" }, { status: 501 }); } diff --git a/app/api/cwd/picker/route.ts b/app/api/cwd/picker/route.ts index c52736d34..cec556278 100644 --- a/app/api/cwd/picker/route.ts +++ b/app/api/cwd/picker/route.ts @@ -1,9 +1,9 @@ -import { pickerCommand } from "@/lib/cwd-picker"; -import { isLoopbackHost } from "@/lib/hosts/host-login"; +import { pickerAvailable } from "@/lib/cwd-picker"; // GET /api/cwd/picker → { available } — may this page open the server machine's folder dialog? -// Only a page opened on the machine itself: a remote browser has no desktop here. -export function GET(request: Request) { - const loopback = isLoopbackHost(new URL(request.url).hostname); - return Response.json({ available: loopback && pickerCommand() !== null }); +// Only a page opened on the machine itself: a remote browser has no desktop here. Locality is the +// connection's peer address from the server (context.localPeer), never request.url's host, which the +// client writes through its Host header. +export function GET(_request: Request, context: { localPeer: boolean }) { + return Response.json({ available: pickerAvailable(context.localPeer) }); } diff --git a/lib/cwd-picker.test.mjs b/lib/cwd-picker.test.mjs index d525341d2..118a3fc58 100644 --- a/lib/cwd-picker.test.mjs +++ b/lib/cwd-picker.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -const { pickDirectory, pickerCommand } = await import("./cwd-picker.ts"); +const { hasPicker, pickDirectory, pickerAvailable, pickerCommand } = await import("./cwd-picker.ts"); test("every desktop platform gets a folder dialog, anything else gets none", () => { const win = pickerCommand("win32"); @@ -14,6 +14,18 @@ test("every desktop platform gets a folder dialog, anything else gets none", () assert.equal(pickerCommand("freebsd"), null); }); -test("no chooser means no dialog and no error", async () => { +test("no chooser means no dialog and no error, and no Browse button either", async () => { assert.equal(await pickDirectory("freebsd"), null); + assert.equal(hasPicker("freebsd"), false); + // Windows and macOS ship their chooser; Linux is the only platform whose binary can be missing. + assert.equal(hasPicker("win32"), true); + assert.equal(hasPicker("darwin"), true); +}); + +test("a connection from another machine never gets the dialog, whatever its Host header said", () => { + // context.localPeer comes from the accepted socket, so a remote client cannot reach the dialog. + assert.equal(pickerAvailable(false, "win32"), false); + assert.equal(pickerAvailable(false, "darwin"), false); + assert.equal(pickerAvailable(true, "win32"), true); + assert.equal(pickerAvailable(true, "freebsd"), false); }); diff --git a/lib/cwd-picker.ts b/lib/cwd-picker.ts index 86ed55d06..5dbb26880 100644 --- a/lib/cwd-picker.ts +++ b/lib/cwd-picker.ts @@ -1,6 +1,6 @@ // The OS folder dialog for the machine running the server. Only meaningful when the page is -// opened on that same desktop, so the /api/cwd routes gate on a loopback request. -import { spawn } from "node:child_process"; +// opened on that same desktop, so the /api/cwd routes gate on the connection's peer address. +import { spawn, spawnSync } from "node:child_process"; export type PickedDirectory = { path: string } | { cancelled: true }; @@ -32,6 +32,19 @@ export function pickerCommand(platform: NodeJS.Platform = process.platform): { f return null; } +/** Whether this platform's chooser is installed: Windows and macOS ship theirs, Linux needs zenity. */ +export function hasPicker(platform: NodeJS.Platform = process.platform): boolean { + const command = pickerCommand(platform); + if (!command) return false; + if (platform !== "linux") return true; + return spawnSync("which", [command.file], { stdio: "ignore" }).status === 0; +} + +/** Both the Browse button and the pick request need this: a chooser on the machine the browser is on. */ +export function pickerAvailable(localPeer: boolean, platform: NodeJS.Platform = process.platform): boolean { + return localPeer && hasPicker(platform); +} + /** Opens the dialog and waits for it; null when this platform has no chooser. */ export function pickDirectory(platform: NodeJS.Platform = process.platform): Promise { const command = pickerCommand(platform); @@ -46,7 +59,8 @@ export function pickDirectory(platform: NodeJS.Platform = process.platform): Pro child.on("error", (cause) => { clearTimeout(timer); reject(cause); }); child.on("close", (code) => { clearTimeout(timer); - const path = stdout.trim(); + // Only the chooser's own line terminator: a directory name may end in a space. + const path = stdout.replace(/[\r\n]+$/, ""); if (path) return resolve({ path }); // Dismissed: zenity and osascript exit 1, the Windows dialog still exits 0 with no output. if (code === 0 || code === 1) return resolve({ cancelled: true }); diff --git a/lib/hosts/host-login.test.mjs b/lib/hosts/host-login.test.mjs index b06dcfaed..a8d7a5324 100644 --- a/lib/hosts/host-login.test.mjs +++ b/lib/hosts/host-login.test.mjs @@ -16,7 +16,7 @@ const lock = `${file}.lock`; const primary = { url: "https://production.example", token: "production-token" }; const staging = { url: "http://127.0.0.1:40000", token: "staging-token" }; const other = { url: "https://other.example", token: "other-token" }; -const { addHostLink, loginHost, readHostLinks, readHostLogin, removeHostLink } = await import("./host-login.ts"); +const { addHostLink, isLoopbackHost, loginHost, readHostLinks, readHostLogin, removeHostLink } = await import("./host-login.ts"); const saved = () => JSON.parse(readFileSync(file, "utf8")); const seed = (value) => writeFileSync(file, JSON.stringify(value)); beforeEach(() => { @@ -209,3 +209,12 @@ test("legacy login and concurrent add retain the additional entry", { timeout: 2 assert.deepEqual(readHostLogin(), other); assert.deepEqual(new Map(readHostLinks().map((link) => [link.url, link.token])), new Map([staging, other].map((link) => [link.url, link.token]))); }); + +test("a socket address is loopback only for this machine, IPv4-mapped included", () => { + for (const address of ["127.0.0.1", "127.8.9.10", "::1", "[::1]", "::ffff:127.0.0.1", "localhost"]) { + assert.equal(isLoopbackHost(address), true, address); + } + for (const address of ["10.0.0.5", "::ffff:10.0.0.5", "192.168.1.20", "", "fe80::1"]) { + assert.equal(isLoopbackHost(address), false, address); + } +}); diff --git a/lib/hosts/host-login.ts b/lib/hosts/host-login.ts index cf905b57d..08d22f4aa 100644 --- a/lib/hosts/host-login.ts +++ b/lib/hosts/host-login.ts @@ -15,7 +15,8 @@ export type HostLink = { url: string; token: string }; type SavedLink = HostLink & Record; type HostConfig = Record & { url?: string; token?: string; links?: SavedLink[] }; -export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname); +/** A loopback name or address, including the IPv4-mapped form a dual-stack socket reports. */ +export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "::1" || hostname === "[::1]" || /^(::ffff:)?127(\.\d{1,3}){3}$/i.test(hostname); /** Existing configuration must never be confused with a first login. */ export class HostLoginUnreadableError extends Error { diff --git a/server/app.ts b/server/app.ts index 5b87e2c65..f04d7537e 100644 --- a/server/app.ts +++ b/server/app.ts @@ -2,6 +2,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { parseArgs } from "node:util"; import { browserLink, type BrowserLinkData } from "@/lib/browser-link"; +import { isLoopbackHost } from "@/lib/hosts/host-login"; import { hostLinkSocket, type LinkSocketData } from "@/lib/hosts/hub"; import { maintenanceSocket, type MaintenanceSocketData } from "@/lib/hosts/maintenance-hub"; import { proxy } from "@/proxy"; @@ -56,7 +57,7 @@ function decodable(pathname: string): boolean { async function handle( request: Request, server: Bun.Server, - respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void }) => Response | undefined | Promise, + respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void; localPeer: boolean }) => Response | undefined | Promise, ): Promise { let pathname: string; try { @@ -67,6 +68,10 @@ async function handle( } const gate = proxy(request); if (gate instanceof Response) return finalizeResponse(request, gate); + // Locality for routes that act on this desktop: the accepted socket, never request.url's host, which the + // client writes through its Host header. + const address = server.requestIP(request)?.address; + const localPeer = address !== undefined && isLoopbackHost(address); if (!decodable(pathname)) return finalizeResponse(request, text("Bad Request", 400)); const lifted = gate === "authenticated" && pathname.startsWith("/api/"); if (lifted) server.timeout(request, 0); @@ -76,6 +81,7 @@ async function handle( try { response = await respond({ gate, + localPeer, disableIdleTimeout: () => { keepOpen = true; server.timeout(request, 0); @@ -133,7 +139,7 @@ export function startServer(options: { port: number; hostname: string; dev: bool for (const [key, mod] of Object.entries(ROUTE_MODULES)) { const { pattern, rest } = routePattern(key); const matcher = new URLPattern({ pathname: pattern }); - routes[pattern] = (request, server) => handle(request, server, ({ disableIdleTimeout }) => { + routes[pattern] = (request, server) => handle(request, server, ({ disableIdleTimeout, localPeer }) => { // Bun's router matched the raw path, but the gate and the handler read request.url, where `..` and `%2e%2e` // are resolved. Answer only when that path is still this route, so no gated route runs under an ungated path. const { pathname } = new URL(request.url); @@ -144,7 +150,7 @@ export function startServer(options: { port: number; hostname: string; dev: bool if (name !== "0" && value !== undefined) params[name] = decodeURIComponent(value); } if (rest) params[rest.name] = pathname.split("/").slice(rest.index).filter(Boolean).map(decodeURIComponent); - return dispatch(mod, request, params, disableIdleTimeout, (data) => server.upgrade(request, { data })); + return dispatch(mod, request, params, disableIdleTimeout, (data) => server.upgrade(request, { data }), localPeer); }); } if (html) routes[DEV_INDEX] = html; diff --git a/server/routes.ts b/server/routes.ts index f26703c0e..a2d3a1428 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -97,9 +97,10 @@ type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; // its socket; see handle() in server/app.ts. // upgrade: makes the request a WebSocket (server.upgrade), a host link or a browser link; a handler that upgraded // returns undefined. +// localPeer: the connection came from this machine's loopback interface. Taken from the socket, never from Host. export type RouteHandler = ( request: Request, - context: { params: Promise; disableIdleTimeout: () => void; upgrade: (data: ServerSocketData) => boolean }, + context: { params: Promise; disableIdleTimeout: () => void; upgrade: (data: ServerSocketData) => boolean; localPeer: boolean }, ) => Response | undefined | Promise; export type RouteModule = Partial>; @@ -209,6 +210,7 @@ export async function dispatch( params: Record, disableIdleTimeout: () => void = () => {}, upgrade: (data: ServerSocketData) => boolean = () => false, + localPeer = false, ): Promise { const handler = mod[request.method as Method] ?? (request.method === "HEAD" ? mod.GET : undefined); if (!handler) { @@ -218,7 +220,7 @@ export async function dispatch( return new Response(null, { status: 204, headers: { allow } }); } try { - return await handler(request, { params: Promise.resolve(params) as Promise, disableIdleTimeout, upgrade }); + return await handler(request, { params: Promise.resolve(params) as Promise, disableIdleTimeout, upgrade, localPeer }); } catch (error) { console.error(error); return Response.json({ error: "Internal Server Error" }, { status: 500 }); From c95747890cc93b890d47a10b16ae8af436cde762 Mon Sep 17 00:00:00 2001 From: 0721-art <0721-art@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:30:08 +0800 Subject: [PATCH 3/3] fix(cwd-picker): treat only a dismissal as cancellation osascript exits 1 for user cancellation (-128) and for every other AppleScript error, so the picker read a real failure as a closed dialog. Only exit 0, zenity's exit 1, and osascript's -128 are dismissals now; anything else reports stderr. --- lib/cwd-picker.test.mjs | 15 ++++++++++++++- lib/cwd-picker.ts | 30 ++++++++++++++++++++++++------ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/lib/cwd-picker.test.mjs b/lib/cwd-picker.test.mjs index 118a3fc58..67ed40e22 100644 --- a/lib/cwd-picker.test.mjs +++ b/lib/cwd-picker.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -const { hasPicker, pickDirectory, pickerAvailable, pickerCommand } = await import("./cwd-picker.ts"); +const { dialogOutcome, hasPicker, pickDirectory, pickerAvailable, pickerCommand } = await import("./cwd-picker.ts"); test("every desktop platform gets a folder dialog, anything else gets none", () => { const win = pickerCommand("win32"); @@ -22,6 +22,19 @@ test("no chooser means no dialog and no error, and no Browse button either", asy assert.equal(hasPicker("darwin"), true); }); +test("a dismissed dialog is not a failure, and an AppleScript error is not a dismissal", () => { + // The chosen path keeps a meaningful trailing space; only the line terminator goes. + assert.deepEqual(dialogOutcome("win32", 0, "C:\\Users\\me\\a folder \r\n", ""), { path: "C:\\Users\\me\\a folder " }); + assert.deepEqual(dialogOutcome("win32", 0, "", ""), { cancelled: true }); + assert.deepEqual(dialogOutcome("linux", 1, "", ""), { cancelled: true }); + assert.deepEqual(dialogOutcome("darwin", 1, "", "execution error: User canceled. (-128)"), { cancelled: true }); + assert.deepEqual(dialogOutcome("darwin", 1, "", "execution error: Can't get application. (-1728)\n"), { + error: "execution error: Can't get application. (-1728)", + }); + assert.deepEqual(dialogOutcome("linux", 2, "", "zenity: cannot open display"), { error: "zenity: cannot open display" }); + assert.deepEqual(dialogOutcome("win32", 1, "", ""), { error: "The folder dialog exited with code 1" }); +}); + test("a connection from another machine never gets the dialog, whatever its Host header said", () => { // context.localPeer comes from the accepted socket, so a remote client cannot reach the dialog. assert.equal(pickerAvailable(false, "win32"), false); diff --git a/lib/cwd-picker.ts b/lib/cwd-picker.ts index 5dbb26880..a19d48f6f 100644 --- a/lib/cwd-picker.ts +++ b/lib/cwd-picker.ts @@ -45,6 +45,27 @@ export function pickerAvailable(localPeer: boolean, platform: NodeJS.Platform = return localPeer && hasPicker(platform); } +/** What a finished dialog means: a chosen path, a dismissal, or a failure worth reporting. */ +export type DialogOutcome = PickedDirectory | { error: string }; + +/** Reads a chooser's exit status: only a real dismissal counts as cancellation. */ +export function dialogOutcome( + platform: NodeJS.Platform | string, + code: number | null, + stdout: string, + stderr: string, +): DialogOutcome { + // Only the chooser's own line terminator: a directory name may end in a space. + const path = stdout.replace(/[\r\n]+$/, ""); + if (path) return { path }; + // Dismissed: zenity exits 1, the Windows dialog exits 0 with no output, and osascript exits 1 + // for a cancelled dialog — but every other AppleScript error exits 1 too, so it needs -128. + const dismissed = + code === 0 || (code === 1 && (platform === "linux" || (platform === "darwin" && stderr.includes("(-128)")))); + if (dismissed) return { cancelled: true }; + return { error: stderr.replace(/[\r\n]+$/, "") || `The folder dialog exited with code ${code}` }; +} + /** Opens the dialog and waits for it; null when this platform has no chooser. */ export function pickDirectory(platform: NodeJS.Platform = process.platform): Promise { const command = pickerCommand(platform); @@ -59,12 +80,9 @@ export function pickDirectory(platform: NodeJS.Platform = process.platform): Pro child.on("error", (cause) => { clearTimeout(timer); reject(cause); }); child.on("close", (code) => { clearTimeout(timer); - // Only the chooser's own line terminator: a directory name may end in a space. - const path = stdout.replace(/[\r\n]+$/, ""); - if (path) return resolve({ path }); - // Dismissed: zenity and osascript exit 1, the Windows dialog still exits 0 with no output. - if (code === 0 || code === 1) return resolve({ cancelled: true }); - reject(new Error(stderr.trim() || `The folder dialog exited with code ${code}`)); + const outcome = dialogOutcome(platform, code, stdout, stderr); + if ("error" in outcome) reject(new Error(outcome.error)); + else resolve(outcome); }); }); }