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

main
ts 262 lines 9.4 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Redacted from "effect/Redacted";
3 import * as Schema from "effect/Schema";
4 import * as Interaction from "../Interaction.ts";
5 import {
6 AuthError,
7 AuthProviderLayer,
8 type ConfigureField,
9 type ConfigureMethod,
10 type EnvironmentVariable,
11 } from "./AuthProvider.ts";
12 import { displayRedacted } from "./Credentials.ts";
13 import { mapPromptCancellation } from "./Env.ts";
14
15 /**
16 * Collected field values: one string per non-omitted field, keyed by
17 * {@link ConfigureField.name}.
18 */
19 export type StoredValue = string | Redacted.Redacted<string>;
20 export type StoredValues = Record<string, StoredValue | undefined>;
21
22 /** Reveal a collected value only at a validation or I/O boundary. */
23 export const storedValueText = (value: StoredValue | undefined) =>
24 value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value;
25
26 /** Preserve or introduce redaction for a collected secret. */
27 export const storedSecret = (value: StoredValue | undefined) =>
28 value === undefined ? undefined : Redacted.isRedacted(value) ? value : Redacted.make(value);
29
30 /**
31 * Everything needed to generate a complete single-method ("stored")
32 * {@link AuthProviderImpl} for a provider whose credential is a token (or a
33 * small set of fields) the user pastes once: prompts, flag-driven
34 * configuration, schema-validated inline values, login/logout, and
35 * structured details.
36 *
37 * Providers with several auth methods (browser OAuth, SSO) don't fit this
38 * factory — they hand-roll the impl and may still reuse
39 * {@link collectFieldValues} for their token-shaped method.
40 */
41 export interface StoredAuthProviderConfig<Resolved> {
42 /** Registry name, e.g. `"Neon"`. */
43 readonly provider: string;
44 /** The fields collected interactively or via `--set`. */
45 readonly fields: ReadonlyArray<ConfigureField>;
46 /**
47 * Derive additional stored values after input collection — e.g. resolve
48 * an account id with an API call using the entered token. Runs for both
49 * the interactive and flag-driven paths, before persistence.
50 */
51 readonly complete?: (values: StoredValues) => Effect.Effect<StoredValues, AuthError>;
52 /**
53 * Map validated stored values to the in-memory resolved credentials.
54 * `source` distinguishes profile-stored values from CI env resolution.
55 */
56 readonly toResolved: (values: StoredValues, source: "stored") => Resolved;
57 /** CI resolution from env vars; requires {@link environment}. */
58 readonly readEnvironment?: Effect.Effect<Resolved, AuthError>;
59 readonly environment?: ReadonlyArray<EnvironmentVariable>;
60 }
61
62 /** Inline-values type for factory-made static-token providers. */
63 export type StoredAuthConfig = {
64 readonly method: "stored";
65 readonly [key: string]: StoredValue | undefined;
66 };
67
68 /**
69 * Validate flag-provided values against the field specs: unknown keys,
70 * missing required fields, and per-field validators all fail with an
71 * actionable {@link AuthError}.
72 */
73 export const validateFieldValues = (
74 provider: string,
75 fields: ReadonlyArray<ConfigureField>,
76 values: Record<string, string>,
77 ): Effect.Effect<StoredValues, AuthError> =>
78 Effect.gen(function* () {
79 const known = new Set(fields.map((field) => field.name));
80 for (const key of Object.keys(values)) {
81 if (!known.has(key)) {
82 return yield* AuthError.make({
83 message:
84 `${provider}: unknown field '${key}'. ` + `Valid fields: ${[...known].join(", ")}.`,
85 });
86 }
87 }
88 const collected: StoredValues = {};
89 for (const field of fields) {
90 const raw = values[field.name] ?? field.defaultValue;
91 if (raw === undefined || raw.length === 0) {
92 if (field.optional) continue;
93 return yield* AuthError.make({
94 message: `${provider}: missing required field '${field.name}' (${field.label}). Pass it with --set ${field.name}=<value>.`,
95 });
96 }
97 const invalid = field.validate?.(raw);
98 if (invalid !== undefined) {
99 return yield* AuthError.make({
100 message: `${provider}: invalid '${field.name}': ${invalid}`,
101 });
102 }
103 collected[field.name] = field.secret ? Redacted.make(raw) : raw;
104 }
105 return collected;
106 });
107
108 /**
109 * Prompt for each field in order (secret fields masked, optional fields
110 * skippable with an empty answer). Shared by the factory's interactive
111 * `configure` and by hand-rolled multi-method providers that want the same
112 * behavior for their token method.
113 */
114 export const collectFieldValues = (
115 fields: ReadonlyArray<ConfigureField>,
116 ): Effect.Effect<StoredValues, AuthError, Interaction.Interaction> =>
117 Effect.gen(function* () {
118 const interaction = yield* Interaction.Interaction;
119 const values: StoredValues = {};
120 for (const field of fields) {
121 const description = [
122 field.description,
123 field.optional ? "Optional — press Enter to skip." : undefined,
124 ]
125 .filter((part): part is string => part !== undefined)
126 .join(" ");
127 const validate = (value: string) => {
128 if (value.length === 0) return field.optional ? undefined : "Required";
129 return field.validate?.(value);
130 };
131 const request = field.secret
132 ? interaction.prompt.password({
133 message: field.label,
134 description: description || undefined,
135 placeholder: field.placeholder,
136 validate,
137 })
138 : interaction.prompt.text({
139 message: field.label,
140 description: description || undefined,
141 placeholder: field.placeholder,
142 defaultValue: field.defaultValue,
143 validate,
144 });
145 const answer = yield* request.pipe(mapPromptCancellation);
146 if (answer.length === 0 && field.optional) continue;
147 values[field.name] = field.secret ? Redacted.make(answer) : answer;
148 }
149 return values;
150 });
151
152 /**
153 * Build a registration Layer (plus the derived inline-values schema)
154 * for a single-method stored-credential provider.
155 *
156 * ```ts
157 * export const { layer: NeonAuth, storedSchema: NeonStoredCredentials } =
158 * makeStoredAuthProvider({
159 * provider: "Neon",
160 * fields: [{ name: "apiKey", label: "Neon API Key", secret: true }],
161 * toResolved: (values, source) => ({ ... }),
162 * readEnvironment: ...,
163 * environment: [...],
164 * });
165 * ```
166 */
167 export const makeStoredAuthProvider = <Resolved>(config: StoredAuthProviderConfig<Resolved>) => {
168 const { provider, fields } = config;
169
170 const fieldSchemas = Object.fromEntries(
171 fields.map((field) => [
172 field.name,
173 field.optional ? Schema.optional(Schema.String) : Schema.String,
174 ]),
175 );
176
177 const storedSchema = Schema.Struct(
178 fieldSchemas,
179 // SAFETY: each generated property schema corresponds exactly to the
180 // ConfigureField entry used to construct StoredValues above.
181 ) as Schema.Codec<StoredValues>;
182
183 const configSchema = Schema.Struct({
184 method: Schema.Literal("stored"),
185 ...fieldSchemas,
186 }) as Schema.Codec<StoredAuthConfig>;
187
188 const layer = AuthProviderLayer<StoredAuthConfig, Resolved>()(
189 provider,
190 Effect.gen(function* () {
191 const persist = (_profileName: string, values: StoredValues) =>
192 Effect.gen(function* () {
193 const complete = config.complete?.(values) ?? Effect.succeed(values);
194 const completed = yield* complete;
195 yield* Interaction.success(`${provider}: credentials saved.`);
196 return {
197 method: "stored" as const,
198 ...Object.fromEntries(
199 Object.entries(completed).map(([key, value]) => [key, storedValueText(value)]),
200 ),
201 };
202 });
203
204 const configure = (profileName: string) =>
205 collectFieldValues(fields).pipe(Effect.flatMap((values) => persist(profileName, values)));
206
207 const configureWith = (
208 profileName: string,
209 input: { method: string; values: Record<string, string> },
210 ) =>
211 input.method === "stored"
212 ? validateFieldValues(provider, fields, input.values).pipe(
213 Effect.flatMap((values) => persist(profileName, values)),
214 )
215 : Effect.fail(
216 AuthError.make({
217 message: `${provider}: unknown method '${input.method}'. Valid methods: stored.`,
218 }),
219 );
220
221 const read = (_profileName: string, values: StoredAuthConfig) =>
222 Effect.succeed(config.toResolved(values, "stored"));
223
224 const login = (_profileName: string, values: StoredAuthConfig) => Effect.succeed(values);
225
226 const logout = (_profileName: string, _config: StoredAuthConfig) => Effect.void;
227
228 const details = (_profileName: string, values: StoredAuthConfig) =>
229 Effect.succeed({
230 lines: fields.flatMap((field) => {
231 const value = values[field.name];
232 if (value === undefined) return [];
233 return [
234 {
235 key: field.name,
236 value: field.secret
237 ? displayRedacted(storedSecret(value) ?? Redacted.make(""))
238 : (storedValueText(value) ?? ""),
239 },
240 ];
241 }),
242 });
243
244 const configureMethods: ReadonlyArray<ConfigureMethod> = [{ method: "stored", fields }];
245
246 return {
247 configSchema,
248 configure,
249 configureWith,
250 configureMethods,
251 login,
252 logout,
253 details,
254 read,
255 readEnvironment: config.readEnvironment,
256 environment: config.environment,
257 };
258 }),
259 );
260
261 return { layer, storedSchema };
262 };