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.

3.4 KB
Raw Blame
// Host-owned runtime data is not a build asset; tracing exclusions preserve runtime guards.
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { parse, stringify } from "yaml";

// Persistent Alfa chat threads — one YAML file per thread under ~/.mso/threads/.
// YAML (not JSON) so the session files stay human-readable (owner's call). `messages`
// = the display bubbles; `history` = the wire turns needed to CONTINUE the chat.
// Both are opaque to the server (stored/restored verbatim); the client owns the shape.
export interface ChatThread {
  id: string;
  title: string;
  createdAt: number;
  updatedAt: number;
  messages: unknown[];
  history: unknown[];
}

export type ThreadSummary = Pick<ChatThread, "id" | "title" | "createdAt" | "updatedAt">;

const DIR = path.resolve(/* turbopackIgnore: true */ process.env.OS_THREADS_DIR || path.join(os.homedir(), ".mso", "threads"));
const THREAD_ID = /^[A-Za-z0-9_-]{1,64}$/;

// ids are app-generated but still arrive over HTTP. Keep the allowlist, then use
// an explicit path.relative containment guard before a filesystem sink. The
// latter is both symlink-independent lexical defence and a pattern CodeQL can
// verify rather than having to trust a project-specific sanitizer helper.
function fileFor(id: string): string {
  if (!THREAD_ID.test(id)) throw new Error("invalid thread id");
  const candidate = path.resolve(DIR, `${id}.yml`);
  const relative = path.relative(DIR, candidate);
  if (relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative)) {
    throw new Error("invalid thread id");
  }
  return candidate;
}

export async function listThreads(): Promise<ThreadSummary[]> {
  let names: string[];
  try {
    names = await fs.readdir(/* turbopackIgnore: true */ DIR);
  } catch {
    return [];
  }
  const out: ThreadSummary[] = [];
  for (const n of names) {
    if (!n.endsWith(".yml")) continue;
    try {
      const t = parse(await fs.readFile(/* turbopackIgnore: true */ path.join(DIR, n), "utf8")) as ChatThread;
      if (t?.id) out.push({ id: t.id, title: t.title || "Untitled", createdAt: t.createdAt || 0, updatedAt: t.updatedAt || 0 });
    } catch {
      /* skip corrupt file */
    }
  }
  return out.sort((a, b) => b.updatedAt - a.updatedAt);
}

export async function getThread(id: string): Promise<ChatThread | null> {
  const file = fileFor(id); // validate before the not-found/corrupt-file catch
  try {
    return parse(await fs.readFile(/* turbopackIgnore: true */ file, "utf8")) as ChatThread;
  } catch {
    return null;
  }
}

export async function saveThread(t: ChatThread): Promise<void> {
  await fs.mkdir(DIR, { recursive: true, mode: 0o700 });
  const dest = fileFor(t.id);
  const tmp = `${dest}.tmp`;
  await fs.writeFile(tmp, stringify(t), { encoding: "utf8", mode: 0o600 });
  await fs.rename(tmp, dest);
}

export async function renameThread(id: string, title: string): Promise<ThreadSummary | null> {
  const t = await getThread(id);
  if (!t) return null;
  t.title = title.trim().slice(0, 120) || "Untitled";
  t.updatedAt = Date.now();
  await saveThread(t);
  return { id: t.id, title: t.title, createdAt: t.createdAt || 0, updatedAt: t.updatedAt };
}

export async function deleteThread(id: string): Promise<void> {
  const file = fileFor(id); // invalid ids are authorization/input errors, not "already gone"
  try {
    await fs.unlink(file);
  } catch {
    /* already gone */
  }
}