fix(zed): harden OAuth lifecycle and live model support

- executors/zed.js: use exact wire values (anthropic, open_ai, google, x_ai)
  and strip incompatible Vertex safetySettings on the Google path
- shared/zedAuth.js: robust callback query parsing, reject garbage PKCS#1 v1.5
  decryptions, and thread proxyOptions when fetching LLM tokens
- oauth: preserve systemId across authorize/register/exchange lifecycle,
  renew proxy idle timeout on reuse, and ignore non-callback localhost requests
- shared/OAuthModal.js: track owned proxy in flowRef and stop at most once
- api/providers/[id]/models: add connection-scoped live Zed model resolver
- registry: unhide provider in dashboard
- tests: add unit coverage for wire format, native auth, and live models
This commit is contained in:
Mosabbir Maruf
2026-09-17 18:46:13 +07:00
parent 725e2c1187
commit ef18175226
13 changed files with 866 additions and 105 deletions

View File

@@ -0,0 +1,121 @@
// Zed completions wire acceptance: the `provider` field of POST /completions
// must use cloud.zed.dev's exact wire values (anthropic/open_ai/google/x_ai),
// and the Zed Gemini path must not carry the shared translator's
// safetySettings (Zed's hosted Gemini backend speaks the Vertex safety
// vocabulary, not the public-Gemini enums).
import { describe, it, expect, beforeEach, vi } from "vitest";
vi.mock("open-sse/shared/zedAuth.js", async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
resolveZedModels: vi.fn(),
zedLlmFetch: vi.fn(),
};
});
import {
resolveZedModels,
zedLlmFetch,
} from "open-sse/shared/zedAuth.js";
import ZedExecutor from "open-sse/executors/zed.js";
function catalogFor(entries) {
const rawById = new Map(entries);
return { rawById, models: [] };
}
function mockCatalogFetch(captured) {
zedLlmFetch.mockImplementation(async (credentials, path, options) => {
captured.body = JSON.parse(options.fetchOptions.body);
return new Response("upstream-error-stub", { status: 500 });
});
}
function makeExecutor() {
const executor = new ZedExecutor();
executor.config = {};
return executor;
}
const CHAT_BODY = { messages: [{ role: "user", content: "hi" }] };
beforeEach(() => {
vi.clearAllMocks();
});
describe("wire provider enum", () => {
it.each([
["Anthropic", "anthropic"],
["anthropic", "anthropic"],
["OpenAi", "open_ai"],
["open_ai", "open_ai"],
["Google", "google"],
["gemini", "google"],
["XAi", "x_ai"],
["x_ai", "x_ai"],
])("catalog provider %j normalizes to wire %j", async (catalogValue, wire) => {
resolveZedModels.mockResolvedValue(catalogFor([["m", { provider: catalogValue }]]));
const executor = makeExecutor();
const { provider } = await executor.resolveModel("m", {}, null, null);
expect(provider).toBe(wire);
});
it("infers wire provider from the model id when the catalog is unavailable", async () => {
resolveZedModels.mockRejectedValue(new Error("catalog down"));
const executor = makeExecutor();
const log = { warn: vi.fn() };
expect((await executor.resolveModel("claude-opus-x", {}, null, log)).provider).toBe("anthropic");
expect((await executor.resolveModel("gemini-3-x", {}, null, log)).provider).toBe("google");
expect((await executor.resolveModel("grok-4-x", {}, null, log)).provider).toBe("x_ai");
expect((await executor.resolveModel("gpt-5-x", {}, null, log)).provider).toBe("open_ai");
});
});
describe("completion payload shaping", () => {
it("sends wire provider values per model family", async () => {
resolveZedModels.mockImplementation(async () => catalogFor([
["claude-x", { provider: "anthropic" }],
["gpt-x", { provider: "open_ai" }],
["gemini-x", { provider: "google" }],
["grok-x", { provider: "x_ai" }],
]));
const captured = {};
mockCatalogFetch(captured);
const executor = makeExecutor();
for (const [model, wire] of [
["claude-x", "anthropic"],
["gpt-x", "open_ai"],
["gemini-x", "google"],
["grok-x", "x_ai"],
]) {
await executor.execute({ model, body: { ...CHAT_BODY }, stream: false, credentials: {} });
expect(captured.body.provider).toBe(wire);
expect(captured.body.model).toBe(model);
}
});
it("strips safetySettings on the Zed Gemini path only", async () => {
resolveZedModels.mockImplementation(async () => catalogFor([
["gemini-x", { provider: "google" }],
["claude-x", { provider: "anthropic" }],
]));
const captured = {};
mockCatalogFetch(captured);
const executor = makeExecutor();
await executor.execute({ model: "gemini-x", body: { ...CHAT_BODY }, stream: false, credentials: {} });
expect(captured.body.provider).toBe("google");
expect(captured.body.provider_request).not.toHaveProperty("safetySettings");
// Sanity: the shared translator still emits safetySettings — the removal
// happens in the Zed executor, not in shared/native Gemini behavior.
const { openaiToGeminiRequest } = await import(
"open-sse/translator/request/openai-to-gemini.js"
);
expect(openaiToGeminiRequest("gemini-x", { ...CHAT_BODY }, true)).toHaveProperty(
"safetySettings",
);
});
});

