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

main
ts 229 lines 9 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Redacted from "effect/Redacted";
7 import { HttpClient } from "effect/http";
8 import { ChildProcessSpawner } from "effect/process";
9
10 import { DEFAULT_SERVER_SETTINGS, SecretProviderId, SecretProviderKind } from "@t3tools/contracts";
11 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
12 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
13 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
14 import * as GitHubCredentials from "./GitHubCredentials.ts";
15
16 const TOKEN_VARIABLES = [
17 "GH_TOKEN",
18 "GITHUB_TOKEN",
19 "GH_ENTERPRISE_TOKEN",
20 "GITHUB_ENTERPRISE_TOKEN",
21 ] as const;
22
23 const ENTERPRISE_TOKEN_VARIABLES = ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"] as const;
24
25 const hostSettings = (
26 hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }>,
27 ) =>
28 Object.fromEntries(
29 Object.entries(hosts).map(([host, choice]) => [host, { enabled: true, ...choice }]),
30 );
31
32 function harness(
33 hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }> = {},
34 signedOut: ReadonlyArray<string> = [],
35 tokens: Record<string, string> = {},
36 ) {
37 const calls: Array<ReadonlyArray<string>> = [];
38 const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = (input) =>
39 Effect.sync(() => {
40 calls.push(input.args);
41 const user = input.args[input.args.indexOf("--user") + 1];
42 if (input.args.includes("--user") && user !== undefined && signedOut.includes(user)) {
43 return {
44 exitCode: ChildProcessSpawner.ExitCode(0),
45 stdout: "",
46 stderr: "",
47 stdoutTruncated: false,
48 stderrTruncated: false,
49 };
50 }
51 // gh hands the enterprise variables to every host but github.com.
52 const fromEnterpriseEnv = input.args.includes("github.com")
53 ? undefined
54 : ENTERPRISE_TOKEN_VARIABLES.map(
55 (name) =>
56 (input.env !== undefined && name in input.env ? input.env : process.env)[name],
57 ).find(Boolean);
58 if (fromEnterpriseEnv !== undefined) {
59 return {
60 exitCode: ChildProcessSpawner.ExitCode(0),
61 stdout: `${fromEnterpriseEnv}\n`,
62 stderr: "",
63 stdoutTruncated: false,
64 stderrTruncated: false,
65 };
66 }
67 return {
68 exitCode: ChildProcessSpawner.ExitCode(0),
69 stdout: input.args.includes("--user") ? `token-for-${user}\n` : "active-token\n",
70 stderr: "",
71 stdoutTruncated: false,
72 stderrTruncated: false,
73 };
74 });
75 const layer = GitHubCredentials.layer.pipe(
76 Layer.provideMerge(
77 TestSourceControlHost.layer({
78 settings: applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
79 sourceControlHosts: { github: { hosts: hostSettings(hosts), tokens } },
80 }),
81 process: { run },
82 }),
83 ),
84 Layer.provide(NodeCrypto.layer),
85 Layer.provide(FileSystem.layerNoop({})),
86 Layer.provide(
87 Layer.succeed(
88 HttpClient.HttpClient,
89 HttpClient.make((request) => Effect.die(`Unexpected request to ${request.url}`)),
90 ),
91 ),
92 );
93 return { layer, calls };
94 }
95
96 describe("GitHubCredentials", () => {
97 beforeEach(() => {
98 for (const name of TOKEN_VARIABLES) vi.stubEnv(name, "");
99 });
100 afterEach(() => {
101 vi.unstubAllEnvs();
102 });
103
104 it.effect("lets an environment token win over a pinned account, as gh does", () => {
105 vi.stubEnv("GH_TOKEN", "from-env");
106 const { layer, calls } = harness({ "github.com": { account: "work" } });
107 return Effect.gen(function* () {
108 const credentials = yield* GitHubCredentials.GitHubCredentials;
109 const credential = yield* credentials.get("github.com");
110 expect(Redacted.value(credential.token)).toBe("from-env");
111 expect(credential.source).toBe("env");
112 expect(calls).toEqual([]);
113 }).pipe(Effect.provide(layer));
114 });
115
116 it.effect("picks up a changed account on the next request without a restart", () => {
117 const { layer, calls } = harness();
118 return Effect.gen(function* () {
119 const credentials = yield* GitHubCredentials.GitHubCredentials;
120 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
121 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
122
123 yield* settings.update({
124 sourceControlHosts: {
125 github: { hosts: { "github.com": { account: "work", enabled: true } } },
126 },
127 });
128 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("token-for-work");
129
130 yield* settings.update({
131 sourceControlHosts: { github: { hosts: { "github.com": { enabled: false } } } },
132 });
133 expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(
134 "GitHubHostDisabledError",
135 );
136
137 yield* settings.update({ sourceControlHosts: { github: { hosts: {} } } });
138 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
139 expect(calls).toHaveLength(2);
140 }).pipe(Effect.provide(layer));
141 });
142
143 it.effect("falls back to the active login when the pinned one is no longer signed in", () => {
144 const { layer, calls } = harness({ "github.com": { account: "gone" } }, ["gone"]);
145 return Effect.gen(function* () {
146 const credentials = yield* GitHubCredentials.GitHubCredentials;
147 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
148 expect(calls).toEqual([
149 ["auth", "token", "--hostname", "github.com", "--user", "gone"],
150 ["auth", "token", "--hostname", "github.com"],
151 ]);
152 }).pipe(Effect.provide(layer));
153 });
154
155 it.effect("uses a token saved in Settings before GH_TOKEN and gh", () => {
156 vi.stubEnv("GH_TOKEN", "env-token");
157 const { layer, calls } = harness({}, [], { "github.com": "saved-token" });
158 return Effect.gen(function* () {
159 const credentials = yield* GitHubCredentials.GitHubCredentials;
160 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
161 const credential = yield* credentials.get("github.com");
162 expect(Redacted.value(credential.token)).toBe("saved-token");
163 expect(credential.source).toBe("settings");
164
165 // A reference left in place by getWithSecrets is one its secret provider could not read.
166 yield* settings.update({
167 secretProviders: {
168 [SecretProviderId.make("vault")]: {
169 kind: SecretProviderKind.make("one_password"),
170 label: "Work vault",
171 config: {},
172 },
173 },
174 sourceControlHosts: {
175 github: {
176 tokens: {
177 "github.com": { provider: SecretProviderId.make("vault"), reference: "gh#token" },
178 },
179 },
180 },
181 });
182 const error = yield* Effect.flip(credentials.get("github.com"));
183 expect(error._tag).toBe("SettingsSecretUnresolvedError");
184 expect(error.message).toContain('"Work vault"');
185 expect(calls).toEqual([]);
186 }).pipe(Effect.provide(layer));
187 });
188
189 it.effect("keeps a host turned off even with a token saved in Settings", () => {
190 const { layer } = harness({ "github.com": { enabled: false } }, [], {
191 "github.com": "saved-token",
192 });
193 return Effect.gen(function* () {
194 const credentials = yield* GitHubCredentials.GitHubCredentials;
195 expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(
196 "GitHubHostDisabledError",
197 );
198 }).pipe(Effect.provide(layer));
199 });
200
201 it.effect.each(ENTERPRISE_TOKEN_VARIABLES)(
202 "keeps %s away from a host other than GH_HOST",
203 (name) => {
204 vi.stubEnv("GH_HOST", "ghe.corp.example");
205 vi.stubEnv(name, "enterprise-secret");
206 const { layer } = harness();
207 return Effect.gen(function* () {
208 const credentials = yield* GitHubCredentials.GitHubCredentials;
209 const other = yield* credentials.get("git.other.example");
210 expect(Redacted.value(other.token)).toBe("active-token");
211 const own = yield* credentials.get("ghe.corp.example");
212 expect(Redacted.value(own.token)).toBe("enterprise-secret");
213 }).pipe(Effect.provide(layer));
214 },
215 );
216
217 it.effect("never hands a token to a host that is not a plain hostname", () => {
218 vi.stubEnv("GH_TOKEN", "env-token");
219 const { layer, calls } = harness();
220 return Effect.gen(function* () {
221 const credentials = yield* GitHubCredentials.GitHubCredentials;
222 for (const host of ["evil.com#.ghe.com", "evil.com/.ghe.com", "user@x.ghe.com"]) {
223 expect(GitHubCredentials.environmentToken(host, { GH_TOKEN: "env-token" })).toBeNull();
224 expect((yield* Effect.flip(credentials.get(host)))._tag).toBe("GitHubNotSignedInError");
225 }
226 expect(calls).toEqual([]);
227 }).pipe(Effect.provide(layer));
228 });
229 });