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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";
import { NextRequest, NextResponse } from "next/server";
import { constantTimeEq, MAX_COMPARE_BYTES, MIN_SECRET_LEN, signSession, type SessionPayload } from "@/lib/auth/session";
import { SESSION_COOKIE } from "@/lib/auth/require-session";
import { configuredSessionCookieScope, sessionCookieAttrs } from "@/lib/auth/session-cookie";
import { currentSessionPolicy, isApproved, isValidDeviceId, recordPending, touchApproved } from "@/lib/auth/device-store";
import { audit } from "@/lib/host/audit-api";
import { IS_DEMO } from "@/lib/demo";
import { clientIp } from "@/lib/host/request-ip";
// Password + device-approval login, implemented for the VPS control plane.
// gate 1 = shared password (OS_LOGIN_PASSWORD)
// gate 2 = device id pre-approved in the device store
// Correct password on an un-approved device → recorded pending, 403, NO cookie.
// Per-IP rejection never charges the global budget. Admission is reserved before
// body reads/password comparison so distributed requests cannot keep testing guesses.
// Exhaustion temporarily rejects all unauthenticated attempts; an already-approved
// session or the local CLI remains the recovery path, not a password oracle.
const MAX_ATTEMPTS = 5;
const WINDOW_MS = 60_000;
const MAX_TRACKED_IPS = 1024;
const GLOBAL_MAX_ATTEMPTS = 30;
const rateLimitMap = new Map<string, { count: number; reset_at: number }>();
let globalWindowStart = Date.now();
let globalAttempts = 0;
function rateLimited(ip: string): boolean {
const now = Date.now();
if (now - globalWindowStart > WINDOW_MS) {
globalWindowStart = now;
globalAttempts = 0;
}
if (rateLimitMap.size > MAX_TRACKED_IPS) {
for (const [k, v] of rateLimitMap) if (now > v.reset_at) rateLimitMap.delete(k);
if (rateLimitMap.size > MAX_TRACKED_IPS) rateLimitMap.clear();
}
const entry = rateLimitMap.get(ip);
const live = entry && now <= entry.reset_at;
if (live && entry.count >= MAX_ATTEMPTS) return true;
if (globalAttempts >= GLOBAL_MAX_ATTEMPTS) return true;
globalAttempts += 1;
if (!live) {
rateLimitMap.set(ip, { count: 1, reset_at: now + WINDOW_MS });
return false;
}
entry.count += 1;
return false;
}
export async function handlePostLogin(req: NextRequest): Promise<Response> {
if (IS_DEMO) {
return NextResponse.json({ error: "login_disabled_in_demo" }, { status: 403 });
}
const sessionSecret = process.env.OS_SESSION_SECRET ?? "";
const password = process.env.OS_LOGIN_PASSWORD ?? "";
// Signing key must be strong and the configured login secret must fit the
// fixed-width comparator. Fail closed on an unusable server configuration.
if (
sessionSecret.length < MIN_SECRET_LEN ||
password.length < 6 ||
Buffer.byteLength(password, "utf8") > MAX_COMPARE_BYTES
) {
return NextResponse.json({ error: "not_configured" }, { status: 500 });
}
const ip = clientIp(req);
if (rateLimited(ip)) {
audit({ action: "auth.ratelimited", ip, ok: false });
return NextResponse.json({ error: "Too many attempts, try again later" }, { status: 429 });
}
let body: Record<string, unknown>;
try {
body = await readRequestJson(req, 16 * 1024);
} catch (error) {
return NextResponse.json({ error: "Invalid request body" }, { status: error instanceof RequestBodyError ? error.status : 400 });
}
const { password: provided, deviceId } = body;
if (
typeof provided !== "string" ||
provided.length === 0 ||
Buffer.byteLength(provided, "utf8") > MAX_COMPARE_BYTES
) {
return NextResponse.json({ error: "bad_password" }, { status: 401 });
}
if (!isValidDeviceId(deviceId)) {
return NextResponse.json({ error: "Missing or invalid device id" }, { status: 400 });
}
const label = typeof body.deviceLabel === "string" ? body.deviceLabel.slice(0, 80) : "unknown device";
// Length-safe fixed-width comparison; no reusable password hash is created.
if (!constantTimeEq(password, provided)) {
audit({ action: "auth.denied", actor: deviceId, ip, ok: false, detail: "bad password" });
return NextResponse.json({ error: "bad_password" }, { status: 401 });
}
if (!(await isApproved(deviceId))) {
await recordPending(deviceId, label, ip);
audit({ action: "auth.pending", actor: deviceId, ip, ok: false, detail: label });
return NextResponse.json({ error: "device_pending", deviceId, label }, { status: 403 });
}
await touchApproved(deviceId);
audit({ action: "auth.login", actor: deviceId, ip, ok: true });
// Guard the env parse: NaN here would mint a cookie that NEVER expires
// (NaN <= Date.now() is false in verifySession) — fail back to 24h instead.
const parsedHours = parseInt(process.env.SESSION_EXPIRY_HOURS ?? "24", 10);
const hours = Number.isFinite(parsedHours) && parsedHours > 0 ? parsedHours : 24;
const now = Date.now();
const policy = await currentSessionPolicy(configuredSessionCookieScope());
const payload: SessionPayload = {
issued_at: now,
expires_at: now + hours * 3600 * 1000,
device_id: deviceId,
cookie_scope: policy.scope,
cookie_epoch: policy.epoch,
};
const res = NextResponse.json({ success: true });
// Attributes (incl. the optional Domain for the split-origin app hosts) come
// from one helper shared with logout, so a cookie can't be set with a Domain
// the clear path then misses.
res.cookies.set(SESSION_COOKIE, signSession(payload, sessionSecret), sessionCookieAttrs(req, hours * 3600));
return res;
}