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

GitHubCredentials.ts

295 lines10.8 KB

1import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
2import * as Cache from "effect/Cache";
3import * as Context from "effect/Context";
4import * as Digest from "effect/crypto/Digest";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Hex from "effect/encoding/Hex";
8import * as Exit from "effect/Exit";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as PlatformError from "effect/PlatformError";
12import * as Redacted from "effect/Redacted";
13import * as Schema from "effect/Schema";
14​
15import * as HostProcess from "@t3tools/shared/HostProcess";
16​
17import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18import { isMissingExecutable } from "@t3tools/source-control-core/server/discovery";
19import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
20import {
21 requireSettingsSecretLiteral,
22 type ServerSettings,
23 type SettingsSecretUnresolvedError,
24} from "@t3tools/contracts";
25​
26import * as GitHubClient from "../shared/definition.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 */
32export const GH_PROCESS_CONCURRENCY = { key: "gh", limit: 4 } as const;
33​
34const TOKEN_TTL = Duration.minutes(5);
35const MISSING_TTL = Duration.seconds(10);
36​
37export const GitHubCredentialSource = Schema.Literals(["settings", "app", "env", "gh"]);
38export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
39​
40export interface GitHubCredential {
41 readonly host: string;
42 readonly token: Redacted.Redacted<string>;
43 readonly source: GitHubCredentialSource;
44 readonly fingerprint: string;
46​
47export 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 }
55​
56export 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.`;
64 }
66​
67export 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.`;
73 }
75​
76export 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 }
84​
85export type GitHubCredentialUnavailableError =
86 | GitHubCliMissingError
87 | GitHubNotSignedInError
88 | GitHubHostDisabledError
89 | GitHubCliFailedError
90 | SettingsSecretUnresolvedError;
91​
92/** Directory-aware `gh` shims choose their login from the checkout's `cwd`. */
93export class GitHubCredentials extends Context.Service<
94 GitHubCredentials,
95 {
96 readonly get: (
97 host: string,
98 cwd?: string,
99 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
100 /** The token saved in Settings for `host`, which outranks every other source. */
101 readonly saved: (
102 host: string,
103 ) => Effect.Effect<
104 Option.Option<GitHubCredential>,
105 GitHubHostDisabledError | GitHubNotSignedInError | SettingsSecretUnresolvedError
106 >;
107 readonly fingerprint: (host: string, token: string) => Effect.Effect<string>;
108 readonly invalidate: (host: string, cwd?: string) => Effect.Effect<void>;
109 }
110>()("@t3tools/source-control-github/server/GitHubCredentials") {}
111​
112const HOSTNAME =
113 /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\d{1,5})?$/;
114​
115/** API URLs are built from the host text, so anything but a bare hostname could redirect a token. */
116export function isGitHubHost(host: string): boolean {
117 return HOSTNAME.test(host);
119​
120function isGitHubDotCom(host: string): boolean {
121 return host === "github.com" || host.endsWith(".ghe.com");
123​
124/** Restrict GH_ENTERPRISE_TOKEN to GH_HOST to prevent remote URLs from leaking it. */
125export function environmentToken(
126 host: string,
127 env: Readonly<Record<string, string | undefined>>,
128): string | null {
129 if (!isGitHubHost(host)) return null;
130 const names = isGitHubDotCom(host)
131 ? ["GH_TOKEN", "GITHUB_TOKEN"]
132 : env.GH_HOST?.trim().toLowerCase() === host
133 ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
134 : [];
135 for (const name of names) {
136 const value = env[name]?.trim();
137 if (value) return value;
138 }
139 return null;
141​
142/** @public */
143export const make = Effect.gen(function* () {
144 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
145 const process = sourceControlHost.process;
146 const crypto = yield* Digest.Digest;
147 const environment = yield* HostProcess.Environment;
148 const workingDirectory = yield* HostProcess.WorkingDirectory;
149​
150 const fingerprintOf = (host: string, token: string) =>
151 crypto.digest(Digest.sha256, new TextEncoder().encode(token)).pipe(
152 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
153 Effect.orDie,
154 );
155​
156 const runGh = (host: string, account: string | undefined, cwd: string) =>
157 process.run({
158 operation: "GitHubCredentials.get",
159 command: "gh",
160 args: [
161 "auth",
162 "token",
163 "--hostname",
164 host,
165 ...(account === undefined ? [] : ["--user", account]),
166 ],
167 cwd,
168 // Never let gh print the token into a debug log.
169 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
170 timeoutMs: 10_000,
171 concurrency: GH_PROCESS_CONCURRENCY,
172 });
173​
174 const fromGh = (host: string, account: string | undefined, cwd: string) =>
175 runGh(host, account, cwd).pipe(
176 // A checkout folder that is gone fails the spawner's cwd check; ask gh from the server.
177 Effect.catchIf(
178 (error) =>
179 cwd !== workingDirectory &&
180 error._tag === "VcsProcessSpawnError" &&
181 PlatformError.isPlatformError(error.cause) &&
182 error.cause.reason._tag === "NotFound" &&
183 !isMissingExecutable(error),
184 () => runGh(host, account, workingDirectory),
185 ),
186 Effect.mapError((error) =>
187 isMissingExecutable(error)
188 ? new GitHubCliMissingError({ host })
189 : // gh exits non-zero with "no oauth token" when it has no login for the host.
190 error._tag === "VcsProcessExitError"
191 ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
192 : new GitHubCliFailedError({ host, cause: error }),
193 ),
194 Effect.map((output) => output.stdout.trim()),
195 Effect.filterOrFail(
196 (token) => token !== "",
197 () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
198 ),
199 );
200​
201 const readSettings = (settings: ServerSettings) =>
202 readSourceControlHostSettings(
203 GitHubClient.settings,
204 settings.sourceControlHosts[GitHubClient.definition.kind],
205 );
206​
207 const hostChoice = (host: string) =>
208 sourceControlHost.settings.get.pipe(
209 Effect.map((settings) => readSettings(settings).hosts[host]),
210 Effect.orElseSucceed(() => undefined),
211 );
212​
213 const savedToken = (host: string) =>
214 sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe(
215 Effect.map((settings) => ({
216 token: readSettings(settings).tokens[host],
217 secretProviders: settings.secretProviders,
218 })),
219 Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),
220 Effect.flatMap(({ token, secretProviders }) =>
221 requireSettingsSecretLiteral(token, secretProviders),
222 ),
223 Effect.map((token) => token.trim() || null),
224 );
225​
226 const cacheKey = (host: string, account: string | undefined, cwd: string | undefined) =>
227 [host, account ?? "", cwd ?? workingDirectory].join("\u0000");
228​
229 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
230 const [host = key, account = "", cwd = workingDirectory] = key.split("\u0000");
231 const choice = account === "" ? undefined : account;
232 const fromEnv = environmentToken(host, environment);
233 const token =
234 fromEnv ??
235 (yield* fromGh(host, choice, cwd).pipe(
236 Effect.catchTags({
237 GitHubNotSignedInError: (error) =>
238 choice === undefined ? Effect.fail(error) : fromGh(host, undefined, cwd),
239 }),
240 ));
241 return {
242 host,
243 token: Redacted.make(token),
244 source: fromEnv !== null ? "env" : "gh",
245 fingerprint: yield* fingerprintOf(host, token),
246 } satisfies GitHubCredential;
247 });
248​
249 const cache = yield* Cache.makeWith(lookup, {
250 capacity: 512,
251 timeToLive: (exit) =>
252 Exit.isSuccess(exit)
253 ? TOKEN_TTL
254 : Exit.findErrorOption(exit).pipe(
255 Option.exists((error) => error._tag === "GitHubCliFailedError"),
256 )
257 ? Duration.zero
258 : MISSING_TTL,
259 });
260​
261 const saved = Effect.fn("GitHubCredentials.saved")(function* (rawHost: string) {
262 const host = normalizeHost(rawHost);
263 if (!isGitHubHost(host)) return yield* new GitHubNotSignedInError({ host });
264 if ((yield* hostChoice(host))?.enabled === false) {
265 return yield* new GitHubHostDisabledError({ host });
266 }
267 const token = yield* savedToken(host);
268 if (token === null) return Option.none<GitHubCredential>();
269 return Option.some<GitHubCredential>({
270 host,
271 token: Redacted.make(token),
272 source: "settings",
273 fingerprint: yield* fingerprintOf(host, token),
274 });
275 });
276​
277 return GitHubCredentials.of({
278 get: Effect.fn("GitHubCredentials.get")(function* (rawHost, cwd) {
279 const host = normalizeHost(rawHost);
280 const fromSettings = yield* saved(host);
281 if (Option.isSome(fromSettings)) return fromSettings.value;
282 return yield* Cache.get(cache, cacheKey(host, (yield* hostChoice(host))?.account, cwd));
283 }),
284 saved,
285 fingerprint: fingerprintOf,
286 invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost, cwd) {
287 const host = normalizeHost(rawHost);
288 return hostChoice(host).pipe(
289 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account, cwd))),
290 );
291 }),
292 });
293});
294​
295export const layer = Layer.effect(GitHubCredentials, make);