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

GitHubCredentials.ts

270 lines9.7 KB

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