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
refactor(lib): drop static next/* imports, plus three measured perf findings
Abdurrahman Fakhrulc846bc7444a4
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 3e77cd4a..3092aaa7 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -11,6 +11,10 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh- `perf` hydration mark chain, and the LCP conclusion it overturns- `tui` close the opencode TUI gap on the seams MSO already owns (#166)+**Changed**++- `lib` drop static next/* imports, plus three measured perf findings+**Docs**- `progress` record the perf gate and the numbers it retracteddiff --git a/docs/MSO-MIGRATION.md b/docs/MSO-MIGRATION.mdindex b3a8856d..f2924a9c 100644--- a/docs/MSO-MIGRATION.md+++ b/docs/MSO-MIGRATION.md@@ -446,8 +446,27 @@ of the measured options, cheapest first:3. **Cut shell mount cost.** Profile and reduce component initialization inside`frontend/slices/appshell/components/desktop.tsx` and the eager slice registry during`#main-content` hydration (mount ~2.6-3.0 s → LCP ~3.2-4.2 s).- *Measurement support:* Supported by the CPU throttle control (−644 ms at 1× CPU vs- 4× CPU). Main-thread execution after JS arrival accounts for 0.4-1.1 s before LCP.+ *Measurement support:* Measured 2026-10-29 (`bun run perf:tasks` + CDP trace analysis,+ Slow 4G + 4× CPU). Between FCP and LCP there is ~800–950 ms of main-thread execution+ split across two phases. Pre-mount (FCP → mount ~2.6 s): ~220 ms React 19 runtime+ bootstrap (`2uq1r5nfrxpmw.js`), ~195 ms eager slice registry and manifests evaluation+ (`3vzf2l_pzsqlz.js`: Alfa tools, quicklinks, appearance presets, 29 app descriptors),+ and ~100–140 ms initial skeleton hydration. Mount → LCP (~2.6 → 3.3–4.0 s): the lazy+ `macos-shell` chunk (45 KB raw / ~14 KB gzip, `1mmmz82o-7zp9.js`) is fetched and+ evaluated, then a 260 ms long task renders `DesktopChrome` (~145 ms React component+ tree, 74 ms UpdateLayoutTree, 40 ms Layout), finishing with ~25–40 ms Paint to the+ menu-bar `SPAN` LCP element. Suspects rejected by measurement: `Wallpaper` execution is+ <2 ms (CSS backdrop loads asynchronously, off the main thread); icon artwork decode is+ 0 ms (async WebP decodes; desktop LCP is text).+ The shell-chunk fetch is *already* concurrent with mount, not serial after it: measured+ request start 2573 ms against mount 2591 ms, response end 2869 ms. Prefetching it from+ inside the app therefore buys nothing — verified, not assumed. Buying anything back+ would require starting the fetch before hydration, which in turn requires knowing the+ surface at SSR time, which is exactly the thing that causes the macOS/iOS hydration+ mismatch. That circularity, not the byte count, is why this lever is structural. It+ could be broken by preloading both shell chunks from the server (≈+14 KB gzip for+ everyone to save ~0.3 s for two thirds of visitors), which trades against §3 item 1 and+ should be decided as a product call, not folded in as an optimization.4. **Migrate a slice (Phase 3).** If in-tree budget and mount optimizations leave LCP> 2.5 s, a framework migration is the only remaining lever that removes ~230 KB of`react-dom` runtime and Next router overhead from the first-load critical path.@@ -523,7 +542,18 @@ Bun; `next` still on Node; build time unchanged or better.The largest durable win and the cheapest real work, because 96 % of `lib/` needs nothing.- Formalize the boundary: `lib/` exports plain request/response types; nothing in `lib/`- may import `next/*`. Two files violate this today — remove them.+ may import `next/*`. **Done 2026-10-29** for the static-import half: the seven files that+ imported `next/server` or `next/headers` now use the web-standard `Request`/`Response`,+ and `grep -rn 'from "next/' lib` (non-test) is 0. `NextResponse.cookies.set` became an+ explicit `Set-Cookie` header in three files, with the same attributes and the same+ `base64url` payloads, so no encoding change. One honest exception remains:+ `lib/auth/require-session.ts` still reaches Next through a *dynamic* `import("next/headers")`+ inside the default `nextSessionCookieReader`, because `cookies()` is request-scoped framework+ plumbing with no web-standard equivalent in place. It is a two-line seam with a default+ parameter, so all 54 call sites are untouched and a SvelteKit adapter can pass its own reader;+ moving the adapter out of `lib/` entirely is 54 mechanical edits and was deliberately not done+ here. The exit criterion below is therefore "no *static* `next/*` import in `lib/`" — a grep for+ `from "next/"` does not see `import(...)` and would give a false green.- Convert the 117 `route.ts` handlers into thin adapters: one shared`NextRequest → { request, ctx }` shim, all logic in `lib/`. Handlers become 3–5 lines.(`NextResponse` 744 usages, `NextRequest` 122 — the shim is the whole job.)@@ -531,8 +561,8 @@ The largest durable win and the cheapest real work, because 96 % of `lib/` needsSvelteKit `+server.ts` later without edits.- Keep `proxy.ts` as-is; it is ported in Phase 6, not here.-Exit criteria: zero `next/*` imports in `lib/`; every route handler ≤ 15 LOC; ratchets-unchanged; full suite green.+Exit criteria: no static `next/*` import in `lib/` (met); every route handler ≤ 15 LOC;+ratchets unchanged; full suite green.Value even if the migration dies here: the backend becomes portable and testable withouta framework. Worth doing on its own.diff --git a/lib/agent/session-compact-now.ts b/lib/agent/session-compact-now.tsindex 5cdc61d5..5a6b50e1 100644--- a/lib/agent/session-compact-now.ts+++ b/lib/agent/session-compact-now.ts@@ -6,7 +6,6 @@ import { appendSemanticSessionEvent } from "./session-semantic";import { archiveAgentSession, pruneAgentSessionArchives } from "./session-archive";import { requireOwned } from "./session-record";import { artifactLocation } from "./artifact-paths";-import { NextResponse } from "next/server";import type { AgentSession, AgentSessionEvent } from "./session-types";export interface CompactAgentSessionReport {@@ -114,15 +113,15 @@ export async function compactAgentSessionNow(export async function compactAgentSessionRouteHandler(principal: string,rawId?: string,-): Promise<NextResponse> {+): Promise<Response> {const id = String(rawId || "").trim();if (!id)- return NextResponse.json(+ return Response.json({ error: "id_required" },{ status: 400 },);const result = await compactAgentSessionNow(principal, id, "manual");- return NextResponse.json({+ return Response.json({session: { ...result.session, artifacts: artifactLocation(result.session) },archived: result.archived,archiveReason: result.archiveReason,diff --git a/lib/auth/require-session.ts b/lib/auth/require-session.tsindex cacfc660..ac267cf6 100644--- a/lib/auth/require-session.ts+++ b/lib/auth/require-session.ts@@ -1,5 +1,4 @@import { deviceSessionValid } from "./live-session";-import { cookies } from "next/headers";import { configuredSessionCookieScope } from "./session-cookie";import { verifySession, type SessionPayload } from "./session";import { currentSessionPolicy, getApprovedDevice, type ApprovedDevice } from "./device-store";@@ -18,14 +17,25 @@ export type SessionContext = {role: DeviceRole;};+export type SessionCookieReader = () => Promise<Iterable<{ value: string }>> | Iterable<{ value: string }>;++/** Default cookie source for Next.js app router request contexts. */+export async function nextSessionCookieReader(): Promise<Iterable<{ value: string }>> {+ const { cookies } = await import("next/headers");+ const jar = await cookies();+ return jar.getAll(SESSION_COOKIE);+}+// Reads + verifies every signed-session candidate, then resolves the device record// live. Role changes and revocation therefore take effect on the next request; no// authorization claim is cached in a cookie that can remain stale for 24 hours.-export async function getSessionContext(): Promise<SessionContext | null> {+export async function getSessionContext(+ cookieReader: SessionCookieReader = nextSessionCookieReader,+): Promise<SessionContext | null> {if (IS_DEMO) return null;- const jar = await cookies();+ const candidates = await cookieReader();const policy = await currentSessionPolicy(configuredSessionCookieScope());- for (const { value } of jar.getAll(SESSION_COOKIE)) {+ for (const { value } of candidates) {const session = verifySession(value, secret());if (!session?.device_id || session.cookie_scope !== policy.scope || session.cookie_epoch !== policy.epoch) continue;const device = await getApprovedDevice(session.device_id);@@ -36,17 +46,24 @@ export async function getSessionContext(): Promise<SessionContext | null> {}/** Compatibility payload accessor for existing callers that do not need role data. */-export async function getSession(): Promise<SessionPayload | null> {- return (await getSessionContext())?.session ?? null;+export async function getSession(+ cookieReader: SessionCookieReader = nextSessionCookieReader,+): Promise<SessionPayload | null> {+ return (await getSessionContext(cookieReader))?.session ?? null;}-export async function requireSession(minimumRole: DeviceRole = "viewer"): Promise<boolean> {- const context = await getSessionContext();+export async function requireSession(+ minimumRole: DeviceRole = "viewer",+ cookieReader: SessionCookieReader = nextSessionCookieReader,+): Promise<boolean> {+ const context = await getSessionContext(cookieReader);return context !== null && roleAtLeast(context.role, minimumRole);}// Approved device id behind the current session, or null. Audit attribution remains// stable across role changes; role is recorded separately by security-sensitive routes.-export async function getSessionActor(): Promise<string | null> {- return (await getSessionContext())?.session.device_id ?? null;+export async function getSessionActor(+ cookieReader: SessionCookieReader = nextSessionCookieReader,+): Promise<string | null> {+ return (await getSessionContext(cookieReader))?.session.device_id ?? null;}diff --git a/lib/camoufox/viewer-gate.ts b/lib/camoufox/viewer-gate.tsindex a3fa70fe..9f0d9708 100644--- a/lib/camoufox/viewer-gate.ts+++ b/lib/camoufox/viewer-gate.ts@@ -1,4 +1,3 @@-import { NextResponse, type NextRequest } from "next/server";import { deviceSessionValid } from "@/lib/auth/live-session";import { getApprovedDevice } from "@/lib/auth/device-store";import { roleAtLeast } from "@/lib/auth/roles";@@ -14,7 +13,7 @@ import { IS_DEMO } from "@/lib/demo";import { CAMOUFOX_VIEWER_ENTRY_PATH, CAMOUFOX_VIEWER_PUBLIC_PREFIX } from "./viewer-path";const AUTHORIZED = Symbol("camoufox-viewer-authorized");-export type CamoufoxViewerGateResult = typeof AUTHORIZED | NextResponse;+export type CamoufoxViewerGateResult = typeof AUTHORIZED | Response;function noStore(headers: Headers): void {@@ -24,7 +23,7 @@ function noStore(headers: Headers): void {}function notFound() {- const response = new NextResponse("Not Found", {+ const response = new Response("Not Found", {status: 404,headers: { "content-type": "text/plain; charset=utf-8" },});@@ -43,9 +42,21 @@ async function approvedDevice(token: string, kind: "ticket" | "cookie") {return deviceSessionValid(payload, device) && device && roleAtLeast(device.role, "operator") ? payload : null;}-async function hasViewerSession(request: NextRequest): Promise<boolean> {- for (const { value } of request.cookies.getAll(CAMOUFOX_VIEWER_COOKIE)) {- if (await approvedDevice(value, "cookie")) return true;+async function hasViewerSession(request: Request): Promise<boolean> {+ const cookieHeader = request.headers.get("cookie");+ if (cookieHeader) {+ for (const part of cookieHeader.split(";")) {+ const [name, ...rest] = part.trim().split("=");+ if (name === CAMOUFOX_VIEWER_COOKIE) {+ if (await approvedDevice(rest.join("="), "cookie")) return true;+ }+ }+ }+ const reqWithCookies = request as { cookies?: { getAll?: (n: string) => Array<{ value: string }> } };+ if (typeof reqWithCookies.cookies?.getAll === "function") {+ for (const { value } of reqWithCookies.cookies.getAll(CAMOUFOX_VIEWER_COOKIE)) {+ if (await approvedDevice(value, "cookie")) return true;+ }}return false;}@@ -72,7 +83,7 @@ const BOOTSTRAP_JS = [].join("");function bootstrap(method: string) {- const response = new NextResponse(method === "HEAD" ? null : BOOTSTRAP_HTML, {+ const response = new Response(method === "HEAD" ? null : BOOTSTRAP_HTML, {status: 200,headers: {"content-type": "text/html; charset=utf-8",@@ -91,7 +102,7 @@ function bootstrap(method: string) {}function bootstrapScript() {- const response = new NextResponse(BOOTSTRAP_JS, {+ const response = new Response(BOOTSTRAP_JS, {status: 200,headers: {"content-type": "application/javascript; charset=utf-8",@@ -104,25 +115,21 @@ function bootstrapScript() {return response;}-async function exchangeTicket(request: NextRequest) {+async function exchangeTicket(request: Request) {if (request.method !== "POST") return notFound();const match = /^Bearer ([A-Za-z0-9._-]{20,4096})$/.exec(request.headers.get("authorization") ?? "");if (!match) return notFound();const session = await approvedDevice(match[1], "ticket");if (!session) return notFound();- const response = new NextResponse(null, { status: 204 });- response.cookies.set(- CAMOUFOX_VIEWER_COOKIE,- createCamoufoxViewerCookie(session, process.env.OS_SESSION_SECRET ?? ""),- {- httpOnly: true,- secure: true,- sameSite: "strict",- path: "/",- maxAge:Math.max(0,Math.floor((Math.min(session.parent_expires_at,Date.now()+CAMOUFOX_VIEWER_COOKIE_TTL_MS)-Date.now())/1000)),+ const maxAge = Math.max(0, Math.floor((Math.min(session.parent_expires_at, Date.now() + CAMOUFOX_VIEWER_COOKIE_TTL_MS) - Date.now()) / 1000));+ const cookie = createCamoufoxViewerCookie(session, process.env.OS_SESSION_SECRET ?? "");+ const response = new Response(null, {+ status: 204,+ headers: {+ "set-cookie": `${CAMOUFOX_VIEWER_COOKIE}=${cookie}; Path=/; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=strict`,},- );+ });noStore(response.headers);return response;}@@ -133,7 +140,7 @@ async function exchangeTicket(request: NextRequest) {* exist. The returned symbol means the caller may proxy a read-only noVNC request.*/export async function gateCamoufoxViewer(- request: NextRequest,+ request: Request,pathname: string,): Promise<CamoufoxViewerGateResult> {if (pathname === "/__viewer_bootstrap.js") {@@ -147,7 +154,7 @@ export async function gateCamoufoxViewer() {const redirect = new URL(request.url);redirect.pathname = CAMOUFOX_VIEWER_ENTRY_PATH;- return NextResponse.redirect(redirect, 307);+ return Response.redirect(redirect, 307);}const inViewerNamespace =diff --git a/lib/managed-apps/session.ts b/lib/managed-apps/session.tsindex 917f66ed..55f14467 100644--- a/lib/managed-apps/session.ts+++ b/lib/managed-apps/session.ts@@ -1,4 +1,3 @@-import { NextResponse, type NextRequest } from "next/server";import { MIN_SECRET_LEN, signSession, verifySession, type SessionPayload } from "@/lib/auth/session";import { liveSessionAuthorized } from "@/lib/auth/live-authorization";import { managedAppOrigin, cockpitOrigin } from "./origin";@@ -42,8 +41,8 @@ export async function managedAppSession(request: Request, id: ManagedAppId): Pro}const SCRIPT = "(async()=>{const p=new URLSearchParams(location.hash.slice(1));const t=p.get('app_ticket');p.delete('app_ticket');history.replaceState(null,'',location.pathname+location.search+(p.toString()?'#'+p.toString():''));if(!t){document.body.textContent='Open this application from MSO to authorize it.';return;}const r=await fetch('/__mso_app_auth',{method:'POST',headers:{authorization:'Bearer '+t},credentials:'include',cache:'no-store'});if(!r.ok){document.body.textContent='Application authorization failed. Reopen it from MSO.';return;}location.reload();})().catch(()=>{document.body.textContent='Application authorization failed.';});";-function response(id: ManagedAppId, body: string | null, status: number, contentType = "text/plain; charset=utf-8") {- return new NextResponse(body, { status, headers: {+function response(id: ManagedAppId, body: string | null, status: number, contentType = "text/plain; charset=utf-8"): Response {+ return new Response(body, { status, headers: {"content-type": contentType, "cache-control": "no-store, no-transform","cdn-cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store","referrer-policy": "no-referrer", "x-content-type-options": "nosniff",@@ -52,16 +51,18 @@ function response(id: ManagedAppId, body: string | null, status: number, content} });}// An app receives a purpose- and origin-bound credential, never the cockpit cookie.-export async function gateManagedApp(request: NextRequest, id: ManagedAppId): Promise<NextResponse | null> {- if (request.nextUrl.pathname === "/__mso_app_bootstrap.js") return request.method === "GET" ? response(id, SCRIPT, 200, "application/javascript; charset=utf-8") : response(id, null, 404);- if (request.nextUrl.pathname === "/__mso_app_auth") {+export async function gateManagedApp(request: Request, id: ManagedAppId): Promise<Response | null> {+ const pathname = new URL(request.url).pathname;+ if (pathname === "/__mso_app_bootstrap.js") return request.method === "GET" ? response(id, SCRIPT, 200, "application/javascript; charset=utf-8") : response(id, null, 404);+ if (pathname === "/__mso_app_auth") {if (request.method !== "POST" || request.headers.get("origin") !== managedAppOrigin(id)) return response(id, null, 403);const token = /^Bearer ([A-Za-z0-9._-]{20,4096})$/.exec(request.headers.get("authorization") ?? "")?.[1];const secret = process.env.OS_SESSION_SECRET ?? "";const session = token ? verifyManagedAppSession(id, token, secret, "ticket") : null;if (!session || !await liveSessionAuthorized(session, "operator")) return response(id, null, 401);const result = response(id, null, 204);- result.cookies.set(MANAGED_APP_SESSION_COOKIE, createManagedAppCookie(id, session, secret), { httpOnly: true, secure: true, sameSite: "strict", path: "/", maxAge:Math.max(0,Math.floor((Math.min(session.parent_expires_at,Date.now()+COOKIE_TTL)-Date.now())/1000)) });+ const maxAge = Math.max(0, Math.floor((Math.min(session.parent_expires_at, Date.now() + COOKIE_TTL) - Date.now()) / 1000));+ result.headers.set("set-cookie", `${MANAGED_APP_SESSION_COOKIE}=${createManagedAppCookie(id, session, secret)}; Path=/; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=Strict`);return result;}if (await managedAppSession(request, id)) return null;diff --git a/lib/managed-apps/socket-policy.ts b/lib/managed-apps/socket-policy.tsindex 93b266af..35538a06 100644--- a/lib/managed-apps/socket-policy.ts+++ b/lib/managed-apps/socket-policy.ts@@ -1,4 +1,3 @@-import type { NextRequest } from "next/server";import { liveSessionAuthorized } from "@/lib/auth/live-authorization";import { MANAGED_APP_SESSION_COOKIE, verifyManagedAppSession } from "./session";import { CAMOUFOX_VIEWER_COOKIE, verifyCamoufoxViewerCookie } from "@/lib/camoufox/viewer-auth";@@ -30,7 +29,24 @@ async function defaultOrcaReadiness(): Promise<OrcaReadinessResult> {}}-export async function socketPolicy(request: NextRequest, deps: SocketPolicyDeps = {}) {+function cookieValues(request: Request, name: string): string[] {+ const cookieHeader = request.headers.get("cookie");+ if (cookieHeader) {+ const values: string[] = [];+ for (const part of cookieHeader.split(";")) {+ const [k, ...rest] = part.trim().split("=");+ if (k === name) values.push(rest.join("="));+ }+ if (values.length > 0) return values;+ }+ const reqWithCookies = request as { cookies?: { getAll?: (n: string) => Array<{ value: string }> } };+ if (typeof reqWithCookies.cookies?.getAll === "function") {+ return reqWithCookies.cookies.getAll(name).map((c) => c.value);+ }+ return [];+}++export async function socketPolicy(request: Request, deps: SocketPolicyDeps = {}) {if (IS_DEMO || request.method !== "GET") return null;const host = request.headers.get("host") ?? "", origin = request.headers.get("origin");if (origin) { try { if (new URL(origin).host !== host) return null; } catch { return null; } }@@ -45,7 +61,7 @@ export async function socketPolicy(request: NextRequest, deps: SocketPolicyDeps}const secret = process.env.OS_SESSION_SECRET ?? "";let identity: string | undefined;- for (const { value } of request.cookies.getAll(viewer ? CAMOUFOX_VIEWER_COOKIE : MANAGED_APP_SESSION_COOKIE)) {+ for (const value of cookieValues(request, viewer ? CAMOUFOX_VIEWER_COOKIE : MANAGED_APP_SESSION_COOKIE)) {const session = viewer ? verifyCamoufoxViewerCookie(value, secret) : verifyManagedAppSession(app!, value, secret);if (!session?.device_id) continue;if (viewer) {@@ -83,8 +99,9 @@ export async function socketPolicy(request: NextRequest, deps: SocketPolicyDeps} catch {return null;}- const pathname = viewer ? camoufoxViewerUpstreamPath(request.nextUrl.pathname) : request.nextUrl.pathname;+ const url = new URL(request.url);+ const pathname = viewer ? camoufoxViewerUpstreamPath(url.pathname) : url.pathname;if (!pathname || pathname.startsWith("/_next")) return null;- const target = new URL(base); target.pathname = pathname; target.search = request.nextUrl.search;+ const target = new URL(base); target.pathname = pathname; target.search = url.search;return { identity: socketIdentity, target: target.toString(), headers: Object.fromEntries(upstreamSocketHeaders(request.headers, app ?? undefined, base)) };}diff --git a/lib/surfaces/session-gate.ts b/lib/surfaces/session-gate.tsindex 03e6bae1..bbae16f8 100644--- a/lib/surfaces/session-gate.ts+++ b/lib/surfaces/session-gate.ts@@ -1,4 +1,3 @@-import { NextResponse, type NextRequest } from "next/server";import { liveSessionAuthorized } from "@/lib/auth/live-authorization";import type { SurfaceApp } from "@/lib/contracts/surface-app";import { createShellAppCredential, verifyShellAppCredential, shellAppSession, SHELL_APP_COOKIE, SHELL_APP_COOKIE_TTL } from "./session";@@ -10,15 +9,15 @@ export function shellSessionHeaders() {export function shellAppResponseHeaders() {return { ...shellSessionHeaders(), "content-security-policy": `frame-ancestors ${new URL(process.env.OS_PUBLIC_ORIGIN!).origin}` };}-function response(body: string | null, status: number, contentType = "text/plain; charset=utf-8") {- return new NextResponse(body, { status, headers: { ...shellAppResponseHeaders(), "content-type": contentType,+function response(body: string | null, status: number, contentType = "text/plain; charset=utf-8"): Response {+ return new Response(body, { status, headers: { ...shellAppResponseHeaders(), "content-type": contentType,"content-security-policy": `default-src 'none'; script-src 'self'; connect-src 'self'; frame-ancestors ${new URL(process.env.OS_PUBLIC_ORIGIN!).origin}` } });}function script() {return "(async()=>{const p=new URLSearchParams(location.hash.slice(1));const t=p.get('app_ticket');p.delete('app_ticket');history.replaceState(null,'',location.pathname+location.search+(p.toString()?'#'+p.toString():''));if(!t){location.replace(decodeURIComponent(document.body.dataset.msoLogin));return;}const r=await fetch('/__mso_app_auth',{method:'POST',headers:{authorization:'Bearer '+t},credentials:'include',cache:'no-store'});if(!r.ok){document.body.textContent='MSO session expired. Reopen this application from MSO.';return;}location.reload();})().catch(()=>{document.body.textContent='Application authorization failed.';});";}-export async function gateShellApp(request: NextRequest, app: SurfaceApp) {- const pathname = request.nextUrl.pathname;+export async function gateShellApp(request: Request, app: SurfaceApp): Promise<Response | null> {+ const pathname = new URL(request.url).pathname;if (pathname === "/__mso_app_bootstrap.js") return request.method === "GET" ? response(script(), 200, "application/javascript; charset=utf-8") : response(null, 404);if (pathname === "/__mso_app_auth") {if (request.method !== "POST" || request.headers.get("origin") !== app.origin) return response(null, 403);@@ -27,9 +26,8 @@ export async function gateShellApp(request: NextRequest, app: SurfaceApp) {const session = token ? verifyShellAppCredential(app, token, secret, "ticket") : null;if (!session || !await liveSessionAuthorized(session, "owner")) return response(null, 401);const result = response(null, 204);- result.cookies.set(SHELL_APP_COOKIE, createShellAppCredential(app, session, secret, "cookie"), {- httpOnly: true, secure: true, sameSite: "strict", path: "/", maxAge: Math.floor(Math.max(0, Math.min(SHELL_APP_COOKIE_TTL, session.parent_expires_at - Date.now()) / 1000)),- });+ const maxAge = Math.floor(Math.max(0, Math.min(SHELL_APP_COOKIE_TTL, session.parent_expires_at - Date.now()) / 1000));+ result.headers.set("set-cookie", `${SHELL_APP_COOKIE}=${createShellAppCredential(app, session, secret, "cookie")}; Path=/; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=strict`);return result;}if (await shellAppSession(request, app)) return null;diff --git a/lib/surfaces/socket-policy.ts b/lib/surfaces/socket-policy.tsindex 1259d907..15cdf230 100644--- a/lib/surfaces/socket-policy.ts+++ b/lib/surfaces/socket-policy.ts@@ -1,13 +1,13 @@-import type { NextRequest } from "next/server";import { sessionAppForHost, shellAppSession, shellAppTarget, shellAppUpstreamHeaders } from "./session";/** The shared server socket relay rechecks this authority before every delivery. */-export async function shellAppSocketPolicy(request: NextRequest) {+export async function shellAppSocketPolicy(request: Request) {const app = await sessionAppForHost(request.headers.get("host") ?? "");- if (!app || request.headers.get("origin") !== app.origin || request.nextUrl.pathname.startsWith("/__mso_") ||- request.nextUrl.pathname.startsWith("/_next")) return null;+ const url = new URL(request.url);+ if (!app || request.headers.get("origin") !== app.origin || url.pathname.startsWith("/__mso_") ||+ url.pathname.startsWith("/_next")) return null;const session = await shellAppSession(request, app);if (!session?.device_id) return null;- return { identity: session.device_id, target: shellAppTarget(app, request.nextUrl).toString(),+ return { identity: session.device_id, target: shellAppTarget(app, url).toString(),headers: Object.fromEntries(shellAppUpstreamHeaders(request.headers, app)) };}diff --git a/next.config.mjs b/next.config.mjsindex d7bef962..be02b7bd 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -90,6 +90,7 @@ const nextConfig = {// Tree-shake heavy icon/radix barrels — keeps the OS shell bundle lean.optimizePackageImports: ["lucide-react",+ "@phosphor-icons/react","@radix-ui/react-dialog","@radix-ui/react-dropdown-menu","@radix-ui/react-tooltip",