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.

7.5 KB
Raw Blame
// Host-owned runtime data is not a build asset; tracing exclusions preserve runtime guards.
// SERVER-ONLY. Bounded best-effort JSONL trail for privileged mutations.
// Location: $OS_AUDIT_LOG, else ~/.mso/audit.log; reads are not audited.
import { constants, promises as fs } from "fs";
import os from "os";
import path from "path";

import type { AuditAction } from "@/lib/contracts/audit";
export type { AuditAction } from "@/lib/contracts/audit";

export interface AuditEntry {
  action: AuditAction;
  /** Approved device id from the session (the actor), when known. */
  actor?: string | null;
  /** Request origin IP, when available (auth events). */
  ip?: string | null;
  /** Primary target — a path, URL, or command (truncated). */
  target?: string;
  /** Outcome flag; false = failed/blocked/denied. */
  ok?: boolean;
  /** Optional extra context (exit code, reason). */
  detail?: string;
  /** Structured side-channel for shape data that does not fit `target` cleanly
   *  (route kind, http status, byte counts, …). Scalar values only so the
   *  JSONL line stays one shallow object — keeps `jq` + grep workflows sane. */
  meta?: Record<string, string | number | boolean>;
}

function auditPath(): string {
  const env = process.env.OS_AUDIT_LOG;
  if (env && env.trim()) return env.replace(/^~(?=$|\/)/, os.homedir());
  return path.join(os.homedir(), ".mso", "audit.log");
}

function trunc(s: string | undefined, max = 512): string | undefined {
  if (s == null) return undefined;
  return s.length > max ? s.slice(0, max) + "…" : s;
}

// Keep caller-supplied metadata bounded and scalar-only.
function clampMeta(
  meta: Record<string, string | number | boolean> | undefined,
): Record<string, string | number | boolean> | undefined {
  if (!meta) return undefined;
  const out: Record<string, string | number | boolean> = {};
  for (const [k, v] of Object.entries(meta)) {
    if (typeof v === "string")
      out[k] = v.length > 256 ? v.slice(0, 256) + "…" : v;
    else if (typeof v === "number" || typeof v === "boolean") out[k] = v;
    // any other type: silently drop
  }
  return out;
}

export interface AuditRecord {
  ts?: string;
  action: string;
  actor?: string | null;
  ip?: string | null;
  target?: string;
  ok?: boolean;
  detail?: string;
  meta?: Record<string, string | number | boolean>;
}

// Read the tail of the audit log, newest-first, optionally filtered to actions
// with a given prefix (e.g. "browser."). Returns [] if the log doesn't exist.
// The single reader of the trail — routes must not re-derive the log path.
export async function readAuditTail(opts?: {
  prefix?: string;
  limit?: number;
}): Promise<AuditRecord[]> {
  const { prefix, limit = 100 } = opts ?? {};
  const raw = await readBoundedTail(auditPath()).catch(() => "");
  return raw
    .split("\n")
    .filter(Boolean)
    .slice(-500)
    .map((l) => {
      try {
        return JSON.parse(l) as AuditRecord;
      } catch {
        return null;
      }
    })
    .filter((e): e is AuditRecord =>
      Boolean(
        e &&
        typeof e.action === "string" &&
        (!prefix || e.action.startsWith(prefix)),
      ),
    )
    .slice(-Math.max(1, Math.min(500, Math.trunc(limit) || 100)))
    .reverse();
}

// Preserve submission order; a failed write must not poison later writes.
let _writeChain: Promise<void> = Promise.resolve();
const AUDIT_MAX_BYTES = 8 * 1024 * 1024;
const AUDIT_READ_TAIL_BYTES = 256 * 1024;
const RATELIMIT_AUDIT_MAX = 60;
const RATELIMIT_AUDIT_WINDOW_MS = 60_000;
let ratelimitWindow = 0;
let ratelimitEntries = 0;

