Open History to see the last commit
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 { settingsSecretLiteral, 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;
40}
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 }
49}
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 }
60}
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 }
69}
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 }
78}
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);
110}
111
112function isGitHubDotCom(host: string): boolean {
113 return host === "github.com" || host.endsWith(".ghe.com");
114}
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;
132}
133
134/** @public */
135export const make = Effect.gen(function* () {
136 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
137 const process = sourceControlHost.process;
138 const crypto = yield* Digest.Digest;
139 const environment = yield* HostProcess.Environment;
140 const workingDirectory = yield* HostProcess.WorkingDirectory;
141
142 const fingerprintOf = (host: string, token: string) =>
143 crypto.digest(Digest.sha256, 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.getWithSecrets(GitHubClient.definition.kind).pipe(
198 Effect.map(
199 (settings) => settingsSecretLiteral(readSettings(settings).tokens[host]).trim() || null,
200 ),
201 Effect.orElseSucceed(() => null),
202 );
203
204 const cacheKey = (host: string, account: string | undefined) =>
205 account === undefined ? host : `${host}\u0000${account}`;
206
207 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
208 const [host = key, choice] = key.split("\u0000");
209 const fromEnv = environmentToken(host, environment);
210 const token =
211 fromEnv ??
212 (yield* fromGh(host, choice).pipe(
213 Effect.catchTags({
214 GitHubNotSignedInError: (error) =>
215 choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
216 }),
217 ));
218 return {
219 host,
220 token: Redacted.make(token),
221 source: fromEnv !== null ? "env" : "gh",
222 fingerprint: yield* fingerprintOf(host, token),
223 } satisfies GitHubCredential;
224 });
225
226 const cache = yield* Cache.makeWith(lookup, {
227 capacity: 32,
228 timeToLive: (exit) =>
229 Exit.isSuccess(exit)
230 ? TOKEN_TTL
231 : Exit.findErrorOption(exit).pipe(
232 Option.exists((error) => error._tag === "GitHubCliFailedError"),
233 )
234 ? Duration.zero
235 : MISSING_TTL,
236 });
237
238 const saved = Effect.fn("GitHubCredentials.saved")(function* (rawHost: string) {
239 const host = normalizeHost(rawHost);
240 if (!isGitHubHost(host)) return yield* new GitHubNotSignedInError({ host });
241 if ((yield* hostChoice(host))?.enabled === false) {
242 return yield* new GitHubHostDisabledError({ host });
243 }
244 const token = yield* savedToken(host);
245 if (token === null) return Option.none<GitHubCredential>();
246 return Option.some<GitHubCredential>({
247 host,
248 token: Redacted.make(token),
249 source: "settings",
250 fingerprint: yield* fingerprintOf(host, token),
251 });
252 });
253
254 return GitHubCredentials.of({
255 get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
256 const host = normalizeHost(rawHost);
257 const fromSettings = yield* saved(host);
258 if (Option.isSome(fromSettings)) return fromSettings.value;
259 return yield* Cache.get(cache, cacheKey(host, (yield* hostChoice(host))?.account));
260 }),
261 saved,
262 fingerprint: fingerprintOf,
263 invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost) {
264 const host = normalizeHost(rawHost);
265 return hostChoice(host).pipe(
266 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
267 );
268 }),
269 });
270});
271
272export const layer = Layer.effect(GitHubCredentials, make);