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

GitHubCredentials.ts

189 lines6.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 VcsProcess from "../vcs/VcsProcess.ts";
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(["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;
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 }
43​
44/** `gh` is installed but holds no login for the host. */
45export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
46 "GitHubNotSignedInError",
47 { host: Schema.String },
48) {
49 override get message(): string {
50 return `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`;
51 }
53​
54/** `gh auth token` timed out or failed for a reason other than having no login. */
55export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedError>()(
56 "GitHubCliFailedError",
57 { host: Schema.String, cause: Schema.Defect() },
58) {
59 override get message(): string {
60 return `The GitHub CLI could not hand over a credential for ${this.host}. Check \`gh auth status\` on the server.`;
61 }
63​
64/** There is no token for the host. */
65export type GitHubCredentialUnavailableError =
66 | GitHubCliMissingError
67 | GitHubNotSignedInError
68 | GitHubCliFailedError;
69​
70/**
71 * Where GitHub tokens come from. Callers ask per host and never see how the token was found,
72 * so another source (an in-app OAuth login) slots in here without touching any of them.
73 */
74export class GitHubCredentials extends Context.Service<
75 GitHubCredentials,
76 {
77 readonly get: (
78 host: string,
79 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
80 /** Drops the held token after GitHub refused it, so the next read asks its source again. */
81 readonly invalidate: (host: string) => Effect.Effect<void>;
82 }
83>()("t3/sourceControl/GitHubCredentials") {}
84​
85function normalizeHost(host: string): string {
86 return host.trim().toLowerCase();
88​
89/** Hosts gh treats as GitHub.com-like for `GH_TOKEN`: github.com and GHE.com data residency. */
90function isGitHubDotCom(host: string): boolean {
91 return host === "github.com" || host.endsWith(".ghe.com");
93​
94/**
95 * The environment token for a host, in gh's precedence order. gh hands `GH_ENTERPRISE_TOKEN` to
96 * any non-github.com host; here it only goes to the host `GH_HOST` names, because a remote URL
97 * picks the host and a hostile one must not receive an enterprise token.
98 */
99export function environmentToken(
100 host: string,
101 env: Readonly<Record<string, string | undefined>>,
102): string | null {
103 const names = isGitHubDotCom(host)
104 ? ["GH_TOKEN", "GITHUB_TOKEN"]
105 : env.GH_HOST?.trim().toLowerCase() === host
106 ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
107 : [];
108 for (const name of names) {
109 const value = env[name]?.trim();
110 if (value) return value;
111 }
112 return null;
114​
115/** @public Service construction is part of the canonical Effect module API. */
116export const make = Effect.gen(function* () {
117 const process = yield* VcsProcess.VcsProcess;
118 const crypto = yield* Crypto.Crypto;
119 const environment = yield* HostProcessEnvironment;
120 const workingDirectory = yield* HostProcessWorkingDirectory;
121​
122 /** `host:sha256(token)`, safe for cache keys and rate-limit scopes. */
123 const fingerprintOf = (host: string, token: string) =>
124 crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(
125 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
126 // Hashing a string in memory has no platform failure worth a typed error.
127 Effect.orDie,
128 );
129​
130 const fromGh = (host: string) =>
131 process
132 .run({
133 operation: "GitHubCredentials.get",
134 command: "gh",
135 args: ["auth", "token", "--hostname", host],
136 cwd: workingDirectory,
137 // Never let gh print the token into a debug log.
138 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
139 timeoutMs: 10_000,
140 })
141 .pipe(
142 Effect.mapError((error) =>
143 error._tag === "VcsProcessSpawnError" &&
144 error.cause instanceof PlatformError.PlatformError &&
145 error.cause.reason._tag === "NotFound"
146 ? new GitHubCliMissingError({ host })
147 : // gh exits non-zero with "no oauth token" when it has no login for the host.
148 error._tag === "VcsProcessExitError"
149 ? new GitHubNotSignedInError({ host })
150 : new GitHubCliFailedError({ host, cause: error }),
151 ),
152 Effect.map((output) => output.stdout.trim()),
153 Effect.filterOrFail(
154 (token) => token !== "",
155 () => new GitHubNotSignedInError({ host }),
156 ),
157 );
158​
159 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (host: string) {
160 const fromEnv = environmentToken(host, environment);
161 const token = fromEnv ?? (yield* fromGh(host));
162 return {
163 host,
164 token: Redacted.make(token),
165 source: fromEnv !== null ? "env" : "gh",
166 fingerprint: yield* fingerprintOf(host, token),
167 } satisfies GitHubCredential;
168 });
169​
170 const cache = yield* Cache.makeWith(lookup, {
171 capacity: 32,
172 // A transient gh failure (a timeout, a locked keyring) is asked again on the next read.
173 timeToLive: (exit) =>
174 Exit.isSuccess(exit)
175 ? TOKEN_TTL
176 : Exit.findErrorOption(exit).pipe(
177 Option.exists((error) => error._tag === "GitHubCliFailedError"),
178 )
179 ? Duration.zero
180 : MISSING_TTL,
181 });
182​
183 return GitHubCredentials.of({
184 get: (host) => Cache.get(cache, normalizeHost(host)),
185 invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),
186 });
187});
188​
189export const layer = Layer.effect(GitHubCredentials, make);