@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 266 lines 8.33 KB
Raw
1 import * as appengine from "@distilled.cloud/gcp/appengine_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 CATCH_ALL_PRIORITY,
12 catchMissing,
13 DEFAULT_ACTION,
14 DEFAULT_SOURCE_RANGE,
15 encodeOwnership,
16 findOwnedFirewallRule,
17 hasOwnershipMarker,
18 ignoreMissing,
19 listFirewallRules,
20 MAX_DESCRIPTION_LENGTH,
21 ownedByAlchemy,
22 ownershipLabels,
23 parseOwnership,
24 resolveAppsId,
25 sameText,
26 toPriority,
27 updateMaskOf,
28 } from "./internal.ts";
29
30 export type AppsFirewallIngressRuleProps = {
31 /**
32 * App Engine application id. Defaults to the current GCP project.
33 * Immutable — changing it replaces the rule.
34 */
35 appsId?: string;
36 /**
37 * Rule priority (lower is evaluated first). If omitted, a unique
38 * priority in `10000-910000` is generated. Immutable — changing it
39 * replaces the rule. The default catch-all (`2147483647`) cannot be
40 * deleted.
41 */
42 priority?: number;
43 /**
44 * Action taken on matching requests.
45 * @default "ALLOW"
46 */
47 action?: appengine.FirewallRuleActionEnum | (string & {});
48 /**
49 * CIDR source range. `"*"` matches all IPv4 and IPv6 addresses.
50 * @default "*"
51 */
52 sourceRange?: string;
53 /**
54 * Human-readable description (max 400 characters). Firewall rules have
55 * no labels field, so Alchemy ownership is stored in a `[alchemy …]`
56 * prefix and stripped from attributes.
57 */
58 description?: string;
59 };
60
61 export type AppsFirewallIngressRule = Resource<
62 "GCP.AppEngine.AppsFirewallIngressRule",
63 AppsFirewallIngressRuleProps,
64 {
65 /** App Engine application id. */
66 appsId: string;
67 /** Project id. */
68 project: string;
69 /** Rule priority (the `{ingressRulesId}` path segment). */
70 priority: number;
71 /** ALLOW or DENY. */
72 action: string;
73 /** CIDR source range. */
74 sourceRange: string | undefined;
75 /** Description with the Alchemy ownership prefix stripped. */
76 description: string | undefined;
77 },
78 never,
79 Providers
80 >;
81
82 /**
83 * An App Engine ingress firewall rule.
84 *
85 * Firewall rules have no labels field, so Alchemy stamps ownership into
86 * `description` for `list` / nuke. Application id and priority are
87 * identity — changing either replaces the rule. Action, source range,
88 * and description update in place.
89 *
90 * ### Creating a Rule
91 * **Example:** Deny a CIDR range
92 * ```typescript
93 * const rule = yield* GCP.AppEngine.AppsFirewallIngressRule("BlockOffice", {
94 * action: "DENY",
95 * sourceRange: "203.0.113.0/24",
96 * description: "office network",
97 * });
98 * ```
99 *
100 * **Example:** Explicit priority
101 * ```typescript
102 * const rule = yield* GCP.AppEngine.AppsFirewallIngressRule("AllowHealth", {
103 * priority: 12000,
104 * action: "ALLOW",
105 * sourceRange: "35.191.0.0/16",
106 * });
107 * ```
108 *
109 * ### Updating a Rule
110 * **Example:** Flip the action
111 * ```typescript
112 * const rule = yield* GCP.AppEngine.AppsFirewallIngressRule("BlockOffice", {
113 * action: "ALLOW",
114 * sourceRange: "203.0.113.0/24",
115 * });
116 * ```
117 *
118 * @resource
119 * @category AppEngine
120 */
121 export const AppsFirewallIngressRule = Resource<AppsFirewallIngressRule>(
122 "GCP.AppEngine.AppsFirewallIngressRule",
123 );
124
125 export class AppsFirewallIngressRuleNotResolved extends Data.TaggedError(
126 "GCP.AppEngine.AppsFirewallIngressRuleNotResolved",
127 )<{
128 appsId: string;
129 priority: number;
130 }> {}
131
132 const toAttrs = (rule: appengine.FirewallRule, appsId: string, project: string) => ({
133 appsId,
134 project,
135 priority: rule.priority ?? 0,
136 action: String(rule.action ?? DEFAULT_ACTION),
137 sourceRange: rule.sourceRange,
138 description: parseOwnership(rule.description).text,
139 });
140
141 const getByPriority = (appsId: string, priority: number) =>
142 catchMissing(
143 appengine.getAppsFirewallIngressRules({
144 appsId,
145 ingressRulesId: String(priority),
146 }),
147 );
148
149 export const AppsFirewallIngressRuleProvider = () =>
150 Provider.succeed(AppsFirewallIngressRule, {
151 stables: ["appsId", "project", "priority"],
152
153 diff: Effect.fn(function* ({ news, olds, output }) {
154 if (!isResolved(news)) return undefined;
155 const previousApp = olds?.appsId ?? output?.appsId;
156 const nextApp = news.appsId ?? previousApp;
157 if (previousApp !== undefined && nextApp !== undefined && nextApp !== previousApp) {
158 return { action: "replace" as const, deleteFirst: false };
159 }
160 const previousPriority = olds?.priority ?? output?.priority;
161 if (
162 previousPriority !== undefined &&
163 news.priority !== undefined &&
164 news.priority !== previousPriority
165 ) {
166 return { action: "replace" as const, deleteFirst: true };
167 }
168 return undefined;
169 }),
170
171 read: Effect.fn(function* ({ id, olds, output, previous }) {
172 const env = yield* GcpEnvironment.current;
173 const appsId = yield* resolveAppsId(olds?.appsId, output?.appsId);
174 const priority = olds?.priority ?? output?.priority;
175 let existing = priority === undefined ? undefined : yield* getByPriority(appsId, priority);
176 if (existing === undefined) {
177 existing = yield* findOwnedFirewallRule(id, yield* listFirewallRules(appsId));
178 }
179 if (existing === undefined) return undefined;
180 const attrs = toAttrs(existing, appsId, env.project);
181 return (yield* ownedByAlchemy(id, existing.description))
182 ? attrs
183 : unownedUnlessPrevious(attrs, previous, "priority");
184 }),
185
186 list: () =>
187 Effect.gen(function* () {
188 const env = yield* GcpEnvironment.current;
189 const rules = yield* listFirewallRules(env.project);
190 return rules
191 .filter((rule) => hasOwnershipMarker(rule.description))
192 .map((rule) => toAttrs(rule, env.project, env.project));
193 }),
194
195 reconcile: Effect.fn(function* ({ id, news, output }) {
196 const env = yield* GcpEnvironment.current;
197 const appsId = yield* resolveAppsId(news.appsId, output?.appsId);
198 const ownership = yield* ownershipLabels(id);
199 const description = encodeOwnership(ownership, news.description, MAX_DESCRIPTION_LENGTH);
200 const priority = yield* toPriority(id, news.priority, output?.priority);
201 const action = news.action ?? DEFAULT_ACTION;
202 const sourceRange = news.sourceRange ?? DEFAULT_SOURCE_RANGE;
203
204 let current = yield* getByPriority(appsId, priority);
205 if (current === undefined) {
206 current = yield* findOwnedFirewallRule(id, yield* listFirewallRules(appsId));
207 }
208
209 if (current === undefined) {
210 const created = yield* appengine
211 .createAppsFirewallIngressRules({
212 appsId,
213 body: {
214 priority,
215 action,
216 sourceRange,
217 description,
218 },
219 })
220 .pipe(Effect.catchTag("Conflict", () => getByPriority(appsId, priority)));
221 current = created ?? undefined;
222 }
223
224 if (current === undefined) {
225 return yield* new AppsFirewallIngressRuleNotResolved({
226 appsId,
227 priority,
228 });
229 }
230
231 const observedPriority = current.priority ?? priority;
232 const actionChanged = !sameText(String(current.action ?? ""), action);
233 const rangeChanged = !sameText(current.sourceRange, sourceRange);
234 const descriptionChanged = !sameText(current.description, description);
235 const updateMask = updateMaskOf(
236 actionChanged ? "action" : undefined,
237 rangeChanged ? "sourceRange" : undefined,
238 descriptionChanged ? "description" : undefined,
239 );
240 if (updateMask.length > 0) {
241 current = yield* appengine.patchAppsFirewallIngressRules({
242 appsId,
243 ingressRulesId: String(observedPriority),
244 updateMask,
245 body: {
246 priority: observedPriority,
247 action,
248 sourceRange,
249 description,
250 },
251 });
252 }
253
254 return toAttrs(current, appsId, env.project);
255 }),
256
257 delete: Effect.fn(function* ({ output }) {
258 if (output.priority === CATCH_ALL_PRIORITY) return;
259 yield* ignoreMissing(
260 appengine.deleteAppsFirewallIngressRules({
261 appsId: output.appsId,
262 ingressRulesId: String(output.priority),
263 }),
264 );
265 }),
266 });