Open History to see the last commit
1import {
2 requireSettingsSecretLiteral,
3 type SettingsSecretUnresolvedError,
4} from "@t3tools/contracts";
5import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
6import * as Cache from "effect/Cache";
7import * as Context from "effect/Context";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as PlatformError from "effect/PlatformError";
14import * as Redacted from "effect/Redacted";
15import * as Schema from "effect/Schema";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
19
20import * as GitCafeClient from "../shared/definition.ts";
21
22const TOKEN_TTL = Duration.minutes(5);
23const MISSING_TTL = Duration.seconds(10);
24
25export interface GitCafeCredential {
26 readonly host: string;
27 readonly token: Redacted.Redacted<string>;
28 readonly source: "settings" | "env" | "cafe";
29}
30
31export class GitCafeCliMissingError extends Schema.TaggedError<GitCafeCliMissingError>()(
32 "GitCafeCliMissingError",
33 { host: Schema.String },
34) {
35 override get message(): string {
36 return `No GitCafe credential for ${this.host}: set CAFE_TOKEN, or install the GitCafe CLI and run \`cafe auth login\`.`;
37 }
38}
39
40export class GitCafeNotSignedInError extends Schema.TaggedError<GitCafeNotSignedInError>()(
41 "GitCafeNotSignedInError",
42 { host: Schema.String },
43) {
44 override get message(): string {
45 return `No GitCafe credential for ${this.host}: run \`cafe auth login --host https://${this.host}/api\`.`;
46 }
47}
48
49export class GitCafeCliFailedError extends Schema.TaggedError<GitCafeCliFailedError>()(
50 "GitCafeCliFailedError",
51 { host: Schema.String, cause: Schema.Defect() },
52) {
53 override get message(): string {
54 return `The GitCafe CLI could not hand over a credential for ${this.host}. Check \`cafe auth status\` on the server.`;
55 }
56}
57
58export type GitCafeCredentialUnavailableError =
59 | GitCafeCliMissingError
60 | GitCafeNotSignedInError
61 | GitCafeCliFailedError
62 | SettingsSecretUnresolvedError;
63
64export class GitCafeCredentials extends Context.Service<
65 GitCafeCredentials,
66 {
67 readonly get: (
68 host: string,
69 ) => Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError>;
70 readonly invalidate: (host: string) => Effect.Effect<void>;
71 readonly cliEnv: (
72 host: string,
73 ) => Effect.Effect<Readonly<Record<string, string>>, SettingsSecretUnresolvedError>;
74 }
75>()("@t3tools/source-control-gitcafe/server/GitCafeCredentials") {}
76
77const DEFAULT_HOST = "git.cafe";
78
79/** Restrict CAFE_TOKEN to CAFE_HOST (default git.cafe), including for staging remotes. */
80export function environmentToken(
81 host: string,
82 env: Readonly<Record<string, string | undefined>>,
83): string | null {
84 const configured = env.CAFE_HOST?.trim();
85 const configuredHost = configured
86 ? URL.parse(configured.includes("://") ? configured : `https://${configured}`)?.host
87 : DEFAULT_HOST;
88 if (configuredHost?.toLowerCase() !== normalizeHost(host)) return null;
89 return env.CAFE_TOKEN?.trim() || null;
90}
91
92function credentialPassword(output: string): string | null {
93 for (const line of output.split(/\r?\n/u)) {
94 if (line.startsWith("password=")) return line.slice("password=".length).trim() || null;
95 }
96 return null;
97}
98
99/** @public */
100export const make = Effect.gen(function* () {
101 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
102 const { process } = sourceControlHost;
103 const environment = yield* HostProcess.Environment;
104 const workingDirectory = yield* HostProcess.WorkingDirectory;
105
106 /** cafe has no auth-token command; its credential helper keeps tokens out of argv/logs. */
107 const fromCafe = (host: string) =>
108 process
109 .run({
110 operation: "GitCafeCredentials.get",
111 command: "cafe",
112 args: ["auth", "http", "credential", "--host", `https://${host}/api`, "get"],
113 cwd: workingDirectory,
114 stdin: `protocol=https\nhost=${host}\n\n`,
115 env: { CAFE_NO_UPDATE_CHECK: "1" },
116 timeoutMs: 10_000,
117 })
118 .pipe(
119 Effect.mapError((error) =>
120 error._tag === "VcsProcessSpawnError" &&
121 error.cause instanceof PlatformError.PlatformError &&
122 error.cause.reason._tag === "NotFound"
123 ? new GitCafeCliMissingError({ host })
124 : error._tag === "VcsProcessExitError"
125 ? new GitCafeNotSignedInError({ host })
126 : new GitCafeCliFailedError({ host, cause: error }),
127 ),
128 Effect.map((output) => credentialPassword(output.stdout)),
129 Effect.filterOrFail(
130 (token): token is string => token !== null,
131 () => new GitCafeNotSignedInError({ host }),
132 ),
133 );
134
135 const fromSettings = (host: string) =>
136 normalizeHost(host) !== DEFAULT_HOST
137 ? Effect.succeed(null)
138 : sourceControlHost.settings.getWithSecrets(GitCafeClient.definition.kind).pipe(
139 Effect.map((settings) => ({
140 token: readSourceControlHostSettings(
141 GitCafeClient.settings,
142 settings.sourceControlHosts[GitCafeClient.definition.kind],
143 ).token,
144 secretProviders: settings.secretProviders,
145 })),
146 Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),
147 Effect.flatMap(({ token, secretProviders }) =>
148 requireSettingsSecretLiteral(token, secretProviders),
149 ),
150 Effect.map((token) => token || null),
151 );
152
153 const lookup = Effect.fn("GitCafeCredentials.lookup")(function* (
154 host: string,
155 ): Effect.fn.Return<GitCafeCredential, GitCafeCredentialUnavailableError> {
156 const fromEnv = environmentToken(host, environment);
157 const token = fromEnv ?? (yield* fromCafe(host));
158 return { host, token: Redacted.make(token), source: fromEnv !== null ? "env" : "cafe" };
159 });
160
161 const cache = yield* Cache.makeWith(lookup, {
162 capacity: 4,
163 timeToLive: (exit) =>
164 Exit.isSuccess(exit)
165 ? TOKEN_TTL
166 : Exit.findErrorOption(exit).pipe(
167 Option.exists((error) => error._tag === "GitCafeCliFailedError"),
168 )
169 ? Duration.zero
170 : MISSING_TTL,
171 });
172
173 return GitCafeCredentials.of({
174 get: Effect.fn("GitCafeCredentials.get")(function (host) {
175 return fromSettings(host).pipe(
176 Effect.flatMap(
177 (saved): Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError> =>
178 saved === null
179 ? Cache.get(cache, normalizeHost(host))
180 : Effect.succeed({
181 host: normalizeHost(host),
182 token: Redacted.make(saved),
183 source: "settings",
184 }),
185 ),
186 );
187 }),
188 invalidate: Effect.fn("GitCafeCredentials.invalidate")(function (host) {
189 return Cache.invalidate(cache, normalizeHost(host));
190 }),
191 cliEnv: Effect.fn("GitCafeCredentials.cliEnv")(function (host) {
192 return fromSettings(host).pipe(
193 Effect.map((saved) => (saved === null ? {} : { CAFE_TOKEN: saved })),
194 );
195 }),
196 });
197});
198
199export const layer = Layer.effect(GitCafeCredentials, make);