Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
31 changes: 29 additions & 2 deletions __tests__/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
},
);
});
123 changes: 123 additions & 0 deletions __tests__/clientRedirects.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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<void>((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" }) : "",
},
]);
},
);
24 changes: 24 additions & 0 deletions __tests__/config.test.ts
Original file line number Diff line number Diff line change
@@ -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()}\` |`,
);
},
);
18 changes: 16 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -47,17 +54,24 @@ export async function post(

const response = await fetch(url.toString(), {
method: "POST",
redirect: "manual",
headers: {
"x-api-key": getApiKey(),
"Content-Type": "application/json",
},
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;
Expand Down
4 changes: 1 addition & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}
Loading