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

main
ts 177 lines 6.33 KB
Raw
1 import * as stream from "@distilled.cloud/cloudflare/stream";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Predicate from "effect/Predicate";
6 import * as Redacted from "effect/Redacted";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.Stream.SigningKey" as const;
12 type TypeId = typeof TypeId;
13
14 export type SigningKeyProps = {};
15
16 export type SigningKeyAttributes = {
17 /**
18 * The unique identifier of the signing key.
19 */
20 keyId: string;
21 /**
22 * The Cloudflare account the signing key belongs to.
23 */
24 accountId: string;
25 /**
26 * The date and time the signing key was created.
27 */
28 created: string | undefined;
29 /**
30 * The signing key in PEM format. Only returned by Cloudflare at
31 * creation time — preserved in state thereafter.
32 */
33 pem: Redacted.Redacted<string>;
34 /**
35 * The signing key in JWK format. Only returned by Cloudflare at
36 * creation time — preserved in state thereafter.
37 */
38 jwk: Redacted.Redacted<string>;
39 };
40
41 export type SigningKey = Resource<TypeId, SigningKeyProps, SigningKeyAttributes, never, Providers>;
42
43 /**
44 * A Cloudflare Stream signing key — an RSA key pair used to sign viewer
45 * playback tokens for videos that require signed URLs.
46 *
47 * The key material (`pem`/`jwk`) is returned by Cloudflare **only at
48 * creation time**; it is persisted as redacted attributes in state and
49 * can never be re-read from the API. If the key is deleted out-of-band,
50 * reconcile creates a brand-new key with new material — anything derived
51 * from the old key (signed tokens) must be re-derived from the new
52 * attributes.
53 *
54 * Requires the Stream subscription to be enabled on the account.
55 * ### Creating a signing key
56 * **Example:** Signing key for signed playback URLs
57 * ```typescript
58 * const key = yield* Cloudflare.Stream.SigningKey("PlaybackKey", {});
59 *
60 * // key.pem / key.jwk are Redacted<string> — use them server-side to
61 * // sign playback tokens for videos with requireSignedURLs enabled.
62 * const pem = key.pem;
63 * ```
64 *
65 * @see https://developers.cloudflare.com/stream/viewing-videos/securing-your-stream/
66 *
67 * @resource
68 * @product Stream
69 * @category Media
70 */
71 export const SigningKey = Resource<SigningKey>(TypeId);
72
73 /**
74 * Returns true if the given value is a SigningKey resource.
75 */
76 export const isSigningKey = (value: unknown): value is SigningKey =>
77 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
78
79 export const SigningKeyProvider = () =>
80 Provider.succeed(SigningKey, {
81 stables: ["keyId", "accountId", "created", "pem", "jwk"],
82
83 list: Effect.fn(function* () {
84 const { accountId } = yield* yield* CloudflareEnvironment;
85 // Account-scoped collection: the keys list endpoint only returns
86 // `id` + `created`. The key material (pem/jwk) is create-only and
87 // can never be re-read, so — matching `read` for a key with no
88 // cached state — we surface it as empty redacted values.
89 return yield* stream.getKey.pages({ accountId }).pipe(
90 Stream.runCollect,
91 Effect.map((chunk) =>
92 Array.from(chunk).flatMap((page) =>
93 (page.result ?? [])
94 .filter(
95 (key): key is stream.KeysGetResultItem & { id: string } =>
96 typeof key.id === "string",
97 )
98 .map(
99 (key) =>
100 ({
101 keyId: key.id,
102 accountId,
103 created: key.created ?? undefined,
104 pem: Redacted.make(""),
105 jwk: Redacted.make(""),
106 }) satisfies SigningKeyAttributes,
107 ),
108 ),
109 ),
110 // Accounts without the Stream subscription are forbidden from the
111 // keys endpoint — treat as an empty collection.
112 Effect.catchTag("Forbidden", () => Effect.succeed([])),
113 );
114 }),
115
116 diff: Effect.fn(function* ({ output }) {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118 if (output !== undefined && output.accountId !== accountId) {
119 return { action: "replace" } as const;
120 }
121 // No mutable props.
122 return undefined;
123 }),
124
125 read: Effect.fn(function* ({ output }) {
126 // The list endpoint only returns `id` + `created` — the key
127 // material is create-only, so without cached state there is
128 // nothing to recover.
129 if (output?.keyId === undefined) return undefined;
130 const found = yield* findKey(output.accountId, output.keyId);
131 // Preserve the stored pem/jwk; the API can never return them again.
132 return found ? output : undefined;
133 }),
134
135 reconcile: Effect.fn(function* ({ output }) {
136 const { accountId } = yield* yield* CloudflareEnvironment;
137
138 // Observe — existence-only resource: check the key is still listed.
139 const exists = output?.keyId
140 ? yield* findKey(output.accountId ?? accountId, output.keyId)
141 : false;
142
143 if (exists && output !== undefined) {
144 // Nothing mutable to sync — keep the cached attributes (they
145 // carry the create-only key material).
146 return output;
147 }
148
149 // Ensure — create a new key (`createKey` takes an empty body).
150 const created = yield* stream.createKey({ accountId });
151 return {
152 keyId: created.id ?? "",
153 accountId,
154 created: created.created ?? undefined,
155 pem: Redacted.make(created.pem ?? ""),
156 jwk: Redacted.make(created.jwk ?? ""),
157 } satisfies SigningKeyAttributes;
158 }),
159
160 delete: Effect.fn(function* ({ output }) {
161 // Idempotent — a key already deleted out-of-band surfaces as
162 // `SigningKeyNotFound` (Cloudflare error code 10003).
163 yield* stream
164 .deleteKey({ accountId: output.accountId, identifier: output.keyId })
165 .pipe(Effect.catchTag("SigningKeyNotFound", () => Effect.void));
166 }),
167 });
168
169 /**
170 * True when the signing key with the given id is present in the
171 * account's key list. Cloudflare returns `result: null` (not `[]`) when
172 * the account has no keys.
173 */
174 const findKey = (accountId: string, keyId: string) =>
175 stream
176 .getKey({ accountId })
177 .pipe(Effect.map((response) => (response.result ?? []).some((key) => key.id === keyId)));