@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 306 lines 10.3 KB
Raw
1 import * as appengine from "@distilled.cloud/gcp/appengine_v1";
2 import { Unowned } 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 catchMissing,
12 encodeOwnership,
13 findOwnedCertificate,
14 hasOwnershipMarker,
15 ignoreMissing,
16 listAuthorizedCertificates,
17 MAX_DISPLAY_NAME_LENGTH,
18 ownedByAlchemy,
19 ownershipLabels,
20 parseCertificateName,
21 parseOwnership,
22 resolveAppsId,
23 sameText,
24 toDisplayName,
25 updateMaskOf,
26 } from "./internal.ts";
27
28 export type AppsAuthorizedCertificateRawData = {
29 /** PEM-encoded x.509 public certificate, including header and footer. */
30 publicCertificate?: string;
31 /**
32 * Unencrypted PEM-encoded RSA private key (2048 bits or fewer), including
33 * header and footer. Input-only.
34 */
35 privateKey?: string;
36 };
37
38 export type AppsAuthorizedCertificateProps = {
39 /**
40 * App Engine application id (the `{appsId}` segment of
41 * `apps/{appsId}/authorizedCertificates/{id}`). Defaults to the current
42 * GCP project. Immutable — changing it replaces the certificate.
43 */
44 appsId?: string;
45 /**
46 * Server-assigned certificate id. Immutable — changing it replaces
47 * the certificate.
48 */
49 certificateId?: string;
50 /**
51 * User-specified display name. App Engine certificates have no labels
52 * field, so Alchemy ownership is stored in a `[alchemy …]` prefix and
53 * stripped from attributes.
54 */
55 displayName?: string;
56 /**
57 * PEM-encoded x.509 public certificate. Input-only. Updating it renews
58 * the certificate in place for the same domains.
59 */
60 publicCertificate?: string;
61 /**
62 * Unencrypted PEM-encoded RSA private key. Input-only.
63 */
64 privateKey?: string;
65 /**
66 * Nested certificate payload. Top-level `publicCertificate` /
67 * `privateKey` take precedence when both are set.
68 */
69 certificateRawData?: AppsAuthorizedCertificateRawData;
70 };
71
72 export type AppsAuthorizedCertificate = Resource<
73 "GCP.AppEngine.AppsAuthorizedCertificate",
74 AppsAuthorizedCertificateProps,
75 {
76 /** Full resource name `apps/{appsId}/authorizedCertificates/{id}`. */
77 name: string;
78 /** Server-assigned certificate id. */
79 certificateId: string;
80 /** App Engine application id. */
81 appsId: string;
82 /** Project id. */
83 project: string;
84 /** Display name with the Alchemy ownership prefix stripped. */
85 displayName: string | undefined;
86 /** Topmost domains this certificate applies to. */
87 domainNames: string[];
88 /** RFC3339 expiry. */
89 expireTime: string | undefined;
90 /** Count of domain mappings using this certificate. */
91 domainMappingsCount: number | undefined;
92 /** Managed-certificate status, if App Engine manages this cert. */
93 managedStatus: string | undefined;
94 /** Last managed-certificate renewal time. */
95 lastRenewalTime: string | undefined;
96 /** Domain mapping resource names visible to the caller. */
97 visibleDomainMappings: string[];
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * An SSL certificate uploaded to an App Engine application.
105 *
106 * App Engine certificates have no labels field, so Alchemy stamps
107 * ownership into `displayName` for `list` / nuke. The application id and
108 * server-assigned certificate id are identity — changing either replaces
109 * the certificate. Display name and PEM data update in place.
110 *
111 * ### Creating a Certificate
112 * **Example:** Upload a self-managed certificate
113 * ```typescript
114 * const cert = yield* GCP.AppEngine.AppsAuthorizedCertificate("FrontendTls", {
115 * displayName: "frontend",
116 * publicCertificate,
117 * privateKey,
118 * });
119 * ```
120 *
121 * **Example:** Nested raw-data payload
122 * ```typescript
123 * const cert = yield* GCP.AppEngine.AppsAuthorizedCertificate("FrontendTls", {
124 * certificateRawData: {
125 * publicCertificate,
126 * privateKey,
127 * },
128 * });
129 * ```
130 *
131 * ### Updating a Certificate
132 * **Example:** Rename
133 * ```typescript
134 * const cert = yield* GCP.AppEngine.AppsAuthorizedCertificate("FrontendTls", {
135 * displayName: "frontend-prod",
136 * publicCertificate,
137 * privateKey,
138 * });
139 * ```
140 *
141 * @resource
142 * @category AppEngine
143 */
144 export const AppsAuthorizedCertificate = Resource<AppsAuthorizedCertificate>(
145 "GCP.AppEngine.AppsAuthorizedCertificate",
146 );
147
148 export class AppsAuthorizedCertificateNotResolved extends Data.TaggedError(
149 "GCP.AppEngine.AppsAuthorizedCertificateNotResolved",
150 )<{
151 resourceName: string;
152 }> {}
153
154 const rawDataOf = (props: AppsAuthorizedCertificateProps) => {
155 const publicCertificate = props.publicCertificate ?? props.certificateRawData?.publicCertificate;
156 const privateKey = props.privateKey ?? props.certificateRawData?.privateKey;
157 if (publicCertificate === undefined && privateKey === undefined) {
158 return undefined;
159 }
160 return { publicCertificate, privateKey };
161 };
162
163 const toAttrs = (certificate: appengine.AuthorizedCertificate, appsId: string, project: string) => {
164 const parsed = parseCertificateName(certificate.name ?? "");
165 return {
166 name: certificate.name ?? `apps/${appsId}/authorizedCertificates/${certificate.id ?? ""}`,
167 certificateId: certificate.id ?? parsed.certificateId,
168 appsId: parsed.appsId ?? appsId,
169 project,
170 displayName: parseOwnership(certificate.displayName).text,
171 domainNames: [...(certificate.domainNames ?? [])],
172 expireTime: certificate.expireTime,
173 domainMappingsCount: certificate.domainMappingsCount,
174 managedStatus: certificate.managedCertificate?.status,
175 lastRenewalTime: certificate.managedCertificate?.lastRenewalTime,
176 visibleDomainMappings: [...(certificate.visibleDomainMappings ?? [])],
177 };
178 };
179
180 const getById = (appsId: string, certificateId: string) =>
181 certificateId.length === 0
182 ? Effect.undefined
183 : catchMissing(
184 appengine.getAppsAuthorizedCertificates({
185 appsId,
186 authorizedCertificatesId: certificateId,
187 }),
188 );
189
190 export const AppsAuthorizedCertificateProvider = () =>
191 Provider.succeed(AppsAuthorizedCertificate, {
192 stables: ["name", "certificateId", "appsId", "project"],
193
194 diff: Effect.fn(function* ({ news, olds, output }) {
195 if (!isResolved(news)) return undefined;
196 const previousApp = olds?.appsId ?? output?.appsId;
197 const nextApp = news.appsId ?? previousApp;
198 if (previousApp !== undefined && nextApp !== undefined && nextApp !== previousApp) {
199 return { action: "replace" as const, deleteFirst: false };
200 }
201 const previousId = olds?.certificateId ?? output?.certificateId;
202 if (
203 previousId !== undefined &&
204 news.certificateId !== undefined &&
205 news.certificateId !== previousId
206 ) {
207 return { action: "replace" as const, deleteFirst: false };
208 }
209 return undefined;
210 }),
211
212 read: Effect.fn(function* ({ id, olds, output }) {
213 const env = yield* GcpEnvironment.current;
214 const appsId = yield* resolveAppsId(olds?.appsId, output?.appsId);
215 let existing = yield* getById(appsId, olds?.certificateId ?? output?.certificateId ?? "");
216 if (existing === undefined) {
217 existing = yield* findOwnedCertificate(id, yield* listAuthorizedCertificates(appsId));
218 }
219 if (existing === undefined) return undefined;
220 const attrs = toAttrs(existing, appsId, env.project);
221 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
222 }),
223
224 list: () =>
225 Effect.gen(function* () {
226 const env = yield* GcpEnvironment.current;
227 const certificates = yield* listAuthorizedCertificates(env.project);
228 return certificates
229 .filter((certificate) => hasOwnershipMarker(certificate.displayName))
230 .map((certificate) => toAttrs(certificate, env.project, env.project));
231 }),
232
233 reconcile: Effect.fn(function* ({ id, news, output }) {
234 const env = yield* GcpEnvironment.current;
235 const appsId = yield* resolveAppsId(news.appsId, output?.appsId);
236 const ownership = yield* ownershipLabels(id);
237 const displayName = encodeOwnership(
238 ownership,
239 yield* toDisplayName(id, news.displayName, output?.displayName),
240 MAX_DISPLAY_NAME_LENGTH,
241 );
242 const certificateRawData = rawDataOf(news);
243
244 let current = yield* getById(appsId, news.certificateId ?? output?.certificateId ?? "");
245 if (current === undefined) {
246 current = yield* findOwnedCertificate(id, yield* listAuthorizedCertificates(appsId));
247 }
248
249 if (current === undefined) {
250 const created = yield* appengine
251 .createAppsAuthorizedCertificates({
252 appsId,
253 body: {
254 displayName,
255 certificateRawData,
256 },
257 })
258 .pipe(
259 Effect.catchTag("Conflict", () =>
260 Effect.gen(function* () {
261 return yield* findOwnedCertificate(id, yield* listAuthorizedCertificates(appsId));
262 }),
263 ),
264 );
265 current = created ?? undefined;
266 }
267
268 if (current === undefined) {
269 return yield* new AppsAuthorizedCertificateNotResolved({
270 resourceName: `apps/${appsId}/authorizedCertificates/${news.certificateId ?? ""}`,
271 });
272 }
273
274 const certificateId = current.id ?? output?.certificateId ?? "";
275 const nameChanged = !sameText(current.displayName, displayName);
276 const pemChanged = certificateRawData !== undefined;
277 const updateMask = updateMaskOf(
278 nameChanged ? "displayName" : undefined,
279 pemChanged ? "certificateRawData" : undefined,
280 );
281 if (updateMask.length > 0) {
282 current = yield* appengine.patchAppsAuthorizedCertificates({
283 appsId,
284 authorizedCertificatesId: certificateId,
285 updateMask,
286 body: {
287 displayName,
288 certificateRawData,
289 },
290 });
291 }
292
293 return toAttrs(current, appsId, env.project);
294 }),
295
296 delete: Effect.fn(function* ({ output }) {
297 if (output.certificateId.length === 0) return;
298 if (output.managedStatus !== undefined) return;
299 yield* ignoreMissing(
300 appengine.deleteAppsAuthorizedCertificates({
301 appsId: output.appsId,
302 authorizedCertificatesId: output.certificateId,
303 }),
304 );
305 }),
306 });