The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeChildProcess from "node:child_process"; |
| 2 | import * as NodeNet from "node:net"; |
| 3 | import { Docker } from "@alchemy.run/docker"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as HttpClient from "effect/http/HttpClient"; |
| 7 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 8 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 9 | import * as Path from "effect/Path"; |
| 10 | import * as Redacted from "effect/Redacted"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | |
| 13 | const swarmLocalNodeState = (): string | undefined => { |
| 14 | const result = NodeChildProcess.spawnSync( |
| 15 | "docker", |
| 16 | ["info", "--format", "{{.Swarm.LocalNodeState}}"], |
| 17 | { stdio: ["ignore", "pipe", "ignore"] }, |
| 18 | ); |
| 19 | return result.status === 0 ? String(result.stdout).trim() : undefined; |
| 20 | }; |
| 21 | |
| 22 | /** |
| 23 | * Idempotently provision the local single-node swarm the `Docker.Service` |
| 24 | * tests deploy to. A single-node manager on the local engine is harmless — |
| 25 | * regular (non-swarm) docker usage is unaffected — and stays active across |
| 26 | * runs so repeated invocations are a no-op. Deactivate manually with |
| 27 | * `docker swarm leave --force`. |
| 28 | * |
| 29 | * Concurrent test files race the init; the loser's "already part of a swarm" |
| 30 | * error is folded into success by re-checking the node state. |
| 31 | */ |
| 32 | export const ensureDockerSwarm: Effect.Effect<void, Error> = Effect.suspend(() => { |
| 33 | if (swarmLocalNodeState() === "active") return Effect.void; |
| 34 | const init = NodeChildProcess.spawnSync( |
| 35 | "docker", |
| 36 | // 127.0.0.1 keeps init deterministic on hosts with several network |
| 37 | // interfaces (init otherwise refuses to pick an advertise address). |
| 38 | ["swarm", "init", "--advertise-addr", "127.0.0.1"], |
| 39 | { stdio: ["ignore", "ignore", "pipe"] }, |
| 40 | ); |
| 41 | if (init.status === 0 || swarmLocalNodeState() === "active") { |
| 42 | return Effect.void; |
| 43 | } |
| 44 | return Effect.fail(new Error(`docker swarm init failed: ${String(init.stderr).trim()}`)); |
| 45 | }); |
| 46 | |
| 47 | export const findAvailablePort = () => |
| 48 | Effect.callback<number, Error>((resume) => { |
| 49 | const server = NodeNet.createServer(); |
| 50 | server.unref(); |
| 51 | server.on("error", (error) => resume(Effect.fail(error))); |
| 52 | server.listen(0, "127.0.0.1", () => { |
| 53 | const address = server.address(); |
| 54 | const port = typeof address === "object" && address ? address.port : undefined; |
| 55 | server.close((error) => { |
| 56 | if (error) { |
| 57 | resume(Effect.fail(error)); |
| 58 | } else if (port) { |
| 59 | resume(Effect.succeed(port)); |
| 60 | } else { |
| 61 | resume(Effect.fail(new Error("Failed to allocate a free host port"))); |
| 62 | } |
| 63 | }); |
| 64 | }); |
| 65 | }); |
| 66 | |
| 67 | // bcrypt htpasswd entry for alchemy:alchemy-test-password (`htpasswd -Bbn`). |
| 68 | const REGISTRY_HTPASSWD = "alchemy:$2y$05$7OoaHcebvt.2oLcNt7oRsOOALGNXUWi8IHUxTMRu9BWyXWDgM/3BK"; |
| 69 | |
| 70 | /** |
| 71 | * Run an htpasswd-protected `registry:2` on a free localhost port for the |
| 72 | * current scope. Anonymous requests get `401`, and nothing on the host holds |
| 73 | * a `docker login` for the ephemeral port, so every pull/push must carry the |
| 74 | * returned `credentials`. |
| 75 | */ |
| 76 | export const authenticatedRegistry = Effect.fn(function* () { |
| 77 | const docker = yield* Docker; |
| 78 | const client = yield* HttpClient.HttpClient; |
| 79 | const port = yield* findAvailablePort(); |
| 80 | const host = `localhost:${port}`; |
| 81 | const name = `alchemy-test-registry-${port}`; |
| 82 | yield* Effect.addFinalizer(() => docker.run(["rm", "-f", name]).pipe(Effect.ignore)); |
| 83 | yield* docker.run([ |
| 84 | "run", |
| 85 | "-d", |
| 86 | "--name", |
| 87 | name, |
| 88 | "-p", |
| 89 | `${port}:5000`, |
| 90 | "-e", |
| 91 | `HTPASSWD=${REGISTRY_HTPASSWD}`, |
| 92 | "-e", |
| 93 | "REGISTRY_AUTH=htpasswd", |
| 94 | "-e", |
| 95 | "REGISTRY_AUTH_HTPASSWD_REALM=alchemy-test", |
| 96 | "-e", |
| 97 | "REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd", |
| 98 | "--entrypoint", |
| 99 | "/bin/sh", |
| 100 | "registry:2", |
| 101 | "-c", |
| 102 | 'mkdir -p /auth && echo "$HTPASSWD" > /auth/htpasswd && exec registry serve /etc/docker/registry/config.yml', |
| 103 | ]); |
| 104 | // Any HTTP response (an anonymous 401) means the registry is serving. |
| 105 | yield* client |
| 106 | .get(`http://${host}/v2/`) |
| 107 | .pipe(Effect.retry({ schedule: Schedule.exponential("250 millis"), times: 20 })); |
| 108 | |
| 109 | const credentials = { |
| 110 | server: host, |
| 111 | username: "alchemy", |
| 112 | password: Redacted.make("alchemy-test-password"), |
| 113 | }; |
| 114 | const basic = Buffer.from("alchemy:alchemy-test-password").toString("base64"); |
| 115 | |
| 116 | /** Whether `repository:tag` was published, checked over the registry API. */ |
| 117 | const hasManifest = (repository: string, tag: string) => |
| 118 | client |
| 119 | .execute( |
| 120 | HttpClientRequest.head(`http://${host}/v2/${repository}/manifests/${tag}`).pipe( |
| 121 | HttpClientRequest.setHeaders({ |
| 122 | authorization: `Basic ${basic}`, |
| 123 | accept: [ |
| 124 | "application/vnd.oci.image.index.v1+json", |
| 125 | "application/vnd.oci.image.manifest.v1+json", |
| 126 | "application/vnd.docker.distribution.manifest.list.v2+json", |
| 127 | "application/vnd.docker.distribution.manifest.v2+json", |
| 128 | ].join(", "), |
| 129 | }), |
| 130 | ), |
| 131 | ) |
| 132 | .pipe(Effect.map((response) => response.status === 200)); |
| 133 | |
| 134 | return { host, credentials, hasManifest }; |
| 135 | }); |
| 136 | |
| 137 | /** |
| 138 | * Run an anonymous `registry:2` on a free localhost port for the current |
| 139 | * scope, so plain `docker pull` (no credentials) can fetch what was pushed. |
| 140 | */ |
| 141 | export const localRegistry = Effect.fn(function* () { |
| 142 | const docker = yield* Docker; |
| 143 | const client = yield* HttpClient.HttpClient; |
| 144 | const port = yield* findAvailablePort(); |
| 145 | const host = `localhost:${port}`; |
| 146 | const name = `alchemy-test-registry-${port}`; |
| 147 | yield* Effect.addFinalizer(() => docker.run(["rm", "-f", name]).pipe(Effect.ignore)); |
| 148 | yield* docker.run(["run", "-d", "--name", name, "-p", `${port}:5000`, "registry:2"]); |
| 149 | yield* client |
| 150 | .get(`http://${host}/v2/`) |
| 151 | .pipe(Effect.retry({ schedule: Schedule.exponential("250 millis"), times: 7 })); |
| 152 | |
| 153 | const credentials = { |
| 154 | server: host, |
| 155 | username: "alchemy", |
| 156 | password: Redacted.make("ignored-by-insecure-registry"), |
| 157 | }; |
| 158 | |
| 159 | /** The published manifest digest of `repository:tag`, read over the registry API. */ |
| 160 | const manifestDigest = (repository: string, tag: string) => |
| 161 | client |
| 162 | .execute( |
| 163 | HttpClientRequest.head(`http://${host}/v2/${repository}/manifests/${tag}`).pipe( |
| 164 | HttpClientRequest.setHeader( |
| 165 | "accept", |
| 166 | [ |
| 167 | "application/vnd.oci.image.index.v1+json", |
| 168 | "application/vnd.oci.image.manifest.v1+json", |
| 169 | "application/vnd.docker.distribution.manifest.list.v2+json", |
| 170 | "application/vnd.docker.distribution.manifest.v2+json", |
| 171 | ].join(", "), |
| 172 | ), |
| 173 | ), |
| 174 | ) |
| 175 | .pipe( |
| 176 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 177 | Effect.map((response) => response.headers["docker-content-digest"]), |
| 178 | ); |
| 179 | |
| 180 | return { host, credentials, manifestDigest }; |
| 181 | }); |
| 182 | |
| 183 | const buildxAsset = (version: string) => |
| 184 | Effect.sync(() => { |
| 185 | const os = process.platform === "win32" ? "windows" : process.platform; |
| 186 | const arch = process.arch === "x64" ? "amd64" : process.arch; |
| 187 | return `buildx-${version}.${os}-${arch}${os === "windows" ? ".exe" : ""}`; |
| 188 | }); |
| 189 | |
| 190 | /** |
| 191 | * Point the Docker CLI at a scratch `DOCKER_CONFIG` for the current scope so |
| 192 | * the version-dependent publish path runs against a real Buildx plugin of |
| 193 | * the given release — or against no plugin at all when `version` is |
| 194 | * `undefined`. The release binary is downloaded once into |
| 195 | * `.alchemy/cache/buildx`. The daemon is unchanged: `DOCKER_HOST` pins the |
| 196 | * current context's endpoint, which the scratch config would otherwise lose. |
| 197 | * |
| 198 | * Mutates `process.env`; tests using it must be `exclusive`. |
| 199 | */ |
| 200 | export const scopedBuildx = Effect.fn(function* (version: string | undefined) { |
| 201 | const docker = yield* Docker; |
| 202 | const fs = yield* FileSystem.FileSystem; |
| 203 | const path = yield* Path.Path; |
| 204 | const client = yield* HttpClient.HttpClient; |
| 205 | |
| 206 | const endpoint = (yield* docker.run([ |
| 207 | "context", |
| 208 | "inspect", |
| 209 | "--format", |
| 210 | "{{.Endpoints.docker.Host}}", |
| 211 | ])).stdout.trim(); |
| 212 | const config = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-test-docker-config-" }); |
| 213 | |
| 214 | if (version !== undefined) { |
| 215 | const asset = yield* buildxAsset(version); |
| 216 | const cwd = yield* Effect.sync(() => process.cwd()); |
| 217 | const cached = path.join(cwd, ".alchemy", "cache", "buildx", asset); |
| 218 | if (!(yield* fs.exists(cached))) { |
| 219 | const response = yield* client |
| 220 | .get(`https://github.com/docker/buildx/releases/download/${version}/${asset}`) |
| 221 | .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); |
| 222 | const bytes = new Uint8Array(yield* response.arrayBuffer); |
| 223 | yield* fs.makeDirectory(path.dirname(cached), { recursive: true }); |
| 224 | yield* fs.writeFile(`${cached}.partial`, bytes); |
| 225 | yield* fs.chmod(`${cached}.partial`, 0o755); |
| 226 | yield* fs.rename(`${cached}.partial`, cached); |
| 227 | } |
| 228 | yield* fs.makeDirectory(path.join(config, "cli-plugins")); |
| 229 | yield* fs.symlink(cached, path.join(config, "cli-plugins", "docker-buildx")); |
| 230 | } |
| 231 | |
| 232 | yield* Effect.acquireRelease( |
| 233 | Effect.sync(() => { |
| 234 | const previous = { |
| 235 | DOCKER_CONFIG: process.env.DOCKER_CONFIG, |
| 236 | DOCKER_HOST: process.env.DOCKER_HOST, |
| 237 | }; |
| 238 | process.env.DOCKER_CONFIG = config; |
| 239 | process.env.DOCKER_HOST = endpoint; |
| 240 | return previous; |
| 241 | }), |
| 242 | (previous) => |
| 243 | Effect.sync(() => { |
| 244 | for (const [key, value] of Object.entries(previous)) { |
| 245 | if (value === undefined) delete process.env[key]; |
| 246 | else process.env[key] = value; |
| 247 | } |
| 248 | }), |
| 249 | ); |
| 250 | |
| 251 | // Verify the pin took: the CLI now reports exactly this plugin (or none). |
| 252 | const probe = yield* docker.run(["buildx", "version"]).pipe(Effect.option); |
| 253 | if ( |
| 254 | version === undefined |
| 255 | ? probe._tag === "Some" |
| 256 | : probe._tag === "None" || !probe.value.stdout.includes(` ${version} `) |
| 257 | ) { |
| 258 | return yield* Effect.die( |
| 259 | new Error( |
| 260 | version === undefined |
| 261 | ? "A system-wide Buildx plugin is installed; cannot exercise the no-Buildx path on this host." |
| 262 | : `Expected Buildx ${version} from ${config}/cli-plugins`, |
| 263 | ), |
| 264 | ); |
| 265 | } |
| 266 | return { config }; |
| 267 | }); |