The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { SecretKey as FlySecretKey } from "@distilled.cloud/fly-io/machines"; |
| 2 | import * as machines from "@distilled.cloud/fly-io/machines"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import { App, listOwnedApps } from "./App.ts"; |
| 11 | import { |
| 12 | createFlyVolumeName, |
| 13 | matchesAlchemyPhysicalName, |
| 14 | sanitizeFlyVolumeName, |
| 15 | } from "./Metadata.ts"; |
| 16 | import type { Providers } from "./Providers.ts"; |
| 17 | |
| 18 | /** |
| 19 | * A resource-valued prop: the resource itself, or an Effect that produces |
| 20 | * it (so `yield* App(...)` and `App(...)` both type-check). |
| 21 | */ |
| 22 | type Ref<T> = T | Effect.Effect<T, never, Providers>; |
| 23 | |
| 24 | export interface SecretKeyProps { |
| 25 | /** |
| 26 | * Parent Fly App. Changing it replaces the secret key. |
| 27 | */ |
| 28 | app: Ref<App>; |
| 29 | /** |
| 30 | * Secret key name, unique per App. If omitted, a unique name is generated |
| 31 | * from the stack, stage and logical ID (the ownership stamp). Changing it |
| 32 | * replaces the key. |
| 33 | */ |
| 34 | name?: string; |
| 35 | /** |
| 36 | * Fly key type (`nacl_sign`, `nacl_box`, `hs256`, `hs384`, `hs512`, |
| 37 | * `xaes256gcm`, `nacl_auth`, `nacl_secretbox`, `es256`). Changing it |
| 38 | * replaces the key. |
| 39 | */ |
| 40 | type?: string; |
| 41 | /** |
| 42 | * Raw key material. If omitted, Fly generates a key via |
| 43 | * `generateSecretKey`. If set, the key is created or updated with |
| 44 | * `setSecretKey`. Never persisted in state. |
| 45 | */ |
| 46 | value?: ReadonlyArray<number>; |
| 47 | } |
| 48 | |
| 49 | export type SecretKey = Resource< |
| 50 | "Fly.SecretKey", |
| 51 | SecretKeyProps, |
| 52 | { |
| 53 | /** Parent Fly App name. */ |
| 54 | appName: string; |
| 55 | /** Secret key name (unique per App). */ |
| 56 | name: string; |
| 57 | /** Observed Fly key type. */ |
| 58 | type: string | undefined; |
| 59 | /** Public key (base64), when the type has one. Never private material. */ |
| 60 | publicKey: string | undefined; |
| 61 | /** RFC3339 creation timestamp. */ |
| 62 | createdAt: string | undefined; |
| 63 | /** RFC3339 last-update timestamp. */ |
| 64 | updatedAt: string | undefined; |
| 65 | }, |
| 66 | never, |
| 67 | Providers |
| 68 | >; |
| 69 | |
| 70 | const resolveSecretKeyProps = ( |
| 71 | props: SecretKeyProps | Effect.Effect<SecretKeyProps, never, Providers>, |
| 72 | ): Effect.Effect<SecretKeyProps, never, Providers> => |
| 73 | Effect.gen(function* () { |
| 74 | const resolved = Effect.isEffect(props) ? yield* props : props; |
| 75 | if (globalThis.__ALCHEMY_RUNTIME__) return resolved; |
| 76 | const app = Effect.isEffect(resolved.app) |
| 77 | ? yield* resolved.app as Effect.Effect<App, never, Providers> |
| 78 | : resolved.app; |
| 79 | return { ...resolved, app }; |
| 80 | }); |
| 81 | |
| 82 | const SecretKeyResource = Resource<SecretKey>("Fly.SecretKey"); |
| 83 | |
| 84 | /** |
| 85 | * A Fly.SecretKey is an App KMS key, not an env secret. Generate a |
| 86 | * random key or set raw material. Private bytes never appear in |
| 87 | * attributes. |
| 88 | * |
| 89 | * Use it at runtime with {@link Encrypt}, {@link Decrypt}, {@link Sign}, |
| 90 | * and {@link Verify}. Generate, set, and delete stay on this resource. |
| 91 | * |
| 92 | * @see https://docs.machines.dev/secrets/Secretkeys_list |
| 93 | * |
| 94 | * ### Generate a key |
| 95 | * Omit `value` and Fly generates a key via `generateSecretKey`. `type` |
| 96 | * is Fly's key type (`nacl_sign`, `nacl_box`, `nacl_secretbox`, |
| 97 | * `hs256`, `hs384`, `hs512`, `xaes256gcm`, `nacl_auth`, `es256`, …). |
| 98 | * |
| 99 | * **Example:** Signing key |
| 100 | * ```typescript |
| 101 | * export const Signing = Fly.SecretKey("Signing", { |
| 102 | * app: Site, |
| 103 | * type: "nacl_sign", |
| 104 | * }); |
| 105 | * ``` |
| 106 | * |
| 107 | * :::caution[Changing `app`, `name`, or `type` replaces the key] |
| 108 | * The new key is created. The old one is deleted. Ciphertext from the |
| 109 | * old key will not decrypt. |
| 110 | * ::: |
| 111 | * |
| 112 | * ### Set raw material |
| 113 | * Pass `value` as bytes. The key is created or updated with |
| 114 | * `setSecretKey`. Never persisted in state. |
| 115 | * |
| 116 | * **Example:** HS256 |
| 117 | * ```typescript |
| 118 | * const hmac = yield* Fly.SecretKey("Hmac", { |
| 119 | * app: Site, |
| 120 | * type: "hs256", |
| 121 | * value: hmacBytes, |
| 122 | * }); |
| 123 | * ``` |
| 124 | * |
| 125 | * ### Encrypt |
| 126 | * Bind {@link Encrypt} to a box/secretbox/AEAD key. Provide |
| 127 | * {@link EncryptHttp}. Optional `associatedData` is AEAD associated |
| 128 | * data. |
| 129 | * |
| 130 | * Fly crypto ops need a KMS token. Org API tokens are typed |
| 131 | * `Forbidden`. Encrypt and sign from a {@link Service}, not a laptop |
| 132 | * Action. |
| 133 | * |
| 134 | * **Example:** Encrypt a payload |
| 135 | * ```typescript |
| 136 | * const encrypt = yield* Fly.Encrypt(Box); |
| 137 | * const { ciphertext } = yield* encrypt({ |
| 138 | * plaintext: new TextEncoder().encode("attack at dawn"), |
| 139 | * }); |
| 140 | * ``` |
| 141 | * |
| 142 | * ### Decrypt |
| 143 | * Bind {@link Decrypt} to the same key. Plaintext comes back |
| 144 | * `Redacted`. Unwrap with `Redacted.value`. `associatedData` must |
| 145 | * match encryption. Provide {@link DecryptHttp}. |
| 146 | * |
| 147 | * **Example:** Decrypt a payload |
| 148 | * ```typescript |
| 149 | * const decrypt = yield* Fly.Decrypt(Box); |
| 150 | * const { plaintext } = yield* decrypt({ ciphertext }); |
| 151 | * const bytes = Redacted.value(plaintext); |
| 152 | * ``` |
| 153 | * |
| 154 | * ### Sign |
| 155 | * Bind {@link Sign} to a signing key (`nacl_sign`, `hs256`, `es256`, |
| 156 | * …). The private key never leaves Fly KMS. Provide {@link SignHttp}. |
| 157 | * |
| 158 | * **Example:** Sign a payload |
| 159 | * ```typescript |
| 160 | * const sign = yield* Fly.Sign(Signing); |
| 161 | * const { signature } = yield* sign({ |
| 162 | * plaintext: new TextEncoder().encode("release-manifest-v1"), |
| 163 | * }); |
| 164 | * ``` |
| 165 | * |
| 166 | * ### Verify |
| 167 | * Bind {@link Verify} to the same key. A bad signature is a typed |
| 168 | * error from the Machines API. Provide {@link VerifyHttp}. |
| 169 | * |
| 170 | * **Example:** Verify a signature |
| 171 | * ```typescript |
| 172 | * const verify = yield* Fly.Verify(Signing); |
| 173 | * const { valid } = yield* verify({ plaintext, signature }); |
| 174 | * ``` |
| 175 | * |
| 176 | * @resource |
| 177 | * @product Secret Key |
| 178 | */ |
| 179 | export const SecretKey: typeof SecretKeyResource = Object.assign( |
| 180 | (id: string, props: SecretKeyProps | Effect.Effect<SecretKeyProps, never, Providers>) => |
| 181 | SecretKeyResource(id, resolveSecretKeyProps(props)), |
| 182 | SecretKeyResource, |
| 183 | ); |
| 184 | |
| 185 | export class SecretKeyNotCreated extends Data.TaggedError("Fly.SecretKeyNotCreated")<{ |
| 186 | appName: string; |
| 187 | secretName: string; |
| 188 | }> {} |
| 189 | |
| 190 | export class SecretKeyAppRequired extends Data.TaggedError("Fly.SecretKeyAppRequired")<{ |
| 191 | message: string; |
| 192 | }> {} |
| 193 | |
| 194 | const appNameOf = (value: unknown): string | undefined => { |
| 195 | if (value === null || typeof value !== "object") return undefined; |
| 196 | const rec = value as { appName?: unknown }; |
| 197 | return typeof rec.appName === "string" && rec.appName.length > 0 ? rec.appName : undefined; |
| 198 | }; |
| 199 | |
| 200 | const resolveName = (id: string, name: string | undefined, existing?: string) => |
| 201 | Effect.gen(function* () { |
| 202 | if (name !== undefined) return sanitizeFlyVolumeName(name); |
| 203 | if (existing !== undefined) return existing; |
| 204 | return yield* createFlyVolumeName(id); |
| 205 | }); |
| 206 | |
| 207 | const toAttrs = ( |
| 208 | appName: string, |
| 209 | key: FlySecretKey, |
| 210 | fallbackName: string, |
| 211 | ): SecretKey["Attributes"] => ({ |
| 212 | appName, |
| 213 | name: key.name ?? fallbackName, |
| 214 | type: key.type, |
| 215 | publicKey: key.public_key, |
| 216 | createdAt: key.created_at, |
| 217 | updatedAt: key.updated_at, |
| 218 | }); |
| 219 | |
| 220 | const getByName = (appName: string, secretName: string) => |
| 221 | machines |
| 222 | .getSecretKey({ |
| 223 | app_name: appName, |
| 224 | secret_name: secretName, |
| 225 | }) |
| 226 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 227 | |
| 228 | const listKeys = (appName: string) => |
| 229 | machines.listSecretKeys({ app_name: appName }).pipe( |
| 230 | Effect.map((res) => res.secret_keys ?? []), |
| 231 | Effect.catchTag(["NotFound", "Forbidden"], () => Effect.succeed([])), |
| 232 | ); |
| 233 | |
| 234 | const putKey = (input: { |
| 235 | appName: string; |
| 236 | secretName: string; |
| 237 | type: string | undefined; |
| 238 | value: ReadonlyArray<number> | undefined; |
| 239 | }) => { |
| 240 | if (input.value !== undefined) { |
| 241 | return machines.setSecretKey({ |
| 242 | app_name: input.appName, |
| 243 | secret_name: input.secretName, |
| 244 | type: input.type, |
| 245 | value: [...input.value], |
| 246 | }); |
| 247 | } |
| 248 | return machines.generateSecretKey({ |
| 249 | app_name: input.appName, |
| 250 | secret_name: input.secretName, |
| 251 | type: input.type, |
| 252 | }); |
| 253 | }; |
| 254 | |
| 255 | const valuesEqual = ( |
| 256 | left: ReadonlyArray<number> | undefined, |
| 257 | right: ReadonlyArray<number> | undefined, |
| 258 | ): boolean => { |
| 259 | if (left === undefined && right === undefined) return true; |
| 260 | if (left === undefined || right === undefined) return false; |
| 261 | return deepEqual(left, right); |
| 262 | }; |
| 263 | |
| 264 | export const SecretKeyProvider = () => |
| 265 | Provider.succeed(SecretKey, { |
| 266 | stables: ["appName", "name", "type", "publicKey", "createdAt"], |
| 267 | nuke: { dependsOn: ["Fly.App"] }, |
| 268 | |
| 269 | diff: Effect.fn(function* ({ news, output }) { |
| 270 | if (news === undefined || !isResolved(news)) return undefined; |
| 271 | if (output === undefined) return undefined; |
| 272 | const desiredName = news.name !== undefined ? sanitizeFlyVolumeName(news.name) : output.name; |
| 273 | const nameChanged = desiredName !== output.name; |
| 274 | const nextApp = appNameOf(news.app); |
| 275 | const appChanged = nextApp !== undefined && nextApp !== output.appName; |
| 276 | const typeChanged = |
| 277 | news.type !== undefined && output.type !== undefined && news.type !== output.type; |
| 278 | if (nameChanged || appChanged || typeChanged) { |
| 279 | return { |
| 280 | action: "replace" as const, |
| 281 | // Same (app, name) cannot hold two types — delete first. |
| 282 | deleteFirst: !nameChanged && !appChanged, |
| 283 | }; |
| 284 | } |
| 285 | return undefined; |
| 286 | }), |
| 287 | |
| 288 | read: Effect.fn(function* ({ id, olds, output }) { |
| 289 | const appName = output?.appName ?? (olds !== undefined ? appNameOf(olds.app) : undefined); |
| 290 | if (appName === undefined) return undefined; |
| 291 | const name = yield* resolveName(id, olds?.name, output?.name); |
| 292 | const found = yield* getByName(appName, name); |
| 293 | if (found === undefined) return undefined; |
| 294 | const attrs = toAttrs(appName, found, name); |
| 295 | if (output !== undefined) return attrs; |
| 296 | return matchesAlchemyPhysicalName(name) ? attrs : Unowned(attrs); |
| 297 | }), |
| 298 | |
| 299 | list: Effect.fn(function* () { |
| 300 | const apps = yield* listOwnedApps(); |
| 301 | const rows = yield* Effect.forEach( |
| 302 | apps, |
| 303 | (app) => |
| 304 | listKeys(app.appName).pipe( |
| 305 | Effect.map((keys) => |
| 306 | keys.flatMap((key) => { |
| 307 | const name = key.name; |
| 308 | if (!matchesAlchemyPhysicalName(name)) return []; |
| 309 | return [toAttrs(app.appName, key, name ?? "")]; |
| 310 | }), |
| 311 | ), |
| 312 | ), |
| 313 | { concurrency: 8 }, |
| 314 | ); |
| 315 | return rows.flat(); |
| 316 | }), |
| 317 | |
| 318 | reconcile: Effect.fn(function* ({ id, news, olds, output }) { |
| 319 | const props = news ?? ({} as SecretKeyProps); |
| 320 | const appName = appNameOf(props.app) ?? output?.appName; |
| 321 | if (appName === undefined) { |
| 322 | return yield* new SecretKeyAppRequired({ |
| 323 | message: "SecretKey requires a resolved Fly.App", |
| 324 | }); |
| 325 | } |
| 326 | const name = yield* resolveName(id, props.name, output?.name); |
| 327 | |
| 328 | // Observe by cached identity, then the desired (app, name). |
| 329 | let current = |
| 330 | output !== undefined ? yield* getByName(output.appName, output.name) : undefined; |
| 331 | if ( |
| 332 | current === undefined && |
| 333 | (output === undefined || output.appName !== appName || output.name !== name) |
| 334 | ) { |
| 335 | current = yield* getByName(appName, name); |
| 336 | } |
| 337 | |
| 338 | if (current === undefined) { |
| 339 | yield* putKey({ |
| 340 | appName, |
| 341 | secretName: name, |
| 342 | type: props.type, |
| 343 | value: props.value, |
| 344 | }).pipe(Effect.catchTag("Conflict", () => Effect.void)); |
| 345 | current = yield* getByName(appName, name); |
| 346 | } |
| 347 | |
| 348 | if (current === undefined) { |
| 349 | return yield* new SecretKeyNotCreated({ appName, secretName: name }); |
| 350 | } |
| 351 | |
| 352 | // Sync — re-set when the caller supplied new material. Observed |
| 353 | // cloud never returns private bytes; `olds.value` is only a hint. |
| 354 | const desiredValue = props.value; |
| 355 | if (desiredValue !== undefined) { |
| 356 | const previousValue = olds?.value; |
| 357 | const shouldSet = previousValue === undefined || !valuesEqual(previousValue, desiredValue); |
| 358 | if (shouldSet) { |
| 359 | yield* putKey({ |
| 360 | appName, |
| 361 | secretName: name, |
| 362 | type: props.type ?? current.type, |
| 363 | value: desiredValue, |
| 364 | }).pipe(Effect.catchTag("Conflict", () => Effect.void)); |
| 365 | current = (yield* getByName(appName, name)) ?? current; |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | return toAttrs(appName, current, name); |
| 370 | }), |
| 371 | |
| 372 | delete: Effect.fn(function* ({ output }) { |
| 373 | if (output.appName.length === 0 || output.name.length === 0) return; |
| 374 | yield* machines |
| 375 | .deleteSecretKey({ |
| 376 | app_name: output.appName, |
| 377 | secret_name: output.name, |
| 378 | }) |
| 379 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 380 | yield* getByName(output.appName, output.name).pipe( |
| 381 | Effect.map((key) => key === undefined), |
| 382 | Effect.repeat({ |
| 383 | schedule: Schedule.spaced("1 second"), |
| 384 | until: (gone) => gone, |
| 385 | times: 8, |
| 386 | }), |
| 387 | ); |
| 388 | }), |
| 389 | }); |