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

main
ts 257 lines 8.3 KB
Raw
1 import * as storage from "@distilled.cloud/gcp/storage_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { DeleteNotConfirmed } from "../Errors.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 isUserManagedAclEntity,
12 listAlchemyBuckets,
13 normalizeEntity,
14 normalizeRole,
15 } from "./internal.ts";
16
17 export type DefaultObjectAccessControlProps = {
18 /**
19 * Name of the bucket whose default object ACL this entry belongs to.
20 * Immutable — changing it replaces the entry.
21 */
22 bucketName: string;
23 /**
24 * Principal granted the role on newly created objects. Forms include
25 * `user-{email}`, `group-{email}`, `domain-{domain}`, `allUsers`, and
26 * `allAuthenticatedUsers`. Immutable — changing it replaces the entry.
27 */
28 entity: string;
29 /**
30 * Access permission for the entity (`OWNER` or `READER`).
31 */
32 role: string;
33 };
34
35 export type DefaultObjectAccessControl = Resource<
36 "GCP.Storage.DefaultObjectAccessControl",
37 DefaultObjectAccessControlProps,
38 {
39 /** Parent bucket name. */
40 bucketName: string;
41 /** Principal granted the role. */
42 entity: string;
43 /** Access permission (`OWNER` or `READER`). */
44 role: string;
45 /** Server-assigned ACL id. */
46 id: string | undefined;
47 /** Domain associated with the entity, if any. */
48 domain: string | undefined;
49 /** Email associated with the entity, if any. */
50 email: string | undefined;
51 /** Numeric entity id, if any. */
52 entityId: string | undefined;
53 /** HTTP etag. */
54 etag: string | undefined;
55 /** GCS self-link. */
56 selfLink: string | undefined;
57 },
58 never,
59 Providers
60 >;
61
62 /**
63 * A Cloud Storage default object ACL entry on a bucket.
64 *
65 * Default object ACLs are copied onto objects created without an explicit
66 * ACL. Identity is `(bucket, entity)`. Role is mutable; changing
67 * `bucketName` or `entity` replaces the entry. Entries have no labels
68 * field, so `list` / `pnpm nuke:gcp` discover them by enumerating
69 * alchemy-labeled buckets and skipping project-team defaults.
70 *
71 * Uniform bucket-level access buckets do not support default object ACLs.
72 *
73 * ### Creating a Default Object ACL
74 * **Example:** Grant a service account reader access on new objects
75 * ```typescript
76 * const bucket = yield* GCP.Storage.Bucket("assets", {
77 * forceDestroy: true,
78 * });
79 * const acl = yield* GCP.Storage.DefaultObjectAccessControl("reader", {
80 * bucketName: bucket.bucketName,
81 * entity: "user-app@project.iam.gserviceaccount.com",
82 * role: "READER",
83 * });
84 * ```
85 *
86 * **Example:** Update the role
87 * ```typescript
88 * const acl = yield* GCP.Storage.DefaultObjectAccessControl("reader", {
89 * bucketName: bucket.bucketName,
90 * entity: "user-app@project.iam.gserviceaccount.com",
91 * role: "OWNER",
92 * });
93 * ```
94 *
95 * @resource
96 * @category Storage
97 */
98 export const DefaultObjectAccessControl = Resource<DefaultObjectAccessControl>(
99 "GCP.Storage.DefaultObjectAccessControl",
100 );
101
102 export class DefaultObjectAccessControlNotResolved extends Data.TaggedError(
103 "GCP.Storage.DefaultObjectAccessControlNotResolved",
104 )<{
105 bucketName: string;
106 entity: string;
107 }> {}
108
109 const toAttrs = (acl: storage.ObjectAccessControl, bucketName: string) => ({
110 bucketName: acl.bucket ?? bucketName,
111 entity: acl.entity ?? "",
112 role: acl.role ?? "",
113 id: acl.id,
114 domain: acl.domain,
115 email: acl.email,
116 entityId: acl.entityId,
117 etag: acl.etag,
118 selfLink: acl.selfLink,
119 });
120
121 const getByEntity = (bucketName: string, entity: string) =>
122 storage
123 .getDefaultObjectAccessControls({ bucket: bucketName, entity })
124 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
125
126 const listOnBucket = (bucketName: string) =>
127 storage.listDefaultObjectAccessControls({ bucket: bucketName }).pipe(
128 Effect.map((page) => page.items ?? []),
129 Effect.catchTag("NotFound", () => Effect.succeed([] as storage.ObjectAccessControl[])),
130 );
131
132 const waitUntilGone = (bucketName: string, entity: string) =>
133 getByEntity(bucketName, entity).pipe(
134 Effect.map((existing) => (existing === undefined ? ("gone" as const) : ("found" as const))),
135 Effect.repeat({
136 schedule: Schedule.spaced("1 second"),
137 until: (status) => status === "gone",
138 times: 30,
139 }),
140 Effect.flatMap((status): Effect.Effect<void, DeleteNotConfirmed> =>
141 status === "gone"
142 ? Effect.void
143 : Effect.fail(
144 new DeleteNotConfirmed({
145 resource: `${bucketName}/defaultObjectAcl/${entity}`,
146 }),
147 ),
148 ),
149 );
150
151 export const DefaultObjectAccessControlProvider = () =>
152 Provider.succeed(DefaultObjectAccessControl, {
153 stables: ["bucketName", "entity", "id", "selfLink"],
154
155 diff: Effect.fn(function* ({ news, olds, output }) {
156 if (!isResolved(news)) return undefined;
157 const previousBucket = olds?.bucketName ?? output?.bucketName;
158 const previousEntity = olds?.entity ?? output?.entity;
159 if (previousBucket !== undefined && news.bucketName !== previousBucket) {
160 return { action: "replace" as const, deleteFirst: false };
161 }
162 if (
163 previousEntity !== undefined &&
164 normalizeEntity(news.entity) !== normalizeEntity(previousEntity)
165 ) {
166 return { action: "replace" as const, deleteFirst: false };
167 }
168 return undefined;
169 }),
170
171 read: Effect.fn(function* ({ olds, output }) {
172 const bucketName = olds?.bucketName ?? output?.bucketName;
173 const entity = olds?.entity ?? output?.entity;
174 if (!bucketName || !entity) return undefined;
175 const existing = yield* getByEntity(bucketName, entity);
176 if (existing === undefined) return undefined;
177 return toAttrs(existing, bucketName);
178 }),
179
180 list: () =>
181 Effect.gen(function* () {
182 const buckets = yield* listAlchemyBuckets();
183 const pages = yield* Effect.forEach(
184 buckets,
185 (bucket) => {
186 const bucketName = bucket.name;
187 // Legacy ACL APIs reject uniform bucket-level access buckets.
188 if (
189 !bucketName ||
190 bucket.iamConfiguration?.uniformBucketLevelAccess?.enabled === true
191 ) {
192 return Effect.succeed([] as Array<DefaultObjectAccessControl["Attributes"]>);
193 }
194 return listOnBucket(bucketName).pipe(
195 Effect.map((items) =>
196 items
197 .filter((item) => isUserManagedAclEntity(item.entity))
198 .map((item) => toAttrs(item, bucketName)),
199 ),
200 );
201 },
202 { concurrency: 8 },
203 );
204 return pages.flat();
205 }),
206
207 reconcile: Effect.fn(function* ({ news, output }) {
208 const bucketName = news.bucketName;
209 const entity = normalizeEntity(news.entity);
210 const role = normalizeRole(news.role);
211
212 let current =
213 output?.entity !== undefined
214 ? yield* getByEntity(output.bucketName ?? bucketName, normalizeEntity(output.entity))
215 : undefined;
216 if (current === undefined) {
217 current = yield* getByEntity(bucketName, entity);
218 }
219
220 if (current === undefined) {
221 const created = yield* storage
222 .insertDefaultObjectAccessControls({
223 bucket: bucketName,
224 body: { entity, role },
225 })
226 .pipe(Effect.catchTag("Conflict", () => getByEntity(bucketName, entity)));
227 current = created ?? undefined;
228 }
229
230 if (current === undefined || !current.entity) {
231 return yield* new DefaultObjectAccessControlNotResolved({
232 bucketName,
233 entity,
234 });
235 }
236
237 if (normalizeRole(current.role ?? "") !== role) {
238 current = yield* storage.patchDefaultObjectAccessControls({
239 bucket: bucketName,
240 entity,
241 body: { entity, role },
242 });
243 }
244
245 return toAttrs(current, bucketName);
246 }),
247
248 delete: Effect.fn(function* ({ output }) {
249 const bucketName = output.bucketName;
250 const entity = output.entity;
251 if (!bucketName || !entity) return;
252 yield* storage
253 .deleteDefaultObjectAccessControls({ bucket: bucketName, entity })
254 .pipe(Effect.catchTag("NotFound", () => Effect.void));
255 yield* waitUntilGone(bucketName, entity);
256 }),
257 });