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

GitCafeCredentials.ts

188 lines6.8 KB

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