Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Outside-workspace file: refuse hidden paths, secret stores and key-like names
milind-soni24092d6c2995
diff --git a/server/message-file.test.ts b/server/message-file.test.tsindex a4763df945..def91ffc65 100644--- a/server/message-file.test.ts+++ b/server/message-file.test.ts@@ -533,7 +533,8 @@ describe("message-linked files", () => {}await expect(openOutsideWorkspaceMessageFile(appFile, [appData])).rejects.toMatchObject({ status: 403, code: "outside_workspace" });- await expect(openOutsideWorkspaceMessageFile(secretFile, [appData])).rejects.toMatchObject({ status: 403, code: "secret_file" });+ // A hidden folder is refused before the file is opened, with the same quiet outside-workspace answer.+ await expect(openOutsideWorkspaceMessageFile(secretFile, [appData])).rejects.toMatchObject({ status: 403, code: "outside_workspace" });await expect(openOutsideWorkspaceMessageFile(folder, [appData])).rejects.toMatchObject({ status: 400, code: "directory" });await expect(openOutsideWorkspaceMessageFile("relative/shared-notes.md", [appData])).rejects.toMatchObject({ status: 403, code: "outside_workspace" });} finally {@@ -541,4 +542,32 @@ describe("message-linked files", () => {rmSync(appData, { recursive: true, force: true });}});++ it("refuses hidden paths, key-like names and a link that resolves into a hidden folder, with the quiet outside answer", async () => {+ const root = mkdtempSync(join(tmpdir(), "omb-outside-guard-"));+ try {+ const ssh = join(root, "home", ".ssh");+ mkdirSync(ssh, { recursive: true });+ const key = join(ssh, "id_ed25519");+ writeFileSync(key, "fixture key");+ const shared = join(root, "shared");+ mkdirSync(shared, { recursive: true });+ const link = join(shared, "notes.md");+ symlinkSync(key, link);+ const env = join(shared, "app.env");+ writeFileSync(env, "TOKEN=fixture");+ const pem = join(shared, "server.pem");+ writeFileSync(pem, "fixture");+ const fine = join(shared, "plan.md");+ writeFileSync(fine, "# plan\n");++ expect(await canOpenOutsideWorkspaceMessageFile(fine, [])).toBe(true);+ for (const refused of [key, link, env, pem]) {+ expect(await canOpenOutsideWorkspaceMessageFile(refused, []), refused).toBe(false);+ await expect(openOutsideWorkspaceMessageFile(refused, []), refused).rejects.toMatchObject({ status: 403, code: "outside_workspace" });+ }+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });});diff --git a/server/message-file.ts b/server/message-file.tsindex 8385ce2ac6..5d25cfc079 100644--- a/server/message-file.ts+++ b/server/message-file.ts@@ -10,6 +10,7 @@ import { fromMarkdown } from "mdast-util-from-markdown";import { windowsPathDestinations } from "../shared/markdown-windows-paths.ts";import { linkPlainPaths } from "../shared/markdown-plain-paths.ts";import { PREVIEW_MAX_BYTES } from "../shared/upload-limits.ts";+import { outsideFileRefused } from "./outside-file-guard.ts";import { inSecretFolder, SECRET_FILE_REFUSAL } from "./secret-folder.ts";import { userErrorThrown } from "./user-errors.ts";@@ -478,7 +479,8 @@ export async function openMessageFile(throw statusError(404, "the linked file is unavailable");}-/** True when an owner's explicit single-file open could succeed without granting any folder or secret/app-data path. */+/** True when an owner's explicit single-file open could succeed without granting any folder, hidden path, secret store,+ * key-like file or app-data path (server/outside-file-guard.ts). */export async function canOpenOutsideWorkspaceMessageFile(href: string, refusedRoots: readonly string[]): Promise<boolean> {let candidate: string;try {@@ -493,7 +495,7 @@ export async function canOpenOutsideWorkspaceMessageFile(href: string, refusedRo} catch {return false;}- if (inSecretFolder(canonical)) return false;+ if (inSecretFolder(canonical) || outsideFileRefused(candidate) || outsideFileRefused(canonical)) return false;const canonicalRefused = await resolveCanonicalRoots(refusedRoots, false);return !canonicalRefused.some((dir) => containedBy(dir, canonical));}@@ -512,13 +514,15 @@ export async function openOutsideWorkspaceMessageFile(} catch {throw statusError(404, "the linked file is unavailable");}- if (canonicalRefused.some((dir) => containedBy(dir, canonicalBefore))) throw outsideWorkspace();+ if (outsideFileRefused(candidate) || outsideFileRefused(canonicalBefore) || canonicalRefused.some((dir) => containedBy(dir, canonicalBefore))) {+ throw outsideWorkspace();+ }try {return await openCanonicalMessageFile(candidate,canonicalBefore,maxBytes,- (canonicalAfter) => !canonicalRefused.some((dir) => containedBy(dir, canonicalAfter)),+ (canonicalAfter) => !outsideFileRefused(canonicalAfter) && !canonicalRefused.some((dir) => containedBy(dir, canonicalAfter)),);} catch (error) {if (error && typeof error === "object" && "status" in error) throw error;diff --git a/server/outside-file-guard.test.ts b/server/outside-file-guard.test.tsnew file mode 100644index 0000000000..041215a3ea--- /dev/null+++ b/server/outside-file-guard.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";++import { outsideFileRefused, type OutsideFilePlace } from "./outside-file-guard.ts";++const mac: OutsideFilePlace = { home: "/Users/ada", platform: "darwin", env: {} };+const linux: OutsideFilePlace = { home: "/home/ada", platform: "linux", env: {} };+const windows: OutsideFilePlace = {+ home: "C:\\Users\\Ada", platform: "win32",+ env: { APPDATA: "C:\\Users\\Ada\\AppData\\Roaming", LOCALAPPDATA: "C:\\Users\\Ada\\AppData\\Local" },+};++describe("files a self-hosted owner may open from outside the workspace", () => {+ it("allows an ordinary document", () => {+ expect(outsideFileRefused("/Users/ada/Documents/plan.md", mac)).toBe(false);+ expect(outsideFileRefused("/home/ada/projects/site/README.md", linux)).toBe(false);+ expect(outsideFileRefused("C:\\Users\\Ada\\Documents\\report.pdf", windows)).toBe(false);+ });++ it.each([+ "/home/ada/.ssh/config", "/home/ada/.aws/credentials", "/home/ada/.gnupg/pubring.kbx", "/home/ada/.config/gh/hosts.yml",+ "/home/ada/.claude/settings.json", "/home/ada/.codex/auth.json", "/home/ada/.pi/agent/auth.json",+ "/home/ada/.openmausbot-profiles/default/config.json", "/home/ada/.openmausbot/config.json", "/home/ada/.npmrc",+ "/home/ada/projects/site/.env", "/srv/app/.git/config",+ ])("refuses a hidden file or a file in a hidden folder: %s", (path) => {+ expect(outsideFileRefused(path, linux)).toBe(true);+ });++ it.each([+ "id_rsa", "id_rsa.pub", "id_ed25519", "id_ecdsa_work", "server.pem", "tls.KEY", "cert.p12", "cert.pfx", "vault.kdbx",+ "credentials", "credentials.json", "production.env",+ ])("refuses a name that looks like a key or credential: %s", (name) => {+ expect(outsideFileRefused(`/home/ada/Downloads/${name}`, linux)).toBe(true);+ });++ it.each([+ "/Users/ada/Library/Keychains/login.keychain-db", "/Library/Keychains/System.keychain", "/Users/ada/Library/Cookies/Cookies.binarycookies",+ "/Users/ada/Library/Application Support/Google/Chrome/Default/Login Data",+ "/Users/ada/Library/Application Support/Firefox/Profiles/x/logins.json", "/users/ADA/library/keychains/login.keychain-db",+ ])("refuses a macOS secret store: %s", (path) => {+ expect(outsideFileRefused(path, mac)).toBe(true);+ });++ it.each([+ "C:\\Users\\Ada\\AppData\\Roaming\\Microsoft\\Credentials\\ABC", "C:\\Users\\Ada\\AppData\\Roaming\\Microsoft\\Protect\\S-1\\x",+ "C:\\Users\\Ada\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data",+ "C:\\Users\\Ada\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Cookies",+ "c:\\users\\ada\\appdata\\roaming\\microsoft\\credentials\\abc",+ ])("refuses a Windows secret store: %s", (path) => {+ expect(outsideFileRefused(path, windows)).toBe(true);+ });++ it("does not refuse another folder that merely shares a store's prefix", () => {+ expect(outsideFileRefused("/Users/ada/Library/KeychainsNotes/plan.md", mac)).toBe(false);+ expect(outsideFileRefused("/Users/ada/Library/Application Support/Notes/plan.md", mac)).toBe(false);+ });+});diff --git a/server/outside-file-guard.ts b/server/outside-file-guard.tsnew file mode 100644index 0000000000..ca2dc906e7--- /dev/null+++ b/server/outside-file-guard.ts@@ -0,0 +1,70 @@+// Security: what a self-hosted owner may open from outside a conversation's workspace when a bot links it. The bot picks+// the path and the server reads it with its own rights, so a boxed or prompt-injected bot must not be able to hand the+// owner a secret it cannot read itself. Every check runs on the resolved path (and on the link as written).+import { realpathSync } from "node:fs";+import { homedir } from "node:os";++export interface OutsideFilePlace {+ home: string;+ platform: NodeJS.Platform;+ env: Record<string, string | undefined>;+}++/** The home folder as resolved paths spell it (macOS's /var is /private/var). */+function resolvedHome(): string {+ try { return realpathSync(homedir()); } catch { return homedir(); }+}++const here = (): OutsideFilePlace => ({ home: resolvedHome(), platform: process.platform, env: process.env });++/** Names that hold keys or credentials wherever they sit. */+const SECRET_NAME = /^(?:id_(?:rsa|ed25519|ecdsa|dsa)|credentials)|\.(?:pem|key|p12|pfx|kdbx|env)$/i;++/** Browser profile folders under macOS's Application Support; each holds cookies, saved passwords and session tokens. */+const MAC_BROWSERS = [+ "Google/Chrome", "Google/Chrome Beta", "Google/Chrome Canary", "Chromium", "BraveSoftware", "Microsoft Edge", "Firefox",+ "Arc", "Vivaldi", "com.operasoftware.Opera", "Orion", "Zen",+];++const segments = (path: string): string[] => path.split(/[\\/]+/).filter(Boolean);+const lowered = (path: string, folds: boolean): string => {+ const slashed = path.replace(/\\/g, "/").replace(/\/+$/, "");+ return folds ? slashed.toLowerCase() : slashed;+};++/** Secret stores whose folders start with no dot, for this computer's platform. */+function secretStores({ home, platform, env }: OutsideFilePlace): string[] {+ if (platform === "darwin") {+ return [+ `${home}/Library/Keychains`, "/Library/Keychains", `${home}/Library/Cookies`,+ ...MAC_BROWSERS.map((browser) => `${home}/Library/Application Support/${browser}`),+ ];+ }+ if (platform === "win32") {+ const roaming = env.APPDATA || `${home}\\AppData\\Roaming`;+ const local = env.LOCALAPPDATA || `${home}\\AppData\\Local`;+ return [+ `${roaming}\\Microsoft\\Credentials`, `${roaming}\\Microsoft\\Protect`, `${local}\\Microsoft\\Credentials`,+ `${local}\\Microsoft\\Vault`, `${roaming}\\Microsoft\\Vault`, `${roaming}\\Mozilla\\Firefox\\Profiles`,+ `${roaming}\\Opera Software`,+ ];+ }+ return [];+}++/** True when this path must not be opened: a hidden file or folder anywhere on it, a known secret store, or a name that+ * looks like a key or credential. Folding case where the file system does. */+export function outsideFileRefused(path: string, place: OutsideFilePlace = here()): boolean {+ const parts = segments(path);+ if (parts.some((part) => part.startsWith("."))) return true;+ const name = parts.at(-1) ?? "";+ if (SECRET_NAME.test(name)) return true;+ const folds = place.platform === "darwin" || place.platform === "win32";+ // Chromium-family browsers on Windows keep every profile under a "User Data" folder.+ if (place.platform === "win32" && parts.some((part) => part.toLowerCase() === "user data")) return true;+ const target = lowered(path, folds);+ return secretStores(place).some((store) => {+ const root = lowered(store, folds);+ return target === root || target.startsWith(`${root}/`);+ });+}