@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 548 lines 17.4 KB
Raw
1 import type {
2 CertificateCheckResponse,
3 CertificateDetail,
4 CertificateSummary,
5 CertificateValidation as FlyCertificateValidation,
6 DNSRequirements,
7 } from "@distilled.cloud/fly-io/machines";
8 import * as machines from "@distilled.cloud/fly-io/machines";
9 import { isResolved } from "alchemy/Diff";
10 import * as Provider from "alchemy/Provider";
11 import { Resource } from "alchemy/Resource";
12 import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import * as Redacted from "effect/Redacted";
15 import * as Schedule from "effect/Schedule";
16 import { listOwnedApps } from "./App.ts";
17 import type { App } from "./App.ts";
18 import type { Providers } from "./Providers.ts";
19
20 /**
21 * A resource-valued prop: the resource itself, or an Effect that produces
22 * it (so `yield* App(...)` and `App(...)` both type-check).
23 */
24 type Ref<T> = T | Effect.Effect<T, never, Providers>;
25
26 export type CertificateKind = "acme" | "custom";
27
28 export type CertificateSource = "custom" | "fly";
29
30 export type CertificateDnsRequirements = {
31 a?: string[];
32 aaaa?: string[];
33 acmeChallenge?: { name?: string; target?: string };
34 cname?: string;
35 ownership?: { appValue?: string; name?: string; orgValue?: string };
36 };
37
38 export type CertificateValidationState = {
39 alpnConfigured?: boolean;
40 dnsConfigured?: boolean;
41 httpConfigured?: boolean;
42 ownershipTxtConfigured?: boolean;
43 };
44
45 export interface CertificateProps {
46 /**
47 * Parent Fly App. Accepts a `Fly.App` resource or an Effect that
48 * produces one. Changing the App replaces the Certificate.
49 */
50 app: Ref<App>;
51 /**
52 * Hostname this Certificate covers. Identity of the resource.
53 * Changing it replaces the Certificate.
54 */
55 hostname: string;
56 /**
57 * How the Certificate is issued. `"acme"` requests a Let's Encrypt
58 * certificate (`createAppAcmeCertificate`). `"custom"` uploads a PEM
59 * (`createAppCustomCertificate`). Changing kind replaces.
60 *
61 * @default "acme"
62 */
63 kind?: CertificateKind;
64 /**
65 * PEM-encoded certificate chain. Required when `kind` is `"custom"`.
66 * Updating it re-uploads in place (custom create upsert, or
67 * delete+create if the API conflicts).
68 */
69 fullchain?: string;
70 /**
71 * PEM-encoded private key. Required when `kind` is `"custom"`. Wrap
72 * with `Redacted.make` to keep it out of logs. Never stored in
73 * attributes.
74 */
75 privateKey?: Redacted.Redacted<string> | string;
76 }
77
78 export type Certificate = Resource<
79 "Fly.Certificate",
80 CertificateProps,
81 {
82 /** Physical Fly App name the Certificate is attached to. */
83 appName: string;
84 /** Hostname this Certificate covers. Identity of the resource. */
85 hostname: string;
86 /** Observed status (`active`, `pending_validation`, …). */
87 status: string | undefined;
88 /** Whether DNS/ownership validation has completed. */
89 configured: boolean | undefined;
90 /** Whether ACME issuance has been requested for this hostname. */
91 acmeRequested: boolean | undefined;
92 /** DNS records Fly expects for validation. */
93 dnsRequirements: CertificateDnsRequirements | undefined;
94 /** Per-challenge validation flags. */
95 validation: CertificateValidationState | undefined;
96 /** Observed source: `"custom"` for uploaded PEMs, `"fly"` for ACME. */
97 source: CertificateSource;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A Fly.Certificate covers a hostname on an {@link App}. Default
105 * `kind` is `"acme"` (Let's Encrypt). `"custom"` uploads a PEM.
106 *
107 * IPs and certificates attach to the App. A {@link Service} publishes
108 * ports. Fly's proxy terminates TLS on 443 once the certificate is
109 * `configured`.
110 *
111 * @see https://fly.io/docs/machines/api/certificates-resource/
112 *
113 * ### ACME certificates
114 * Request Let's Encrypt for a hostname. The Service does not change.
115 * Yield the certificate in the Stack. Point DNS at the App.
116 *
117 * **Example:** Let's Encrypt
118 * ```typescript
119 * export const Www = Fly.Certificate("Www", {
120 * app: Site,
121 * hostname: "www.example.com",
122 * });
123 * ```
124 *
125 * :::caution[Changing `hostname` replaces the Certificate]
126 * Hostname is the identity. The old hostname is deleted, then the new
127 * one is created.
128 * :::
129 *
130 * :::caution[Changing `app` or `kind` replaces the Certificate]
131 * The certificate is created on the new App or with the new issuer.
132 * :::
133 *
134 * ### DNS
135 * Point an A record at a `shared_v4` {@link IpAssignment} and an AAAA
136 * at `v6`. Plus whatever `dnsRequirements` lists for the ACME
137 * challenge. Alchemy re-checks via `checkAppCertificate` while
138 * `configured` is false.
139 *
140 * Observed attrs include `status`, `configured`, `acmeRequested`,
141 * `dnsRequirements`, and `validation`.
142 *
143 * **Example:** Yield next to a Service
144 * ```typescript
145 * export default Alchemy.Stack(
146 * "MyApp",
147 * { providers: Fly.providers(), state: Alchemy.localState() },
148 * Effect.gen(function* () {
149 * const api = yield* Api;
150 * const ip = yield* PublicIp;
151 * const v6 = yield* V6;
152 * const www = yield* Www;
153 * return {
154 * url: api.url,
155 * ip: ip.ip,
156 * v6: v6.ip,
157 * dns: www.dnsRequirements,
158 * };
159 * }),
160 * );
161 * ```
162 *
163 * ### Custom certificates
164 * `"custom"` uploads `fullchain` and `privateKey`. Wrap the key with
165 * `Redacted.make` so it never logs. Never stored in attributes.
166 * Updating the PEM re-uploads in place.
167 *
168 * **Example:** Upload a PEM
169 * ```typescript
170 * export const Www = Fly.Certificate("Www", {
171 * app: Site,
172 * hostname: "www.example.com",
173 * kind: "custom",
174 * fullchain: pem,
175 * privateKey: Redacted.make(key),
176 * });
177 * ```
178 *
179 * @resource
180 * @product Certificate
181 */
182 export const Certificate = Resource<Certificate>("Fly.Certificate");
183
184 export class CertificateNotCreated extends Data.TaggedError("Fly.CertificateNotCreated")<{
185 appName: string;
186 hostname: string;
187 }> {}
188
189 export class CertificateAppMissing extends Data.TaggedError("Fly.CertificateAppMissing")<{
190 hostname: string;
191 }> {}
192
193 export class CertificateMaterialRequired extends Data.TaggedError(
194 "Fly.CertificateMaterialRequired",
195 )<{
196 hostname: string;
197 }> {}
198
199 type ObservedCert = CertificateDetail | CertificateCheckResponse;
200
201 const appNameOf = (value: unknown): string | undefined => {
202 if (value === null || typeof value !== "object") return undefined;
203 const rec = value as { appName?: unknown; name?: unknown };
204 if (typeof rec.appName === "string" && rec.appName.length > 0) {
205 return rec.appName;
206 }
207 if (typeof rec.name === "string" && rec.name.length > 0) {
208 return rec.name;
209 }
210 return undefined;
211 };
212
213 const unwrapSecret = (
214 value: Redacted.Redacted<string> | string | undefined,
215 ): string | undefined => {
216 if (value === undefined) return undefined;
217 return Redacted.isRedacted(value) ? Redacted.value(value) : value;
218 };
219
220 const normalizePem = (pem: string | undefined): string => (pem ?? "").replace(/\r\n/g, "\n").trim();
221
222 const desiredKind = (props: Pick<CertificateProps, "kind">): CertificateKind =>
223 props.kind ?? "acme";
224
225 const kindOf = (source: CertificateSource): CertificateKind =>
226 source === "custom" ? "custom" : "acme";
227
228 const sourceOf = (detail: ObservedCert): CertificateSource => {
229 const entries = detail.certificates ?? [];
230 if (entries.some((entry) => entry.source === "custom")) return "custom";
231 if (entries.some((entry) => entry.source === "fly")) return "fly";
232 return detail.acme_requested === true ? "fly" : "custom";
233 };
234
235 const sourceFromSummary = (summary: CertificateSummary): CertificateSource =>
236 summary.has_custom_certificate === true ? "custom" : "fly";
237
238 const toDnsRequirements = (
239 req: DNSRequirements | undefined,
240 ): CertificateDnsRequirements | undefined => {
241 if (req === undefined) return undefined;
242 return {
243 a: req.a,
244 aaaa: req.aaaa,
245 acmeChallenge:
246 req.acme_challenge === undefined
247 ? undefined
248 : {
249 name: req.acme_challenge.name,
250 target: req.acme_challenge.target,
251 },
252 cname: req.cname,
253 ownership:
254 req.ownership === undefined
255 ? undefined
256 : {
257 appValue: req.ownership.app_value,
258 name: req.ownership.name,
259 orgValue: req.ownership.org_value,
260 },
261 };
262 };
263
264 const toValidation = (
265 validation: FlyCertificateValidation | undefined,
266 ): CertificateValidationState | undefined => {
267 if (validation === undefined) return undefined;
268 return {
269 alpnConfigured: validation.alpn_configured,
270 dnsConfigured: validation.dns_configured,
271 httpConfigured: validation.http_configured,
272 ownershipTxtConfigured: validation.ownership_txt_configured,
273 };
274 };
275
276 const toAttrs = (
277 appName: string,
278 detail: ObservedCert,
279 fallbackHostname?: string,
280 ): Certificate["Attributes"] => ({
281 appName,
282 hostname: detail.hostname ?? fallbackHostname ?? "",
283 status: detail.status,
284 configured: detail.configured,
285 acmeRequested: detail.acme_requested,
286 dnsRequirements: toDnsRequirements(detail.dns_requirements),
287 validation: toValidation(detail.validation),
288 source: sourceOf(detail),
289 });
290
291 const toAttrsFromSummary = (
292 appName: string,
293 summary: CertificateSummary,
294 ): Certificate["Attributes"] | undefined => {
295 const hostname = summary.hostname;
296 if (hostname === undefined || hostname.length === 0) return undefined;
297 return {
298 appName,
299 hostname,
300 status: summary.status,
301 configured: summary.configured,
302 acmeRequested: summary.acme_requested,
303 dnsRequirements: undefined,
304 validation: {
305 alpnConfigured: summary.acme_alpn_configured,
306 dnsConfigured: summary.acme_dns_configured,
307 httpConfigured: summary.acme_http_configured,
308 ownershipTxtConfigured: summary.ownership_txt_configured,
309 },
310 source: sourceFromSummary(summary),
311 };
312 };
313
314 const getByHostname = (appName: string, hostname: string) =>
315 machines
316 .getAppCertificate({ app_name: appName, hostname })
317 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
318
319 const listAppCertificates = (appName: string) =>
320 Effect.gen(function* () {
321 const all: CertificateSummary[] = [];
322 let cursor: string | undefined;
323 for (let i = 0; i < 8; i++) {
324 const page = yield* machines
325 .listAppCertificates({
326 app_name: appName,
327 cursor,
328 limit: 100,
329 })
330 .pipe(
331 Effect.catchTag(["NotFound", "Forbidden"], () =>
332 Effect.succeed({
333 certificates: [] as CertificateSummary[],
334 next_cursor: undefined,
335 }),
336 ),
337 );
338 all.push(...(page.certificates ?? []));
339 if (page.next_cursor === undefined || page.next_cursor.length === 0) {
340 break;
341 }
342 cursor = page.next_cursor;
343 }
344 return all;
345 });
346
347 const waitUntilGone = (appName: string, hostname: string) =>
348 getByHostname(appName, hostname).pipe(
349 Effect.map((found) => found === undefined),
350 Effect.repeat({
351 schedule: Schedule.spaced("1 second"),
352 until: (gone) => gone,
353 times: 8,
354 }),
355 );
356
357 const requireCustomMaterial = (
358 hostname: string,
359 fullchain: string | undefined,
360 privateKey: string | undefined,
361 ) =>
362 fullchain === undefined ||
363 fullchain.length === 0 ||
364 privateKey === undefined ||
365 privateKey.length === 0
366 ? new CertificateMaterialRequired({ hostname })
367 : undefined;
368
369 const createAcme = (appName: string, hostname: string) =>
370 machines
371 .createAppAcmeCertificate({
372 app_name: appName,
373 hostname,
374 })
375 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
376
377 const createCustom = (appName: string, hostname: string, fullchain: string, privateKey: string) =>
378 machines
379 .createAppCustomCertificate({
380 app_name: appName,
381 hostname,
382 fullchain,
383 private_key: privateKey,
384 })
385 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
386
387 const replaceCustom = (appName: string, hostname: string, fullchain: string, privateKey: string) =>
388 Effect.gen(function* () {
389 yield* machines
390 .deleteAppCustomCertificate({
391 app_name: appName,
392 hostname,
393 })
394 .pipe(Effect.catchTag("NotFound", () => Effect.void));
395 yield* machines.createAppCustomCertificate({
396 app_name: appName,
397 hostname,
398 fullchain,
399 private_key: privateKey,
400 });
401 });
402
403 export const CertificateProvider = () =>
404 Provider.succeed(Certificate, {
405 stables: ["appName", "hostname", "source"],
406 nuke: { dependsOn: ["Fly.App"] },
407
408 diff: Effect.fn(function* ({ news, output }) {
409 if (news === undefined || !isResolved(news)) return undefined;
410 if (output === undefined) return undefined;
411 const appName = appNameOf(news.app);
412 const appChanged = appName !== undefined && appName !== output.appName;
413 const hostnameChanged = news.hostname !== output.hostname;
414 const nextKind = desiredKind(news);
415 const kindChanged = nextKind !== kindOf(output.source);
416 if (appChanged || hostnameChanged || kindChanged) {
417 return {
418 action: "replace" as const,
419 // Same hostname cannot exist twice — delete the old kind first.
420 deleteFirst: !hostnameChanged && !appChanged,
421 };
422 }
423 return undefined;
424 }),
425
426 read: Effect.fn(function* ({ olds, output }) {
427 const appName = output?.appName ?? appNameOf(olds?.app);
428 const hostname = output?.hostname ?? olds?.hostname;
429 if (appName === undefined || hostname === undefined) return undefined;
430 const found = yield* getByHostname(appName, hostname);
431 if (found === undefined) return undefined;
432 return toAttrs(appName, found, hostname);
433 }),
434
435 list: Effect.fn(function* () {
436 const apps = yield* listOwnedApps();
437 const rows = yield* Effect.forEach(
438 apps,
439 (app) =>
440 listAppCertificates(app.appName).pipe(
441 Effect.map((certs) =>
442 certs.flatMap((item) => {
443 const attrs = toAttrsFromSummary(app.appName, item);
444 return attrs === undefined ? [] : [attrs];
445 }),
446 ),
447 ),
448 { concurrency: 8 },
449 );
450 return rows.flat();
451 }),
452
453 reconcile: Effect.fn(function* ({ news, olds, output }) {
454 const props = news ?? ({} as CertificateProps);
455 const appName = appNameOf(props.app) ?? output?.appName;
456 const hostname = props.hostname ?? output?.hostname;
457 if (appName === undefined) {
458 return yield* new CertificateAppMissing({
459 hostname: hostname ?? "",
460 });
461 }
462 if (hostname === undefined || hostname.length === 0) {
463 return yield* new CertificateNotCreated({
464 appName,
465 hostname: "",
466 });
467 }
468
469 const kind = desiredKind(props);
470
471 // Observe by cached identity, then by desired hostname.
472 let current =
473 output?.hostname !== undefined
474 ? yield* getByHostname(
475 output.appName.length > 0 ? output.appName : appName,
476 output.hostname,
477 )
478 : undefined;
479 if (current === undefined && (output?.hostname !== hostname || output?.appName !== appName)) {
480 current = yield* getByHostname(appName, hostname);
481 }
482
483 let createdThisPass = false;
484 if (current === undefined) {
485 if (kind === "custom") {
486 const fullchain = props.fullchain;
487 const privateKey = unwrapSecret(props.privateKey);
488 const missing = requireCustomMaterial(hostname, fullchain, privateKey);
489 if (missing !== undefined) return yield* missing;
490 const created = yield* createCustom(appName, hostname, fullchain!, privateKey!);
491 current = created ?? (yield* getByHostname(appName, hostname));
492 } else {
493 const created = yield* createAcme(appName, hostname);
494 current = created ?? (yield* getByHostname(appName, hostname));
495 }
496 createdThisPass = true;
497 }
498
499 if (current === undefined) {
500 return yield* new CertificateNotCreated({ appName, hostname });
501 }
502
503 if (kind === "custom") {
504 const fullchain = props.fullchain;
505 const privateKey = unwrapSecret(props.privateKey);
506 const missing = requireCustomMaterial(hostname, fullchain, privateKey);
507 if (missing !== undefined) return yield* missing;
508 const previousChain = olds?.fullchain;
509 const previousKey = unwrapSecret(olds?.privateKey);
510 const materialChanged =
511 olds === undefined ||
512 normalizePem(fullchain) !== normalizePem(previousChain) ||
513 normalizePem(privateKey) !== normalizePem(previousKey);
514 if (!createdThisPass && materialChanged) {
515 const upserted = yield* createCustom(appName, hostname, fullchain!, privateKey!);
516 if (upserted === undefined) {
517 yield* replaceCustom(appName, hostname, fullchain!, privateKey!);
518 }
519 current = upserted ?? (yield* getByHostname(appName, hostname)) ?? current;
520 }
521 } else if (current.configured !== true) {
522 const checked = yield* machines
523 .checkAppCertificate({
524 app_name: appName,
525 hostname,
526 })
527 .pipe(Effect.catchTag(["NotFound", "BadRequest"], () => Effect.undefined));
528 if (checked !== undefined) {
529 current = checked;
530 }
531 }
532
533 return toAttrs(appName, current, hostname);
534 }),
535
536 delete: Effect.fn(function* ({ output }) {
537 const appName = output.appName;
538 const hostname = output.hostname;
539 if (appName.length === 0 || hostname.length === 0) return;
540 yield* machines
541 .deleteAppCertificate({
542 app_name: appName,
543 hostname,
544 })
545 .pipe(Effect.catchTag("NotFound", () => Effect.void));
546 yield* waitUntilGone(appName, hostname);
547 }),
548 });