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
fix(oauth): re-register a cached public client id on demand
MSO18a3ff022e51
diff --git a/app/oauth/authorize/actions.test.ts b/app/oauth/authorize/actions.test.tsindex cbcf9559..d15b29cb 100644--- a/app/oauth/authorize/actions.test.ts+++ b/app/oauth/authorize/actions.test.ts@@ -3,13 +3,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({requireSession: vi.fn(),getClient: vi.fn(),+ ensureClient: vi.fn(),storeCode: vi.fn(),randomToken: vi.fn(),}));vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));vi.mock("@/lib/mcp/store", () => ({- getClient: mocks.getClient, storeCode: mocks.storeCode, CODE_TTL_MS: 60_000,+ getClient: mocks.getClient,+ ensureClient: mocks.ensureClient,+ isAutoRegisterableClientId: (id: string) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id) && !/^(manual:|pat:|mso_)/.test(id),+ storeCode: mocks.storeCode, CODE_TTL_MS: 60_000,}));vi.mock("@/lib/mcp/pkce", () => ({randomToken: mocks.randomToken,@@ -49,6 +53,7 @@ describe("OAuth consent approval", () => {mocks.requireSession.mockResolvedValue(true);mocks.randomToken.mockReturnValue("mso_code_test");mocks.getClient.mockResolvedValue({ name: "ChatGPT", profile: "chatgpt", redirectUris: ["https://chatgpt.com/connector/oauth/test"] });+ mocks.ensureClient.mockResolvedValue({ name: "ChatGPT", profile: "full", redirectUris: ["https://chatgpt.com/connector/oauth/test"] });});afterEach(() => vi.unstubAllEnvs());@@ -78,11 +83,21 @@ describe("OAuth consent approval", () => {expect(mocks.storeCode).not.toHaveBeenCalled();});- it.each(["chatgpt-mso", "mcpc_pruned", "manual:pat:another-owner"])("rejects unregistered principal %s even with an HTTPS callback", async (id) => {+ it.each(["manual:pat:another-owner", "pat:abc", "mso_code_x"])("rejects reserved MSO principal %s even with an HTTPS callback", async (id) => {mocks.getClient.mockResolvedValue(null);const data = form("https://attacker.example/callback"); data.set("client_id", id);expect(await approve(data)).toMatchObject({ ok: false, error: expect.stringContaining("register") });expect(mocks.storeCode).not.toHaveBeenCalled();+ expect(mocks.ensureClient).not.toHaveBeenCalled();+ });++ it("registers a self-declared public client id on demand and continues the flow", async () => {+ mocks.getClient.mockResolvedValue(null);+ const data = form();+ data.set("client_id", "chatgpt-mso");+ await expect(approve(data)).resolves.toMatchObject({ ok: true, redirectTo: expect.stringContaining("code=mso_code_test") });+ expect(mocks.ensureClient).toHaveBeenCalledWith("chatgpt-mso", ["https://chatgpt.com/connector/oauth/test"]);+ expect(mocks.storeCode).toHaveBeenCalledWith("mso_code_test", expect.objectContaining({ clientId: "chatgpt-mso", profile: "full" }));});it("does not authorize a registered client at another callback", async () => {diff --git a/app/oauth/authorize/actions.ts b/app/oauth/authorize/actions.tsindex a3dbf485..25dbd49f 100644--- a/app/oauth/authorize/actions.ts+++ b/app/oauth/authorize/actions.ts@@ -2,7 +2,8 @@import { requireSession } from "@/lib/auth/require-session";import { headers } from "next/headers";-import { getClient, storeCode, CODE_TTL_MS } from "@/lib/mcp/store";+import { getClient, ensureClient, isAutoRegisterableClientId, storeCode, CODE_TTL_MS } from "@/lib/mcp/store";+import type { McpToolProfile } from "@/lib/mcp/tool-contract";import { randomToken, isAllowedRedirect } from "@/lib/mcp/pkce";import { parseScope, clampScope, mcpEnabled, type Scope } from "@/lib/mcp/scope";@@ -48,27 +49,50 @@ export async function approve(form: FormData): Promise<ApprovalResult> {if (!expectedIssuer || issuer !== expectedIssuer || resource !== `${expectedIssuer}/mcp`) return { ok: false, error: "OAuth resource/issuer mismatch." };const client = await getClient(clientId);- // Only server-generated registrations own durable client principals.- if (!client) return { ok: false, error: "This client must register before requesting authorization." };+ // An unknown but valid public client id is registered on demand here too: the+ // consent page already offered Allow for it (inert until this approval), and+ // ChatGPT's user-defined client caches its id across connects. Reserved MSO+ // principals and malformed ids still fail closed.+ if (!client && !isAutoRegisterableClientId(clientId)) {+ return { ok: false, error: "This client must register before requesting authorization." };+ }+ if (!client) {+ await ensureClient(clientId, [redirectUri]);+ return approveRegistered({ clientId, redirectUri, challenge, state, scope, resource, issuer, offlineAccess, profile: "full" });+ }if (!client.redirectUris.includes(redirectUri)) {return { ok: false, error: "That redirect target is not registered for this client." };}+ return approveRegistered({ clientId, redirectUri, challenge, state, scope, resource, issuer, offlineAccess, profile: client.profile });+}++async function approveRegistered(input: {+ clientId: string;+ redirectUri: string;+ challenge: string;+ state: string;+ scope: Scope;+ resource: string;+ issuer: string;+ offlineAccess: boolean;+ profile?: McpToolProfile;+}): Promise<ApprovalResult> {const code = randomToken("mso_code_");await storeCode(code, {- clientId,- redirectUri,- codeChallenge: challenge,- scope,- resource,- profile: client.profile,- offlineAccess,+ clientId: input.clientId,+ redirectUri: input.redirectUri,+ codeChallenge: input.challenge,+ scope: input.scope,+ resource: input.resource,+ profile: input.profile,+ offlineAccess: input.offlineAccess,expiresAt: Date.now() + CODE_TTL_MS,});- const dest = new URL(redirectUri);+ const dest = new URL(input.redirectUri);dest.searchParams.set("code", code);- if (state) dest.searchParams.set("state", state);- dest.searchParams.set("iss", issuer);+ if (input.state) dest.searchParams.set("state", input.state);+ dest.searchParams.set("iss", input.issuer);return { ok: true, redirectTo: dest.toString() };}diff --git a/app/oauth/authorize/page.tsx b/app/oauth/authorize/page.tsxindex 4809364e..9f9bd2ed 100644--- a/app/oauth/authorize/page.tsx+++ b/app/oauth/authorize/page.tsx@@ -2,7 +2,7 @@ import Link from "next/link";import { notFound } from "next/navigation";import { headers } from "next/headers";import { requireSession } from "@/lib/auth/require-session";-import { getClient } from "@/lib/mcp/store";+import { getClient, isAutoRegisterableClientId } from "@/lib/mcp/store";import { isAllowedRedirect } from "@/lib/mcp/pkce";import { denyUrl, selfUrl } from "@/lib/mcp/redirect";import { mcpEnabled, maxScope } from "@/lib/mcp/scope";@@ -79,11 +79,15 @@ export default async function AuthorizePage({// Fail loudly and specifically BEFORE showing an Allow button — a consent screen// that approves a malformed request is worse than one that refuses to render.- const client = await getClient(clientId);+ const provided = (await getClient(clientId)) ?? (+ isAutoRegisterableClientId(clientId)+ ? { name: clientId, redirectUris: [redirectUri], createdAt: 0 }+ : null+ );const problem =!clientId ? "The client did not send a client_id."- : !client ? "This client must register before requesting authorization."- : !client.redirectUris.includes(redirectUri) ? "That redirect target is not registered for this client."+ : !provided ? "This client must register before requesting authorization."+ : !provided.redirectUris.includes(redirectUri) ? "That redirect target is not registered for this client.": !isAllowedRedirect(redirectUri) ? "The client's redirect target is missing, or is not https (or localhost).": method !== "S256" || !challenge ? "The client did not use PKCE with S256, which mso requires.": !issuer || resource !== expectedResource ? "The OAuth resource does not match this MSO MCP endpoint."@@ -113,7 +117,7 @@ export default async function AuthorizePage({return (<Shell><ConsentForm- clientName={client?.name ?? clientId}+ clientName={provided?.name ?? clientId}redirectUri={redirectUri}denyUrl={deny}ceiling={maxScope()}diff --git a/docs/MCP-HOW-TO.md b/docs/MCP-HOW-TO.mdindex 1fc1b563..295554e8 100644--- a/docs/MCP-HOW-TO.md+++ b/docs/MCP-HOW-TO.md@@ -57,7 +57,8 @@ Pilih scope sesuai tugas: jangan menyebut seluruh MSO read-only hanya karena satdan autentikasi **OAuth**. Gunakan domain instalasi sendiri, bukan `/api/mcp` atau `/sse`.4. Selesaikan login/consent pada domain MSO dan pilih scope minimum. Gunakan discovery/DCRuntuk mendaftarkan callback URL dan mendapatkan Client ID unik tanpa client secret.- Client ID manual lama `chatgpt-mso` perlu didaftarkan dan disambungkan ulang.+ Client ID manual lama `chatgpt-mso` kini didaftarkan ulang otomatis bila belum ada,+ memakai callback yang sama; reconnect ke callback yang sama tetap berhasil.Jangan memasukkan password MSO sebagai client secret dan jangan memilih No Authentication.5. Scan/refresh tools, simpan/publikasikan sesuai UI workspace, lalu aktifkan MSO pada percakapan.6. Uji dengan `@MSO tolong cek status VPS tanpa mengubah apa pun`.diff --git a/docs/MCP.md b/docs/MCP.mdindex 74844bc2..0988ae3e 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -94,9 +94,13 @@ client-specific numbered steps. Use [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) fthe current field mapping, OAuth sequence, tool-snapshot refresh and troubleshooting.OAuth clients register their exact callback URLs through `/oauth/register` (RFC 7591).-Use the returned unique Client ID without a client secret. Unregistered/manual IDs,-including the former `chatgpt-mso` fallback and pruned registrations, cannot authorize;-register and reconnect instead. Client IDs are generated by the server and never reused.+Use the returned unique Client ID without a client secret. A client that caches its+own id across connects (ChatGPT's user-defined client) is tolerated: a well-formed+public id that is unknown — a swept registration, or a self-declared id the client+kept — is registered on demand at `/oauth/authorize` for its exact callback, remaining+inert until the owner approves and completes PKCE. Server-owned MSO principals+(`manual:`, `pat:`, `mso_`) and malformed ids still cannot authorize; register and+reconnect instead. Server-generated Client IDs are never reused.Refresh grants have an absolute 90-day lifetime from consent. Rotation is limited to oneper 30 seconds per authenticated family, independent of proxy/IP headers. Expired accessdiff --git a/lib/mcp/store-clients.test.ts b/lib/mcp/store-clients.test.tsnew file mode 100644index 00000000..4894c385--- /dev/null+++ b/lib/mcp/store-clients.test.ts@@ -0,0 +1,41 @@+import { afterAll, beforeEach, describe, expect, it } from "vitest";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";++const DIR = path.join(os.tmpdir(), `mso-mcp-clients-test-${process.pid}`);+process.env.OS_MCP_STORE = path.join(DIR, "mcp.json");++const store = await import("./store-clients");++beforeEach(async () => {+ await fs.rm(DIR, { recursive: true, force: true });+});+afterAll(async () => {+ await fs.rm(DIR, { recursive: true, force: true });+});++describe("on-demand client registration", () => {+ it("registers a self-declared public client id, unions redirects, and refuses reserved principals", async () => {+ const first = await store.ensureClient("chatgpt-user-defined", ["https://chatgpt.com/cb"], "ChatGPT");+ expect(first).toMatchObject({ name: "ChatGPT", redirectUris: ["https://chatgpt.com/cb"] });+ expect(await store.getClient("chatgpt-user-defined")).toMatchObject({ name: "ChatGPT" });++ // A reconnect may present an additional callback; the client keeps its identity.+ const again = await store.ensureClient("chatgpt-user-defined", ["https://chatgpt.com/cb", "http://localhost:1455/cb"]);+ expect(again.redirectUris).toEqual(["https://chatgpt.com/cb", "http://localhost:1455/cb"]);++ await expect(store.ensureClient("manual:pat:other-owner", ["https://x.example/cb"])).rejects.toThrow(/reserved/);+ await expect(store.ensureClient("mso_code_leak", ["https://x.example/cb"])).rejects.toThrow(/reserved/);+ });++ it("classifies auto-registerable ids and rejects reserved or malformed ones", () => {+ expect(store.isAutoRegisterableClientId("chatgpt-mso")).toBe(true);+ expect(store.isAutoRegisterableClientId("mcpc_abc123")).toBe(true);+ expect(store.isAutoRegisterableClientId("manual:pat:x")).toBe(false);+ expect(store.isAutoRegisterableClientId("pat:x")).toBe(false);+ expect(store.isAutoRegisterableClientId("mso_refresh_x")).toBe(false);+ expect(store.isAutoRegisterableClientId("")).toBe(false);+ expect(store.isAutoRegisterableClientId("has space")).toBe(false);+ });+});diff --git a/lib/mcp/store-clients.ts b/lib/mcp/store-clients.tsnew file mode 100644index 00000000..589fc1b9--- /dev/null+++ b/lib/mcp/store-clients.ts@@ -0,0 +1,78 @@+import { randomUUID } from "node:crypto";+import { detectMcpToolProfile } from "./client-profile";+import { assertMcpClientCapacity, commitMcpStore as write, mutateMcpStore as mutate, readMcpStore as read, sweepMcpStore as sweep } from "./store-state";+import type { McpClient } from "./store-types";++// Registration, lookup and the on-demand compatibility seam. Split out of store.ts+// to keep both files inside the 220-line architecture ratchet; re-exported from+// store.ts so callers keep one import path.++export function registerClient(name: string, redirectUris: string[]): Promise<string> {+ return mutate(async () => {+ const store = sweep(await read());+ assertMcpClientCapacity(store);+ const clientId = "mcpc_" + randomUUID().replaceAll("-", "").slice(0, 24);+ const cleanName = name.slice(0, 80) || "MCP Client";+ store.clients[clientId] = {+ name: cleanName,+ redirectUris,+ profile: detectMcpToolProfile({ clientId, name: cleanName, redirectUris }),+ createdAt: Date.now(),+ };+ await write(store);+ return clientId;+ });+}++export async function getClient(clientId: string): Promise<McpClient | null> {+ const clients = sweep(await read()).clients;+ return Object.hasOwn(clients, clientId) ? clients[clientId] : null;+}++// MSO principals are server-owned. A request that names one of these is trying to+// alias an existing authority and must never be auto-registered.+const RESERVED_CLIENT_ID = /^(manual:|pat:|mso_)/;++/** A self-declared public client id that may be registered on demand. */+export function isAutoRegisterableClientId(clientId: string): boolean {+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(clientId) && !RESERVED_CLIENT_ID.test(clientId);+}++/**+ * Compatibility seam for OAuth clients that cache a client_id across connects+ * (ChatGPT's user-defined client is the motivating case). The MSO design kept+ * rejecting any id it had not minted itself, but `/oauth/register` is ALREADY a+ * public endpoint that mints a client for any https callback — so the rejection+ * added no security; it only broke clients whose registration had been swept.+ *+ * Idempotent: an existing client is returned with its redirect list unioned (a+ * reconnect may present a new callback). A new registration is server-side and+ * INERT until the owner approves it on the consent page and completes PKCE, and+ * reserved MSO principals are refused outright.+ */+export function ensureClient(clientId: string, redirectUris: string[], name?: string): Promise<McpClient> {+ return mutate(async () => {+ const store = sweep(await read());+ const existing = Object.hasOwn(store.clients, clientId) ? store.clients[clientId] : undefined;+ if (existing) {+ const merged = [...new Set([...existing.redirectUris, ...redirectUris])].slice(0, 8);+ if (merged.length !== existing.redirectUris.length) {+ store.clients[clientId] = { ...existing, redirectUris: merged };+ await write(store);+ }+ return store.clients[clientId];+ }+ if (!isAutoRegisterableClientId(clientId)) throw new Error("reserved MCP client id");+ assertMcpClientCapacity(store);+ const cleanName = (name ?? "").slice(0, 80) || "MCP Client";+ const uris = [...new Set(redirectUris)].slice(0, 8);+ store.clients[clientId] = {+ name: cleanName,+ redirectUris: uris,+ profile: detectMcpToolProfile({ clientId, name: cleanName, redirectUris: uris }),+ createdAt: Date.now(),+ };+ await write(store);+ return store.clients[clientId];+ });+}diff --git a/lib/mcp/store.ts b/lib/mcp/store.tsindex cfbd5d98..41335313 100644--- a/lib/mcp/store.ts+++ b/lib/mcp/store.ts@@ -2,21 +2,19 @@ import { TenantDenied } from "@/lib/tenancy/authority";import { tenantCredentialFields } from "@/lib/tenancy/credentials";import { authorizeMcpTenantGrant } from "@/lib/tenancy/runtime";import type { TenantCredentialBinding } from "@/lib/tenancy/types";-import { randomUUID } from "node:crypto";import { sha256hex } from "./pkce";import type { Scope } from "./scope";import type { McpToolProfile } from "./tool-contract";-import { detectMcpToolProfile } from "./client-profile";import {commitMcpStore as write,mutateMcpStore as mutate,- assertMcpClientCapacity,readMcpStore as read,sweepMcpStore as sweep,} from "./store-state";-import type { McpClient, McpCode, McpRefreshToken, McpToken } from "./store-types";+import type { McpCode, McpRefreshToken, McpToken } from "./store-types";export type { McpClient, McpCode, McpRefreshToken, McpToken, TokenView } from "./store-types";+export { registerClient, getClient, ensureClient, isAutoRegisterableClientId } from "./store-clients";export const CODE_TTL_MS = 60_000;export const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;@@ -24,27 +22,6 @@ export const OAUTH_ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000;export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;export class OAuthRefreshRateLimit extends Error {}-export function registerClient(name: string, redirectUris: string[]): Promise<string> {- return mutate(async () => {- const store = sweep(await read());- assertMcpClientCapacity(store);- const clientId = "mcpc_" + randomUUID().replaceAll("-", "").slice(0, 24);- const cleanName = name.slice(0, 80) || "MCP Client";- store.clients[clientId] = {- name: cleanName,- redirectUris,- profile: detectMcpToolProfile({ clientId, name: cleanName, redirectUris }),- createdAt: Date.now(),- };- await write(store);- return clientId;- });-}--export async function getClient(clientId: string): Promise<McpClient | null> {- const clients = sweep(await read()).clients;- return Object.hasOwn(clients, clientId) ? clients[clientId] : null;-}export function storeCode(code: string, rec: McpCode): Promise<void> {const captured = structuredClone(rec), tenant = tenantCredentialFields(captured);diff --git a/scripts/e2e/mcp-settings.mjs b/scripts/e2e/mcp-settings.mjsindex 993ca0ae..f7bdde34 100644--- a/scripts/e2e/mcp-settings.mjs+++ b/scripts/e2e/mcp-settings.mjs@@ -148,7 +148,7 @@ export async function oauthRegistrationJourney(page, fixture) {try {for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {await page.setViewportSize(viewport);- await page.goto(consent("chatgpt-mso", "https://attacker.invalid/callback"));+ await page.goto(consent("manual:pat:another-owner", "https://attacker.invalid/callback"));await expect(page.getByRole("heading", { name: "Cannot connect this client" })).toBeVisible();await expect(page.getByText("This client must register before requesting authorization.")).toBeVisible();await expect(page.getByRole("button", { name: "Allow", exact: true })).toHaveCount(0);@@ -167,9 +167,14 @@ export async function oauthRegistrationJourney(page, fixture) {const url = new URL(page.url()); expect(url.searchParams.get("state")).toBe("fixture-state");const exchanged = await page.request.post(fixture.base + "/oauth/token", { form: { grant_type: "authorization_code", code: url.searchParams.get("code"), code_verifier: verifier, client_id: clientId, redirect_uri: callback, resource: fixture.base + "/mcp" } });expect(exchanged.status()).toBe(200); expect((await exchanged.json()).token_type).toBe("Bearer");- // Replacing the isolated test store simulates a pruned registration, never owner data.+ // Replacing the isolated test store simulates a swept registration, never owner+ // data. A self-declared public id may re-register on demand at its own callback+ // (consent renders, Allow is offered), but a reserved MSO principal fails closed.await fixture.seedMcp();await page.goto(consent(clientId));+ await expect(page.getByRole("heading", { name: /to your VPS$/ })).toBeVisible();+ await expect(page.getByRole("button", { name: "Allow", exact: true })).toHaveCount(1);+ await page.goto(consent("manual:pat:pruned"));await expect(page.getByText("This client must register before requesting authorization.")).toBeVisible();await expect(page.getByRole("button", { name: "Allow", exact: true })).toHaveCount(0);}