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

GitHubCredentials.ts

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