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

main
ts 182 lines 6.27 KB
Raw
1 import * as iam from "@distilled.cloud/gcp/iam_v2";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import {
6 alchemyLabelKeys,
7 createInternalLabels,
8 hasAlchemyLabels,
9 sanitizeLabelValue,
10 toLabels,
11 } from "../Labels.ts";
12 import { waitForOperation as waitForLongRunning, type LongRunningOperation } from "../Operation.ts";
13
14 export const MAX_POLICY_ID = 63;
15
16 export class ResourceNotResolved extends Data.TaggedError("GCP.IAM.ResourceNotResolved")<{
17 resourceName: string;
18 }> {}
19
20 export const lastSegment = (value: string) => {
21 const trimmed = value.replace(/\/+$/, "");
22 const parts = trimmed.split("/");
23 return parts[parts.length - 1] || trimmed;
24 };
25
26 export const attachmentPointOf = (project: string, attachmentPoint?: string) => {
27 if (attachmentPoint && attachmentPoint.length > 0) {
28 return attachmentPoint.includes("%2F") ? attachmentPoint : encodeURIComponent(attachmentPoint);
29 }
30 return encodeURIComponent(`cloudresourcemanager.googleapis.com/projects/${project}`);
31 };
32
33 export const denypoliciesParent = (attachmentPoint: string) =>
34 `policies/${attachmentPoint}/denypolicies`;
35
36 export const policyName = (attachmentPoint: string, policyId: string) =>
37 `${denypoliciesParent(attachmentPoint)}/${policyId}`;
38
39 export const parsePolicyName = (name: string) => {
40 const parts = name.split("/").filter((part) => part.length > 0);
41 const policiesAt = parts.indexOf("policies");
42 const denyAt = parts.lastIndexOf("denypolicies");
43 return {
44 attachmentPoint: policiesAt >= 0 && parts[policiesAt + 1] ? parts[policiesAt + 1]! : "",
45 policyId: denyAt >= 0 && parts[denyAt + 1] ? parts[denyAt + 1]! : lastSegment(name),
46 };
47 };
48
49 const rfc1035 = (value: string) => {
50 let next = value
51 .toLowerCase()
52 .replace(/[^a-z0-9.-]/g, "-")
53 .replace(/-+/g, "-")
54 .replace(/^-+|-+$/g, "");
55 if (!/^[a-z]/.test(next)) next = `p${next}`;
56 next = next.slice(0, MAX_POLICY_ID).replace(/-+$/g, "");
57 if (next.length < 3) next = `${next}xxx`.slice(0, MAX_POLICY_ID);
58 return next;
59 };
60
61 export const toPolicyId = (id: string, requested: string | undefined, existing?: string) =>
62 Effect.gen(function* () {
63 if (requested !== undefined) return rfc1035(requested);
64 if (existing !== undefined) return existing;
65 return rfc1035(
66 yield* createPhysicalName({
67 id,
68 maxLength: MAX_POLICY_ID,
69 lowercase: true,
70 }),
71 );
72 });
73
74 export const ownershipAnnotations = (id: string) =>
75 Effect.gen(function* () {
76 return toLabels(yield* createInternalLabels(id));
77 });
78
79 export const hasOwnershipAnnotations = (
80 annotations: Record<string, string | undefined> | null | undefined,
81 ) => Object.keys(annotations ?? {}).some((key) => key.startsWith("alchemy-"));
82
83 export const ownedByAlchemy = (
84 id: string,
85 annotations: Record<string, string | undefined> | null | undefined,
86 ) =>
87 hasAlchemyLabels(
88 id,
89 Object.fromEntries(
90 Object.entries(annotations ?? {}).filter(
91 (entry): entry is [string, string] => typeof entry[1] === "string",
92 ),
93 ),
94 );
95
96 export const userAnnotations = (
97 annotations: Record<string, string | undefined> | null | undefined,
98 ): Record<string, string> =>
99 Object.fromEntries(
100 Object.entries(annotations ?? {}).filter(
101 ([key, value]) => !key.startsWith("alchemy-") && typeof value === "string",
102 ),
103 ) as Record<string, string>;
104
105 export { alchemyLabelKeys, sanitizeLabelValue };
106
107 /** IAM descriptions are capped at 256 characters. */
108 export const DESCRIPTION_MAX = 256;
109
110 /**
111 * Ownership marker for IAM resources that have no labels (service accounts,
112 * workload identity pools and providers). Alchemy stamps `[alchemy alchemy-stack=… alchemy-stage=…
113 * alchemy-id=…]` in front of the user description and strips it back out of
114 * the `description` attribute.
115 */
116 export const encodeOwnedDescription = (
117 labels: Record<string, string>,
118 description: string | undefined,
119 maxLength = DESCRIPTION_MAX,
120 ): string => {
121 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
122 if (!description) return marker.slice(0, maxLength);
123 const sep = "\n";
124 const budget = maxLength - marker.length - sep.length;
125 if (budget <= 0) return marker.slice(0, maxLength);
126 return `${marker}${sep}${description.slice(0, budget)}`;
127 };
128
129 export const parseOwnedDescription = (
130 description: string | undefined,
131 ): {
132 labels: Record<string, string>;
133 description: string | undefined;
134 } => {
135 if (!description?.startsWith("[alchemy ")) {
136 return { labels: {}, description: description || undefined };
137 }
138 const end = description.indexOf("]");
139 if (end < 0) return { labels: {}, description };
140 const labels: Record<string, string> = {};
141 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
142 const eq = part.indexOf("=");
143 if (eq > 0) {
144 labels[part.slice(0, eq)] = part.slice(eq + 1);
145 }
146 }
147 const rest = description.slice(end + 1).replace(/^\n/, "");
148 return { labels, description: rest.length > 0 ? rest : undefined };
149 };
150
151 export const hasOwnedDescription = (description: string | undefined) =>
152 Object.keys(parseOwnedDescription(description).labels).some((key) => key.startsWith("alchemy-"));
153
154 /** Deny policy operations finish within seconds. */
155 const OPERATION_BUDGET = "5 minutes";
156
157 /**
158 * Wait for a long-running operation. ALREADY_EXISTS (code 6) means a
159 * concurrent create won the race; reconcile observes the resource next.
160 */
161 export const waitForOperation = (operation: LongRunningOperation) =>
162 waitForLongRunning(operation, (name) => iam.getPoliciesOperations({ name }), {
163 budget: OPERATION_BUDGET,
164 }).pipe(
165 Effect.catchIf(
166 (error) => error._tag === "GCP.OperationFailed" && error.code === 6,
167 () => Effect.succeed(operation),
168 ),
169 );
170
171 /**
172 * Wait for a delete operation. A vanished operation or NOT_FOUND (code 5)
173 * means the resource is already gone.
174 */
175 export const waitForDeleteOperation = (operation: LongRunningOperation) =>
176 waitForOperation(operation).pipe(
177 Effect.catchIf(
178 (error) =>
179 error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5),
180 () => Effect.succeed(operation),
181 ),
182 );