@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 220 lines 8.25 KB
Raw
1 import * as images from "@distilled.cloud/cloudflare/images";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Redacted from "effect/Redacted";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.Images.SigningKey" as const;
14 type TypeId = typeof TypeId;
15
16 export interface SigningKeyProps {
17 /**
18 * Account the signing key is created in. Defaults to the ambient
19 * Cloudflare account. Changing it triggers a replacement.
20 */
21 accountId?: string;
22 /**
23 * Name of the signing key — the PUT path identifier. If omitted, a unique
24 * name is generated from the app, stage, and logical ID. Changing the
25 * name triggers a replacement.
26 *
27 * @default ${app}-${stage}-${id}
28 */
29 name?: string;
30 }
31
32 export interface SigningKeyAttributes {
33 /** The signing key's name (its API path identifier). */
34 keyName: string;
35 /** Account the key belongs to. */
36 accountId: string;
37 /** The HMAC key material used to sign image delivery URLs. */
38 value: Redacted.Redacted<string>;
39 }
40
41 export type SigningKey = Resource<TypeId, SigningKeyProps, SigningKeyAttributes, never, Providers>;
42
43 /**
44 * A Cloudflare Images signing key — an HMAC key used to generate signed
45 * image delivery URLs (`?sig=` tokens) for images that require signed URLs.
46 *
47 * Cloudflare allows at most **two** keys per account, supporting a
48 * create-second/migrate/delete-first rotation model, and refuses to delete
49 * the last remaining key. Re-PUTting an existing key name **rotates** (i.e.
50 * regenerates) its value, so this resource is existence-only: once the key
51 * exists, redeploys never re-PUT and the key material stays stable.
52 *
53 * Requires the Cloudflare Images subscription; accounts without it receive
54 * the typed `ImagesAccessNotEnabled` error.
55 * ### Creating a Signing Key
56 * **Example:** Key with a generated name
57 * ```typescript
58 * const key = yield* Cloudflare.Images.SigningKey("UrlSigner", {});
59 * ```
60 *
61 * **Example:** Key with an explicit name
62 * ```typescript
63 * const key = yield* Cloudflare.Images.SigningKey("UrlSigner", {
64 * name: "my-app-signer",
65 * });
66 * ```
67 *
68 * ### Using the key
69 * **Example:** Signing image delivery URLs server-side
70 * ```typescript
71 * // The key material is redacted — pass it to your URL signer:
72 * const secret = key.value; // Redacted<string>
73 * ```
74 *
75 * @see https://developers.cloudflare.com/images/manage-images/serve-images/serve-private-images/
76 *
77 * @resource
78 * @product Images
79 * @category Media
80 */
81 export const SigningKey = Resource<SigningKey>(TypeId);
82
83 /**
84 * Returns true if the given value is an SigningKey resource.
85 */
86 export const isSigningKey = (value: unknown): value is SigningKey =>
87 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
88
89 export const SigningKeyProvider = () =>
90 Provider.succeed(SigningKey, {
91 stables: ["keyName", "accountId", "value"],
92
93 diff: Effect.fn(function* ({ olds, news, output }) {
94 // News may still contain unresolved plan-time expressions — defer to
95 // the engine's default update logic until everything is concrete.
96 if (!isResolved(news)) return undefined;
97 // The key name is its PUT path identifier — it cannot be renamed.
98 // Only compare when the old name is knowable; a generated name is
99 // stable across deploys so an omitted name never replaces.
100 const oldName = output?.keyName ?? olds?.name;
101 if (oldName !== undefined && news.name !== undefined && news.name !== oldName) {
102 return { action: "replace" } as const;
103 }
104 if (
105 typeof olds?.accountId === "string" &&
106 typeof news.accountId === "string" &&
107 olds.accountId !== news.accountId
108 ) {
109 return { action: "replace" } as const;
110 }
111 if (
112 output?.accountId !== undefined &&
113 typeof news.accountId === "string" &&
114 news.accountId !== output.accountId
115 ) {
116 return { action: "replace" } as const;
117 }
118 return undefined;
119 }),
120
121 read: Effect.fn(function* ({ id, output, olds }) {
122 const { accountId } = yield* yield* CloudflareEnvironment;
123 const acct = output?.accountId ?? (olds?.accountId as string | undefined) ?? accountId;
124 const name = output?.keyName ?? (yield* createKeyName(id, olds?.name));
125
126 const observed = yield* findKey(acct, name);
127 if (!observed) return undefined;
128 const attrs = toAttributes(observed, acct);
129 // Signing keys carry no ownership markers. With no prior output we
130 // cannot prove we created a same-named key — report it `Unowned` so
131 // the engine gates takeover behind the adopt policy.
132 return output?.keyName ? attrs : Unowned(attrs);
133 }),
134
135 // Account-scoped collection (Cloudflare caps it at two keys per
136 // account). The non-paginated `listV1Keys` returns the whole set in one
137 // call; map each entry to the same Attributes shape `read` produces.
138 // Accounts without the Images signing-keys entitlement have no keys to
139 // enumerate — treat as an empty set rather than a hard failure.
140 list: Effect.fn(function* () {
141 const { accountId } = yield* yield* CloudflareEnvironment;
142 return yield* images.listV1Keys({ accountId }).pipe(
143 Effect.map((response): SigningKeyAttributes[] =>
144 (response.keys ?? []).map((key) => toAttributes(key, accountId)),
145 ),
146 Effect.catchTag("ImagesAccessNotEnabled", () => Effect.succeed<SigningKeyAttributes[]>([])),
147 );
148 }),
149
150 reconcile: Effect.fn(function* ({ id, news }) {
151 const { accountId } = yield* yield* CloudflareEnvironment;
152 // Inputs have been resolved to concrete strings by Plan.
153 const acct = (news.accountId as string | undefined) ?? accountId;
154 const name = yield* createKeyName(id, news.name);
155
156 // 1. Observe — list the account's keys and look for ours. `output`
157 // is only a cache of the name; the list is authoritative.
158 let observed = yield* findKey(acct, name);
159
160 // 2. Ensure — existence-only resource: PUT only when the key is
161 // missing. Re-PUTting an existing name would ROTATE the key
162 // material out from under consumers, so a present key is final —
163 // there is no sync step.
164 if (!observed) {
165 const created = yield* images.putV1Key({
166 accountId: acct,
167 signingKeyName: name,
168 });
169 observed = created.keys?.find((key) => key.name === name) ?? (yield* findKey(acct, name));
170 }
171 if (!observed?.value) {
172 // The PUT response and the follow-up list both failed to surface
173 // the key — eventual-consistency blip; fail typed so the engine
174 // can retry the reconcile.
175 return yield* images.KeyNotFound.make({
176 code: 5404,
177 message: `signing key ${name} not observable after create`,
178 });
179 }
180
181 return toAttributes(observed, acct);
182 }),
183
184 delete: Effect.fn(function* ({ output }) {
185 // Note: Cloudflare refuses to delete the last remaining signing key —
186 // that error is surfaced as-is (non-retryable) rather than swallowed.
187 yield* images
188 .deleteV1Key({
189 accountId: output.accountId,
190 signingKeyName: output.keyName,
191 })
192 .pipe(Effect.catchTag("KeyNotFound", () => Effect.void));
193 }),
194 });
195
196 type ObservedKey = { name?: string | null; value?: string | null };
197
198 /**
199 * Find a signing key by exact name in the account's key list. Returns
200 * `undefined` when absent.
201 */
202 const findKey = (accountId: string, name: string) =>
203 images
204 .listV1Keys({ accountId })
205 .pipe(
206 Effect.map((response) =>
207 (response.keys ?? []).find((key): key is ObservedKey => key.name === name),
208 ),
209 );
210
211 const createKeyName = (id: string, name: string | undefined) =>
212 Effect.gen(function* () {
213 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
214 });
215
216 const toAttributes = (key: ObservedKey, accountId: string): SigningKeyAttributes => ({
217 keyName: key.name ?? "",
218 accountId,
219 value: Redacted.make(key.value ?? ""),
220 });