Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(workflows): harden reconciled artifact history reads

Rahman3230585468d3
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 195a6880..d6014732 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,27 @@
+## 2026-09-17 — Recover dormant PR/branch work without overwriting active agents
+
+Reconciled the verified performance candidate, the preserved GitHub OAuth-first preference,
+the dormant exact-session-artifact history candidate, and fork PR #44's edge/directory
+improvements onto the current main lineage in an isolated worktree. Newer semantic session
+labels, script/learning directories, read-only session graphs and VPS-backed Store behavior
+are preserved instead of taking the older fork files wholesale. Original candidate branches
+remain recoverable until integration is complete. Active hosted/Hermes and gateway work is
+owned by other sessions and is not replaced or deployed by this reconciliation.
+
+Historical artifact previews now reapply current host read-root/credential policy, refuse
+symlink aliases, use bounded no-follow descriptor reads with post-open path identity checks,
+and compute diffs from the same verified byte buffers. Git blob identity is computed from
+already-read bytes, eliminating diff/hash-object subprocesses and repository filters during
+capture. No file body is persisted in the event metadata. PTY access remains scoped to its
+creating principal. Added denial coverage for restricted paths, symlink escapes and revoked
+read roots; synthetic test roots explicitly grant only their own read/write access.
+
+The audit records every observed branch, worktree and PR with a disposition. Normal Git
+cleanup removes only clean, dormant worktrees whose HEAD is already reachable from main;
+active/dirty/unmerged trees, local environments and referenced dependencies remain protected.
+A verified private Git bundle and ignored-note backups precede cleanup. Detailed verification
+and release status belong to the workflow evidence; this entry does not claim deployment.
+
## 2026-09-17 — GitHub OAuth-first Integrations routing
GitHub Connections now present hosted OAuth and provider-owned OAuth/MCP before the manual PAT fallback. The direct GitHub path remains available without capability loss, but it is explicitly labeled as a fallback and recommends an expiring fine-grained token when a direct credential is deliberately required. `/integrations` now states the no-silent-fallback rule: a failed OAuth/MCP identity must never be replaced by another PAT/principal implicitly. This complements Baton tenant OAuth, which remains a separate user/workspace trust boundary instead of copying customer OAuth tokens into the MSO operator vault.
diff --git a/lib/agent/session-artifact-history.test.ts b/lib/agent/session-artifact-history.test.ts
index 6ee11b82..eef8bac1 100644
--- a/lib/agent/session-artifact-history.test.ts
+++ b/lib/agent/session-artifact-history.test.ts
@@ -1,13 +1,15 @@
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { execFileSync } from "node:child_process";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { captureSessionArtifactRevision, resolveArtifactRevisionView } from "./session-artifact-history";
const roots: string[] = [];
afterEach(async () => {
+ vi.unstubAllEnvs();
delete process.env.OS_FS_WRITE_ROOTS;
+ delete process.env.OS_FS_READ_ROOTS;
while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });
});
@@ -17,7 +19,7 @@ function git(cwd: string, ...args: string[]) {
async function fixture() {
const root = await mkdtemp(path.join(os.tmpdir(), "mso-artifact-history-"));
- roots.push(root); process.env.OS_FS_WRITE_ROOTS = root;
+ roots.push(root); process.env.OS_FS_WRITE_ROOTS = root; process.env.OS_FS_READ_ROOTS = root;
git(root, "init", "-b", "main");
git(root, "config", "user.email", "[email protected]"); git(root, "config", "user.name", "MSO Test");
await writeFile(path.join(root, "app.ts"), "export const value = 1;\n", "utf8");
@@ -65,6 +67,27 @@ describe("session artifact revision proof", () => {
expect(view.diff).toMatchObject({ available: true, changed: false });
});
+ it("denies credential paths and symlink escapes before capture", async () => {
+ const root = await fixture();
+ vi.stubEnv("HOME", root);
+ await mkdir(path.join(root, ".mso"));
+ await writeFile(path.join(root, ".mso", "private.json"), '{"private":true}');
+ expect(await captureSessionArtifactRevision({ kind: "tool", tool: "fs_write", detail: ".mso/private.json" }, root)).toBeUndefined();
+ const outside = await mkdtemp(path.join(os.tmpdir(), "mso-history-outside-")); roots.push(outside);
+ await writeFile(path.join(outside, "private.ts"), "private bytes");
+ await symlink(outside, path.join(root, "alias"));
+ expect(await captureSessionArtifactRevision({ kind: "tool", tool: "fs_write", detail: "alias/private.ts" }, root)).toBeUndefined();
+ });
+
+ it("rechecks read access before returning an existing historical blob", async () => {
+ const root = await fixture();
+ const revision = await captureSessionArtifactRevision({ kind: "tool", tool: "fs_write", detail: "app.ts" }, root);
+ expect(revision?.headBlob).toBeDefined();
+ const other = await mkdtemp(path.join(os.tmpdir(), "mso-history-new-root-")); roots.push(other);
+ process.env.OS_FS_READ_ROOTS = other;
+ expect(await resolveArtifactRevisionView(revision)).toMatchObject({ historical: { available: false }, current: { available: false } });
+ });
+
it("keeps read-only/legacy events metadata-free rather than pretending a snapshot exists", async () => {
const root = await fixture();
expect(await captureSessionArtifactRevision({ kind: "tool", tool: "fs_read", detail: "app.ts" }, root)).toBeUndefined();
diff --git a/lib/agent/session-artifact-history.ts b/lib/agent/session-artifact-history.ts
index 082b2c7b..2a886150 100644
--- a/lib/agent/session-artifact-history.ts
+++ b/lib/agent/session-artifact-history.ts
@@ -7,11 +7,12 @@ import { childEnv } from "@/lib/host/child-env";
import { resolveCwd } from "@/lib/host/exec";
import { redactText } from "@/lib/security/redact-text";
import { resolveSessionArtifactCandidate } from "./session-artifact-path";
+import { ARTIFACT_FILE_LIMIT, authorizeArtifactPath, readArtifactFile as regularFileInfo } from "./session-artifact-read";
import type { AgentSessionArtifactRevision, AgentSessionEvent } from "./session-types";
const OID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
const SHA256 = /^[a-f0-9]{64}$/i;
-const MAX_FILE_BYTES = 4 * 1024 * 1024;
+const MAX_FILE_BYTES = ARTIFACT_FILE_LIMIT;
const MAX_SNAPSHOT_TEXT = 128 * 1024;
const MAX_DIFF_BYTES = 256 * 1024;
const GIT_TIMEOUT_MS = 5_000;
@@ -42,16 +43,6 @@ async function git(cwd: string, args: string[], maxBytes = MAX_DIFF_BYTES): Prom
});
}
-async function regularFileInfo(file: string): Promise<{ bytes: Buffer; sha256: string; size: number } | null> {
- try {
- const stat = await fs.lstat(file);
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size < 0 || stat.size > MAX_FILE_BYTES) return null;
- const bytes = await fs.readFile(file);
- if (bytes.length !== stat.size || bytes.length > MAX_FILE_BYTES) return null;
- return { bytes, sha256: createHash("sha256").update(bytes).digest("hex"), size: bytes.length };
- } catch { return null; }
-}
-
function safeRel(value: string): boolean {
return Boolean(value && !path.isAbsolute(value) && value !== ".." && !value.startsWith("../") && !value.includes("\0"));
}
@@ -80,7 +71,7 @@ export async function captureSessionArtifactRevision(event: Pick<AgentSessionEve
const dir = await resolveCwd(cwd).catch(() => null);
if (!dir) return undefined;
const candidate = resolveSessionArtifactCandidate(event.detail, dir);
- if (!candidate) return undefined;
+ if (!candidate || !await authorizeArtifactPath(candidate.path)) return undefined;
const current = await regularFileInfo(candidate.path);
const base: AgentSessionArtifactRevision = {
version: 1, cwd: dir, relativePath: candidate.relativePath,
@@ -97,14 +88,11 @@ export async function captureSessionArtifactRevision(event: Pick<AgentSessionEve
if (!safeRel(repoRel)) return base;
const tree = await git(repoRoot, ["ls-tree", "-z", "HEAD", "--", repoRel], 32 * 1024);
const headBlob = tree.code === 0 ? parseLsTree(tree.stdout, repoRel) : undefined;
- let cleanAtCapture = false, worktreeBlob: string | undefined;
- const diff = await git(repoRoot, ["diff", "--quiet", "HEAD", "--", repoRel], 8 * 1024).catch(() => null);
- cleanAtCapture = Boolean(current && headBlob && diff?.code === 0);
- if (current) {
- const hashed = await git(repoRoot, ["hash-object", "--no-filters", "--", candidate.path], 8 * 1024).catch(() => null);
- const oid = hashed?.stdout.toString("utf8").trim().toLowerCase();
- if (hashed?.code === 0 && oid && OID.test(oid)) worktreeBlob = oid;
- }
+ // Git blob IDs are content hashes; compute from the already-read bytes instead
+ // of spawning diff/hash-object or running repository filters for every event.
+ const worktreeBlob = current ? createHash(head.length === 64 ? "sha256" : "sha1")
+ .update(`blob ${current.size}\0`).update(current.bytes).digest("hex") : undefined;
+ const cleanAtCapture = Boolean(current && headBlob && headBlob === worktreeBlob);
return {
...base, repoRoot, repoRelativePath: repoRel, gitHead: head,
...(headBlob ? { headBlob } : {}), ...(worktreeBlob ? { worktreeBlob } : {}), cleanAtCapture,
@@ -144,13 +132,15 @@ async function exactSnapshot(revision: AgentSessionArtifactRevision, current: Aw
return null;
}
-async function unifiedDiff(relativePath: string, historical: Buffer, currentPath: string): Promise<{ text: string; changed: boolean } | null> {
+async function unifiedDiff(relativePath: string, historical: Buffer, current: Buffer): Promise<{ text: string; changed: boolean } | null> {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-artifact-diff-"));
await fs.chmod(root, 0o700).catch(() => undefined);
const oldFile = path.join(root, `${randomUUID()}.old`);
+ const currentPath = path.join(root, `${randomUUID()}.new`);
try {
await fs.writeFile(oldFile, historical, { mode: 0o600, flag: "wx" });
- const result = await git(root, ["diff", "--no-index", "--no-ext-diff", "--unified=3", "--", oldFile, currentPath], MAX_DIFF_BYTES).catch(() => null);
+ await fs.writeFile(currentPath, current, { mode: 0o600, flag: "wx" });
+ const result = await git(root, ["diff", "--no-index", "--no-ext-diff", "--no-textconv", "--unified=3", "--", oldFile, currentPath], MAX_DIFF_BYTES).catch(() => null);
if (!result || (result.code !== 0 && result.code !== 1)) return null;
let text = result.stdout.toString("utf8");
text = text.replaceAll(oldFile, `a/${relativePath}`).replaceAll(currentPath, `b/${relativePath}`);
@@ -173,10 +163,16 @@ export async function resolveArtifactRevisionView(revision: AgentSessionArtifact
const currentPath = path.resolve(captureCwd, revision.relativePath);
const relCheck = path.relative(captureCwd, currentPath);
if (!relCheck || relCheck === ".." || relCheck.startsWith(`..${path.sep}`) || path.isAbsolute(relCheck)) throw new Error("artifact revision escaped capture root");
+ if (!await authorizeArtifactPath(currentPath)) return {
+ capture: { state: "captured" as const, exactAtCapture: false },
+ current: { available: false as const },
+ historical: { available: false as const, reason: "path_unavailable" },
+ diff: { available: false as const, reason: "path_unavailable" },
+ };
const current = await regularFileInfo(currentPath);
const historical = await exactSnapshot(revision, current);
const snapshotSha = historical ? createHash("sha256").update(historical.bytes).digest("hex") : undefined;
- const diff = historical && current ? await unifiedDiff(revision.relativePath, historical.bytes, currentPath) : null;
+ const diff = historical && current ? await unifiedDiff(revision.relativePath, historical.bytes, current.bytes) : null;
return {
capture: {
state: "captured" as const, exactAtCapture: Boolean(revision.cleanAtCapture && revision.headBlob), sha256: revision.worktreeSha256, bytes: revision.bytes,
diff --git a/lib/agent/session-artifact-read.ts b/lib/agent/session-artifact-read.ts
new file mode 100644
index 00000000..55d37b99
--- /dev/null
+++ b/lib/agent/session-artifact-read.ts
@@ -0,0 +1,55 @@
+import { constants, promises as fs } from "node:fs";
+import { createHash } from "node:crypto";
+import path from "node:path";
+import { isCredentialPath, resolveReadable } from "@/lib/host/paths";
+
+export const ARTIFACT_FILE_LIMIT = 4 * 1024 * 1024;
+
+/** Reapply current host policy even when reading a historical blob of a deleted file. */
+export async function authorizeArtifactPath(file: string): Promise<string | null> {
+ const absolute = path.resolve(file);
+ if (isCredentialPath(absolute)) return null;
+ try {
+ const real = await resolveReadable(absolute);
+ // Captures must name the actual file, not a mutable symlink alias.
+ return real === absolute ? real : null;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return null;
+ try {
+ const parent = await resolveReadable(path.dirname(absolute));
+ return parent === path.dirname(absolute) ? absolute : null;
+ } catch { return null; }
+ }
+}
+
+/** Descriptor-based, bounded read: never follow a last-component symlink or read a growing file unboundedly. */
+export async function readArtifactFile(file: string): Promise<{ bytes: Buffer; sha256: string; size: number } | null> {
+ const real = await authorizeArtifactPath(file);
+ if (!real) return null;
+ let handle;
+ try {
+ handle = await fs.open(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const before = await handle.stat();
+ // Re-resolve after opening to reject a parent symlink changed between guard and open.
+ const authorized = await authorizeArtifactPath(file);
+ if (authorized !== real) return null;
+ const named = await fs.lstat(real);
+ if (named.dev !== before.dev || named.ino !== before.ino) return null;
+ if (!before.isFile() || before.size > ARTIFACT_FILE_LIMIT) return null;
+ const buffer = Buffer.alloc(before.size + 1);
+ let length = 0;
+ while (length < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
+ if (!bytesRead) break;
+ length += bytesRead;
+ }
+ const after = await handle.stat();
+ if (length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) return null;
+ if (await authorizeArtifactPath(file) !== real) return null;
+ const finalPath = await fs.lstat(real);
+ if (finalPath.dev !== before.dev || finalPath.ino !== before.ino) return null;
+ const bytes = buffer.subarray(0, length);
+ return { bytes, sha256: createHash("sha256").update(bytes).digest("hex"), size: bytes.length };
+ } catch { return null; }
+ finally { await handle?.close(); }
+}
diff --git a/lib/mcp/tools-agent.test.ts b/lib/mcp/tools-agent.test.ts
index b521e782..857685a2 100644
--- a/lib/mcp/tools-agent.test.ts
+++ b/lib/mcp/tools-agent.test.ts
@@ -7,7 +7,8 @@ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-tools-agent-p1-"));
process.env.OS_AGENT_MEMORY_DIR = root;
process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");
process.env.OS_FS_WRITE_ROOTS = root;
-afterAll(async () => { delete process.env.OS_AGENT_MEMORY_DIR; delete process.env.OS_AGENT_SESSIONS_DIR; delete process.env.OS_FS_WRITE_ROOTS; await fs.rm(root, { recursive: true, force: true }); });
+process.env.OS_FS_READ_ROOTS = root;
+afterAll(async () => { delete process.env.OS_AGENT_MEMORY_DIR; delete process.env.OS_AGENT_SESSIONS_DIR; delete process.env.OS_FS_WRITE_ROOTS; delete process.env.OS_FS_READ_ROOTS; await fs.rm(root, { recursive: true, force: true }); });
vi.resetModules();
const { AGENT_TOOLS } = await import("./tools-agent");