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.

test(perf,api): prove the gate catches regressions, and restore the rationale the refactor dropped

Abdurrahman Fakhrul957099af54b0
diff --git a/app/.well-known/oauth-authorization-server/handler.ts b/app/.well-known/oauth-authorization-server/handler.ts
index ad4aa596..3eccc8dd 100644
--- a/app/.well-known/oauth-authorization-server/handler.ts
+++ b/app/.well-known/oauth-authorization-server/handler.ts
@@ -1,6 +1,12 @@
import { publicOrigin } from "@/lib/mcp/origin";
import { mcpEnabled } from "@/lib/mcp/scope";
+
+// RFC 8414 — authorization-server metadata. Public clients only (no secret),
+// PKCE S256 only; authorization_code + rotating refresh_token grants. Dynamic Client Registration is
+// advertised because Claude.ai, Cursor and mcp-remote all expect it; ChatGPT
+// uses a user-defined client and never touches /oauth/register.
+
const PUBLIC_CORS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
diff --git a/app/.well-known/oauth-protected-resource/handler.ts b/app/.well-known/oauth-protected-resource/handler.ts
index 78f92755..0744940a 100644
--- a/app/.well-known/oauth-protected-resource/handler.ts
+++ b/app/.well-known/oauth-protected-resource/handler.ts
@@ -1,6 +1,12 @@
import { publicOrigin } from "@/lib/mcp/origin";
import { mcpEnabled } from "@/lib/mcp/scope";
+
+// RFC 9728 — tells an MCP client which authorization server protects /mcp.
+// This MUST be served from the same origin as the MCP URL: a client's first
+// discovery probe goes to the resource host, and mirroring it anywhere else is
+// what produces "MCP server does not implement OAuth" with no further detail.
+
const PUBLIC_CORS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
diff --git a/app/api/auth/login/handler.ts b/app/api/auth/login/handler.ts
index 80d2eb3a..8c7b6bef 100644
--- a/app/api/auth/login/handler.ts
+++ b/app/api/auth/login/handler.ts
@@ -8,6 +8,17 @@ 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;
diff --git a/app/api/changelog/handler.ts b/app/api/changelog/handler.ts
index c79560c8..4958b345 100644
--- a/app/api/changelog/handler.ts
+++ b/app/api/changelog/handler.ts
@@ -3,6 +3,15 @@ import path from "node:path";
import { NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
+
+// Serves docs/CHANGELOG.md so Settings → Account → About can show "What's new" in the running
+// app. The point of the whole thing: a shipped change should be visible where the
+// owner already is, not only in a terminal they would have to go and open.
+//
+// Session-gated like every other read here. The file is generated from git subjects,
+// so it carries nothing secret — but it does enumerate what this deployment is, and
+// that is not something an unauthenticated visitor needs.
+
const LIMIT = 40_000; // ~60 days of subjects; the file is capped upstream anyway
export async function handleGetChangelog(): Promise<Response> {
diff --git a/app/api/config/handler.ts b/app/api/config/handler.ts
index 97626e1b..beb28b08 100644
--- a/app/api/config/handler.ts
+++ b/app/api/config/handler.ts
@@ -17,6 +17,12 @@ import { PROVIDERS } from "@/lib/models";
import { defaultModelFor } from "@/lib/models/defaults";
import { resolveSafeProviderEndpoint } from "@/lib/host/ssrf";
+
+// GET → masked config + the list of connected providers (built-in-with-key +
+// custom). POST → set a built-in provider/model/key, OR add a custom provider.
+// DELETE ?provider=slug → forget a provider (its key + custom wiring). Session-gated;
+// raw keys never leave the server.
+
const mask = (k: string) => (k ? `${k.slice(0, 6)}…${k.slice(-4)}` : "");
type CustomBody = { name?: string; baseURL?: string; baseUrl?: string; apiKey?: string; protocol?: string; models?: string[] };
diff --git a/app/api/health/handler.ts b/app/api/health/handler.ts
index 6004616f..5638beca 100644
--- a/app/api/health/handler.ts
+++ b/app/api/health/handler.ts
@@ -2,6 +2,10 @@ import { NextResponse } from "next/server";
import pkg from "../../../package.json";
import { IS_DEMO } from "@/lib/demo";
+
+// Public liveness probe — no auth. Used by systemd WatchdogSec / Dokploy /
+// uptime monitors. Cheap, never cached. Demo builds avoid exposing host uptime.
+
export async function handleGetHealth(): Promise<Response> {
if (IS_DEMO) {
return NextResponse.json(
diff --git a/app/api/mcp/tokens/handler.ts b/app/api/mcp/tokens/handler.ts
index f5563a7d..9840175d 100644
--- a/app/api/mcp/tokens/handler.ts
+++ b/app/api/mcp/tokens/handler.ts
@@ -7,6 +7,11 @@ import { toolsetInfo } from "@/lib/mcp/toolset";
import { publicOrigin } from "@/lib/mcp/origin";
import { getRuntimeIdentity } from "@/lib/host/system-api";
+
+// Token management for Settings → MCP. Under /api on purpose: this one IS
+// cookie-authenticated and DOES want the depth-2 CSRF gate in proxy.ts, unlike
+// /mcp itself.
+
export async function handleGetTokens(req: Request): Promise<Response> {
if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), origin: publicOrigin(req), toolset: toolsetInfo(TOOLS), tokens: await listTokens(), targetIdentity: getRuntimeIdentity() });
diff --git a/app/api/memory/handler.ts b/app/api/memory/handler.ts
index 78ec422e..3f82067d 100644
--- a/app/api/memory/handler.ts
+++ b/app/api/memory/handler.ts
@@ -2,6 +2,10 @@ import { NextRequest, NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
import { listMemories, addMemory, removeMemory } from "@/lib/agent/legacy-owner-memory";
+
+// Alfa's cross-session memory (facts recalled into the system prompt). Session-gated.
+// GET → list · POST { text } → add · DELETE ?id=<id> → remove
+
export async function handleGetMemory(): Promise<Response> {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
return NextResponse.json({ memories: await listMemories() });
diff --git a/app/api/models/discover/handler.ts b/app/api/models/discover/handler.ts
index cca9eb2a..ea77e245 100644
--- a/app/api/models/discover/handler.ts
+++ b/app/api/models/discover/handler.ts
@@ -4,6 +4,14 @@ import { hostCredentialStore, readConfig, safeProviderId } from "@/lib/config/st
import { discoverEndpointModels } from "@/lib/models/discover.js";
import { assertSafeUrl } from "@/lib/host/ssrf";
+
+// List the model ids a custom endpoint actually serves, so it can be configured
+// without knowing them in advance. Owner-only. Two credential sources:
+// • `provider` — an already-saved custom provider; the key comes from the host store.
+// • `baseURL` + `apiKey` (+`protocol`) — while adding one, before it is saved.
+// A custom URL is SSRF-checked and fetched through the pinned transport, so DNS
+// cannot rebind at connect. The key is never returned, logged, or read back.
+
type DiscoverBody = { provider?: string; baseURL?: string; apiKey?: string; protocol?: string };
export async function handlePostDiscover(req: NextRequest): Promise<Response> {
diff --git a/app/api/models/test/handler.ts b/app/api/models/test/handler.ts
index c62cba80..ed828c12 100644
--- a/app/api/models/test/handler.ts
+++ b/app/api/models/test/handler.ts
@@ -8,6 +8,11 @@ import { codexModels, ensureFreshCodex } from "@/lib/ai/oauth/codex";
import { streamCodex } from "@/lib/ai/codex-stream";
import { boundedProviderFetch, providerErrorText } from "@/lib/ai/provider-response";
+
+// Minimal inference validation of the SELECTED provider's key + endpoint. Session-gated POST.
+// Returns { ok:true } or { ok:false, error } (HTTP 200 either way — a failed key is
+// a normal UX outcome, not a server error). Mirrors models-rahmanef-com testCredential.
+
export async function handlePostTest(): Promise<Response> {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
diff --git a/app/api/oauth/[provider]/handler.ts b/app/api/oauth/[provider]/handler.ts
index e7943ff0..236038cb 100644
--- a/app/api/oauth/[provider]/handler.ts
+++ b/app/api/oauth/[provider]/handler.ts
@@ -4,6 +4,13 @@ import { writeConfig, writeOAuthBundle } from "@/lib/config/store";
import { codexStart, codexPoll, codexModels, CODEX } from "@/lib/ai/oauth/codex";
import { setFlow, getFlow, clearFlow } from "@/lib/ai/oauth/flow-state";
+
+// OAuth "sign in with…" for subscription providers. POST { action:"start"|"poll" }.
+// Only OpenAI (Codex device-code) is wired today; others return not-supported.
+// Session-gated; the token bundle lands in the 0600 host config file.
+// Connecting credentials is intentionally separate from choosing the active runtime:
+// callers must send select:true on the successful poll to switch Alfa immediately.
+
export async function handlePostOAuth(req: NextRequest, ctx: { params: Promise<{ provider: string }> }): Promise<Response> {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { provider } = await ctx.params;
diff --git a/app/api/prefs/handler.ts b/app/api/prefs/handler.ts
index 51f24699..5c472e75 100644
--- a/app/api/prefs/handler.ts
+++ b/app/api/prefs/handler.ts
@@ -4,6 +4,11 @@ import { readPrefs, writePrefs, type OsPrefs } from "@/lib/prefs/store";
import { sanitizeUpdatesPatch } from "@/lib/prefs/updates";
import { applyAutomation } from "@/lib/host/update-automation";
+
+// Cross-device prefs sync (appearance tweaks + quicklinks + update automation).
+// GET → stored prefs; POST → partial section merge. Session-gated; mirrors
+// /api/config exactly.
+
export async function handleGetPrefs(): Promise<Response> {
if (!(await requireSession())) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
diff --git a/app/api/threads/handler.ts b/app/api/threads/handler.ts
index 3826a2e9..c707b0bf 100644
--- a/app/api/threads/handler.ts
+++ b/app/api/threads/handler.ts
@@ -2,6 +2,14 @@ import { NextRequest, NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
import { listThreads, getThread, saveThread, deleteThread, renameThread, type ChatThread } from "@/lib/ai/threads";
+
+// Persistent Alfa chat threads (YAML files in ~/.mso/threads/). Session-gated.
+// GET → list summaries
+// GET ?id=<id> → one full thread
+// POST { id, title?, createdAt?, messages[], history[] } → save (create/update)
+// DELETE ?id=<id> → remove
+// PATCH { id, title } → rename thread
+
const THREAD_ID = /^[A-Za-z0-9_-]{1,64}$/;
export async function handleGetThreads(req: NextRequest): Promise<Response> {
diff --git a/app/api/v1/camoufox/service/route.ts b/app/api/v1/camoufox/service/route.ts
index 77a03d21..3e7a4b46 100644
--- a/app/api/v1/camoufox/service/route.ts
+++ b/app/api/v1/camoufox/service/route.ts
@@ -1,5 +1,10 @@
import { handleGetCamoufoxService, handlePostCamoufoxService } from "@/lib/camoufox/http";
+
+// Power for the Camoufox display, so the Browser app's on/off switch reaches the
+// host instead of only hiding a window. Two actions, no unit name from the client —
+// the module owns the unit, this route owns the gate.
+
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
diff --git a/app/api/v1/camoufox/session/route.ts b/app/api/v1/camoufox/session/route.ts
index 18659dc2..97e9b139 100644
--- a/app/api/v1/camoufox/session/route.ts
+++ b/app/api/v1/camoufox/session/route.ts
@@ -1,5 +1,8 @@
import { handleGetCamoufoxSession } from "@/lib/camoufox/http";
+
+// Demo has no host, no display and no session — never hand out a credential there.
+
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
diff --git a/app/api/v1/channels/telegram/[id]/handler.ts b/app/api/v1/channels/telegram/[id]/handler.ts
index 3a7de770..cf0c5004 100644
--- a/app/api/v1/channels/telegram/[id]/handler.ts
+++ b/app/api/v1/channels/telegram/[id]/handler.ts
@@ -4,6 +4,10 @@ import { admitChannelWebhook } from "@/lib/channels/webhook-admission";
import { channelWorkflowRuntime } from "../../workflow-runtime";
import { readSetupJson } from "@/lib/infra/setup-http";
+
+// 202 = acknowledged and intentionally not acted on (bot echo, or a group
+// message that is not an owner /discuss command). Telegram should not retry.
+
export async function handlePostTelegram(req: NextRequest, id: string) {
try {
admitChannelWebhook(req, id);
diff --git a/app/api/v1/editor/exec/handler.ts b/app/api/v1/editor/exec/handler.ts
index 52a98a8a..e2a09853 100644
--- a/app/api/v1/editor/exec/handler.ts
+++ b/app/api/v1/editor/exec/handler.ts
@@ -3,6 +3,10 @@ import { verifyAuth } from "@/lib/agent/server";
import { apiError } from "@/lib/host/request-api";
import { fileStream, statReadable, readFile, writeFile } from "@/lib/host/fs-api";
import {
+
+// In-place file edit, atomic server-side. If the file EXISTS it must be a
+// valid doc (never clobber a non-doc file); only a MISSING file is seeded.
+
blankDoc,
buildDocFromImage,
imageSize,
diff --git a/app/api/v1/infra/providers/handler.ts b/app/api/v1/infra/providers/handler.ts
index b21c6a25..8a67e570 100644
--- a/app/api/v1/infra/providers/handler.ts
+++ b/app/api/v1/infra/providers/handler.ts
@@ -7,6 +7,9 @@ import { getSessionContext } from "@/lib/auth/require-session";
import { audit } from "@/lib/host/audit-api";
import { INFRA_PROVIDER_IDS, isInfraProviderId, readInfraProvider, removeInfraProvider, setInfraProvider, summarizeInfraProvider } from "@/lib/infra";
+
+// Per-project view: cloud and self-hosted rows together, credentials never included.
+
const headers = { "Cache-Control": "no-store, private", "Pragma": "no-cache", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff" };
async function ownerContext() {
diff --git a/app/api/v1/integrations/handler.ts b/app/api/v1/integrations/handler.ts
index decb89a2..0aa5e443 100644
--- a/app/api/v1/integrations/handler.ts
+++ b/app/api/v1/integrations/handler.ts
@@ -7,6 +7,14 @@ import { DemoCredentialError, revealSecret } from "@/lib/infra/demo-credentials"
import { IntegrationError } from "@/lib/infra/identity";
import { audit } from "@/lib/host/audit-api";
+
+// Reveal is the only mode whose body carries a stored secret value, so it gets its
+// own stricter headers. Nothing else in this route may return one.
+
+// Reveal is deliberately NOT a manage/execute action: those are exposed to the
+// agent as MCP tools, and a reveal is a human action. It also re-checks live
+// authorization, because a cached owner claim is not proof the device still is one.
+
const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer" };
const revealHeaders = { "Cache-Control": "private, no-store", "Pragma": "no-cache", "Referrer-Policy": "no-referrer" };
diff --git a/app/api/v1/managed-apps/[id]/install/handler.ts b/app/api/v1/managed-apps/[id]/install/handler.ts
index 72ec9f80..e0465361 100644
--- a/app/api/v1/managed-apps/[id]/install/handler.ts
+++ b/app/api/v1/managed-apps/[id]/install/handler.ts
@@ -10,6 +10,20 @@ import { startInstall } from "@/lib/managed-apps/install";
import { rememberJobActor } from "@/lib/managed-apps/job-audit";
import { redact } from "@/lib/managed-apps/redact";
+
+// Same gate order as every other managed-app route: verifyAuth -> demo 403 ->
+// rate limit -> the lib (which takes the operation lock) -> audit. Answers 202 +
+// a job id; the transcript is polled at /jobs/<id> like update's.
+//
+// This route is the one place in the managed-app surface that receives a
+// CREDENTIAL, so two things are deliberate and must stay that way:
+// 1. `apiKey` is handed to startInstall and nowhere else. It is not echoed in
+// the response, not put in the audit meta, and not passed as a job argv —
+// the argv IS persisted and IS audited (see the meta below, which prints
+// it verbatim for every job).
+// 2. The audit line records THAT a provider was configured, never which key.
+// `provider` is an allowlisted id, so it is safe to log; the key is not.
+
export async function handlePostManagedAppInstall(req: Request, id: string): Promise<Response> {
if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
if (IS_DEMO) return NextResponse.json({ error: "managed application actions are disabled in demo mode" }, { status: 403 });
diff --git a/app/api/v1/managed-apps/[id]/jobs/[jobId]/handler.ts b/app/api/v1/managed-apps/[id]/jobs/[jobId]/handler.ts
index 7212643e..8d6696c2 100644
--- a/app/api/v1/managed-apps/[id]/jobs/[jobId]/handler.ts
+++ b/app/api/v1/managed-apps/[id]/jobs/[jobId]/handler.ts
@@ -8,6 +8,21 @@ import { isManagedAppId } from "@/lib/managed-apps/catalog";
import { auditJobCompletion } from "@/lib/managed-apps/job-audit";
import { cancelManagedAppJob, readManagedAppJob } from "@/lib/managed-apps/jobs";
+
+// A job id from another app must 404 here, not leak that app's transcript
+// into a window the operator opened for this one.
+
+// The way out of a wedged operation. A job holds the app's lock until it reaches
+// a terminal status, so anything that leaves one running — a leaked grandchild
+// keeping the pipes open past its own reaper, a CLI that hangs below its timeout —
+// makes every later start/stop/restart/update/backup on that app answer 409. The
+// only other cure is restarting mso, which is precisely what an operator must
+// not do mid-update. It cannot end a healthy job by accident: the exact 24-hex id
+// AND its owning app are required, the outcome is always `failed` and never
+// `succeeded`, and cancelManagedAppJob refuses (false, never throws) while the job
+// is still inside its mandatory pre-flight backup — abandoning that copy is the
+// outcome the backup exists to prevent.
+
export async function handleGetManagedAppJob(req: Request, id: string, jobId: string): Promise<Response> {
if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
if (!isManagedAppId(id)) return NextResponse.json({ error: "unknown managed application" }, { status: 404 });
diff --git a/app/api/v1/managed-apps/[id]/update/handler.ts b/app/api/v1/managed-apps/[id]/update/handler.ts
index 1249d1fc..1e970097 100644
--- a/app/api/v1/managed-apps/[id]/update/handler.ts
+++ b/app/api/v1/managed-apps/[id]/update/handler.ts
@@ -11,6 +11,22 @@ import { redact } from "@/lib/managed-apps/redact";
import type { ManagedAppId, ManagedAppJob } from "@/lib/managed-apps/types";
import { cachedUpdateStatus, checkUpdate, setChannel, startRollback, startUninstall, startUpdate } from "@/lib/managed-apps/update";
+
+// Same gate order as every other managed-app route: verifyAuth -> demo 403 ->
+// action allowlist -> rate limit -> the lib (which takes the operation lock) ->
+// audit. The allowlist moved ahead of the limiter only because the action now
+// chooses WHICH budget to spend; an action outside it still does no work.
+// The four destructive actions answer 202 + a job id and are polled at
+// /jobs/<id>; only `check` answers inline. GET is a cache read (see there).
+
+// READ-ONLY, and that is load-bearing: the CSRF gate in proxy.ts only covers
+// POST/PUT/PATCH/DELETE, and the session cookie is Domain=mso.example.com with
+// SameSite=Strict, so every sibling origin under the configured site (~100 on this
+// box) can make the browser send this GET. If it probed, that would be a blind
+// cross-origin trigger for `hermes update --check` — two git fetches inside the
+// operator's own checkout — from any of them. So it serves the cache and
+// nothing else; the probe is `POST {action:"check"}`, behind the gate.
+
const ACTIONS = ["check", "apply", "channel", "rollback", "uninstall"] as const;
type Action = (typeof ACTIONS)[number];
diff --git a/app/api/v1/sys/audit/route.ts b/app/api/v1/sys/audit/route.ts
index 35ad9f22..315f682d 100644
--- a/app/api/v1/sys/audit/route.ts
+++ b/app/api/v1/sys/audit/route.ts
@@ -1,5 +1,13 @@
import { handleSysAudit } from "@/lib/host/sys-audit-service";
+
+// The audit trail, read-only. Session-gated like every other /api/v1 route.
+//
+// There is deliberately NO MCP tool for this. The trail records what every MCP
+// token did; letting a token read it would let a compromised one check whether it
+// had been noticed, and edit nothing but its own expectations. Forensics is a
+// surface for the owner in a browser, not for an agent.
+
export const dynamic = "force-dynamic";
export async function GET(req: Request) {
diff --git a/app/api/v1/sys/update/route.ts b/app/api/v1/sys/update/route.ts
index 8d6f9868..440f55b3 100644
--- a/app/api/v1/sys/update/route.ts
+++ b/app/api/v1/sys/update/route.ts
@@ -1,5 +1,10 @@
import { handleGetSysUpdate, handlePostSysUpdate } from "@/lib/host/sys-update-service";
+
+// A manual update is the operator's answer to the unattended pause. Clear the
+// failure streak when this one was accepted; otherwise the gate keeps refusing
+// forever and its own advice ("run mso update from a terminal") would be false.
+
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
diff --git a/app/api/v1/term/input/route.ts b/app/api/v1/term/input/route.ts
index e1b35f6f..0453f5eb 100644
--- a/app/api/v1/term/input/route.ts
+++ b/app/api/v1/term/input/route.ts
@@ -1,5 +1,11 @@
import { handleTermInput } from "@/lib/host/term-service";
+
+// POST /term/input {id,data} → raw keystrokes into the pty. Not audited and
+// not command-filtered by design — see lib/host/pty.ts (owner shell; the
+// auditable boundary is session open/close). No rate limit: a fast typist or
+// a paste easily outruns any sane per-minute cap.
+
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
diff --git a/app/api/v1/term/open/route.ts b/app/api/v1/term/open/route.ts
index af638a71..98f09220 100644
--- a/app/api/v1/term/open/route.ts
+++ b/app/api/v1/term/open/route.ts
@@ -1,5 +1,9 @@
import { handleTermOpen } from "@/lib/host/term-service";
+
+// POST /term/open {cols,rows,cwd?} → {id}. Spawns the owner's interactive
+// login shell (see lib/host/pty.ts for why no command filter applies here).
+
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
diff --git a/app/oauth/register/handler.ts b/app/oauth/register/handler.ts
index bd4ac86b..23a1cea7 100644
--- a/app/oauth/register/handler.ts
+++ b/app/oauth/register/handler.ts
@@ -5,6 +5,11 @@ import { mcpEnabled } from "@/lib/mcp/scope";
import { clientIp } from "@/lib/mcp/origin";
import { rateLimited, rateLimitedUntrusted } from "@/lib/host/limits-api";
+
+// RFC 7591 Dynamic Client Registration. Open by design and safe to be: a
+// registered client is INERT until the owner approves it on the consent page and
+// completes PKCE. All this records is a name and a redirect list.
+
const DCR_CORS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7e3cea60..176d17c9 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -10,6 +10,10 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
- `agent` show the todo checklist in the TUI and in the status row (#179)
+**Tests**
+
+- `perf,api` prove the gate catches regressions, and restore the rationale the refactor dropped
+
**Docs**
- `bench` the after-side comparison, and a status header that was no longer true
diff --git a/lib/managed-apps/proxy-handler.ts b/lib/managed-apps/proxy-handler.ts
index befde911..8a4ccf75 100644
--- a/lib/managed-apps/proxy-handler.ts
+++ b/lib/managed-apps/proxy-handler.ts
@@ -12,6 +12,13 @@ import { contentSecurityPolicy } from "@/lib/managed-apps/proxy-csp";
import { errorPage, wantsErrorPage } from "@/lib/managed-apps/proxy-error-page";
import { getOrcaReadiness } from "@/lib/managed-apps/orca-readiness";
import {
+
+// A login POST answers 302 + Set-Cookie, so the cookies must ride the
+// rewritten redirect too — not just plain 2xx bodies.
+
+// The frame is CROSS-origin, so frame-ancestors must name the cockpit or the
+// browser refuses to display it at all.
+
buildUpstreamHeaders,
isSecureRequest,
isServiceWorkerRequest,
diff --git a/scripts/check-perf.test.ts b/scripts/check-perf.test.ts
new file mode 100644
index 00000000..3dca364b
--- /dev/null
+++ b/scripts/check-perf.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from "vitest";
+import { parsePerfReport, perfViolations } from "./lib/perf-report.mjs";
+import { timingSkipReason } from "./lib/perf-timing-load.mjs";
+
+const baseline = {
+ schemaVersion: 1,
+ host: { cpus: 16, loadAvg1AtMeasure: 0.32 },
+ runs: [
+ { label: "desktop", tbtMs: 164 },
+ { label: "mobile", tbtMs: 132 },
+ ],
+};
+
+const budget = {
+ schemaVersion: 1,
+ enforce: {
+ tbtMsBlowupFactor: 2.0,
+ maxLoadAvg1ForTiming: 4.0,
+ },
+};
+
+function makeRun(overrides: Record<string, unknown> = {}) {
+ return {
+ label: "desktop",
+ viewport: { width: 1440, height: 900 },
+ fcpMs: 1180,
+ lcpMs: 3222,
+ tbtMs: 164,
+ cls: 0.001,
+ longTasks: 4,
+ maxLongTaskMs: 128,
+ firstLoadJsBytes: 900_000,
+ ...overrides,
+ };
+}
+
+function makeReport(
+ runOverrides: Record<string, unknown> = {},
+ hostOverrides: Record<string, unknown> = {},
+) {
+ return {
+ schemaVersion: 1,
+ host: {
+ cpus: 16,
+ loadAvg1: 0.5,
+ ...hostOverrides,
+ },
+ runs: [
+ makeRun(runOverrides),
+ {
+ label: "mobile",
+ viewport: { width: 390, height: 844 },
+ fcpMs: 1166,
+ lcpMs: 3054,
+ tbtMs: 132,
+ cls: 0,
+ longTasks: 4,
+ maxLongTaskMs: 126,
+ firstLoadJsBytes: 850_000,
+ },
+ ],
+ };
+}
+
+describe("check-perf gate verification", () => {
+ it("1. synthetic report over the byte cap -> violation", () => {
+ const budgetWithCap = {
+ ...budget,
+ enforce: { ...budget.enforce, firstLoadJsBytes: { desktop: 800_000 } },
+ };
+ const report = parsePerfReport(makeReport({ firstLoadJsBytes: 950_000 }));
+ const violations = perfViolations(report, budgetWithCap, baseline);
+ expect(violations).toContain("desktop: firstLoadJsBytes 950000 > 800000");
+ });
+
+ it("2. report with missing tbtMs -> violation (a null measurement must fail, not pass)", () => {
+ const report = parsePerfReport(makeReport({ tbtMs: null }));
+ const violations = perfViolations(report, budget, baseline);
+ expect(violations).toContain("desktop: missing tbtMs measurement");
+ });
+
+ it("3. TBT above 2x baseline, same core count, idle load -> violation", () => {
+ // Baseline is 164ms, blowup limit is 328ms. 350ms > 328ms.
+ const report = parsePerfReport(makeReport({ tbtMs: 350 }, { cpus: 16, loadAvg1: 0.5 }));
+ const violations = perfViolations(report, budget, baseline);
+ expect(violations).toContain("desktop: tbtMs 350ms > 2x baseline 164ms");
+ expect(timingSkipReason(report, budget, baseline)).toBeNull();
+ });
+
+ it("4. same report, different core count -> no violation AND timingSkipReason explains it", () => {
+ // Same inflated TBT (350ms) and idle load (0.5), but running on 4 cpus instead of baseline 16.
+ const report = parsePerfReport(makeReport({ tbtMs: 350 }, { cpus: 4, loadAvg1: 0.5 }));
+ const violations = perfViolations(report, budget, baseline);
+ expect(violations).toEqual([]);
+ const reason = timingSkipReason(report, budget, baseline);
+ expect(reason).not.toBeNull();
+ expect(reason).toMatch(/this host has 4 cpus, the committed baseline was taken on 16/);
+ });
+
+ it("5. same report, load above maxLoadAvg1ForTiming -> no violation AND the reason explains the load", () => {
+ // Same inflated TBT (350ms) and matching cpus (16), but loadAvg1 is 7.5 > maxLoadAvg1ForTiming (4.0).
+ const report = parsePerfReport(makeReport({ tbtMs: 350 }, { cpus: 16, loadAvg1: 7.5 }));
+ const violations = perfViolations(report, budget, baseline);
+ expect(violations).toEqual([]);
+ const reason = timingSkipReason(report, budget, baseline);
+ expect(reason).not.toBeNull();
+ expect(reason).toMatch(/host load1=7.5 exceeds 4/);
+ });
+
+ it("6. clean report -> no violations, no skip reason", () => {
+ const report = parsePerfReport(makeReport({ tbtMs: 160 }, { cpus: 16, loadAvg1: 0.5 }));
+ const violations = perfViolations(report, budget, baseline);
+ expect(violations).toEqual([]);
+ expect(timingSkipReason(report, budget, baseline)).toBeNull();
+ });
+});