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

GitHubCredentials.ts

259 lines9.1 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​
99const HOSTNAME =
100 /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\d{1,5})?$/;
101​
102/** API URLs are built from the host text, so anything but a bare hostname could redirect a token. */
103export function isGitHubHost(host: string): boolean {
104 return HOSTNAME.test(host);
106​
107function isGitHubDotCom(host: string): boolean {
108 return host === "github.com" || host.endsWith(".ghe.com");
110​
111/** Restrict GH_ENTERPRISE_TOKEN to GH_HOST to prevent remote URLs from leaking it. */
112export function environmentToken(
113 host: string,
114 env: Readonly<Record<string, string | undefined>>,
115): string | null {
116 if (!isGitHubHost(host)) return null;
117 const names = isGitHubDotCom(host)
118 ? ["GH_TOKEN", "GITHUB_TOKEN"]
119 : env.GH_HOST?.trim().toLowerCase() === host
120 ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
121 : [];
122 for (const name of names) {
123 const value = env[name]?.trim();
124 if (value) return value;
125 }
126 return null;
128​
129/** @public */
130export const make = Effect.gen(function* () {
131 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
132 const process = sourceControlHost.process;
133 const crypto = yield* Crypto.Crypto;
134 const environment = yield* HostProcess.Environment;
135 const workingDirectory = yield* HostProcess.WorkingDirectory;
136​
137 const fingerprintOf = (host: string, token: string) =>
138 crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(
139 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
140 Effect.orDie,
141 );
142​
143 const fromGh = (host: string, account: string | undefined) =>
144 process
145 .run({
146 operation: "GitHubCredentials.get",
147 command: "gh",
148 args: [
149 "auth",
150 "token",
151 "--hostname",
152 host,
153 ...(account === undefined ? [] : ["--user", account]),
154 ],
155 cwd: workingDirectory,
156 // Never let gh print the token into a debug log.
157 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
158 timeoutMs: 10_000,
159 concurrency: GH_PROCESS_CONCURRENCY,
160 })
161 .pipe(
162 Effect.mapError((error) =>
163 error._tag === "VcsProcessSpawnError" &&
164 error.cause instanceof PlatformError.PlatformError &&
165 error.cause.reason._tag === "NotFound"
166 ? new GitHubCliMissingError({ host })
167 : // gh exits non-zero with "no oauth token" when it has no login for the host.
168 error._tag === "VcsProcessExitError"
169 ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
170 : new GitHubCliFailedError({ host, cause: error }),
171 ),
172 Effect.map((output) => output.stdout.trim()),
173 Effect.filterOrFail(
174 (token) => token !== "",
175 () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
176 ),
177 );
178​
179 const readSettings = (settings: ServerSettings) =>
180 readSourceControlHostSettings(
181 GitHubClient.settings,
182 settings.sourceControlHosts[GitHubClient.definition.kind],
183 );
184​
185 const hostChoice = (host: string) =>
186 sourceControlHost.settings.get.pipe(
187 Effect.map((settings) => readSettings(settings).hosts[host]),
188 Effect.orElseSucceed(() => undefined),
189 );
190​
191 const savedToken = (host: string) =>
192 sourceControlHost.settings.get.pipe(
193 Effect.map((settings) => readSettings(settings).tokens[host]?.trim() || null),
194 Effect.orElseSucceed(() => null),
195 );
196​
197 const cacheKey = (host: string, account: string | undefined) =>
198 account === undefined ? host : `${host}\u0000${account}`;
199​
200 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
201 const [host = key, choice] = key.split("\u0000");
202 const fromEnv = environmentToken(host, environment);
203 const token =
204 fromEnv ??
205 (yield* fromGh(host, choice).pipe(
206 Effect.catchTags({
207 GitHubNotSignedInError: (error) =>
208 choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
209 }),
210 ));
211 return {
212 host,
213 token: Redacted.make(token),
214 source: fromEnv !== null ? "env" : "gh",
215 fingerprint: yield* fingerprintOf(host, token),
216 } satisfies GitHubCredential;
217 });
218​
219 const cache = yield* Cache.makeWith(lookup, {
220 capacity: 32,
221 timeToLive: (exit) =>
222 Exit.isSuccess(exit)
223 ? TOKEN_TTL
224 : Exit.findErrorOption(exit).pipe(
225 Option.exists((error) => error._tag === "GitHubCliFailedError"),
226 )
227 ? Duration.zero
228 : MISSING_TTL,
229 });
230​
231 return GitHubCredentials.of({
232 get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
233 const host = normalizeHost(rawHost);
234 if (!isGitHubHost(host)) return yield* new GitHubNotSignedInError({ host });
235 const choice = yield* hostChoice(host);
236 if (choice?.enabled === false) {
237 return yield* new GitHubHostDisabledError({ host });
238 }
239 const saved = yield* savedToken(host);
240 if (saved !== null) {
241 return {
242 host,
243 token: Redacted.make(saved),
244 source: "settings",
245 fingerprint: yield* fingerprintOf(host, saved),
246 } satisfies GitHubCredential;
247 }
248 return yield* Cache.get(cache, cacheKey(host, choice?.account));
249 }),
250 invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost) {
251 const host = normalizeHost(rawHost);
252 return hostChoice(host).pipe(
253 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
254 );
255 }),
256 });
257});
258​
259export const layer = Layer.effect(GitHubCredentials, make);