From 94a9db294afb4108c0957f1ab913477168c433fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Thu, 3 Dec 2026 07:45:37 +0000 Subject: [PATCH] The data and state directories are the person's alone (S2, L-S9) One ownDir() makes paths.data and paths.state 0700 and tightens an existing looser one; every writer of the two uses it. The session and library databases (and their -wal/-shm) and the prompt history are 0600, existing files included. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ src/acp/files.ts | 4 ++-- src/acp/hub.ts | 6 +++--- src/acp/pending.ts | 6 +++--- src/config/load.ts | 6 +++--- src/config/paths.ts | 21 ++++++++++++++++++++- src/library/store.ts | 6 +++--- src/mcp/oauth.ts | 6 +++--- src/project/files.ts | 6 +++--- src/project/init.ts | 4 ++-- src/project/root.ts | 4 ++-- src/service.ts | 4 ++-- src/session/store.ts | 7 ++++--- src/tui/history.ts | 9 +++++---- tests/own-files.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 15 files changed, 101 insertions(+), 34 deletions(-) create mode 100644 tests/own-files.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 02e8c85..09437f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,11 @@ All notable changes to LLeMbas CLI. The format follows directory the project's agent directory is `.lembas`, and with `remote files-that-run-code` off the web could still write its config (MCP servers), commands, agents and skills. Edit mode and the file manager now read one list of the files that run code. +- **Your sessions are no longer readable by other users of the computer.** The data and state + directories took whatever mode the first program to write them gave them, and the session + database was created readable by everyone on the machine. Both directories are now made — and, + when they already exist, set — readable by you alone, and so are the session and library + databases and the prompt history. - A folder whose name begins with two dots (`..cache`) inside an allowed folder is inside it. - **The force-push floor reads the push.** It refused any forced push with "main" somewhere in it (`feature/main-menu`) and missed deleting the branch (`git push origin :main`, diff --git a/src/acp/files.ts b/src/acp/files.ts index 077254c..b7bfa24 100644 --- a/src/acp/files.ts +++ b/src/acp/files.ts @@ -10,7 +10,7 @@ import { cp, rm } from "node:fs/promises" import { createHash } from "node:crypto" import { homedir } from "node:os" import { basename, dirname, isAbsolute, join, resolve } from "node:path" -import { expandHome, globalPaths, paths } from "../config/paths.ts" +import { expandHome, globalPaths, ownDir, paths } from "../config/paths.ts" import type { Mode } from "../config/schema.ts" import { LOOP } from "../harness.ts" import { realPath } from "../permission/evaluate.ts" @@ -182,7 +182,7 @@ function journal(change?: (list: string[]) => string[]): string[] { if (!change) return list const next = change(list) try { - mkdirSync(paths.state, { recursive: true, mode: 0o700 }) + ownDir(paths.state) writeFileSync(journalFile(), JSON.stringify(next), { mode: 0o600 }) } catch {} return next diff --git a/src/acp/hub.ts b/src/acp/hub.ts index f6db042..e0a6c96 100644 --- a/src/acp/hub.ts +++ b/src/acp/hub.ts @@ -17,10 +17,10 @@ // // The socket is the user's own (0600, in ~/.local/state/lembas). It answers JSON-RPC, one // message a line, the same framing as `serve --stdio`. -import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs" +import { chmodSync, existsSync, rmSync } from "node:fs" import { connect, createServer, type Server, type Socket } from "node:net" import { join } from "node:path" -import { isLocal, paths } from "../config/paths.ts" +import { isLocal, ownDir, paths } from "../config/paths.ts" import type { Mode } from "../config/schema.ts" import type { CommandInfo } from "../session/commands.ts" import { clampMode, keeps, occupied, refusalFor, type AcpAgent, type Limits } from "./agent.ts" @@ -140,7 +140,7 @@ export class Hub { /** Take the socket. False: another hub is alive on it. */ async listen(path = hubSocket()): Promise { if (isLocal()) return false - mkdirSync(paths.state, { recursive: true }) + ownDir(paths.state) if (existsSync(path)) { if (await answers(path)) return false rmSync(path, { force: true }) diff --git a/src/acp/pending.ts b/src/acp/pending.ts index dd26b79..55e12bd 100644 --- a/src/acp/pending.ts +++ b/src/acp/pending.ts @@ -12,9 +12,9 @@ // through a rename, so a reader never sees half of it; deduplicated; the newest DELETED_MAX kept — // a machine whose link never comes back must not grow it for ever, and a chat that old is long // out of anybody's mind. -import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs" +import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs" import { join } from "node:path" -import { isLocal, paths } from "../config/paths.ts" +import { isLocal, ownDir, paths } from "../config/paths.ts" export const DELETED_MAX = 500 @@ -33,7 +33,7 @@ export function pendingDeleted(): string[] { function write(ids: string[]) { const file = deletedFile() if (!ids.length) return void rmSync(file, { force: true }) - mkdirSync(paths.state, { recursive: true }) + ownDir(paths.state) const tmp = `${file}.${process.pid}.tmp` writeFileSync(tmp, JSON.stringify(ids), { mode: 0o600 }) renameSync(tmp, file) diff --git a/src/config/load.ts b/src/config/load.ts index d216298..dc5df03 100644 --- a/src/config/load.ts +++ b/src/config/load.ts @@ -1,9 +1,9 @@ import { match as wildcardMatch } from "../permission/wildcard.ts" -import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs" +import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs" import { join } from "node:path" import { isScalar, parse, parseDocument } from "yaml" import { z } from "zod" -import { connectionFiles, isLocal, paths } from "./paths.ts" +import { connectionFiles, isLocal, ownDir, paths } from "./paths.ts" import { asMode, Config, McpServer, PERSONALITIES, renamePermissionKeys, WebuiConnection, type Connection, type PermissionConfig } from "./schema.ts" import { substituteDeep } from "./substitute.ts" import { expandWebui, refreshFailures, type WebuiMark } from "../lembas/webui.ts" @@ -470,7 +470,7 @@ function migrateRef(file: string, key: string, old: string, now: string) { } } done[id] = now - mkdirSync(paths.state, { recursive: true }) + ownDir(paths.state) writeFileSync(record, JSON.stringify(done, null, 2) + "\n") } catch {} } diff --git a/src/config/paths.ts b/src/config/paths.ts index bf696dc..7879f22 100644 --- a/src/config/paths.ts +++ b/src/config/paths.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, mkdtempSync } from "node:fs" +import { chmodSync, existsSync, mkdirSync, mkdtempSync } from "node:fs" import { homedir, tmpdir } from "node:os" import { isAbsolute, join } from "node:path" @@ -59,6 +59,25 @@ export const paths = { }, } +/** One of LLeMbas CLI's own data or state directories: made 0700, and tightened to 0700 when it + * already exists with a looser mode (whichever writer came first used to decide, and sessions.db + * was readable by every local user). Returns the directory. */ +export function ownDir(p: string): string { + mkdirSync(p, { recursive: true, mode: 0o700 }) + try { + chmodSync(p, 0o700) + } catch {} + return p +} + +/** A file of the person's that holds what they wrote or were told (a database, a history): 0600, + * existing files included. Missing is fine. */ +export function ownFile(f: string) { + try { + chmodSync(f, 0o600) + } catch {} +} + export function expandHome(p: string): string { if (p === "~") return homedir() if (p.startsWith("~/")) return join(homedir(), p.slice(2)) diff --git a/src/library/store.ts b/src/library/store.ts index d3f7e4b..c60dfd1 100644 --- a/src/library/store.ts +++ b/src/library/store.ts @@ -6,9 +6,8 @@ // bases it searches (`knowledge:` in its config). import { Database } from "bun:sqlite" import { createHash } from "node:crypto" -import { mkdirSync } from "node:fs" import { join } from "node:path" -import { paths } from "../config/paths.ts" +import { ownDir, ownFile, paths } from "../config/paths.ts" import { anyOf, ftsQuery } from "../tool/session_search.ts" import { split } from "./chunks.ts" @@ -121,9 +120,10 @@ export class Library { readonly db: Database constructor(file = join(paths.data, "library.db")) { - mkdirSync(paths.data, { recursive: true }) + ownDir(paths.data) this.db = new Database(file, { create: true }) this.db.run("PRAGMA journal_mode = WAL") + for (const f of [file, `${file}-wal`, `${file}-shm`]) ownFile(f) this.db.run("PRAGMA foreign_keys = ON") this.db.exec(SCHEMA) } diff --git a/src/mcp/oauth.ts b/src/mcp/oauth.ts index d921912..99aa74d 100644 --- a/src/mcp/oauth.ts +++ b/src/mcp/oauth.ts @@ -4,11 +4,11 @@ // ~/.local/share/lembas/mcp-auth.json (mode 600), keyed by server and checked against its URL, // and catches the redirect on 127.0.0.1. A sign-in's state and PKCE verifier stay in memory, with // the sign-in: another LLeMbas CLI connecting meanwhile must not replace them. -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } from "node:fs" +import { existsSync, readFileSync, renameSync, writeFileSync, chmodSync } from "node:fs" import { join } from "node:path" import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js" import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js" -import { paths } from "../config/paths.ts" +import { ownDir, paths } from "../config/paths.ts" import type { McpServer } from "../config/schema.ts" export const CALLBACK_PORT = 19876 @@ -35,7 +35,7 @@ function readAll(strict = false): Record { } function writeAll(all: Record) { - mkdirSync(paths.data, { recursive: true }) + ownDir(paths.data) const tmp = `${file()}.${process.pid}.tmp` writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 0o600 }) chmodSync(tmp, 0o600) diff --git a/src/project/files.ts b/src/project/files.ts index 9ea0008..e406b59 100644 --- a/src/project/files.ts +++ b/src/project/files.ts @@ -1,9 +1,9 @@ // The project's file list for @ completion: ripgrep when present (honours .gitignore), a walk // otherwise; refreshed at most every few seconds. Ranked with fuzzysort, nudged by frecency. -import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs" +import { readFileSync, statSync, writeFileSync } from "node:fs" import { join } from "node:path" import fuzzysort from "fuzzysort" -import { paths } from "../config/paths.ts" +import { ownDir, paths } from "../config/paths.ts" const MAX = 50_000 const IGNORED = ["node_modules", ".git", "dist", "build", ".venv", "venv", "__pycache__", "target", ".next", ".cache"] @@ -86,7 +86,7 @@ export class FileIndex { const all = readFrecency() all[this.root] = this.frecency try { - mkdirSync(paths.state, { recursive: true }) + ownDir(paths.state) writeFileSync(join(paths.state, "frecency.json"), JSON.stringify(all)) } catch {} } diff --git a/src/project/init.ts b/src/project/init.ts index e09c150..75746a5 100644 --- a/src/project/init.ts +++ b/src/project/init.ts @@ -1,7 +1,7 @@ // The first time LLeMbas CLI opens a directory: trust, git, and the .agent skeleton. import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs" import { join, relative } from "node:path" -import { paths } from "../config/paths.ts" +import { ownDir, paths } from "../config/paths.ts" import type { Project } from "./root.ts" const CONFIG_TEMPLATE = `# LLeMbas CLI settings for this project. Merged over ~/.config/lembas/config.yaml, @@ -66,6 +66,6 @@ export function neverGitInit(root: string): boolean { export function setNeverGitInit(root: string) { const p = readPrefs() p[root] = { ...p[root], gitInit: "never" } - mkdirSync(paths.state, { recursive: true }) + ownDir(paths.state) writeFileSync(prefsFile(), JSON.stringify(p, null, 2)) } diff --git a/src/project/root.ts b/src/project/root.ts index cecd550..2b36cfe 100644 --- a/src/project/root.ts +++ b/src/project/root.ts @@ -2,7 +2,7 @@ import { within } from "../within.ts" import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs" import { dirname, join, resolve } from "node:path" import { parseDocument } from "yaml" -import { paths } from "../config/paths.ts" +import { ownDir, paths } from "../config/paths.ts" import type { Rule } from "../permission/evaluate.ts" import { assertProjectFile } from "./safe.ts" @@ -110,7 +110,7 @@ export function trustedWithin(dir: string): boolean { export function setTrust(root: string, level: TrustLevel) { const t = readTrust() t[resolve(root)] = level - mkdirSync(paths.state, { recursive: true }) + ownDir(paths.state) writeFileSync(trustFile(), JSON.stringify(t, null, 2)) } diff --git a/src/service.ts b/src/service.ts index 763ba9c..f0288fa 100644 --- a/src/service.ts +++ b/src/service.ts @@ -13,7 +13,7 @@ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs" import { homedir } from "node:os" import { join } from "node:path" -import { paths } from "./config/paths.ts" +import { ownDir, paths } from "./config/paths.ts" import { LinkError, limitsFromConfig, runLink, type LinkStatus } from "./acp/link.ts" import { Hub } from "./acp/hub.ts" @@ -151,7 +151,7 @@ export function holdsLock(pid: number): boolean { * made exclusively (never checked and then written: two starting together would both pass the * check), and a lock whose holder is gone is taken over. */ export function takeLock(file = lockFile()): () => void { - mkdirSync(paths.state, { recursive: true }) + ownDir(paths.state) const release = () => { // Only this process's own: a lock taken over meanwhile is the other's. try { diff --git a/src/session/store.ts b/src/session/store.ts index 1f51032..e24e1e5 100644 --- a/src/session/store.ts +++ b/src/session/store.ts @@ -1,7 +1,6 @@ import { Database } from "bun:sqlite" -import { mkdirSync } from "node:fs" import { join } from "node:path" -import { paths } from "../config/paths.ts" +import { ownDir, ownFile, paths } from "../config/paths.ts" import type { Message, Usage } from "../provider/types.ts" import { isNote } from "./prefix.ts" @@ -109,9 +108,11 @@ export class Store { readonly db: Database constructor(file = join(paths.data, "sessions.db")) { - if (file !== ":memory:") mkdirSync(paths.data, { recursive: true }) + if (file !== ":memory:") ownDir(paths.data) this.db = new Database(file, { create: true }) this.db.run("PRAGMA journal_mode = WAL") + // Every conversation is in here: the person's alone, an existing file tightened too. + if (file !== ":memory:") for (const f of [file, `${file}-wal`, `${file}-shm`]) ownFile(f) // Several writers share this file: every terminal, the service, and in the service one // connection per session it holds. Without a timeout a write that meets another's lock fails at // once with "database is locked" — a delete from the web UI among them, which the instance then diff --git a/src/tui/history.ts b/src/tui/history.ts index e9645ac..33e1c1c 100644 --- a/src/tui/history.ts +++ b/src/tui/history.ts @@ -1,6 +1,6 @@ -import { appendFileSync, mkdirSync, readFileSync } from "node:fs" +import { appendFileSync, readFileSync } from "node:fs" import { join } from "node:path" -import { paths } from "../config/paths.ts" +import { ownDir, ownFile, paths } from "../config/paths.ts" // Prompt history, shared across projects, newest last: ~/.local/state/lembas/history.jsonl. const MAX = 500 @@ -24,8 +24,9 @@ export class History { if (!text.trim() || this.items[this.items.length - 1] === text) return this.reset() this.items.push(text) try { - mkdirSync(paths.state, { recursive: true }) - appendFileSync(this.file, JSON.stringify(text) + "\n") + ownDir(paths.state) + appendFileSync(this.file, JSON.stringify(text) + "\n", { mode: 0o600 }) + ownFile(this.file) } catch {} this.reset() } diff --git a/tests/own-files.test.ts b/tests/own-files.test.ts new file mode 100644 index 0000000..c736c4b --- /dev/null +++ b/tests/own-files.test.ts @@ -0,0 +1,41 @@ +// The CLI's own data and state directories are the person's alone (S2): made 0700, an existing +// looser one tightened; the session database 0600 even when it was made with a looser mode. +import { afterEach, beforeEach, expect, test } from "bun:test" +import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { ownDir, paths } from "../src/config/paths.ts" +import { Store } from "../src/session/store.ts" + +let home: string +let before: string | undefined +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "lembas-own-")) + before = process.env.LEMBAS_HOME + process.env.LEMBAS_HOME = home +}) +afterEach(() => { + if (before === undefined) delete process.env.LEMBAS_HOME + else process.env.LEMBAS_HOME = before + rmSync(home, { recursive: true, force: true }) +}) + +const mode = (p: string) => statSync(p).mode & 0o777 + +test("a new directory is 0700, an existing looser one is tightened", () => { + expect(mode(ownDir(paths.state))).toBe(0o700) + chmodSync(paths.state, 0o775) + expect(mode(ownDir(paths.state))).toBe(0o700) +}) + +test("the session database and its directory are the person's alone, existing ones included", () => { + mkdirSync(paths.data, { recursive: true, mode: 0o775 }) + chmodSync(paths.data, 0o775) + const file = join(paths.data, "sessions.db") + writeFileSync(file, "") + chmodSync(file, 0o644) + const s = new Store() + s.db.close() + expect(mode(paths.data)).toBe(0o700) + expect(mode(file)).toBe(0o600) +})