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

cliproxyApi.test.ts

517 lines17.9 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.each([
268 "https://tools.test/cliproxy",
269 "https://tools.test/cliproxy/",
270 "https://tools.test/cliproxy/management.html",
271 "https://tools.test/cliproxy/management.html/",
272 "https://tools.test/cliproxy/MANAGEMENT.HTML",
273 "https://tools.test/cliproxy/management.html?tab=accounts",
274 "https://tools.test/cliproxy/management.html#accounts",
275 "https://tools.test/cliproxy/management.html/?tab=accounts",
276 "https://tools.test/cliproxy/management.html/#accounts",
277 ])("keeps the path of a hub served under a prefix: %s", (url) =>
278 Effect.gen(function* () {
279 const test = fixture();
280 const api = yield* test.api;
281 yield* api.readAccounts({ ...config, url });
282 expect(test.requests.length).toBeGreaterThan(0);
283 expect(
284 test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")),
285 ).toBe(true);
286 }),
287 );
288​
289 it.effect("preserves a hub path that only ends with the panel filename", () =>
290 Effect.gen(function* () {
291 const test = fixture();
292 const api = yield* test.api;
293 yield* api.readAccounts({ ...config, url: "https://tools.test/team-management.html" });
294 expect(test.requests.length).toBeGreaterThan(0);
295 expect(
296 test.requests.every((request) =>
297 request.path.startsWith("/team-management.html/v0/management/"),
298 ),
299 ).toBe(true);
300 }),
301 );
302​
303 it.effect("keeps usage when the credits endpoint fails", () =>
304 Effect.gen(function* () {
305 const test = fixture({
306 upstream: (request) =>
307 request.url?.endsWith("rate-limit-reset-credits")
308 ? { status: 503, body: { token: "do-not-publish" } }
309 : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
310 });
311 const api = yield* test.api;
312 const result = yield* api.readAccounts(config);
313 expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
314 expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
315 }),
316 );
317​
318 it.effect("isolates a failed account and never publishes upstream error bodies", () =>
319 Effect.gen(function* () {
320 const test = fixture({
321 upstream: (request) =>
322 request.auth_index === "a"
323 ? { status: 401, body: { token: "do-not-publish" } }
324 : {
325 status: 200,
326 body: request.url?.endsWith("rate-limit-reset-credits")
327 ? { credits: [] }
328 : { rate_limit: { primary_window: { used_percent: 12 } } },
329 },
330 });
331 const api = yield* test.api;
332 const result = yield* api.readAccounts(config);
333 expect(result[0]?.usageLimits.unavailable?.reason).toBe("probeFailed");
334 expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
335 expect(encodeJson(result)).not.toContain("do-not-publish");
336 }),
337 );
338​
339 it.effect("maps Claude scoped windows without a scheduler plugin", () =>
340 Effect.gen(function* () {
341 const test = fixture({
342 accounts: [{ ...accounts[0]!, provider: "claude" }],
343 // The usage endpoint answers 429 to requests without a Claude Code user agent.
344 upstream: (request) => ({
345 status: request.header?.["User-Agent"]?.startsWith("claude-code/") ? 200 : 429,
346 body: {
347 five_hour: { utilization: 10, resets_at: null },
348 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
349 limits: [
350 {
351 kind: "weekly_scoped",
352 percent: 80,
353 resets_at: null,
354 scope: { model: { display_name: "Fable" } },
355 },
356 ],
357 },
358 }),
359 });
360 const api = yield* test.api;
361 const result = yield* api.readAccounts(config);
362 expect(
363 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
364 ).toEqual([
365 ["five_hour", 10],
366 ["seven_day", 50],
367 ["seven_day_fable", 80],
368 ]);
369 }),
370 );
371​
372 it.effect.each([
373 {
374 name: "spend budget",
375 budget: {
376 spend: {
377 enabled: true,
378 used: { amount_minor: 4_631, currency: "USD", exponent: 2 },
379 limit: { amount_minor: 50_000, currency: "USD", exponent: 2 },
380 },
381 },
382 },
383 {
384 name: "extra usage",
385 budget: {
386 extra_usage: {
387 is_enabled: true,
388 used_credits: 4_631,
389 monthly_limit: 50_000,
390 utilization: 9,
391 },
392 },
393 },
394 ])("keeps Claude monthly spend from $name beside rolling windows", ({ budget }) =>
395 Effect.gen(function* () {
396 const test = fixture({
397 accounts: [{ ...accounts[0]!, provider: "claude" }],
398 upstream: () => ({
399 status: 200,
400 body: { five_hour: { utilization: 10, resets_at: null }, ...budget },
401 }),
402 });
403 const result = yield* (yield* test.api).readAccounts(config);
404 expect(
405 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
406 ).toEqual([
407 ["five_hour", 10],
408 ["monthly_spend", expect.closeTo(9.262, 10)],
409 ]);
410 }),
411 );
412​
413 it.effect("omits disabled Claude budgets without losing rolling windows", () =>
414 Effect.gen(function* () {
415 const test = fixture({
416 accounts: [{ ...accounts[0]!, provider: "claude" }],
417 upstream: () => ({
418 status: 200,
419 body: {
420 five_hour: { utilization: 10, resets_at: null },
421 spend: { enabled: false, used: null, limit: null },
422 extra_usage: {
423 is_enabled: false,
424 used_credits: null,
425 monthly_limit: null,
426 utilization: null,
427 },
428 },
429 }),
430 });
431 const result = yield* (yield* test.api).readAccounts(config);
432 expect(result[0]?.usageLimits.windows.map((window) => window.id)).toEqual(["five_hour"]);
433 }),
434 );
435​
436 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
437 Effect.gen(function* () {
438 const test = fixture();
439 const api = yield* test.api;
440 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
441 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
442 const redemptions = test.requests.filter((request) =>
443 request.body?.url?.endsWith("/consume"),
444 );
445 expect(redemptions).toHaveLength(2);
446 expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
447 expect(redemptions[0]?.body?.data).toBe(
448 encodeJson({
449 redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705",
450 credit_id: "credit-b",
451 }),
452 );
453 expect(
454 test.requests
455 .filter((request) => request.path.endsWith("/reset-quota"))
456 .map((request) => request.body?.auth_index),
457 ).toEqual(["b", "b"]);
458 }),
459 );
460​
461 it.effect("reports redemption success even if cooldown clearing fails", () =>
462 Effect.gen(function* () {
463 const api = yield* fixture({ cooldownStatus: 404 }).api;
464 const result = yield* api.consume(config, "first.json", "credit");
465 expect(result.outcome).toBe("reset");
466 expect(result.warning).toContain("cooldown");
467 }),
468 );
469​
470 it.effect("skips disabled accounts and rejects redemption on them", () =>
471 Effect.gen(function* () {
472 const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
473 const api = yield* test.api;
474 expect(yield* api.readAccounts(config)).toEqual([]);
475 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
476 "Failure",
477 );
478 expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
479 }),
480 );
481​
482 it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
483 Effect.gen(function* () {
484 let attempts = 0;
485 const test = fixture({
486 upstream: () =>
487 ++attempts === 1
488 ? { status: 503, body: {} }
489 : { status: 200, body: { code: "already_redeemed" } },
490 });
491 const api = yield* test.api;
492 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
493 "Failure",
494 );
495 expect(yield* api.consume(config, "first.json", "credit")).toEqual({
496 outcome: "alreadyRedeemed",
497 });
498 const data = test.requests
499 .filter((request) => request.body?.url?.endsWith("/consume"))
500 .map((request) => request.body?.data);
501 expect(data[0]).toBe(data[1]);
502 expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
503 1,
504 );
505 }),
506 );
507​
508 it.effect("rejects unknown accounts without forwarding a redemption", () =>
509 Effect.gen(function* () {
510 const test = fixture();
511 const api = yield* test.api;
512 const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
513 expect(result._tag).toBe("Failure");
514 expect(test.requests).toHaveLength(1);
515 }),
516 );
517});