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

main
ts 484 lines 14.4 KB
Raw
1 import type * as cloudfront from "@distilled.cloud/aws/cloudfront";
2 import type { Input } from "alchemy/Input";
3 import * as Namespace from "alchemy/Namespace";
4 import * as Output from "alchemy/Output";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { Distribution } from "../CloudFront/Distribution.ts";
8 import { Invalidation } from "../CloudFront/Invalidation.ts";
9 import {
10 MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID,
11 MANAGED_CACHING_DISABLED_POLICY_ID,
12 MANAGED_CACHING_OPTIMIZED_POLICY_ID,
13 } from "../CloudFront/ManagedPolicies.ts";
14 import { OriginAccessControl } from "../CloudFront/OriginAccessControl.ts";
15 import { domainCertificate, resolveDomainDns } from "../CustomDomain.ts";
16 import type { Service } from "../ECS/Service.ts";
17 import type { PolicyStatement } from "../IAM/Policy.ts";
18 import { Function } from "../Lambda/Function.ts";
19 import { Bucket } from "../S3/Bucket.ts";
20 import type { AssetFileOption } from "./AssetDeployment.ts";
21 import { AssetDeployment } from "./AssetDeployment.ts";
22 import {
23 normalizeWebsiteDomain,
24 type SsrSiteRouteTargets,
25 type WebsiteInvalidationProps,
26 type WebsiteStandaloneDomainProps,
27 } from "./shared.ts";
28
29 export class SsrSiteInvalidProps extends Data.TaggedError("SsrSiteInvalidProps")<{
30 readonly message: string;
31 readonly cause?: unknown;
32 }> {}
33
34 /**
35 * The dynamic origin CloudFront forwards requests to: a Lambda Function URL,
36 * a public ECS Service, or any plain URL.
37 */
38 export type SsrSiteServerOrigin =
39 | {
40 type: "lambda";
41 /**
42 * Lambda Function created with `functionUrl` enabled — its function URL
43 * becomes the origin.
44 */
45 function: Function;
46 /**
47 * Protocol CloudFront uses to reach the origin.
48 * @default "https-only"
49 */
50 originProtocolPolicy?: "https-only";
51 }
52 | {
53 type: "ecs";
54 /**
55 * ECS Service created with `public: true` — its load balancer URL
56 * becomes the origin.
57 */
58 service: Service;
59 /**
60 * Protocol CloudFront uses to reach the origin.
61 * @default "https-only"
62 */
63 originProtocolPolicy?: "http-only" | "https-only" | "match-viewer";
64 }
65 | {
66 type: "url";
67 /**
68 * Origin URL to forward requests to.
69 */
70 url: Input<string>;
71 /**
72 * Protocol CloudFront uses to reach the origin.
73 * @default "https-only"
74 */
75 originProtocolPolicy?: cloudfront.OriginProtocolPolicy;
76 };
77
78 export interface SsrSiteProps {
79 /**
80 * Dynamic server origin behind CloudFront.
81 */
82 server: SsrSiteServerOrigin;
83 /**
84 * Optional custom domain (Route 53 by default; see `dns`). A string is
85 * shorthand for `{ name }`; `null` explicitly clears a previously set
86 * domain.
87 */
88 domain?: string | WebsiteStandaloneDomainProps | null;
89 /**
90 * Optional static asset bundle to serve from S3.
91 */
92 assets?: {
93 /**
94 * Local build output directory to upload.
95 */
96 sourcePath: Input<string>;
97 /**
98 * Optional deterministic S3 bucket name.
99 */
100 bucketName?: string;
101 /**
102 * Optional asset key prefix.
103 */
104 prefix?: string;
105 /**
106 * Path pattern that should be served from the asset bucket.
107 * @default "/_assets/*"
108 */
109 pathPattern?: string;
110 /**
111 * Remove stale files under the prefix.
112 * @default false
113 */
114 purge?: boolean;
115 /**
116 * Optional file overrides.
117 */
118 fileOptions?: AssetFileOption[];
119 };
120 /**
121 * CloudFront cache policy ID for the dynamic server route.
122 * @default CloudFront managed CachingDisabled
123 */
124 cachePolicyId?: Input<string>;
125 /**
126 * Cache invalidation behavior for asset updates.
127 * @default false
128 */
129 invalidate?: false | WebsiteInvalidationProps;
130 /**
131 * Whether to create a standalone CloudFront distribution for the site.
132 * Set this to `false` when the site should be routed through `AWS.Website.Router`.
133 * @default true
134 */
135 cdn?: boolean;
136 /**
137 * User-defined tags applied to created resources.
138 */
139 tags?: Record<string, string>;
140 }
141
142 const serverUrlOf = (server: SsrSiteServerOrigin): Input<string> => {
143 switch (server.type) {
144 case "lambda":
145 return Output.map((url: string | undefined) => {
146 if (!url) {
147 throw new Error(
148 "SsrSite lambda origins require a function created with `functionUrl` enabled.",
149 );
150 }
151 return url;
152 })(server.function.functionUrl as any) as any;
153 case "ecs":
154 return Output.map((url: string | undefined) => {
155 if (!url) {
156 throw new Error("SsrSite ECS origins require a service created with `public: true`.");
157 }
158 return url;
159 })(server.service.url as any) as any;
160 case "url":
161 return server.url;
162 }
163 };
164
165 const serverOriginOf = (server: SsrSiteServerOrigin): Input<string> =>
166 Output.map((url: string) => new URL(url).hostname)(serverUrlOf(server) as any) as any;
167
168 /**
169 * A server-rendered website behind CloudFront.
170 *
171 * `SsrSite` serves a dynamic origin behind CloudFront and can optionally split
172 * immutable static assets into a private S3 bucket origin.
173 * ### Creating SSR Sites
174 * **Example:** Lambda URL Origin
175 * ```typescript
176 * const site = yield* SsrSite("App", {
177 * server: {
178 * type: "lambda",
179 * function: appFunction,
180 * },
181 * });
182 * ```
183 *
184 * **Example:** SSR With Static Assets
185 * ```typescript
186 * const site = yield* SsrSite("App", {
187 * server: {
188 * type: "lambda",
189 * function: appFunction,
190 * },
191 * assets: {
192 * sourcePath: "./dist/client",
193 * },
194 * });
195 * ```
196 *
197 * ### Custom Domains
198 * **Example:** SSR Site With A Route 53 Domain
199 * ```typescript
200 * const site = yield* SsrSite("App", {
201 * server: {
202 * type: "ecs",
203 * service: webService,
204 * },
205 * domain: {
206 * name: "app.example.com",
207 * hostedZoneId: zone.hostedZoneId,
208 * },
209 * });
210 * ```
211 *
212 * **Example:** SSR Site With A Cloudflare Domain
213 * ```typescript
214 * // Certificate validation and the CNAME to CloudFront go through the
215 * // Cloudflare zone. Requires `Cloudflare.providers()` in the stack.
216 * const site = yield* SsrSite("App", {
217 * server: {
218 * type: "ecs",
219 * service: webService,
220 * },
221 * domain: {
222 * name: "app.example.com",
223 * dns: Cloudflare.DNS.Adapter(),
224 * },
225 * });
226 * ```
227 *
228 * ### Router Composition
229 * **Example:** Route Through An Existing Router
230 * ```typescript
231 * // Skip the standalone distribution and register the returned
232 * // routeTargets on an AWS.Website.Router instead.
233 * const site = yield* SsrSite("App", {
234 * server: {
235 * type: "lambda",
236 * function: appFunction,
237 * },
238 * cdn: false,
239 * });
240 *
241 * const router = yield* AWS.Website.Router("WebsiteRouter", {
242 * routes: {
243 * "/*": site.routeTargets.server,
244 * },
245 * });
246 * ```
247 *
248 * @resource
249 */
250 export const SsrSite = (id: string, props: SsrSiteProps) =>
251 Effect.gen(function* () {
252 const domain = normalizeWebsiteDomain(props.domain);
253 const assetPattern = props.assets?.pathPattern ?? "/_assets/*";
254 const serverUrl = serverUrlOf(props.server);
255 const serverOriginHost = serverOriginOf(props.server);
256
257 const assetBucket = props.assets
258 ? yield* Bucket("AssetsBucket", {
259 bucketName: props.assets.bucketName,
260 tags: props.tags,
261 })
262 : undefined;
263
264 const assetFiles =
265 props.assets && assetBucket
266 ? yield* AssetDeployment("AssetsFiles", {
267 bucket: assetBucket,
268 sourcePath: props.assets.sourcePath,
269 prefix: props.assets.prefix,
270 purge: props.assets.purge ?? false,
271 fileOptions: props.assets.fileOptions,
272 })
273 : undefined;
274
275 const assetOac =
276 props.assets && assetBucket
277 ? yield* OriginAccessControl("AssetsOriginAccessControl", {
278 originType: "s3",
279 description: `${id} SSR asset origin access control`,
280 })
281 : undefined;
282
283 const routeTargets: SsrSiteRouteTargets = {
284 server: {
285 url: serverUrl,
286 originProtocolPolicy: props.server.originProtocolPolicy ?? "https-only",
287 },
288 assets:
289 assetBucket && assetOac
290 ? {
291 pattern: assetPattern,
292 route: {
293 bucket: assetBucket,
294 originAccessControlId: assetOac.originAccessControlId,
295 originPath: props.assets?.prefix,
296 version: assetFiles?.version,
297 },
298 }
299 : undefined,
300 };
301
302 if (props.cdn === false) {
303 return {
304 assetBucket,
305 assetFiles,
306 assetOriginAccessControl: assetOac,
307 certificate: undefined,
308 distribution: undefined,
309 records: [],
310 invalidation: undefined,
311 routeTargets,
312 url: undefined,
313 urls: [] as Input<string>[],
314 };
315 }
316
317 if (domain && domain.dns === false && !domain.cert) {
318 return yield* new SsrSiteInvalidProps({
319 message: "SsrSite domain configuration with `dns: false` requires `cert`.",
320 });
321 }
322
323 const managed =
324 domain && !domain.cert
325 ? yield* domainCertificate(
326 "Certificate",
327 {
328 domainName: domain.name,
329 subjectAlternativeNames: [...(domain.aliases ?? []), ...(domain.redirects ?? [])],
330 hostedZoneId: domain.hostedZoneId,
331 tags: props.tags,
332 },
333 domain.dns,
334 )
335 : undefined;
336 const certificate =
337 managed?.certificate ?? (domain?.cert ? { certificateArn: domain.cert } : undefined);
338 // Resolves once the certificate is issued (see `domainCertificate`).
339 const viewerCertificateArn = managed?.certificateArn ?? domain?.cert;
340
341 const distribution = yield* Distribution("Distribution", {
342 aliases: domain ? [domain.name, ...(domain.aliases ?? [])] : undefined,
343 origins: [
344 {
345 id: "server",
346 domainName: serverOriginHost,
347 customOriginConfig: {
348 originProtocolPolicy: props.server.originProtocolPolicy ?? "https-only",
349 },
350 },
351 ...(assetBucket && assetOac
352 ? [
353 {
354 id: "assets",
355 domainName: assetBucket.bucketRegionalDomainName,
356 originPath: props.assets?.prefix,
357 s3Origin: true,
358 originAccessControlId: assetOac.originAccessControlId,
359 },
360 ]
361 : []),
362 ],
363 defaultCacheBehavior: {
364 targetOriginId: "server",
365 viewerProtocolPolicy: "redirect-to-https",
366 compress: true,
367 allowedMethods: ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"],
368 cachedMethods: ["GET", "HEAD"],
369 cachePolicyId: props.cachePolicyId ?? MANAGED_CACHING_DISABLED_POLICY_ID,
370 originRequestPolicyId: MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID,
371 },
372 orderedCacheBehaviors:
373 assetBucket && assetOac
374 ? [
375 {
376 pathPattern: assetPattern,
377 targetOriginId: "assets",
378 viewerProtocolPolicy: "redirect-to-https",
379 compress: true,
380 allowedMethods: ["GET", "HEAD", "OPTIONS"],
381 cachedMethods: ["GET", "HEAD"],
382 cachePolicyId: MANAGED_CACHING_OPTIMIZED_POLICY_ID,
383 },
384 ]
385 : undefined,
386 viewerCertificate: viewerCertificateArn
387 ? {
388 acmCertificateArn: viewerCertificateArn,
389 sslSupportMethod: "sni-only",
390 minimumProtocolVersion: "TLSv1.2_2021",
391 }
392 : undefined,
393 tags: props.tags,
394 });
395
396 if (assetBucket && assetOac) {
397 const bucketPolicy: PolicyStatement = {
398 Effect: "Allow",
399 Principal: {
400 Service: "cloudfront.amazonaws.com",
401 },
402 Action: ["s3:GetObject"],
403 Resource: [Output.interpolate`${assetBucket.bucketArn}/*` as any],
404 Condition: {
405 StringEquals: {
406 "AWS:SourceArn": distribution.distributionArn as any,
407 },
408 },
409 };
410
411 yield* assetBucket.bind`AWS.S3.Policy(${distribution}, ${assetBucket})`({
412 policyStatements: [bucketPolicy],
413 });
414 }
415
416 const dns =
417 domain && domain.dns !== false
418 ? yield* resolveDomainDns(domain.dns, domain.hostedZoneId)
419 : undefined;
420 const records =
421 domain && dns
422 ? yield* Effect.forEach(
423 [domain.name, ...(domain.aliases ?? []), ...(domain.redirects ?? [])],
424 (name, index) =>
425 // The DNS host infers the zone containing `name` unless one
426 // is pinned.
427 dns.alias(`AliasRecord${index + 1}`, {
428 name,
429 target: {
430 hostname: distribution.domainName,
431 route53Alias: { hostedZoneId: distribution.hostedZoneId },
432 },
433 }),
434 { concurrency: "unbounded" },
435 )
436 : [];
437
438 const invalidation =
439 props.invalidate === false || !assetFiles
440 ? undefined
441 : yield* Invalidation("Invalidation", {
442 distributionId: distribution.distributionId,
443 version: assetFiles.version,
444 wait: props.invalidate?.wait,
445 paths:
446 props.invalidate?.paths === "versioned"
447 ? [assetPattern]
448 : props.invalidate?.paths === "all" || !props.invalidate?.paths
449 ? ["/*"]
450 : props.invalidate.paths,
451 });
452
453 // Precedence: the canonical domain, then aliases in declaration order,
454 // then the CloudFront default domain. Redirect hostnames never appear.
455 const urls: Input<string>[] = domain
456 ? [
457 Output.interpolate`https://${domain.name}`,
458 ...(domain.aliases ?? []).map((alias) => `https://${alias}`),
459 Output.interpolate`https://${distribution.domainName}`,
460 ]
461 : [Output.interpolate`https://${distribution.domainName}`];
462
463 return {
464 assetBucket,
465 assetFiles,
466 assetOriginAccessControl: assetOac,
467 certificate,
468 distribution,
469 records,
470 invalidation,
471 routeTargets,
472 /**
473 * The most significant URL the site serves at — always `urls[0]`.
474 */
475 url: urls[0],
476 /**
477 * Every URL that serves this site, most significant first —
478 * `[https://<domain.name>?, ...aliases, <CloudFront default
479 * domain>]`. Redirect hostnames never appear — they serve no
480 * content.
481 */
482 urls,
483 };
484 }).pipe(Namespace.push(id));