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

main
ts 540 lines 19.7 KB
Raw
1 import { createHash } from "node:crypto";
2 import { toPath } from "alchemy/FQN";
3 import type { Input } from "alchemy/Input";
4 import * as Namespace from "alchemy/Namespace";
5 import * as Output from "alchemy/Output";
6 import { Stack } from "alchemy/Stack";
7 import { Stage } from "alchemy/Stage";
8 import * as Effect from "effect/Effect";
9 import { CachePolicy } from "../CloudFront/CachePolicy.ts";
10 import { Distribution, type DistributionBehavior } from "../CloudFront/Distribution.ts";
11 import { Function as CloudFrontFunction } from "../CloudFront/Function.ts";
12 import { Invalidation } from "../CloudFront/Invalidation.ts";
13 import { KeyValueStore } from "../CloudFront/KeyValueStore.ts";
14 import { KvEntries } from "../CloudFront/KvEntries.ts";
15 import { KvRoutesUpdate } from "../CloudFront/KvRoutesUpdate.ts";
16 import { MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID } from "../CloudFront/ManagedPolicies.ts";
17 import { domainCertificate, resolveDomainDns } from "../CustomDomain.ts";
18 import type { PolicyStatement } from "../IAM/Policy.ts";
19 import type { Bucket } from "../S3/Bucket.ts";
20 import { buildHostRedirectInjection, CF_ROUTER_INJECTION } from "./cfcode.ts";
21 import { normalizeWebsiteDomain, type RouterProps } from "./shared.ts";
22
23 /**
24 * Shared CloudFront front door with KV-based dynamic routing.
25 *
26 * `Router` owns a single CloudFront distribution with a placeholder origin.
27 * Routes are registered lazily via KV entries. A CloudFront Function reads the
28 * KV store at the edge and dynamically sets the origin using
29 * `cf.updateRequestOrigin()`.
30 *
31 * Sites register themselves by writing their file manifest and metadata into
32 * the Router's KV store. The Router's CF function matches incoming requests to
33 * routes by host pattern and path prefix, then delegates to `routeSite()` for
34 * static site routing or directly sets URL/S3 origins.
35 * ### Creating Routers
36 * **Example:** Basic Router
37 * ```typescript
38 * const router = yield* Router("WebsiteRouter", {
39 * domain: { name: "example.com", hostedZoneId },
40 * });
41 * ```
42 *
43 * **Example:** Router On A Cloudflare Domain
44 * ```typescript
45 * // The certificate, the Router's own CNAMEs, and hostnames bound by
46 * // attached sites all go through the Cloudflare zone. Requires
47 * // `Cloudflare.providers()` in the stack.
48 * const router = yield* Router("WebsiteRouter", {
49 * domain: { name: "example.com", dns: Cloudflare.DNS.Adapter() },
50 * });
51 * ```
52 *
53 * ### Inline Routes
54 * **Example:** URL And Bucket Routes
55 * ```typescript
56 * const router = yield* Router("WebsiteRouter", {
57 * routes: {
58 * "/api/*": { url: api.functionUrl },
59 * "/*": { bucket: assetsBucket },
60 * },
61 * });
62 * ```
63 *
64 * ### Attaching Sites
65 * **Example:** Serve A StaticSite Through The Router
66 * ```typescript
67 * const router = yield* Router("WebsiteRouter", {
68 * invalidation: { paths: "all", wait: true },
69 * });
70 *
71 * // The site registers itself in the Router's KV store; no new
72 * // distribution is created.
73 * const docs = yield* AWS.Website.StaticSite("DocsSite", {
74 * path: "./docs/dist",
75 * domain: {
76 * router,
77 * path: "/docs",
78 * },
79 * });
80 * ```
81 *
82 * @resource
83 */
84 export const Router = Effect.fn("AWS.Website.Router")(
85 function* (id: string, props: RouterProps) {
86 const domain = normalizeWebsiteDomain(props.domain);
87
88 if (domain && domain.dns === false && !domain.cert) {
89 return yield* Effect.die("Router domain configuration with `dns: false` requires `cert`.");
90 }
91 if (props.cloudfrontUrl === false && !domain) {
92 return yield* Effect.die(
93 `"cloudfrontUrl: false" requires a "domain" — without one the Router would be unreachable (the CloudFront default domain is its only URL).`,
94 );
95 }
96 if (domain?.redirects?.length && domain.name.includes("*")) {
97 return yield* Effect.die(
98 `"domain.redirects" requires a concrete (non-wildcard) "domain.name" to redirect to.`,
99 );
100 }
101
102 // The managed certificate (when the Router owns one) doubles as a bind
103 // target for attached-site hostnames — keep the resource handle distinct
104 // from the viewer-certificate value, which may be a user-provided ARN.
105 const managed =
106 domain && !domain.cert
107 ? yield* domainCertificate(
108 "Certificate",
109 {
110 domainName: domain.name,
111 subjectAlternativeNames: [...(domain.aliases ?? []), ...(domain.redirects ?? [])],
112 hostedZoneId: domain.hostedZoneId,
113 tags: props.tags,
114 },
115 domain.dns,
116 )
117 : undefined;
118 const managedCertificate = managed?.certificate;
119 const certificate =
120 managedCertificate ?? (domain?.cert ? { certificateArn: domain.cert } : undefined);
121 // Resolves once the certificate is issued (see `domainCertificate`).
122 const viewerCertificateArn = managed?.certificateArn ?? domain?.cert;
123
124 const stack = yield* Stack;
125 const stage = yield* Stage;
126 const ns = yield* Namespace.CurrentNamespace;
127 const fqn = ns ? toPath(ns).join("/") : id;
128 const kvNamespace = createHash("md5")
129 .update(`${stack.name}-${stage}-${fqn}`)
130 .digest("hex")
131 .substring(0, 4);
132
133 const kvStore = yield* KeyValueStore("KvStore", {});
134
135 const viewerRequest = yield* CloudFrontFunction("ViewerRequest", {
136 comment: `${id} viewer request`,
137 code: buildRouterRequestFunctionCode({
138 kvNamespace,
139 userInjection: props.edge?.viewerRequest?.injection,
140 hostRedirect: domain
141 ? {
142 to: domain.name,
143 hosts: domain.redirects ?? [],
144 cloudfrontDefault: props.cloudfrontUrl === false,
145 }
146 : undefined,
147 }),
148 keyValueStoreArns: [kvStore.keyValueStoreArn],
149 });
150
151 const viewerResponse = props.edge?.viewerResponse
152 ? yield* CloudFrontFunction("ViewerResponse", {
153 comment: `${id} viewer response`,
154 code: buildRouterResponseFunctionCode(props.edge.viewerResponse.injection),
155 keyValueStoreArns: props.edge.viewerResponse.keyValueStoreArn
156 ? [props.edge.viewerResponse.keyValueStoreArn as any]
157 : undefined,
158 })
159 : undefined;
160
161 const functionAssociations: DistributionBehavior["functionAssociations"] = [
162 {
163 eventType: "viewer-request" as const,
164 functionArn: viewerRequest.functionArn as any,
165 },
166 ...(viewerResponse
167 ? [
168 {
169 eventType: "viewer-response" as const,
170 functionArn: viewerResponse.functionArn as any,
171 },
172 ]
173 : []),
174 ];
175
176 const inlineRouteEntries: Record<string, Input<string>> = {};
177 const routeBuckets: Bucket[] = [];
178
179 if (props.routes) {
180 let routeIndex = 0;
181 for (const [pattern, route] of Object.entries(props.routes)) {
182 routeIndex++;
183 const routeNs = createHash("md5")
184 .update(`${stack.name}-${stage}-${fqn}:route:${routeIndex}`)
185 .digest("hex")
186 .substring(0, 4);
187
188 if (typeof route === "string" || "url" in (route as any)) {
189 const url = typeof route === "string" ? route : (route as any).url;
190 const origin = (route as any).origin;
191 inlineRouteEntries[`${routeNs}:metadata`] = stringifyResolvedString(
192 url,
193 (resolvedUrl) => {
194 const { host, protocol } = new URL(resolvedUrl);
195 return JSON.stringify({
196 host,
197 // `setUrlOrigin` defaults to https:443, so keep an `http://` url on http.
198 origin: protocol === "http:" ? { protocol: "http", ...origin } : origin,
199 rewrite: (route as any).rewrite,
200 });
201 },
202 );
203 yield* KvRoutesUpdate(`Route${routeIndex}`, {
204 store: kvStore.keyValueStoreArn as any,
205 namespace: kvNamespace,
206 key: "routes",
207 entry: `url,${kvNamespace}:${routeNs},,${normalizePattern(pattern)}`,
208 });
209 } else {
210 const bucketRoute = route as any;
211 if (typeof bucketRoute.bucket !== "string") {
212 routeBuckets.push(bucketRoute.bucket as Bucket);
213 }
214 const bucketDomain =
215 typeof bucketRoute.bucket === "string"
216 ? bucketRoute.bucket
217 : bucketRoute.bucket.bucketRegionalDomainName;
218 inlineRouteEntries[`${routeNs}:metadata`] = stringifyResolvedString(
219 bucketDomain,
220 (resolvedDomain) =>
221 JSON.stringify({
222 domain: resolvedDomain,
223 origin: bucketRoute.origin,
224 rewrite: bucketRoute.rewrite,
225 }),
226 );
227 yield* KvRoutesUpdate(`Route${routeIndex}`, {
228 store: kvStore.keyValueStoreArn as any,
229 namespace: kvNamespace,
230 key: "routes",
231 entry: `bucket,${kvNamespace}:${routeNs},,${normalizePattern(pattern)}`,
232 });
233 }
234 }
235 }
236
237 if (Object.keys(inlineRouteEntries).length > 0) {
238 yield* KvEntries("InlineRouteEntries", {
239 store: kvStore.keyValueStoreArn as any,
240 namespace: kvNamespace,
241 entries: inlineRouteEntries,
242 });
243 }
244
245 // One behavior serves every attached site — static AND server-rendered
246 // — so the cache policy must not cache responses that carry no
247 // Cache-Control (SSR pages), while still honoring the immutable
248 // Cache-Control the asset uploader sets. Managed CachingOptimized
249 // would cache header-less SSR responses for a day. The
250 // AllViewerExceptHostHeader origin-request policy forwards viewer
251 // headers/cookies/query to server origins (required for Lambda URLs,
252 // whose Host must stay the function URL's own domain).
253 const cachePolicy = yield* CachePolicy("CachePolicy", {
254 comment: `${id} router cache policy`,
255 minTTL: 0,
256 defaultTTL: 0,
257 maxTTL: "365 days",
258 parametersInCacheKeyAndForwardedToOrigin: {
259 EnableAcceptEncodingGzip: true,
260 EnableAcceptEncodingBrotli: true,
261 QueryStringsConfig: { QueryStringBehavior: "all" },
262 HeadersConfig: { HeaderBehavior: "none" },
263 CookiesConfig: { CookieBehavior: "none" },
264 },
265 });
266
267 const distribution = yield* Distribution("Distribution", {
268 aliases: domain
269 ? [domain.name, ...(domain.aliases ?? []), ...(domain.redirects ?? [])]
270 : undefined,
271 origins: [
272 {
273 id: "default",
274 domainName: "placeholder.alchemy.run",
275 customOriginConfig: {
276 httpPort: 80,
277 httpsPort: 443,
278 originProtocolPolicy: "https-only",
279 originReadTimeout: "20 seconds",
280 originSslProtocols: ["TLSv1.2"],
281 },
282 },
283 ],
284 defaultCacheBehavior: {
285 targetOriginId: "default",
286 viewerProtocolPolicy: "redirect-to-https",
287 allowedMethods: ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"],
288 cachedMethods: ["GET", "HEAD"],
289 compress: true,
290 cachePolicyId: cachePolicy.cachePolicyId,
291 originRequestPolicyId: MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID,
292 functionAssociations,
293 },
294 viewerCertificate: viewerCertificateArn
295 ? {
296 acmCertificateArn: viewerCertificateArn,
297 sslSupportMethod: "sni-only",
298 minimumProtocolVersion: "TLSv1.2_2021",
299 }
300 : undefined,
301 tags: props.tags,
302 });
303
304 // Inline bucket routes are served through the router's distribution with
305 // OAC-signed requests (see `setS3Origin` in cfcode.ts) — each bucket must
306 // allow this distribution or every request 403s.
307 yield* Effect.forEach(routeBuckets, (routeBucket) => {
308 const bucketPolicy: PolicyStatement = {
309 Effect: "Allow",
310 Principal: {
311 Service: "cloudfront.amazonaws.com",
312 },
313 Action: ["s3:GetObject"],
314 Resource: [Output.interpolate`${routeBucket.bucketArn}/*` as any],
315 Condition: {
316 StringEquals: {
317 "AWS:SourceArn": distribution.distributionArn as any,
318 },
319 },
320 };
321 return routeBucket.bind`AWS.S3.Policy(CloudFront, ${routeBucket})`({
322 policyStatements: [bucketPolicy],
323 });
324 });
325
326 const dns =
327 domain && domain.dns !== false
328 ? yield* resolveDomainDns(domain.dns, domain.hostedZoneId)
329 : undefined;
330 const aliasTarget = {
331 hostname: distribution.domainName,
332 route53Alias: { hostedZoneId: distribution.hostedZoneId },
333 };
334 const records =
335 domain && dns
336 ? yield* Effect.forEach(
337 [domain.name, ...(domain.aliases ?? []), ...(domain.redirects ?? [])],
338 (name, index) =>
339 // The DNS host infers the zone containing `name` unless one
340 // is pinned.
341 dns.alias(`AliasRecord${index + 1}`, {
342 name,
343 target: aliasTarget,
344 }),
345 { concurrency: "unbounded" },
346 )
347 : [];
348
349 // Bind target for attached-site hostnames: a record set (initially
350 // empty) that same-stack sites bind their concrete hostnames onto, each
351 // becoming a record pointing at this distribution (see
352 // `WebsiteRouterBindTargets`). The set infers its zone from the first
353 // bound hostname when none is pinned.
354 const siteRecords =
355 domain && dns ? yield* dns.aliasSet("SiteAliasRecords", { target: aliasTarget }) : undefined;
356
357 const invalidation =
358 props.invalidation === false || !props.invalidation
359 ? undefined
360 : yield* Invalidation("Invalidation", {
361 distributionId: distribution.distributionId,
362 version: createHash("sha256").update(JSON.stringify(inlineRouteEntries)).digest("hex"),
363 wait: props.invalidation.wait,
364 paths:
365 props.invalidation.paths === "all" || !props.invalidation.paths
366 ? ["/*"]
367 : Array.isArray(props.invalidation.paths)
368 ? props.invalidation.paths
369 : ["/*"],
370 });
371
372 // Precedence: the canonical domain, then aliases in declaration order,
373 // then the distribution's own URL (only while `cloudfrontUrl` is
374 // enabled). Redirect hostnames never appear.
375 //
376 // `distribution.url` rather than an interpolated
377 // `https://${distribution.domainName}`: the distribution knows its own
378 // address, which is `https://{id}.cloudfront.net` on AWS and
379 // `http://localhost:{port}` under `alchemy dev`, where that AWS hostname
380 // resolves to nothing.
381 const urls: Input<string>[] = domain
382 ? [
383 Output.interpolate`https://${domain.name}`,
384 ...(domain.aliases ?? []).map((alias) => `https://${alias}`),
385 ...(props.cloudfrontUrl !== false ? [distribution.url] : []),
386 ]
387 : [distribution.url];
388
389 return {
390 certificate,
391 distribution,
392 records,
393 invalidation,
394 kvStoreArn: kvStore.keyValueStoreArn as Input<string>,
395 kvNamespace,
396 distributionId: distribution.distributionId as Input<string>,
397 distributionArn: distribution.distributionArn as Input<string>,
398 /**
399 * Same-stack bind targets for attached-site hostnames (see
400 * `WebsiteRouterBindTargets` in shared.ts): a site declaring
401 * `domain: { name, router }` binds its concrete hostnames onto the
402 * distribution (alias), the managed certificate (SAN), and the
403 * Route 53 record set. Only populated when the Router owns a
404 * `domain` — without one there is no viewer certificate to cover
405 * bound aliases.
406 */
407 bindTargets: domain
408 ? {
409 distribution,
410 certificate: managedCertificate,
411 records: siteRecords,
412 }
413 : undefined,
414 /**
415 * The most significant URL the Router serves at — always `urls[0]`.
416 */
417 url: urls[0],
418 /**
419 * Every URL the Router serves at, most significant first —
420 * `[https://<domain.name>?, ...aliases, <CloudFront default
421 * domain>?]` (the default domain only while `cloudfrontUrl` is
422 * enabled). Redirect hostnames never appear — they serve no content.
423 */
424 urls,
425 };
426 },
427 (effect, id: string, _props: RouterProps) => effect.pipe(Namespace.push(id)),
428 );
429
430 const buildRouterRequestFunctionCode = ({
431 kvNamespace,
432 userInjection,
433 hostRedirect,
434 }: {
435 kvNamespace: string;
436 userInjection?: string;
437 hostRedirect?: {
438 to: string;
439 hosts: string[];
440 cloudfrontDefault: boolean;
441 };
442 }) => `import cf from "cloudfront";
443 async function handler(event) {
444 ${userInjection ?? ""}
445 ${
446 hostRedirect
447 ? buildHostRedirectInjection({
448 to: hostRedirect.to,
449 hosts: hostRedirect.hosts,
450 cloudfrontDefault: hostRedirect.cloudfrontDefault,
451 })
452 : ""
453 }
454 ${CF_ROUTER_INJECTION}
455
456 async function getRoutes() {
457 var routerNS = "${kvNamespace}";
458 var routes = [];
459 try {
460 var v = await cf.kvs().get(routerNS + ":routes");
461 routes = JSON.parse(v);
462 if (routes.parts) {
463 var chunkPromises = [];
464 for (var i = 0; i < routes.parts; i++) {
465 chunkPromises.push(cf.kvs().get(routerNS + ":routes:" + i));
466 }
467 var chunks = await Promise.all(chunkPromises);
468 routes = JSON.parse(chunks.join(""));
469 }
470 } catch (e) {}
471 return routes;
472 }
473
474 async function matchRoute(routes) {
475 var requestHost = event.request.headers.host.value;
476 var requestHostWithEscapedDots = requestHost.replace(/\\./g, "\\\\.");
477 var requestHostRegexPattern = "^" + requestHost + "$";
478 var match;
479 routes.forEach(function(r) {
480 var parts = r.split(",");
481 var type = parts[0];
482 var routeNs = parts[1];
483 var host = parts[2];
484 var hostLength = host.length;
485 var path = parts[3];
486 var pathLength = path.length;
487 if (match && (hostLength < match.hostLength || (hostLength === match.hostLength && pathLength < match.pathLength))) return;
488 var hostMatches = host === "" || host === requestHostWithEscapedDots || (host.includes("*") && new RegExp(host).test(requestHostRegexPattern));
489 if (!hostMatches) return;
490 var pathMatches = event.request.uri.startsWith(path) && (event.request.uri === path || path.endsWith('/') || event.request.uri[path.length] === '/' || path === '/');
491 if (!pathMatches) return;
492 match = { type: type, routeNs: routeNs, host: host, hostLength: hostLength, path: path, pathLength: pathLength };
493 });
494 if (match) {
495 try {
496 var type = match.type;
497 var routeNs = match.routeNs;
498 var v = await cf.kvs().get(routeNs + ":metadata");
499 return { type: type, routeNs: routeNs, metadata: JSON.parse(v) };
500 } catch (e) {}
501 }
502 }
503
504 var routes = await getRoutes();
505 var route = await matchRoute(routes);
506 if (!route) return event.request;
507 if (route.metadata.rewrite) {
508 var rw = route.metadata.rewrite;
509 event.request.uri = event.request.uri.replace(new RegExp(rw.regex), rw.to);
510 }
511 if (route.type === "url") setUrlOrigin(route.metadata.host, route.metadata.origin);
512 if (route.type === "bucket") setS3Origin(route.metadata.domain, route.metadata.origin);
513 if (route.type === "site") {
514 var response = await routeSite(route.routeNs, route.metadata);
515 return response || event.request;
516 }
517 return event.request;
518 }`;
519
520 const buildRouterResponseFunctionCode = (userInjection?: string) =>
521 `import cf from "cloudfront";
522 async function handler(event) {
523 ${userInjection ?? ""}
524 return event.response;
525 }`;
526
527 const normalizePattern = (pattern: string) => {
528 if (pattern === "/" || pattern === "/*") return "/";
529 return pattern.replace(/\/?\*$/, "");
530 };
531
532 const stringifyResolvedString = (
533 value: Input<string>,
534 build: (resolved: string) => string,
535 ): Input<string> =>
536 typeof value === "string"
537 ? build(value)
538 : Effect.isEffect(value)
539 ? value.pipe(Effect.map((resolved) => build(resolved)))
540 : value.pipe(Output.map((resolved) => build(resolved)));