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

GitHubCredentials.ts

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