import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Digest from "effect/crypto/Digest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
import {
requireSettingsSecretLiteral,
type ServerSettings,
type SettingsSecretUnresolvedError,
} from "@t3tools/contracts";
import * as GitHubClient from "../shared/definition.ts";
/**
* Every gh run on the server shares this. A burst of them (a status poll across many checkouts)
* otherwise starts enough at once to trip GitHub's secondary rate limit.
*/
export const GH_PROCESS_CONCURRENCY = { key: "gh", limit: 4 } as const;
const TOKEN_TTL = Duration.minutes(5);
const MISSING_TTL = Duration.seconds(10);
export const GitHubCredentialSource = Schema.Literals(["settings", "app", "env", "gh"]);
export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
export interface GitHubCredential {
readonly host: string;
readonly token: Redacted.Redacted<string>;
readonly source: GitHubCredentialSource;
readonly fingerprint: string;
}
export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(
"GitHubCliMissingError",
{ host: Schema.String },
) {
override get message(): string {
return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
}
}
export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
"GitHubNotSignedInError",
{ host: Schema.String, account: Schema.optional(Schema.String) },
) {
override get message(): string {
return this.account === undefined
? `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`
: `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.`;
}
}
export class GitHubHostDisabledError extends Schema.TaggedError<GitHubHostDisabledError>()(
"GitHubHostDisabledError",
{ host: Schema.String },
) {
override get message(): string {
return `GitHub host ${this.host} is turned off in Settings → Source Control.`;
}
}
export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedError>()(
"GitHubCliFailedError",
{ host: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `The GitHub CLI could not hand over a credential for ${this.host}. Check \`gh auth status\` on the server.`;
}
}
export type GitHubCredentialUnavailableError =
| GitHubCliMissingError
| GitHubNotSignedInError
| GitHubHostDisabledError
| GitHubCliFailedError
| SettingsSecretUnresolvedError;
export class GitHubCredentials extends Context.Service<
GitHubCredentials,
{
readonly get: (
host: string,
) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
/** The token saved in Settings for `host`, which outranks every other source. */
readonly saved: (
host: string,
) => Effect.Effect<
Option.Option<GitHubCredential>,
GitHubHostDisabledError | GitHubNotSignedInError | SettingsSecretUnresolvedError
>;
readonly fingerprint: (host: string, token: string) => Effect.Effect<string>;
readonly invalidate: (host: string) => Effect.Effect<void>;
}
>()("@t3tools/source-control-github/server/GitHubCredentials") {}
const HOSTNAME =
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\d{1,5})?$/;
/** API URLs are built from the host text, so anything but a bare hostname could redirect a token. */
export function isGitHubHost(host: string): boolean {
return HOSTNAME.test(host);
}
function isGitHubDotCom(host: string): boolean {
return host === "github.com" || host.endsWith(".ghe.com");
}
/** Restrict GH_ENTERPRISE_TOKEN to GH_HOST to prevent remote URLs from leaking it. */
export function environmentToken(
host: string,
env: Readonly<Record<string, string | undefined>>,
): string | null {
if (!isGitHubHost(host)) return null;
const names = isGitHubDotCom(host)
? ["GH_TOKEN", "GITHUB_TOKEN"]
: env.GH_HOST?.trim().toLowerCase() === host
? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
: [];
for (const name of names) {
const value = env[name]?.trim();
if (value) return value;
}
return null;
}
/** @public */
export const make = Effect.gen(function* () {
const sourceControlHost = yield* SourceControlHost.SourceControlHost;
const process = sourceControlHost.process;
const crypto = yield* Digest.Digest;
const environment = yield* HostProcess.Environment;
const workingDirectory = yield* HostProcess.WorkingDirectory;
const fingerprintOf = (host: string, token: string) =>
crypto.digest(Digest.sha256, new TextEncoder().encode(token)).pipe(
Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
Effect.orDie,
);
const fromGh = (host: string, account: string | undefined) =>
process
.run({
operation: "GitHubCredentials.get",
command: "gh",
args: [
"auth",
"token",
"--hostname",
host,
...(account === undefined ? [] : ["--user", account]),
],
cwd: workingDirectory,
// Never let gh print the token into a debug log.
env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
timeoutMs: 10_000,
concurrency: GH_PROCESS_CONCURRENCY,
})
.pipe(
Effect.mapError((error) =>
error._tag === "VcsProcessSpawnError" &&
error.cause instanceof PlatformError.PlatformError &&
error.cause.reason._tag === "NotFound"
? new GitHubCliMissingError({ host })
: // gh exits non-zero with "no oauth token" when it has no login for the host.
error._tag === "VcsProcessExitError"
? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
: new GitHubCliFailedError({ host, cause: error }),
),
Effect.map((output) => output.stdout.trim()),
Effect.filterOrFail(
(token) => token !== "",
() => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
),
);
const readSettings = (settings: ServerSettings) =>
readSourceControlHostSettings(
GitHubClient.settings,
settings.sourceControlHosts[GitHubClient.definition.kind],
);
const hostChoice = (host: string) =>
sourceControlHost.settings.get.pipe(
Effect.map((settings) => readSettings(settings).hosts[host]),
Effect.orElseSucceed(() => undefined),
);
const savedToken = (host: string) =>
sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe(
Effect.map((settings) => ({
token: readSettings(settings).tokens[host],
secretProviders: settings.secretProviders,
})),
Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),
Effect.flatMap(({ token, secretProviders }) =>
requireSettingsSecretLiteral(token, secretProviders),
),
Effect.map((token) => token.trim() || null),
);
const cacheKey = (host: string, account: string | undefined) =>
account === undefined ? host : `${host}\u0000${account}`;
const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
const [host = key, choice] = key.split("\u0000");
const fromEnv = environmentToken(host, environment);
const token =
fromEnv ??
(yield* fromGh(host, choice).pipe(
Effect.catchTags({
GitHubNotSignedInError: (error) =>
choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
}),
));
return {
host,
token: Redacted.make(token),
source: fromEnv !== null ? "env" : "gh",
fingerprint: yield* fingerprintOf(host, token),
} satisfies GitHubCredential;
});
const cache = yield* Cache.makeWith(lookup, {
capacity: 32,
timeToLive: (exit) =>
Exit.isSuccess(exit)
? TOKEN_TTL
: Exit.findErrorOption(exit).pipe(
Option.exists((error) => error._tag === "GitHubCliFailedError"),
)
? Duration.zero
: MISSING_TTL,
});
const saved = Effect.fn("GitHubCredentials.saved")(function* (rawHost: string) {
const host = normalizeHost(rawHost);
if (!isGitHubHost(host)) return yield* new GitHubNotSignedInError({ host });
if ((yield* hostChoice(host))?.enabled === false) {
return yield* new GitHubHostDisabledError({ host });
}
const token = yield* savedToken(host);
if (token === null) return Option.none<GitHubCredential>();
return Option.some<GitHubCredential>({
host,
token: Redacted.make(token),
source: "settings",
fingerprint: yield* fingerprintOf(host, token),
});
});
return GitHubCredentials.of({
get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
const host = normalizeHost(rawHost);
const fromSettings = yield* saved(host);
if (Option.isSome(fromSettings)) return fromSettings.value;
return yield* Cache.get(cache, cacheKey(host, (yield* hostChoice(host))?.account));
}),
saved,
fingerprint: fingerprintOf,
invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost) {
const host = normalizeHost(rawHost);
return hostChoice(host).pipe(
Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
);
}),
});
});
export const layer = Layer.effect(GitHubCredentials, make);