View File

@@ -0,0 +1,165 @@
// Route-level acceptance for the Zed live-model wiring:
// GET /api/providers/[connectionId]/models → resolveZedModels → UI rows
// RUN WITH AN ISOLATED DB: DATA_DIR=$(mktemp -d) npx vitest run ...
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { GET } from "@/app/api/providers/[id]/models/route.js";
import { createProviderConnection } from "@/models/index.js";
// Transport stub BELOW resolveZedModels: proxyAwareFetch captures the native
// fetch at import time, so stubbing globalThis.fetch cannot intercept it.
// Mock the module instead; untouched hosts pass through to native fetch.
const stub = vi.hoisted(() => {
const nativeFetch = globalThis.fetch.bind(globalThis);
return { mode: "ok", calls: [], nativeFetch };
});
vi.mock("open-sse/utils/proxyFetch.js", () => ({
proxyAwareFetch: async (url, options) => {
const u = String(url);
stub.calls.push(u);
if (u.includes("cloud.zed.dev/client/users/me")) {
return Response.json({ default_organization_id: "org-1" });
}
if (u.includes("cloud.zed.dev/client/llm_tokens")) {
return Response.json({ token: "llm-token" });
}
if (u.includes("cloud.zed.dev/models")) {
if (stub.mode === "error") return new Response("boom", { status: 500 });
if (stub.mode === "empty") return Response.json({ models: [] });
return Response.json(stub.catalog);
}
return stub.nativeFetch(url, options);
},
default: async (url, options) => stub.nativeFetch(url, options),
}));
stub.catalog = {
models: [
{
id: "claude-opus-4-live",
display_name: "Claude Opus Live",
provider: "anthropic",
max_token_count: 200000,
max_output_tokens: 32000,
supports_tools: true,
supports_images: true,
supports_thinking: true,
is_disabled: false,
},
{
id: "gpt-live",
display_name: "GPT Live",
provider: "openai",
max_token_count: 128000,
max_output_tokens: 16384,
supports_tools: true,
is_disabled: false,
},
{
id: "retired-model",
display_name: "Retired",
provider: "openai",
is_disabled: true,
},
],
default_model: "claude-opus-4-live",
};
beforeEach(() => {
stub.mode = "ok";
stub.calls.length = 0;
});
afterEach(() => {
vi.restoreAllMocks();
});
async function seedZed(n) {
return createProviderConnection({
provider: "zed",
authType: "oauth",
accessToken: `tok-live-${n}-${Date.now()}`,
email: `zed-live-${n}-${Date.now()}@example.com`,
providerSpecificData: { userId: `u-${n}`, systemId: `sys-${n}` },
testStatus: "active",
});
}
async function getModels(connectionId) {
const req = new Request(`http://localhost/api/providers/${connectionId}/models`);
return GET(req, { params: Promise.resolve({ id: connectionId }) });
}
describe("criterion 1+2 — active connection + live catalog → models with metadata", () => {
it("returns enabled models with preserved metadata, no secrets", async () => {
const conn = await seedZed("m1");
const res = await getModels(conn.id);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.models.map((m) => m.id).sort()).toEqual(["claude-opus-4-live", "gpt-live"]);
const opus = data.models.find((m) => m.id === "claude-opus-4-live");
expect(opus.name).toBe("Claude Opus Live");
expect(opus.contextLength).toBe(200000);
expect(opus.maxOutputTokens).toBe(32000);
expect(opus.supportsTools).toBe(true);
expect(opus.supportsImages).toBe(true);
expect(opus.supportsThinking).toBe(true);
// Credentials must never leak into the client response.
expect(JSON.stringify(data)).not.toContain(conn.accessToken);
expect(JSON.stringify(data)).not.toContain("tok-live");
});
});
describe("criterion 4 — disabled models excluded", () => {
it("is_disabled entries never reach the UI", async () => {
const conn = await seedZed("m2");
const data = await (await getModels(conn.id)).json();
expect(data.models.some((m) => m.id === "retired-model")).toBe(false);
});
});
describe("criterion 4b — empty catalog → explicit warning", () => {
it("returns warning instead of silent zero", async () => {
stub.mode = "empty";
const conn = await seedZed("m3");
const res = await getModels(conn.id);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.models).toEqual([]);
expect(data.warning).toMatch(/no live models/i);
});
});
describe("criterion 5 — resolver failure → useful warning, no crash", () => {
it("returns 200 with warning text", async () => {
stub.mode = "error";
const conn = await seedZed("m4");
const res = await getModels(conn.id);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.models).toEqual([]);
expect(data.warning).toMatch(/failed to fetch zed models/i);
});
});
describe("criterion 6 (route) — unknown connection → 404", () => {
it("rejects missing connections", async () => {
const res = await getModels("00000000-0000-0000-0000-000000000000");
expect(res.status).toBe(404);
});
});
describe("criterion 5 (guard) — unsupported provider unchanged", () => {
it("still 400s for providers without a models config", async () => {
const conn = await createProviderConnection({
provider: "kimchi-nope",
authType: "oauth",
accessToken: "x",
email: `guard-${Date.now()}@example.com`,
testStatus: "active",
}).catch(() => null);
// createProviderConnection may reject unknown providers; either way the
// route must not have gained a zed-shaped branch for others.
if (!conn) return;
const res = await getModels(conn.id);
expect(res.status).toBe(400);
});
});

