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

main
ts 416 lines 15.7 KB
Raw
1 import crypto from "node:crypto";
2 import { DEFAULT_COMPATIBILITY_DATE } from "@alchemy.run/cloudflare-runtime/core/internal/constants";
3 import { RuntimeContext } from "alchemy/RuntimeContext";
4 import {
5 BearerTokenValidator,
6 StateApi,
7 StateAuthLive,
8 StateStoreFailure,
9 } from "alchemy/State/HttpStateApi";
10 import { Redacted } from "effect";
11 import * as Effect from "effect/Effect";
12 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
13 import * as HttpApiError from "effect/http-api/HttpApiError";
14 import * as Etag from "effect/http/Etag";
15 import * as HttpPlatform from "effect/http/HttpPlatform";
16 import * as HttpRouter from "effect/http/HttpRouter";
17 import * as HttpServerRequest from "effect/http/HttpServerRequest";
18 import * as HttpServerResponse from "effect/http/HttpServerResponse";
19 import * as Layer from "effect/Layer";
20 import * as Path from "effect/Path";
21 import { ReadSecret } from "../SecretsStore/ReadSecret.ts";
22 import { ReadSecretBinding } from "../SecretsStore/ReadSecretBinding.ts";
23 import { Worker } from "../Workers/Worker.ts";
24 import Store, { retrySecretRead } from "./Store.ts";
25 import { AuthToken, DEFAULT_STATE_STORE_NAME, StateStoreName } from "./Token.ts";
26
27 export const STATE_STORE_SCRIPT_NAME = DEFAULT_STATE_STORE_NAME;
28
29 /**
30 * Version of the deployed Cloudflare State Store worker contract.
31 *
32 * Bump this whenever the wire format or runtime behaviour of the
33 * worker changes in a way that an older deployed copy can no longer
34 * satisfy. Clients query `/version` on the deployed worker and
35 * compare against this constant; a mismatch (or 404) triggers a
36 * forced redeploy via the bootstrap flow.
37 */
38 // v8: failures behind the auth middleware answer as a typed `StateStoreFailure`
39 // (v7 encoded them through `Unauthorized`'s schema and answered a bare 500),
40 // FQNs longer than 100 URI-encoded chars are routed, secret reads retry, and
41 // requests for the legacy bootstrap stack are refused.
42 export const STATE_STORE_VERSION = 8 as const;
43
44 /**
45 * The stack older Alchemy versions deployed the store itself with. Those
46 * versions redeploy a store they find out of date through this stack, and on a
47 * store whose rows are missing they generate a new auth token and encryption
48 * key and overwrite the existing secrets with them, losing all state. The
49 * Worker refuses every request for this stack, so such a redeploy fails while
50 * reading its state, before it touches a secret. Deleting the whole stack is
51 * the exception: bootstrap removes its records so it can't be destroyed.
52 */
53 const LEGACY_BOOTSTRAP_STACK = "CloudflareStateStore";
54
55 const isLegacyBootstrapRequest = (request: HttpServerRequest.HttpServerRequest) => {
56 const { pathname } = new URL(request.url, "http://store");
57 const match = new RegExp(`^/state/stacks/${LEGACY_BOOTSTRAP_STACK}(/.*)?$`).exec(pathname);
58 return match !== null && !(request.method === "DELETE" && match[1] === undefined);
59 };
60
61 const refuseLegacyBootstrap = <E, R>(
62 app: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
63 ) =>
64 Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) =>
65 isLegacyBootstrapRequest(request)
66 ? Effect.succeed(
67 HttpServerResponse.text(
68 `This Cloudflare State Store was deployed by a newer version of Alchemy. ` +
69 `Upgrade alchemy to use it.`,
70 { status: 409 },
71 ),
72 )
73 : app,
74 );
75
76 /**
77 * Hard-coded OTLP/HTTP endpoints. Point at the public ingest relay
78 * defined in `stacks/src/otel.ts` (bound to `otel.alchemy.run`), which
79 * forwards to Axiom with the bearer token attached server-side. Hard-
80 * coded on purpose: the worker has no env-var plumbing and the relay
81 * is account-level infra that lives outside any single deploy.
82 */
83 // const OTEL_TRACES_URL = "https://otel.alchemy.run/v1/traces";
84 // const OTEL_METRICS_URL = "https://otel.alchemy.run/v1/metrics";
85 // const OTEL_LOGS_URL = "https://otel.alchemy.run/v1/logs";
86
87 /**
88 * OTLP traces + metrics + logs Layer for the state-store worker.
89 * Mirrors the CLI's `TelemetryLive` so every signal the worker emits
90 * (`Effect.withSpan`, runtime metrics, `Effect.log*`) ships to the
91 * same Axiom datasets as deploy-time CLI signals. Resource attributes
92 * brand each signal with the worker's service name + contract version
93 * so they're easy to slice in Axiom.
94 */
95 // const otelResource = {
96 // serviceName: STATE_STORE_SCRIPT_NAME,
97 // serviceVersion: String(STATE_STORE_VERSION),
98 // attributes: {
99 // "alchemy.state_store.script_name": STATE_STORE_SCRIPT_NAME,
100 // "alchemy.state_store.version": STATE_STORE_VERSION,
101 // },
102 // } as const;
103
104 // const TelemetryLive = Layer.mergeAll(
105 // OtlpTracer.layer({
106 // url: OTEL_TRACES_URL,
107 // resource: otelResource,
108 // exportInterval: "1 second",
109 // }),
110 // OtlpMetrics.layer({
111 // url: OTEL_METRICS_URL,
112 // resource: otelResource,
113 // exportInterval: "1 second",
114 // }),
115 // // Replace (don't merge with) the default stdout logger so worker logs
116 // // ship to Axiom instead of just `wrangler tail`.
117 // OtlpLogger.layer({
118 // url: OTEL_LOGS_URL,
119 // resource: otelResource,
120 // exportInterval: "1 second",
121 // mergeWithExisting: false,
122 // }),
123 // ).pipe(
124 // Layer.provide(OtlpSerialization.layerJson),
125 // Layer.provide(FetchHttpClient.layer),
126 // );
127
128 /** This module, the state-store Worker's bundling entry (see `Deploy.ts`). */
129 export const API_MAIN = import.meta.url;
130
131 /**
132 * A failed Durable Object call, as the API's declared error: the operation and
133 * the kind of failure for the client, the full cause in the Worker's logs.
134 */
135 const failed =
136 (operation: string) =>
137 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, StateStoreFailure, R> =>
138 effect.pipe(
139 Effect.tapError((error) => Effect.logError(`State store ${operation} failed`, error)),
140 Effect.mapError((error) =>
141 StateStoreFailure.make({
142 operation,
143 reason:
144 typeof error === "object" && error !== null && "_tag" in error
145 ? String(error._tag)
146 : "UnknownError",
147 }),
148 ),
149 );
150
151 export default Worker(
152 "Api",
153 Effect.map(StateStoreName, (name) => ({
154 name,
155 main: API_MAIN,
156 workersDev: true,
157 compatibility: {
158 date: DEFAULT_COMPATIBILITY_DATE,
159 },
160 })),
161 Effect.gen(function* () {
162 const remoteSecret = yield* ReadSecret(AuthToken);
163 const store = yield* Store;
164
165 const bearerTokenValidator = Layer.succeed(
166 BearerTokenValidator,
167 BearerTokenValidator.of({
168 validate: Effect.fn(function* (token) {
169 const expected = yield* remoteSecret
170 .get()
171 .pipe(retrySecretRead, Effect.orDie, Effect.provide(RuntimeContext.phantom));
172 return !!expected && timingSafeEqual(token.trim(), Redacted.value(expected).trim())
173 ? yield* Effect.void
174 : yield* HttpApiError.Unauthorized.make({});
175 }),
176 }),
177 );
178
179 const versionApi = HttpApiBuilder.group(StateApi, "version", (handlers) =>
180 handlers.handle("getVersion", () =>
181 Effect.succeed({ version: STATE_STORE_VERSION }).pipe(
182 Effect.withSpan("state_store.getVersion", {
183 attributes: { "alchemy.state_store.op": "getVersion" },
184 }),
185 ),
186 ),
187 );
188
189 const stateApi = HttpApiBuilder.group(StateApi, "state", (handlers) =>
190 handlers
191 .handle("listStacks", () =>
192 store
193 .getByName(Store.ROOT_DO_NAME)
194 .listStacks()
195 .pipe(
196 failed("listStacks"),
197 Effect.withSpan("state_store.listStacks", {
198 attributes: { "alchemy.state_store.op": "listStacks" },
199 }),
200 ),
201 )
202 .handle("listStages", ({ params }) =>
203 store
204 .getByName(params.stack)
205 .listStages()
206 .pipe(
207 failed("listStages"),
208 Effect.withSpan("state_store.listStages", {
209 attributes: {
210 "alchemy.state_store.op": "listStages",
211 "alchemy.state_store.stack": params.stack,
212 },
213 }),
214 ),
215 )
216 .handle("listResources", ({ params }) =>
217 store
218 .getByName(params.stack)
219 .listResources({ stage: params.stage })
220 .pipe(
221 failed("listResources"),
222 Effect.withSpan("state_store.listResources", {
223 attributes: {
224 "alchemy.state_store.op": "listResources",
225 "alchemy.state_store.stack": params.stack,
226 "alchemy.state_store.stage": params.stage,
227 },
228 }),
229 ),
230 )
231 .handle("getState", ({ params }) => {
232 const fqn = decodeURIComponent(params.fqn);
233 return store
234 .getByName(params.stack)
235 .get({ stage: params.stage, fqn })
236 .pipe(
237 failed("getState"),
238 Effect.withSpan("state_store.getState", {
239 attributes: {
240 "alchemy.state_store.op": "getState",
241 "alchemy.state_store.stack": params.stack,
242 "alchemy.state_store.stage": params.stage,
243 "alchemy.state_store.fqn": fqn,
244 },
245 }),
246 );
247 })
248 .handle("setState", ({ params, payload }) => {
249 const fqn = decodeURIComponent(params.fqn);
250 return store
251 .getByName(params.stack)
252 .set({ stage: params.stage, fqn, value: payload as any })
253 .pipe(
254 Effect.tap(() =>
255 store.getByName(Store.ROOT_DO_NAME).registerStack({ stack: params.stack }),
256 ),
257 failed("setState"),
258 Effect.withSpan("state_store.setState", {
259 attributes: {
260 "alchemy.state_store.op": "setState",
261 "alchemy.state_store.stack": params.stack,
262 "alchemy.state_store.stage": params.stage,
263 "alchemy.state_store.fqn": fqn,
264 },
265 }),
266 );
267 })
268 .handle("deleteState", ({ params }) => {
269 const fqn = decodeURIComponent(params.fqn);
270 // The DO method is `remove`, not `delete` — `delete` is
271 // reserved by Cloudflare's RPC stub proxy.
272 return store
273 .getByName(params.stack)
274 .remove({ stage: params.stage, fqn })
275 .pipe(
276 Effect.asVoid,
277 failed("deleteState"),
278 Effect.withSpan("state_store.deleteState", {
279 attributes: {
280 "alchemy.state_store.op": "deleteState",
281 "alchemy.state_store.stack": params.stack,
282 "alchemy.state_store.stage": params.stage,
283 "alchemy.state_store.fqn": fqn,
284 },
285 }),
286 );
287 })
288 .handle("getReplacedResources", ({ params }) =>
289 store
290 .getByName(params.stack)
291 .getReplacedResources({ stage: params.stage })
292 .pipe(
293 failed("getReplacedResources"),
294 Effect.withSpan("state_store.getReplacedResources", {
295 attributes: {
296 "alchemy.state_store.op": "getReplacedResources",
297 "alchemy.state_store.stack": params.stack,
298 "alchemy.state_store.stage": params.stage,
299 },
300 }),
301 ),
302 )
303 .handle("getStackOutput", ({ params }) =>
304 store
305 .getByName(params.stack)
306 .getOutput({ stage: params.stage })
307 .pipe(
308 failed("getStackOutput"),
309 Effect.withSpan("state_store.getStackOutput", {
310 attributes: {
311 "alchemy.state_store.op": "getStackOutput",
312 "alchemy.state_store.stack": params.stack,
313 "alchemy.state_store.stage": params.stage,
314 },
315 }),
316 ),
317 )
318 .handle("setStackOutput", ({ params, payload }) =>
319 store
320 .getByName(params.stack)
321 .setOutput({ stage: params.stage, value: payload as any })
322 .pipe(
323 Effect.tap(() =>
324 store.getByName(Store.ROOT_DO_NAME).registerStack({ stack: params.stack }),
325 ),
326 failed("setStackOutput"),
327 Effect.withSpan("state_store.setStackOutput", {
328 attributes: {
329 "alchemy.state_store.op": "setStackOutput",
330 "alchemy.state_store.stack": params.stack,
331 "alchemy.state_store.stage": params.stage,
332 },
333 }),
334 ),
335 )
336 .handle("deleteStack", ({ params, query }) =>
337 store
338 .getByName(params.stack)
339 .deleteStack(query.stage === undefined ? {} : { stage: query.stage })
340 .pipe(
341 Effect.flatMap(() =>
342 query.stage === undefined
343 ? store.getByName(Store.ROOT_DO_NAME).unregisterStack({ stack: params.stack })
344 : Effect.void,
345 ),
346 Effect.asVoid,
347 failed("deleteStack"),
348 Effect.withSpan("state_store.deleteStack", {
349 attributes: {
350 "alchemy.state_store.op": "deleteStack",
351 "alchemy.state_store.stack": params.stack,
352 "alchemy.state_store.stage": query.stage ?? "",
353 "alchemy.state_store.scope": query.stage === undefined ? "stack" : "stage",
354 },
355 }),
356 ),
357 ),
358 );
359
360 return {
361 fetch: HttpApiBuilder.layer(StateApi).pipe(
362 Layer.provide(stateApi),
363 Layer.provide(versionApi),
364 Layer.provide(StateAuthLive),
365 Layer.provide(bearerTokenValidator),
366 // The state-store worker never serves files, so HttpPlatform's
367 // file-response surface is stubbed.
368 Layer.provide([Etag.layer, HttpPlatformStub, Path.layer]),
369 HttpRouter.toHttpEffect,
370 // An FQN travels as one URI-encoded path segment, and the router's
371 // default 100-char cap on a parameter left a longer one unrouted.
372 Effect.provideService(HttpRouter.RouterConfig, { maxParamLength: MAX_PARAM_LENGTH }),
373 Effect.map(refuseLegacyBootstrap),
374 // Effect.provide(TelemetryLive),
375 ),
376 };
377 }).pipe(Effect.provide(Layer.mergeAll(ReadSecretBinding))),
378 );
379
380 /**
381 * Longest path parameter the worker routes, within a Cloudflare URL's 16 KiB.
382 */
383 const MAX_PARAM_LENGTH = 16_384;
384
385 /**
386 * Stub `HttpPlatform` for the worker. The state-store API never
387 * issues file responses, so both surface methods die if invoked. Lets
388 * us avoid pulling in a `FileSystem` dependency that workers don't
389 * have.
390 */
391 const HttpPlatformStub = Layer.succeed(HttpPlatform.HttpPlatform, {
392 platform: "web",
393 // Advertises no algorithms, so the compression middleware never engages
394 // and compressResponse is never called.
395 compression: {
396 algorithms: new Set<HttpPlatform.CompressionAlgorithm>(),
397 compressResponse: (response) => Effect.succeed(response),
398 },
399 fileResponse: () => Effect.die("HttpPlatform.fileResponse not supported"),
400 fileWebResponse: () => Effect.die("HttpPlatform.fileWebResponse not supported"),
401 });
402
403 /**
404 * Timing-safe string comparison using the Workers runtime's built-in
405 * `crypto.subtle.timingSafeEqual`.
406 *
407 * @see https://developers.cloudflare.com/workers/examples/protect-against-timing-attacks/
408 */
409 const timingSafeEqual = (a: string, b: string): boolean => {
410 const encoder = new TextEncoder();
411 const aBytes = encoder.encode(a);
412 const bBytes = encoder.encode(b);
413 if (aBytes.byteLength !== bBytes.byteLength) return false;
414 // @ts-expect-error - TODO(sam)
415 return crypto.subtle.timingSafeEqual(aBytes, bBytes);
416 };