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

cliproxyApi.test.ts

478 lines16.7 KB

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<
53 (typeof accounts)[number] & {
54 disabled?: boolean;
55 id_token: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
56 }
57 >;
58 upstream?: (request: RequestBody) => { status: number; body: unknown };
59 cooldownStatus?: number;
60 } = {},
61) {
62 const requests: Array<{ path: string; body?: RequestBody }> = [];
63 const http = HttpClient.make((request) =>
64 Effect.sync(() => {
65 expect(request.headers.authorization).toBe("Bearer management-secret");
66 const path = new URL(request.url).pathname;
67 const body =
68 request.body._tag === "Uint8Array"
69 ? decodeRequest(new TextDecoder().decode(request.body.body))
70 : undefined;
71 requests.push({ path, ...(body ? { body } : {}) });
72 if (path.endsWith("/auth-files"))
73 return HttpClientResponse.fromWeb(
74 request,
75 Response.json({ files: options.accounts ?? accounts }),
76 );
77 if (path.endsWith("/reset-quota"))
78 return HttpClientResponse.fromWeb(
79 request,
80 Response.json({}, { status: options.cooldownStatus ?? 200 }),
81 );
82 expect(path).toMatch(/\/v0\/management\/api-call$/);
83 expect(body?.header?.Authorization).toBe("Bearer $TOKEN$");
84 const upstream = options.upstream?.(body!) ?? {
85 status: 200,
86 body: body?.url?.endsWith("/consume")
87 ? { code: "reset" }
88 : body?.url?.endsWith("/rate-limit-reset-credits")
89 ? {
90 credits: [
91 credit("later", "2099-02-01T00:00:00Z"),
92 credit("first"),
93 credit("expired", "2000-01-01T00:00:00Z"),
94 { ...credit("used"), status: "redeemed" },
95 ],
96 }
97 : {
98 plan_type: "pro",
99 rate_limit: {
100 secondary_window: {
101 used_percent: 78,
102 reset_at: 4070908800,
103 limit_window_seconds: 604800,
104 },
105 },
106 },
107 };
108 return HttpClientResponse.fromWeb(
109 request,
110 Response.json({ status_code: upstream.status, body: encodeJson(upstream.body) }),
111 );
112 }),
113 );
114 return {
115 requests,
116 api: makeCliproxyApi.pipe(
117 Effect.provideService(HttpClient.HttpClient, http),
118 Effect.provide(NodeCrypto.layer),
119 ),
120 };
122​
123/** A hub API whose every request fails the way `fail` says. */
124const unreachableHub = (
125 fail: (
126 request: Parameters<Parameters<typeof HttpClient.make>[0]>[0],
127 ) => HttpClientError.HttpClientError,
128) =>
129 makeCliproxyApi.pipe(
130 Effect.provideService(
131 HttpClient.HttpClient,
132 HttpClient.make((request) => Effect.fail(fail(request))),
133 ),
134 Effect.provide(NodeCrypto.layer),
135 );
136​
137describe("CLIProxyAPI hub failures", () => {
138 it.effect("names the TLS code when the hub's certificate is not trusted", () =>
139 Effect.gen(function* () {
140 const api = yield* unreachableHub(
141 (request) =>
142 new HttpClientError.HttpClientError({
143 reason: new HttpClientError.TransportError({
144 request,
145 // Node's fetch wraps the TLS error, which carries the code, in a generic TypeError.
146 cause: new TypeError("fetch failed", {
147 cause: Object.assign(new Error("unable to get local issuer certificate"), {
148 code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
149 }),
150 }),
151 }),
152 }),
153 );
154 const error = yield* Effect.flip(api.readAccounts(config));
155 expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
156 expect(error.detail).toContain("NODE_EXTRA_CA_CERTS");
157 }),
158 );
159​
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 it.effect("says when the hub does not answer in time", () =>
197 Effect.gen(function* () {
198 const api = yield* makeCliproxyApi.pipe(
199 Effect.provideService(
200 HttpClient.HttpClient,
201 HttpClient.make(() => Effect.never),
202 ),
203 Effect.provide(NodeCrypto.layer),
204 );
205 const pending = yield* Effect.flip(api.readAccounts(config)).pipe(
206 Effect.forkChild({ startImmediately: true }),
207 );
208 yield* TestClock.adjust("15 seconds");
209 const error = yield* Fiber.join(pending);
210 expect(error.detail).toContain("did not answer within 15 seconds");
211 }),
212 );
213​
214 it.effect("keeps a malformed account list generic", () =>
215 Effect.gen(function* () {
216 const test = HttpClient.make((request) =>
217 Effect.succeed(
218 HttpClientResponse.fromWeb(request, Response.json({ nope: "hub-internal" })),
219 ),
220 );
221 const api = yield* makeCliproxyApi.pipe(
222 Effect.provideService(HttpClient.HttpClient, test),
223 Effect.provide(NodeCrypto.layer),
224 );
225 const error = yield* Effect.flip(api.readAccounts(config));
226 expect(error.detail).toBe("The hub could not list accounts.");
227 }),
228 );
229});
230​
231describe("CLIProxyAPI built-in management API", () => {
232 it.effect(
233 "reads both accounts and their earliest unexpired credits without plugin endpoints",
234 () =>
235 Effect.gen(function* () {
236 yield* TestClock.setTime(1788710400000);
237 const test = fixture();
238 const api = yield* test.api;
239 const result = yield* api.readAccounts(config);
240 expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([
241 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
242 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
243 ]);
244 expect(result[0]?.usageLimits.windows).toMatchObject([
245 { id: "secondary", usedPercent: 78, kind: "weekly" },
246 ]);
247 const calls = test.requests.filter((request) => request.body?.url);
248 expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([
249 "a",
250 "a",
251 "b",
252 "b",
253 ]);
254 expect(
255 calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[
256 "Chatgpt-Account-Id"
257 ],
258 ).toBe("account-b");
259 }),
260 );
261​
262 it.effect("resolves a missing usage plan from current, then legacy, token plans", () =>
263 Effect.gen(function* () {
264 const test = fixture({
265 accounts: [
266 { ...accounts[0]!, id_token: { chatgpt_account_id: "account-a", plan_type: "free" } },
267 {
268 ...accounts[1]!,
269 id_token: {
270 chatgpt_account_id: "account-b",
271 plan_type: "go",
272 chatgpt_plan_type: "plus",
273 },
274 },
275 {
276 ...accounts[1]!,
277 id: "third.json",
278 auth_index: "c",
279 id_token: { chatgpt_account_id: "account-c", chatgpt_plan_type: "free" },
280 },
281 ],
282 upstream: (request) => ({
283 status: 200,
284 body: {
285 ...(request.auth_index === "a" ? { plan_type: "plus" } : {}),
286 rate_limit: { primary_window: { used_percent: 12 } },
287 },
288 }),
289 });
290 const api = yield* test.api;
291 const result = yield* api.readAccounts(config);
292 expect(result.map((account) => [account.plan, account.usageLimits.windows[0]?.kind])).toEqual(
293 [
294 ["ChatGPT Plus Subscription", "session"],
295 ["ChatGPT Go Subscription", "monthly"],
296 ["ChatGPT Free Subscription", "monthly"],
297 ],
298 );
299 }),
300 );
301​
302 it.effect("keeps the path of a hub served under a prefix", () =>
303 Effect.gen(function* () {
304 const test = fixture();
305 const api = yield* test.api;
306 yield* api.readAccounts({ ...config, url: "https://tools.test/cliproxy" });
307 expect(test.requests.length).toBeGreaterThan(0);
308 expect(
309 test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")),
310 ).toBe(true);
311 }),
312 );
313​
314 it.effect("keeps usage when the credits endpoint fails", () =>
315 Effect.gen(function* () {
316 const test = fixture({
317 upstream: (request) =>
318 request.url?.endsWith("rate-limit-reset-credits")
319 ? { status: 503, body: { token: "do-not-publish" } }
320 : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
321 });
322 const api = yield* test.api;
323 const result = yield* api.readAccounts(config);
324 expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
325 expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
326 }),
327 );
328​
329 it.effect("isolates a failed account and never publishes upstream error bodies", () =>
330 Effect.gen(function* () {
331 const test = fixture({
332 upstream: (request) =>
333 request.auth_index === "a"
334 ? { status: 401, body: { token: "do-not-publish" } }
335 : {
336 status: 200,
337 body: request.url?.endsWith("rate-limit-reset-credits")
338 ? { credits: [] }
339 : { rate_limit: { primary_window: { used_percent: 12 } } },
340 },
341 });
342 const api = yield* test.api;
343 const result = yield* api.readAccounts(config);
344 expect(result[0]?.usageLimits.unavailable?.reason).toBe("probeFailed");
345 expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
346 expect(encodeJson(result)).not.toContain("do-not-publish");
347 }),
348 );
349​
350 it.effect("maps Claude scoped windows without a scheduler plugin", () =>
351 Effect.gen(function* () {
352 const test = fixture({
353 accounts: [{ ...accounts[0]!, provider: "claude" }],
354 upstream: () => ({
355 status: 200,
356 body: {
357 five_hour: { utilization: 10, resets_at: null },
358 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
359 limits: [
360 {
361 kind: "weekly_scoped",
362 percent: 80,
363 resets_at: null,
364 scope: { model: { display_name: "Fable" } },
365 },
366 ],
367 },
368 }),
369 });
370 const api = yield* test.api;
371 const result = yield* api.readAccounts(config);
372 expect(
373 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
374 ).toEqual([
375 ["five_hour", 10],
376 ["seven_day", 50],
377 ["seven_day_fable", 80],
378 ]);
379 }),
380 );
381​
382 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
383 Effect.gen(function* () {
384 const test = fixture();
385 const api = yield* test.api;
386 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
387 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
388 const redemptions = test.requests.filter((request) =>
389 request.body?.url?.endsWith("/consume"),
390 );
391 expect(redemptions).toHaveLength(2);
392 expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
393 expect(redemptions[0]?.body?.data).toBe(
394 encodeJson({
395 redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705",
396 credit_id: "credit-b",
397 }),
398 );
399 expect(
400 test.requests
401 .filter((request) => request.path.endsWith("/reset-quota"))
402 .map((request) => request.body?.auth_index),
403 ).toEqual(["b", "b"]);
404 }),
405 );
406​
407 it.effect.each([
408 ["nothing_to_reset", "nothingToReset"],
409 ["no_credit", "noCredit"],
410 ["already_redeemed", "alreadyRedeemed"],
411 ] as const)("reports %s accurately", ([code, outcome]) =>
412 Effect.gen(function* () {
413 const test = fixture({ upstream: () => ({ status: 200, body: { code } }) });
414 const api = yield* test.api;
415 expect(yield* api.consume(config, "first.json", "credit")).toEqual({ outcome });
416 expect(test.requests.some((request) => request.path.endsWith("/reset-quota"))).toBe(
417 code === "already_redeemed",
418 );
419 }),
420 );
421​
422 it.effect("reports redemption success even if cooldown clearing fails", () =>
423 Effect.gen(function* () {
424 const api = yield* fixture({ cooldownStatus: 404 }).api;
425 const result = yield* api.consume(config, "first.json", "credit");
426 expect(result.outcome).toBe("reset");
427 expect(result.warning).toContain("cooldown");
428 }),
429 );
430​
431 it.effect("skips disabled accounts and rejects redemption on them", () =>
432 Effect.gen(function* () {
433 const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
434 const api = yield* test.api;
435 expect(yield* api.readAccounts(config)).toEqual([]);
436 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
437 "Failure",
438 );
439 expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
440 }),
441 );
442​
443 it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
444 Effect.gen(function* () {
445 let attempts = 0;
446 const test = fixture({
447 upstream: () =>
448 ++attempts === 1
449 ? { status: 503, body: {} }
450 : { status: 200, body: { code: "already_redeemed" } },
451 });
452 const api = yield* test.api;
453 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
454 "Failure",
455 );
456 expect(yield* api.consume(config, "first.json", "credit")).toEqual({
457 outcome: "alreadyRedeemed",
458 });
459 const data = test.requests
460 .filter((request) => request.body?.url?.endsWith("/consume"))
461 .map((request) => request.body?.data);
462 expect(data[0]).toBe(data[1]);
463 expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
464 1,
465 );
466 }),
467 );
468​
469 it.effect("rejects unknown accounts without forwarding a redemption", () =>
470 Effect.gen(function* () {
471 const test = fixture();
472 const api = yield* test.api;
473 const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
474 expect(result._tag).toBe("Failure");
475 expect(test.requests).toHaveLength(1);
476 }),
477 );
478});