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

cliproxyApi.test.ts

630 lines22.6 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 id: string;
53 auth_index: string;
54 provider: string;
55 email?: string;
56 disabled?: boolean;
57 project_id?: string;
58 id_token?: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
59 }>;
60 upstream?: (request: RequestBody) => { status: number; body: unknown };
61 cooldownStatus?: number;
62 models?: (name: string) => Response;
63 } = {},
64) {
65 const requests: Array<{ path: string; body?: RequestBody }> = [];
66 const http = HttpClient.make((request) =>
67 Effect.sync(() => {
68 expect(request.headers.authorization).toBe("Bearer management-secret");
69 const path = new URL(request.url).pathname;
70 const body =
71 request.body._tag === "Uint8Array"
72 ? decodeRequest(new TextDecoder().decode(request.body.body))
73 : undefined;
74 requests.push({ path, ...(body ? { body } : {}) });
75 if (path.endsWith("/auth-files/models"))
76 return HttpClientResponse.fromWeb(
77 request,
78 options.models?.(new URL(request.url).searchParams.get("name")!) ??
79 Response.json({}, { status: 404 }),
80 );
81 if (path.endsWith("/auth-files"))
82 return HttpClientResponse.fromWeb(
83 request,
84 Response.json({ files: options.accounts ?? accounts }),
85 );
86 if (path.endsWith("/reset-quota"))
87 return HttpClientResponse.fromWeb(
88 request,
89 Response.json({}, { status: options.cooldownStatus ?? 200 }),
90 );
91 expect(path).toMatch(/\/v0\/management\/api-call$/);
92 expect(body?.header?.Authorization).toBe("Bearer $TOKEN$");
93 const upstream = options.upstream?.(body!) ?? {
94 status: 200,
95 body: body?.url?.endsWith("/consume")
96 ? { code: "reset" }
97 : body?.url?.endsWith("/rate-limit-reset-credits")
98 ? {
99 credits: [
100 credit("later", "2099-02-01T00:00:00Z"),
101 credit("first"),
102 credit("expired", "2000-01-01T00:00:00Z"),
103 { ...credit("used"), status: "redeemed" },
104 ],
105 }
106 : {
107 plan_type: "pro",
108 rate_limit: {
109 secondary_window: {
110 used_percent: 78,
111 reset_at: 4070908800,
112 limit_window_seconds: 604800,
113 },
114 },
115 },
116 };
117 return HttpClientResponse.fromWeb(
118 request,
119 Response.json({ status_code: upstream.status, body: encodeJson(upstream.body) }),
120 );
121 }),
122 );
123 return {
124 requests,
125 api: makeCliproxyApi.pipe(
126 Effect.provideService(HttpClient.HttpClient, http),
127 Effect.provide(NodeCrypto.layer),
128 ),
129 };
131​
132const unreachableHub = (
133 fail: (
134 request: Parameters<Parameters<typeof HttpClient.make>[0]>[0],
135 ) => HttpClientError.HttpClientError,
136) =>
137 makeCliproxyApi.pipe(
138 Effect.provideService(
139 HttpClient.HttpClient,
140 HttpClient.make((request) => Effect.fail(fail(request))),
141 ),
142 Effect.provide(NodeCrypto.layer),
143 );
144​
145describe("CLIProxyAPI hub failures", () => {
146 it.effect("names the TLS code when the hub's certificate is not trusted", () =>
147 Effect.gen(function* () {
148 const api = yield* unreachableHub(
149 (request) =>
150 new HttpClientError.HttpClientError({
151 reason: new HttpClientError.TransportError({
152 request,
153 // Node's fetch wraps the TLS error, which carries the code, in a generic TypeError.
154 cause: new TypeError("fetch failed", {
155 cause: Object.assign(new Error("unable to get local issuer certificate"), {
156 code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
157 }),
158 }),
159 }),
160 }),
161 );
162 const error = yield* Effect.flip(api.readAccounts(config));
163 expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
164 expect(error.detail).toContain("NODE_EXTRA_CA_CERTS");
165 }),
166 );
167​
168 // regression: #18168 Limits hub failures name their TLS, HTTP, or timeout cause
169 it.effect("ignores a transport code that is not a short Node error code", () =>
170 Effect.gen(function* () {
171 const api = yield* unreachableHub(
172 (request) =>
173 new HttpClientError.HttpClientError({
174 reason: new HttpClientError.TransportError({
175 request,
176 cause: Object.assign(new Error("odd"), { code: "X".repeat(200) }),
177 }),
178 }),
179 );
180 const error = yield* Effect.flip(api.readAccounts(config));
181 expect(error.detail).toBe("The hub management request failed.");
182 }),
183 );
184​
185 it.effect("names the status, not the body, when the hub rejects the request", () =>
186 Effect.gen(function* () {
187 const test = HttpClient.make((request) =>
188 Effect.succeed(
189 HttpClientResponse.fromWeb(
190 request,
191 Response.json({ error: "management-secret is wrong" }, { status: 401 }),
192 ),
193 ),
194 );
195 const api = yield* makeCliproxyApi.pipe(
196 Effect.provideService(HttpClient.HttpClient, test),
197 Effect.provide(NodeCrypto.layer),
198 );
199 const error = yield* Effect.flip(api.readAccounts(config));
200 expect(error.detail).toContain("401");
201 expect(error.detail).not.toContain("management-secret");
202 }),
203 );
204});
205​
206describe("CLIProxyAPI built-in management API", () => {
207 it.effect(
208 "reads both accounts and their earliest unexpired credits without plugin endpoints",
209 () =>
210 Effect.gen(function* () {
211 yield* TestClock.setTime(1788710400000);
212 const test = fixture();
213 const api = yield* test.api;
214 const result = yield* api.readAccounts(config);
215 expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([
216 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
217 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
218 ]);
219 expect(result[0]?.usageLimits.windows).toMatchObject([
220 { id: "secondary", usedPercent: 78, kind: "weekly" },
221 ]);
222 const calls = test.requests.filter((request) => request.body?.url);
223 expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([
224 "a",
225 "a",
226 "b",
227 "b",
228 ]);
229 expect(
230 calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[
231 "Chatgpt-Account-Id"
232 ],
233 ).toBe("account-b");
234 }),
235 );
236​
237 it.effect("names the models the hub routes to each account, when the hub lists them", () =>
238 Effect.gen(function* () {
239 const test = fixture({
240 accounts: [...accounts, { ...accounts[1]!, id: "third.json", auth_index: "c" }],
241 models: (name) =>
242 name === "first.json"
243 ? Response.json({ models: [{ id: "gpt-5.6-sol" }, { id: " " }] })
244 : name === "third.json"
245 ? Response.json({ models: [] })
246 : Response.json({}, { status: 404 }),
247 });
248 const api = yield* test.api;
249 const result = yield* api.readAccounts(config);
250 expect(result.map((account) => account.models)).toEqual([["gpt-5.6-sol"], undefined, []]);
251 expect(result[1]?.usageLimits.windows).toHaveLength(1);
252 }),
253 );
254​
255 it.effect("resolves a missing usage plan from current, then legacy, token plans", () =>
256 Effect.gen(function* () {
257 const test = fixture({
258 accounts: [
259 { ...accounts[0]!, id_token: { chatgpt_account_id: "account-a", plan_type: "free" } },
260 {
261 ...accounts[1]!,
262 id_token: {
263 chatgpt_account_id: "account-b",
264 plan_type: "go",
265 chatgpt_plan_type: "plus",
266 },
267 },
268 {
269 ...accounts[1]!,
270 id: "third.json",
271 auth_index: "c",
272 id_token: { chatgpt_account_id: "account-c", chatgpt_plan_type: "free" },
273 },
274 ],
275 upstream: (request) => ({
276 status: 200,
277 body: {
278 ...(request.auth_index === "a" ? { plan_type: "plus" } : {}),
279 rate_limit: { primary_window: { used_percent: 12 } },
280 },
281 }),
282 });
283 const api = yield* test.api;
284 const result = yield* api.readAccounts(config);
285 expect(result.map((account) => [account.plan, account.usageLimits.windows[0]?.kind])).toEqual(
286 [
287 ["ChatGPT Plus Subscription", "session"],
288 ["ChatGPT Go Subscription", "monthly"],
289 ["ChatGPT Free Subscription", "monthly"],
290 ],
291 );
292 }),
293 );
294​
295 it.effect.each([
296 "https://tools.test/cliproxy",
297 "https://tools.test/cliproxy/",
298 "https://tools.test/cliproxy/management.html",
299 "https://tools.test/cliproxy/management.html/",
300 "https://tools.test/cliproxy/MANAGEMENT.HTML",
301 "https://tools.test/cliproxy/management.html?tab=accounts",
302 "https://tools.test/cliproxy/management.html#accounts",
303 "https://tools.test/cliproxy/management.html/?tab=accounts",
304 "https://tools.test/cliproxy/management.html/#accounts",
305 ])("keeps the path of a hub served under a prefix: %s", (url) =>
306 Effect.gen(function* () {
307 const test = fixture();
308 const api = yield* test.api;
309 yield* api.readAccounts({ ...config, url });
310 expect(test.requests.length).toBeGreaterThan(0);
311 expect(
312 test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")),
313 ).toBe(true);
314 }),
315 );
316​
317 it.effect("preserves a hub path that only ends with the panel filename", () =>
318 Effect.gen(function* () {
319 const test = fixture();
320 const api = yield* test.api;
321 yield* api.readAccounts({ ...config, url: "https://tools.test/team-management.html" });
322 expect(test.requests.length).toBeGreaterThan(0);
323 expect(
324 test.requests.every((request) =>
325 request.path.startsWith("/team-management.html/v0/management/"),
326 ),
327 ).toBe(true);
328 }),
329 );
330​
331 it.effect("keeps usage when the credits endpoint fails", () =>
332 Effect.gen(function* () {
333 const test = fixture({
334 upstream: (request) =>
335 request.url?.endsWith("rate-limit-reset-credits")
336 ? { status: 503, body: { token: "do-not-publish" } }
337 : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
338 });
339 const api = yield* test.api;
340 const result = yield* api.readAccounts(config);
341 expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
342 expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
343 }),
344 );
345​
346 it.effect("isolates a failed account and never publishes upstream error bodies", () =>
347 Effect.gen(function* () {
348 const test = fixture({
349 upstream: (request) =>
350 request.auth_index === "a"
351 ? { status: 401, body: { token: "do-not-publish" } }
352 : {
353 status: 200,
354 body: request.url?.endsWith("rate-limit-reset-credits")
355 ? { credits: [] }
356 : { rate_limit: { primary_window: { used_percent: 12 } } },
357 },
358 });
359 const api = yield* test.api;
360 const result = yield* api.readAccounts(config);
361 expect(result[0]?.usageLimits.unavailable).toEqual({
362 reason: "probeFailed",
363 message: "The provider refused the hub request (HTTP 401).",
364 });
365 expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
366 expect(encodeJson(result)).not.toContain("do-not-publish");
367 }),
368 );
369​
370 it.effect("maps Claude scoped windows without a scheduler plugin", () =>
371 Effect.gen(function* () {
372 const test = fixture({
373 accounts: [{ ...accounts[0]!, provider: "claude" }],
374 // The usage endpoint answers 429 to requests without a Claude Code user agent.
375 upstream: (request) => ({
376 status: request.header?.["User-Agent"]?.startsWith("claude-code/") ? 200 : 429,
377 body: {
378 five_hour: { utilization: 10, resets_at: null },
379 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
380 limits: [
381 {
382 kind: "weekly_scoped",
383 percent: 80,
384 resets_at: null,
385 scope: { model: { display_name: "Fable" } },
386 },
387 ],
388 },
389 }),
390 });
391 const api = yield* test.api;
392 const result = yield* api.readAccounts(config);
393 expect(
394 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
395 ).toEqual([
396 ["five_hour", 10],
397 ["seven_day", 50],
398 ["seven_day_fable", 80],
399 ]);
400 }),
401 );
402​
403 it.effect.each([
404 {
405 name: "spend budget",
406 budget: {
407 spend: {
408 enabled: true,
409 used: { amount_minor: 4_631, currency: "USD", exponent: 2 },
410 limit: { amount_minor: 50_000, currency: "USD", exponent: 2 },
411 },
412 },
413 },
414 {
415 name: "extra usage",
416 budget: {
417 extra_usage: {
418 is_enabled: true,
419 used_credits: 4_631,
420 monthly_limit: 50_000,
421 utilization: 9,
422 },
423 },
424 },
425 ])("keeps Claude monthly spend from $name beside rolling windows", ({ budget }) =>
426 Effect.gen(function* () {
427 const test = fixture({
428 accounts: [{ ...accounts[0]!, provider: "claude" }],
429 upstream: () => ({
430 status: 200,
431 body: { five_hour: { utilization: 10, resets_at: null }, ...budget },
432 }),
433 });
434 const result = yield* (yield* test.api).readAccounts(config);
435 expect(
436 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
437 ).toEqual([
438 ["five_hour", 10],
439 ["monthly_spend", expect.closeTo(9.262, 10)],
440 ]);
441 }),
442 );
443​
444 it.effect("omits disabled Claude budgets without losing rolling windows", () =>
445 Effect.gen(function* () {
446 const test = fixture({
447 accounts: [{ ...accounts[0]!, provider: "claude" }],
448 upstream: () => ({
449 status: 200,
450 body: {
451 five_hour: { utilization: 10, resets_at: null },
452 spend: { enabled: false, used: null, limit: null },
453 extra_usage: {
454 is_enabled: false,
455 used_credits: null,
456 monthly_limit: null,
457 utilization: null,
458 },
459 },
460 }),
461 });
462 const result = yield* (yield* test.api).readAccounts(config);
463 expect(result[0]?.usageLimits.windows.map((window) => window.id)).toEqual(["five_hour"]);
464 }),
465 );
466​
467 it.effect("keeps a Claude account whose window reports no utilization", () =>
468 Effect.gen(function* () {
469 const test = fixture({
470 accounts: [{ ...accounts[0]!, provider: "claude" }],
471 upstream: () => ({
472 status: 200,
473 body: {
474 five_hour: { utilization: null, resets_at: null },
475 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
476 },
477 }),
478 });
479 const result = yield* (yield* test.api).readAccounts(config);
480 expect(result[0]?.usageLimits.unavailable).toBeUndefined();
481 expect(
482 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
483 ).toEqual([["seven_day", 50]]);
484 }),
485 );
486​
487 it.effect("reads an xAI account as Grok with Grok CLI headers", () =>
488 Effect.gen(function* () {
489 const test = fixture({
490 accounts: [{ id: "xai.json", auth_index: "x", provider: "xai", email: "x@example.com" }],
491 upstream: () => ({
492 status: 200,
493 body: {
494 config: {
495 creditUsagePercent: 40,
496 currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: "2099-01-01T00:00:00Z" },
497 },
498 },
499 }),
500 });
501 const [account] = yield* (yield* test.api).readAccounts(config);
502 expect(account).toMatchObject({ driver: "grok", email: "x@example.com" });
503 expect(account?.usageLimits.windows).toMatchObject([
504 { id: "subscription", kind: "weekly", usedPercent: 40 },
505 ]);
506 const call = test.requests.find((request) => request.body?.url)?.body;
507 expect(call?.method).toBe("GET");
508 expect(call?.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits");
509 expect(call?.header).toMatchObject({
510 "x-xai-token-auth": "xai-grok-cli",
511 "x-grok-client-version": expect.any(String),
512 "User-Agent": expect.stringMatching(/^grok-cli\//),
513 });
514 }),
515 );
516​
517 it.effect.each([
518 { name: "a refused xAI call", provider: "xai", status: 403, body: { error: "denied" } },
519 { name: "a malformed xAI answer", provider: "xai", status: 200, body: { config: "x" } },
520 ])("reports $name as unreadable", ({ provider, status, body }) =>
521 Effect.gen(function* () {
522 const test = fixture({
523 accounts: [{ id: `${provider}.json`, auth_index: "a", provider }],
524 upstream: () => ({ status, body }),
525 });
526 const [account] = yield* (yield* test.api).readAccounts(config);
527 expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
528 }),
529 );
530​
531 it.effect("skips accounts of providers the hub table does not know", () =>
532 Effect.gen(function* () {
533 const test = fixture({
534 accounts: [
535 { id: "kiro.json", auth_index: "k", provider: "kiro", email: "k@example.com" },
536 // Antigravity only allows ACP clients, so its internal quota API is never called.
537 { id: "antigravity.json", auth_index: "g", provider: "antigravity", project_id: "p" },
538 { ...accounts[0]!, provider: "claude" },
539 ],
540 upstream: () => ({ status: 200, body: { five_hour: { utilization: 1, resets_at: null } } }),
541 });
542 const result = yield* (yield* test.api).readAccounts(config);
543 expect(result.map((account) => account.driver)).toEqual(["claudeAgent"]);
544 expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("k");
545 expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("g");
546 }),
547 );
548​
549 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
550 Effect.gen(function* () {
551 const test = fixture();
552 const api = yield* test.api;
553 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
554 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
555 const redemptions = test.requests.filter((request) =>
556 request.body?.url?.endsWith("/consume"),
557 );
558 expect(redemptions).toHaveLength(2);
559 expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
560 expect(redemptions[0]?.body?.data).toBe(
561 encodeJson({
562 redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705",
563 credit_id: "credit-b",
564 }),
565 );
566 expect(
567 test.requests
568 .filter((request) => request.path.endsWith("/reset-quota"))
569 .map((request) => request.body?.auth_index),
570 ).toEqual(["b", "b"]);
571 }),
572 );
573​
574 it.effect("reports redemption success even if cooldown clearing fails", () =>
575 Effect.gen(function* () {
576 const api = yield* fixture({ cooldownStatus: 404 }).api;
577 const result = yield* api.consume(config, "first.json", "credit");
578 expect(result.outcome).toBe("reset");
579 expect(result.warning).toContain("cooldown");
580 }),
581 );
582​
583 it.effect("skips disabled accounts and rejects redemption on them", () =>
584 Effect.gen(function* () {
585 const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
586 const api = yield* test.api;
587 expect(yield* api.readAccounts(config)).toEqual([]);
588 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
589 "Failure",
590 );
591 expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
592 }),
593 );
594​
595 it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
596 Effect.gen(function* () {
597 let attempts = 0;
598 const test = fixture({
599 upstream: () =>
600 ++attempts === 1
601 ? { status: 503, body: {} }
602 : { status: 200, body: { code: "already_redeemed" } },
603 });
604 const api = yield* test.api;
605 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
606 "Failure",
607 );
608 expect(yield* api.consume(config, "first.json", "credit")).toEqual({
609 outcome: "alreadyRedeemed",
610 });
611 const data = test.requests
612 .filter((request) => request.body?.url?.endsWith("/consume"))
613 .map((request) => request.body?.data);
614 expect(data[0]).toBe(data[1]);
615 expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
616 1,
617 );
618 }),
619 );
620​
621 it.effect("rejects unknown accounts without forwarding a redemption", () =>
622 Effect.gen(function* () {
623 const test = fixture();
624 const api = yield* test.api;
625 const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
626 expect(result._tag).toBe("Failure");
627 expect(test.requests).toHaveLength(1);
628 }),
629 );
630});