Keep every bot's computer work in its own workspace folder

Computers now mount only /home/gem/workspace from DATA_DIR/computers/<id>,
so only the workspace persists and goes into the data archive. An older
computer's whole home is moved aside to <id>-home-<ts> (kept, never
archived) and its container recreated once by sync-computers.

Each run works in bots/<bot>/users/<user> (also its cwd and HOME), with
bots/<bot> for work every user shares and workspaces/<id> shared by a
workspace's bots; the coordinator reaches the whole workspace. Computer
tools are gated by withComputerDirs: bash and code start there, file tool
paths and file: URLs outside the run's folders are refused, and so is sudo.
search_computers, import_file and script tools start there too.

The files browser shows members only the bots' folders they reach, their
own user folder in each and their workspaces', with names on the id folders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-25 08:24:49 +01:00
co-authored by Claude Opus 5.5
parent fefc295d15
commit 86becd50bc
41 changed files with 1012 additions and 105 deletions
@@ -0,0 +1,87 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import reachableBotsSql from "@/src/utils/crew-access/reachable-bots-sql";
import workspacesSql from "@/src/utils/crew-access/workspaces-sql";
import type { CrewRole } from "@/src/utils/rbac/crew-role";
type Params = {
role: CrewRole;
user_id: number | string;
};
export type ComputerFolderAccess = {
/**
* What `computerPathAllowed` needs about the user.
*/
manages_crew: boolean;
user_id: number;
bot_ids: number[];
workspace_ids: number[];
/**
* Names for the workspace's id folders (`bots/<id>`, `users/<id>`,
* `workspaces/<id>`), the ones the user may see.
*/
names: {
bots: Record<string, string>;
users: Record<string, string>;
workspaces: Record<string, string>;
};
};
/**
* Which of a computer's workspace folders a user may open in the files
* browser, and what they are called: the bots and workspaces they reach,
* by the same crew SQL as the rest of the app. Crew managers see every
* one, and every user's folder in them.
*/
export default async function grabComputerFolderAccess({
role,
user_id,
}: Params): Promise<ComputerFolderAccess> {
const manages_crew = role != "member";
const bot_access = reachableBotsSql({ role, user_id });
const workspace_access = workspacesSql({ role, user_id });
const [bots, workspaces, users] = await Promise.all([
rows<{ id: number; name?: string | null }>({
sql: `SELECT b.id, b.name FROM bots b WHERE ${bot_access.sql}`,
values: bot_access.values,
}),
rows<{ id: number; name?: string | null }>({
sql: `SELECT w.id, w.name FROM workspaces w WHERE ${workspace_access.sql}`,
values: workspace_access.values,
}),
rows<{ id: number; first_name?: string | null; last_name?: string | null; username?: string | null }>({
sql: `SELECT id, first_name, last_name, username FROM users${manages_crew ? "" : " WHERE id = ?"}`,
values: manages_crew ? [] : [Number(user_id)],
}),
]);
return {
manages_crew,
user_id: Number(user_id),
bot_ids: bots.map((bot) => Number(bot.id)),
workspace_ids: workspaces.map((workspace) => Number(workspace.id)),
names: {
bots: Object.fromEntries(bots.map((bot) => [String(bot.id), bot.name || `Bot ${bot.id}`])),
workspaces: Object.fromEntries(
workspaces.map((workspace) => [String(workspace.id), workspace.name || `Workspace ${workspace.id}`]),
),
users: Object.fromEntries(
users.map((user) => [
String(user.id),
[user.first_name, user.last_name].filter(Boolean).join(" ") || user.username || `User ${user.id}`,
]),
),
},
};
}
async function rows<T extends { [k: string]: any }>({
sql,
values,
}: {
sql: string;
values: (string | number)[];
}) {
return (await BunSQLite.sql<T>({ sql, values })).payload || [];
}
@@ -2,6 +2,7 @@ import { statSync } from "node:fs";
import path from "node:path";
import { AppData } from "@/src/data/app-data";
import { mimeTypeForFile } from "../db/bot-files/media-type-for-file";
import { canSeePath } from "./list-storage-entries";
import resolveStoragePath from "./resolve-storage-path";
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
@@ -31,7 +32,8 @@ export type StorageFile = {
/**
* One file for the browser to open: checked to be inside the volume (the
* same rules a bot's own path gets), to exist, and to be a regular file
* rather than a folder. Null when it isn't one, so a caller can answer
* rather than a folder, and one the user may see in a computer's workspace
* (`canSeePath`). Null when it isn't one, so a caller can answer
* "not found" without leaking what is there.
*/
export default function grabStorageFile({ resolved, path: requested }: Params): StorageFile | null {
@@ -39,6 +41,8 @@ export default function grabStorageFile({ resolved, path: requested }: Params):
if (!resolved_path.name) return null;
if (!canSeePath({ resolved, path: resolved_path.relative })) return null;
let stats;
try {
@@ -4,6 +4,8 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_FILES } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import grabMediaURL from "../media/grab-media-url";
import computerFolderLabel from "@/src/utils/computer-folder-label";
import computerPathAllowed from "@/src/utils/computer-path-allowed";
import { isInsideRoot } from "./resolve-storage-path";
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
import {
@@ -52,13 +54,20 @@ export type StorageEntry = {
* browser's own streaming route.
*/
url?: string;
/**
* What an id folder in a computer's workspace is: the bot's, user's or
* workspace's name.
*/
label?: string;
};
/**
* One directory on the data volume, for the files browser: its entries
* (folders first), a page of them, and a `bot_files` row attached to any
* that has one. Entries a symlink leads out of the volume with are left
* out, so nothing outside the folder is ever listed.
* out, so nothing outside the folder is ever listed. In a computer's
* workspace only what the user may see is listed (`computerPathAllowed`),
* and a folder they may not see reads as missing.
*/
export default async function listStorageEntries({
resolved,
@@ -74,7 +83,9 @@ export default async function listStorageEntries({
* all, which a stale folder link lands on (the page says so, instead of
* claiming the folder is empty).
*/
if (!existsSync(absolute)) return { entries: [], total: 0, offset, missing: true };
if (!existsSync(absolute) || !canSeePath({ resolved, path: relative })) {
return { entries: [], total: 0, offset, missing: true };
}
const rows = readdirSync(absolute, { withFileTypes: true });
const indexed = await botFileRows({ resolved, paths: rows.map((row) => joinPath({ relative, name: row.name })) });
@@ -86,6 +97,8 @@ export default async function listStorageEntries({
const entry_path = joinPath({ relative, name: row.name });
if (!canSeePath({ resolved, path: entry_path })) continue;
if (needle && !entry_path.toLowerCase().includes(needle)) continue;
const entry_absolute = path.join(absolute, row.name);
@@ -114,6 +127,9 @@ export default async function listStorageEntries({
size: 0,
modified_at: Math.round(stats.mtimeMs),
url: storageSpecHref({ spec: resolved.spec, path: entry_path }),
label: resolved.computer
? computerFolderLabel({ path: entry_path, names: resolved.computer.names }) || undefined
: undefined,
});
continue;
}
@@ -197,6 +213,14 @@ async function botFileRows({
return rows;
}
/**
* Whether the user may see a path in the folder: anything in it, except
* inside a computer's workspace (`computerPathAllowed`).
*/
export function canSeePath({ resolved, path }: { resolved: ResolvedStorageSpec; path: string }) {
return !resolved.computer || computerPathAllowed({ ...resolved.computer, path });
}
function joinPath({ relative, name }: { relative: string; name: string }) {
return relative ? `${relative}/${name}` : name;
}
@@ -63,7 +63,7 @@ describe("resolveStoragePath", () => {
test("refuses a path that is too deep", () => {
expect(() =>
resolveStoragePath({ root, path: Array.from({ length: 12 }, (_, i) => `f${i}`).join("/") }),
resolveStoragePath({ root, path: Array.from({ length: 20 }, (_, i) => `f${i}`).join("/") }),
).toThrow();
});
});
@@ -78,9 +78,9 @@ export default function resolveStoragePath({
}
}
if (segments.length > AppData.BotFilePathMaxDepth) {
if (segments.length > AppData.StorageBrowserMaxDepth) {
throw new AppError(
`That path is too deep: at most ${AppData.BotFilePathMaxDepth} folders.`,
`That path is too deep: at most ${AppData.StorageBrowserMaxDepth} folders.`,
);
}
@@ -8,9 +8,10 @@ import grabDirNames from "@/src/utils/grab-dir-names";
import type { CrewRole } from "@/src/utils/rbac/crew-role";
import { storageVolumeLabel, type StorageSpec } from "@/src/utils/storage-volumes";
import grabCrewRole from "../db/access/grab-crew-role";
import grabComputerFolderAccess from "./grab-computer-folder-access";
import grabUserBot from "../db/bots/grab-user-bot";
import grabUserComputer from "../db/computers/grab-user-computer";
import resolveComputerHomeDir from "../db/computers/resolve-computer-home-dir";
import resolveComputerWorkspaceDir from "../db/computers/resolve-computer-workspace-dir";
import grabEnv from "../db/envs/grab-env";
import grabUserWorkspace from "../db/workspaces/grab-user-workspace";
@@ -29,7 +30,9 @@ type Params = {
* crew uses (`grabUserBot`, `grabUserWorkspace`, `grabUserComputer`, so a
* member sees only their own grants); their own media folder, and only
* their own whatever their role; an MCP server's install folder for crew
* managers; the database for the super admin alone.
* managers; the database for the super admin alone. Inside a computer's
* workspace a member sees only their bots' folders, their own user folder
* in each, and their workspaces' (`computerPathAllowed`).
*/
export default async function resolveStorageSpec({ user_id, spec }: Params) {
const role = await grabCrewRole({ user_id });
@@ -41,6 +44,11 @@ export default async function resolveStorageSpec({ user_id, spec }: Params) {
spec,
root,
label: await storageLabel({ spec, role, user_id }),
/**
* A computer's workspace: which of its folders the user may see,
* and their names (`computerPathAllowed`, `computerFolderLabel`).
*/
computer: spec.volume == "computers" ? await grabComputerFolderAccess({ role, user_id }) : null,
};
}
@@ -76,7 +84,7 @@ async function storageRoot({
if (!computer) return null;
return resolveComputerHomeDir({
return resolveComputerWorkspaceDir({
computer_id: spec.owner_id,
kind: computer.kind,
metadata: await computerContainerMetadata({ container_id: computer.container_id }),