Open History to see the last commit
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";
13import { readSourceControlHostSettings } from "@t3tools/source-control-core/client/definition";
14
15import * as GitCafeClient from "../client/definition.ts";
16
17const TOKEN_TTL = Duration.minutes(5);
18const MISSING_TTL = Duration.seconds(10);
19
20export interface GitCafeCredential {
21 readonly host: string;
22 readonly token: Redacted.Redacted<string>;
23 readonly source: "settings" | "env" | "cafe";
24}
25
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 }
33}
34
35export class GitCafeNotSignedInError extends Schema.TaggedError<GitCafeNotSignedInError>()(
36 "GitCafeNotSignedInError",
37 { host: Schema.String },
38) {
39 override get message(): string {
40 return `No GitCafe credential for ${this.host}: run \`cafe auth login --host https://${this.host}/api\`.`;
41 }
42}
43
44export class GitCafeCliFailedError extends Schema.TaggedError<GitCafeCliFailedError>()(
45 "GitCafeCliFailedError",
46 { host: Schema.String, cause: Schema.Defect() },
47) {
48 override get message(): string {
49 return `The GitCafe CLI could not hand over a credential for ${this.host}. Check \`cafe auth status\` on the server.`;
50 }
51}
52
53export type GitCafeCredentialUnavailableError =
54 | GitCafeCliMissingError
55 | GitCafeNotSignedInError
56 | GitCafeCliFailedError;
57
58export class GitCafeCredentials extends Context.Service<
59 GitCafeCredentials,
60 {
61 readonly get: (
62 host: string,
63 ) => Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError>;
64 readonly invalidate: (host: string) => Effect.Effect<void>;
65 readonly cliEnv: (host: string) => Effect.Effect<Readonly<Record<string, string>>>;
66 }
67>()("@t3tools/source-control-gitcafe/server/GitCafeCredentials") {}
68
69const normalizeHost = (host: string) => host.trim().toLowerCase();
70const DEFAULT_HOST = "git.cafe";
71
72/**
73 * `CAFE_TOKEN`, but only for the host `cafe` itself would send it to (`CAFE_HOST`, git.cafe by
74 * default): a remote URL picks the host, and must not steer a production token to staging.
75 */
76export function environmentToken(
77 host: string,
78 env: Readonly<Record<string, string | undefined>>,
79): string | null {
80 const configured = env.CAFE_HOST?.trim();
81 const configuredHost = configured
82 ? URL.parse(configured.includes("://") ? configured : `https://${configured}`)?.host
83 : DEFAULT_HOST;
84 if (configuredHost?.toLowerCase() !== normalizeHost(host)) return null;
85 return env.CAFE_TOKEN?.trim() || null;
86}
87
88function credentialPassword(output: string): string | null {
89 for (const line of output.split(/\r?\n/u)) {
90 if (line.startsWith("password=")) return line.slice("password=".length).trim() || null;
91 }
92 return null;
93}
94
95/** @public Service construction is part of the canonical Effect module API. */
96export const make = Effect.gen(function* () {
97 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
98 const { process } = sourceControlHost;
99 const environment = yield* HostProcess.Environment;
100 const workingDirectory = yield* HostProcess.WorkingDirectory;
101
102 /**
103 * `cafe` has no `auth token` command; its Git credential helper is the supported way to hand
104 * the stored login to another program, and answers over stdin/stdout so the token never
105 * reaches an argument list or a log.
106 */
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.get.pipe(
139 Effect.map(
140 (settings) =>
141 readSourceControlHostSettings(
142 GitCafeClient.settings,
143 settings.sourceControlHosts[GitCafeClient.definition.kind],
144 ).token || null,
145 ),
146 Effect.orElseSucceed(() => null),
147 );
148
149 const lookup = Effect.fn("GitCafeCredentials.lookup")(function* (
150 host: string,
151 ): Effect.fn.Return<GitCafeCredential, GitCafeCredentialUnavailableError> {
152 const fromEnv = environmentToken(host, environment);
153 const token = fromEnv ?? (yield* fromCafe(host));
154 return { host, token: Redacted.make(token), source: fromEnv !== null ? "env" : "cafe" };
155 });
156
157 const cache = yield* Cache.makeWith(lookup, {
158 capacity: 4,
159 timeToLive: (exit) =>
160 Exit.isSuccess(exit)
161 ? TOKEN_TTL
162 : Exit.findErrorOption(exit).pipe(
163 Option.exists((error) => error._tag === "GitCafeCliFailedError"),
164 )
165 ? Duration.zero
166 : MISSING_TTL,
167 });
168
169 return GitCafeCredentials.of({
170 get: (host) =>
171 fromSettings(host).pipe(
172 Effect.flatMap(
173 (saved): Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError> =>
174 saved === null
175 ? Cache.get(cache, normalizeHost(host))
176 : Effect.succeed({
177 host: normalizeHost(host),
178 token: Redacted.make(saved),
179 source: "settings",
180 }),
181 ),
182 ),
183 invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),
184 cliEnv: (host) =>
185 fromSettings(host).pipe(Effect.map((saved) => (saved === null ? {} : { CAFE_TOKEN: saved }))),
186 });
187});
188
189export const layer = Layer.effect(GitCafeCredentials, make);