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