The best way to control Claude Code, Codex and more from any computer or phone

main
ts 332 lines 11.6 KB
Raw
1 import {
2 anonymous,
3 DEFAULT_API_BASE_URL,
4 loginWithOidcAuth,
5 loginWithUniversalAuth,
6 } from "@distilled.cloud/infisical";
7 import * as Retry from "@distilled.cloud/infisical/Retry";
8 import { AuthError, AuthProviderLayer, type ConfigureField } from "alchemy/Auth/AuthProvider";
9 import { displayRedacted } from "alchemy/Auth/Credentials";
10 import { getEnv, getEnvRedacted, mapPromptCancellation } from "alchemy/Auth/Env";
11 import { detectOidcToken, SUPPORTED_OIDC_PLATFORMS } from "alchemy/Auth/OidcToken";
12 import {
13 collectFieldValues,
14 storedValueText,
15 validateFieldValues,
16 type StoredValues,
17 } from "alchemy/Auth/StoredAuthProvider";
18 import * as Interaction from "alchemy/Interaction";
19 import * as Duration from "effect/Duration";
20 import * as Effect from "effect/Effect";
21 import type * as HttpClient from "effect/http/HttpClient";
22 import * as Redacted from "effect/Redacted";
23 import * as Schema from "effect/Schema";
24
25 export const INFISICAL_TOKEN_ENV = "INFISICAL_TOKEN";
26 /** The machine identity to log into with a platform OIDC token. */
27 export const INFISICAL_IDENTITY_ID_ENV = "INFISICAL_IDENTITY_ID";
28 /** Same name the Infisical CLI uses for self-hosted instances. */
29 export const INFISICAL_API_URL_ENV = "INFISICAL_API_URL";
30 /** Explicit OIDC token for platforms that are not auto-detected. */
31 export const INFISICAL_OIDC_TOKEN_ENV = "INFISICAL_OIDC_TOKEN";
32 /** Optional audience to request in the platform's OIDC token. */
33 export const INFISICAL_OIDC_AUDIENCE_ENV = "INFISICAL_OIDC_AUDIENCE";
34
35 const PROVIDER_NAME = "Infisical";
36 const API_TIMEOUT = Duration.seconds(30);
37
38 /**
39 * A machine identity's client id + secret. The secret never expires unless
40 * given a TTL in Infisical, and Alchemy exchanges it for a short-lived
41 * access token on every read, so this is the method for local development.
42 */
43 const UniversalAuthConfig = Schema.Struct({
44 method: Schema.Literal("universal-auth"),
45 clientId: Schema.NonEmptyString,
46 clientSecret: Schema.NonEmptyString,
47 apiBaseUrl: Schema.optional(Schema.String),
48 });
49
50 /** A user token from the dashboard's "Copy Token" menu item. Valid for 10 days. */
51 const AccessTokenConfig = Schema.Struct({
52 method: Schema.Literal("access-token"),
53 token: Schema.NonEmptyString,
54 apiBaseUrl: Schema.optional(Schema.String),
55 });
56
57 export const InfisicalAuthConfigSchema = Schema.Union([UniversalAuthConfig, AccessTokenConfig]);
58 export type InfisicalAuthConfig = typeof InfisicalAuthConfigSchema.Type;
59
60 export interface InfisicalResolvedCredentials {
61 readonly token: Redacted.Redacted<string>;
62 readonly apiBaseUrl: string;
63 }
64
65 const apiBaseUrlField: ConfigureField = {
66 name: "apiBaseUrl",
67 label: "Infisical API URL",
68 description: "For the EU cloud (https://eu.infisical.com) or a self-hosted instance.",
69 placeholder: DEFAULT_API_BASE_URL,
70 optional: true,
71 };
72
73 const universalAuthFields: ReadonlyArray<ConfigureField> = [
74 {
75 name: "clientId",
76 label: "Machine identity client ID",
77 description:
78 "From the machine identity's Universal Auth settings in Infisical. See https://infisical.com/docs/documentation/platform/identities/universal-auth",
79 },
80 {
81 name: "clientSecret",
82 label: "Machine identity client secret",
83 secret: true,
84 },
85 apiBaseUrlField,
86 ];
87
88 const accessTokenFields: ReadonlyArray<ConfigureField> = [
89 {
90 name: "token",
91 label: "Infisical user token",
92 description:
93 'From the account menu in the Infisical dashboard ("Copy Token"). Valid for 10 days.',
94 secret: true,
95 },
96 apiBaseUrlField,
97 ];
98
99 const toCredentials = (
100 response: { readonly accessToken: string | Redacted.Redacted<string> },
101 apiBaseUrl: string | undefined,
102 ): InfisicalResolvedCredentials => ({
103 token: Redacted.isRedacted(response.accessToken)
104 ? response.accessToken
105 : Redacted.make(response.accessToken),
106 apiBaseUrl: apiBaseUrl ?? DEFAULT_API_BASE_URL,
107 });
108
109 /**
110 * Exchange a machine identity's client credentials for an access token.
111 * Infisical answers 401 when either half is wrong or the secret is spent.
112 */
113 export const mintAccessToken = (config: {
114 readonly clientId: string;
115 readonly clientSecret: string;
116 readonly apiBaseUrl?: string;
117 }) =>
118 loginWithUniversalAuth({
119 clientId: config.clientId,
120 clientSecret: Redacted.make(config.clientSecret),
121 }).pipe(
122 Retry.none,
123 Effect.provide(anonymous({ apiBaseUrl: config.apiBaseUrl })),
124 Effect.timeout(API_TIMEOUT),
125 Effect.map((response) => toCredentials(response, config.apiBaseUrl)),
126 Effect.mapError((cause) =>
127 AuthError.make({
128 message:
129 "Infisical rejected the machine identity credentials. Check the client ID and secret, and that the secret has not expired or hit its use limit.",
130 cause,
131 }),
132 ),
133 );
134
135 /**
136 * Exchange a platform-issued OIDC token for an access token of the machine
137 * identity whose OIDC auth trusts that platform's issuer.
138 */
139 export const mintAccessTokenFromOidc = (config: {
140 readonly identityId: string;
141 readonly jwt: Redacted.Redacted<string>;
142 readonly apiBaseUrl?: string;
143 }) =>
144 loginWithOidcAuth({
145 identityId: config.identityId,
146 jwt: Redacted.value(config.jwt),
147 }).pipe(
148 Retry.none,
149 Effect.provide(anonymous({ apiBaseUrl: config.apiBaseUrl })),
150 Effect.timeout(API_TIMEOUT),
151 Effect.map((response) => toCredentials(response, config.apiBaseUrl)),
152 Effect.mapError((cause) =>
153 AuthError.make({
154 message: `Infisical rejected the OIDC login for identity '${config.identityId}': ${cause.message}. Check that the identity's OIDC auth trusts this platform's issuer, subject, and audience.`,
155 cause,
156 }),
157 ),
158 );
159
160 /**
161 * Resolve the token a stored configuration grants. Annotated because the two
162 * branches are differently shaped Effects and a union of Effects does not
163 * flow through `flatMap`.
164 */
165 const resolve = (
166 config: InfisicalAuthConfig,
167 ): Effect.Effect<InfisicalResolvedCredentials, AuthError, HttpClient.HttpClient> =>
168 config.method === "universal-auth"
169 ? mintAccessToken(config)
170 : Effect.succeed({
171 token: Redacted.make(config.token),
172 apiBaseUrl: config.apiBaseUrl ?? DEFAULT_API_BASE_URL,
173 });
174
175 /** Turn collected field values into a stored configuration. */
176 const toConfig = (
177 method: InfisicalAuthConfig["method"],
178 values: StoredValues,
179 ): InfisicalAuthConfig => {
180 const apiBaseUrl = storedValueText(values.apiBaseUrl);
181 return method === "access-token"
182 ? { method, token: storedValueText(values.token)!, apiBaseUrl }
183 : {
184 method,
185 clientId: storedValueText(values.clientId)!,
186 clientSecret: storedValueText(values.clientSecret)!,
187 apiBaseUrl,
188 };
189 };
190
191 /**
192 * Verify Universal Auth with a login before storing it. Pasted access
193 * tokens are used as supplied and checked when secrets are requested.
194 */
195 const verify = (config: InfisicalAuthConfig) => resolve(config).pipe(Effect.as(config));
196
197 const fieldsFor = (method: InfisicalAuthConfig["method"]) =>
198 method === "universal-auth" ? universalAuthFields : accessTokenFields;
199
200 const chooseMethod = Interaction.select({
201 message: "Infisical authentication method",
202 options: [
203 {
204 value: "universal-auth" as const,
205 label: "Machine identity",
206 description: "Client ID and secret; mints a fresh access token on each run",
207 },
208 {
209 value: "access-token" as const,
210 label: "User token",
211 description: "Copied from the dashboard; valid for 10 days",
212 },
213 ],
214 }).pipe(mapPromptCancellation);
215
216 /**
217 * How CI authenticates, decided from the environment: a ready token, or a
218 * machine identity to log into with the platform's OIDC token. Environment
219 * credentials take precedence over stored profiles, including outside CI.
220 */
221 const readEnvironment = Effect.gen(function* () {
222 const apiBaseUrl = yield* getEnv(INFISICAL_API_URL_ENV);
223 const token = yield* getEnvRedacted(INFISICAL_TOKEN_ENV);
224 if (token !== undefined && Redacted.value(token).length > 0) {
225 return { token, apiBaseUrl: apiBaseUrl ?? DEFAULT_API_BASE_URL };
226 }
227 const identityId = yield* getEnv(INFISICAL_IDENTITY_ID_ENV);
228 if (!identityId) {
229 return yield* AuthError.make({
230 message: `Infisical credentials are missing. In CI set ${INFISICAL_TOKEN_ENV}, or set ${INFISICAL_IDENTITY_ID_ENV} to log in with the platform's OIDC token; locally run \`alchemy profile edit --add Infisical\`.`,
231 });
232 }
233 const oidc = yield* detectOidcToken({
234 token: INFISICAL_OIDC_TOKEN_ENV,
235 audience: INFISICAL_OIDC_AUDIENCE_ENV,
236 });
237 if (oidc === undefined) {
238 return yield* AuthError.make({
239 message: `${INFISICAL_IDENTITY_ID_ENV} is set but no platform OIDC token was found. Supported: ${SUPPORTED_OIDC_PLATFORMS}; elsewhere pass the token in ${INFISICAL_OIDC_TOKEN_ENV}.`,
240 });
241 }
242 return yield* mintAccessTokenFromOidc({
243 identityId,
244 jwt: oidc.token,
245 apiBaseUrl,
246 });
247 });
248
249 /**
250 * Infisical profile authentication: a machine identity's universal-auth
251 * credentials (recommended) or a pasted access token.
252 */
253 export const InfisicalAuth = AuthProviderLayer<InfisicalAuthConfig, InfisicalResolvedCredentials>()(
254 PROVIDER_NAME,
255 {
256 configSchema: InfisicalAuthConfigSchema,
257 configure: () =>
258 chooseMethod.pipe(
259 Effect.flatMap((method) =>
260 collectFieldValues(fieldsFor(method)).pipe(
261 Effect.map((values) => toConfig(method, values)),
262 ),
263 ),
264 Effect.flatMap(verify),
265 ),
266 configureMethods: [
267 { method: "universal-auth", fields: universalAuthFields },
268 { method: "access-token", fields: accessTokenFields },
269 ],
270 configureWith: (_, input) => {
271 if (input.method !== "universal-auth" && input.method !== "access-token") {
272 return Effect.fail(
273 AuthError.make({
274 message: `Infisical: unknown method '${input.method}'. Valid methods: universal-auth, access-token.`,
275 }),
276 );
277 }
278 const method = input.method;
279 return validateFieldValues(PROVIDER_NAME, fieldsFor(method), input.values).pipe(
280 Effect.map((values) => toConfig(method, values)),
281 Effect.flatMap(verify),
282 );
283 },
284 // Nothing to re-authenticate: stored credentials are long-lived (or, for
285 // access tokens, replaced by reconfiguring). Verifying them is enough.
286 login: (_, config) => verify(config),
287 // Client secrets are revoked from the Infisical dashboard by an admin;
288 // there is nothing session-like to tear down.
289 logout: () => Effect.void,
290 read: (_, config) => resolve(config),
291 details: (_, config) =>
292 Effect.succeed({
293 lines: [
294 { key: "method", value: config.method },
295 config.method === "universal-auth"
296 ? { key: "clientId", value: config.clientId }
297 : {
298 key: "token",
299 value: displayRedacted(Redacted.make(config.token)),
300 },
301 { key: "apiBaseUrl", value: config.apiBaseUrl ?? DEFAULT_API_BASE_URL },
302 ],
303 }),
304 readEnvironment,
305 environment: [
306 {
307 name: INFISICAL_TOKEN_ENV,
308 required: true,
309 secret: true,
310 alternatives: [INFISICAL_IDENTITY_ID_ENV],
311 description:
312 "A machine identity access token; or set INFISICAL_IDENTITY_ID instead to log in with the platform's OIDC token (Vercel, GitHub Actions, GitLab CI, GCP)",
313 },
314 {
315 name: INFISICAL_OIDC_TOKEN_ENV,
316 required: false,
317 secret: true,
318 description: "Explicit OIDC token for platforms that are not auto-detected",
319 },
320 {
321 name: INFISICAL_OIDC_AUDIENCE_ENV,
322 required: false,
323 description: "Audience to request in the platform's OIDC token",
324 },
325 {
326 name: INFISICAL_API_URL_ENV,
327 required: false,
328 description: "Base URL of a self-hosted Infisical instance",
329 },
330 ],
331 },
332 );