Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubCredentials.ts

266 lines10.2 KB

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;
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 }
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 }
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 }
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 }
76​
77/** There is no token for the host. */
78export type GitHubCredentialUnavailableError =
79 | GitHubCliMissingError
80 | GitHubNotSignedInError
81 | GitHubHostDisabledError
82 | GitHubCliFailedError;
83​
84export const isGitHubCredentialUnavailableError = Schema.is(
85 Schema.Union([GitHubCliMissingError, GitHubNotSignedInError, GitHubHostDisabledError]),
86);
87​
88/**
89 * Where GitHub tokens come from. Callers ask per host and never see how the token was found,
90 * so another source (an in-app OAuth login) slots in here without touching any of them.
91 */
92export class GitHubCredentials extends Context.Service<
93 GitHubCredentials,
94 {
95 readonly get: (
96 host: string,
97 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
98 /** Drops the held token after GitHub refused it, so the next read asks its source again. */
99 readonly invalidate: (host: string) => Effect.Effect<void>;
100 }
101>()("t3/sourceControl/GitHubCredentials") {}
102​
103function normalizeHost(host: string): string {
104 return host.trim().toLowerCase();
106​
107/** Hosts gh treats as GitHub.com-like for `GH_TOKEN`: github.com and GHE.com data residency. */
108function isGitHubDotCom(host: string): boolean {
109 return host === "github.com" || host.endsWith(".ghe.com");
111​
112/**
113 * The environment token for a host, in gh's precedence order. gh hands `GH_ENTERPRISE_TOKEN` to
114 * any non-github.com host; here it only goes to the host `GH_HOST` names, because a remote URL
115 * picks the host and a hostile one must not receive an enterprise token.
116 */
117export function environmentToken(
118 host: string,
119 env: Readonly<Record<string, string | undefined>>,
120): string | null {
121 const names = isGitHubDotCom(host)
122 ? ["GH_TOKEN", "GITHUB_TOKEN"]
123 : env.GH_HOST?.trim().toLowerCase() === host
124 ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
125 : [];
126 for (const name of names) {
127 const value = env[name]?.trim();
128 if (value) return value;
129 }
130 return null;
132​
133/** @public Service construction is part of the canonical Effect module API. */
134export const make = Effect.gen(function* () {
135 const process = yield* VcsProcess.VcsProcess;
136 const serverSettings = yield* ServerSettings.ServerSettingsService;
137 const crypto = yield* Crypto.Crypto;
138 const environment = yield* HostProcessEnvironment;
139 const workingDirectory = yield* HostProcessWorkingDirectory;
140​
141 /** `host:sha256(token)`, safe for cache keys and rate-limit scopes. */
142 const fingerprintOf = (host: string, token: string) =>
143 crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(
144 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
145 // Hashing a string in memory has no platform failure worth a typed error.
146 Effect.orDie,
147 );
148​
149 const fromGh = (host: string, account: string | undefined) =>
150 process
151 .run({
152 operation: "GitHubCredentials.get",
153 command: "gh",
154 args: [
155 "auth",
156 "token",
157 "--hostname",
158 host,
159 ...(account === undefined ? [] : ["--user", account]),
160 ],
161 cwd: workingDirectory,
162 // Never let gh print the token into a debug log.
163 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
164 timeoutMs: 10_000,
165 })
166 .pipe(
167 Effect.mapError((error) =>
168 error._tag === "VcsProcessSpawnError" &&
169 error.cause instanceof PlatformError.PlatformError &&
170 error.cause.reason._tag === "NotFound"
171 ? new GitHubCliMissingError({ host })
172 : // gh exits non-zero with "no oauth token" when it has no login for the host.
173 error._tag === "VcsProcessExitError"
174 ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
175 : new GitHubCliFailedError({ host, cause: error }),
176 ),
177 Effect.map((output) => output.stdout.trim()),
178 Effect.filterOrFail(
179 (token) => token !== "",
180 () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
181 ),
182 );
183​
184 /** The Settings choice for a host; unreadable settings fall back to gh's own choice. */
185 const hostChoice = (host: string) =>
186 serverSettings.getSettings.pipe(
187 Effect.map((settings) => settings.github.hosts[host]),
188 Effect.orElseSucceed(() => undefined),
189 );
190​
191 /** A token saved in Settings for the host, read fresh so a saved or removed one applies at once. */
192 const savedToken = (host: string) =>
193 serverSettings.getSettings.pipe(
194 Effect.map((settings) => settings.github.tokens[host]?.trim() || null),
195 Effect.orElseSucceed(() => null),
196 );
197​
198 /** Cache key: the host plus its pinned account, so a changed pin misses the cache. */
199 const cacheKey = (host: string, account: string | undefined) =>
200 account === undefined ? host : `${host}\u0000${account}`;
201​
202 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
203 const [host = key, choice] = key.split("\u0000");
204 // An environment token wins over a pinned account, exactly as it does in gh.
205 const fromEnv = environmentToken(host, environment);
206 // A pinned login gh no longer holds (logged out, expired) falls back to the active one,
207 // which is what discovery reports as the account in use.
208 const token =
209 fromEnv ??
210 (yield* fromGh(host, choice).pipe(
211 Effect.catchTags({
212 GitHubNotSignedInError: (error) =>
213 choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
214 }),
215 ));
216 return {
217 host,
218 token: Redacted.make(token),
219 source: fromEnv !== null ? "env" : "gh",
220 fingerprint: yield* fingerprintOf(host, token),
221 } satisfies GitHubCredential;
222 });
223​
224 const cache = yield* Cache.makeWith(lookup, {
225 capacity: 32,
226 // A transient gh failure (a timeout, a locked keyring) is asked again on the next read.
227 timeToLive: (exit) =>
228 Exit.isSuccess(exit)
229 ? TOKEN_TTL
230 : Exit.findErrorOption(exit).pipe(
231 Option.exists((error) => error._tag === "GitHubCliFailedError"),
232 )
233 ? Duration.zero
234 : MISSING_TTL,
235 });
236​
237 return GitHubCredentials.of({
238 get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
239 const host = normalizeHost(rawHost);
240 const choice = yield* hostChoice(host);
241 if (choice?.enabled === false) {
242 return yield* new GitHubHostDisabledError({ host });
243 }
244 // A token saved in Settings is the most deliberate choice, so it comes before the
245 // environment and gh. It is read from the secret store each time, so it needs no cache.
246 const saved = yield* savedToken(host);
247 if (saved !== null) {
248 return {
249 host,
250 token: Redacted.make(saved),
251 source: "settings",
252 fingerprint: yield* fingerprintOf(host, saved),
253 } satisfies GitHubCredential;
254 }
255 return yield* Cache.get(cache, cacheKey(host, choice?.account));
256 }),
257 invalidate: (rawHost) => {
258 const host = normalizeHost(rawHost);
259 return hostChoice(host).pipe(
260 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
261 );
262 },
263 });
264});
265​
266export const layer = Layer.effect(GitHubCredentials, make);