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