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