Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Schema from "effect/Schema";
5import * as TestClock from "effect/testing/TestClock";
6import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
7
8import { makeCliproxyApi } from "./cliproxyApi.ts";
9
10const config = {
11 kind: "cliproxy",
12 url: "http://hub.test:8317",
13 managementKey: "management-secret",
14 enabled: true,
15} as const;
16const accounts = [
17 {
18 id: "first.json",
19 auth_index: "a",
20 provider: "codex",
21 email: "first@example.com",
22 id_token: { chatgpt_account_id: "account-a" },
23 },
24 {
25 id: "second.json",
26 auth_index: "b",
27 provider: "codex",
28 email: "second@example.com",
29 id_token: { chatgpt_account_id: "account-b" },
30 },
31];
32const credit = (id: string, expires_at = "2099-01-01T00:00:00Z") => ({
33 id,
34 expires_at,
35 status: "available",
36 reset_type: "codex_rate_limits",
37});
38const RequestBody = Schema.Struct({
39 auth_index: Schema.String,
40 method: Schema.optional(Schema.String),
41 url: Schema.optional(Schema.String),
42 header: Schema.optional(Schema.Record(Schema.String, Schema.String)),
43 data: Schema.optional(Schema.String),
44});
45type RequestBody = typeof RequestBody.Type;
46const decodeRequest = Schema.decodeUnknownSync(Schema.fromJsonString(RequestBody));
47const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
48
49function fixture(
50 options: {
51 accounts?: Array<
52 (typeof accounts)[number] & {
53 disabled?: boolean;
54 id_token: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
55 }
56 >;
57 upstream?: (request: RequestBody) => { status: number; body: unknown };
58 cooldownStatus?: number;
59 } = {},
60) {
61 const requests: Array<{ path: string; body?: RequestBody }> = [];
62 const http = HttpClient.make((request) =>
63 Effect.sync(() => {
64 expect(request.headers.authorization).toBe("Bearer management-secret");
65 const path = new URL(request.url).pathname;
66 const body =
67 request.body._tag === "Uint8Array"
68 ? decodeRequest(new TextDecoder().decode(request.body.body))
69 : undefined;
70 requests.push({ path, ...(body ? { body } : {}) });
71 if (path.endsWith("/auth-files"))
72 return HttpClientResponse.fromWeb(
73 request,
74 Response.json({ files: options.accounts ?? accounts }),
75 );
76 if (path.endsWith("/reset-quota"))
77 return HttpClientResponse.fromWeb(
78 request,
79 Response.json({}, { status: options.cooldownStatus ?? 200 }),
80 );
81 expect(path).toMatch(/\/v0\/management\/api-call$/);
82 expect(body?.header?.Authorization).toBe("Bearer $TOKEN$");
83 const upstream = options.upstream?.(body!) ?? {
84 status: 200,
85 body: body?.url?.endsWith("/consume")
86 ? { code: "reset" }
87 : body?.url?.endsWith("/rate-limit-reset-credits")
88 ? {
89 credits: [
90 credit("later", "2099-02-01T00:00:00Z"),
91 credit("first"),
92 credit("expired", "2000-01-01T00:00:00Z"),
93 { ...credit("used"), status: "redeemed" },
94 ],
95 }
96 : {
97 plan_type: "pro",
98 rate_limit: {
99 secondary_window: {
100 used_percent: 78,
101 reset_at: 4070908800,
102 limit_window_seconds: 604800,
103 },
104 },
105 },
106 };
107 return HttpClientResponse.fromWeb(
108 request,
109 Response.json({ status_code: upstream.status, body: encodeJson(upstream.body) }),
110 );
111 }),
112 );
113 return {
114 requests,
115 api: makeCliproxyApi.pipe(
116 Effect.provideService(HttpClient.HttpClient, http),
117 Effect.provide(NodeCrypto.layer),
118 ),
119 };
120}
121
122/** A hub API whose every request fails the way `fail` says. */
123const unreachableHub = (
124 fail: (
125 request: Parameters<Parameters<typeof HttpClient.make>[0]>[0],
126 ) => HttpClientError.HttpClientError,
127) =>
128 makeCliproxyApi.pipe(
129 Effect.provideService(
130 HttpClient.HttpClient,
131 HttpClient.make((request) => Effect.fail(fail(request))),
132 ),
133 Effect.provide(NodeCrypto.layer),
134 );
135
136describe("CLIProxyAPI hub failures", () => {
137 it.effect("names the TLS code when the hub's certificate is not trusted", () =>
138 Effect.gen(function* () {
139 const api = yield* unreachableHub(
140 (request) =>
141 new HttpClientError.HttpClientError({
142 reason: new HttpClientError.TransportError({
143 request,
144 // Node's fetch wraps the TLS error, which carries the code, in a generic TypeError.
145 cause: new TypeError("fetch failed", {
146 cause: Object.assign(new Error("unable to get local issuer certificate"), {
147 code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
148 }),
149 }),
150 }),
151 }),
152 );
153 const error = yield* Effect.flip(api.readAccounts(config));
154 expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
155 expect(error.detail).toContain("NODE_EXTRA_CA_CERTS");
156 }),
157 );
158
159 // regression: #18168 Limits hub failures name their TLS, HTTP, or timeout cause
160 it.effect("ignores a transport code that is not a short Node error code", () =>
161 Effect.gen(function* () {
162 const api = yield* unreachableHub(
163 (request) =>
164 new HttpClientError.HttpClientError({
165 reason: new HttpClientError.TransportError({
166 request,
167 cause: Object.assign(new Error("odd"), { code: "X".repeat(200) }),
168 }),
169 }),
170 );
171 const error = yield* Effect.flip(api.readAccounts(config));
172 expect(error.detail).toBe("The hub management request failed.");
173 }),
174 );
175
176 it.effect("names the status, not the body, when the hub rejects the request", () =>
177 Effect.gen(function* () {
178 const test = HttpClient.make((request) =>
179 Effect.succeed(
180 HttpClientResponse.fromWeb(
181 request,
182 Response.json({ error: "management-secret is wrong" }, { status: 401 }),
183 ),
184 ),
185 );
186 const api = yield* makeCliproxyApi.pipe(
187 Effect.provideService(HttpClient.HttpClient, test),
188 Effect.provide(NodeCrypto.layer),
189 );
190 const error = yield* Effect.flip(api.readAccounts(config));
191 expect(error.detail).toContain("401");
192 expect(error.detail).not.toContain("management-secret");
193 }),
194 );
195});
196
197describe("CLIProxyAPI built-in management API", () => {
198 it.effect(
199 "reads both accounts and their earliest unexpired credits without plugin endpoints",
200 () =>
201 Effect.gen(function* () {
202 yield* TestClock.setTime(1788710400000);
203 const test = fixture();
204 const api = yield* test.api;
205 const result = yield* api.readAccounts(config);
206 expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([
207 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
208 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
209 ]);
210 expect(result[0]?.usageLimits.windows).toMatchObject([
211 { id: "secondary", usedPercent: 78, kind: "weekly" },
212 ]);
213 const calls = test.requests.filter((request) => request.body?.url);
214 expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([
215 "a",
216 "a",
217 "b",
218 "b",
219 ]);
220 expect(
221 calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[
222 "Chatgpt-Account-Id"
223 ],
224 ).toBe("account-b");
225 }),
226 );
227
228 it.effect("resolves a missing usage plan from current, then legacy, token plans", () =>
229 Effect.gen(function* () {
230 const test = fixture({
231 accounts: [
232 { ...accounts[0]!, id_token: { chatgpt_account_id: "account-a", plan_type: "free" } },
233 {
234 ...accounts[1]!,
235 id_token: {
236 chatgpt_account_id: "account-b",
237 plan_type: "go",
238 chatgpt_plan_type: "plus",
239 },
240 },
241 {
242 ...accounts[1]!,
243 id: "third.json",
244 auth_index: "c",
245 id_token: { chatgpt_account_id: "account-c", chatgpt_plan_type: "free" },
246 },
247 ],
248 upstream: (request) => ({
249 status: 200,
250 body: {
251 ...(request.auth_index === "a" ? { plan_type: "plus" } : {}),
252 rate_limit: { primary_window: { used_percent: 12 } },
253 },
254 }),
255 });
256 const api = yield* test.api;
257 const result = yield* api.readAccounts(config);
258 expect(result.map((account) => [account.plan, account.usageLimits.windows[0]?.kind])).toEqual(
259 [
260 ["ChatGPT Plus Subscription", "session"],
261 ["ChatGPT Go Subscription", "monthly"],
262 ["ChatGPT Free Subscription", "monthly"],
263 ],
264 );
265 }),
266 );
267
268 it.effect("keeps the path of a hub served under a prefix", () =>
269 Effect.gen(function* () {
270 const test = fixture();
271 const api = yield* test.api;
272 yield* api.readAccounts({ ...config, url: "https://tools.test/cliproxy" });
273 expect(test.requests.length).toBeGreaterThan(0);
274 expect(
275 test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")),
276 ).toBe(true);
277 }),
278 );
279
280 it.effect("keeps usage when the credits endpoint fails", () =>
281 Effect.gen(function* () {
282 const test = fixture({
283 upstream: (request) =>
284 request.url?.endsWith("rate-limit-reset-credits")
285 ? { status: 503, body: { token: "do-not-publish" } }
286 : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
287 });
288 const api = yield* test.api;
289 const result = yield* api.readAccounts(config);
290 expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
291 expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
292 }),
293 );
294
295 it.effect("isolates a failed account and never publishes upstream error bodies", () =>
296 Effect.gen(function* () {
297 const test = fixture({
298 upstream: (request) =>
299 request.auth_index === "a"
300 ? { status: 401, body: { token: "do-not-publish" } }
301 : {
302 status: 200,
303 body: request.url?.endsWith("rate-limit-reset-credits")
304 ? { credits: [] }
305 : { rate_limit: { primary_window: { used_percent: 12 } } },
306 },
307 });
308 const api = yield* test.api;
309 const result = yield* api.readAccounts(config);
310 expect(result[0]?.usageLimits.unavailable?.reason).toBe("probeFailed");
311 expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
312 expect(encodeJson(result)).not.toContain("do-not-publish");
313 }),
314 );
315
316 it.effect("maps Claude scoped windows without a scheduler plugin", () =>
317 Effect.gen(function* () {
318 const test = fixture({
319 accounts: [{ ...accounts[0]!, provider: "claude" }],
320 // The usage endpoint answers 429 to requests without a Claude Code user agent.
321 upstream: (request) => ({
322 status: request.header?.["User-Agent"]?.startsWith("claude-code/") ? 200 : 429,
323 body: {
324 five_hour: { utilization: 10, resets_at: null },
325 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
326 limits: [
327 {
328 kind: "weekly_scoped",
329 percent: 80,
330 resets_at: null,
331 scope: { model: { display_name: "Fable" } },
332 },
333 ],
334 },
335 }),
336 });
337 const api = yield* test.api;
338 const result = yield* api.readAccounts(config);
339 expect(
340 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
341 ).toEqual([
342 ["five_hour", 10],
343 ["seven_day", 50],
344 ["seven_day_fable", 80],
345 ]);
346 }),
347 );
348
349 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
350 Effect.gen(function* () {
351 const test = fixture();
352 const api = yield* test.api;
353 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
354 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
355 const redemptions = test.requests.filter((request) =>
356 request.body?.url?.endsWith("/consume"),
357 );
358 expect(redemptions).toHaveLength(2);
359 expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
360 expect(redemptions[0]?.body?.data).toBe(
361 encodeJson({
362 redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705",
363 credit_id: "credit-b",
364 }),
365 );
366 expect(
367 test.requests
368 .filter((request) => request.path.endsWith("/reset-quota"))
369 .map((request) => request.body?.auth_index),
370 ).toEqual(["b", "b"]);
371 }),
372 );
373
374 it.effect("reports redemption success even if cooldown clearing fails", () =>
375 Effect.gen(function* () {
376 const api = yield* fixture({ cooldownStatus: 404 }).api;
377 const result = yield* api.consume(config, "first.json", "credit");
378 expect(result.outcome).toBe("reset");
379 expect(result.warning).toContain("cooldown");
380 }),
381 );
382
383 it.effect("skips disabled accounts and rejects redemption on them", () =>
384 Effect.gen(function* () {
385 const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
386 const api = yield* test.api;
387 expect(yield* api.readAccounts(config)).toEqual([]);
388 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
389 "Failure",
390 );
391 expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
392 }),
393 );
394
395 it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
396 Effect.gen(function* () {
397 let attempts = 0;
398 const test = fixture({
399 upstream: () =>
400 ++attempts === 1
401 ? { status: 503, body: {} }
402 : { status: 200, body: { code: "already_redeemed" } },
403 });
404 const api = yield* test.api;
405 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
406 "Failure",
407 );
408 expect(yield* api.consume(config, "first.json", "credit")).toEqual({
409 outcome: "alreadyRedeemed",
410 });
411 const data = test.requests
412 .filter((request) => request.body?.url?.endsWith("/consume"))
413 .map((request) => request.body?.data);
414 expect(data[0]).toBe(data[1]);
415 expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
416 1,
417 );
418 }),
419 );
420
421 it.effect("rejects unknown accounts without forwarding a redemption", () =>
422 Effect.gen(function* () {
423 const test = fixture();
424 const api = yield* test.api;
425 const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
426 expect(result._tag).toBe("Failure");
427 expect(test.requests).toHaveLength(1);
428 }),
429 );
430});