diff --git a/CLAUDE.md b/CLAUDE.md index 5c22814..22c61a4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,8 +25,9 @@ pnpm test # Run tests with vitest - `src/commands/` — One file per command group ## API Base URL -Default: `https://recoup-api.vercel.app` +Default: `https://api.recoupable.dev` Override: `RECOUP_API_URL` env var +GET/POST requests reject redirects (`redirect: "manual"` with explicit 3xx rejection); never forward credentials to a redirect target. ## Code Principles - SRP: One exported function per file diff --git a/README.md b/README.md index 4e2044e..ef8ba9c 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,14 @@ establish that a new npm version has been published. | Variable | Required | Description | |----------|----------|-------------| | `RECOUP_API_KEY` | Yes | Your Recoup API key | -| `RECOUP_API_URL` | No | API base URL (default: `https://recoup-api.vercel.app`) | +| `RECOUP_API_URL` | No | API base URL (default: `https://api.recoupable.dev`) | + +GET and POST requests reject redirects instead of forwarding the API key or request +to the redirect target. A 3xx response fails with `API redirect rejected. Use a trusted +API URL that does not redirect.`; the error omits request and redirect details. +`RECOUP_API_URL` still selects the initial API origin; use +only an endpoint you trust with your API key. This source behavior does not establish +which version is published or installed. ## License diff --git a/__tests__/client.test.ts b/__tests__/client.test.ts index 40ff3c0..0a2597c 100644 --- a/__tests__/client.test.ts +++ b/__tests__/client.test.ts @@ -105,10 +105,37 @@ describe("post", () => { mockFetch.mockResolvedValue({ ok: false, status: 400, - json: () => - Promise.resolve({ status: "error", message: "Bad request" }), + json: () => Promise.resolve({ status: "error", message: "Bad request" }), }); await expect(post("/api/test", {})).rejects.toThrow("Bad request"); }); }); + +describe("transport errors", () => { + it.each(["GET", "POST"])( + "preserves the original %s network failure", + async (method) => { + const failure = new TypeError("synthetic network failure"); + mockFetch.mockRejectedValueOnce(failure); + await expect( + method === "GET" ? get("/api/test") : post("/api/test", {}), + ).rejects.toBe(failure); + }, + ); + it.each(["GET", "POST"])( + "rejects %s redirects without parsing or exposing response details", + async (method) => { + const json = vi.fn(); + mockFetch.mockResolvedValueOnce({ status: 307, ok: false, json }); + await expect( + method === "GET" + ? get("/api/test?private=synthetic") + : post("/api/test?private=synthetic", { private: "synthetic" }), + ).rejects.toThrow( + "API redirect rejected. Use a trusted API URL that does not redirect.", + ); + expect(json).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/__tests__/clientRedirects.test.ts b/__tests__/clientRedirects.test.ts new file mode 100644 index 0000000..90c1a2f --- /dev/null +++ b/__tests__/clientRedirects.test.ts @@ -0,0 +1,123 @@ +import { createServer, type Server, type RequestListener } from "node:http"; +import type { AddressInfo } from "node:net"; +import { afterEach, expect, it, vi } from "vitest"; +import { get, post } from "../src/client.js"; + +const servers: Server[] = []; +const fakeKey = "fixture-not-a-real-key"; +async function listen(handler: RequestListener) { + const server = createServer(handler); + servers.push(server); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +} +afterEach(async () => { + vi.unstubAllEnvs(); + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + server.closeAllConnections(); + }), + ), + ); +}); + +const redirects = [301, 302, 303, 307, 308].flatMap((status) => + ["GET", "POST"].flatMap((method) => + ["same-origin", "cross-origin"].map((target) => ({ + status, + method, + target, + })), + ), +); +it.each(redirects)( + "rejects $status $method $target before sending the redirected request", + async ({ status, method, target }) => { + let destinationRequests = 0; + let originalRequests = 0; + const destination = await listen((_req, res) => { + destinationRequests++; + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify({ status: "success" })); + }); + const origin = await listen((req, res) => { + if (req.url === "/destination") { + destinationRequests++; + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify({ status: "success" })); + return; + } + originalRequests++; + expect(req.headers["x-api-key"]).toBe(fakeKey); + res.writeHead(status, { + Location: + target === "same-origin" + ? "/destination" + : `${destination}/destination`, + }); + res.end(); + }); + vi.stubEnv("RECOUP_API_KEY", fakeKey); + vi.stubEnv("RECOUP_API_URL", origin); + const result = await ( + method === "GET" + ? get("/redirect") + : post("/redirect", { example: "synthetic" }) + ).then( + (value) => ({ value, error: undefined }), + (error) => ({ value: undefined, error }), + ); + expect(originalRequests).toBe(1); + expect(destinationRequests).toBe(0); + expect(result.error).toBeInstanceOf(Error); + expect(result.error.message).toBe( + "API redirect rejected. Use a trusted API URL that does not redirect.", + ); + expect(result.value).toBeUndefined(); + }, +); + +it.each(["GET", "POST"])( + "preserves a successful direct %s request", + async (method) => { + const requests: { + method: string | undefined; + url: string | undefined; + key: string | string[] | undefined; + body: string; + }[] = []; + const origin = await listen(async (req, res) => { + let body = ""; + for await (const chunk of req) body += chunk.toString(); + requests.push({ + method: req.method, + url: req.url, + key: req.headers["x-api-key"], + body, + }); + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify({ status: "success", result: "synthetic" })); + }); + vi.stubEnv("RECOUP_API_KEY", fakeKey); + vi.stubEnv("RECOUP_API_URL", origin); + const result = + method === "GET" + ? await get("/direct", { q: "a b", empty: "" }) + : await post("/direct", { example: "synthetic" }); + expect(result).toEqual({ status: "success", result: "synthetic" }); + expect(requests).toEqual([ + { + method, + url: method === "GET" ? "/direct?q=a+b" : "/direct", + key: fakeKey, + body: method === "POST" ? JSON.stringify({ example: "synthetic" }) : "", + }, + ]); + }, +); diff --git a/__tests__/config.test.ts b/__tests__/config.test.ts new file mode 100644 index 0000000..234d420 --- /dev/null +++ b/__tests__/config.test.ts @@ -0,0 +1,24 @@ +import { readFileSync } from "node:fs"; +import { afterEach, expect, it, vi } from "vitest"; +import { getBaseUrl } from "../src/config.js"; + +afterEach(() => vi.unstubAllEnvs()); +it("defaults to the canonical API origin", () => { + vi.stubEnv("RECOUP_API_URL", ""); + expect(getBaseUrl()).toBe("https://api.recoupable.dev"); +}); +it("retains the explicit API URL override", () => { + vi.stubEnv("RECOUP_API_URL", "http://127.0.0.1:12345"); + expect(getBaseUrl()).toBe("http://127.0.0.1:12345"); +}); + +it.skipIf(!process.env.RECOUP_CLI_REFERENCE_PATH)( + "keeps the candidate guide default aligned with source", + () => { + vi.stubEnv("RECOUP_API_URL", ""); + const guide = readFileSync(process.env.RECOUP_CLI_REFERENCE_PATH!, "utf8"); + expect(guide).toContain( + `| \`RECOUP_API_URL\` | No | \`${getBaseUrl()}\` |`, + ); + }, +); diff --git a/src/client.ts b/src/client.ts index d2d326a..733bb35 100644 --- a/src/client.ts +++ b/src/client.ts @@ -23,16 +23,23 @@ export async function get( const response = await fetch(url.toString(), { method: "GET", + redirect: "manual", headers: { "x-api-key": getApiKey(), "Content-Type": "application/json", }, }); + if (response.status >= 300 && response.status < 400) { + throw new Error("API redirect rejected. Use a trusted API URL that does not redirect."); + } + const data: ApiResponse = await response.json(); if (!response.ok || data.status === "error") { - throw new Error(data.error || data.message || `Request failed: ${response.status}`); + throw new Error( + data.error || data.message || `Request failed: ${response.status}`, + ); } return data; @@ -47,6 +54,7 @@ export async function post( const response = await fetch(url.toString(), { method: "POST", + redirect: "manual", headers: { "x-api-key": getApiKey(), "Content-Type": "application/json", @@ -54,10 +62,16 @@ export async function post( body: JSON.stringify(body), }); + if (response.status >= 300 && response.status < 400) { + throw new Error("API redirect rejected. Use a trusted API URL that does not redirect."); + } + const data: ApiResponse = await response.json(); if (!response.ok || data.status === "error") { - throw new Error(data.error || data.message || `Request failed: ${response.status}`); + throw new Error( + data.error || data.message || `Request failed: ${response.status}`, + ); } return data; diff --git a/src/config.ts b/src/config.ts index b7381d2..5a0bd34 100644 --- a/src/config.ts +++ b/src/config.ts @@ -11,7 +11,5 @@ export function getApiKey(): string { } export function getBaseUrl(): string { - return ( - process.env.RECOUP_API_URL || "https://recoup-api.vercel.app" - ); + return process.env.RECOUP_API_URL || "https://api.recoupable.dev"; }