@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 671 lines 26.3 KB
Raw
1 import { describe, expect, it } from "@effect/vitest";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 // @effect-diagnostics-next-line nodeBuiltinImport:off -- A real socket server verifies the HTTP wire format.
5 import * as NodeHttp from "node:http";
6 // @effect-diagnostics-next-line nodeBuiltinImport:off -- The socket fixture owns its temporary directory.
7 import * as NodeFSP from "node:fs/promises";
8 import * as NodeOS from "node:os";
9 // @effect-diagnostics-next-line nodeBuiltinImport:off -- Keep the native socket path within the temporary directory.
10 import * as NodePath from "node:path";
11 import * as HostProcess from "@t3tools/shared/HostProcess";
12 import * as Effect from "effect/Effect";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Layer from "effect/Layer";
15 import * as Redacted from "effect/Redacted";
16 import * as TestClock from "effect/testing/TestClock";
17 import * as Tracer from "effect/Tracer";
18 import { ChildProcessSpawner } from "effect/process";
19 import { VcsProcessTimeoutError } from "@t3tools/contracts";
20 import { HttpClient, HttpClientResponse, HttpClientRequest } from "effect/http";
21 import { GraphQLClient } from "effect/graphql";
22
23 import * as GitHubRest from "./GitHubRest.ts";
24 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
25 import * as GitHubCredentials from "./GitHubCredentials.ts";
26 import * as GitHubQuota from "./GitHubQuota.ts";
27 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
28 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
29 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
30 import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
31 import * as GitHubHttpClient from "./GitHubHttpClient.ts";
32 import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
33 import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts";
34 import { driver } from "./driver.ts";
35
36 const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
37 enabled: false,
38 token: () => Effect.succeedNone,
39 invalidate: () => Effect.void,
40 });
41
42 const NOW = Date.parse("2026-10-05T12:00:00.000Z");
43
44 function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
45 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
46 let tokens = ["first", "second"];
47 let invalidations = 0;
48 let credentialReads = 0;
49 const credentials = Layer.succeed(
50 GitHubCredentials.GitHubCredentials,
51 GitHubCredentials.GitHubCredentials.of({
52 get: (host) =>
53 Effect.sync(() => {
54 credentialReads++;
55 return {
56 host,
57 token: Redacted.make(tokens[0]!),
58 source: "gh" as const,
59 fingerprint: `${host}:${tokens[0]}`,
60 };
61 }),
62 saved: () => Effect.succeedNone,
63 fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
64 invalidate: () =>
65 Effect.sync(() => {
66 invalidations++;
67 tokens = tokens.slice(1);
68 }),
69 }),
70 );
71 const http = Layer.succeed(
72 HttpClient.HttpClient,
73 HttpClient.make((request) => {
74 requests.push(request);
75 return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
76 }),
77 );
78 const layer = GitHubRest.layer.pipe(
79 Layer.provide(Layer.mergeAll(credentials, http, appSignedOut)),
80 Layer.provideMerge(GitHubQuota.layer),
81 Layer.provideMerge(SourceControlRateLimit.layer),
82 );
83 return {
84 layer,
85 requests,
86 invalidations: () => invalidations,
87 credentialReads: () => credentialReads,
88 };
89 }
90
91 const json = (body: unknown, init?: ResponseInit) =>
92 new Response(JSON.stringify(body), {
93 ...init,
94 headers: { "content-type": "application/json", ...init?.headers },
95 });
96
97 describe("environmentToken", () => {
98 it("follows gh's precedence per kind of host", () => {
99 const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
100 expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
101 expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
102 "github",
103 );
104 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
105 expect(
106 GitHubCredentials.environmentToken("git.acme.internal", {
107 ...env,
108 GH_HOST: "git.acme.internal",
109 }),
110 ).toBe("ghe");
111 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
112 });
113 });
114
115 describe("GitHubRest", () => {
116 it.live("routes REST and GraphQL through gh's plain HTTP Unix socket", () =>
117 Effect.gen(function* () {
118 const directory = yield* Effect.acquireRelease(
119 Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "gh-"))),
120 (directory) =>
121 Effect.promise(() => NodeFSP.rm(directory, { recursive: true, force: true })),
122 );
123 const socketPath = NodePath.join(directory, "api.sock");
124 const requests: Array<{
125 method: string | undefined;
126 path: string | undefined;
127 headers: NodeHttp.IncomingHttpHeaders;
128 body: string;
129 }> = [];
130 let redirectClosed = Promise.resolve();
131 const server = NodeHttp.createServer(async (request, response) => {
132 const chunks: Array<Buffer> = [];
133 for await (const chunk of request) chunks.push(Buffer.from(chunk));
134 const body = Buffer.concat(chunks).toString();
135 requests.push({
136 method: request.method,
137 path: request.url,
138 headers: request.headers,
139 body,
140 });
141 if (request.url?.endsWith("/renamed-user")) {
142 redirectClosed = new Promise<void>((resolve) => response.once("close", resolve));
143 response.writeHead(301, { location: "user?per_page=1" });
144 response.flushHeaders();
145 return;
146 }
147 if (request.url === "/cross-host" || request.url === "/loop") {
148 response.writeHead(301, {
149 location: request.url === "/loop" ? "/loop" : "https://redirect.acme.test:8443/user",
150 });
151 response.end();
152 return;
153 }
154 if (request.url === "/cross-post-307" || request.url === "/cross-post-308") {
155 response.writeHead(Number(request.url.slice(-3)), {
156 location: "https://redirect.acme.test:8443/user",
157 });
158 response.end();
159 return;
160 }
161 if (request.url === "/post-303" || request.url === "/post-307") {
162 response.writeHead(request.url === "/post-303" ? 303 : 307, { location: "/user" });
163 response.end();
164 return;
165 }
166 response.statusCode = request.url === "/user/starred/acme/web" ? 204 : 200;
167 response.setHeader("content-type", "application/json");
168 response.end(
169 JSON.stringify(
170 body.includes("query PullRequestByNumber")
171 ? {
172 data: {
173 repository: {
174 pullRequest: {
175 number: 7,
176 title: "Socket request",
177 url: "https://github.com/acme/web/pull/7",
178 baseRefName: "main",
179 headRefName: "feature",
180 headRefOid: "f".repeat(40),
181 state: "OPEN",
182 isDraft: false,
183 mergedAt: null,
184 closedAt: null,
185 updatedAt: "2026-01-02T00:00:00Z",
186 isCrossRepository: false,
187 headRepository: { name: "web", nameWithOwner: "acme/web" },
188 headRepositoryOwner: { __typename: "User", login: "acme" },
189 },
190 },
191 },
192 }
193 : request.url?.endsWith("graphql")
194 ? { data: { repository: { pullRequest: { additions: 3, deletions: 1 } } } }
195 : { login: "proxy-user" },
196 ),
197 );
198 });
199 yield* Effect.acquireRelease(
200 Effect.promise(
201 () =>
202 new Promise<void>((resolve, reject) => {
203 server.once("error", reject);
204 server.listen(socketPath, resolve);
205 }),
206 ),
207 () =>
208 Effect.promise(
209 () =>
210 new Promise<void>((resolve, reject) =>
211 server.close((error) => (error ? reject(error) : resolve())),
212 ),
213 ),
214 );
215 const directRequests: Array<string> = [];
216 const fallback = Layer.succeed(
217 HttpClient.HttpClient,
218 HttpClient.make((request) => {
219 directRequests.push(request.url);
220 return Effect.succeed(HttpClientResponse.fromWeb(request, json({}, { status: 401 })));
221 }),
222 );
223 const host = TestSourceControlHost.layer({
224 process: {
225 run: (input) => {
226 expect(input.command).toBe("gh");
227 if (input.args[0] === "config") {
228 expect(input.args).toEqual(["config", "get", "http_unix_socket"]);
229 return Effect.succeed(TestSourceControlHost.processOutput(`${socketPath}\n`));
230 }
231 expect(input.args.slice(0, 2)).toEqual(["auth", "token"]);
232 return Effect.succeed(TestSourceControlHost.processOutput("placeholder\n"));
233 },
234 },
235 });
236 const layer = GitHubRest.layerWithDependencies.pipe(
237 Layer.provideMerge(GitHubHttpClient.layer),
238 Layer.provide(
239 Layer.mergeAll(
240 host,
241 fallback,
242 NodeServices.layer,
243 NodeCrypto.layer,
244 SourceControlRateLimit.layer,
245 ),
246 ),
247 );
248 yield* Effect.gen(function* () {
249 const rest = yield* GitHubRest.GitHubRest;
250 const client = yield* GraphQLClient.make(
251 PullRequestBatchesGraphQLGroup.middleware(GitHubGraphQlClient.GitHubGraphQlAuth),
252 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
253 for (const [host, apiHost, root] of [
254 ["github.com", "api.github.com", ""],
255 ["git.acme.test:8443", "git.acme.test:8443", "/api/v3"],
256 ] as const) {
257 const answer = yield* rest.rest({
258 host,
259 operation: "user",
260 path: "user?per_page=1",
261 });
262 expect(JSON.parse(answer.body)).toEqual({ login: "proxy-user" });
263 const stats = yield* client
264 .PullRequestStats({ owner: "acme", name: "web", number: 7 })
265 .pipe(GitHubGraphQlClient.call({ host, operation: "stats" }));
266 expect(stats).toEqual({ repository: { pullRequest: { additions: 3, deletions: 1 } } });
267 const [restRequest, graphqlRequest] = requests.slice(-2);
268 expect(restRequest).toMatchObject({ method: "GET", path: `${root}/user?per_page=1` });
269 expect(graphqlRequest).toMatchObject({
270 method: "POST",
271 path: root === "" ? "/graphql" : "/api/graphql",
272 });
273 for (const request of [restRequest!, graphqlRequest!]) {
274 expect(request.headers).toMatchObject({
275 host: apiHost,
276 authorization: "Bearer placeholder",
277 "user-agent": "t3code",
278 "x-github-api-version": "2022-11-28",
279 });
280 }
281 expect(JSON.parse(graphqlRequest!.body).variables).toEqual({
282 owner: "acme",
283 name: "web",
284 number: 7,
285 });
286 }
287 const renamed = yield* rest.rest({
288 host: "github.com",
289 operation: "renamedUser",
290 path: "renamed-user",
291 });
292 expect(JSON.parse(renamed.body)).toEqual({ login: "proxy-user" });
293 yield* Effect.promise(() => redirectClosed);
294 expect(requests.at(-1)).toMatchObject({
295 path: "/user?per_page=1",
296 headers: { host: "api.github.com", authorization: "Bearer placeholder" },
297 });
298 yield* rest.rest({ host: "github.com", operation: "redirect", path: "cross-host" });
299 expect(requests.at(-1)?.headers.host).toBe("redirect.acme.test:8443");
300 expect(requests.at(-1)?.headers.authorization).toBeUndefined();
301 const loopError = yield* Effect.flip(
302 rest.rest({ host: "github.com", operation: "redirectLoop", path: "loop" }),
303 );
304 expect(loopError._tag).toBe("GitHubApiResponseError");
305 expect(requests.filter((request) => request.path === "/loop")).toHaveLength(11);
306 const http = yield* HttpClient.HttpClient;
307 for (const status of [303, 307]) {
308 const response = yield* http.execute(
309 HttpClientRequest.post(`https://api.github.com/post-${status}`).pipe(
310 HttpClientRequest.bodyJsonUnsafe({ query: "query { viewer { login } }" }),
311 HttpClientRequest.bearerToken("placeholder"),
312 ),
313 );
314 yield* response.text;
315 expect(requests.at(-1)).toMatchObject({
316 method: status === 303 ? "GET" : "POST",
317 path: "/user",
318 body: status === 303 ? "" : JSON.stringify({ query: "query { viewer { login } }" }),
319 });
320 }
321 for (const status of [307, 308]) {
322 const before = requests.length;
323 const response = yield* http.execute(
324 HttpClientRequest.post(`https://api.github.com/cross-post-${status}`).pipe(
325 HttpClientRequest.bodyJsonUnsafe({ query: "query { viewer { login } }" }),
326 HttpClientRequest.bearerToken("placeholder"),
327 ),
328 );
329 yield* response.text;
330 expect(response.status).toBe(status);
331 expect(requests.slice(before)).toHaveLength(1);
332 expect(requests.at(-1)?.headers.host).toBe("api.github.com");
333 }
334 const instance = yield* driver.make.pipe(
335 Effect.provide(
336 Layer.mergeAll(
337 host,
338 fallback,
339 NodeServices.layer,
340 NodeCrypto.layer,
341 SourceControlRateLimit.layer,
342 ),
343 ),
344 );
345 const reference = yield* instance.sourceControl.getChangeRequest({
346 cwd: directory,
347 reference: "https://github.com/acme/web/pull/7",
348 });
349 expect(reference.number).toBe(7);
350 expect(requests.at(-1)?.body).toContain("query PullRequestByNumber");
351 expect(yield* instance.isRepositoryStarred!("github.com", "acme/web")).toBe(true);
352 expect(requests.at(-1)?.path).toBe("/user/starred/acme/web");
353 yield* Effect.promise(() => NodeFSP.unlink(socketPath));
354 const error = yield* Effect.flip(
355 rest.rest({ host: "github.com", operation: "user", path: "user" }),
356 );
357 expect(error._tag).toBe("GitHubApiRequestError");
358 expect(directRequests).toEqual([]);
359 const mediaUrl = "https://objects.githubusercontent.com/proof.png";
360 const media = yield* instance.fetchMedia!({ url: mediaUrl, headers: {} });
361 expect(media?.status).toBe(401);
362 expect(directRequests).toEqual([mediaUrl]);
363 }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}));
364 }),
365 );
366
367 it.effect.each(["", "unavailable"])(
368 "keeps the existing HTTP client when gh's socket is %s",
369 (config) => {
370 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
371 const fallback = Layer.succeed(
372 HttpClient.HttpClient,
373 HttpClient.make((request) => {
374 requests.push(request);
375 return Effect.succeed(
376 HttpClientResponse.fromWeb(request, json({ login: "direct-user" })),
377 );
378 }),
379 );
380 const host = TestSourceControlHost.layer({
381 process: {
382 run: () =>
383 config === ""
384 ? Effect.succeed(TestSourceControlHost.processOutput("\n"))
385 : Effect.fail(
386 new VcsProcessTimeoutError({
387 operation: "GitHubHttpClient.config",
388 command: "gh",
389 cwd: "/",
390 timeoutMs: 10_000,
391 }),
392 ),
393 },
394 });
395 return Effect.gen(function* () {
396 const api = yield* HttpClient.HttpClient;
397 const answer = yield* api.execute(
398 HttpClientRequest.get("https://api.github.com/user").pipe(
399 HttpClientRequest.bearerToken("first"),
400 ),
401 );
402 expect(yield* answer.json).toEqual({ login: "direct-user" });
403 expect(requests).toHaveLength(1);
404 expect(requests[0]).toMatchObject({
405 url: "https://api.github.com/user",
406 headers: { authorization: "Bearer first" },
407 });
408 }).pipe(
409 Effect.provide(GitHubHttpClient.layer.pipe(Layer.provide(Layer.merge(host, fallback)))),
410 );
411 },
412 );
413
414 it.effect("traces the operation, path and quota, never the query string or the token", () => {
415 const spans: Array<Tracer.NativeSpan> = [];
416 const tracer = Tracer.make({
417 span: (options) => {
418 const span = new Tracer.NativeSpan(options);
419 spans.push(span);
420 return span;
421 },
422 });
423 const { layer } = harness(() =>
424 json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
425 );
426 return Effect.gen(function* () {
427 yield* TestClock.setTime(NOW);
428 const api = yield* GitHubRest.GitHubRest;
429 yield* api.rest({
430 host: "github.com",
431 operation: "listWorkflowRuns",
432 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
433 });
434 const send = spans.find((span) => span.name === "GitHubRest.send")!;
435 expect(Object.fromEntries(send.attributes)).toMatchObject({
436 "github.operation": "listWorkflowRuns",
437 "github.kind": "rest",
438 "url.path": "/repos/acme/web/actions/runs",
439 "http.response.status_code": 200,
440 "github.ratelimit.remaining": 4800,
441 });
442 const everything = spans
443 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
444 .join("\n");
445 expect(everything).not.toContain("head_sha");
446 expect(everything).not.toContain("first");
447 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
448 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
449 });
450
451 it.effect("lets an interactive request through a pause a background read recorded", () => {
452 const reset = Math.floor(NOW / 1000) + 600;
453 let call = 0;
454 const { layer, requests } = harness(() =>
455 ++call === 1
456 ? json(
457 { message: "API rate limit exceeded" },
458 {
459 status: 403,
460 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
461 },
462 )
463 : json({ ok: true }),
464 );
465 return Effect.gen(function* () {
466 yield* TestClock.setTime(NOW);
467 const api = yield* GitHubRest.GitHubRest;
468 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
469 yield* Effect.flip(api.rest(read));
470 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
471 const merged = yield* api
472 .rest({
473 host: "github.com",
474 operation: "merge",
475 method: "PUT",
476 path: "repos/acme/web/pulls/7/merge",
477 })
478 .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
479 expect(merged.status).toBe(200);
480 expect(requests).toHaveLength(2);
481 }).pipe(Effect.provide(layer));
482 });
483
484 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
485 let call = 0;
486 const { layer } = harness(() =>
487 ++call === 1
488 ? new Response(null, { status: 304 })
489 : json(
490 { message: "API rate limit exceeded" },
491 {
492 status: 403,
493 headers: { "retry-after": "60" },
494 },
495 ),
496 );
497 return Effect.gen(function* () {
498 yield* TestClock.setTime(NOW);
499 const api = yield* GitHubRest.GitHubRest;
500 const notModified = yield* api.rest({
501 host: "github.com",
502 operation: "checks",
503 path: "repos/acme/web/pulls/7",
504 ifNoneMatch: '"abc"',
505 });
506 expect(notModified.status).toBe(304);
507 const error = yield* Effect.flip(
508 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
509 );
510 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
511 }).pipe(Effect.provide(layer));
512 });
513
514 it.effect("reads a proxy's 403 with Retry-After as a refusal and keeps the host open", () => {
515 const pages = [
516 "<html><head><title>403 Forbidden</title></head><body>nginx</body></html>",
517 "<html><body>Request blocked by proxy abuse detection; contact your administrator</body></html>",
518 ];
519 const { layer, requests } = harness(
520 () =>
521 new Response(pages.shift(), {
522 status: 403,
523 headers: { "content-type": "text/html", "retry-after": "5" },
524 }),
525 );
526 return Effect.gen(function* () {
527 yield* TestClock.setTime(NOW);
528 const api = yield* GitHubRest.GitHubRest;
529 const read = {
530 host: "ghes.example.internal",
531 operation: "checks",
532 path: "repos/acme/web/pulls/7",
533 };
534 const first = yield* Effect.flip(api.rest(read));
535 expect(first).toMatchObject({ _tag: "GitHubApiResponseError", status: 403 });
536 const second = yield* Effect.flip(api.rest(read));
537 expect(second).toMatchObject({ _tag: "GitHubApiResponseError", status: 403 });
538 expect(requests).toHaveLength(2);
539 }).pipe(Effect.provide(layer));
540 });
541
542 it.effect("pauses the host on an abuse-detection 403 that never says rate limit", () => {
543 const { layer, requests } = harness(() =>
544 json(
545 {
546 message: "You have triggered an abuse detection mechanism. Please wait before retrying.",
547 documentation_url:
548 "https://docs.github.com/rest/overview/resources-in-the-rest-api#abuse-rate-limits",
549 },
550 { status: 403, headers: { "retry-after": "60", "x-ratelimit-remaining": "4878" } },
551 ),
552 );
553 return Effect.gen(function* () {
554 yield* TestClock.setTime(NOW);
555 const api = yield* GitHubRest.GitHubRest;
556 const read = { host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" };
557 expect(yield* Effect.flip(api.rest(read))).toMatchObject({
558 _tag: "GitHubApiRateLimitError",
559 retryAt: NOW + 60_000,
560 });
561 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
562 expect(requests).toHaveLength(1);
563 }).pipe(Effect.provide(layer));
564 });
565
566 it.effect("drops a refused token so the next request asks the source again", () => {
567 const { layer, requests, invalidations } = harness((request) =>
568 request.headers.authorization === "Bearer first"
569 ? new Response(null, { status: 401 })
570 : json({ ok: true }),
571 );
572 return Effect.gen(function* () {
573 const api = yield* GitHubRest.GitHubRest;
574 const refused = yield* Effect.flip(
575 api.rest({ host: "github.com", operation: "user", path: "user" }),
576 );
577 expect(refused._tag).toBe("GitHubApiAuthenticationError");
578 expect(invalidations()).toBe(1);
579 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
580 expect(answered.status).toBe(200);
581 expect(requests.map((request) => request.headers.authorization)).toEqual([
582 "Bearer first",
583 "Bearer second",
584 ]);
585 }).pipe(Effect.provide(layer));
586 });
587
588 it.effect("refuses to send a pinned credential to another host", () => {
589 const { layer, requests } = harness(() => json({}));
590 return Effect.gen(function* () {
591 const api = yield* GitHubRest.GitHubRest;
592 const error = yield* Effect.flip(
593 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
594 ).pipe(
595 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
596 host: "github.com",
597 token: Redacted.make("pinned"),
598 credentialFingerprint: "github.com:pinned",
599 }),
600 );
601 expect(error._tag).toBe("GitHubApiAuthenticationError");
602 expect(requests).toHaveLength(0);
603 }).pipe(Effect.provide(layer));
604 });
605 });
606
607 describe("GitHubCredentials", () => {
608 const unexpectedHttp = HttpClient.make((request) =>
609 Effect.die(`Unexpected request to ${request.url}`),
610 );
611 const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
612 GitHubCredentials.layer.pipe(
613 Layer.provide(TestSourceControlHost.layer({ process: { run } })),
614 Layer.provide(NodeCrypto.layer),
615 Layer.provide(FileSystem.layerNoop({})),
616 Layer.provide(Layer.succeed(HttpClient.HttpClient, unexpectedHttp)),
617 );
618
619 it.effect("reports a gh timeout as a timeout and does not cache it", () => {
620 let calls = 0;
621 return Effect.gen(function* () {
622 const credentials = yield* GitHubCredentials.GitHubCredentials;
623 const first = yield* Effect.flip(credentials.get("github.com"));
624 expect(first._tag).toBe("GitHubCliTimeoutError");
625 expect(first.message).not.toContain("gh auth status");
626 expect((yield* credentials.get("github.com")).source).toBe("gh");
627 expect(calls).toBe(2);
628 }).pipe(
629 Effect.provide(
630 credentialsWith(() =>
631 ++calls === 1
632 ? Effect.fail(
633 new VcsProcessTimeoutError({
634 operation: "GitHubCredentials.get",
635 command: "gh",
636 cwd: "/",
637 timeoutMs: 10_000,
638 }),
639 )
640 : Effect.succeed({
641 exitCode: ChildProcessSpawner.ExitCode(0),
642 stdout: "token\n",
643 stderr: "",
644 stdoutTruncated: false,
645 stderrTruncated: false,
646 }),
647 ),
648 ),
649 );
650 });
651
652 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
653 Effect.gen(function* () {
654 const credentials = yield* GitHubCredentials.GitHubCredentials;
655 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
656 expect(error._tag).toBe("GitHubNotSignedInError");
657 }).pipe(
658 Effect.provide(
659 credentialsWith(() =>
660 Effect.succeed({
661 exitCode: ChildProcessSpawner.ExitCode(0),
662 stdout: "\n",
663 stderr: "",
664 stdoutTruncated: false,
665 stderrTruncated: false,
666 }),
667 ),
668 ),
669 ),
670 );
671 });