@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 304 lines 11.1 KB
Raw
1 import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
2 import * as Cache from "effect/Cache";
3 import * as Context from "effect/Context";
4 import * as Digest from "effect/crypto/Digest";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as Hex from "effect/encoding/Hex";
8 import * as Exit from "effect/Exit";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as PlatformError from "effect/PlatformError";
12 import * as Redacted from "effect/Redacted";
13 import * as Schema from "effect/Schema";
14
15 import * as HostProcess from "@t3tools/shared/HostProcess";
16
17 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18 import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
19 import {
20 requireSettingsSecretLiteral,
21 type ServerSettings,
22 type SettingsSecretUnresolvedError,
23 } from "@t3tools/contracts";
24
25 import * as GitHubClient from "../shared/definition.ts";
26 import { makeGhProcess } from "./gitHubCliProcess.ts";
27
28 /**
29 * Every gh run on the server shares this. A burst of them (a status poll across many checkouts)
30 * otherwise starts enough at once to trip GitHub's secondary rate limit.
31 */
32 export const GH_PROCESS_CONCURRENCY = { key: "gh", limit: 4 } as const;
33
34 const TOKEN_TTL = Duration.minutes(5);
35 const MISSING_TTL = Duration.seconds(10);
36
37 export const GitHubCredentialSource = Schema.Literals(["settings", "app", "env", "gh"]);
38 export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
39
40 export interface GitHubCredential {
41 readonly host: string;
42 readonly token: Redacted.Redacted<string>;
43 readonly source: GitHubCredentialSource;
44 readonly fingerprint: string;
45 }
46
47 export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(
48 "GitHubCliMissingError",
49 { host: Schema.String },
50 ) {
51 override get message(): string {
52 return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
53 }
54 }
55
56 export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
57 "GitHubNotSignedInError",
58 { host: Schema.String, account: Schema.optional(Schema.String) },
59 ) {
60 override get message(): string {
61 return this.account === undefined
62 ? `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`
63 : `No GitHub credential for ${this.account} on ${this.host}: run \`gh auth login --hostname ${this.host}\` for that account or pick another in Settings → Source control & issues.`;
64 }
65 }
66
67 export class GitHubHostDisabledError extends Schema.TaggedError<GitHubHostDisabledError>()(
68 "GitHubHostDisabledError",
69 { host: Schema.String },
70 ) {
71 override get message(): string {
72 return `GitHub host ${this.host} is turned off in Settings → Source control & issues.`;
73 }
74 }
75
76 export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedError>()(
77 "GitHubCliFailedError",
78 { host: Schema.String, cause: Schema.Defect() },
79 ) {
80 override get message(): string {
81 return `The GitHub CLI could not hand over a credential for ${this.host}. Check \`gh auth status\` on the server.`;
82 }
83 }
84
85 export class GitHubCliTimeoutError extends Schema.TaggedError<GitHubCliTimeoutError>()(
86 "GitHubCliTimeoutError",
87 { host: Schema.String, timeoutMs: Schema.Number, cause: Schema.Defect() },
88 ) {
89 override get message(): string {
90 return `The GitHub CLI did not hand over a credential for ${this.host} within ${this.timeoutMs / 1000} seconds. The server may be overloaded; try again.`;
91 }
92 }
93
94 export type GitHubCredentialUnavailableError =
95 | GitHubCliMissingError
96 | GitHubNotSignedInError
97 | GitHubHostDisabledError
98 | GitHubCliFailedError
99 | GitHubCliTimeoutError
100 | SettingsSecretUnresolvedError;
101
102 export class GitHubCredentials extends Context.Service<
103 GitHubCredentials,
104 {
105 readonly get: (
106 host: string,
107 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
108 /** The token saved in Settings for `host`, which outranks every other source. */
109 readonly saved: (
110 host: string,
111 ) => Effect.Effect<
112 Option.Option<GitHubCredential>,
113 GitHubHostDisabledError | GitHubNotSignedInError | SettingsSecretUnresolvedError
114 >;
115 readonly fingerprint: (host: string, token: string) => Effect.Effect<string>;
116 readonly invalidate: (host: string) => Effect.Effect<void>;
117 }
118 >()("@t3tools/source-control-github/server/GitHubCredentials") {}
119
120 const HOSTNAME =
121 /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\d{1,5})?$/;
122
123 /** API URLs are built from the host text, so anything but a bare hostname could redirect a token. */
124 export function isGitHubHost(host: string): boolean {
125 return HOSTNAME.test(host);
126 }
127
128 function isGitHubDotCom(host: string): boolean {
129 return host === "github.com" || host.endsWith(".ghe.com");
130 }
131
132 /** Restrict GH_ENTERPRISE_TOKEN to GH_HOST to prevent remote URLs from leaking it. */
133 export function environmentToken(
134 host: string,
135 env: Readonly<Record<string, string | undefined>>,
136 ): string | null {
137 if (!isGitHubHost(host)) return null;
138 const names = isGitHubDotCom(host)
139 ? ["GH_TOKEN", "GITHUB_TOKEN"]
140 : env.GH_HOST?.trim().toLowerCase() === host
141 ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
142 : [];
143 for (const name of names) {
144 const value = env[name]?.trim();
145 if (value) return value;
146 }
147 return null;
148 }
149
150 /** @public */
151 export const make = Effect.gen(function* () {
152 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
153 const process = yield* makeGhProcess;
154 const crypto = yield* Digest.Digest;
155 const environment = yield* HostProcess.Environment;
156 const workingDirectory = yield* HostProcess.WorkingDirectory;
157
158 const fingerprintOf = (host: string, token: string) =>
159 crypto.digest(Digest.sha256, new TextEncoder().encode(token)).pipe(
160 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
161 Effect.orDie,
162 );
163
164 const fromGh = (host: string, account: string | undefined) =>
165 process
166 .run({
167 operation: "GitHubCredentials.get",
168 command: "gh",
169 args: [
170 "auth",
171 "token",
172 "--hostname",
173 host,
174 ...(account === undefined ? [] : ["--user", account]),
175 ],
176 cwd: workingDirectory,
177 // Never let gh print the token into a debug log. gh answers any host but github.com with
178 // the enterprise variables, which would undo the GH_HOST restriction above.
179 env: {
180 GH_DEBUG: "",
181 GH_PROMPT_DISABLED: "1",
182 GH_ENTERPRISE_TOKEN: "",
183 GITHUB_ENTERPRISE_TOKEN: "",
184 },
185 timeoutMs: 10_000,
186 concurrency: GH_PROCESS_CONCURRENCY,
187 })
188 .pipe(
189 Effect.mapError((error) =>
190 error._tag === "VcsProcessSpawnError" &&
191 error.cause instanceof PlatformError.PlatformError &&
192 error.cause.reason._tag === "NotFound"
193 ? new GitHubCliMissingError({ host })
194 : // gh exits non-zero with "no oauth token" when it has no login for the host.
195 error._tag === "VcsProcessExitError"
196 ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
197 : error._tag === "VcsProcessTimeoutError"
198 ? new GitHubCliTimeoutError({ host, timeoutMs: error.timeoutMs, cause: error })
199 : new GitHubCliFailedError({ host, cause: error }),
200 ),
201 Effect.map((output) => output.stdout.trim()),
202 Effect.filterOrFail(
203 (token) => token !== "",
204 () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
205 ),
206 );
207
208 const readSettings = (settings: ServerSettings) =>
209 readSourceControlHostSettings(
210 GitHubClient.settings,
211 settings.sourceControlHosts[GitHubClient.definition.kind],
212 );
213
214 const hostChoice = (host: string) =>
215 sourceControlHost.settings.get.pipe(
216 Effect.map((settings) => readSettings(settings).hosts[host]),
217 Effect.orElseSucceed(() => undefined),
218 );
219
220 const savedToken = (host: string) =>
221 sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe(
222 Effect.map((settings) => ({
223 token: readSettings(settings).tokens[host],
224 secretProviders: settings.secretProviders,
225 })),
226 Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),
227 Effect.flatMap(({ token, secretProviders }) =>
228 requireSettingsSecretLiteral(token, secretProviders),
229 ),
230 Effect.map((token) => token.trim() || null),
231 );
232
233 const cacheKey = (host: string, account: string | undefined) =>
234 account === undefined ? host : `${host}\u0000${account}`;
235
236 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
237 const [host = key, choice] = key.split("\u0000");
238 const fromEnv = environmentToken(host, environment);
239 const token =
240 fromEnv ??
241 (yield* fromGh(host, choice).pipe(
242 Effect.catchTags({
243 GitHubNotSignedInError: (error) =>
244 choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
245 }),
246 ));
247 return {
248 host,
249 token: Redacted.make(token),
250 source: fromEnv !== null ? "env" : "gh",
251 fingerprint: yield* fingerprintOf(host, token),
252 } satisfies GitHubCredential;
253 });
254
255 const cache = yield* Cache.makeWith(lookup, {
256 capacity: 32,
257 timeToLive: (exit) =>
258 Exit.isSuccess(exit)
259 ? TOKEN_TTL
260 : Exit.findErrorOption(exit).pipe(
261 Option.exists(
262 (error) =>
263 error._tag === "GitHubCliFailedError" || error._tag === "GitHubCliTimeoutError",
264 ),
265 )
266 ? Duration.zero
267 : MISSING_TTL,
268 });
269
270 const saved = Effect.fn("GitHubCredentials.saved")(function* (rawHost: string) {
271 const host = normalizeHost(rawHost);
272 if (!isGitHubHost(host)) return yield* new GitHubNotSignedInError({ host });
273 if ((yield* hostChoice(host))?.enabled === false) {
274 return yield* new GitHubHostDisabledError({ host });
275 }
276 const token = yield* savedToken(host);
277 if (token === null) return Option.none<GitHubCredential>();
278 return Option.some<GitHubCredential>({
279 host,
280 token: Redacted.make(token),
281 source: "settings",
282 fingerprint: yield* fingerprintOf(host, token),
283 });
284 });
285
286 return GitHubCredentials.of({
287 get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
288 const host = normalizeHost(rawHost);
289 const fromSettings = yield* saved(host);
290 if (Option.isSome(fromSettings)) return fromSettings.value;
291 return yield* Cache.get(cache, cacheKey(host, (yield* hostChoice(host))?.account));
292 }),
293 saved,
294 fingerprint: fingerprintOf,
295 invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost) {
296 const host = normalizeHost(rawHost);
297 return hostChoice(host).pipe(
298 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
299 );
300 }),
301 });
302 });
303
304 export const layer = Layer.effect(GitHubCredentials, make);