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

main
ts 405 lines 13 KB
Raw
1 import { createHash } from "node:crypto";
2 import type { AppSecret } from "@distilled.cloud/fly-io/machines";
3 import * as machines from "@distilled.cloud/fly-io/machines";
4 import { Unowned } from "alchemy/AdoptPolicy";
5 import { isResolved } from "alchemy/Diff";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import * as Schedule from "effect/Schedule";
12 import { App, listOwnedApps } from "./App.ts";
13 import { createFlyVolumeName, matchesAlchemyPhysicalName } from "./Metadata.ts";
14 import type { Providers } from "./Providers.ts";
15
16 /**
17 * A resource-valued prop: the resource itself, or an Effect that produces
18 * it (so `yield* App(...)` and `App(...)` both type-check).
19 */
20 type Ref<T> = T | Effect.Effect<T, never, Providers>;
21
22 export interface SecretProps {
23 /**
24 * Parent Fly App. Changing it replaces the secret.
25 */
26 app: Ref<App>;
27 /**
28 * Secret name. Used as the Machine env-var name when set by the user
29 * (case-sensitive, stored as-is). If omitted, a unique name is generated
30 * from the stack, stage and logical ID (the ownership stamp). Changing
31 * it replaces the secret.
32 */
33 name?: string;
34 /**
35 * Secret value. Wrap with `Redacted.make(...)` so it is never logged.
36 * Updated in place via `updateSecrets`. Never persisted in attributes.
37 */
38 value: Redacted.Redacted<string> | string;
39 }
40
41 export type Secret = Resource<
42 "Fly.Secret",
43 SecretProps,
44 {
45 /** Parent Fly App name. */
46 appName: string;
47 /** Secret name (unique per App). */
48 name: string;
49 /** Fly digest of the current value. Not the plaintext. */
50 digest: string | undefined;
51 /** RFC3339 creation timestamp. */
52 createdAt: string | undefined;
53 /** RFC3339 last-update timestamp. */
54 updatedAt: string | undefined;
55 },
56 never,
57 Providers
58 >;
59
60 const resolveSecretProps = (
61 props: SecretProps | Effect.Effect<SecretProps, never, Providers>,
62 ): Effect.Effect<SecretProps, never, Providers> =>
63 Effect.gen(function* () {
64 const resolved = Effect.isEffect(props) ? yield* props : props;
65 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
66 const app = Effect.isEffect(resolved.app)
67 ? yield* resolved.app as Effect.Effect<App, never, Providers>
68 : resolved.app;
69 return { ...resolved, app };
70 });
71
72 const SecretResource = Resource<Secret>("Fly.Secret");
73
74 /**
75 * A Fly.Secret is an App vault entry. Fly injects it as an environment
76 * variable on every Machine. Use it when the value is shared and
77 * managed in one place by Fly.
78 *
79 * For a secret only this {@link Service} reads from `.env` at deploy
80 * time, yield `Config.Redacted` instead. Do not pass `env: { ... }` on
81 * a Service.
82 *
83 * @see https://fly.io/docs/apps/secrets/
84 *
85 * ### Config.Redacted on a Service
86 * Most secrets in a Service come from your `.env`. Yield
87 * `Config.Redacted` in init. Alchemy binds the value onto the Machine.
88 *
89 * **Example:** Bind from .env
90 * ```typescript
91 * import * as Config from "effect/Config";
92 * import * as Redacted from "effect/Redacted";
93 *
94 * export default class Api extends Fly.Service<Api>()(
95 * "Api",
96 * { app: Site, main: import.meta.url, port: 3000 },
97 * Effect.gen(function* () {
98 * const apiKey = yield* Config.Redacted("API_KEY");
99 *
100 * return {
101 * fetch: Effect.gen(function* () {
102 * const token = Redacted.value(apiKey);
103 * return HttpServerResponse.text("ok");
104 * }),
105 * };
106 * }),
107 * ) {}
108 * ```
109 *
110 * ### Create a Secret
111 * Wrap the value with `Redacted.make` so it is never logged. The
112 * plaintext is never stored in attributes. Omit `name` and Alchemy
113 * generates an ownership-stamped name.
114 *
115 * **Example:** Generated name
116 * ```typescript
117 * const dbUrl = yield* Fly.Secret("DatabaseUrl", {
118 * app: Site,
119 * value: Redacted.make("postgres://…"),
120 * });
121 * ```
122 *
123 * :::caution[Changing `app` replaces the Secret]
124 * The value is created on the new App. The old name is deleted.
125 * :::
126 *
127 * ### Env-var name
128 * `name` is the env-var Machines see. It is stored as-is
129 * (case-sensitive).
130 *
131 * **Example:** Explicit name
132 * ```typescript
133 * export const ApiToken = Fly.Secret("ApiToken", {
134 * app: Site,
135 * name: "API_TOKEN",
136 * value: Redacted.make("sk_live_…"),
137 * });
138 * ```
139 *
140 * :::caution[Changing `name` replaces the Secret]
141 * Fly cannot rename a secret. Alchemy creates the new name, then
142 * deletes the old one.
143 * :::
144 *
145 * ### Rotate the value
146 * Updating `value` is in place via `updateSecrets`.
147 *
148 * **Example:** New value
149 * ```typescript
150 * export const ApiToken = Fly.Secret("ApiToken", {
151 * app: Site,
152 * name: "API_TOKEN",
153 * value: Redacted.make("sk_live_rotated"),
154 * });
155 * ```
156 *
157 * ### Get a secret at runtime
158 * {@link GetSecret} is bound to one Secret. Provide
159 * {@link GetSecretHttp}. Fly only returns plaintext from a Machine in
160 * the same App. From a deploy-time Action you get metadata (name,
161 * digest, timestamps).
162 *
163 * **Example:** GetSecret
164 * ```typescript
165 * const get = yield* Fly.GetSecret(ApiToken);
166 * const got = yield* get();
167 * ```
168 *
169 * ### List secrets
170 * {@link ListSecrets} is bound to an {@link App}. From an Action, the
171 * org token can list any App in the org. From a Machine, deploy tokens
172 * are per-App. Mixing Apps on one Machine shares one `FLY_API_TOKEN`
173 * and is not supported.
174 *
175 * **Example:** ListSecrets
176 * ```typescript
177 * const list = yield* Fly.ListSecrets(Site);
178 * const { secrets } = yield* list();
179 * ```
180 *
181 * ### Write secrets
182 * {@link WriteSecret} creates, updates, and deletes by name. Provide
183 * {@link WriteSecretHttp} on the Action or Service Effect.
184 *
185 * **Example:** Rotate from an Action
186 * ```typescript
187 * const Seed = Alchemy.Action(
188 * "Seed",
189 * Effect.gen(function* () {
190 * const secrets = yield* Fly.WriteSecret(ApiToken);
191 *
192 * return Effect.fn(function* () {
193 * yield* secrets.update("API_TOKEN", Redacted.make("sk_live_rotated"));
194 * });
195 * }).pipe(Effect.provide(Fly.WriteSecretHttp)),
196 * );
197 * ```
198 *
199 * @resource
200 * @product Secret
201 */
202 export const Secret: typeof SecretResource = Object.assign(
203 (id: string, props: SecretProps | Effect.Effect<SecretProps, never, Providers>) =>
204 SecretResource(id, resolveSecretProps(props)),
205 SecretResource,
206 );
207
208 export class SecretNotCreated extends Data.TaggedError("Fly.SecretNotCreated")<{
209 appName: string;
210 secretName: string;
211 }> {}
212
213 export class SecretAppRequired extends Data.TaggedError("Fly.SecretAppRequired")<{
214 message: string;
215 }> {}
216
217 const appNameOf = (value: unknown): string | undefined => {
218 if (value === null || typeof value !== "object") return undefined;
219 const rec = value as { appName?: unknown };
220 return typeof rec.appName === "string" && rec.appName.length > 0 ? rec.appName : undefined;
221 };
222
223 const unwrapSecret = (value: Redacted.Redacted<string> | string): string =>
224 Redacted.isRedacted(value) ? Redacted.value(value) : value;
225
226 const resolveName = (id: string, name: string | undefined, existing?: string) =>
227 Effect.gen(function* () {
228 // User env-var names are stored as-is (case-sensitive). Generated
229 // names use the Volume underscore shape — Fly rejects hyphens.
230 if (name !== undefined) return name;
231 if (existing !== undefined) return existing;
232 return yield* createFlyVolumeName(id);
233 });
234
235 const toAttrs = (
236 appName: string,
237 secret: AppSecret,
238 fallbackName: string,
239 ): Secret["Attributes"] => ({
240 appName,
241 name: secret.name ?? fallbackName,
242 digest: secret.digest,
243 createdAt: secret.created_at,
244 updatedAt: secret.updated_at,
245 });
246
247 const getByName = (appName: string, secretName: string) =>
248 machines
249 .getSecret({
250 app_name: appName,
251 secret_name: secretName,
252 show_secrets: false,
253 })
254 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
255
256 const listSecrets = (appName: string) =>
257 machines
258 .listSecrets({
259 app_name: appName,
260 show_secrets: false,
261 })
262 .pipe(
263 Effect.map((res) => res.secrets ?? []),
264 Effect.catchTag(["NotFound", "Forbidden"], () => Effect.succeed([])),
265 );
266
267 const flyDigestCandidates = (plain: string) =>
268 Effect.sync(() => {
269 const utf8 = Buffer.from(plain, "utf8");
270 return [
271 createHash("md5").update(utf8).digest("hex"),
272 createHash("sha256").update(utf8).digest("hex"),
273 ];
274 });
275
276 export const SecretProvider = () =>
277 Provider.succeed(Secret, {
278 stables: ["appName", "name", "createdAt"],
279 nuke: { dependsOn: ["Fly.App"] },
280
281 diff: Effect.fn(function* ({ news, output }) {
282 if (news === undefined || !isResolved(news)) return undefined;
283 if (output === undefined) return undefined;
284 const desiredName = news.name !== undefined ? news.name : output.name;
285 const nameChanged = desiredName !== output.name;
286 const nextApp = appNameOf(news.app);
287 const appChanged = nextApp !== undefined && nextApp !== output.appName;
288 if (nameChanged || appChanged) {
289 return {
290 action: "replace" as const,
291 // Same (app, name) cannot exist twice — delete the old secret first.
292 deleteFirst: nameChanged && !appChanged,
293 };
294 }
295 return undefined;
296 }),
297
298 read: Effect.fn(function* ({ id, olds, output }) {
299 const appName = output?.appName ?? (olds !== undefined ? appNameOf(olds.app) : undefined);
300 if (appName === undefined) return undefined;
301 const name = yield* resolveName(id, olds?.name, output?.name);
302 const found = yield* getByName(appName, name);
303 if (found === undefined) return undefined;
304 const attrs = toAttrs(appName, found, name);
305 if (output !== undefined) return attrs;
306 return matchesAlchemyPhysicalName(name) ? attrs : Unowned(attrs);
307 }),
308
309 list: Effect.fn(function* () {
310 const apps = yield* listOwnedApps();
311 const rows = yield* Effect.forEach(
312 apps,
313 (app) =>
314 listSecrets(app.appName).pipe(
315 Effect.map((secrets) =>
316 secrets.flatMap((secret) => {
317 const name = secret.name;
318 if (!matchesAlchemyPhysicalName(name)) return [];
319 return [toAttrs(app.appName, secret, name ?? "")];
320 }),
321 ),
322 ),
323 { concurrency: 8 },
324 );
325 return rows.flat();
326 }),
327
328 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
329 const props = news ?? ({} as SecretProps);
330 const appName = appNameOf(props.app) ?? output?.appName;
331 if (appName === undefined) {
332 return yield* new SecretAppRequired({
333 message: "Secret requires a resolved Fly.App",
334 });
335 }
336 const name = yield* resolveName(id, props.name, output?.name);
337 const desiredPlain = unwrapSecret(props.value);
338
339 // Observe by cached identity, then the desired (app, name).
340 let current =
341 output !== undefined ? yield* getByName(output.appName, output.name) : undefined;
342 if (
343 current === undefined &&
344 (output === undefined || output.appName !== appName || output.name !== name)
345 ) {
346 current = yield* getByName(appName, name);
347 }
348
349 let createdThisRun = false;
350 if (current === undefined) {
351 yield* machines
352 .createSecret({
353 app_name: appName,
354 secret_name: name,
355 value: desiredPlain,
356 })
357 .pipe(Effect.catchTag("Conflict", () => Effect.void));
358 current = yield* getByName(appName, name);
359 createdThisRun = true;
360 }
361
362 if (current === undefined) {
363 return yield* new SecretNotCreated({ appName, secretName: name });
364 }
365
366 // Sync — skip if we just created. Prefer observed digest vs hash of
367 // desired; otherwise re-put when olds is absent (adoption) or the
368 // previous value differs. Never log the plaintext.
369 if (!createdThisRun) {
370 const candidates = yield* flyDigestCandidates(desiredPlain);
371 const digestMatches = current.digest !== undefined && candidates.includes(current.digest);
372 const previousPlain = olds?.value !== undefined ? unwrapSecret(olds.value) : undefined;
373 const valueChanged = previousPlain === undefined || previousPlain !== desiredPlain;
374 if (!digestMatches && valueChanged) {
375 yield* machines
376 .updateSecrets({
377 app_name: appName,
378 values: { [name]: desiredPlain },
379 })
380 .pipe(Effect.catchTag("Conflict", () => Effect.void));
381 current = (yield* getByName(appName, name)) ?? current;
382 }
383 }
384
385 return toAttrs(appName, current, name);
386 }),
387
388 delete: Effect.fn(function* ({ output }) {
389 if (output.appName.length === 0 || output.name.length === 0) return;
390 yield* machines
391 .deleteSecret({
392 app_name: output.appName,
393 secret_name: output.name,
394 })
395 .pipe(Effect.catchTag("NotFound", () => Effect.void));
396 yield* getByName(output.appName, output.name).pipe(
397 Effect.map((secret) => secret === undefined),
398 Effect.repeat({
399 schedule: Schedule.spaced("1 second"),
400 until: (gone) => gone,
401 times: 8,
402 }),
403 );
404 }),
405 });