function allowRateLimitAudit(action: AuditAction): boolean {
  if (action !== "auth.ratelimited") return true;
  const now = Date.now();
  if (now - ratelimitWindow >= RATELIMIT_AUDIT_WINDOW_MS) {
    ratelimitWindow = now;
    ratelimitEntries = 0;
  }
  if (ratelimitEntries >= RATELIMIT_AUDIT_MAX) return false;
  ratelimitEntries += 1;
  return true;
}

async function readBoundedTail(file: string): Promise<string> {
  let handle;
  try {
    handle = await fs.open(/* turbopackIgnore: true */ file, constants.O_RDONLY | constants.O_NOFOLLOW);
    const stat = await handle.stat();
    if (!stat.isFile()) return "";
    const size = Math.min(stat.size, AUDIT_READ_TAIL_BYTES);
    const offset = Math.max(0, stat.size - size);
    const buffer = Buffer.alloc(size);
    const { bytesRead } = await handle.read(buffer, 0, size, offset);
    let text = buffer.subarray(0, bytesRead).toString("utf8");
    if (offset > 0) {
      const newline = text.indexOf("\n");
      text = newline >= 0 ? text.slice(newline + 1) : "";
    }
    return text;
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
    throw error;
  } finally {
    await handle?.close().catch(() => undefined);
  }
}

async function copyHandle(source: Awaited<ReturnType<typeof fs.open>>, dest: Awaited<ReturnType<typeof fs.open>>, bytes: number): Promise<void> {
  const buffer = Buffer.allocUnsafe(64 * 1024);
  let position = 0;
  while (position < bytes) {
    const length = Math.min(buffer.length, bytes - position);
    const { bytesRead } = await source.read(buffer, 0, length, position);
    if (!bytesRead) break;
    await dest.write(buffer, 0, bytesRead, null);
    position += bytesRead;
  }
}

async function writeLine(line: string): Promise<void> {
  // Tests require an explicit synthetic trail; never append to the owner's log.
  if (process.env.VITEST && !process.env.OS_AUDIT_LOG) return;
  const file = auditPath();
  let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
  try {
    await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
    handle = await fs.open(
      /* turbopackIgnore: true */ file,
      constants.O_RDWR | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW,
      0o600,
    );
    const stat = await handle.stat();
    if (!stat.isFile()) throw new Error("audit log must be a regular file");

    if (stat.size + Buffer.byteLength(line) > AUDIT_MAX_BYTES) {
      const rotated = file + ".1";
      let rotatedHandle: Awaited<ReturnType<typeof fs.open>> | undefined;
      try {
        rotatedHandle = await fs.open(
          /* turbopackIgnore: true */ rotated,
          constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
          0o600,
        );
        await copyHandle(handle, rotatedHandle, stat.size);
        await rotatedHandle.sync();
      } finally {
        await rotatedHandle?.close().catch(() => undefined);
      }
      await handle.truncate(0);
    }

    await handle.writeFile(line);
  } catch (e) {
    console.error("[audit] write failed:", e instanceof Error ? e.message : e);
  } finally {
    await handle?.close().catch(() => undefined);
  }
}

// Resolves after the best-effort write; failures never break the caller.
export function audit(entry: AuditEntry): Promise<void> {
  if (!allowRateLimitAudit(entry.action)) return Promise.resolve();
  // Drop `meta` from the serialized line when it's empty so existing greps that
  // assume a fixed-shape record don't suddenly see `"meta":{}` everywhere.
  const clamped = clampMeta(entry.meta);
  const hasMeta = clamped && Object.keys(clamped).length > 0;
  const line =
    JSON.stringify({
      ts: new Date().toISOString(),
      action: entry.action,
      actor: entry.actor ?? null,
      ip: entry.ip ?? null,
      target: trunc(entry.target),
      ok: entry.ok ?? true,
      detail: trunc(entry.detail, 256),
      ...(hasMeta ? { meta: clamped } : {}),
    }) + "\n";
  _writeChain = _writeChain.then(() => writeLine(line));
  return _writeChain;
}