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

TanStackSourceCredentials.ts

249 lines9.7 KB

1import {
2 requireSettingsSecretLiteral,
3 type ServerSettings,
4 type SettingsSecretUnresolvedError,
5} from "@t3tools/contracts";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
8import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
10import * as Cache from "effect/Cache";
11import * as Context from "effect/Context";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as PlatformError from "effect/PlatformError";
18import * as Redacted from "effect/Redacted";
19import * as Schema from "effect/Schema";
20​
21import * as TanStackSource from "../shared/definition.ts";
22import * as Hosts from "./tanStackSourceHosts.ts";
23​
24const TOKEN_TTL = Duration.minutes(5);
25const MISSING_TTL = Duration.seconds(10);
26​
27export const TanStackSourceCredentialSource = Schema.Literals(["settings", "env", "src"]);
28export type TanStackSourceCredentialSource = typeof TanStackSourceCredentialSource.Type;
29​
30export interface TanStackSourceCredential {
31 readonly host: string;
32 readonly token: Redacted.Redacted<string>;
33 readonly source: TanStackSourceCredentialSource;
35​
36export class TanStackSourceCliMissingError extends Schema.TaggedError<TanStackSourceCliMissingError>()(
37 "TanStackSourceCliMissingError",
38 { host: Schema.String },
39) {
40 override get message(): string {
41 return `No TanStack Source credential for ${this.host}: save a token in Settings, set SRC_TOKEN, or install the src CLI and run \`src auth login --web\`.`;
42 }
44​
45export class TanStackSourceNotSignedInError extends Schema.TaggedError<TanStackSourceNotSignedInError>()(
46 "TanStackSourceNotSignedInError",
47 { host: Schema.String, account: Schema.optional(Schema.String) },
48) {
49 override get message(): string {
50 return this.account === undefined
51 ? `No TanStack Source credential for ${this.host}: run \`src auth login --web --hostname ${this.host}\`.`
52 : `No TanStack Source credential for ${this.account} on ${this.host}: run \`src auth login --web --hostname ${this.host}\` for that account or pick another in Settings → Source control & issues.`;
53 }
55​
56export class TanStackSourceHostDisabledError extends Schema.TaggedError<TanStackSourceHostDisabledError>()(
57 "TanStackSourceHostDisabledError",
58 { host: Schema.String },
59) {
60 override get message(): string {
61 return `TanStack Source host ${this.host} is turned off in Settings → Source control & issues.`;
62 }
64​
65export class TanStackSourceCliFailedError extends Schema.TaggedError<TanStackSourceCliFailedError>()(
66 "TanStackSourceCliFailedError",
67 { host: Schema.String, cause: Schema.Defect() },
68) {
69 override get message(): string {
70 return `The src CLI could not hand over a credential for ${this.host}. Check \`src auth status\` on the server.`;
71 }
73​
74export class TanStackSourceCliTimeoutError extends Schema.TaggedError<TanStackSourceCliTimeoutError>()(
75 "TanStackSourceCliTimeoutError",
76 { host: Schema.String, timeoutMs: Schema.Number, cause: Schema.Defect() },
77) {
78 override get message(): string {
79 return `The src CLI did not hand over a credential for ${this.host} within ${this.timeoutMs / 1000} seconds. The server may be overloaded; try again.`;
80 }
82​
83export type TanStackSourceCredentialUnavailableError =
84 | TanStackSourceCliMissingError
85 | TanStackSourceNotSignedInError
86 | TanStackSourceHostDisabledError
87 | TanStackSourceCliFailedError
88 | TanStackSourceCliTimeoutError
89 | SettingsSecretUnresolvedError;
90​
91/** Where requests to a host get their token. The API layer asks; it never reads a source itself. */
92export class TanStackSourceCredentials extends Context.Service<
93 TanStackSourceCredentials,
94 {
95 readonly get: (
96 host: string,
97 ) => Effect.Effect<TanStackSourceCredential, TanStackSourceCredentialUnavailableError>;
98 readonly invalidate: (host: string) => Effect.Effect<void>;
99 }
100>()("@t3tools/source-control-tanstack-source/server/TanStackSourceCredentials") {}
101​
102/** `src` sends SRC_TOKEN only to SRC_HOST (default source.tanstack.com); so does T3. */
103export function environmentToken(
104 host: string,
105 env: Readonly<Record<string, string | undefined>>,
106): string | null {
107 const configured = env.SRC_HOST?.trim().toLowerCase() || TanStackSource.TANSTACK_SOURCE_HOST;
108 if (configured !== normalizeHost(host)) return null;
109 return env.SRC_TOKEN?.trim() || null;
111​
112/** @public */
113export const make = Effect.gen(function* () {
114 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
115 const environment = yield* HostProcess.Environment;
116 const workingDirectory = yield* HostProcess.WorkingDirectory;
117​
118 const fromCli = (host: string, account: string | undefined) =>
119 sourceControlHost.process
120 .run({
121 operation: "TanStackSourceCredentials.get",
122 command: "src",
123 args: [
124 "auth",
125 "token",
126 "--hostname",
127 host,
128 ...(account === undefined ? [] : ["--user", account]),
129 ],
130 cwd: workingDirectory,
131 // An inherited SRC_TOKEN would answer in place of the login asked for; it is read above.
132 env: { SRC_TOKEN: "", SRC_NO_TELEMETRY: "1" },
133 timeoutMs: 10_000,
134 })
135 .pipe(
136 Effect.mapError((error) =>
137 error._tag === "VcsProcessSpawnError" &&
138 error.cause instanceof PlatformError.PlatformError &&
139 error.cause.reason._tag === "NotFound"
140 ? new TanStackSourceCliMissingError({ host })
141 : // src exits 1 with "no oauth token found" when it has no login for the host.
142 error._tag === "VcsProcessExitError"
143 ? new TanStackSourceNotSignedInError({
144 host,
145 ...(account === undefined ? {} : { account }),
146 })
147 : error._tag === "VcsProcessTimeoutError"
148 ? new TanStackSourceCliTimeoutError({
149 host,
150 timeoutMs: error.timeoutMs,
151 cause: error,
152 })
153 : new TanStackSourceCliFailedError({ host, cause: error }),
154 ),
155 Effect.map((output) => output.stdout.trim()),
156 Effect.filterOrFail(
157 (token) => token !== "",
158 () =>
159 new TanStackSourceNotSignedInError({
160 host,
161 ...(account === undefined ? {} : { account }),
162 }),
163 ),
164 );
165​
166 const readSettings = (settings: ServerSettings) =>
167 readSourceControlHostSettings(
168 TanStackSource.settings,
169 settings.sourceControlHosts[TanStackSource.definition.kind],
170 );
171​
172 const hostChoice = (host: string) =>
173 sourceControlHost.settings.get.pipe(
174 Effect.map((settings) => readSettings(settings).hosts[host]),
175 Effect.orElseSucceed(() => undefined),
176 );
177​
178 const savedToken = (host: string) =>
179 sourceControlHost.settings.getWithSecrets(TanStackSource.definition.kind).pipe(
180 Effect.map((settings) => ({
181 token: readSettings(settings).tokens[host],
182 secretProviders: settings.secretProviders,
183 })),
184 Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),
185 Effect.flatMap(({ token, secretProviders }) =>
186 requireSettingsSecretLiteral(token, secretProviders),
187 ),
188 Effect.map((token) => token.trim() || null),
189 );
190​
191 const cacheKey = (host: string, account: string | undefined) =>
192 account === undefined ? host : `${host}\u0000${account}`;
193​
194 const lookup = Effect.fn("TanStackSourceCredentials.lookup")(function* (key: string) {
195 const [host = key, account] = key.split("\u0000");
196 const fromEnv = environmentToken(host, environment);
197 const token =
198 fromEnv ??
199 (yield* fromCli(host, account).pipe(
200 Effect.catchTags({
201 TanStackSourceNotSignedInError: (error) =>
202 account === undefined ? Effect.fail(error) : fromCli(host, undefined),
203 }),
204 ));
205 return {
206 host,
207 token: Redacted.make(token),
208 source: fromEnv === null ? "src" : "env",
209 } satisfies TanStackSourceCredential;
210 });
211​
212 const cache = yield* Cache.makeWith(lookup, {
213 capacity: 8,
214 timeToLive: (exit) =>
215 Exit.isSuccess(exit)
216 ? TOKEN_TTL
217 : Exit.findErrorOption(exit).pipe(
218 Option.exists(
219 (error) =>
220 error._tag === "TanStackSourceCliFailedError" ||
221 error._tag === "TanStackSourceCliTimeoutError",
222 ),
223 )
224 ? Duration.zero
225 : MISSING_TTL,
226 });
227​
228 return TanStackSourceCredentials.of({
229 get: Effect.fn("TanStackSourceCredentials.get")(function* (rawHost) {
230 const host = normalizeHost(rawHost);
231 // Only Source's own hosts get a token, whatever host a remote or link names.
232 if (Hosts.tanStackSourceHost(host) === null)
233 return yield* new TanStackSourceNotSignedInError({ host });
234 const choice = yield* hostChoice(host);
235 if (choice?.enabled === false) return yield* new TanStackSourceHostDisabledError({ host });
236 const saved = yield* savedToken(host);
237 if (saved !== null) return { host, token: Redacted.make(saved), source: "settings" as const };
238 return yield* Cache.get(cache, cacheKey(host, choice?.account));
239 }),
240 invalidate: Effect.fn("TanStackSourceCredentials.invalidate")(function (rawHost) {
241 const host = normalizeHost(rawHost);
242 return hostChoice(host).pipe(
243 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
244 );
245 }),
246 });
247});
248​
249export const layer = Layer.effect(TanStackSourceCredentials, make);