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

main
ts 157 lines 5.89 KB
Raw
1 import * as Output from "alchemy/Output";
2 import { defaultProviderMode } from "alchemy/ProviderMode";
3 import { sha256 } from "alchemy/Util/sha256";
4 import * as Effect from "effect/Effect";
5 import * as Redacted from "effect/Redacted";
6 import { AccountApiToken } from "../ApiToken/AccountApiToken.ts";
7 import type { PermissionGroupRef, Policy } from "../ApiToken/Common.ts";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Worker } from "../Workers/Worker.ts";
10 import type { WorkerBinding } from "../Workers/WorkerBinding.ts";
11 import type { Bucket } from "./Bucket.ts";
12 import type { S3Credentials, S3CredentialsAccess, S3CredentialsValue } from "./S3Credentials.ts";
13
14 /**
15 * Deploy-time half of `Cloudflare.R2.S3Credentials`, shared by async Worker
16 * `env` declarations and the Effect-native bindings (`S3Credentials`,
17 * `PresignGetObjectToken`, `PresignPutObjectToken`).
18 *
19 * Binds `bindingName` on the host Worker to the JSON-encoded
20 * {@link S3CredentialsValue} for `bucket`:
21 *
22 * - **live** — mints (or extends) the Worker's {@link AccountApiToken} with
23 * a policy scoped to `bucket` (see {@link s3CredentialsPolicy}) and
24 * injects a `secret_text` binding. R2 derives S3 credentials from any API
25 * token: the access key id is the token id and the secret access key is
26 * the SHA-256 of the token value.
27 * - **local** (`alchemy dev`, `dev:` bucket) — injects the dev-only
28 * `r2_s3_credentials` binding. The local runtime lowers it to the Worker's
29 * local S3 endpoint and fixed local credentials, and serves the bucket on
30 * that endpoint. No token or cloud call is involved.
31 *
32 * NOT exported from `index.ts`.
33 */
34 export const bindS3Credentials = Effect.fn(function* (
35 host: Worker,
36 bindingName: string,
37 bucket: Bucket,
38 access: S3CredentialsAccess,
39 ) {
40 if (yield* isLocal(host, bucket)) {
41 yield* host.bind`${bindingName}`({
42 bindings: [
43 {
44 type: "r2_s3_credentials",
45 name: bindingName,
46 bucketName: bucket.bucketName,
47 },
48 ],
49 });
50 return;
51 }
52
53 const { accountId } = yield* yield* CloudflareEnvironment;
54 const token = yield* AccountApiToken(`${host.LogicalId}Token`);
55 // One binding id per bucket + access level: bindings sharing an id
56 // collapse to one, which would drop a write grant when a read binding
57 // targets the same bucket (and vice versa).
58 yield* token.bind`Cloudflare.R2.S3Credentials(${bucket.LogicalId}, ${access})`({
59 policies: [
60 Output.all(bucket.bucketName, bucket.jurisdiction).pipe(
61 Output.map(([bucketName, jurisdiction]) =>
62 s3CredentialsPolicy(accountId, bucketName, jurisdiction, access),
63 ),
64 ),
65 ],
66 });
67 const binding = Output.all(
68 token.tokenId,
69 token.value,
70 bucket.bucketName,
71 bucket.jurisdiction,
72 ).pipe(
73 Output.mapEffect(([tokenId, value, bucketName, jurisdiction]) =>
74 value.pipe(
75 Redacted.value,
76 sha256,
77 Effect.map((secretAccessKey): WorkerBinding => ({
78 type: "secret_text",
79 name: bindingName,
80 text: JSON.stringify({
81 endpoint: liveEndpoint(accountId, jurisdiction),
82 bucketName,
83 region: "auto",
84 accessKeyId: tokenId,
85 secretAccessKey,
86 } satisfies S3CredentialsValue),
87 })),
88 ),
89 ),
90 );
91 yield* host.bind`${bindingName}`({ bindings: [binding] });
92 });
93
94 /**
95 * A bucket, or its declaration (`Cloudflare.R2.Bucket("Uploads")`), which
96 * is resolved when the credentials are bound.
97 */
98 export type BucketInput = Bucket | Effect.Effect<Bucket, never, any>;
99
100 /** Resolve a {@link BucketInput} to the bucket resource. */
101 export const resolveBucket = (bucket: BucketInput) =>
102 (Effect.isEffect(bucket) ? bucket : Effect.succeed(bucket)) as Effect.Effect<Bucket>;
103
104 /**
105 * The token policy behind deployed `S3Credentials`: `access` to the objects of
106 * one bucket. Bucket-scoped groups on the bucket resource, because the
107 * account-level R2 groups would reach every bucket in the account.
108 *
109 * @see https://developers.cloudflare.com/r2/api/tokens/#bucket
110 */
111 export const s3CredentialsPolicy = (
112 accountId: string,
113 bucketName: string,
114 jurisdiction: Bucket.Jurisdiction,
115 access: S3CredentialsAccess,
116 ): Policy => ({
117 effect: "allow",
118 permissionGroups: PERMISSION_GROUPS[access],
119 resources: {
120 [`com.cloudflare.edge.r2.bucket.${accountId}_${jurisdiction}_${bucketName}`]: "*",
121 },
122 });
123
124 const PERMISSION_GROUPS: Record<S3CredentialsAccess, PermissionGroupRef[]> = {
125 read: ["Workers R2 Storage Bucket Item Read"],
126 write: ["Workers R2 Storage Bucket Item Write"],
127 "read-write": ["Workers R2 Storage Bucket Item Read", "Workers R2 Storage Bucket Item Write"],
128 };
129
130 export const liveEndpoint = (accountId: string, jurisdiction: Bucket.Jurisdiction): string =>
131 jurisdiction === "default"
132 ? `https://${accountId}.r2.cloudflarestorage.com`
133 : `https://${accountId}.${jurisdiction}.r2.cloudflarestorage.com`;
134
135 /**
136 * Whether both the Worker and the bucket are emulated locally in this run.
137 * Each resolves its own mode: pinned via `Alchemy.remote()` → live;
138 * otherwise the run default (`alchemy dev` → local).
139 */
140 const isLocal = (host: Worker, bucket: Bucket) =>
141 Effect.gen(function* () {
142 const runDefault = yield* defaultProviderMode;
143 return (host.Mode ?? runDefault) === "local" && (bucket.Mode ?? runDefault) === "local";
144 });
145
146 /**
147 * Whether an env value is a `Cloudflare.R2.S3Credentials` declaration (keyed
148 * on the static `~alchemy/Kind` marker — the value is also an Effect, so env
149 * resolution must check this before yielding Effects). Lives here, free of
150 * value imports from `Worker.ts`, so async env resolution can use it without
151 * a module cycle.
152 */
153 export const isS3Credentials = (value: unknown): value is S3Credentials =>
154 typeof value === "object" &&
155 value !== null &&
156 "~alchemy/Kind" in value &&
157 (value as S3Credentials)["~alchemy/Kind"] === "Cloudflare.R2.S3Credentials";