@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 624 lines 19.7 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import type {
3 CreateFirewallRequestApplyToItem,
4 CreateFirewallRequestRulesItem,
5 GetFirewallResponseFirewall,
6 GetFirewallResponseFirewallAppliedToItem,
7 GetFirewallResponseFirewallRulesItem,
8 ListFirewallsResponseFirewallsItem,
9 } from "@distilled.cloud/hetzner/firewalls";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { deepEqual, isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import { recordsEqual } from "alchemy/Util/equal";
16 import * as Data from "effect/Data";
17 import * as Effect from "effect/Effect";
18 import * as Stream from "effect/Stream";
19 import { waitForActions } from "./actions.ts";
20 import {
21 alchemyStackSelector,
22 createInternalLabels,
23 diffLabels,
24 hasAlchemyLabels,
25 labelSelector,
26 stripInternalLabels,
27 toLabels,
28 } from "./Labels.ts";
29 import type { Providers } from "./Providers.ts";
30
31 /**
32 * Resource-valued prop. The engine resolves `Effect`s (including other
33 * Resources) before lifecycle operations see the value.
34 */
35 type Ref<T> = T | Effect.Effect<T, never, Providers>;
36
37 /**
38 * Server identity used by `applyTo`. A `Hetzner.Server` resource
39 * satisfies this via `serverId`.
40 */
41 type Server = { readonly serverId: number };
42
43 export type FirewallDirection = "in" | "out";
44 export type FirewallProtocol = "tcp" | "udp" | "icmp" | "esp" | "gre";
45
46 export interface FirewallRule {
47 /**
48 * Description of the rule.
49 */
50 description?: string;
51 /**
52 * Traffic direction. Incoming rules use `sourceIps`; outgoing rules
53 * use `destinationIps`.
54 */
55 direction: FirewallDirection;
56 /**
57 * Network protocol this rule applies to.
58 */
59 protocol: FirewallProtocol;
60 /**
61 * Port or port range (`22` or `1024-5000`). Only valid for `tcp` and
62 * `udp`.
63 */
64 port?: string;
65 /**
66 * Permitted source CIDRs for incoming traffic. Use `0.0.0.0/0` and
67 * `::/0` to allow any address.
68 */
69 sourceIps?: string[];
70 /**
71 * Permitted destination CIDRs for outgoing traffic. Use `0.0.0.0/0`
72 * and `::/0` to allow any address.
73 */
74 destinationIps?: string[];
75 }
76
77 export interface FirewallProps {
78 /**
79 * Name of the firewall. Must be unique per Hetzner project. If
80 * omitted, a unique name is generated from `${stack}-${id}-${stage}`.
81 */
82 name?: string;
83 /**
84 * Firewall rules. Limited to 50 entries per firewall. An empty list
85 * (the default) drops all inbound traffic and accepts all outbound
86 * traffic.
87 */
88 rules?: FirewallRule[];
89 /**
90 * Servers this firewall is applied to. This wave's tests leave
91 * `applyTo` empty; the type still accepts `Server` resources.
92 */
93 applyTo?: Array<Ref<Server>>;
94 /**
95 * User-defined labels. Alchemy ownership labels (`alchemy.stack`,
96 * `alchemy.stage`, `alchemy.id`) are always merged in.
97 */
98 labels?: Record<string, string>;
99 }
100
101 export type FirewallAppliedTo = { type: "server"; serverId: number };
102
103 export interface Firewall extends Resource<
104 "Hetzner.Firewall",
105 FirewallProps,
106 {
107 /**
108 * Numeric Hetzner firewall id.
109 */
110 id: number;
111 /**
112 * Name of the firewall.
113 */
114 name: string;
115 /**
116 * RFC3339 timestamp when the firewall was created.
117 */
118 created: string;
119 /**
120 * Current rules, in the same camelCase shape as {@link FirewallRule}.
121 */
122 rules: FirewallRule[];
123 /**
124 * Server ids the firewall is currently applied to (direct
125 * `type=server` attachments only).
126 */
127 appliedTo: FirewallAppliedTo[];
128 /**
129 * User-facing labels (Alchemy ownership labels stripped).
130 */
131 labels: Record<string, string>;
132 },
133 never,
134 Providers
135 > {}
136
137 /**
138 * A Hetzner Cloud firewall — a named set of inbound/outbound rules that
139 * can be applied to one or more Servers.
140 *
141 * Name, rules, labels, and `applyTo` are all mutable. Changing the name
142 * updates the existing firewall in place (it is unique per project).
143 * @see https://docs.hetzner.cloud/reference/cloud#firewalls
144 *
145 * ### Creating a Firewall
146 * **Example:** Basic firewall
147 * ```typescript
148 * const web = yield* Hetzner.Firewall("web", {
149 * rules: [
150 * {
151 * direction: "in",
152 * protocol: "tcp",
153 * port: "22",
154 * sourceIps: ["0.0.0.0/0", "::/0"],
155 * },
156 * ],
157 * });
158 * ```
159 *
160 * **Example:** Firewall applied to a Server
161 * ```typescript
162 * const server = yield* Hetzner.Server("app", {
163 * image: "ubuntu-24.04",
164 * serverType: "cx22",
165 * location: "nbg1",
166 * });
167 * const web = yield* Hetzner.Firewall("web", {
168 * applyTo: [server],
169 * rules: [
170 * {
171 * direction: "in",
172 * protocol: "tcp",
173 * port: "443",
174 * sourceIps: ["0.0.0.0/0", "::/0"],
175 * },
176 * ],
177 * });
178 * ```
179 *
180 * ### Updating rules
181 * **Example:** Replace the rule set
182 * ```typescript
183 * const web = yield* Hetzner.Firewall("web", {
184 * rules: [
185 * {
186 * direction: "in",
187 * protocol: "tcp",
188 * port: "80",
189 * sourceIps: ["0.0.0.0/0", "::/0"],
190 * },
191 * {
192 * direction: "in",
193 * protocol: "tcp",
194 * port: "443",
195 * sourceIps: ["0.0.0.0/0", "::/0"],
196 * },
197 * ],
198 * });
199 * ```
200 *
201 * @resource
202 * @product Firewall
203 */
204 export const Firewall = Resource<Firewall>("Hetzner.Firewall");
205
206 export class FirewallNotCreated extends Data.TaggedError("Hetzner.FirewallNotCreated")<{
207 resourceName: string;
208 }> {}
209
210 type FirewallAttributes = Firewall["Attributes"];
211 type ObservedFirewall = GetFirewallResponseFirewall | ListFirewallsResponseFirewallsItem;
212
213 const NAME_MAX_LENGTH = 128;
214
215 const createFirewallName = (id: string, name: string | undefined) =>
216 Effect.gen(function* () {
217 if (name !== undefined) return name;
218 return yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH });
219 });
220
221 const compactLabels = (
222 labels: Record<string, string | undefined> | null | undefined,
223 ): Record<string, string> =>
224 Object.fromEntries(
225 Object.entries(labels ?? {}).filter(
226 (entry): entry is [string, string] => entry[1] !== undefined,
227 ),
228 );
229
230 const desiredLabels = Effect.fn(function* (id: string, user: Record<string, string> | undefined) {
231 const internal = yield* createInternalLabels(id);
232 return { ...toLabels(user), ...internal };
233 });
234
235 const sortIps = (ips: ReadonlyArray<string> | undefined): string[] =>
236 [...(ips ?? [])].map((ip) => ip.toLowerCase()).sort();
237
238 const normalizeRule = (rule: {
239 description?: string | null;
240 direction: string;
241 protocol: string;
242 port?: string | null;
243 sourceIps?: ReadonlyArray<string>;
244 destinationIps?: ReadonlyArray<string>;
245 }): FirewallRule => {
246 const description = rule.description ?? undefined;
247 const port = rule.port ?? undefined;
248 return {
249 direction: rule.direction as FirewallDirection,
250 protocol: rule.protocol as FirewallProtocol,
251 ...(description !== undefined ? { description } : {}),
252 ...(port !== undefined && port.length > 0 ? { port } : {}),
253 sourceIps: sortIps(rule.sourceIps),
254 destinationIps: sortIps(rule.destinationIps),
255 };
256 };
257
258 const fromObservedRule = (rule: GetFirewallResponseFirewallRulesItem): FirewallRule =>
259 normalizeRule({
260 description: rule.description,
261 direction: rule.direction,
262 protocol: rule.protocol,
263 port: rule.port,
264 sourceIps: rule.source_ips,
265 destinationIps: rule.destination_ips,
266 });
267
268 const toWireRule = (rule: FirewallRule): CreateFirewallRequestRulesItem => {
269 const description = rule.description;
270 const port =
271 (rule.protocol === "tcp" || rule.protocol === "udp") && rule.port ? rule.port : undefined;
272 return {
273 direction: rule.direction,
274 protocol: rule.protocol,
275 ...(description !== undefined ? { description } : {}),
276 ...(port !== undefined ? { port } : {}),
277 ...(rule.sourceIps !== undefined ? { source_ips: [...rule.sourceIps] } : {}),
278 ...(rule.destinationIps !== undefined ? { destination_ips: [...rule.destinationIps] } : {}),
279 };
280 };
281
282 const desiredRules = (rules: FirewallRule[] | undefined): FirewallRule[] =>
283 (rules ?? []).map((rule) =>
284 normalizeRule({
285 description: rule.description,
286 direction: rule.direction,
287 protocol: rule.protocol,
288 port: rule.port,
289 sourceIps: rule.sourceIps,
290 destinationIps: rule.destinationIps,
291 }),
292 );
293
294 const rulesEqual = (a: FirewallRule[], b: FirewallRule[]): boolean =>
295 deepEqual(a, b, { stripNullish: true });
296
297 const serverIdOf = (value: unknown): number | undefined => {
298 if (value === null || typeof value !== "object") return undefined;
299 const rec = value as { serverId?: unknown; id?: unknown };
300 if (typeof rec.serverId === "number") return rec.serverId;
301 if (typeof rec.id === "number") return rec.id;
302 return undefined;
303 };
304
305 const desiredServerIds = (applyTo: FirewallProps["applyTo"] | undefined): number[] => {
306 const ids = new Set<number>();
307 for (const item of applyTo ?? []) {
308 const id = serverIdOf(item);
309 if (id !== undefined) ids.add(id);
310 }
311 return [...ids].sort((a, b) => a - b);
312 };
313
314 const observedServerIds = (
315 appliedTo: ReadonlyArray<GetFirewallResponseFirewallAppliedToItem>,
316 ): number[] => {
317 const ids = new Set<number>();
318 for (const item of appliedTo) {
319 if (item.type === "server" && item.server?.id !== undefined) {
320 ids.add(item.server.id);
321 }
322 }
323 return [...ids].sort((a, b) => a - b);
324 };
325
326 const toAppliedTo = (
327 appliedTo: ReadonlyArray<GetFirewallResponseFirewallAppliedToItem>,
328 ): FirewallAppliedTo[] =>
329 observedServerIds(appliedTo).map((serverId) => ({ type: "server" as const, serverId }));
330
331 const toServerApplyItems = (ids: ReadonlyArray<number>): CreateFirewallRequestApplyToItem[] =>
332 ids.map((id) => ({ type: "server" as const, server: { id } }));
333
334 const detachItems = (
335 appliedTo: ReadonlyArray<GetFirewallResponseFirewallAppliedToItem>,
336 ): CreateFirewallRequestApplyToItem[] => {
337 const items: CreateFirewallRequestApplyToItem[] = [];
338 for (const item of appliedTo) {
339 if (item.type === "server" && item.server?.id !== undefined) {
340 items.push({ type: "server", server: { id: item.server.id } });
341 } else if (item.type === "label_selector" && item.label_selector?.selector !== undefined) {
342 items.push({
343 type: "label_selector",
344 label_selector: { selector: item.label_selector.selector },
345 });
346 }
347 }
348 return items;
349 };
350
351 const toAttrs = (firewall: ObservedFirewall): FirewallAttributes => ({
352 id: firewall.id,
353 name: firewall.name,
354 created: firewall.created,
355 rules: firewall.rules.map(fromObservedRule),
356 appliedTo: toAppliedTo(firewall.applied_to),
357 labels: stripInternalLabels(compactLabels(firewall.labels)),
358 });
359
360 const getById = (id: number) =>
361 Hetzner.firewalls.getFirewall({ id }).pipe(
362 Effect.map(({ firewall }) => firewall),
363 Effect.catchTag("NotFound", () => Effect.undefined),
364 );
365
366 const findByName = (name: string) =>
367 Effect.gen(function* () {
368 const { firewalls } = yield* Hetzner.firewalls.listFirewalls({ name, per_page: 50 });
369 return firewalls.find((item) => item.name === name);
370 });
371
372 const findByLabels = (id: string) =>
373 Effect.gen(function* () {
374 const selector = labelSelector(yield* createInternalLabels(id));
375 const { firewalls } = yield* Hetzner.firewalls.listFirewalls({
376 label_selector: selector,
377 per_page: 50,
378 });
379 return firewalls[0];
380 });
381
382 const observe = (input: { id: string; name: string; output: FirewallAttributes | undefined }) =>
383 Effect.gen(function* () {
384 if (input.output?.id !== undefined) {
385 const byId = yield* getById(input.output.id);
386 if (byId !== undefined) return byId;
387 }
388 const byName = yield* findByName(input.name);
389 if (byName !== undefined) return byName;
390 return yield* findByLabels(input.id);
391 });
392
393 const waitActions = (actions: ReadonlyArray<{ readonly id: number }>) =>
394 waitForActions(actions.map((action) => action.id));
395
396 const ensureFirewall = Effect.fn(function* (input: {
397 name: string;
398 labels: Record<string, string>;
399 rules: FirewallRule[];
400 serverIds: number[];
401 }) {
402 const created = yield* Hetzner.firewalls
403 .createFirewall({
404 name: input.name,
405 labels: input.labels,
406 ...(input.rules.length > 0 ? { rules: input.rules.map(toWireRule) } : {}),
407 ...(input.serverIds.length > 0 ? { apply_to: toServerApplyItems(input.serverIds) } : {}),
408 })
409 .pipe(
410 Effect.catchTag("Conflict", () =>
411 findByName(input.name).pipe(
412 Effect.flatMap((existing) =>
413 existing !== undefined
414 ? Effect.succeed({ firewall: existing, actions: [] })
415 : Hetzner.firewalls
416 .listFirewalls({ name: input.name, per_page: 1 })
417 .pipe(Effect.map(({ firewalls }) => ({ firewall: firewalls[0], actions: [] }))),
418 ),
419 ),
420 ),
421 );
422 yield* waitActions(created.actions ?? []);
423 return created.firewall ?? (yield* findByName(input.name));
424 });
425
426 const syncNameAndLabels = Effect.fn(function* (input: {
427 firewallId: number;
428 observedName: string;
429 desiredName: string;
430 observedLabels: Record<string, string>;
431 desiredLabels: Record<string, string>;
432 }) {
433 const nameChanged = input.observedName !== input.desiredName;
434 const { upsert, removed } = diffLabels(input.observedLabels, input.desiredLabels);
435 const labelsChanged = upsert.length > 0 || removed.length > 0;
436 if (!nameChanged && !labelsChanged) return;
437 yield* Hetzner.firewalls.updateFirewall({
438 id: input.firewallId,
439 ...(nameChanged ? { name: input.desiredName } : {}),
440 ...(labelsChanged ? { labels: input.desiredLabels } : {}),
441 });
442 });
443
444 const syncRules = Effect.fn(function* (input: {
445 firewallId: number;
446 observed: FirewallRule[];
447 desired: FirewallRule[];
448 }) {
449 if (rulesEqual(input.observed, input.desired)) return;
450 const { actions } = yield* Hetzner.firewallActions.setFirewallRules({
451 id: input.firewallId,
452 rules: input.desired.map(toWireRule),
453 });
454 yield* waitActions(actions);
455 });
456
457 const syncApplyTo = Effect.fn(function* (input: {
458 firewallId: number;
459 observed: ReadonlyArray<GetFirewallResponseFirewallAppliedToItem>;
460 desiredIds: number[];
461 }) {
462 const observedIds = new Set(observedServerIds(input.observed));
463 const desiredIds = new Set(input.desiredIds);
464 const toAdd = [...desiredIds].filter((id) => !observedIds.has(id));
465 const toRemove = [...observedIds].filter((id) => !desiredIds.has(id));
466 if (toAdd.length > 0) {
467 const { actions } = yield* Hetzner.firewallActions.applyFirewallToResources({
468 id: input.firewallId,
469 apply_to: toServerApplyItems(toAdd),
470 });
471 yield* waitActions(actions);
472 }
473 if (toRemove.length > 0) {
474 const { actions } = yield* Hetzner.firewallActions.removeFirewallFromResources({
475 id: input.firewallId,
476 remove_from: toServerApplyItems(toRemove),
477 });
478 yield* waitActions(actions);
479 }
480 });
481
482 const detachAll = Effect.fn(function* (
483 firewallId: number,
484 appliedTo: ReadonlyArray<GetFirewallResponseFirewallAppliedToItem>,
485 ) {
486 const removeFrom = detachItems(appliedTo);
487 if (removeFrom.length === 0) return;
488 const result = yield* Hetzner.firewallActions
489 .removeFirewallFromResources({ id: firewallId, remove_from: removeFrom })
490 .pipe(
491 Effect.catchTag(["NotFound", "UnprocessableEntity"], () => Effect.succeed({ actions: [] })),
492 );
493 yield* waitActions(result.actions);
494 });
495
496 export const FirewallProvider = () =>
497 Provider.succeed(Firewall, {
498 stables: ["id", "created"],
499 list: Effect.fn(function* () {
500 const rows = yield* Hetzner.firewalls.listFirewalls
501 .items({ label_selector: alchemyStackSelector, per_page: 50 })
502 .pipe(Stream.runCollect);
503 return Array.from(rows, toAttrs);
504 }),
505 diff: Effect.fn(function* ({ id, olds, news, output }) {
506 if (!isResolved(news)) return undefined;
507 const oldName = output?.name ?? (yield* createFirewallName(id, olds?.name));
508 const newName = news.name ?? oldName;
509 if (oldName !== newName) {
510 return { action: "update" } as const;
511 }
512 if (
513 !rulesEqual(desiredRules(olds?.rules), desiredRules(news.rules)) ||
514 !recordsEqual(olds?.labels ?? {}, news.labels ?? {})
515 ) {
516 return { action: "update" } as const;
517 }
518 const oldIds = desiredServerIds(olds?.applyTo);
519 const newIds = desiredServerIds(news.applyTo);
520 if (!deepEqual(oldIds, newIds)) {
521 return { action: "update" } as const;
522 }
523 if (output !== undefined) {
524 if (!rulesEqual(output.rules, desiredRules(news.rules))) {
525 return { action: "update" } as const;
526 }
527 const outputIds = output.appliedTo.map((item) => item.serverId);
528 if (
529 !deepEqual(
530 [...outputIds].sort((a, b) => a - b),
531 newIds,
532 )
533 ) {
534 return { action: "update" } as const;
535 }
536 }
537 return undefined;
538 }),
539 read: Effect.fn(function* ({ id, olds, output }) {
540 const name =
541 output?.name ??
542 (olds?.name !== undefined
543 ? olds.name
544 : output !== undefined
545 ? undefined
546 : yield* createFirewallName(id, olds?.name));
547 const observed =
548 output?.id !== undefined
549 ? ((yield* getById(output.id)) ??
550 (name !== undefined ? yield* findByName(name) : undefined) ??
551 (yield* findByLabels(id)))
552 : name !== undefined
553 ? ((yield* findByName(name)) ?? (yield* findByLabels(id)))
554 : yield* findByLabels(id);
555 if (observed === undefined) return undefined;
556 const attrs = toAttrs(observed);
557 const ours = yield* hasAlchemyLabels(id, compactLabels(observed.labels));
558 return ours ? attrs : Unowned(attrs);
559 }),
560 reconcile: Effect.fn(function* ({ id, news, output }) {
561 const name = news.name ?? output?.name ?? (yield* createFirewallName(id, news.name));
562 const labels = yield* desiredLabels(id, news.labels);
563 const rules = desiredRules(news.rules);
564 const serverIds = desiredServerIds(news.applyTo);
565
566 // Observe — cached id is a hint; cloud state is authoritative.
567 let current = yield* observe({ id, name, output });
568
569 // Ensure — create if missing. A Conflict is a name-race; look up
570 // the existing firewall and fall through to sync.
571 if (current === undefined) {
572 yield* ensureFirewall({ name, labels, rules, serverIds });
573 }
574 if (current === undefined) {
575 current = yield* observe({ id, name, output });
576 }
577 if (current === undefined) {
578 return yield* new FirewallNotCreated({ resourceName: name });
579 }
580
581 // Sync each mutable aspect against observed cloud state.
582 yield* syncNameAndLabels({
583 firewallId: current.id,
584 observedName: current.name,
585 desiredName: name,
586 observedLabels: compactLabels(current.labels),
587 desiredLabels: labels,
588 });
589 yield* syncRules({
590 firewallId: current.id,
591 observed: current.rules.map(fromObservedRule),
592 desired: rules,
593 });
594 yield* syncApplyTo({
595 firewallId: current.id,
596 observed: current.applied_to,
597 desiredIds: serverIds,
598 });
599
600 const fresh = (yield* getById(current.id)) ?? current;
601 return toAttrs(fresh);
602 }),
603 delete: Effect.fn(function* ({ output }) {
604 const id = output.id;
605 const observed = yield* getById(id);
606 if (observed !== undefined) {
607 yield* detachAll(id, observed.applied_to);
608 }
609 yield* Hetzner.firewalls.deleteFirewall({ id }).pipe(
610 Effect.catchTags({
611 NotFound: () => Effect.void,
612 UnprocessableEntity: () =>
613 Effect.gen(function* () {
614 const again = yield* getById(id);
615 if (again === undefined) return;
616 yield* detachAll(id, again.applied_to);
617 yield* Hetzner.firewalls
618 .deleteFirewall({ id })
619 .pipe(Effect.catchTag("NotFound", () => Effect.void));
620 }),
621 }),
622 );
623 }),
624 });