@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, 04:45 UTC

main
ts 211 lines 7.29 KB
Raw
1 import type { RuntimeContext } from "alchemy/RuntimeContext";
2 import { Self } from "alchemy/Self";
3 import * as Effect from "effect/Effect";
4 import type * as HttpClient from "effect/http/HttpClient";
5 import type * as Redacted from "effect/Redacted";
6 import * as Stream from "effect/Stream";
7 import { AccountApiToken } from "../ApiToken/AccountApiToken.ts";
8 import type { PermissionGroupRef } from "../ApiToken/Common.ts";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Credentials } from "../Credentials.ts";
11 import { requireLiveResource } from "../HttpBindingDev.ts";
12 import type { Bucket } from "./Bucket.ts";
13 import { R2Error, type R2Object } from "./BucketTypes.ts";
14
15 /**
16 * Injectable auth used by the R2 HTTP client builders. Both the token-scoped
17 * `*Http` layers and the current-credentials `*Local` layers build one of
18 * these so they can share the exact same client implementation.
19 */
20 export interface R2Auth {
21 /** Provide credentials + HTTP client to a raw distilled R2 op. */
22 authorize: <A, E>(
23 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
24 ) => Effect.Effect<A, E, RuntimeContext>;
25 /** Resolve the Cloudflare account id. */
26 accountId: Effect.Effect<string>;
27 }
28
29 export const makeHttpBucketBinding = <Client>(options: {
30 permissionGroups: PermissionGroup[];
31 makeClient: (
32 token: HttpToken,
33 bucketName: Effect.Effect<string>,
34 jurisdiction: Effect.Effect<string>,
35 ) => Client;
36 }) =>
37 Effect.gen(function* () {
38 const Token = yield* AccountApiToken;
39 const self = yield* Self;
40
41 return Effect.fn(function* (bucket: Bucket) {
42 if (!globalThis.__ALCHEMY_RUNTIME__) yield* requireLiveResource(bucket);
43 const token = yield* Token(`${self.LogicalId}Token`);
44 if (!globalThis.__ALCHEMY_RUNTIME__) {
45 const { accountId } = yield* CloudflareEnvironment.current;
46 yield* token.bind`${bucket.LogicalId}`({
47 policies: [
48 {
49 effect: "allow",
50 permissionGroups: options.permissionGroups,
51 resources: {
52 [`com.cloudflare.api.account.${accountId}`]: "*",
53 },
54 },
55 ],
56 });
57 }
58 const bound = {
59 value: yield* token.value,
60 accountId: yield* token.accountId,
61 } satisfies HttpToken;
62 const bucketName = yield* bucket.bucketName;
63 const jurisdiction = yield* bucket.jurisdiction;
64 return options.makeClient(bound, bucketName, jurisdiction);
65 });
66 });
67
68 export interface HttpScope {
69 accountId: string;
70 bucketName: string;
71 cfR2Jurisdiction: string | undefined;
72 }
73 export interface HttpToken {
74 value: Effect.Effect<Redacted.Redacted<string>>;
75 accountId: Effect.Effect<string>;
76 }
77
78 const R2_HTTP_PERMISSION_GROUPS: PermissionGroupRef[] = [
79 "Workers R2 Storage Read",
80 "Workers R2 Storage Write",
81 ];
82
83 type PermissionGroup = (typeof R2_HTTP_PERMISSION_GROUPS)[number];
84
85 /** Resolve the account, bucket, and jurisdiction once per operation. */
86 export const makeR2HttpScope = (
87 accountId: Effect.Effect<string>,
88 bucketName: Effect.Effect<string>,
89 jurisdiction: Effect.Effect<string>,
90 ): Effect.Effect<HttpScope> =>
91 Effect.gen(function* () {
92 const accountId_ = yield* accountId;
93 const bucket = yield* bucketName;
94 const j = yield* jurisdiction;
95 return {
96 accountId: accountId_,
97 bucketName: bucket,
98 cfR2Jurisdiction: j === "default" ? undefined : j,
99 };
100 });
101
102 /**
103 * Bind the token's `value` (as `secret_text`) and `accountId` (as `plain_text`)
104 * into the Worker so they can be read at runtime.
105 */
106
107 export const toR2Error = (error: unknown): R2Error =>
108 new R2Error({
109 message:
110 typeof error === "object" && error !== null && "message" in error
111 ? String((error as { message: unknown }).message)
112 : "Unknown R2 error",
113 cause: error instanceof Error ? error : new Error(String(error)),
114 });
115
116 const stripQuotes = (etag: string | undefined): string | undefined =>
117 etag === undefined ? undefined : etag.replace(/^"|"$/g, "");
118
119 export interface HttpMetadata {
120 contentType?: string;
121 contentEncoding?: string;
122 contentDisposition?: string;
123 contentLanguage?: string;
124 cacheControl?: string;
125 cacheExpiry?: Date;
126 }
127
128 /** Normalize the caller's `httpMetadata` option (object or `Headers`). */
129 export const readHttpMetadata = (
130 options: { httpMetadata?: unknown } | undefined,
131 ): HttpMetadata | undefined => {
132 const meta = options?.httpMetadata;
133 if (!meta) return undefined;
134 if (meta instanceof Headers) {
135 return {
136 contentType: meta.get("content-type") ?? undefined,
137 contentEncoding: meta.get("content-encoding") ?? undefined,
138 contentDisposition: meta.get("content-disposition") ?? undefined,
139 contentLanguage: meta.get("content-language") ?? undefined,
140 cacheControl: meta.get("cache-control") ?? undefined,
141 };
142 }
143 return meta as HttpMetadata;
144 };
145
146 /** Write an object's HTTP metadata onto a `Headers` instance. */
147 const applyHttpMetadata = (headers: Headers, meta: HttpMetadata): void => {
148 if (meta.contentType) headers.set("content-type", meta.contentType);
149 if (meta.contentEncoding) headers.set("content-encoding", meta.contentEncoding);
150 if (meta.contentDisposition) headers.set("content-disposition", meta.contentDisposition);
151 if (meta.contentLanguage) headers.set("content-language", meta.contentLanguage);
152 if (meta.cacheControl) headers.set("cache-control", meta.cacheControl);
153 };
154
155 export const baseObject = (
156 key: string,
157 meta: HttpMetadata,
158 attrs: {
159 size?: number;
160 etag?: string;
161 uploaded?: Date;
162 storageClass?: string;
163 customMetadata?: Record<string, string>;
164 },
165 ): R2Object =>
166 ({
167 key,
168 version: "",
169 size: attrs.size ?? 0,
170 etag: stripQuotes(attrs.etag) ?? "",
171 httpEtag: attrs.etag ?? "",
172 checksums: {},
173 uploaded: attrs.uploaded ?? new Date(0),
174 httpMetadata: meta,
175 customMetadata: attrs.customMetadata ?? {},
176 range: undefined,
177 storageClass: attrs.storageClass ?? "Standard",
178 writeHttpMetadata: (headers: Headers) => Effect.sync(() => applyHttpMetadata(headers, meta)),
179 }) as unknown as R2Object;
180
181 /** Collect a put `value` into a body accepted by the R2 HTTP API. */
182 export const toBody = (
183 value:
184 | ReadableStream
185 | ArrayBuffer
186 | ArrayBufferView
187 | string
188 | null
189 | Blob
190 | Stream.Stream<Uint8Array, unknown>,
191 ): Effect.Effect<
192 { body: Blob | Uint8Array | ArrayBuffer | string; contentLength?: number },
193 R2Error
194 > =>
195 Effect.gen(function* () {
196 if (value === null) return { body: new Uint8Array(0), contentLength: 0 };
197 if (typeof value === "string") return { body: value };
198 if (value instanceof Blob) return { body: value, contentLength: value.size };
199 if (value instanceof ArrayBuffer) return { body: value, contentLength: value.byteLength };
200 if (Stream.isStream(value) || value instanceof ReadableStream) {
201 const readable = Stream.isStream(value) ? Stream.toReadableStream(value) : value;
202 const buffer = yield* Effect.tryPromise({
203 try: () => new Response(readable as any).arrayBuffer(),
204 catch: toR2Error,
205 });
206 return { body: new Uint8Array(buffer), contentLength: buffer.byteLength };
207 }
208 const view = value as ArrayBufferView;
209 const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
210 return { body: bytes, contentLength: bytes.byteLength };
211 });