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