@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 262 lines 9.62 KB
Raw
1 import { hostname } from "node:os";
2 import {
3 authOidc,
4 authorizeCliAuth,
5 generateCliAuth,
6 revokeCliAuth,
7 } from "@distilled.cloud/doppler";
8 import * as Retry from "@distilled.cloud/doppler/Retry";
9 import { AuthError, AuthProviderLayer, type ConfigureField } from "alchemy/Auth/AuthProvider";
10 import { getEnv, getEnvRedacted, mapPromptCancellation } from "alchemy/Auth/Env";
11 import { detectOidcToken, SUPPORTED_OIDC_PLATFORMS } from "alchemy/Auth/OidcToken";
12 import { storedValueText, validateFieldValues } from "alchemy/Auth/StoredAuthProvider";
13 import * as Interaction from "alchemy/Interaction";
14 import * as Duration from "effect/Duration";
15 import * as Effect from "effect/Effect";
16 import * as Redacted from "effect/Redacted";
17 import * as Schedule from "effect/Schedule";
18 import * as Schema from "effect/Schema";
19 import packageJson from "../package.json" with { type: "json" };
20
21 export const DopplerAuthConfigSchema = Schema.Struct({
22 method: Schema.Literals(["login", "api-token"]),
23 token: Schema.NonEmptyString,
24 });
25 export type DopplerAuthConfig = typeof DopplerAuthConfigSchema.Type;
26
27 export interface DopplerResolvedCredentials {
28 readonly token: Redacted.Redacted<string>;
29 }
30
31 const PROVIDER_NAME = "Doppler";
32 export const DOPPLER_TOKEN_ENV = "DOPPLER_TOKEN";
33 /** A service account identity to log into with a platform OIDC token. */
34 export const DOPPLER_IDENTITY_ID_ENV = "DOPPLER_IDENTITY_ID";
35 /** Explicit OIDC token for platforms that are not auto-detected. */
36 export const DOPPLER_OIDC_TOKEN_ENV = "DOPPLER_OIDC_TOKEN";
37 /** Optional audience to request in the platform's OIDC token. */
38 export const DOPPLER_OIDC_AUDIENCE_ENV = "DOPPLER_OIDC_AUDIENCE";
39
40 /** How long the user has to approve the browser login. */
41 const LOGIN_TIMEOUT = Duration.minutes(5);
42 const APPROVAL_POLL_INTERVAL = Duration.seconds(2);
43 const API_TIMEOUT = Duration.seconds(30);
44
45 /**
46 * Describe this machine the way Doppler's CLI auth endpoint expects it.
47 * Doppler validates these fields, so the values mirror what its own CLI sends.
48 */
49 const client = {
50 // Doppler cuts the token name at the first ".", so drop any domain suffix
51 // (e.g. "Yoru.local" -> "Yoru").
52 hostname: `Alchemy (${hostname().split(".")[0]})`,
53 // Doppler requires vMAJOR.MINOR.PATCH; prerelease suffixes are rejected.
54 version: `v${packageJson.version.split("-")[0]}`,
55 os: process.platform === "win32" ? "windows" : process.platform,
56 // Doppler expects Go-style architecture names.
57 arch: process.arch === "x64" ? "amd64" : process.arch === "ia32" ? "386" : process.arch,
58 };
59
60 /**
61 * Poll Doppler until the user approves the login in their browser.
62 * Doppler answers `409 Conflict` while approval is still pending; any other
63 * failure (rejected, expired) ends the flow.
64 */
65 const awaitApproval = (authorization: { polling_code: string | Redacted.Redacted<string> }) =>
66 authorizeCliAuth({ code: authorization.polling_code }).pipe(
67 Retry.none,
68 Effect.retry({
69 while: (error) => error._tag === "Conflict",
70 schedule: Schedule.spaced(APPROVAL_POLL_INTERVAL).pipe(
71 Schedule.upTo({ duration: LOGIN_TIMEOUT }),
72 ),
73 }),
74 );
75
76 /**
77 * Explicit browser login. Only ever run from `alchemy profile edit` /
78 * `profile refresh`; reading credentials or loading secrets never logs in.
79 */
80 export const login = Effect.gen(function* () {
81 const authorization = yield* generateCliAuth(client).pipe(
82 Retry.none,
83 Effect.timeout(API_TIMEOUT),
84 );
85
86 const credentials = yield* Interaction.browserLogin({
87 provider: "Doppler",
88 waitingLabel: "Waiting for Doppler authorization (up to 5 minutes)…",
89 url: authorization.auth_url,
90 code: authorization.code,
91 waitFor: awaitApproval(authorization),
92 }).pipe(mapPromptCancellation, Effect.timeout(LOGIN_TIMEOUT));
93
94 const config: DopplerAuthConfig = {
95 method: "login",
96 token: Redacted.isRedacted(credentials.token)
97 ? Redacted.value(credentials.token)
98 : credentials.token,
99 };
100 return config;
101 }).pipe(
102 Effect.mapError(() =>
103 AuthError.make({
104 message:
105 "Doppler login did not complete. Run `alchemy profile edit --add Doppler` to try again, or configure an API token.",
106 }),
107 ),
108 );
109
110 const tokenFields: ReadonlyArray<ConfigureField> = [
111 { name: "token", label: "Doppler API token", secret: true },
112 ];
113
114 /** Interactive alternative to {@link login}: paste a service or personal token. */
115 const promptForToken = Interaction.password({
116 message: "Doppler API token",
117 description: "A service token or personal token. Stored in your Alchemy profile.",
118 validate: (value) => (value.trim().length ? undefined : "Required"),
119 }).pipe(
120 mapPromptCancellation,
121 Effect.map((token): DopplerAuthConfig => ({
122 method: "api-token",
123 token: token.trim(),
124 })),
125 );
126
127 const chooseMethod = Interaction.select({
128 message: "Doppler authentication method",
129 options: [
130 {
131 value: "login" as const,
132 label: "Login",
133 description: "Login using your browser",
134 },
135 {
136 value: "api-token" as const,
137 label: "API token",
138 description: "Use a service token or personal token",
139 },
140 ],
141 }).pipe(
142 mapPromptCancellation,
143 Effect.flatMap((method) => (method === "login" ? login : promptForToken)),
144 );
145
146 /** Browser-login tokens are revocable; API tokens were minted elsewhere and are left alone. */
147 const revokeLoginToken = (config: DopplerAuthConfig) =>
148 config.method === "login"
149 ? revokeCliAuth({ token: Redacted.make(config.token) }).pipe(
150 Retry.none,
151 Effect.timeout(API_TIMEOUT),
152 Effect.asVoid,
153 Effect.mapError(() =>
154 AuthError.make({
155 message: "Could not revoke the Doppler login token. Try logging out again.",
156 }),
157 ),
158 )
159 : Effect.void;
160
161 /**
162 * Exchange a platform-issued OIDC token for a short-lived Doppler token via
163 * the service account identity that trusts that platform's issuer.
164 * Identities are a Team/Enterprise plan feature.
165 */
166 export const mintTokenFromOidc = (config: {
167 readonly identityId: string;
168 readonly jwt: Redacted.Redacted<string>;
169 }) =>
170 authOidc({
171 identity: config.identityId,
172 token: Redacted.value(config.jwt),
173 }).pipe(
174 Retry.none,
175 Effect.timeout(API_TIMEOUT),
176 Effect.map((response): DopplerResolvedCredentials => ({
177 token: Redacted.isRedacted(response.token) ? response.token : Redacted.make(response.token),
178 })),
179 Effect.mapError((cause) =>
180 AuthError.make({
181 message: `Doppler rejected the OIDC login for identity '${config.identityId}': ${cause.message}. Check that the service account identity trusts this platform's issuer, subject, and audience, and that the workplace plan includes identities.`,
182 cause,
183 }),
184 ),
185 );
186
187 /**
188 * How CI authenticates, decided from the environment: a ready token, or a
189 * service account identity to log into with the platform's OIDC token.
190 */
191 const readEnvironment = Effect.gen(function* () {
192 const token = yield* getEnvRedacted(DOPPLER_TOKEN_ENV);
193 if (token !== undefined && Redacted.value(token).length > 0) {
194 return { token };
195 }
196 const identityId = yield* getEnv(DOPPLER_IDENTITY_ID_ENV);
197 if (!identityId) {
198 return yield* AuthError.make({
199 message: `Doppler credentials are missing. In CI set ${DOPPLER_TOKEN_ENV}, or set ${DOPPLER_IDENTITY_ID_ENV} to log in with the platform's OIDC token; locally run \`alchemy profile edit --add Doppler\` and choose Login.`,
200 });
201 }
202 const oidc = yield* detectOidcToken({
203 token: DOPPLER_OIDC_TOKEN_ENV,
204 audience: DOPPLER_OIDC_AUDIENCE_ENV,
205 });
206 if (oidc === undefined) {
207 return yield* AuthError.make({
208 message: `${DOPPLER_IDENTITY_ID_ENV} is set but no platform OIDC token was found. Supported: ${SUPPORTED_OIDC_PLATFORMS}; elsewhere pass the token in ${DOPPLER_OIDC_TOKEN_ENV}.`,
209 });
210 }
211 return yield* mintTokenFromOidc({ identityId, jwt: oidc.token });
212 });
213
214 /** Doppler profile authentication: explicit browser Login or a stored API token. */
215 export const DopplerAuth = AuthProviderLayer<DopplerAuthConfig, DopplerResolvedCredentials>()(
216 PROVIDER_NAME,
217 {
218 configSchema: DopplerAuthConfigSchema,
219 configure: () => chooseMethod,
220 configureMethods: [{ method: "api-token", fields: tokenFields }],
221 configureWith: (_, input) =>
222 input.method === "api-token"
223 ? validateFieldValues(PROVIDER_NAME, tokenFields, input.values).pipe(
224 Effect.map((values): DopplerAuthConfig => ({
225 method: "api-token",
226 token: storedValueText(values.token)!,
227 })),
228 )
229 : Effect.fail(
230 AuthError.make({
231 message:
232 "Doppler: use method 'api-token' for flag-driven configuration. Login requires interactive profile setup.",
233 }),
234 ),
235 login: (_, config) => (config.method === "login" ? login : promptForToken),
236 logout: (_, config) => revokeLoginToken(config),
237 read: (_, config) => Effect.succeed({ token: Redacted.make(config.token) }),
238 details: (_, config) => Effect.succeed({ lines: [{ key: "method", value: config.method }] }),
239 readEnvironment,
240 environment: [
241 {
242 name: DOPPLER_TOKEN_ENV,
243 required: true,
244 secret: true,
245 alternatives: [DOPPLER_IDENTITY_ID_ENV],
246 description:
247 "A service token or personal token; or set DOPPLER_IDENTITY_ID instead to log in with the platform's OIDC token (Vercel, GitHub Actions, GitLab CI, GCP)",
248 },
249 {
250 name: DOPPLER_OIDC_TOKEN_ENV,
251 required: false,
252 secret: true,
253 description: "Explicit OIDC token for platforms that are not auto-detected",
254 },
255 {
256 name: DOPPLER_OIDC_AUDIENCE_ENV,
257 required: false,
258 description: "Audience to request in the platform's OIDC token",
259 },
260 ],
261 },
262 );