@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, 06:00 UTC

main
ts 432 lines 14.7 KB
Raw
1 import * as resourceSharing from "@distilled.cloud/cloudflare/resource-sharing";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
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.ResourceSharing.Share" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Type of resource that can be shared across accounts/organizations.
17 */
18 export type ShareableResourceType =
19 | "custom-ruleset"
20 | "gateway-policy"
21 | "gateway-destination-ip"
22 | "gateway-block-page-settings"
23 | "gateway-extended-email-matching"
24 | "idp-federation-grant";
25
26 /**
27 * Lifecycle status of a share. Deletion is asynchronous — a deleted share
28 * transitions `active → deleting → deleted`.
29 */
30 export type ShareStatus = "active" | "deleting" | "deleted";
31
32 /**
33 * A recipient of a share — exactly one of `accountId` / `organizationId`.
34 */
35 export type ShareRecipientInput = {
36 /**
37 * Recipient account identifier. Exactly one of `accountId` /
38 * `organizationId` must be set.
39 */
40 accountId?: string;
41 /**
42 * Recipient organization identifier. Exactly one of `accountId` /
43 * `organizationId` must be set.
44 */
45 organizationId?: string;
46 };
47
48 /**
49 * A resource entry shared by a share.
50 */
51 export type ShareResourceInput = {
52 /**
53 * Type of the shared resource (e.g. `gateway-policy`).
54 */
55 resourceType: ShareableResourceType;
56 /**
57 * Identifier of the resource being shared (e.g. the gateway policy id).
58 */
59 resourceId: string;
60 /**
61 * Account that owns the resource being shared.
62 * @default the current account
63 */
64 resourceAccountId?: string;
65 /**
66 * Resource metadata forwarded to the share API.
67 * @default {}
68 */
69 meta?: unknown;
70 };
71
72 export type ShareProps = {
73 /**
74 * The name of the share. The only share-level mutable field. If omitted, a
75 * unique name is generated from the app, stage, and logical ID.
76 * @default ${app}-${stage}-${id}
77 */
78 name?: string;
79 /**
80 * Recipients of the share. The create API requires at least one. Changes
81 * are reconciled via the recipient sub-API (add/remove deltas). Do not mix
82 * with standalone `ShareRecipient` resources on the same share — the Share
83 * provider treats this list as the full desired set.
84 */
85 recipients: ShareRecipientInput[];
86 /**
87 * Resources shared by the share. The create API requires at least one.
88 * Changes are reconciled via the resource sub-API (`meta` updates in place;
89 * changing `resourceType`/`resourceId` of an entry deletes and recreates
90 * that entry). Do not mix with standalone `ShareResource` resources on the
91 * same share — the Share provider treats this list as the full desired set.
92 */
93 resources: ShareResourceInput[];
94 };
95
96 export type ShareAttributes = {
97 /**
98 * Share identifier tag. Stable across updates.
99 */
100 shareId: string;
101 /**
102 * The Cloudflare account that owns (sends) the share.
103 */
104 accountId: string;
105 /**
106 * The name of the share.
107 */
108 name: string;
109 /**
110 * Lifecycle status of the share.
111 */
112 status: ShareStatus;
113 /**
114 * Whether the share targets an account or an organization.
115 */
116 targetType: "account" | "organization";
117 /**
118 * Whether this share is sent by or received by the current account.
119 */
120 kind: "sent" | "received";
121 /**
122 * Organization identifier of the owning account.
123 */
124 organizationId: string;
125 /**
126 * When the share was created.
127 */
128 created: string;
129 /**
130 * When the share was last modified.
131 */
132 modified: string;
133 };
134
135 export type Share = Resource<TypeId, ShareProps, ShareAttributes, never, Providers>;
136
137 /**
138 * A Cloudflare resource share — shares account-level configuration (gateway
139 * policies, custom rulesets, IdP federation grants, …) with another account
140 * or organization.
141 *
142 * The create API requires at least one recipient and one resource, so both
143 * are seeded inline. Post-create changes to those arrays are reconciled
144 * through the recipient/resource sub-APIs; only `name` is mutable on the
145 * share itself. Deletion is asynchronous (`active → deleting → deleted`).
146 * ### Creating a Share
147 * **Example:** Share a gateway policy with another account
148 * ```typescript
149 * const policy = yield* Cloudflare.Gateway.Rule("BlockPhishing", {
150 * action: "block",
151 * traffic: 'dns.fqdn == "phishing.example"',
152 * filters: ["dns"],
153 * });
154 *
155 * const share = yield* Cloudflare.ResourceSharing.Share("PolicyShare", {
156 * recipients: [{ accountId: "<recipient-account-id>" }],
157 * resources: [
158 * { resourceType: "gateway-policy", resourceId: policy.ruleId },
159 * ],
160 * });
161 * ```
162 *
163 * ### Updating a Share
164 * **Example:** Rename in place
165 * ```typescript
166 * const share = yield* Cloudflare.ResourceSharing.Share("PolicyShare", {
167 * name: "security-baseline-v2",
168 * recipients: [{ accountId: "<recipient-account-id>" }],
169 * resources: [
170 * { resourceType: "gateway-policy", resourceId: policy.ruleId },
171 * ],
172 * });
173 * ```
174 *
175 * @see https://developers.cloudflare.com/fundamentals/manage-account-resources/
176 *
177 * @resource
178 * @product Resource Sharing
179 * @category Account & Identity
180 */
181 export const Share = Resource<Share>(TypeId);
182
183 /**
184 * Returns true if the given value is a Share resource.
185 */
186 export const isShare = (value: unknown): value is Share =>
187 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
188
189 export const ShareProvider = () =>
190 Provider.succeed(Share, {
191 stables: ["shareId", "accountId", "organizationId", "created"],
192 // Account collection — enumerate every share this account sends
193 // (the ones we own and can delete), exhaustively paginated, mapped
194 // into the same Attributes shape `read` returns. Deleted shares are
195 // excluded since they no longer exist.
196 list: Effect.fn(function* () {
197 const { accountId } = yield* yield* CloudflareEnvironment;
198 return yield* resourceSharing.listResourceSharings
199 .pages({ accountId, kind: "sent", perPage: 50 })
200 .pipe(
201 Stream.runCollect,
202 Effect.map((chunk) =>
203 Array.from(chunk).flatMap((page) =>
204 (page.result ?? [])
205 .filter((s) => s.status !== "deleted")
206 .map((s) => toAttributes(s, accountId)),
207 ),
208 ),
209 );
210 }),
211 diff: Effect.fn(function* ({ news, output }) {
212 if (!isResolved(news)) return undefined;
213 const { accountId } = yield* yield* CloudflareEnvironment;
214 if ((output?.accountId ?? accountId) !== accountId) {
215 return { action: "replace" } as const;
216 }
217 return undefined;
218 }),
219 read: Effect.fn(function* ({ id, olds, output }) {
220 const { accountId } = yield* yield* CloudflareEnvironment;
221 const acct = output?.accountId ?? accountId;
222
223 if (output?.shareId) {
224 const observed = yield* getShare(acct, output.shareId);
225 return observed ? toAttributes(observed, acct) : undefined;
226 }
227 // Cold read — recover from lost state by matching the deterministic
228 // physical name among shares we sent. Names are not unique on
229 // Cloudflare's side; an exact match is the best identity we have.
230 const name = yield* createShareName(id, olds?.name);
231 const match = yield* findByName(acct, name);
232 return match ? toAttributes(match, acct) : undefined;
233 }),
234 reconcile: Effect.fn(function* ({ id, news, output }) {
235 const { accountId } = yield* yield* CloudflareEnvironment;
236 const name = yield* createShareName(id, news.name);
237 const desiredRecipients = news.recipients.map((r) => ({
238 accountId: r.accountId as string | undefined,
239 organizationId: r.organizationId as string | undefined,
240 }));
241 const desiredResources = news.resources.map((r) => ({
242 resourceType: r.resourceType,
243 resourceId: r.resourceId as string,
244 resourceAccountId: (r.resourceAccountId as string) ?? accountId,
245 meta: r.meta ?? {},
246 }));
247
248 // Observe — the shareId cached on `output` is a hint, not a
249 // guarantee: a missing (or fully deleted) share falls through and
250 // we recreate.
251 const observed = output?.shareId
252 ? yield* getShare(output.accountId ?? accountId, output.shareId)
253 : undefined;
254
255 if (!observed) {
256 // Ensure — greenfield (or out-of-band delete): the create API
257 // requires both arrays, so seed them inline. Share names are not
258 // unique so there is no AlreadyExists race to tolerate.
259 const created = yield* resourceSharing.createResourceSharing({
260 accountId,
261 name,
262 recipients: desiredRecipients,
263 resources: desiredResources,
264 });
265 return toAttributes(created, accountId);
266 }
267
268 const acct = output?.accountId ?? accountId;
269
270 // Sync name — the only share-level mutable field.
271 if (observed.name !== name) {
272 yield* resourceSharing.updateResourceSharing({
273 accountId: acct,
274 shareId: observed.id,
275 name,
276 });
277 }
278
279 // Sync recipients — diff observed cloud state against desired and
280 // apply add/remove deltas through the recipient sub-API.
281 const observedRecipients = yield* resourceSharing.listRecipients
282 .items({ accountId: acct, shareId: observed.id, perPage: 50 })
283 .pipe(
284 Stream.runCollect,
285 Effect.map((chunk) => Array.from(chunk)),
286 );
287 const liveRecipients = observedRecipients.filter(
288 (r) => r.associationStatus !== "disassociated",
289 );
290 for (const desired of desiredRecipients) {
291 const match = liveRecipients.find(
292 (r) => r.accountId === (desired.accountId ?? desired.organizationId),
293 );
294 if (!match) {
295 yield* resourceSharing.createRecipient({
296 accountId: acct,
297 shareId: observed.id,
298 recipientAccountId: desired.accountId,
299 organizationId: desired.organizationId,
300 });
301 }
302 }
303 for (const live of liveRecipients) {
304 const wanted = desiredRecipients.some(
305 (d) => (d.accountId ?? d.organizationId) === live.accountId,
306 );
307 if (!wanted) {
308 yield* resourceSharing
309 .deleteRecipient({
310 accountId: acct,
311 shareId: observed.id,
312 recipientId: live.id,
313 })
314 .pipe(Effect.catchTag("ShareRecipientNotFound", () => Effect.void));
315 }
316 }
317
318 // Sync resources — keyed by (resourceType, resourceId): create
319 // missing entries, update `meta` in place, delete extras.
320 const observedResources = yield* resourceSharing.listResources
321 .items({ accountId: acct, shareId: observed.id, perPage: 50 })
322 .pipe(
323 Stream.runCollect,
324 Effect.map((chunk) => Array.from(chunk)),
325 );
326 const liveResources = observedResources.filter(
327 (r) => r.status !== "deleted" && r.status !== "deleting",
328 );
329 for (const desired of desiredResources) {
330 const match = liveResources.find(
331 (r) => r.resourceType === desired.resourceType && r.resourceId === desired.resourceId,
332 );
333 if (!match) {
334 yield* resourceSharing.createResource({
335 accountId: acct,
336 shareId: observed.id,
337 resourceType: desired.resourceType,
338 resourceId: desired.resourceId,
339 resourceAccountId: desired.resourceAccountId,
340 meta: desired.meta,
341 });
342 } else if (JSON.stringify(match.meta ?? {}) !== JSON.stringify(desired.meta ?? {})) {
343 yield* resourceSharing.updateResource({
344 accountId: acct,
345 shareId: observed.id,
346 shareResourceId: match.id,
347 meta: desired.meta,
348 });
349 }
350 }
351 for (const live of liveResources) {
352 const wanted = desiredResources.some(
353 (d) => d.resourceType === live.resourceType && d.resourceId === live.resourceId,
354 );
355 if (!wanted) {
356 yield* resourceSharing
357 .deleteResource({
358 accountId: acct,
359 shareId: observed.id,
360 shareResourceId: live.id,
361 })
362 .pipe(Effect.catchTag("ShareResourceNotFound", () => Effect.void));
363 }
364 }
365
366 // Return — re-read for fresh attributes after the sub-API syncs.
367 const fresh = yield* getShare(acct, observed.id);
368 return fresh ? toAttributes(fresh, acct) : toAttributes(observed, acct);
369 }),
370 delete: Effect.fn(function* ({ output }) {
371 // Deletion is asynchronous (`active → deleting → deleted`); the
372 // DELETE call itself is idempotent against a missing share.
373 yield* resourceSharing
374 .deleteResourceSharing({
375 accountId: output.accountId,
376 shareId: output.shareId,
377 })
378 .pipe(Effect.catchTag("ShareNotFound", () => Effect.void));
379 }),
380 });
381
382 type ObservedShare = resourceSharing.GetResourceSharingResponse;
383
384 /**
385 * Read a share by id, mapping "gone" (`ShareNotFound`, Cloudflare error code
386 * 1004 / HTTP 404) and the terminal `deleted` status to `undefined`.
387 */
388 const getShare = (accountId: string, shareId: string) =>
389 resourceSharing.getResourceSharing({ accountId, shareId }).pipe(
390 Effect.map((share): ObservedShare | undefined =>
391 share.status === "deleted" ? undefined : share,
392 ),
393 Effect.catchTag("ShareNotFound", () => Effect.undefined),
394 );
395
396 /**
397 * Find a sent share by exact name. If several shares carry the same name,
398 * pick the oldest for determinism.
399 */
400 const findByName = (accountId: string, name: string) =>
401 resourceSharing.listResourceSharings({ accountId, kind: "sent", perPage: 50 }).pipe(
402 Effect.map((list) =>
403 list.result
404 .filter((s) => s.name === name && s.status !== "deleted")
405 .sort((a, b) => a.created.localeCompare(b.created))
406 .at(0),
407 ),
408 );
409
410 const createShareName = (id: string, name: string | undefined) =>
411 Effect.gen(function* () {
412 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
413 });
414
415 const toAttributes = (
416 share:
417 | ObservedShare
418 | resourceSharing.CreateResourceSharingResponse
419 | resourceSharing.ListResourceSharingsResponse["result"][number],
420 accountId: string,
421 ): ShareAttributes => ({
422 shareId: share.id,
423 accountId,
424 name: share.name,
425 // Distilled widens generated string enums to open unions (`string & {}`).
426 status: share.status as ShareStatus,
427 targetType: share.targetType as "account" | "organization",
428 kind: (share.kind ?? "sent") as "sent" | "received",
429 organizationId: share.organizationId,
430 created: share.created,
431 modified: share.modified,
432 });