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

GitHubCredentials.ts

249 lines8.6 KB

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