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

GitHubCredentials.ts

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