From c56a6dd3bd7905f536613a0c3d441152213b58bf Mon Sep 17 00:00:00 2001 From: Hydra Date: Sat, 14 Nov 2026 01:10:05 +0200 Subject: [PATCH 1/2] Discover the same-origin API when logging in through a public URL --- apps/cli/src/commands/login.ts | 29 +++++++++++----- apps/cli/src/lib/public-instance-api.ts | 20 +++++++++++ apps/cli/test/e2e/login.test.ts | 33 +++++++++++++++++++ .../cli/test/unit/public-instance-api.test.ts | 20 +++++++++++ 4 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 apps/cli/src/lib/public-instance-api.ts create mode 100644 apps/cli/test/unit/public-instance-api.test.ts diff --git a/apps/cli/src/commands/login.ts b/apps/cli/src/commands/login.ts index e8da11cd3..fb5e18403 100644 --- a/apps/cli/src/commands/login.ts +++ b/apps/cli/src/commands/login.ts @@ -18,6 +18,7 @@ import { fetchCaps } from "../lib/caps"; import { err, info, isJsonMode, ok, printJson } from "../lib/output"; import { exitCommand } from "../lib/command-exit"; import { readSecret } from "../lib/command-input"; +import { discoverPublicInstanceApi } from "../lib/public-instance-api"; export interface LoginOptions { token?: string; @@ -80,7 +81,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { const existing = getContext(contextName); const local = !opts.cloud && !opts.apiUrl && !existing.apiUrl ? localConnectionEndpoints() : undefined; - const apiUrl = opts.cloud ? CLOUD_API_URL : opts.apiUrl || existing.apiUrl || local!.apiUrl; + let apiUrl = opts.cloud ? CLOUD_API_URL : opts.apiUrl || existing.apiUrl || local!.apiUrl; const normalizedApi = new HttpClient({ baseUrl: apiUrl }).apiUrl; const sameEndpoint = existing.apiUrl && new HttpClient({ baseUrl: existing.apiUrl }).apiUrl === normalizedApi; @@ -89,7 +90,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { : opts.dashboardUrl || (sameEndpoint ? existing.dashboardUrl : undefined) || local?.dashboardUrl || - normalizedApi.slice(0, -4); + normalizedApi.slice(0, -4).replace(/\/api\/proxy$/, ""); let token: string | undefined = opts.tokenFile ? readSecret(opts.tokenFile) : opts.token; @@ -132,13 +133,23 @@ export async function runLogin(options: LoginOptions = {}): Promise { // Validate the token against an authenticated endpoint before storing. // 200 → valid; 403 → valid but lacks settings:read scope (still usable). let scoped = false; - try { - const client = new OpenshipClient({ baseUrl: apiUrl, token, timeoutMs: 8000 }); - await client.tokens.list(); - } catch (error) { - if (error instanceof ApiError && error.status === 403) { - scoped = true; - } else { + for (let attempt = 0; ; attempt++) { + try { + const client = new OpenshipClient({ baseUrl: apiUrl, token, timeoutMs: 8000 }); + await client.tokens.list(); + break; + } catch (error) { + if (error instanceof ApiError && error.status === 403) { + scoped = true; + break; + } + // A missing/non-JSON route can mean the supplied URL is the dashboard. + // An actual authentication refusal must never switch endpoints. + if (attempt === 0 && !opts.cloud && error instanceof ApiError && + (error.status === 404 || error.message === "Invalid JSON response")) { + const discovered = await discoverPublicInstanceApi(apiUrl); + if (discovered) { apiUrl = discovered; continue; } + } err( error instanceof ApiError && error.status === 401 ? "Token rejected by the API. Check that it is valid and not revoked." diff --git a/apps/cli/src/lib/public-instance-api.ts b/apps/cli/src/lib/public-instance-api.ts new file mode 100644 index 000000000..ae98a4e1e --- /dev/null +++ b/apps/cli/src/lib/public-instance-api.ts @@ -0,0 +1,20 @@ +import { SDK_CAPABILITIES } from "@repo/contracts"; +import { HttpClient } from "@repo/sdk/client"; + +/** A public dashboard may mount the API beneath /api/proxy. Probe without + * credentials and never follow redirects or infer another origin. */ +export async function discoverPublicInstanceApi(baseUrl: string): Promise { + const base = new HttpClient({ baseUrl }).apiUrl.slice(0, -4); + if (/\/(?:api|api\/proxy)$/.test(new URL(baseUrl).pathname.replace(/\/+$/, ""))) return null; + const candidate = `${base}/api/proxy`; + try { + const response = await fetch(`${candidate}/api/health`, { + headers: { Accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(3_000), + }); + if (!response.ok) return null; + const health = await response.json() as { status?: string; sdk?: { protocol?: number } }; + return health?.status === "ok" && health.sdk?.protocol === SDK_CAPABILITIES.protocol ? candidate : null; + } catch { + return null; + } +} diff --git a/apps/cli/test/e2e/login.test.ts b/apps/cli/test/e2e/login.test.ts index b869db092..1116501fd 100644 --- a/apps/cli/test/e2e/login.test.ts +++ b/apps/cli/test/e2e/login.test.ts @@ -48,6 +48,7 @@ vi.mock("../../src/lib/local-connection", () => ({ import { loginCommand } from "../../src/commands/login"; import { CLOUD_API_URL, CLOUD_DASHBOARD_URL, LOCAL_DASHBOARD_URL } from "@repo/core"; +import { SDK_CAPABILITIES } from "@repo/contracts"; import { runCommand, stubFetch, type FetchStub } from "../helpers/harness"; import { setJsonMode } from "../../src/lib/output"; @@ -67,6 +68,38 @@ afterEach(() => { }); describe("openship login endpoint preservation", () => { + it.each([404, 200])("discovers the same-origin API after a dashboard response (%s) and saves it", async (status) => { + fetchStub.restore(); + fetchStub = stubFetch(request => { + if (request.url === "https://ship.example.com/api/tokens") return { status, text: "Dashboard" }; + if (request.url.endsWith("/health")) { + expect(request.headers.authorization).toBeUndefined(); + return { json: { status: "ok", sdk: SDK_CAPABILITIES } }; + } + expect(request.url).toBe("https://ship.example.com/api/proxy/api/tokens"); + expect(request.headers.authorization).toBe("Bearer opsh_pat_test"); + return { json: { data: [] } }; + }); + const result = await runCommand(loginCommand, ["--api-url", "https://ship.example.com", "--token", "opsh_pat_test"]); + expect(result.code).toBe(0); + expect(h.added.at(-1)?.opts).toMatchObject({ apiUrl: "https://ship.example.com/api/proxy", dashboardUrl: "https://ship.example.com" }); + expect(fetchStub.calls).toHaveLength(3); + }); + + it("does not send a token to a guessed endpoint without a valid API health response", async () => { + fetchStub.restore(); + fetchStub = stubFetch(() => ({ status: 404, json: { error: "Not found" } })); + const result = await runCommand(loginCommand, ["--api-url", "https://ship.example.com", "--token", "opsh_pat_test"]); + expect(result.code).toBe(1); + expect(h.added).toEqual([]); + expect(fetchStub.calls.map(call => call.url)).toEqual(["https://ship.example.com/api/tokens", "https://ship.example.com/api/proxy/api/health"]); + expect(fetchStub.calls[1]!.headers.authorization).toBeUndefined(); + }); + + it("derives the dashboard correctly for an explicitly supplied proxy API", async () => { + await runCommand(loginCommand, ["--api-url", "https://ship.example.com/api/proxy", "--token", "opsh_pat_test"]); + expect(h.added.at(-1)?.opts.dashboardUrl).toBe("https://ship.example.com"); + }); it("guides a fresh interactive login to Cloud and opens its token page", async () => { h.interactive = true; const result = await runCommand(loginCommand, []); diff --git a/apps/cli/test/unit/public-instance-api.test.ts b/apps/cli/test/unit/public-instance-api.test.ts new file mode 100644 index 000000000..89ac6d914 --- /dev/null +++ b/apps/cli/test/unit/public-instance-api.test.ts @@ -0,0 +1,20 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { SDK_CAPABILITIES } from "@repo/contracts"; +import { discoverPublicInstanceApi } from "../../src/lib/public-instance-api"; +afterEach(() => vi.unstubAllGlobals()); + +it("confines credential-free discovery to the supplied origin and refuses redirects", async () => { + const fetcher = vi.fn(async () => Response.json({ status: "ok", sdk: SDK_CAPABILITIES })); + vi.stubGlobal("fetch", fetcher); + expect(await discoverPublicInstanceApi("https://ship.test/prefix/")).toBe("https://ship.test/prefix/api/proxy"); + expect(fetcher).toHaveBeenCalledWith("https://ship.test/prefix/api/proxy/api/health", expect.objectContaining({ redirect: "error", headers: { Accept: "application/json" } })); +}); +it.each(["https://ship.test/api", "https://ship.test/api/proxy", "https://ship.test/prefix/api/proxy/"])("does not reinterpret an explicit API: %s", async url => { + const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher); + expect(await discoverPublicInstanceApi(url)).toBeNull(); + expect(fetcher).not.toHaveBeenCalled(); +}); +it.each([{ status: "ok" }, { sdk: SDK_CAPABILITIES }, { status: "ok", sdk: { protocol: -1 } }])("ignores an unrelated health response: %j", async body => { + vi.stubGlobal("fetch", vi.fn(async () => Response.json(body))); + expect(await discoverPublicInstanceApi("https://ship.test")).toBeNull(); +}); From 0157dcd7c048a3ec744557d7c0b024c53123cda7 Mon Sep 17 00:00:00 2001 From: Hydra Date: Sat, 14 Nov 2026 01:40:18 +0200 Subject: [PATCH 2/2] Document optional unauthenticated API discovery fallback --- apps/cli/src/lib/public-instance-api.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/cli/src/lib/public-instance-api.ts b/apps/cli/src/lib/public-instance-api.ts index ae98a4e1e..6df441097 100644 --- a/apps/cli/src/lib/public-instance-api.ts +++ b/apps/cli/src/lib/public-instance-api.ts @@ -15,6 +15,7 @@ export async function discoverPublicInstanceApi(baseUrl: string): Promise