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 Result from "effect/Result";
13import * as Schema from "effect/Schema";
14
15import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
16
17import * as ServerSettings from "../serverSettings.ts";
18import * as VcsProcess from "../vcs/VcsProcess.ts";
19
20/** How long a token is reused before `gh` is asked again, so a `gh auth switch` applies soon. */
21const TOKEN_TTL = Duration.minutes(5);
22/** No credential is retried sooner, so a fresh `gh auth login` takes effect on the next read. */
23const MISSING_TTL = Duration.seconds(10);
24
25export const GitHubCredentialSource = Schema.Literals(["settings", "env", "gh"]);
26export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
27
28export interface GitHubCredential {
29 readonly host: string;
30 readonly token: Redacted.Redacted<string>;
31 readonly source: GitHubCredentialSource;
32 /** A digest of host and token: safe for cache keys and rate-limit scopes, never the token. */
33 readonly fingerprint: string;
34}
35
36/** Nothing in the environment, and no `gh` on PATH to ask. */
37export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(
38 "GitHubCliMissingError",
39 { host: Schema.String },
40) {
41 override get message(): string {
42 return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
43 }
44}
45
46/** `gh` is installed but holds no login for the host, or not the account chosen in Settings. */
47export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
48 "GitHubNotSignedInError",
49 { host: Schema.String, account: Schema.optional(Schema.String) },
50) {
51 override get message(): string {
52 return this.account === undefined
53 ? `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`
54 : `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.`;
55 }
56}
57
58/** The user turned the host off in Settings. */
59export class GitHubHostDisabledError extends Schema.TaggedError<GitHubHostDisabledError>()(
60 "GitHubHostDisabledError",
61 { host: Schema.String },
62) {
63 override get message(): string {
64 return `GitHub host ${this.host} is turned off in Settings → Source Control.`;
65 }
66}
67
68/** `gh auth token` timed out or failed for a reason other than having no login. */
69export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedError>()(
70 "GitHubCliFailedError",
71 { host: Schema.String, cause: Schema.Defect() },
72) {
73 override get message(): string {
74 return `The GitHub CLI could not hand over a credential for ${this.host}. Check \`gh auth status\` on the server.`;
75 }
76}
77
78/** There is no token for the host. */
79export type GitHubCredentialUnavailableError =
80 | GitHubCliMissingError
81 | GitHubNotSignedInError
82 | GitHubHostDisabledError
83 | GitHubCliFailedError;
84
85export const isGitHubCredentialUnavailableError = Schema.is(
86 Schema.Union([GitHubCliMissingError, GitHubNotSignedInError, GitHubHostDisabledError]),
87);
88
89/**
90 * What a caller knows about the repository its work concerns. Nothing here changes where a token
91 * may come from: Settings and the environment still speak first, because both are choices the user
92 * made about the host itself.
93 */
94export interface GitHubCredentialRequest {
95 /**
96 * The owner of the repository the credential is for. `gh` is asked for that login before the
97 * Settings choice, which is how a repository owned by a second signed-in account stays readable
98 * while another account is active. An owner that is not a login — an organization — and one `gh`
99 * no longer holds both fall back to the Settings choice and then to `gh`'s active login, so
100 * naming an owner can only ever add a source, never remove one.
101 */
102 readonly account?: string | undefined;
103 /**
104 * Whether only that owner's own login may answer. Git asks for this: its credential helper already
105 * answers as the active account, so naming that account explicitly would replace whatever else the
106 * machine is configured with, and a repository owned by an organization is better left to the
107 * helper. The default also accepts the Settings choice and the active login, which is what an API
108 * request needs to authenticate at all.
109 */
110 readonly ownerOnly?: boolean;
111}
112
113/**
114 * Where GitHub tokens come from. Callers ask per host, and may name the owner of the repository they
115 * are about; they never see how the token was found, so another source (an in-app OAuth login)
116 * slots in here without touching any of them.
117 */
118export class GitHubCredentials extends Context.Service<
119 GitHubCredentials,
120 {
121 readonly get: (
122 host: string,
123 request?: GitHubCredentialRequest,
124 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
125 /** Drops the held token after GitHub refused it, so the next read asks its source again. */
126 readonly invalidate: (host: string, request?: GitHubCredentialRequest) => Effect.Effect<void>;
127 }
128>()("t3/sourceControl/GitHubCredentials") {}
129
130function normalizeHost(host: string): string {
131 return host.trim().toLowerCase();
132}
133
134/** Hosts gh treats as GitHub.com-like for `GH_TOKEN`: github.com and GHE.com data residency. */
135export function isGitHubDotCom(host: string): boolean {
136 return host === "github.com" || host.endsWith(".ghe.com");
137}
138
139/**
140 * The environment token for a host, in gh's precedence order. gh hands `GH_ENTERPRISE_TOKEN` to
141 * any non-github.com host; here it only goes to the host `GH_HOST` names, because a remote URL
142 * picks the host and a hostile one must not receive an enterprise token.
143 */
144export function environmentToken(
145 host: string,
146 env: Readonly<Record<string, string | undefined>>,
147): string | null {
148 const names = isGitHubDotCom(host)
149 ? ["GH_TOKEN", "GITHUB_TOKEN"]
150 : env.GH_HOST?.trim().toLowerCase() === host
151 ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
152 : [];
153 for (const name of names) {
154 const value = env[name]?.trim();
155 if (value) return value;
156 }
157 return null;
158}
159
160/** @public Service construction is part of the canonical Effect module API. */
161export const make = Effect.gen(function* () {
162 const process = yield* VcsProcess.VcsProcess;
163 const serverSettings = yield* ServerSettings.ServerSettingsService;
164 const crypto = yield* Crypto.Crypto;
165 const environment = yield* HostProcessEnvironment;
166 const workingDirectory = yield* HostProcessWorkingDirectory;
167
168 /** `host:sha256(token)`, safe for cache keys and rate-limit scopes. */
169 const fingerprintOf = (host: string, token: string) =>
170 crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(
171 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
172 // Hashing a string in memory has no platform failure worth a typed error.
173 Effect.orDie,
174 );
175
176 const fromGh = (host: string, account: string | undefined) =>
177 process
178 .run({
179 operation: "GitHubCredentials.get",
180 command: "gh",
181 args: [
182 "auth",
183 "token",
184 "--hostname",
185 host,
186 ...(account === undefined ? [] : ["--user", account]),
187 ],
188 cwd: workingDirectory,
189 // Never let gh print the token into a debug log.
190 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
191 timeoutMs: 10_000,
192 })
193 .pipe(
194 Effect.mapError((error) =>
195 error._tag === "VcsProcessSpawnError" &&
196 error.cause instanceof PlatformError.PlatformError &&
197 error.cause.reason._tag === "NotFound"
198 ? new GitHubCliMissingError({ host })
199 : // gh exits non-zero with "no oauth token" when it has no login for the host.
200 error._tag === "VcsProcessExitError"
201 ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
202 : new GitHubCliFailedError({ host, cause: error }),
203 ),
204 Effect.map((output) => output.stdout.trim()),
205 Effect.filterOrFail(
206 (token) => token !== "",
207 () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
208 ),
209 );
210
211 /** The Settings choice for a host; unreadable settings fall back to gh's own choice. */
212 const hostChoice = (host: string) =>
213 serverSettings.getSettings.pipe(
214 Effect.map((settings) => settings.github.hosts[host]),
215 Effect.orElseSucceed(() => undefined),
216 );
217
218 /** A token saved in Settings for the host, read fresh so a saved or removed one applies at once. */
219 const savedToken = (host: string) =>
220 serverSettings.getSettings.pipe(
221 Effect.map((settings) => settings.github.tokens[host]?.trim() || null),
222 Effect.orElseSucceed(() => null),
223 );
224
225 /**
226 * Cache key: the host, the login asked for and whether only that login may answer, so two logins of
227 * one host — and the same login asked for strictly and loosely — never share an entry.
228 */
229 const cacheKey = (host: string, account: string | undefined, ownerOnly: boolean) =>
230 `${host}\u0000${account ?? ""}\u0000${ownerOnly ? "owner" : "any"}`;
231
232 /** A blank account is no account: it may not reach the cache key or `gh --user`. */
233 const normalizeAccount = (account: string | undefined): string | undefined => {
234 const trimmed = account?.trim();
235 return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;
236 };
237
238 /**
239 * A token from the first login `gh` holds one for, in the order the caller ranked them. A login `gh`
240 * no longer holds is a reason to try the next one, not to fail: an owner is often an organization
241 * rather than a login. A trailing `undefined` asks for `gh`'s active login, and the caller that put
242 * it there is the one that decided a guess is better than no answer.
243 */
244 const tokenFor = (host: string, attempts: ReadonlyArray<string | undefined>) =>
245 Effect.gen(function* () {
246 const candidates = [
247 ...new Set(attempts.filter((account) => account === undefined || account.length > 0)),
248 ];
249 let refusal: GitHubCredentialUnavailableError | null = null;
250 for (const account of candidates) {
251 const attempt = yield* fromGh(host, account).pipe(Effect.result);
252 if (Result.isSuccess(attempt)) return attempt.success;
253 refusal ??= attempt.failure;
254 }
255 // Every login was refused, so the first refusal is reported: it names the account asked for.
256 return yield* Effect.fail(refusal!);
257 });
258
259 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
260 const [host = key, account, mode] = key.split("\u0000");
261 // An environment token wins over a login, exactly as it does in gh.
262 const fromEnv = environmentToken(host, environment);
263 // The owner the caller named comes first, then the login Settings pins. `gh`'s active login is
264 // the fallback for both, because an owner is often an organization rather than a login — unless
265 // the caller asked for the owner's own login, which is a caller that must not replace whatever
266 // authentication the machine already had.
267 const token =
268 fromEnv ??
269 (yield* tokenFor(
270 host,
271 mode === "owner" ? [account] : [account, (yield* hostChoice(host))?.account, undefined],
272 ));
273 return {
274 host,
275 token: Redacted.make(token),
276 source: fromEnv !== null ? "env" : "gh",
277 fingerprint: yield* fingerprintOf(host, token),
278 } satisfies GitHubCredential;
279 });
280
281 const cache = yield* Cache.makeWith(lookup, {
282 capacity: 32,
283 // A transient gh failure (a timeout, a locked keyring) is asked again on the next read.
284 timeToLive: (exit) =>
285 Exit.isSuccess(exit)
286 ? TOKEN_TTL
287 : Exit.findErrorOption(exit).pipe(
288 Option.exists((error) => error._tag === "GitHubCliFailedError"),
289 )
290 ? Duration.zero
291 : MISSING_TTL,
292 });
293
294 return GitHubCredentials.of({
295 get: Effect.fn("GitHubCredentials.get")(function* (rawHost, request) {
296 const host = normalizeHost(rawHost);
297 const choice = yield* hostChoice(host);
298 if (choice?.enabled === false) {
299 return yield* new GitHubHostDisabledError({ host });
300 }
301 // A token saved in Settings is the most deliberate choice, so it comes before the
302 // environment and gh. It is read from the secret store each time, so it needs no cache.
303 const saved = yield* savedToken(host);
304 if (saved !== null) {
305 return {
306 host,
307 token: Redacted.make(saved),
308 source: "settings",
309 fingerprint: yield* fingerprintOf(host, saved),
310 } satisfies GitHubCredential;
311 }
312 // The owner the caller named is more specific than the host's pin, so it is the cache key and
313 // `lookup` ranks the pin behind it.
314 return yield* Cache.get(
315 cache,
316 cacheKey(host, normalizeAccount(request?.account) ?? choice?.account, request?.ownerOnly === true),
317 );
318 }),
319 invalidate: (rawHost, request) =>
320 Effect.gen(function* () {
321 const host = normalizeHost(rawHost);
322 const choice = yield* hostChoice(host);
323 yield* Cache.invalidate(
324 cache,
325 cacheKey(
326 host,
327 normalizeAccount(request?.account) ?? choice?.account,
328 request?.ownerOnly === true,
329 ),
330 );
331 }),
332 });
333});
334
335export const layer = Layer.effect(GitHubCredentials, make);