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

main
ts 198 lines 7.29 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as secretsStore from "@distilled.cloud/cloudflare/secrets-store";
6 import * as Alchemy from "alchemy";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as Redacted from "effect/Redacted";
11 import { MinimumLogLevel } from "effect/References";
12 import * as Schedule from "effect/Schedule";
13 import * as pathe from "pathe";
14
15 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
16 // matching the process topology of the real `alchemy dev` command (see
17 // MakeOptions.sidecar in Test/Core.ts).
18 const { test } = Test.make({
19 providers: Cloudflare.providers(),
20 dev: true,
21 });
22
23 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
24
25 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
26 status: number;
27 }> {}
28
29 const getJsonReady = (url: string) =>
30 Effect.gen(function* () {
31 const client = yield* HttpClient.HttpClient;
32 const res = yield* client.get(url).pipe(
33 Effect.flatMap((res) =>
34 res.status === 200
35 ? Effect.succeed(res)
36 : Effect.fail(new WorkerNotReady({ status: res.status })),
37 ),
38 Effect.retry({
39 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
40 // Cap the backoff: an uncapped exponential over 10 recurs sums to
41 // ~8.5 minutes and turns a persistent non-200 into an apparent hang.
42 schedule: Schedule.max([
43 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
44 Schedule.recurs(10),
45 ]),
46 }),
47 );
48 return yield* res.json;
49 }).pipe(Effect.orDie);
50
51 /**
52 * Under `alchemy dev` the Store and Secret resources are emulated by the
53 * local providers (`dev:` ids, no cloud API calls): the Secret's reconcile
54 * seeds its value into the local workerd Secrets Store simulator through
55 * the admin gateway, and the worker's `secrets_store_secret` binding is
56 * lowered onto the local secrets-store service, so `env.SECRET.get()`
57 * returns the seeded value. A value update re-seeds the same key
58 * (idempotent overwrite) and the worker sees the new value after redeploy.
59 */
60 test.provider(
61 "secrets store secret round-trips against the local simulator",
62 (stack) =>
63 Effect.gen(function* () {
64 yield* stack.destroy();
65
66 const deployAt = (value: string) =>
67 Effect.gen(function* () {
68 const store = yield* Cloudflare.SecretsStore.Store("LocalSecretsStore");
69 const secret = yield* Cloudflare.SecretsStore.Secret("LocalApiKey", {
70 store,
71 value: Redacted.make(value),
72 });
73 const worker = yield* Cloudflare.Worker("secrets-local-worker", {
74 main: pathe.resolve(import.meta.dirname, "fixtures/secrets-local-worker.ts"),
75 env: { SECRET: secret },
76 });
77 return { store, secret, worker };
78 });
79
80 const v1 = yield* stack.deploy(deployAt("sk-local-value-1"));
81
82 // The local providers fabricate `dev:` ids — proof no cloud call ran
83 // — and the worker serves from the local dev proxy.
84 expect(v1.store.storeId).toMatch(/^dev:/);
85 expect(v1.secret.secretId).toMatch(/^dev:/);
86 expect(v1.secret.storeId).toBe(v1.store.storeId);
87 expect(v1.secret.status).toBe("active");
88 expect(v1.worker.url).toMatch(/^http:\/\/localhost:\d+$/);
89
90 const body1 = (yield* getJsonReady(`${v1.worker.url}/secret`)) as {
91 value: string;
92 };
93 expect(body1.value).toBe("sk-local-value-1");
94
95 // Update the value — same identity, re-seeded key.
96 const v2 = yield* stack.deploy(deployAt("sk-local-value-2"));
97 expect(v2.secret.secretId).toBe(v1.secret.secretId);
98 expect(v2.secret.storeId).toBe(v1.secret.storeId);
99
100 const body2 = (yield* getJsonReady(`${v2.worker.url}/secret`)) as {
101 value: string;
102 };
103 expect(body2.value).toBe("sk-local-value-2");
104
105 yield* stack.destroy();
106 }).pipe(logLevel),
107 {
108 tags: [
109 "provider:cloudflare",
110 "provider:cloudflare:secretsstore",
111 "provider:cloudflare:worker",
112 "local",
113 ],
114 timeout: 180_000,
115 },
116 );
117
118 /**
119 * `Alchemy.remote()` opts the resources OUT of local emulation: even under
120 * `alchemy dev` the store/secret are created on real Cloudflare (live
121 * providers) and the worker's binding proxies to the live secret remotely.
122 * Out-of-band reads through the cloud API prove the secret landed in the
123 * real store, and destroy (driven by the stamped `live` provider mode)
124 * removes it again.
125 */
126 test.provider(
127 "Alchemy.remote() secret runs live in dev",
128 (stack) =>
129 Effect.gen(function* () {
130 yield* stack.destroy();
131
132 const deployed = yield* stack.deploy(
133 Effect.gen(function* () {
134 const store = yield* Cloudflare.SecretsStore.Store("RemoteSecretsStore").pipe(
135 Alchemy.remote(),
136 );
137 const secret = yield* Cloudflare.SecretsStore.Secret("RemoteDevApiKey", {
138 store,
139 value: Redacted.make("sk-remote-dev-value"),
140 }).pipe(Alchemy.remote());
141 const worker = yield* Cloudflare.Worker("secrets-remote-worker", {
142 main: pathe.resolve(import.meta.dirname, "fixtures/secrets-local-worker.ts"),
143 env: { SECRET: secret },
144 });
145 return { store, secret, worker };
146 }),
147 );
148
149 // Real (non-`dev:`) identities — the live providers ran.
150 expect(deployed.store.storeId).not.toMatch(/^dev:/);
151 expect(deployed.secret.secretId).not.toMatch(/^dev:/);
152 expect(deployed.secret.storeId).toBe(deployed.store.storeId);
153
154 // The locally-served worker reads the live secret through the
155 // remote-proxied binding.
156 const body = (yield* getJsonReady(`${deployed.worker.url}/secret`)) as {
157 value: string;
158 };
159 expect(body.value).toBe("sk-remote-dev-value");
160
161 // Out-of-band: the secret exists in the real store.
162 const { accountId } = yield* yield* CloudflareEnvironment;
163 const live = yield* secretsStore.getStoreSecret({
164 accountId,
165 storeId: deployed.secret.storeId,
166 secretId: deployed.secret.secretId,
167 });
168 expect(live.name).toBe(deployed.secret.secretName);
169
170 yield* stack.destroy();
171
172 // The secret was deleted from the cloud on destroy (its state row is
173 // stamped live, so the live provider handles the delete even in a
174 // dev run). The store itself is account-level infrastructure whose
175 // delete is an intentional no-op.
176 const gone = yield* secretsStore
177 .getStoreSecret({
178 accountId,
179 storeId: deployed.secret.storeId,
180 secretId: deployed.secret.secretId,
181 })
182 .pipe(
183 Effect.as(false),
184 Effect.catchTag("SecretNotFound", () => Effect.succeed(true)),
185 Effect.catchTag("StoreNotFound", () => Effect.succeed(true)),
186 );
187 expect(gone).toBe(true);
188 }).pipe(logLevel),
189 {
190 tags: [
191 "provider:cloudflare",
192 "provider:cloudflare:secretsstore",
193 "provider:cloudflare:worker",
194 "live",
195 ],
196 timeout: 180_000,
197 },
198 );