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