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 { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
15
16import * as ServerSettings from "../serverSettings.ts";
17import * as VcsProcess from "../vcs/VcsProcess.ts";
18
19/** How long a token is reused before `gh` is asked again, so a `gh auth switch` applies soon. */
20const TOKEN_TTL = Duration.minutes(5);
21/** No credential is retried sooner, so a fresh `gh auth login` takes effect on the next read. */
22const MISSING_TTL = Duration.seconds(10);
23
24export const GitHubCredentialSource = Schema.Literals(["settings", "env", "gh"]);
25export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
26
27export interface GitHubCredential {
28 readonly host: string;
29 readonly token: Redacted.Redacted<string>;
30 readonly source: GitHubCredentialSource;
31 /** A digest of host and token: safe for cache keys and rate-limit scopes, never the token. */
32 readonly fingerprint: string;
33}
34
35/** Nothing in the environment, and no `gh` on PATH to ask. */
36export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(
37 "GitHubCliMissingError",
38 { host: Schema.String },
39) {
40 override get message(): string {
41 return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
42 }
43}
44
45/** `gh` is installed but holds no login for the host, or not the account chosen in Settings. */
46export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
47 "GitHubNotSignedInError",
48 { host: Schema.String, account: Schema.optional(Schema.String) },
49) {
50 override get message(): string {
51 return this.account === undefined
52 ? `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`
53 : `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.`;
54 }
55}
56
57/** The user turned the host off in Settings. */
58export class GitHubHostDisabledError extends Schema.TaggedError<GitHubHostDisabledError>()(
59 "GitHubHostDisabledError",
60 { host: Schema.String },
61) {
62 override get message(): string {
63 return `GitHub host ${this.host} is turned off in Settings → Source Control.`;
64 }
65}
66
67/** `gh auth token` timed out or failed for a reason other than having no login. */
68export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedError>()(
69 "GitHubCliFailedError",
70 { host: Schema.String, cause: Schema.Defect() },
71) {
72 override get message(): string {
73 return `The GitHub CLI could not hand over a credential for ${this.host}. Check \`gh auth status\` on the server.`;
74 }
75}
76
77/** There is no token for the host. */
78export type GitHubCredentialUnavailableError =
79 | GitHubCliMissingError
80 | GitHubNotSignedInError
81 | GitHubHostDisabledError
82 | GitHubCliFailedError;
83
84/**
85 * Where GitHub tokens come from. Callers ask per host and never see how the token was found,
86 * so another source (an in-app OAuth login) slots in here without touching any of them.
87 */
88export class GitHubCredentials extends Context.Service<
89 GitHubCredentials,
90 {
91 readonly get: (
92 host: string,
93 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
94 /** Drops the held token after GitHub refused it, so the next read asks its source again. */
95 readonly invalidate: (host: string) => Effect.Effect<void>;
96 }
97>()("t3/sourceControl/GitHubCredentials") {}
98
99function normalizeHost(host: string): string {
100 return host.trim().toLowerCase();
101}
102
103/** Hosts gh treats as GitHub.com-like for `GH_TOKEN`: github.com and GHE.com data residency. */
104function isGitHubDotCom(host: string): boolean {
105 return host === "github.com" || host.endsWith(".ghe.com");
106}
107
108/**
109 * The environment token for a host, in gh's precedence order. gh hands `GH_ENTERPRISE_TOKEN` to
110 * any non-github.com host; here it only goes to the host `GH_HOST` names, because a remote URL
111 * picks the host and a hostile one must not receive an enterprise token.
112 */
113export function environmentToken(
114 host: string,
115 env: Readonly<Record<string, string | undefined>>,
116): string | 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;
127}
128
129/** @public Service construction is part of the canonical Effect module API. */
130export const make = Effect.gen(function* () {
131 const process = yield* VcsProcess.VcsProcess;
132 const serverSettings = yield* ServerSettings.ServerSettingsService;
133 const crypto = yield* Crypto.Crypto;
134 const environment = yield* HostProcessEnvironment;
135 const workingDirectory = yield* HostProcessWorkingDirectory;
136
137 /** `host:sha256(token)`, safe for cache keys and rate-limit scopes. */
138 const fingerprintOf = (host: string, token: string) =>
139 crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(
140 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
141 // Hashing a string in memory has no platform failure worth a typed error.
142 Effect.orDie,
143 );
144
145 const fromGh = (host: string, account: string | undefined) =>
146 process
147 .run({
148 operation: "GitHubCredentials.get",
149 command: "gh",
150 args: [
151 "auth",
152 "token",
153 "--hostname",
154 host,
155 ...(account === undefined ? [] : ["--user", account]),
156 ],
157 cwd: workingDirectory,
158 // Never let gh print the token into a debug log.
159 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
160 timeoutMs: 10_000,
161 })
162 .pipe(
163 Effect.mapError((error) =>
164 error._tag === "VcsProcessSpawnError" &&
165 error.cause instanceof PlatformError.PlatformError &&
166 error.cause.reason._tag === "NotFound"
167 ? new GitHubCliMissingError({ host })
168 : // gh exits non-zero with "no oauth token" when it has no login for the host.
169 error._tag === "VcsProcessExitError"
170 ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
171 : new GitHubCliFailedError({ host, cause: error }),
172 ),
173 Effect.map((output) => output.stdout.trim()),
174 Effect.filterOrFail(
175 (token) => token !== "",
176 () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
177 ),
178 );
179
180 /** The Settings choice for a host; unreadable settings fall back to gh's own choice. */
181 const hostChoice = (host: string) =>
182 serverSettings.getSettings.pipe(
183 Effect.map((settings) => settings.github.hosts[host]),
184 Effect.orElseSucceed(() => undefined),
185 );
186
187 /** A token saved in Settings for the host, read fresh so a saved or removed one applies at once. */
188 const savedToken = (host: string) =>
189 serverSettings.getSettings.pipe(
190 Effect.map((settings) => settings.github.tokens[host]?.trim() || null),
191 Effect.orElseSucceed(() => null),
192 );
193
194 /** Cache key: the host plus its pinned account, so a changed pin misses the cache. */
195 const cacheKey = (host: string, account: string | undefined) =>
196 account === undefined ? host : `${host}\u0000${account}`;
197
198 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
199 const [host = key, choice] = key.split("\u0000");
200 // An environment token wins over a pinned account, exactly as it does in gh.
201 const fromEnv = environmentToken(host, environment);
202 // A pinned login gh no longer holds (logged out, expired) falls back to the active one,
203 // which is what discovery reports as the account in use.
204 const token =
205 fromEnv ??
206 (yield* fromGh(host, choice).pipe(
207 Effect.catchTags({
208 GitHubNotSignedInError: (error) =>
209 choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
210 }),
211 ));
212 return {
213 host,
214 token: Redacted.make(token),
215 source: fromEnv !== null ? "env" : "gh",
216 fingerprint: yield* fingerprintOf(host, token),
217 } satisfies GitHubCredential;
218 });
219
220 const cache = yield* Cache.makeWith(lookup, {
221 capacity: 32,
222 // A transient gh failure (a timeout, a locked keyring) is asked again on the next read.
223 timeToLive: (exit) =>
224 Exit.isSuccess(exit)
225 ? TOKEN_TTL
226 : Exit.findErrorOption(exit).pipe(
227 Option.exists((error) => error._tag === "GitHubCliFailedError"),
228 )
229 ? Duration.zero
230 : MISSING_TTL,
231 });
232
233 return GitHubCredentials.of({
234 get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
235 const host = normalizeHost(rawHost);
236 const choice = yield* hostChoice(host);
237 if (choice?.enabled === false) {
238 return yield* new GitHubHostDisabledError({ host });
239 }
240 // A token saved in Settings is the most deliberate choice, so it comes before the
241 // environment and gh. It is read from the secret store each time, so it needs no cache.
242 const saved = yield* savedToken(host);
243 if (saved !== null) {
244 return {
245 host,
246 token: Redacted.make(saved),
247 source: "settings",
248 fingerprint: yield* fingerprintOf(host, saved),
249 } satisfies GitHubCredential;
250 }
251 return yield* Cache.get(cache, cacheKey(host, choice?.account));
252 }),
253 invalidate: (rawHost) => {
254 const host = normalizeHost(rawHost);
255 return hostChoice(host).pipe(
256 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
257 );
258 },
259 });
260});
261
262export const layer = Layer.effect(GitHubCredentials, make);