Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cliproxyApi.test.ts

493 lines17.0 KB

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 };
121​
122const unreachableHub = (
123 fail: (
124 request: Parameters<Parameters<typeof HttpClient.make>[0]>[0],
125 ) => HttpClientError.HttpClientError,
126) =>
127 makeCliproxyApi.pipe(
128 Effect.provideService(
129 HttpClient.HttpClient,
130 HttpClient.make((request) => Effect.fail(fail(request))),
131 ),
132 Effect.provide(NodeCrypto.layer),
133 );
134​
135describe("CLIProxyAPI hub failures", () => {
136 it.effect("names the TLS code when the hub's certificate is not trusted", () =>
137 Effect.gen(function* () {
138 const api = yield* unreachableHub(
139 (request) =>
140 new HttpClientError.HttpClientError({
141 reason: new HttpClientError.TransportError({
142 request,
143 // Node's fetch wraps the TLS error, which carries the code, in a generic TypeError.
144 cause: new TypeError("fetch failed", {
145 cause: Object.assign(new Error("unable to get local issuer certificate"), {
146 code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
147 }),
148 }),
149 }),
150 }),
151 );
152 const error = yield* Effect.flip(api.readAccounts(config));
153 expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
154 expect(error.detail).toContain("NODE_EXTRA_CA_CERTS");
155 }),
156 );
157​
158 // regression: #18168 Limits hub failures name their TLS, HTTP, or timeout cause
159 it.effect("ignores a transport code that is not a short Node error code", () =>
160 Effect.gen(function* () {
161 const api = yield* unreachableHub(
162 (request) =>
163 new HttpClientError.HttpClientError({
164 reason: new HttpClientError.TransportError({
165 request,
166 cause: Object.assign(new Error("odd"), { code: "X".repeat(200) }),
167 }),
168 }),
169 );
170 const error = yield* Effect.flip(api.readAccounts(config));
171 expect(error.detail).toBe("The hub management request failed.");
172 }),
173 );
174​
175 it.effect("names the status, not the body, when the hub rejects the request", () =>
176 Effect.gen(function* () {
177 const test = HttpClient.make((request) =>
178 Effect.succeed(
179 HttpClientResponse.fromWeb(
180 request,
181 Response.json({ error: "management-secret is wrong" }, { status: 401 }),
182 ),
183 ),
184 );
185 const api = yield* makeCliproxyApi.pipe(
186 Effect.provideService(HttpClient.HttpClient, test),
187 Effect.provide(NodeCrypto.layer),
188 );
189 const error = yield* Effect.flip(api.readAccounts(config));
190 expect(error.detail).toContain("401");
191 expect(error.detail).not.toContain("management-secret");
192 }),
193 );
194});
195​
196describe("CLIProxyAPI built-in management API", () => {
197 it.effect(
198 "reads both accounts and their earliest unexpired credits without plugin endpoints",
199 () =>
200 Effect.gen(function* () {
201 yield* TestClock.setTime(1788710400000);
202 const test = fixture();
203 const api = yield* test.api;
204 const result = yield* api.readAccounts(config);
205 expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([
206 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
207 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
208 ]);
209 expect(result[0]?.usageLimits.windows).toMatchObject([
210 { id: "secondary", usedPercent: 78, kind: "weekly" },
211 ]);
212 const calls = test.requests.filter((request) => request.body?.url);
213 expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([
214 "a",
215 "a",
216 "b",
217 "b",
218 ]);
219 expect(
220 calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[
221 "Chatgpt-Account-Id"
222 ],
223 ).toBe("account-b");
224 }),
225 );
226​
227 it.effect("resolves a missing usage plan from current, then legacy, token plans", () =>
228 Effect.gen(function* () {
229 const test = fixture({
230 accounts: [
231 { ...accounts[0]!, id_token: { chatgpt_account_id: "account-a", plan_type: "free" } },
232 {
233 ...accounts[1]!,
234 id_token: {
235 chatgpt_account_id: "account-b",
236 plan_type: "go",
237 chatgpt_plan_type: "plus",
238 },
239 },
240 {
241 ...accounts[1]!,
242 id: "third.json",
243 auth_index: "c",
244 id_token: { chatgpt_account_id: "account-c", chatgpt_plan_type: "free" },
245 },
246 ],
247 upstream: (request) => ({
248 status: 200,
249 body: {
250 ...(request.auth_index === "a" ? { plan_type: "plus" } : {}),
251 rate_limit: { primary_window: { used_percent: 12 } },
252 },
253 }),
254 });
255 const api = yield* test.api;
256 const result = yield* api.readAccounts(config);
257 expect(result.map((account) => [account.plan, account.usageLimits.windows[0]?.kind])).toEqual(
258 [
259 ["ChatGPT Plus Subscription", "session"],
260 ["ChatGPT Go Subscription", "monthly"],
261 ["ChatGPT Free Subscription", "monthly"],
262 ],
263 );
264 }),
265 );
266​
267 it.effect("keeps the path of a hub served under a prefix", () =>
268 Effect.gen(function* () {
269 const test = fixture();
270 const api = yield* test.api;
271 yield* api.readAccounts({ ...config, url: "https://tools.test/cliproxy" });
272 expect(test.requests.length).toBeGreaterThan(0);
273 expect(
274 test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")),
275 ).toBe(true);
276 }),
277 );
278​
279 it.effect("keeps usage when the credits endpoint fails", () =>
280 Effect.gen(function* () {
281 const test = fixture({
282 upstream: (request) =>
283 request.url?.endsWith("rate-limit-reset-credits")
284 ? { status: 503, body: { token: "do-not-publish" } }
285 : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
286 });
287 const api = yield* test.api;
288 const result = yield* api.readAccounts(config);
289 expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
290 expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
291 }),
292 );
293​
294 it.effect("isolates a failed account and never publishes upstream error bodies", () =>
295 Effect.gen(function* () {
296 const test = fixture({
297 upstream: (request) =>
298 request.auth_index === "a"
299 ? { status: 401, body: { token: "do-not-publish" } }
300 : {
301 status: 200,
302 body: request.url?.endsWith("rate-limit-reset-credits")
303 ? { credits: [] }
304 : { rate_limit: { primary_window: { used_percent: 12 } } },
305 },
306 });
307 const api = yield* test.api;
308 const result = yield* api.readAccounts(config);
309 expect(result[0]?.usageLimits.unavailable?.reason).toBe("probeFailed");
310 expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
311 expect(encodeJson(result)).not.toContain("do-not-publish");
312 }),
313 );
314​
315 it.effect("maps Claude scoped windows without a scheduler plugin", () =>
316 Effect.gen(function* () {
317 const test = fixture({
318 accounts: [{ ...accounts[0]!, provider: "claude" }],
319 // The usage endpoint answers 429 to requests without a Claude Code user agent.
320 upstream: (request) => ({
321 status: request.header?.["User-Agent"]?.startsWith("claude-code/") ? 200 : 429,
322 body: {
323 five_hour: { utilization: 10, resets_at: null },
324 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
325 limits: [
326 {
327 kind: "weekly_scoped",
328 percent: 80,
329 resets_at: null,
330 scope: { model: { display_name: "Fable" } },
331 },
332 ],
333 },
334 }),
335 });
336 const api = yield* test.api;
337 const result = yield* api.readAccounts(config);
338 expect(
339 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
340 ).toEqual([
341 ["five_hour", 10],
342 ["seven_day", 50],
343 ["seven_day_fable", 80],
344 ]);
345 }),
346 );
347​
348 it.effect.each([
349 {
350 name: "spend budget",
351 budget: {
352 spend: {
353 enabled: true,
354 used: { amount_minor: 4_631, currency: "USD", exponent: 2 },
355 limit: { amount_minor: 50_000, currency: "USD", exponent: 2 },
356 },
357 },
358 },
359 {
360 name: "extra usage",
361 budget: {
362 extra_usage: {
363 is_enabled: true,
364 used_credits: 4_631,
365 monthly_limit: 50_000,
366 utilization: 9,
367 },
368 },
369 },
370 ])("keeps Claude monthly spend from $name beside rolling windows", ({ budget }) =>
371 Effect.gen(function* () {
372 const test = fixture({
373 accounts: [{ ...accounts[0]!, provider: "claude" }],
374 upstream: () => ({
375 status: 200,
376 body: { five_hour: { utilization: 10, resets_at: null }, ...budget },
377 }),
378 });
379 const result = yield* (yield* test.api).readAccounts(config);
380 expect(
381 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
382 ).toEqual([
383 ["five_hour", 10],
384 ["monthly_spend", expect.closeTo(9.262, 10)],
385 ]);
386 }),
387 );
388​
389 it.effect("omits disabled Claude budgets without losing rolling windows", () =>
390 Effect.gen(function* () {
391 const test = fixture({
392 accounts: [{ ...accounts[0]!, provider: "claude" }],
393 upstream: () => ({
394 status: 200,
395 body: {
396 five_hour: { utilization: 10, resets_at: null },
397 spend: { enabled: false, used: null, limit: null },
398 extra_usage: {
399 is_enabled: false,
400 used_credits: null,
401 monthly_limit: null,
402 utilization: null,
403 },
404 },
405 }),
406 });
407 const result = yield* (yield* test.api).readAccounts(config);
408 expect(result[0]?.usageLimits.windows.map((window) => window.id)).toEqual(["five_hour"]);
409 }),
410 );
411​
412 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
413 Effect.gen(function* () {
414 const test = fixture();
415 const api = yield* test.api;
416 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
417 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
418 const redemptions = test.requests.filter((request) =>
419 request.body?.url?.endsWith("/consume"),
420 );
421 expect(redemptions).toHaveLength(2);
422 expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
423 expect(redemptions[0]?.body?.data).toBe(
424 encodeJson({
425 redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705",
426 credit_id: "credit-b",
427 }),
428 );
429 expect(
430 test.requests
431 .filter((request) => request.path.endsWith("/reset-quota"))
432 .map((request) => request.body?.auth_index),
433 ).toEqual(["b", "b"]);
434 }),
435 );
436​
437 it.effect("reports redemption success even if cooldown clearing fails", () =>
438 Effect.gen(function* () {
439 const api = yield* fixture({ cooldownStatus: 404 }).api;
440 const result = yield* api.consume(config, "first.json", "credit");
441 expect(result.outcome).toBe("reset");
442 expect(result.warning).toContain("cooldown");
443 }),
444 );
445​
446 it.effect("skips disabled accounts and rejects redemption on them", () =>
447 Effect.gen(function* () {
448 const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
449 const api = yield* test.api;
450 expect(yield* api.readAccounts(config)).toEqual([]);
451 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
452 "Failure",
453 );
454 expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
455 }),
456 );
457​
458 it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
459 Effect.gen(function* () {
460 let attempts = 0;
461 const test = fixture({
462 upstream: () =>
463 ++attempts === 1
464 ? { status: 503, body: {} }
465 : { status: 200, body: { code: "already_redeemed" } },
466 });
467 const api = yield* test.api;
468 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
469 "Failure",
470 );
471 expect(yield* api.consume(config, "first.json", "credit")).toEqual({
472 outcome: "alreadyRedeemed",
473 });
474 const data = test.requests
475 .filter((request) => request.body?.url?.endsWith("/consume"))
476 .map((request) => request.body?.data);
477 expect(data[0]).toBe(data[1]);
478 expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
479 1,
480 );
481 }),
482 );
483​
484 it.effect("rejects unknown accounts without forwarding a redemption", () =>
485 Effect.gen(function* () {
486 const test = fixture();
487 const api = yield* test.api;
488 const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
489 expect(result._tag).toBe("Failure");
490 expect(test.requests).toHaveLength(1);
491 }),
492 );
493});