Skip to content

Commit 05cd27a

Browse files
ScottN-PVclaude
andcommitted
fix(server): a Limits hub failure names its TLS, HTTP, or timeout cause
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 8d199b4 commit 05cd27a

2 files changed

Lines changed: 141 additions & 4 deletions

File tree

‎apps/server/src/usage/cliproxyApi.test.ts‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import { describe, expect, it } from "@effect/vitest";
33
import * as Effect from "effect/Effect";
4+
import * as Fiber from "effect/Fiber";
45
import * as Schema from "effect/Schema";
56
import * as TestClock from "effect/testing/TestClock";
6-
import { HttpClient, HttpClientResponse } from "effect/http";
7+
import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
78

89
import { makeCliproxyApi } from "./cliproxyApi.ts";
910

@@ -114,6 +115,99 @@ function fixture(
114115
};
115116
}
116117

118+
/** A hub API whose every request fails the way `fail` says. */
119+
const 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+
132+
describe("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("could not list accounts");
151+
expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
152+
expect(error.detail).toContain("NODE_EXTRA_CA_CERTS");
153+
}),
154+
);
155+
156+
it.effect("names the status, not the body, when the hub rejects the request", () =>
157+
Effect.gen(function* () {
158+
const test = HttpClient.make((request) =>
159+
Effect.succeed(
160+
HttpClientResponse.fromWeb(
161+
request,
162+
Response.json({ error: "management-secret is wrong" }, { status: 401 }),
163+
),
164+
),
165+
);
166+
const api = yield* makeCliproxyApi.pipe(
167+
Effect.provideService(HttpClient.HttpClient, test),
168+
Effect.provide(NodeCrypto.layer),
169+
);
170+
const error = yield* Effect.flip(api.readAccounts(config));
171+
expect(error.detail).toContain("401");
172+
expect(error.detail).not.toContain("management-secret");
173+
}),
174+
);
175+
176+
it.effect("says when the hub does not answer in time", () =>
177+
Effect.gen(function* () {
178+
const api = yield* makeCliproxyApi.pipe(
179+
Effect.provideService(
180+
HttpClient.HttpClient,
181+
HttpClient.make(() => Effect.never),
182+
),
183+
Effect.provide(NodeCrypto.layer),
184+
);
185+
const pending = yield* Effect.flip(api.readAccounts(config)).pipe(
186+
Effect.forkChild({ startImmediately: true }),
187+
);
188+
yield* TestClock.adjust("15 seconds");
189+
const error = yield* Fiber.join(pending);
190+
expect(error.detail).toContain("did not answer within 15 seconds");
191+
}),
192+
);
193+
194+
it.effect("keeps a malformed account list generic", () =>
195+
Effect.gen(function* () {
196+
const test = HttpClient.make((request) =>
197+
Effect.succeed(
198+
HttpClientResponse.fromWeb(request, Response.json({ nope: "hub-internal" })),
199+
),
200+
);
201+
const api = yield* makeCliproxyApi.pipe(
202+
Effect.provideService(HttpClient.HttpClient, test),
203+
Effect.provide(NodeCrypto.layer),
204+
);
205+
const error = yield* Effect.flip(api.readAccounts(config));
206+
expect(error.detail).toBe("The hub could not list accounts.");
207+
}),
208+
);
209+
});
210+
117211
describe("CLIProxyAPI built-in management API", () => {
118212
it.effect(
119213
"reads both accounts and their earliest unexpired credits without plugin endpoints",

‎apps/server/src/usage/cliproxyApi.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import {
55
type UsageLimitSourceAccount,
66
type UsageLimitSourceConfig,
77
} from "@t3tools/contracts";
8+
import * as Cause from "effect/Cause";
89
import * as Crypto from "effect/Crypto";
910
import * as DateTime from "effect/DateTime";
1011
import * as Effect from "effect/Effect";
1112
import * as Hex from "effect/encoding/Hex";
1213
import * as Schema from "effect/Schema";
13-
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
14+
import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
1415

1516
import { codexPlanLabel } from "../provider/CodexProvider.ts";
1617
import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
@@ -88,6 +89,43 @@ const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(Credit
8889
const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
8990
const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
9091
const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
92+
93+
// Codes that mean the certificate chain is not trusted, which an extra CA can fix. Expired or
94+
// mismatched certificates are reported by code only.
95+
const UNTRUSTED_CERTIFICATE_CODES = new Set([
96+
"DEPTH_ZERO_SELF_SIGNED_CERT",
97+
"SELF_SIGNED_CERT_IN_CHAIN",
98+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
99+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
100+
]);
101+
102+
/** The Node error code under a failed fetch, which wraps it in a generic `TypeError`. */
103+
const nodeErrorCode = (cause: unknown) => {
104+
for (let error = cause, depth = 0; error instanceof Error && depth < 3; depth += 1) {
105+
const code = (error as { readonly code?: unknown }).code;
106+
if (typeof code === "string" && /^[A-Z0-9_]+$/.test(code)) return code;
107+
error = error.cause;
108+
}
109+
return undefined;
110+
};
111+
112+
// Hub responses and nested error messages can carry keys or tokens, so only the failure's kind,
113+
// HTTP status, or Node error code reaches the client.
114+
const describeManagementFailure = (error: unknown) => {
115+
if (Cause.isTimeoutError(error)) return "The hub did not answer within 15 seconds.";
116+
if (HttpClientError.isHttpClientError(error)) {
117+
const reason = error.reason;
118+
if (reason._tag === "StatusCodeError") {
119+
return `The hub answered with HTTP ${reason.response.status}.`;
120+
}
121+
const code = reason._tag === "TransportError" ? nodeErrorCode(reason.cause) : undefined;
122+
if (code !== undefined && UNTRUSTED_CERTIFICATE_CODES.has(code)) {
123+
return `The hub's TLS certificate is not trusted (${code}). If it comes from a private CA, add that CA to NODE_EXTRA_CA_CERTS.`;
124+
}
125+
if (code !== undefined) return `The hub request failed (${code}).`;
126+
}
127+
return "The hub management request failed.";
128+
};
91129
const decodeConsumeResponse = Schema.decodeUnknownEffect(
92130
Schema.fromJsonString(
93131
Schema.Struct({
@@ -144,7 +182,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
144182
Effect.flatMap((response) => response.json),
145183
Effect.timeout("15 seconds"),
146184
Effect.mapError(
147-
() => new UsageLimitSourceError({ detail: "The hub management request failed." }),
185+
(error) => new UsageLimitSourceError({ detail: describeManagementFailure(error) }),
148186
),
149187
);
150188
return response;
@@ -310,7 +348,12 @@ export const makeCliproxyApi = Effect.gen(function* () {
310348
): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
311349
const accounts = yield* authFiles(config).pipe(
312350
Effect.mapError(
313-
() => new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
351+
(error) =>
352+
new UsageLimitSourceError({
353+
detail: isUsageLimitSourceError(error)
354+
? `The hub could not list accounts. ${error.detail}`
355+
: "The hub could not list accounts.",
356+
}),
314357
),
315358
);
316359
return yield* Effect.forEach(

0 commit comments

Comments
 (0)