@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 194 lines 6.96 KB
Raw
1 import * as CoreBinding from "alchemy/Binding";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import { sanitizeKey } from "alchemy/RuntimeContext";
4 import * as Effect from "effect/Effect";
5 import { isWorker, type Worker, WorkerEnvironment } from "../Workers/Worker.ts";
6 import type { Bucket } from "./Bucket.ts";
7 import { bindS3Credentials, type BucketInput, resolveBucket } from "./S3CredentialsBinding.ts";
8
9 export { isS3Credentials } from "./S3CredentialsBinding.ts";
10
11 /** Which object operations the credentials' API token is granted. */
12 export type S3CredentialsAccess = "read" | "write" | "read-write";
13
14 export interface S3CredentialsOptions {
15 /**
16 * Object operations the credentials may perform. Deployed, this selects
17 * the permission groups of the bucket-scoped API token they are derived
18 * from (`Workers R2 Storage Bucket Item Read` and/or
19 * `Workers R2 Storage Bucket Item Write`).
20 */
21 access: S3CredentialsAccess;
22 }
23
24 /**
25 * S3 API credentials and endpoint for one R2 bucket, as delivered to the
26 * Worker. Use them with any S3 client (`aws4fetch`, `@aws-sdk/client-s3`)
27 * with path-style addressing: `{endpoint}/{bucketName}/{key}`.
28 */
29 export interface S3CredentialsValue {
30 /**
31 * S3 endpoint, without the bucket: `https://{accountId}.r2.cloudflarestorage.com`
32 * when deployed, `{worker url}/cdn-cgi/local/r2/s3` under `alchemy dev`.
33 */
34 endpoint: string;
35 /** Bucket name — the path segment after the endpoint. */
36 bucketName: string;
37 /** SigV4 signing region. */
38 region: "auto";
39 accessKeyId: string;
40 secretAccessKey: string;
41 }
42
43 /**
44 * The value returned by {@link S3Credentials}: declarable on an async
45 * Worker's `env` (where it arrives as a JSON string) and `yield*`-able in an
46 * Effect-native Worker (where it resolves to a deferred accessor).
47 */
48 export interface S3Credentials extends Effect.Effect<
49 Effect.Effect<S3CredentialsValue, never, RuntimeContext>,
50 never,
51 WorkerEnvironment
52 > {
53 readonly "~alchemy/Kind": "Cloudflare.R2.S3Credentials";
54 readonly bucket: BucketInput;
55 readonly access: S3CredentialsAccess;
56 }
57
58 /**
59 * S3 API credentials for an R2 bucket that work unchanged in `alchemy dev`
60 * and when deployed — for presigned URLs or any S3 client.
61 *
62 * The native R2 binding cannot presign or speak the S3 API: that requires S3
63 * credentials and R2's S3 endpoint. `S3Credentials` provides both, resolved
64 * per mode:
65 *
66 * - **Deployed** — Alchemy mints an account API token for the Worker whose
67 * policy is scoped to this bucket only, and derives S3 credentials from it
68 * (access key id = token id, secret = SHA-256 of the token value). The
69 * endpoint is
70 * `https://{accountId}.r2.cloudflarestorage.com` (`.eu.`/`.fedramp.` for
71 * jurisdictional buckets). The value is injected as a secret.
72 * - **`alchemy dev`** — a locally-emulated bucket is served on the Worker's
73 * local S3 endpoint (`{worker url}/cdn-cgi/local/r2/s3`) with fixed local
74 * credentials. No token or cloud call is involved, and objects are shared
75 * with the Worker's native bindings of the bucket.
76 *
77 * The Effect-native presign bindings (`PresignGetObjectToken`,
78 * `PresignPutObjectToken`) are built on it.
79 *
80 * ### Effect-native Workers
81 * **Example:** Read the credentials at runtime
82 * ```typescript
83 * const credentials = yield* Cloudflare.R2.S3Credentials(Uploads, {
84 * access: "read-write",
85 * });
86 * // inside a handler:
87 * const { endpoint, bucketName, accessKeyId, secretAccessKey } =
88 * yield* credentials;
89 * ```
90 *
91 * ### Async Workers
92 * **Example:** Presign an upload with aws4fetch
93 * ```typescript
94 * // alchemy.run.ts
95 * export const Uploads = Cloudflare.R2.Bucket("Uploads");
96 * export const Api = Cloudflare.Worker("Api", {
97 * main: "./src/worker.ts",
98 * env: {
99 * UPLOADS_S3: Cloudflare.R2.S3Credentials(Uploads, { access: "write" }),
100 * },
101 * });
102 * export type ApiEnv = Cloudflare.InferEnv<typeof Api>;
103 *
104 * // src/worker.ts
105 * import { AwsClient } from "aws4fetch";
106 * import type * as Cloudflare from "@alchemy.run/cloudflare";
107 * import type { ApiEnv } from "../alchemy.run.ts";
108 *
109 * export default {
110 * async fetch(request: Request, env: ApiEnv) {
111 * // `UPLOADS_S3` is a JSON string (a secret when deployed)
112 * const s3: Cloudflare.R2.S3CredentialsValue = JSON.parse(env.UPLOADS_S3);
113 * const client = new AwsClient({ ...s3, service: "s3" });
114 * const url = new URL(`${s3.endpoint}/${encodeURIComponent(s3.bucketName)}/avatar.png`);
115 * url.searchParams.set("X-Amz-Expires", "900");
116 * const signed = await client.sign(url.toString(), {
117 * method: "PUT",
118 * aws: { signQuery: true },
119 * });
120 * return Response.json({ url: signed.url });
121 * },
122 * };
123 * ```
124 *
125 * @binding
126 * @product R2
127 * @category Storage & Databases
128 */
129 export const S3Credentials = (
130 bucket: BucketInput,
131 options: S3CredentialsOptions,
132 ): S3Credentials => {
133 const { access } = options;
134 return Object.assign(
135 Effect.gen(function* () {
136 const host = yield* CoreBinding.Host;
137 return yield* makeS3Credentials(
138 isWorker(host) ? host : undefined,
139 yield* WorkerEnvironment,
140 yield* resolveBucket(bucket),
141 access,
142 );
143 }),
144 {
145 "~alchemy/Kind": "Cloudflare.R2.S3Credentials" as const,
146 bucket,
147 access,
148 },
149 );
150 };
151
152 /**
153 * Bind {@link S3Credentials} for `bucket` on `host` (deploy time) and return
154 * the runtime accessor. `host` is only read at deploy time; it is
155 * `undefined` inside the deployed Worker.
156 *
157 * NOT exported from `index.ts`.
158 */
159 export const makeS3Credentials = (
160 host: Worker | undefined,
161 env: WorkerEnvironment["Service"],
162 bucket: Bucket,
163 access: S3CredentialsAccess,
164 ) =>
165 Effect.gen(function* () {
166 const bindingName = sanitizeKey(
167 `R2_S3_CREDENTIALS_${bucket.LogicalId}_${access}`,
168 ).toUpperCase();
169 if (!globalThis.__ALCHEMY_RUNTIME__) {
170 if (host === undefined) {
171 return yield* Effect.die(
172 new Error(
173 `Cloudflare.R2.S3Credentials(${bucket.LogicalId}) can only be bound to a Cloudflare Worker.`,
174 ),
175 );
176 }
177 // Deploy-time only; its requirements (CloudflareEnvironment, the
178 // token provider) are ambient wherever a Worker is evaluated, so they
179 // are erased like `Binding.Host`'s.
180 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- deploy-time only; requirements are ambient where the Worker is evaluated
181 yield* bindS3Credentials(host, bindingName, bucket, access) as Effect.Effect<void>;
182 }
183 // Captured at init; read at exec phase, where it is populated.
184 return Effect.suspend(() => {
185 const raw = (env as Record<string, unknown>)[bindingName];
186 return typeof raw === "string"
187 ? Effect.succeed(JSON.parse(raw) as S3CredentialsValue)
188 : Effect.die(
189 new Error(
190 `Cloudflare.R2.S3Credentials(${bucket.LogicalId}) is not bound to this Worker: missing "${bindingName}".`,
191 ),
192 );
193 }) as Effect.Effect<S3CredentialsValue, never, RuntimeContext>;
194 });