@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 266 lines 9.26 KB
Raw
1 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import type { Providers } from "../Providers.ts";
10
11 export class KeyGroupConflict extends Data.TaggedError("KeyGroupConflict")<{
12 readonly message: string;
13 readonly cause?: unknown;
14 }> {}
15
16 export class KeyGroupUnexpectedResponse extends Data.TaggedError("KeyGroupUnexpectedResponse")<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export interface KeyGroupProps {
22 /**
23 * Name of the key group. If omitted, a deterministic name is generated.
24 *
25 * Names must be unique per AWS account. Changing the name triggers
26 * a replacement.
27 */
28 name?: string;
29 /**
30 * Public key IDs that belong to the group. Order is preserved.
31 */
32 items: Input<string>[];
33 /**
34 * Optional comment describing the group.
35 */
36 comment?: string;
37 }
38
39 export interface KeyGroup extends Resource<
40 "AWS.CloudFront.KeyGroup",
41 KeyGroupProps,
42 {
43 /**
44 * CloudFront-assigned key group identifier. Used by Distributions in
45 * `TrustedKeyGroups` to authorize signed URLs/cookies.
46 */
47 keyGroupId: string;
48 /**
49 * Name of the key group.
50 */
51 name: string;
52 /**
53 * Public key IDs that belong to the group.
54 */
55 items: string[];
56 /**
57 * Most recent entity tag for update/delete operations.
58 */
59 etag: string | undefined;
60 /**
61 * Current comment on the group.
62 */
63 comment: string | undefined;
64 },
65 never,
66 Providers
67 > {}
68
69 /**
70 * A CloudFront key group.
71 *
72 * Key groups bundle one or more {@link PublicKey} resources for use as
73 * `TrustedKeyGroups` on a Distribution's cache behavior. CloudFront uses
74 * the keys in the group to verify the signatures on signed URLs and
75 * signed cookies for that behavior.
76 * ### Creating Key Groups
77 * **Example:** Group two public keys for signed URL verification
78 * ```typescript
79 * const primary = yield* PublicKey("PrimarySigningKey", {
80 * encodedKey: yield* fs.readFileString("./primary.pem"),
81 * });
82 * const secondary = yield* PublicKey("SecondarySigningKey", {
83 * encodedKey: yield* fs.readFileString("./secondary.pem"),
84 * });
85 *
86 * const keyGroup = yield* KeyGroup("SignedUrlKeys", {
87 * comment: "Trusted signers for /private",
88 * items: [primary.publicKeyId, secondary.publicKeyId],
89 * });
90 * ```
91 *
92 * @resource
93 */
94 export const KeyGroup = Resource<KeyGroup>("AWS.CloudFront.KeyGroup");
95
96 export const KeyGroupProvider = () =>
97 Provider.effect(
98 KeyGroup,
99 Effect.gen(function* () {
100 const getById = Effect.fn(function* (id: string) {
101 const config = yield* cloudfront
102 .getKeyGroupConfig({ Id: id })
103 .pipe(Effect.catchTag("NoSuchResource", () => Effect.undefined));
104 if (!config?.KeyGroupConfig) return undefined;
105 return { config: config.KeyGroupConfig, etag: config.ETag };
106 });
107
108 const getByName = Effect.fn(function* (name: string) {
109 const listed = yield* cloudfront.listKeyGroups({});
110 const summary = listed.KeyGroupList?.Items?.find(
111 (item) => item.KeyGroup?.KeyGroupConfig?.Name === name,
112 );
113 if (!summary?.KeyGroup?.Id) return undefined;
114 return yield* getById(summary.KeyGroup.Id).pipe(
115 Effect.map((found) => (found ? { id: summary.KeyGroup.Id, ...found } : undefined)),
116 );
117 });
118
119 const buildConfig = (
120 name: string,
121 items: string[],
122 comment: string | undefined,
123 ): cloudfront.KeyGroupConfig => ({
124 Name: name,
125 Items: items,
126 Comment: comment,
127 });
128
129 const toAttrs = (
130 id: string,
131 config: cloudfront.KeyGroupConfig,
132 etag: string | undefined,
133 ) => ({
134 keyGroupId: id,
135 name: config.Name,
136 items: config.Items,
137 etag,
138 comment: config.Comment,
139 });
140
141 return {
142 stables: ["keyGroupId"],
143 list: () =>
144 Effect.gen(function* () {
145 const items: ReturnType<typeof toAttrs>[] = [];
146 let marker: string | undefined = undefined;
147 do {
148 const listed: cloudfront.ListKeyGroupsResult = yield* cloudfront.listKeyGroups({
149 Marker: marker,
150 });
151 for (const summary of listed.KeyGroupList?.Items ?? []) {
152 const id = summary.KeyGroup?.Id;
153 const config = summary.KeyGroup?.KeyGroupConfig;
154 if (!id || !config) continue;
155 // The list summary omits the ETag; re-read each group to
156 // produce the exact Attributes shape `read` returns.
157 const found = yield* getById(id);
158 items.push(toAttrs(id, found?.config ?? config, found?.etag));
159 }
160 marker = listed.KeyGroupList?.NextMarker;
161 } while (marker);
162 return items;
163 }),
164 diff: Effect.fn(function* ({ id, news, olds }) {
165 if (!isResolved(news)) return undefined;
166 if ((yield* createName(id, olds ?? {})) !== (yield* createName(id, news))) {
167 return { action: "replace" } as const;
168 }
169 }),
170 read: Effect.fn(function* ({ id, olds, output }) {
171 if (output?.keyGroupId) {
172 const found = yield* getById(output.keyGroupId);
173 if (found) return toAttrs(output.keyGroupId, found.config, found.etag);
174 }
175 const name = yield* createName(id, olds ?? {});
176 const found = yield* getByName(name);
177 if (!found) return undefined;
178 return toAttrs(found.id, found.config, found.etag);
179 }),
180 reconcile: Effect.fn(function* ({ id, news, output, session }) {
181 const name = yield* createName(id, news);
182 const items = news.items as string[];
183
184 // Observe — locate the key group by id (cached on `output`) or
185 // by name. Trust observed cloud state, not stale `olds`.
186 let observed = output?.keyGroupId
187 ? yield* getById(output.keyGroupId).pipe(
188 Effect.map((found) => (found ? { id: output.keyGroupId, ...found } : undefined)),
189 )
190 : undefined;
191 if (!observed) {
192 observed = yield* getByName(name);
193 }
194
195 // Ensure — create the key group if it's missing. Tolerate
196 // `KeyGroupAlreadyExists` (race with a peer reconciler).
197 if (!observed) {
198 const created = yield* cloudfront
199 .createKeyGroup({
200 KeyGroupConfig: buildConfig(name, items, news.comment),
201 })
202 .pipe(
203 Effect.catchTag("KeyGroupAlreadyExists", () =>
204 getByName(name).pipe(
205 Effect.flatMap((existing) =>
206 existing
207 ? Effect.succeed({
208 KeyGroup: {
209 Id: existing.id,
210 LastModifiedTime: new Date(),
211 KeyGroupConfig: existing.config,
212 },
213 ETag: existing.etag,
214 Location: undefined,
215 })
216 : Effect.fail(
217 new KeyGroupConflict({
218 message: `Key group '${name}' already exists but could not be recovered`,
219 }),
220 ),
221 ),
222 ),
223 ),
224 );
225 if (!created.KeyGroup?.Id) {
226 return yield* new KeyGroupUnexpectedResponse({
227 message: "createKeyGroup returned no identifier",
228 });
229 }
230 yield* session.note(created.KeyGroup.Id);
231 return toAttrs(created.KeyGroup.Id, created.KeyGroup.KeyGroupConfig, created.ETag);
232 }
233
234 // Sync — patch the observed config to the desired state. The
235 // freshly observed ETag handles optimistic concurrency.
236 const updated = yield* cloudfront.updateKeyGroup({
237 Id: observed.id,
238 IfMatch: observed.etag,
239 KeyGroupConfig: buildConfig(observed.config.Name, items, news.comment),
240 });
241 if (!updated.KeyGroup?.Id) {
242 return yield* new KeyGroupUnexpectedResponse({
243 message: "updateKeyGroup returned no identifier",
244 });
245 }
246 yield* session.note(observed.id);
247 return toAttrs(updated.KeyGroup.Id, updated.KeyGroup.KeyGroupConfig, updated.ETag);
248 }),
249 delete: Effect.fn(function* ({ output }) {
250 const current = yield* getById(output.keyGroupId);
251 if (!current) return;
252 yield* cloudfront
253 .deleteKeyGroup({
254 Id: output.keyGroupId,
255 IfMatch: current.etag,
256 })
257 .pipe(Effect.catchTag("NoSuchResource", () => Effect.void));
258 }),
259 };
260 }),
261 );
262
263 const createName = (id: string, props: { name?: string }) =>
264 props.name
265 ? Effect.succeed(props.name)
266 : createPhysicalName({ id, maxLength: 128, lowercase: true });