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

main
ts 169 lines 6.33 KB
Raw
1 import { downloadSecret, fromApiKey } from "@distilled.cloud/doppler";
2 import * as Retry from "@distilled.cloud/doppler/Retry";
3 import { AuthError, refreshHint } from "alchemy/Auth/AuthProvider";
4 import { SuppressMissingProviderConfig } from "alchemy/Auth/Profile";
5 import { resolveProviderConfig } from "alchemy/Auth/Resolve";
6 import { logLoadedKeys } from "alchemy/Secrets/Log";
7 import {
8 CredentialsConfig,
9 resolveSecretsOption,
10 type SecretsLayer,
11 type SecretsOption,
12 } from "alchemy/Secrets/Provider";
13 import { UserFacingError } from "alchemy/UserFacingError";
14 import * as ConfigProvider from "effect/ConfigProvider";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import type * as Redacted from "effect/Redacted";
18 import {
19 DopplerAuth,
20 type DopplerAuthConfig,
21 type DopplerResolvedCredentials,
22 } from "./AuthProvider.ts";
23
24 export interface DopplerOptions {
25 /** Project slug. Required with browser login or personal tokens. */
26 project?: string;
27 /** Config slug, e.g. `dev` or `prd`. Required with browser login or personal tokens. */
28 config?: string;
29 }
30
31 interface DopplerCredentials {
32 readonly token: Redacted.Redacted<string>;
33 /** Set when the token came from a stored Alchemy profile. */
34 readonly profileName?: string;
35 /** How the stored profile authenticated, when the token came from one. */
36 readonly method?: DopplerAuthConfig["method"];
37 }
38
39 /** Human description of which secrets were asked for, for error messages. */
40 const describeSelection = (options: DopplerOptions) => {
41 if (options.project && options.config) {
42 return `project '${options.project}' config '${options.config}'`;
43 }
44 if (options.project) {
45 return `project '${options.project}'`;
46 }
47 return "the token's own project and config";
48 };
49
50 /**
51 * Doppler could not serve the requested secrets. The message says "Doppler"
52 * up front and names the selection, so a stack trace never has to be read
53 * to know which secrets source broke.
54 */
55 export class DopplerSecretsError extends Data.TaggedError("DopplerSecretsError")<{
56 readonly selection: DopplerOptions;
57 readonly credentials: DopplerCredentials;
58 /** What the Doppler SDK failed with. */
59 readonly cause: { readonly _tag: string; readonly message: string };
60 }> {
61 readonly [UserFacingError] = true;
62
63 override get message() {
64 const selection = describeSelection(this.selection);
65 switch (this.cause._tag) {
66 case "Unauthorized":
67 return this.credentials.profileName === undefined
68 ? "Doppler rejected the token. Check DOPPLER_TOKEN; to log in locally run `alchemy profile edit --add Doppler`."
69 : `Doppler credentials were rejected. ${refreshHint("Doppler", this.credentials.profileName)}`;
70 case "NotFound":
71 return `Doppler could not find ${selection}: ${this.cause.message}. Check Doppler.Secrets({ project, config }) and that the token has access to it.`;
72 default:
73 return `Doppler could not download secrets for ${selection}: ${this.cause.message}`;
74 }
75 }
76 }
77
78 /**
79 * Resolve the token through the Doppler auth provider: `DOPPLER_TOKEN` when
80 * present, otherwise the selected profile.
81 */
82 const resolveCredentials = Effect.gen(function* () {
83 const resolved = yield* resolveProviderConfig<DopplerAuthConfig, DopplerResolvedCredentials>(
84 "Doppler",
85 ).pipe(Effect.provide(DopplerAuth));
86 const { token } = yield* resolved.resolve;
87 const credentials: DopplerCredentials = {
88 token,
89 profileName: resolved.profileName,
90 method: resolved.config?.method,
91 };
92 return credentials;
93 }).pipe(Effect.provide(CredentialsConfig));
94
95 /** Download every secret of the selected project/config as a flat env map. */
96 const downloadSecrets = Effect.fn("downloadDopplerSecrets")(function* (
97 options: DopplerOptions,
98 credentials: DopplerCredentials,
99 ) {
100 const secrets = yield* downloadSecret({
101 project: options.project,
102 config: options.config,
103 format: "json",
104 }).pipe(
105 Retry.none,
106 Effect.provide(fromApiKey({ apiKey: credentials.token })),
107 Effect.timeout("30 seconds"),
108 Effect.mapError((cause) => new DopplerSecretsError({ selection: options, credentials, cause })),
109 );
110
111 const env: Record<string, string> = {};
112 for (const [key, value] of Object.entries(secrets)) {
113 if (value !== undefined) env[key] = value;
114 }
115 return env;
116 });
117
118 /** A `secrets` entry that loads a Doppler config. */
119 export class DopplerSecretsProvider extends Data.TaggedClass("alchemy/SecretProvider::Doppler")<{
120 readonly layer: SecretsLayer;
121 }> {}
122
123 /**
124 * Load Doppler secrets into Effect Config without touching `process.env`.
125 * Config-scoped service tokens may omit `project` and `config`.
126 *
127 * Authenticate locally with `alchemy profile edit --add Doppler` and choose
128 * Login or API token. In CI, set `DOPPLER_TOKEN`, or `DOPPLER_IDENTITY_ID`
129 * to log in with the platform's OIDC token. Loading secrets never starts a
130 * login flow.
131 *
132 * ```ts
133 * secrets: [
134 * Doppler.Secrets(({ stage }) => ({
135 * project: "my-app",
136 * config: stage === "prod" ? "prd" : "dev",
137 * })),
138 * ]
139 * ```
140 */
141 export const Secrets = (options: SecretsOption<DopplerOptions> = {}) =>
142 new DopplerSecretsProvider({
143 layer: ConfigProvider.layerAdd(
144 Effect.gen(function* () {
145 // Auth-provider discovery builds stack layers just to find out which
146 // providers are used. It must work offline and with expired tokens, so
147 // the user can configure or refresh the very token this layer needs.
148 if (yield* SuppressMissingProviderConfig) return ConfigProvider.fromEnv({ env: {} });
149
150 const resolved = yield* resolveSecretsOption(options);
151 const credentials = yield* resolveCredentials;
152
153 // Browser-login tokens are personal tokens: they can see every project,
154 // so Doppler needs to be told which one to read.
155 const missingSelector = !resolved.project || !resolved.config;
156 if (credentials.method === "login" && missingSelector) {
157 return yield* AuthError.make({
158 message:
159 "Doppler browser login requires both project and config in Doppler.Secrets({ project, config }).",
160 });
161 }
162
163 const env = yield* downloadSecrets(resolved, credentials);
164 yield* logLoadedKeys(`Doppler (${describeSelection(resolved)})`, Object.keys(env));
165 return ConfigProvider.fromEnv({ env, preserveEmptyStrings: true });
166 }),
167 { asPrimary: true },
168 ),
169 });