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

GitCafeCredentials.ts

166 lines6.3 KB

1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as PlatformError from "effect/PlatformError";
9import * as Redacted from "effect/Redacted";
10import * as Schema from "effect/Schema";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
13​
14/** How long a token is reused before `cafe` is asked again, so a re-login applies soon. */
15const TOKEN_TTL = Duration.minutes(5);
16/** No credential is retried sooner, so a fresh `cafe auth login` takes effect on the next read. */
17const MISSING_TTL = Duration.seconds(10);
18​
19export interface GitCafeCredential {
20 readonly host: string;
21 readonly token: Redacted.Redacted<string>;
22 readonly source: "env" | "cafe";
24​
25/** No `CAFE_TOKEN` for the host, and no `cafe` on PATH to ask. */
26export class GitCafeCliMissingError extends Schema.TaggedError<GitCafeCliMissingError>()(
27 "GitCafeCliMissingError",
28 { host: Schema.String },
29) {
30 override get message(): string {
31 return `No GitCafe credential for ${this.host}: set CAFE_TOKEN, or install the GitCafe CLI and run \`cafe auth login\`.`;
32 }
34​
35/** `cafe` is installed but holds no login for the host. */
36export class GitCafeNotSignedInError extends Schema.TaggedError<GitCafeNotSignedInError>()(
37 "GitCafeNotSignedInError",
38 { host: Schema.String },
39) {
40 override get message(): string {
41 return `No GitCafe credential for ${this.host}: run \`cafe auth login --host https://${this.host}/api\`.`;
42 }
44​
45/** `cafe` timed out or failed for a reason other than having no login. */
46export class GitCafeCliFailedError extends Schema.TaggedError<GitCafeCliFailedError>()(
47 "GitCafeCliFailedError",
48 { host: Schema.String, cause: Schema.Defect() },
49) {
50 override get message(): string {
51 return `The GitCafe CLI could not hand over a credential for ${this.host}. Check \`cafe auth status\` on the server.`;
52 }
54​
55export type GitCafeCredentialUnavailableError =
56 | GitCafeCliMissingError
57 | GitCafeNotSignedInError
58 | GitCafeCliFailedError;
59​
60/** Where GitCafe tokens come from. Callers ask per host and never see how the token was found. */
61export class GitCafeCredentials extends Context.Service<
62 GitCafeCredentials,
63 {
64 readonly get: (
65 host: string,
66 ) => Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError>;
67 /** Drops the held token after GitCafe refused it, so the next read asks its source again. */
68 readonly invalidate: (host: string) => Effect.Effect<void>;
69 }
70>()("@t3tools/source-control-gitcafe/server/GitCafeCredentials") {}
71​
72const normalizeHost = (host: string) => host.trim().toLowerCase();
73​
74/**
75 * `CAFE_TOKEN`, but only for the host `cafe` itself would send it to (`CAFE_HOST`, git.cafe by
76 * default): a remote URL picks the host, and must not steer a production token to staging.
77 */
78export function environmentToken(
79 host: string,
80 env: Readonly<Record<string, string | undefined>>,
81): string | null {
82 const configured = env.CAFE_HOST?.trim();
83 const configuredHost = configured
84 ? URL.parse(configured.includes("://") ? configured : `https://${configured}`)?.host
85 : "git.cafe";
86 if (configuredHost?.toLowerCase() !== normalizeHost(host)) return null;
87 return env.CAFE_TOKEN?.trim() || null;
89​
90/** A Git credential `get` answer: `key=value` lines, of which only `password` matters here. */
91function credentialPassword(output: string): string | null {
92 for (const line of output.split(/\r?\n/u)) {
93 if (line.startsWith("password=")) return line.slice("password=".length).trim() || null;
94 }
95 return null;
97​
98/** @public Service construction is part of the canonical Effect module API. */
99export const make = Effect.gen(function* () {
100 const { process } = yield* SourceControlHost.SourceControlHost;
101 const environment = yield* HostProcess.Environment;
102 const workingDirectory = yield* HostProcess.WorkingDirectory;
103​
104 /**
105 * `cafe` has no `auth token` command; its Git credential helper is the supported way to hand
106 * the stored login to another program, and answers over stdin/stdout so the token never
107 * reaches an argument list or a log.
108 */
109 const fromCafe = (host: string) =>
110 process
111 .run({
112 operation: "GitCafeCredentials.get",
113 command: "cafe",
114 args: ["auth", "http", "credential", "--host", `https://${host}/api`, "get"],
115 cwd: workingDirectory,
116 stdin: `protocol=https\nhost=${host}\n\n`,
117 env: { CAFE_NO_UPDATE_CHECK: "1" },
118 timeoutMs: 10_000,
119 })
120 .pipe(
121 Effect.mapError((error) =>
122 error._tag === "VcsProcessSpawnError" &&
123 error.cause instanceof PlatformError.PlatformError &&
124 error.cause.reason._tag === "NotFound"
125 ? new GitCafeCliMissingError({ host })
126 : error._tag === "VcsProcessExitError"
127 ? new GitCafeNotSignedInError({ host })
128 : new GitCafeCliFailedError({ host, cause: error }),
129 ),
130 Effect.map((output) => credentialPassword(output.stdout)),
131 Effect.filterOrFail(
132 (token): token is string => token !== null,
133 () => new GitCafeNotSignedInError({ host }),
134 ),
135 );
136​
137 const lookup = Effect.fn("GitCafeCredentials.lookup")(function* (host: string) {
138 const fromEnv = environmentToken(host, environment);
139 const token = fromEnv ?? (yield* fromCafe(host));
140 return {
141 host,
142 token: Redacted.make(token),
143 source: fromEnv !== null ? "env" : "cafe",
144 } satisfies GitCafeCredential;
145 });
146​
147 const cache = yield* Cache.makeWith(lookup, {
148 capacity: 4,
149 // A transient failure (a timeout, a locked keyring) is asked again on the next read.
150 timeToLive: (exit) =>
151 Exit.isSuccess(exit)
152 ? TOKEN_TTL
153 : Exit.findErrorOption(exit).pipe(
154 Option.exists((error) => error._tag === "GitCafeCliFailedError"),
155 )
156 ? Duration.zero
157 : MISSING_TTL,
158 });
159​
160 return GitCafeCredentials.of({
161 get: (host) => Cache.get(cache, normalizeHost(host)),
162 invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),
163 });
164});
165​
166export const layer = Layer.effect(GitCafeCredentials, make);