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

main
ts 202 lines 7.1 KB
Raw
1 import * as calls from "@distilled.cloud/cloudflare/calls";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Redacted from "effect/Redacted";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Calls.TurnKey" as const;
13 type TypeId = typeof TypeId;
14
15 export type TurnKeyProps = {
16 /**
17 * A short description of the TURN key, not shown to end users and not
18 * unique. Mutable in place. If omitted, a unique name is generated from
19 * the app, stage, and logical ID.
20 * @default ${app}-${stage}-${id}
21 */
22 name?: string;
23 };
24
25 export type TurnKeyAttributes = {
26 /**
27 * Cloudflare-generated unique identifier for the TURN key. Used in the
28 * credential-minting API path
29 * (`https://rtc.live.cloudflare.com/v1/turn/keys/{keyId}/credentials/generate`).
30 */
31 keyId: string;
32 /**
33 * The Cloudflare account the TURN key belongs to.
34 */
35 accountId: string;
36 /**
37 * TURN key secret (bearer token) used to mint short-lived TURN
38 * credentials. Returned only at creation time and never re-readable —
39 * Alchemy persists it in state and carries it forward across updates.
40 */
41 key: Redacted.Redacted<string>;
42 /**
43 * A short description of the TURN key.
44 */
45 name: string;
46 /**
47 * When the TURN key was created.
48 */
49 created: string;
50 /**
51 * When the TURN key was last modified.
52 */
53 modified: string;
54 };
55
56 export type TurnKey = Resource<TypeId, TurnKeyProps, TurnKeyAttributes, never, Providers>;
57
58 /**
59 * A Cloudflare Realtime (formerly "Calls") TURN key.
60 *
61 * A TURN key authenticates your backend against Cloudflare's managed TURN
62 * service: you exchange the create-only `key` (a bearer token) for
63 * short-lived TURN credentials that WebRTC clients use to relay traffic
64 * through Cloudflare's network. The only configurable property is the
65 * human-readable `name`, which is mutable in place.
66 * ### Creating a TURN key
67 * **Example:** TURN key with a generated name
68 * ```typescript
69 * const turnKey = yield* Cloudflare.Calls.TurnKey("turn", {});
70 * ```
71 *
72 * **Example:** TURN key with an explicit name
73 * ```typescript
74 * const turnKey = yield* Cloudflare.Calls.TurnKey("turn", {
75 * name: "my-turn-key",
76 * });
77 * ```
78 *
79 * ### Using the key
80 * **Example:** Minting TURN credentials server-side
81 * ```typescript
82 * // keyId is public — it appears in the credential-minting URL:
83 * const keyId = turnKey.keyId;
84 *
85 * // The key is redacted — POST it as a bearer token to
86 * // https://rtc.live.cloudflare.com/v1/turn/keys/{keyId}/credentials/generate
87 * const apiToken = turnKey.key; // Redacted<string>
88 * ```
89 *
90 * @see https://developers.cloudflare.com/realtime/turn/
91 *
92 * @resource
93 * @product Calls
94 * @category Media
95 */
96 export const TurnKey = Resource<TurnKey>(TypeId);
97
98 /**
99 * Returns true if the given value is a TurnKey resource.
100 */
101 export const isTurnKey = (value: unknown): value is TurnKey =>
102 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
103
104 export const TurnKeyProvider = () =>
105 Provider.succeed(TurnKey, {
106 stables: ["keyId", "accountId", "key", "created"],
107 diff: Effect.fn(function* ({ output }) {
108 const { accountId } = yield* yield* CloudflareEnvironment;
109 if (output !== undefined && output.accountId !== accountId) {
110 return { action: "replace" } as const;
111 }
112 return undefined;
113 }),
114 read: Effect.fn(function* ({ output }) {
115 // The TURN key secret is returned only at creation time, so a key
116 // cannot be re-hydrated without prior state — no cold read /
117 // adoption path.
118 if (!output?.keyId) return undefined;
119 const observed = yield* getTurnKey(output.accountId, output.keyId);
120 return observed ? toAttributes(observed, output.accountId, output.key) : undefined;
121 }),
122 list: Effect.fn(function* () {
123 const { accountId } = yield* yield* CloudflareEnvironment;
124 // Account-scoped collection: paginate the TURN keys list exhaustively.
125 // The list response carries every readable field (uid/name/created/
126 // modified) — the bearer `key` is returned only at creation and is
127 // never re-readable, so we hydrate it as an empty redacted value to
128 // match exactly what `read` would produce on a cold (stateless) read.
129 return yield* calls.listTurns.pages({ accountId }).pipe(
130 Stream.runCollect,
131 Effect.map((chunk) =>
132 Array.from(chunk).flatMap((page) =>
133 (page.result ?? []).map((turnKey) =>
134 toAttributes(turnKey, accountId, Redacted.make("")),
135 ),
136 ),
137 ),
138 );
139 }),
140 reconcile: Effect.fn(function* ({ id, news, output }) {
141 const { accountId } = yield* yield* CloudflareEnvironment;
142 const name = yield* createTurnKeyName(id, news.name);
143
144 // Observe — the keyId cached on `output` is a hint, not a guarantee:
145 // a missing key (code 20008) falls through and we recreate.
146 const observed = output?.keyId
147 ? yield* getTurnKey(output.accountId ?? accountId, output.keyId)
148 : undefined;
149
150 if (!observed || !output) {
151 // Ensure — greenfield (or out-of-band delete): create and capture
152 // the create-only key. Names are not unique on Cloudflare's side,
153 // so there is no AlreadyExists race to tolerate.
154 const created = yield* calls.createTurn({ accountId, name });
155 return toAttributes(created, accountId, Redacted.make(created.key ?? ""));
156 }
157
158 // Sync — the only mutable aspect is `name`; diff observed cloud
159 // state against desired and skip the PUT entirely on a no-op.
160 if (observed.name === name) {
161 return toAttributes(observed, output.accountId, output.key);
162 }
163 const updated = yield* calls.updateTurn({
164 accountId: output.accountId,
165 keyId: output.keyId,
166 name,
167 });
168 return toAttributes(updated, output.accountId, output.key);
169 }),
170 delete: Effect.fn(function* ({ output }) {
171 yield* calls
172 .deleteTurn({ accountId: output.accountId, keyId: output.keyId })
173 .pipe(Effect.catchTag("TurnKeyNotFound", () => Effect.void));
174 }),
175 });
176
177 /**
178 * Read a TURN key by id, mapping "gone" (`TurnKeyNotFound`, Cloudflare
179 * error code 20008) to `undefined`.
180 */
181 const getTurnKey = (accountId: string, keyId: string) =>
182 calls
183 .getTurn({ accountId, keyId })
184 .pipe(Effect.catchTag("TurnKeyNotFound", () => Effect.undefined));
185
186 const createTurnKeyName = (id: string, name: string | undefined) =>
187 Effect.gen(function* () {
188 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
189 });
190
191 const toAttributes = (
192 turnKey: calls.GetTurnResponse | calls.CreateTurnResponse | calls.UpdateTurnResponse,
193 accountId: string,
194 key: Redacted.Redacted<string>,
195 ): TurnKeyAttributes => ({
196 keyId: turnKey.uid ?? "",
197 accountId,
198 key,
199 name: turnKey.name ?? "",
200 created: turnKey.created ?? "",
201 modified: turnKey.modified ?? "",
202 });