Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(lending): allow the whole home folder with edits and the Windows system drive after a warning
Bugfixer 212c869ea503c
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mtsindex f426b5f0e0..7c41e31a1b 100644--- a/electron/computer-sharing.d.mts+++ b/electron/computer-sharing.d.mts@@ -1,4 +1,4 @@-export interface SharedFolder { id: string; name: string; path: string; write: boolean; /** The person's whole home folder. */ home?: boolean }+export interface SharedFolder { id: string; name: string; path: string; write: boolean; /** The person's whole home folder. */ home?: boolean; /** The whole Windows system drive (C:\\). */ system?: boolean }export interface SharingState {enabled: boolean;folders: SharedFolder[];@@ -92,7 +92,7 @@ export function automaticGrant(input: { kept?: SharedFolder[]; home?: SharedFoldexport function lendsAsWanted(record: unknown, wanted: AutomaticGrant): boolean;export function isHomeFolder(target: string): Promise<boolean>;export function existingFolders<T>(folders: unknown[], validate: (folders: unknown[]) => Promise<T[]>): Promise<T[]>;-export function validateSharedFolders(folders: unknown, options?: { homeEdits?: boolean }): Promise<SharedFolder[]>;+export function validateSharedFolders(folders: unknown, options?: { homeEdits?: boolean; platform?: NodeJS.Platform }): Promise<SharedFolder[]>;/** The sign-in a server answers with (/api/auth/session) is this desktop's admin pairing on a server of the person's own. */export function ownServerSession(auth: unknown): boolean;export function validSharedOperation(operation: unknown, computerId: string): boolean;@@ -156,7 +156,7 @@ export function createComputerSharing(options: {identity(env: Workspace): Promise<Identity>;observe(env: Workspace): Promise<Identity | null>;decline(env: Workspace, identity: Identity): void;- save(env: Workspace, input: Pick<SharingState, "folders" | "terminal" | "computer">, identity: Identity): Promise<SharingState>;+ save(env: Workspace, input: Pick<SharingState, "folders" | "terminal" | "computer">, identity: Identity, options?: { homeEdits?: boolean }): Promise<SharingState>;revoke(env: Workspace): SharingState;/** `env` is a server of the person's own, checked now: its identity, else null. */ownServer(env: Workspace): Promise<Identity | null>;@@ -166,7 +166,7 @@ export function createComputerSharing(options: {* false when it is not a server of the person's own. */ownOffer(env: Workspace): Promise<Identity | null | false>;/** The person allowed a server of their own to use this computer. */- lendOwn(env: Workspace, input: Partial<Pick<SharingState, "folders" | "terminal" | "computer">>): Promise<SharingState>;+ lendOwn(env: Workspace, input: Partial<Pick<SharingState, "folders" | "terminal" | "computer">>, options?: { homeEdits?: boolean }): Promise<SharingState>;/** Not now: nothing is lent, and this pairing is not asked again. */declineOwn(env: Workspace, identity: Identity): void;forget(env: Workspace): void;diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex aab379a932..3662b44075 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -16,7 +16,7 @@ import { BACKGROUND_HEADERS, CloudAsleepError, asleepAnswer, createCloudPowerGatimport { linkUrl, runDeviceLink } from "./device-link.mjs";import { createComputerAsks } from "./computer-asks.mjs";import { LINK_ASLEEP, linkPath } from "./device-link-protocol.mjs";-import { shareableDrive } from "./shared-drives.mjs";+import { isSystemDrive, shareableDrive } from "./shared-drives.mjs";import nativeText from "./native-text.cjs";import { actingBot } from "./lending-indicator.mjs";@@ -67,7 +67,7 @@ async function volumeRoot(canonical) {}/** Whether `target` is exactly the person's home folder. Only the home folder itself may be lent on request (see- * `home` in validateSharedFolders); the folders above it, and the system disk, never can. */+ * `home` in validateSharedFolders); the folders above it never can, and the system disk only as isSystemDrive says. */export async function isHomeFolder(target) {try {const [home] = homeCandidates();@@ -87,9 +87,9 @@ export async function existingFolders(folders, validate) {return found.filter(Boolean);}-/** `homeEdits`: the home folder keeps the editing it asks for, which only the person's own Clouds get (lendAutomatically);- * any other server gets it read only. */-export async function validateSharedFolders(folders, { homeEdits = false } = {}) {+/** `homeEdits`: the home folder and system drive keep the editing they ask for, which the person's own Clouds get+ * (lendAutomatically) and a server only after its edit warning (confirmServerAccess); else they are lent read only. */+export async function validateSharedFolders(folders, { homeEdits = false, platform = process.platform } = {}) {if (!Array.isArray(folders) || folders.length > 20) throw Object.assign(new Error("Choose at most 20 shared folders"), { code: "TOO_MANY" });const result = [];const enclosing = await enclosingHomeIdentities();@@ -97,15 +97,15 @@ export async function validateSharedFolders(folders, { homeEdits = false } = {})if (!uuid(folder?.id) || typeof folder.path !== "string" || !path.isAbsolute(folder.path) || typeof folder.write !== "boolean") throw Object.assign(new Error("Choose folders using the desktop folder picker"), { code: "NOT_PICKED" });const canonical = await fsp.realpath(folder.path);if (!(await fsp.stat(canonical)).isDirectory()) throw Object.assign(new Error("Choose a folder, not a file"), { code: "NOT_FOLDER" });- // The home folder, everything above it and the system disk are never shared. A separate drive (an external disk, a data- // disk on a server, a drive letter) may be shared whole; any other mount point is still refused.- // The home folder itself is lent only when asked for by name (`home: true`); anything above it, and the system disk,- // are refused whatever is asked. Security: with editing, a write through it still never reaches its hidden files,- // Library or AppData (insideHomeSettings), where shell start-up files and ~/.ssh live.+ // Nothing above the home folder is shared. A separate drive (an external disk, a data disk on a server, a drive+ // letter) may be shared whole; any other mount point is refused. The home folder is lent only by name (`home: true`)+ // and the Windows system drive by `system: true`, both set by main's picker after a warning. Security: with editing,+ // a write through either never reaches home's hidden files, Library or AppData (insideHomeSettings) or ~/.ssh.const home = folder.home === true && await isHomeFolder(canonical);- if (!home && (enclosing.has(await identify(canonical)) || ((await volumeRoot(canonical)) && !(await shareableDrive(canonical))))) throw Object.assign(new Error("Choose specific folders or a separate drive, not the entire computer or home folder"), { code: "HOME_OR_ROOT" });+ const system = !home && folder.system === true && await isSystemDrive(canonical, platform);+ if (!home && !system && (enclosing.has(await identify(canonical)) || ((await volumeRoot(canonical)) && !(await shareableDrive(canonical))))) throw Object.assign(new Error("Choose specific folders or a separate drive, not the entire computer or home folder"), { code: "HOME_OR_ROOT" });if (result.some(entry => entry.id === folder.id || entry.path === canonical)) continue;- result.push({ id: folder.id, path: canonical, name: path.basename(canonical).slice(0, 120), write: home && !homeEdits ? false : folder.write, ...(home ? { home: true } : {}) });+ result.push({ id: folder.id, path: canonical, name: path.basename(canonical).slice(0, 120), write: (home || system) && !homeEdits ? false : folder.write, ...(home ? { home: true } : {}), ...(system ? { system: true } : {}) });}return result;}@@ -851,11 +851,11 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, loreturn info;},decline(env, info) { changeGrant(env.id); disconnect(env, records[env.id]); store({ ...records, [env.id]: { ...info, enabled: false, folders: [], terminal: false, computer: false } }); },- async save(env, input, info) {+ async save(env, input, info, { homeEdits = false } = {}) {const version = changeGrant(env.id);const fresh = await identity(env);if (!matches(info, fresh)) throw new Error("Server sign-in changed. Review computer access again.");- const folders = await validateSharedFolders(input.folders);+ const folders = await validateSharedFolders(input.folders, { homeEdits });await requireEnabled();const grant = { ...fresh, id: randomUUID(), secret: randomBytes(32).toString("hex"), enabled: true, folders, terminal: input.terminal === true, computer: input.computer === true };if (!folders.length && !grant.terminal && !grant.computer) throw new Error("Choose at least one folder or capability to share");@@ -876,12 +876,12 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, loreturn info;},/** The person allowed a server of their own to use this computer: what `input` lends, checked as every grant is, the- * home folder read only. Security: only while this desktop is that server's admin now; no folder unless chosen. */- async lendOwn(env, input) {+ * home folder read only unless `homeEdits`. Security: only while this desktop is that server's admin now; no folder unless chosen. */+ async lendOwn(env, input, { homeEdits = false } = {}) {const version = changeGrant(env.id);if (closed) throw new Error("Lending is unavailable while the app is closing.");const info = await ownIdentity(env);- const folders = await validateSharedFolders(input?.folders ?? []);+ const folders = await validateSharedFolders(input?.folders ?? [], { homeEdits });const grant = { ...info, id: randomUUID(), secret: randomBytes(32).toString("hex"), enabled: true, own: true, folders, terminal: input?.terminal === true, computer: input?.computer === true };if (!folders.length && !grant.terminal && !grant.computer) throw new Error("Choose at least one folder or capability to share");if (grantVersions.get(env.id) !== version) return state(env.id);diff --git a/electron/lending-dialogs.mjs b/electron/lending-dialogs.mjsindex e56fdbce03..e732f7f9e5 100644--- a/electron/lending-dialogs.mjs+++ b/electron/lending-dialogs.mjs@@ -7,7 +7,7 @@ import nativeText from "./native-text.cjs";export function serverAccessDetail(env, { folders, terminal, computer }, t = nativeText.englishText.t) {return [t("native.lend.server", { origin: env.origin }),- ...folders.map(folder => `${t(folder.write ? "native.lend.readWrite" : "native.lend.readOnly", { path: folder.path })}${folder.home ? ` ${t("native.lend.wholeHome")}` : ""}`),+ ...folders.map(folder => `${t(folder.write ? "native.lend.readWrite" : "native.lend.readOnly", { path: folder.path })}${folder.home ? ` ${t("native.lend.wholeHome")}` : folder.system ? ` ${t("native.lend.systemDrive")}` : ""}`),t(terminal === true ? "native.lend.terminalOn" : "native.lend.terminalOff"),t(computer === true ? "native.lend.computerOn" : "native.lend.computerOff"),t("native.lend.footer"),@@ -18,12 +18,13 @@ export function serverAccessDetail(env, { folders, terminal, computer }, t = nat* @param {{* dialog: { showOpenDialog: Function, showMessageBox: Function },* window: () => ({ isDestroyed(): boolean } | null),- * validate: (folders: Array<{ id: string, path: string, write: boolean, home?: boolean }>) => Promise<Array<{ id: string, path: string, name: string, write: boolean, home?: boolean }>>,+ * validate: (folders: Array<{ id: string, path: string, write: boolean, home?: boolean, system?: boolean }>, options?: { homeEdits?: boolean }) => Promise<Array<{ id: string, path: string, name: string, write: boolean, home?: boolean, system?: boolean }>>,* isHome?: (path: string) => Promise<boolean>,+ * isSystemDrive?: (path: string) => Promise<boolean>,* t?: (key: string, params?: Record<string, string | number>) => string,* }} deps*/-export function createLendingDialogs({ dialog, window, validate, isHome = async () => false, t = nativeText.englishText.t }) {+export function createLendingDialogs({ dialog, window, validate, isHome = async () => false, isSystemDrive = async () => false, t = nativeText.englishText.t }) {let askingTerminal = false;return {/** Turning the terminal on runs `lend` only once the person confirms, one question at a time; turning it off never asks.@@ -45,7 +46,8 @@ export function createLendingDialogs({ dialog, window, validate, isHome = asyncreturn true;},/** The folder or drive the person picks, read only and checked as every lent folder is; null when they cancel. The- * home folder is lent only when it is picked here and confirmed here: the folders above it and the system disk never are. */+ * home folder and the Windows system drive are lent only when picked here and confirmed here: the other folders above+ * home never are. */async chooseFolder(title) {const picked = await dialog.showOpenDialog(window(), { title, properties: ["openDirectory"] });if (picked.canceled || !picked.filePaths[0]) return null;@@ -58,10 +60,24 @@ export function createLendingDialogs({ dialog, window, validate, isHome = asyncbuttons: [t("native.lend.home.button"), t("native.common.cancel")], defaultId: 1, cancelId: 1 });if (response !== 0) return null;folder.home = true;+ } else if (await isSystemDrive(folder.path)) {+ const { response } = await dialog.showMessageBox(window(), { type: "warning", message: t("native.lend.drive.title", { path: folder.path }),+ detail: t("native.lend.drive.detail"),+ buttons: [t("native.lend.drive.button"), t("native.common.cancel")], defaultId: 1, cancelId: 1 });+ if (response !== 0) return null;+ folder.system = true;}return (await validate([folder]))[0];},+ /** Edits on the whole home folder or system drive get their own warning first; Cancel on either lends nothing. */async confirmServerAccess(env, grant) {+ const whole = grant.folders.filter(folder => folder.write && (folder.home || folder.system));+ if (whole.length) {+ const { response } = await dialog.showMessageBox(window(), { type: "warning", message: t("native.lend.wholeEdits.title", { name: env.name }),+ detail: t("native.lend.wholeEdits.detail", { paths: whole.map(folder => folder.path).join(", ") }),+ buttons: [t("native.lend.wholeEdits.button"), t("native.common.cancel")], defaultId: 1, cancelId: 1 });+ if (response !== 0) return false;+ }const { response } = await dialog.showMessageBox(window(), { type: "warning", message: t("native.lend.allow.title", { name: env.name }), detail: serverAccessDetail(env, grant, t),buttons: [t("native.lend.allow.button"), t("native.common.cancel")], defaultId: 1, cancelId: 1 });return response === 0;diff --git a/electron/lending-dialogs.node-test.mjs b/electron/lending-dialogs.node-test.mjsindex b58496957e..a51ccc23dd 100644--- a/electron/lending-dialogs.node-test.mjs+++ b/electron/lending-dialogs.node-test.mjs@@ -143,3 +143,50 @@ test("main asks in its own dialog before a server gets this computer, and Cancelassert.deepEqual({ path: folder.path, write: folder.write }, { path: "/Users/me/Plans", write: false });assert.equal(allowed.calls.at(-1)[2].title, "Choose a folder or drive to share");});++test("the whole system drive is lent only after its own warning, and is named in the access dialog", async () => {+ const win = liveWindow(), isSystemDrive = async (path) => path === "C:\\";+ for (const [response, lent] of [[0, true], [1, false], [-1, false]]) {+ const { dialog, calls } = fakeDialog({ response, picked: { canceled: false, filePaths: ["C:\\"] } });+ const folder = await createLendingDialogs({ dialog, window: () => win, validate: named, isSystemDrive }).chooseFolder("Choose");+ assert.equal(calls[1][2].message, "Share the whole C:\\ drive?");+ assert.match(calls[1][2].detail, /readable by the bots you allow.*keys, passwords and browser data, and this app's own data, always stay private\./);+ assert.deepEqual([calls[1][2].type, calls[1][2].defaultId, calls[1][2].cancelId], ["warning", 1, 1]);+ assert.equal(folder === null, !lent);+ if (lent) assert.deepEqual({ system: folder.system, home: folder.home, write: folder.write }, { system: true, home: undefined, write: false });+ }+ const detail = serverAccessDetail({ name: "S", origin: "https://s.test" }, { folders: [{ path: "C:\\", write: false, system: true }], terminal: false, computer: false });+ assert.equal(detail.split("\n\n")[1], "Read only: C:\\ (the whole system drive)");+});++test("edits on the whole home folder or system drive need their own warning before the access dialog", async () => {+ const env = { name: "VPS", origin: "https://vps.test" };+ const grant = { folders: [{ path: "/Users/me", write: true, home: true }, { path: "/Users/me/Notes", write: true }], terminal: false, computer: false };+ for (const [response, allowed, asked] of [[0, true, 2], [1, false, 1], [-1, false, 1]]) {+ const { dialog, calls } = fakeDialog({ response });+ assert.equal(await createLendingDialogs({ dialog, window: liveWindow, validate: named }).confirmServerAccess(env, grant), allowed);+ assert.equal(calls.length, asked, "Cancel on the edit warning asks nothing more");+ assert.equal(calls[0][2].message, "Let bots on VPS change files anywhere in it?");+ assert.match(calls[0][2].detail, /add and change files anywhere in \/Users\/me, not just/);+ assert.deepEqual([calls[0][2].buttons, calls[0][2].defaultId, calls[0][2].cancelId], [["Allow edits", "Cancel"], 1, 1]);+ }+ const plain = fakeDialog({ response: 0 });+ await createLendingDialogs({ dialog: plain.dialog, window: liveWindow, validate: named }).confirmServerAccess(env, { ...grant, folders: [{ path: "/Users/me", write: false, home: true }] });+ assert.equal(plain.calls.length, 1, "read only asks only the access dialog");+});++test("a server keeps edits on the home folder only once the person confirmed both dialogs", async () => {+ const saved = [], handlers = new Map(), win = liveWindow();+ for (const response of [1, 0]) {+ const { dialog } = fakeDialog({ response });+ const team = { id: "vps", name: "VPS", origin: "https://vps.test" };+ const controller = { state: () => ({}), ownServer: async () => null, identity: async () => ({ id: "info" }), save: async (env, grant, info, options) => { saved.push([grant, options]); } };+ installServerLending({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: (_channel, handler) => handler, sharing: () => controller,+ dialogs: createLendingDialogs({ dialog, window: () => win, validate: named }), validate: named, dialog, window: () => win,+ saved: () => team, candidate: () => true, flag: async () => true, environments: () => [team] });+ await handlers.get("sharing:save")({}, "vps", { folders: [{ path: "/Users/me", write: true, home: true }] });+ }+ assert.equal(saved.length, 1, "Cancel saves nothing");+ assert.deepEqual(saved[0][1], { homeEdits: true });+ assert.equal(saved[0][0].folders[0].write, true);+});diff --git a/electron/lending-guards.node-test.mjs b/electron/lending-guards.node-test.mjsindex 8e2307c265..25fc575d31 100644--- a/electron/lending-guards.node-test.mjs+++ b/electron/lending-guards.node-test.mjs@@ -449,3 +449,23 @@ test("a Windows path in a failure collapses to its file name before it leaves th});assert.equal(text(results[0]), "cannot open state.json: denied");});++test("direct executor: through the whole system drive, the home folder's hidden files, Library and AppData stay unchangeable", async t => {+ const home = await realpath(await mkdtemp(path.join(tmpdir(), "omb-drive-home-")));+ const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };+ t.after(async () => {+ for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value;+ await rm(home, { recursive: true, force: true });+ });+ process.env.HOME = home; process.env.USERPROFILE = home;+ const drive = path.parse(home).root;+ const folder = { id: randomUUID(), name: drive, path: drive, write: true, system: true };+ const grant = { enabled: true, folders: [folder], terminal: false, computer: false };+ const inHome = relative => [...path.relative(drive, home).split(path.sep), ...relative.split("/")].join("/");+ const run = operation => executeSharedOperation(grant, { folder_id: folder.id, ...operation }, new AbortController().signal);+ for (const candidate of [".bashrc", ".ssh/authorized_keys", "AppData/Roaming/x.txt", "library/LaunchAgents/x.plist"]) {+ await assert.rejects(run({ action: "write_file", path: inHome(candidate), content: "x" }), /hidden files, Library and AppData/, candidate);+ }+ await run({ action: "write_file", path: inHome("Documents/plan.txt"), content: "fine" });+ assert.equal(await readFile(path.join(home, "Documents", "plan.txt"), "utf8"), "fine");+});diff --git a/electron/main.mjs b/electron/main.mjsindex a26622a9d5..973bd627d4 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -90,7 +90,7 @@ import environmentsModule from "./environments.cjs";import { pairingPageUrl, vouchForPlainHttpServers } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { createTailnetShare, remotePolicyAllows } from "./tailnet-share.mjs"; import { checkTailscale } from "./tailscale-check.mjs"; import { onTailnet } from "./tailnet.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs";import localOriginModule from "./local-origin.cjs";import { buildApplicationMenu } from "./menu.mjs";-import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { installServerLending } from "./server-lending.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";+import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { isSystemDrive } from "./shared-drives.mjs"; import { installServerLending } from "./server-lending.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";import { createHostScreenLease } from "./host-screen-lease.mjs";import { acquireDataDirLease } from "./data-dir-lease.mjs";import { reviveAfterFailedSwitch, switchLocalEnvironment } from "./environment-switch.mjs";@@ -2620,7 +2620,7 @@ const announceAddedCloud = createAddedCloudNotice({ t: nativeT, Notification, foinstallPlaceLook({ ipcMain, guard: workspaceOnly, place: () => savedPlace(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),setColor: (id, swatch) => ensureCloudAccount().setCloudColor(id, swatch), save: (id, color) => persistEnvironments(withPlaceColor(environmentsState, id, color)),rail: { owns: event => chromeRail.owns(event), places: railList, saved: id => savedPlace(environmentsState, id) }, t: nativeT });-const lendingDialogs = createLendingDialogs({ dialog, window: () => mainWindow, validate: validateSharedFolders, isHome: isHomeFolder, t: nativeT });+const lendingDialogs = createLendingDialogs({ dialog, window: () => mainWindow, validate: validateSharedFolders, isHome: isHomeFolder, isSystemDrive, t: nativeT });// Settings → Servers' computer access, and the popup after pairing a server of the person's own (server-lending.mjs).const serverLending = installServerLending({ ipcMain, guard: localWorkspaceOnly, sharing: sharingController, dialogs: lendingDialogs, validate: validateSharedFolders, dialog, window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null),saved: savedWorkspace, candidate: lendableServer, flag: refreshSharedComputersAllowed, environments: () => environmentsState.environments, active: () => activeEnvironment(environmentsState), openSettings: openWorkspaceSettings, t: nativeT, log: slog, screen: screenControl.now, allowScreen: screenControl.start, local: event => cloudPageAsking(event) === "local", page: event => { const env = activeEnvironment(environmentsState); return env?.origin && env.kind !== "local" && activePageOrigin(event) === env.origin ? env : null; } });diff --git a/electron/server-lending.mjs b/electron/server-lending.mjsindex 26d9170474..8a7fb107e1 100644--- a/electron/server-lending.mjs+++ b/electron/server-lending.mjs@@ -63,10 +63,11 @@ export function installServerLending({ ipcMain, guard, sharing, dialogs, validatconst env = saved(id);const mine = await requireOwnOrFlag(env);const info = mine ? null : await sharing().identity(env);- const grant = { folders: await validate(input?.folders), terminal: input?.terminal === true, computer: input?.computer === true };+ // Edits on the home folder or the system drive are kept only because confirmServerAccess asks about them first.+ const grant = { folders: await validate(input?.folders, { homeEdits: true }), terminal: input?.terminal === true, computer: input?.computer === true };if (!(await dialogs.confirmServerAccess(env, grant))) return null;saved(id);- return mine ? sharing().lendOwn(env, grant) : sharing().save(env, grant, info);+ return mine ? sharing().lendOwn(env, grant, { homeEdits: true }) : sharing().save(env, grant, info, { homeEdits: true });}));/** Settings → Servers: each server of the person's own, and how lending to it is. */ipcMain.handle("sharing:servers", guard("sharing:servers", async () => {diff --git a/electron/shared-computer-access.mjs b/electron/shared-computer-access.mjsindex d6fdc1368b..7401093770 100644--- a/electron/shared-computer-access.mjs+++ b/electron/shared-computer-access.mjs@@ -2,6 +2,7 @@import fs from "node:fs/promises";import { constants } from "node:fs";import path from "node:path";+import os from "node:os";import { createHash } from "node:crypto";import { spawn } from "node:child_process";import readline from "node:readline";@@ -58,6 +59,22 @@ function editedText(current, oldText, newText) {const absent = error => error.code === "ENOENT" || error.code === "ENOTDIR";const identify = async candidate => { const info = await fs.stat(candidate, { bigint: true }); return `${info.dev}:${info.ino}`; };+/** Where `target` is inside the home folder, "/"-separated ("" for the home folder itself), or null outside it. By+ * {dev, ino}, as the home boundary is, so another spelling of the same folder (8.3 names, case) is no way around it. */+async function insideHomePath(target, home = os.homedir()) {+ let homeIdentity;+ try { homeIdentity = await identify(await fs.realpath(home)); } catch (error) { if (absent(error)) return null; throw error; }+ const { root } = path.parse(target);+ const parts = target.slice(root.length).split(path.sep).filter(Boolean);+ let current = root;+ for (let index = 0; index <= parts.length; index++) {+ try { if ((await identify(current)) === homeIdentity) return parts.slice(index).join("/"); }+ catch (error) { if (absent(error)) return null; throw error; }+ if (index < parts.length) current = path.join(current, parts[index]);+ }+ return null;+}+/** {dev, ino}, never path text; a root a fresh install has not created yet is skipped. */export async function protectedIdentities(roots) {const identities = new Set();@@ -311,6 +328,11 @@ export async function executeSharedOperation(grant, operation, signal, cua, lentif (changes && folder.write !== true) throw new Error("This folder is read-only");if (changes && insideGitInternals(folder.path, operation.path ?? "")) throw new Error(GIT_INTERNALS);if (changes && folder.home === true && insideHomeSettings(operation.path ?? "")) throw new Error(HOME_SETTINGS);+ // The whole system drive holds the home folder too: the same files stay out of reach through it.+ if (changes && folder.system === true) {+ const inHome = await insideHomePath(target);+ if (inHome !== null && insideHomeSettings(inHome)) throw new Error(HOME_SETTINGS);+ }let data;if (write) {if (typeof operation.content !== "string") throw new Error("Give file content to write");diff --git a/electron/shared-drives.mjs b/electron/shared-drives.mjsindex 8874bd97a9..83c2f04c29 100644--- a/electron/shared-drives.mjs+++ b/electron/shared-drives.mjs@@ -5,8 +5,11 @@// directory that happens to be its own partition, and never a virtual filesystem. The decision is made on the// canonical path the OS resolved, so a symlink to a drive is judged by where it ends up.import fsp from "node:fs/promises";+import os from "node:os";import path from "node:path";+const identify = async candidate => { const info = await fsp.stat(candidate, { bigint: true }); return `${info.dev}:${info.ino}`; };+/** Linux filesystems that live on a real disk or network share. tmpfs, proc, sysfs, overlay, squashfs, cgroup and the* desktop's fuse portals are not on this list, so they are never a drive. */const LINUX_DISK_FILESYSTEMS = new Set([@@ -62,3 +65,14 @@ export async function readLinuxMounts() {export async function shareableDrive(canonical, platform = process.platform, readMounts = readLinuxMounts) {return isShareableDriveRoot(canonical, platform, platform === "linux" ? await readMounts() : []);}++/** Whether `target` is the whole drive the home folder is on (C:\\ on Windows), lent only when asked for by name (`system`+ * in validateSharedFolders) after its own warning. Windows only: elsewhere "/" holds /proc and the system's own files. */+export async function isSystemDrive(target, platform = process.platform) {+ if (platform !== "win32") return false;+ try {+ const canonical = await fsp.realpath(target);+ if (path.parse(canonical).root !== canonical) return false;+ return (await identify(canonical)) === (await identify(path.parse(await fsp.realpath(os.homedir())).root));+ } catch { return false; }+}diff --git a/electron/shared-drives.node-test.mjs b/electron/shared-drives.node-test.mjsindex 86d70103b9..cff75a2128 100644--- a/electron/shared-drives.node-test.mjs+++ b/electron/shared-drives.node-test.mjs@@ -1,6 +1,6 @@import assert from "node:assert/strict";import test from "node:test";-import { isShareableDriveRoot, linuxDrive, parseMountInfo, shareableDrive } from "./shared-drives.mjs";+import { isShareableDriveRoot, isSystemDrive, linuxDrive, parseMountInfo, shareableDrive } from "./shared-drives.mjs";const MOUNTINFO = ["25 1 259:2 / / rw,relatime shared:1 - ext4 /dev/nvme0n1p2 rw",@@ -71,3 +71,36 @@ test("the home folder is lent only when asked for by the picker; its parents andrmSync(base, { recursive: true, force: true });}});++test("the Windows system drive is lent whole only when the picker asks for it, read only until edits are confirmed", async () => {+ const { mkdtempSync, mkdirSync, realpathSync, rmSync } = await import("node:fs");+ const { tmpdir } = await import("node:os");+ const path = await import("node:path");+ const { validateSharedFolders } = await import("./computer-sharing.mjs");+ const base = realpathSync.native(mkdtempSync(path.join(tmpdir(), "omb-system-drive-")));+ const home = path.join(base, "me");+ mkdirSync(home, { recursive: true });+ const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };+ const id = "8b0c8d3e-1f2a-4b5c-8d6e-7f8091a2b3c4";+ // The drive the home folder is on: C:\ on Windows; "/" here, standing in for it with platform "win32".+ const drive = path.parse(home).root;+ try {+ process.env.HOME = home; process.env.USERPROFILE = home;+ assert.equal(await isSystemDrive(drive, "win32"), true);+ assert.equal(await isSystemDrive(drive, "darwin"), false, "Windows only");+ assert.equal(await isSystemDrive(base, "win32"), false, "a folder, not the drive");+ const asked = { id, path: drive, write: true, system: true };+ const [lent] = await validateSharedFolders([asked], { platform: "win32" });+ assert.deepEqual({ system: lent.system, write: lent.write, home: lent.home }, { system: true, write: false, home: undefined });+ const [edits] = await validateSharedFolders([asked], { platform: "win32", homeEdits: true });+ assert.equal(edits.write, true, "edits once the person confirmed them");+ await assert.rejects(validateSharedFolders([{ ...asked, system: undefined }], { platform: "win32" }), { code: "HOME_OR_ROOT" }, "not without the request");+ await assert.rejects(validateSharedFolders([asked], { platform: "linux" }), { code: "HOME_OR_ROOT" }, "elsewhere / stays refused");+ await assert.rejects(validateSharedFolders([{ ...asked, path: base }], { platform: "win32" }), { code: "HOME_OR_ROOT" }, "folders above home stay refused");+ const [homeEdits] = await validateSharedFolders([{ id, path: home, write: true, home: true }], { homeEdits: true });+ assert.equal(homeEdits.write, true, "the home folder keeps confirmed edits too");+ } finally {+ for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value;+ rmSync(base, { recursive: true, force: true });+ }+});diff --git a/src/locales/en.json b/src/locales/en.jsonindex aac855d04c..ed1fa4f70a 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -9974,6 +9974,13 @@"native.lend.home.title": "Share your whole home folder?","native.lend.home.detail": "Everything in your home folder becomes readable by the bots you allow. The places that hold keys, passwords and browser data, like .ssh and your browsers' profiles, always stay private.","native.lend.home.button": "Share home folder",+ "native.lend.drive.title": "Share the whole {path} drive?",+ "native.lend.drive.detail": "Everything on this drive that you can open becomes readable by the bots you allow: your home folder, programs' files and Windows' own files. The places that hold keys, passwords and browser data, and this app's own data, always stay private.",+ "native.lend.drive.button": "Share whole drive",+ "native.lend.systemDrive": "(the whole system drive)",+ "native.lend.wholeEdits.title": "Let bots on {name} change files anywhere in it?",+ "native.lend.wholeEdits.detail": "With edits allowed, bots on this server can add and change files anywhere in {paths}, not just in one project folder. A mistake or a bad instruction can change files you care about. Your home folder's hidden files, Library and AppData, and the places that hold keys and passwords, still can't be changed.",+ "native.lend.wholeEdits.button": "Allow edits","native.common.cancel": "Cancel","native.badge.one": "{count} unread conversation","native.badge.many": "{count} unread conversations",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 4165209349..e691cf44cf 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -9899,6 +9899,13 @@"native.lend.home.title": "Compartilhar sua pasta pessoal inteira?","native.lend.home.detail": "Os bots que você autorizar vão poder ler tudo na sua pasta pessoal. Os lugares que guardam chaves, senhas e dados do navegador, como .ssh e os perfis dos navegadores, continuam sempre privados.","native.lend.home.button": "Compartilhar pasta pessoal",+ "native.lend.drive.title": "Compartilhar a unidade {path} inteira?",+ "native.lend.drive.detail": "Tudo nesta unidade que você pode abrir passa a poder ser lido pelos bots que você permitir: sua pasta pessoal, os arquivos dos programas e os arquivos do próprio Windows. Os lugares que guardam chaves, senhas e dados do navegador, e os dados deste app, continuam sempre privados.",+ "native.lend.drive.button": "Compartilhar unidade inteira",+ "native.lend.systemDrive": "(a unidade do sistema inteira)",+ "native.lend.wholeEdits.title": "Permitir que bots em {name} alterem arquivos em qualquer lugar dela?",+ "native.lend.wholeEdits.detail": "Com edições permitidas, os bots deste servidor podem adicionar e alterar arquivos em qualquer lugar de {paths}, não só em uma pasta de projeto. Um erro ou uma instrução ruim pode alterar arquivos importantes para você. Os arquivos ocultos, Library e AppData da sua pasta pessoal, e os lugares que guardam chaves e senhas, continuam sem poder ser alterados.",+ "native.lend.wholeEdits.button": "Permitir edições","native.common.cancel": "Cancelar","native.badge.one": "{count} conversa não lida","native.badge.many": "{count} conversas não lidas",