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.

4.0 KB
Raw Blame
import { NextResponse } from "next/server";
import { text } from "node:stream/consumers";
import { verifyAuth } from "@/lib/agent/server";
import { getSessionActor } from "@/lib/auth/require-session";
import { apiError, invalidRequest } from "@/lib/host/request-api";
import { audit } from "@/lib/host/audit-api";
import { boundaryFromContentType, parseMultipart, resolveUploadDest, streamFileInto, UploadTooLargeError } from "@/lib/host/fs-api";
import { rateLimited } from "@/lib/host/limits-api";
import { managedAppIdForHost, isUnclaimedAppNamespaceHost } from "@/lib/managed-apps/origin";

const FS_UPLOAD_MAX = 20;
const FS_UPLOAD_WINDOW_MS = 60_000;
const MAX_TOTAL = 200 * 1024 * 1024;
let activeUploads = 0;

export async function handlePostFsUpload(req: Request): Promise<Response> {
  const host = req.headers.get("host") ?? new URL(req.url).host;
  if (managedAppIdForHost(host) || isUnclaimedAppNamespaceHost(host))
    return new NextResponse("Not Found", { status: 404 });
  const site = req.headers.get("sec-fetch-site");
  const origin = req.headers.get("origin");
  if (site && site !== "same-origin" && site !== "none")
    return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403 });
  if (origin) {
    try {
      if (new URL(origin).host !== host) return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403 });
    } catch {
      return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403 });
    }
  }
  if (!(await verifyAuth(req)))
    return NextResponse.json({ error: "unauthorized" }, { status: 401 });
  if (activeUploads >= 4) return NextResponse.json({ error: "uploads_busy" }, { status: 429 });
  activeUploads++;
  try {
    return await streamUpload(req);
  } finally {
    activeUploads--;
  }
}

async function streamUpload(req: Request) {
  const actor = await getSessionActor();
  if (rateLimited(`fs.upload:${actor ?? "anon"}`, FS_UPLOAD_MAX, FS_UPLOAD_WINDOW_MS)) {
    audit({ action: "fs.upload", actor, ok: false, detail: "rate-limited" });
    return NextResponse.json({ error: "Too many upload requests, slow down" }, { status: 429 });
  }

  let boundary: string;
  try {
    boundary = boundaryFromContentType(req.headers.get("content-type"));
  } catch {
    return NextResponse.json({ error: "expected multipart/form-data" }, { status: 400 });
  }
  if (!req.body) return NextResponse.json({ error: "expected multipart/form-data" }, { status: 400 });

  let dest: string | undefined;
  let destReal: string | undefined;
  let written = 0;
  const failed: string[] = [];

  try {
    for await (const part of parseMultipart(req.body, boundary, MAX_TOTAL)) {
      if (part.filename === undefined) {
        if (part.name === "dest") {
          dest = (await text(part.body)).trim();
          if (dest) destReal = await resolveUploadDest(dest);
        } else {
          await drainPart(part.body);
        }
        continue;
      }
      if (!destReal) {
        await drainPart(part.body);
        failed.push(part.filename || "(unnamed)");
        continue;
      }
      const r = await streamFileInto(destReal, part.filename, part.body);
      if (r === "ok") written++;
      else failed.push(part.filename + (r === "too-large" ? " (too large)" : ""));
    }
  } catch (e) {
    if (e instanceof UploadTooLargeError) {
      audit({ action: "fs.upload", actor, target: dest ?? "", ok: false, detail: String(e) });
      return NextResponse.json({ error: String(e.message) }, { status: 413 });
    }
    audit({ action: "fs.upload", actor, target: dest ?? "", ok: false, detail: String(e) });
    return apiError("fs/upload", e);
  }

  if (typeof dest !== "string" || !dest) return invalidRequest("dest");

  audit({
    action: "fs.upload",
    actor,
    target: dest,
    ok: failed.length === 0,
    detail: `${written} written${failed.length ? `, ${failed.length} failed` : ""}`,
  });
  return NextResponse.json({ written, failed });
}

async function drainPart(body: AsyncIterable<Uint8Array>): Promise<void> {
  for await (const _chunk of body) void _chunk;
}