View File

@@ -0,0 +1,266 @@
// Acceptance suite for the Zed native-app auth fix.
// RUN WITH AN ISOLATED DB: DATA_DIR=$(mktemp -d) npx vitest run unit/zed-native-auth.test.js
//
// Covers criteria:
// 1. Zed proxy starts
// 2. Stray callback (no params) MUST NOT kill session / stop proxy
// 3. Real callback (user_id + access_token) MUST complete session + save connection
// 4. RSA decrypt works (round-trip)
// 5. systemId identical authorize → exchange → stored connection
// 6. register-session failure is distinguishable (backend contract)
// 8. (backend) reopen/re-register creates a fresh session
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import crypto from "node:crypto";
import {
createZedNativeAuthData,
parseZedCallbackPayload,
decryptZedAccessToken,
} from "open-sse/shared/zedAuth.js";
import {
startZedProxy,
stopZedProxy,
registerZedSession,
getZedSessionStatus,
clearZedSession,
} from "@/lib/oauth/utils/server.js";
import {
generateAuthData,
exchangeTokens,
} from "@/lib/oauth/providers/index.js";
const realFetch = globalThis.fetch;
// Never hit the real network in tests: cloud.zed.dev calls are best-effort
// (postExchange try/catch) — fail them fast and loud instead.
beforeEach(() => {
globalThis.fetch = async (url, init) => {
if (String(url).includes("cloud.zed.dev")) {
return new Response("test-stubbed", { status: 500 });
}
return realFetch(url, init);
};
});
afterEach(async () => {
globalThis.fetch = realFetch;
stopZedProxy();
vi.restoreAllMocks();
});
async function startTestProxy() {
const started = await startZedProxy(0); // random loopback port — parallel-safe
expect(started.success).toBe(true);
return started;
}
/** Simulate zed.dev: RSA-encrypt a plaintext token with the flow's public key. */
function encryptForCallback(publicKeyB64Url, plaintext) {
const der = Buffer.from(String(publicKeyB64Url), "base64url");
const key = crypto.createPublicKey({ key: der, format: "der", type: "pkcs1" });
return crypto
.publicEncrypt(
{ key, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
Buffer.from(plaintext, "utf8"),
)
.toString("base64url");
}
describe("criterion 1 — Zed proxy starts", () => {
it("binds 127.0.0.1 and reports a usable callback URL", async () => {
const started = await startTestProxy();
expect(started.port).toBeGreaterThan(0);
expect(started.callbackUrl).toBe(`http://127.0.0.1:${started.port}/`);
});
});
describe("criterion 4 — RSA decrypt works", () => {
it("round-trips OAEP-SHA256 through the verifier slot", async () => {
const auth = createZedNativeAuthData({}, { nativeAppPort: 1 });
const encrypted = encryptForCallback(auth.publicKey, "plaintext-token-abc");
expect(decryptZedAccessToken(encrypted, auth.privateKeyVerifier)).toBe(
"plaintext-token-abc",
);
});
it("rejects a missing verifier instead of silently failing", () => {
const auth = createZedNativeAuthData({}, { nativeAppPort: 1 });
const encrypted = encryptForCallback(auth.publicKey, "x");
expect(() => decryptZedAccessToken(encrypted, null)).toThrow(
/private key verifier/i,
);
});
it("parser keeps strict validation (no weakened acceptance)", () => {
expect(() => parseZedCallbackPayload("")).toThrow();
expect(() => parseZedCallbackPayload("http://127.0.0.1:1/")).toThrow(
/user_id and access_token/,
);
expect(() =>
parseZedCallbackPayload("http://127.0.0.1:1/?user_id=only-user"),
).toThrow(/user_id and access_token/);
});
});
describe("criterion 2 — stray callback MUST NOT kill session", () => {
it("bare GET / leaves session pending and proxy listening", async () => {
const started = await startTestProxy();
const auth = createZedNativeAuthData({}, { nativeAppPort: started.port });
expect(
registerZedSession({ state: "stray-state-1", codeVerifier: auth.privateKeyVerifier }),
).toBe(true);
const res = await realFetch(`http://127.0.0.1:${started.port}/`);
expect(res.status).toBe(200);
// Session must still be pending (not poisoned to error)…
const session = getZedSessionStatus("stray-state-1");
expect(session).not.toBeNull();
expect(session.status).toBe("pending");
// …and the SAME server must still own the port (no silent restart).
const again = await startZedProxy(0);
expect(again.port).toBe(started.port);
clearZedSession("stray-state-1");
});
it("GET /callback with unrelated params leaves session pending", async () => {
const started = await startTestProxy();
const auth = createZedNativeAuthData({}, { nativeAppPort: started.port });
registerZedSession({ state: "stray-state-2", codeVerifier: auth.privateKeyVerifier });
const res = await realFetch(`http://127.0.0.1:${started.port}/callback?foo=bar`);
expect(res.status).toBe(200);
const session = getZedSessionStatus("stray-state-2");
expect(session).not.toBeNull();
expect(session.status).toBe("pending");
clearZedSession("stray-state-2");
});
});
describe("criterion 3 — real callback completes session + saves connection", () => {
it("user_id + access_token → done, decrypted token persisted", async () => {
const started = await startTestProxy();
const auth = createZedNativeAuthData({}, { nativeAppPort: started.port });
const state = `real-state-${Date.now()}`;
registerZedSession({ state, codeVerifier: auth.privateKeyVerifier, systemId: auth.systemId });
const encrypted = encryptForCallback(auth.publicKey, "decrypted-token-xyz");
const cb = new URL(`http://127.0.0.1:${started.port}/`);
cb.searchParams.set("user_id", "user-123");
cb.searchParams.set("access_token", encrypted);
const res = await realFetch(cb.toString());
expect(res.status).toBe(200);
const session = getZedSessionStatus(state);
expect(session).not.toBeNull();
expect(session.status).toBe("done");
expect(session.connectionId).toBeTruthy();
const { getProviderConnectionById } = await import("@/models/index.js");
const conn = await getProviderConnectionById(session.connectionId);
expect(conn).toBeTruthy();
expect(conn.provider).toBe("zed");
expect(conn.accessToken).toBe("decrypted-token-xyz");
expect(conn.providerSpecificData?.userId).toBe("user-123");
expect(conn.providerSpecificData?.systemId).toBe(auth.systemId);
// Proxy stopped itself after the terminal outcome (no orphan listener).
const again = await startZedProxy(0);
expect(again.port).not.toBe(started.port);
stopZedProxy();
});
});
describe("criterion 5 — systemId stable authorize → exchange → stored", () => {
it("generateAuthData exposes the systemId sent to zed.dev", async () => {
const auth = await generateAuthData("zed", "http://127.0.0.1:59999/", {
nativeAppPort: 59999,
});
const url = new URL(auth.authUrl);
expect(url.searchParams.get("native_app_port")).toBe("59999");
// The system_id embedded in the sign-in URL must be observable downstream.
expect(auth.systemId).toBe(url.searchParams.get("system_id"));
expect(auth.systemId).toBeTruthy();
});
it("exchange preserves the registered systemId (no regeneration)", async () => {
const auth = await generateAuthData("zed", "http://127.0.0.1:59998/", {
nativeAppPort: 59998,
});
// Public key always rides in the authorize URL (mirrors the real flow).
const pubFromUrl = new URL(auth.authUrl).searchParams.get("native_app_public_key");
expect(pubFromUrl).toBeTruthy();
const enc2 = encryptForCallback(pubFromUrl, "tok2");
const tokens = await exchangeTokens(
"zed",
`/?user_id=u1&access_token=${encodeURIComponent(enc2)}`,
null,
auth.codeVerifier,
auth.state,
{ systemId: auth.systemId },
);
expect(tokens.providerSpecificData.systemId).toBe(auth.systemId);
});
});
describe("criterion 6 — register-session failure is distinguishable", () => {
it("route reports { success: false } when the verifier is missing", async () => {
const { POST } = await import("@/app/api/oauth/[provider]/[action]/route.js");
const req = new Request("http://localhost/api/oauth/zed/register-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ state: "no-verifier-state" }),
});
const res = await POST(req, {
params: Promise.resolve({ provider: "zed", action: "register-session" }),
});
const data = await res.json();
// Backend contract: failure must be explicit (modal is required to check it).
expect(data.success).toBe(false);
});
});
describe("criterion 8 (backend) — re-register creates a fresh session", () => {
it("a new register supersedes the old state cleanly", async () => {
const a = createZedNativeAuthData({}, { nativeAppPort: 1 });
const b = createZedNativeAuthData({}, { nativeAppPort: 1 });
registerZedSession({ state: "old-state", codeVerifier: a.privateKeyVerifier });
registerZedSession({ state: "new-state", codeVerifier: b.privateKeyVerifier });
expect(getZedSessionStatus("old-state")).toBeNull();
const fresh = getZedSessionStatus("new-state");
expect(fresh).not.toBeNull();
expect(fresh.status).toBe("pending");
expect(fresh.codeVerifier).toBe(b.privateKeyVerifier);
clearZedSession("new-state");
});
});
describe("criterion L — decrypt failure errors the session but keeps the server", () => {
it("wrong-key token → session error, listener survives for the live attempt", async () => {
const started = await startTestProxy();
const live = createZedNativeAuthData({}, { nativeAppPort: started.port });
const other = createZedNativeAuthData({}, { nativeAppPort: started.port });
const state = `wrongkey-state-${Date.now()}`;
registerZedSession({ state, codeVerifier: live.privateKeyVerifier });
// Token encrypted for a DIFFERENT keypair (e.g. superseded popup).
const bad = encryptForCallback(other.publicKey, "not-for-this-key");
const cb = new URL(`http://127.0.0.1:${started.port}/`);
cb.searchParams.set("user_id", "user-123");
cb.searchParams.set("access_token", bad);
const res = await realFetch(cb.toString());
expect(res.status).toBe(200);
const session = getZedSessionStatus(state);
expect(session).not.toBeNull();
expect(session.status).toBe("error");
expect(session.error).toMatch(/decrypt/i);
// Server must still be alive (same port) for the live attempt.
const again = await startZedProxy(0);
expect(again.port).toBe(started.port);
clearZedSession(state);
});
});