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.

fix(api): restore the models provider name the route extraction dropped (#169)

Abdurrahman Fakhrul0185bd1354aa
diff --git a/app/api/auth/session-cookie.test.ts b/app/api/auth/session-cookie.test.ts
index 20f03ace..53073b67 100644
--- a/app/api/auth/session-cookie.test.ts
+++ b/app/api/auth/session-cookie.test.ts
@@ -18,6 +18,7 @@ vi.mock("@/lib/auth/device-store", () => ({
// constant; only its next/headers dependency (needs a request scope) is stubbed.
vi.mock("next/headers", () => ({ cookies: async () => ({ getAll: () => [] }) }));
+
const DEVICE = "a".repeat(32);
const PASSWORD = "correct-horse";
@@ -36,6 +37,7 @@ async function login(host = "mso.example.com"): Promise<string[]> {
}
async function logout(host = "mso.example.com"): Promise<string[]> {
+ await registerCookieReader();
const { POST } = await import("./logout/route");
const res = await POST(new Request("http://internal/api/auth/logout", { method: "POST", headers: { host } }));
return res.headers.getSetCookie();
@@ -50,6 +52,17 @@ beforeEach(() => {
vi.resetModules();
});
+// `lib/` no longer imports next/headers; instrumentation.ts registers the reader at boot.
+// Registration must happen AFTER vi.resetModules(), which is why it lives here and not at
+// module scope, and it exercises the same seam production uses.
+async function registerCookieReader(): Promise<void> {
+ const { registerSessionCookieReader } = await import("@/lib/auth/require-session");
+ registerSessionCookieReader(async () => {
+ const { cookies } = await import("next/headers");
+ return (await cookies()).getAll("session");
+ });
+}
+
afterEach(() => {
delete process.env.OS_SESSION_COOKIE_DOMAIN;
});
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index ab259167..da6e9c4f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,7 +13,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
-- `api` restore the provider name in the models catalog, and drop three new em dashes
+- `api` restore the models provider name the route extraction dropped (#168)
- `build` restore the turbopackIgnore annotation the route extraction dropped
**Faster**
@@ -24,6 +24,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Changed**
+- `auth` register the session cookie reader from the framework entry, so lib is next-free
- `api` every route handler is a thin adapter, and lib is next-free
- `lib` drop static next/* imports, plus three measured perf findings
diff --git a/docs/MSO-MIGRATION.md b/docs/MSO-MIGRATION.md
index 140219cd..be356000 100644
--- a/docs/MSO-MIGRATION.md
+++ b/docs/MSO-MIGRATION.md
@@ -602,14 +602,19 @@ The largest durable win and the cheapest real work, because 96 % of `lib/` needs
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.
+ `base64url` payloads, so no encoding change.
+
+ **Done 2026-10-29 for the dynamic half too.** The one remaining exception was
+ `lib/auth/require-session.ts` reaching Next through a *dynamic* `import("next/headers")`
+ inside the default `nextSessionCookieReader`, because `cookies()` is request-scoped
+ framework plumbing. That reader now moved to the framework entry: `instrumentation.ts`
+ imports `next/headers` once at boot and calls `registerSessionCookieReader(...)`, while
+ `lib/auth` holds only a registered callback and a `defaultCookieReader()` that THROWS a
+ named error when nothing registered. Nothing is threaded through the 54 call sites, the
+ seam stays a default parameter, and a SvelteKit adapter can register its own reader the
+ same way. The failure mode is deliberate: an unregistered reader fails closed and loud,
+ never silently unauthenticated. The exit criterion is now a plain `next/*` grep in `lib/`,
+ which covers both static imports and `import(...)`.
- 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.)
diff --git a/instrumentation.ts b/instrumentation.ts
index 5164813a..ab424186 100644
--- a/instrumentation.ts
+++ b/instrumentation.ts
@@ -6,6 +6,15 @@ import type { Instrumentation } from "next";
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
+ // The only place that knows how Next exposes cookies. `lib/auth` stays framework-free
+ // and asks this registered reader, which keeps Phase 2's boundary honest. A failure
+ // here is NOT swallowed: without it every session read fails closed, and a silent
+ // catch would turn that into a confusing "not registered" error per request.
+ await import("next/headers").then(({ cookies }) =>
+ import("./lib/auth/require-session").then(({ registerSessionCookieReader, SESSION_COOKIE }) =>
+ registerSessionCookieReader(async () => (await cookies()).getAll(SESSION_COOKIE)),
+ ),
+ );
// Warm durable agent-session maintenance before accepting requests. Backfilling
// the conversation index once at boot keeps MCP lookup O(1) even on hosts with
// thousands of old CLI sessions; archive retention remains best-effort.
diff --git a/lib/auth/require-session.test.ts b/lib/auth/require-session.test.ts
index f9bd3a97..1d019bb0 100644
--- a/lib/auth/require-session.test.ts
+++ b/lib/auth/require-session.test.ts
@@ -35,6 +35,14 @@ beforeEach(() => {
delete process.env.OS_SESSION_COOKIE_DOMAIN;
});
+// The framework cookie read is registered by instrumentation.ts in production. The test
+// does the same thing through the same seam, which is also the proof the seam works.
+const { registerSessionCookieReader } = await import("./require-session");
+registerSessionCookieReader(async () => {
+ const { cookies } = await import("next/headers");
+ return (await cookies()).getAll("session");
+});
+
describe("getSession with a shadowed cookie", () => {
it("accepts the real session even when a forged one sorts first", async () => {
const { getSession } = await import("./require-session");
diff --git a/lib/auth/require-session.ts b/lib/auth/require-session.ts
index ac267cf6..212e7eef 100644
--- a/lib/auth/require-session.ts
+++ b/lib/auth/require-session.ts
@@ -19,18 +19,39 @@ export type SessionContext = {
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);
+// `lib/` must not reach for a framework, so the Next cookie source is registered by the
+// framework's own entry point (instrumentation.ts) instead of imported here. Anything that
+// forgets to register gets a loud error rather than a silent unauthenticated request.
+//
+// The slot lives on `globalThis` on purpose. In a production build the bundler can inline
+// this module into more than one chunk (instrumentation and the route graph are separate
+// entries), which yields two module instances each with its own variable. A registration
+// that landed in the instrumentation copy would then be invisible to every route, and the
+// process would fail closed on every request with "not registered". One process-global slot
+// is what makes the registration actually shared.
+const READER_SLOT = Symbol.for("mso.sessionCookieReader");
+
+type ReaderSlot = { [READER_SLOT]?: SessionCookieReader };
+
+export function registerSessionCookieReader(reader: SessionCookieReader): void {
+ (globalThis as ReaderSlot)[READER_SLOT] = reader;
+}
+
+function defaultCookieReader(): Promise<Iterable<{ value: string }>> | Iterable<{ value: string }> {
+ const reader = (globalThis as ReaderSlot)[READER_SLOT];
+ if (!reader) {
+ throw new Error(
+ "session cookie reader is not registered; call registerSessionCookieReader() from the app entry (instrumentation.ts)",
+ );
+ }
+ return reader();
}
// 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(
- cookieReader: SessionCookieReader = nextSessionCookieReader,
+ cookieReader: SessionCookieReader = defaultCookieReader,
): Promise<SessionContext | null> {
if (IS_DEMO) return null;
const candidates = await cookieReader();
@@ -47,14 +68,14 @@ export async function getSessionContext(
/** Compatibility payload accessor for existing callers that do not need role data. */
export async function getSession(
- cookieReader: SessionCookieReader = nextSessionCookieReader,
+ cookieReader: SessionCookieReader = defaultCookieReader,
): Promise<SessionPayload | null> {
return (await getSessionContext(cookieReader))?.session ?? null;
}
export async function requireSession(
minimumRole: DeviceRole = "viewer",
- cookieReader: SessionCookieReader = nextSessionCookieReader,
+ cookieReader: SessionCookieReader = defaultCookieReader,
): Promise<boolean> {
const context = await getSessionContext(cookieReader);
return context !== null && roleAtLeast(context.role, minimumRole);
@@ -63,7 +84,7 @@ export async function requireSession(
// 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(
- cookieReader: SessionCookieReader = nextSessionCookieReader,
+ cookieReader: SessionCookieReader = defaultCookieReader,
): Promise<string | null> {
return (await getSessionContext(cookieReader))?.session.device_id ?? null;
}