// OPEN A FOLDER IN THE OS FILE MANAGER (the clip export's "Open folder", // `umtool export … --open`): umtool runs on the operator's own machine, so it // can ask that machine's desktop to show a folder -- and, where the file // manager takes it, to select the file in it. // // Linux org.freedesktop.FileManager1.ShowItems over the session bus // (dbus-send: Files, Dolphin, Nemo, Thunar … reveal and select the // file), else `xdg-open ` // macOS `open -R ` (Finder, selected), else `open ` // // REFUSED, with the reason in words: inside a container (there is no desktop // to open it on), on any other platform, and -- for a request -- from // anywhere but this machine (the phone has Download for that). The request // check reads the headers a browser sends (Host, Origin, X-Forwarded-For): // it keeps a page opened from another device from popping windows on this // one; it is not an access control, and the route is a writer's // (refuseCaller) besides. import { spawn } from "node:child_process"; import { appendFileSync, existsSync } from "node:fs"; import { pathToFileURL } from "node:url"; const LOOPBACK = new Set(["localhost", "127.0.0.1", "::1", "[::1]", "0:0:0:0:0:0:0:1"]); /** Is this host name (no port) this machine's loopback? */ export function isLoopbackHost(host) { const h = String(host ?? "").trim().toLowerCase().replace(/^\[|\]$/g, ""); return LOOPBACK.has(h) || /^127(\.\d{1,3}){3}$/.test(h) || h === "::ffff:127.0.0.1" || h.endsWith(".localhost"); } /** A Host header's name without its port: `localhost:3050` → `localhost`, `[::1]:3050` → `::1`. */ export function hostName(header) { const v = String(header ?? "").trim(); if (v.startsWith("[")) return v.slice(1, v.indexOf("]") > 0 ? v.indexOf("]") : undefined); return v.split(":")[0]; } /** * Whether a request came from this machine, by the headers it carries: * `{ ok: true }` or `{ ok: false, why }`. * * @param {{ get(name: string): string | null }} headers */ export function localRequest(headers) { const host = hostName(headers.get("host")); if (!isLoopbackHost(host)) return { ok: false, why: `this page is open at ${host || "an unknown host"}, not on the machine umtool runs on` }; const fwd = (headers.get("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean); const far = fwd.find((a) => !isLoopbackHost(a)); if (far) return { ok: false, why: `the request was forwarded from ${far}` }; const origin = headers.get("origin"); if (origin && origin !== "null") { try { const o = new URL(origin).hostname; if (!isLoopbackHost(o)) return { ok: false, why: `the request came from a page at ${o}` }; } catch { return { ok: false, why: "the request's origin is not a URL" }; } } return { ok: true }; } /** Is this process inside a container (docker, podman)? */ export function inContainer({ exists = existsSync, env = process.env } = {}) { return exists("/.dockerenv") || exists("/run/.containerenv") || env.container === "docker" || env.container === "podman"; } /** * The commands that would show `dir` (and select `file` in it), in the order * to try them, for a platform. [] where there is none. * * @param {{ dir: string, file?: string | null, platform?: string }} o * @returns {Array<{ cmd: string, args: string[], selects: boolean }>} */ export function openersFor({ dir, file = null, platform = process.platform }) { if (platform === "linux") { const out = []; if (file) { out.push({ cmd: "dbus-send", args: [ "--session", "--print-reply", "--dest=org.freedesktop.FileManager1", "--type=method_call", "/org/freedesktop/FileManager1", "org.freedesktop.FileManager1.ShowItems", `array:string:${pathToFileURL(file).href}`, "string:", ], selects: true, }); } out.push({ cmd: "xdg-open", args: [dir], selects: false }); return out; } if (platform === "darwin") { return [...(file ? [{ cmd: "open", args: ["-R", file], selects: true }] : []), { cmd: "open", args: [dir], selects: false }]; } return []; } /** Why a folder cannot be opened here, or null when it can be tried. */ export function cannotOpen({ platform = process.platform, container = inContainer() } = {}) { // TEST-ONLY: the e2e log stands in for the file manager wherever the suite runs (a container too). if (process.env.E2E_UMTOOL_OPEN_FOLDER_LOG) return null; if (container) return "umtool is running in a container: there is no desktop here to open a folder on — use Download"; if (platform !== "linux" && platform !== "darwin") return `opening a folder is not wired for ${platform} — use Download`; return null; } /** Run one opener; resolves to its exit code (null for a spawn error). */ function tryOpen({ cmd, args }, { timeoutMs = 5000 } = {}) { return new Promise((resolve) => { let child; try { child = spawn(cmd, args, { stdio: "ignore", detached: true }); } catch { resolve({ code: null, error: `${cmd} could not be started` }); return; } const timer = setTimeout(() => { // Still running after the wait: it launched (xdg-open may stay with the app it opened). child.unref(); resolve({ code: 0 }); }, timeoutMs); child.on("error", (e) => { clearTimeout(timer); resolve({ code: null, error: e?.code === "ENOENT" ? `${cmd} is not installed` : String(e?.message ?? e) }); }); child.on("exit", (code) => { clearTimeout(timer); resolve({ code }); }); }); } /** * Show `dir` in the file manager, selecting `file` where it can. Resolves to * `{ ok: true, how, selected }` or `{ ok: false, error }`; never throws. * * @param {{ dir: string, file?: string | null, platform?: string, container?: boolean, run?: typeof tryOpen }} o */ export async function openFolder({ dir, file = null, platform = process.platform, container = inContainer(), run = tryOpen }) { // TEST-ONLY: E2E_UMTOOL_OPEN_FOLDER_LOG (umtool/playwright.config.ts) records the ask in that file and opens // nothing -- a spec must never pop a file manager on the machine it runs on. const log = process.env.E2E_UMTOOL_OPEN_FOLDER_LOG; if (log) { appendFileSync(/* turbopackIgnore: true */ log, `${JSON.stringify({ dir, file })}\n`); return { ok: true, how: "e2e-log", selected: !!file }; } const no = cannotOpen({ platform, container }); if (no) return { ok: false, error: no }; const tried = []; for (const op of openersFor({ dir, file, platform })) { const r = await run(op); if (r.code === 0) return { ok: true, how: op.cmd, selected: op.selects }; tried.push(r.error ?? `${op.cmd} exited ${r.code}`); } return { ok: false, error: `no file manager answered (${tried.join("; ")}) — use Download` }; }