@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 111 lines 3.95 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 { AccountApiToken } from "../ApiToken/AccountApiToken.ts";
7 import type { PermissionGroupRef } from "../ApiToken/Common.ts";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Credentials } from "../Credentials.ts";
10 import { requireLiveResource } from "../HttpBindingDev.ts";
11 import { authorizeWith } from "../HttpClientUtils.ts";
12 import type { InstantNamespace } from "./InstantNamespace.ts";
13 import type { Namespace } from "./Namespace.ts";
14 import { NamespaceError } from "./NamespaceTypes.ts";
15
16 /**
17 * Shared scaffolding for the HTTP-backed KV services.
18 *
19 * Creates a scoped {@link AccountApiToken}, binds its `value` / `accountId`
20 * into the host Worker at deploy time, then delegates to `makeClient` with
21 * the bound token and the namespace's `namespaceId`.
22 */
23 export const makeHttpKVNamespaceBinding = <Client>(options: {
24 permissionGroups: PermissionGroup[];
25 makeClient: (token: HttpToken, namespaceId: Effect.Effect<string>) => Client;
26 }) =>
27 Effect.gen(function* () {
28 const Token = yield* AccountApiToken;
29 const self = yield* Self;
30
31 return Effect.fn(function* (namespace: Namespace | InstantNamespace) {
32 if (!globalThis.__ALCHEMY_RUNTIME__) yield* requireLiveResource(namespace);
33 const token = yield* Token(`${self.LogicalId}Token`);
34 if (!globalThis.__ALCHEMY_RUNTIME__) {
35 const { accountId } = yield* CloudflareEnvironment.current;
36 yield* token.bind`${namespace.LogicalId}`({
37 policies: [
38 {
39 effect: "allow",
40 permissionGroups: options.permissionGroups,
41 resources: {
42 [`com.cloudflare.api.account.${accountId}`]: "*",
43 },
44 },
45 ],
46 });
47 }
48 const bound = {
49 value: yield* token.value,
50 accountId: yield* token.accountId,
51 } satisfies HttpToken;
52 const namespaceId = yield* namespace.namespaceId;
53 return options.makeClient(bound, namespaceId);
54 });
55 });
56
57 export interface HttpToken {
58 value: Effect.Effect<Redacted.Redacted<string>>;
59 accountId: Effect.Effect<string>;
60 }
61
62 export interface HttpScope {
63 accountId: string;
64 namespaceId: string;
65 }
66
67 /**
68 * Injectable auth for the KV HTTP client builders. Both the scoped-token
69 * (`*Http`) and current-credentials (`*Local`) variants supply an `authorize`
70 * (which provides `Credentials` + `HttpClient` to a raw SDK op) and an
71 * `accountId`, so the client builders are agnostic to how creds are obtained.
72 */
73 export interface KVAuth {
74 authorize: <A, E>(
75 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
76 ) => Effect.Effect<A, E, RuntimeContext>;
77 accountId: Effect.Effect<string>;
78 }
79
80 /** Build a scoped-token {@link KVAuth} from a bound {@link HttpToken}. */
81 export const makeKVAuth = (token: HttpToken): KVAuth => ({
82 authorize: authorizeWith(token),
83 accountId: token.accountId,
84 });
85
86 const KV_HTTP_PERMISSION_GROUPS: PermissionGroupRef[] = [
87 "Workers KV Storage Read",
88 "Workers KV Storage Write",
89 ];
90
91 type PermissionGroup = (typeof KV_HTTP_PERMISSION_GROUPS)[number];
92
93 /** Resolve the account and namespace id once per operation. */
94 export const makeKVHttpScope = (
95 auth: KVAuth,
96 namespaceId: Effect.Effect<string>,
97 ): Effect.Effect<HttpScope> =>
98 Effect.gen(function* () {
99 const accountId = yield* auth.accountId;
100 const id = yield* namespaceId;
101 return { accountId, namespaceId: id };
102 });
103
104 export const toKVNamespaceError = (error: unknown): NamespaceError =>
105 new NamespaceError({
106 message:
107 typeof error === "object" && error !== null && "message" in error
108 ? String((error as { message: unknown }).message)
109 : "Unknown KV error",
110 cause: error instanceof Error ? error : new Error(String(error)),
111 });