@elumixor/devkit 0.12.3 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +87 -0
  2. package/package.json +26 -2
  3. package/src/bin/devkit.ts +32 -1
  4. package/src/blob/index.ts +169 -0
  5. package/src/build-targets/web.ts +66 -20
  6. package/src/cloud/aws.ts +108 -0
  7. package/src/cloud/bootstrap.ts +114 -0
  8. package/src/cloud/cli.ts +56 -0
  9. package/src/cloud/commands/context.ts +42 -0
  10. package/src/cloud/commands/destroy.ts +43 -0
  11. package/src/cloud/commands/domains.ts +68 -0
  12. package/src/cloud/commands/env.ts +59 -0
  13. package/src/cloud/commands/init.ts +74 -0
  14. package/src/cloud/commands/logs.ts +35 -0
  15. package/src/cloud/commands/rollback.ts +54 -0
  16. package/src/cloud/commands/status.ts +50 -0
  17. package/src/cloud/edge/router.js +86 -0
  18. package/src/cloud/env.ts +93 -0
  19. package/src/cloud/github.ts +92 -0
  20. package/src/cloud/index.ts +9 -0
  21. package/src/cloud/log-events.ts +56 -0
  22. package/src/cloud/mcp.ts +150 -0
  23. package/src/cloud/names.ts +98 -0
  24. package/src/cloud/nitro-build.ts +42 -0
  25. package/src/cloud/overview.ts +105 -0
  26. package/src/cloud/project.ts +146 -0
  27. package/src/cloud/reconcile/acm.ts +97 -0
  28. package/src/cloud/reconcile/cloudflare.ts +103 -0
  29. package/src/cloud/reconcile/edge.ts +108 -0
  30. package/src/cloud/reconcile/guardrails.ts +112 -0
  31. package/src/cloud/reconcile/iam.ts +328 -0
  32. package/src/cloud/reconcile/kvs.ts +98 -0
  33. package/src/cloud/reconcile/lambda.ts +305 -0
  34. package/src/cloud/reconcile/logs.ts +24 -0
  35. package/src/cloud/reconcile/platform.ts +281 -0
  36. package/src/cloud/reconcile/s3.ts +155 -0
  37. package/src/cloud/reconcile/scheduler.ts +100 -0
  38. package/src/cloud/records.ts +129 -0
  39. package/src/cloud/release.ts +268 -0
  40. package/src/cloud/runtime-wrapper.ts +84 -0
  41. package/src/deploy-targets/aws.ts +26 -0
  42. package/src/run-target.ts +2 -0
  43. package/src/runtime/index.ts +50 -0
@@ -0,0 +1,105 @@
1
+ import { GetMetricDataCommand } from "@aws-sdk/client-cloudwatch";
2
+ import { cloudwatch } from "./aws.ts";
3
+ import { Target } from "./project.ts";
4
+ import {
5
+ type CurrentPointer,
6
+ type DeployRecord,
7
+ listDeploys,
8
+ listProjects,
9
+ readCurrent,
10
+ readRegistry,
11
+ } from "./records.ts";
12
+
13
+ const DAY_SECONDS = 24 * 60 * 60;
14
+
15
+ /** Last day's traffic for one function, from CloudWatch. */
16
+ export interface Metrics {
17
+ calls: number;
18
+ errors: number;
19
+ p95ms: number;
20
+ }
21
+
22
+ export interface StageOverview {
23
+ project: string;
24
+ stage: string;
25
+ functionName: string;
26
+ hostnames: readonly string[];
27
+ current?: CurrentPointer;
28
+ live?: DeployRecord;
29
+ metrics: Metrics;
30
+ }
31
+
32
+ export interface ProjectOverview {
33
+ project: string;
34
+ stages: StageOverview[];
35
+ }
36
+
37
+ /** What `status`, the MCP server and the dashboard all show: every stage, what is live on it, how it did today. */
38
+ export async function overview(project?: string): Promise<ProjectOverview[]> {
39
+ const registries = project
40
+ ? [await readRegistry(project)].filter((registry) => registry !== undefined)
41
+ : await listProjects();
42
+ return Promise.all(
43
+ registries.map(async (registry) => ({
44
+ project: registry.project,
45
+ stages: await Promise.all(
46
+ Object.entries(registry.stages).map(async ([stage, recorded]) => {
47
+ const target = new Target(registry.project, stage);
48
+ const [current, metrics, deploys] = await Promise.all([
49
+ readCurrent(target),
50
+ metricsFor(target.functionName),
51
+ listDeploys(target, 3),
52
+ ]);
53
+ return {
54
+ project: registry.project,
55
+ stage,
56
+ functionName: target.functionName,
57
+ hostnames: recorded.hostnames,
58
+ current,
59
+ live: deploys.find((deploy) => deploy.id === current?.deployId),
60
+ metrics,
61
+ };
62
+ }),
63
+ ),
64
+ })),
65
+ );
66
+ }
67
+
68
+ async function metricsFor(functionName: string): Promise<Metrics> {
69
+ const end = new Date();
70
+ const start = new Date(end.getTime() - DAY_SECONDS * 1000);
71
+ const query = (id: string, metric: string, stat: string) => ({
72
+ Id: id,
73
+ MetricStat: {
74
+ Metric: {
75
+ Namespace: "AWS/Lambda",
76
+ MetricName: metric,
77
+ Dimensions: [{ Name: "FunctionName", Value: functionName }],
78
+ },
79
+ Period: DAY_SECONDS,
80
+ Stat: stat,
81
+ },
82
+ });
83
+ const result = await cloudwatch().send(
84
+ new GetMetricDataCommand({
85
+ StartTime: start,
86
+ EndTime: end,
87
+ MetricDataQueries: [
88
+ query("calls", "Invocations", "Sum"),
89
+ query("errors", "Errors", "Sum"),
90
+ query("p95", "Duration", "p95"),
91
+ ],
92
+ }),
93
+ );
94
+ const value = (id: string) => result.MetricDataResults?.find((item) => item.Id === id)?.Values?.[0] ?? 0;
95
+ return { calls: value("calls"), errors: value("errors"), p95ms: Math.round(value("p95")) };
96
+ }
97
+
98
+ /** `3m ago`, `2h ago` — for terminals and the dashboard alike. */
99
+ export function age(iso: string) {
100
+ const seconds = Math.round((Date.now() - new Date(iso).getTime()) / 1000);
101
+ if (seconds < 90) return `${seconds}s ago`;
102
+ if (seconds < 90 * 60) return `${Math.round(seconds / 60)}m ago`;
103
+ if (seconds < 36 * 3600) return `${Math.round(seconds / 3600)}h ago`;
104
+ return `${Math.round(seconds / 86400)}d ago`;
105
+ }
@@ -0,0 +1,146 @@
1
+ import { $ } from "bun";
2
+ import type { WebBuildOptions } from "../build-targets/web.ts";
3
+ import { CloudError } from "./aws.ts";
4
+ import { stage as names, PRODUCTION, STAGE_BRANCHES } from "./names.ts";
5
+
6
+ /** One scheduled call into the API, in the shape Vercel's `vercel.json` used. */
7
+ export interface CronConfig {
8
+ /** Path the function is called on, e.g. `/api/cron/sync`. */
9
+ path: string;
10
+ /** Cron expression in UTC, five fields. */
11
+ schedule: string;
12
+ }
13
+
14
+ export type Routing = "spa" | "pages" | "ssr";
15
+
16
+ /** One IAM `Allow` statement the function's role gets besides its own logs and blob prefix. */
17
+ export interface Permission {
18
+ Action: string | string[];
19
+ Resource: string | string[];
20
+ Condition?: Record<string, Record<string, string | string[]>>;
21
+ }
22
+
23
+ /** The `aws` deploy target's options, in the `devkit.deploy.<name>.options` block. */
24
+ export interface AwsTargetOptions extends Omit<WebBuildOptions, "host"> {
25
+ /** Project name: resource names, bucket prefixes and the default hostname (default: repo name). */
26
+ project?: string;
27
+ /** How the edge serves paths that aren't the API (default `spa`). */
28
+ routing?: Routing;
29
+ /** Function memory in MB (default 512 — the account caps functions at 512 until AWS raises it). */
30
+ memory?: number;
31
+ /** Function timeout in seconds (default 120; CloudFront waits 60 s for a first byte, a stream may go on longer). */
32
+ timeout?: number;
33
+ /** Scheduled calls into the API. */
34
+ crons?: CronConfig[];
35
+ /**
36
+ * Custom hostnames per stage, besides the default `<project>.devkit.atmagaming.com`. A `*.` entry is a
37
+ * wildcard alias only (no route or DNS): hostnames under it then share one certificate name.
38
+ */
39
+ domains?: Record<string, string[]>;
40
+ /** Shell command run with the stage's env after the code is published and before it goes live — migrations. */
41
+ predeploy?: string;
42
+ /** Path the health check hits on the new version before it goes live (default `/api/health`). */
43
+ healthPath?: string;
44
+ /** Stage name to git branch (default production=main, development=develop). */
45
+ stages?: Record<string, string>;
46
+ /** Extra IAM statements for the function — an app that reads other AWS resources, like the dashboard. */
47
+ permissions?: Permission[];
48
+ }
49
+
50
+ export const DEFAULTS = { memory: 512, timeout: 120, routing: "spa" as Routing, healthPath: "/api/health" };
51
+
52
+ /** A project and stage with every default filled in — what the reconciler and the commands work from. */
53
+ export class Target {
54
+ readonly project: string;
55
+ readonly stage: string;
56
+ readonly options: Readonly<AwsTargetOptions>;
57
+
58
+ constructor(project: string, stage: string, options: Readonly<AwsTargetOptions> = { apiPrefixes: ["api"] }) {
59
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(project))
60
+ throw new CloudError(`Project name "${project}" must be lowercase letters, digits and dashes`);
61
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(stage))
62
+ throw new CloudError(`Stage name "${stage}" must be lowercase letters, digits and dashes`);
63
+ this.project = project;
64
+ this.stage = stage;
65
+ this.options = options;
66
+ }
67
+
68
+ get functionName() {
69
+ return names.fn(this.project, this.stage);
70
+ }
71
+ get roleName() {
72
+ return names.role(this.project, this.stage);
73
+ }
74
+ get logGroup() {
75
+ return names.logGroup(this.project, this.stage);
76
+ }
77
+ get ssmPrefix() {
78
+ return names.ssmPrefix(this.project, this.stage);
79
+ }
80
+ get defaultHost() {
81
+ return names.defaultHost(this.project, this.stage);
82
+ }
83
+ get domains(): readonly string[] {
84
+ return this.options.domains?.[this.stage] ?? [];
85
+ }
86
+ /** Every hostname that routes to this stage; the first custom domain is the one the app calls its own. */
87
+ get hostnames(): readonly string[] {
88
+ return [...this.domains.filter((host) => !host.startsWith("*.")), this.defaultHost];
89
+ }
90
+ get primaryHost() {
91
+ return this.hostnames[0] as string;
92
+ }
93
+ get apiPrefixes(): readonly string[] {
94
+ return (this.options.apiPrefixes ?? ["api"]).map((prefix) => prefix.replace(/^\/+|\/+$/g, ""));
95
+ }
96
+ get routing() {
97
+ return this.options.routing ?? DEFAULTS.routing;
98
+ }
99
+ get memory() {
100
+ return this.options.memory ?? DEFAULTS.memory;
101
+ }
102
+ get timeout() {
103
+ return this.options.timeout ?? DEFAULTS.timeout;
104
+ }
105
+ get crons(): readonly CronConfig[] {
106
+ return this.options.crons ?? [];
107
+ }
108
+ get healthPath() {
109
+ return this.options.healthPath ?? DEFAULTS.healthPath;
110
+ }
111
+ get permissions(): readonly Permission[] {
112
+ return this.options.permissions ?? [];
113
+ }
114
+ get isProduction() {
115
+ return this.stage === PRODUCTION;
116
+ }
117
+ }
118
+
119
+ /** The project name: configured, or the repo's name, or the package name. */
120
+ export async function projectName(options: Pick<AwsTargetOptions, "project">, root = process.cwd()) {
121
+ if (options.project) return options.project;
122
+ const remote = await $`git -C ${root} remote get-url origin`.quiet().nothrow().text();
123
+ const fromRemote = remote
124
+ .trim()
125
+ .replace(/\.git$/, "")
126
+ .split("/")
127
+ .pop();
128
+ if (fromRemote) return fromRemote.toLowerCase();
129
+ const pkg = (await Bun.file(`${root}/package.json`).json()) as { name?: string };
130
+ if (!pkg.name) throw new CloudError("Cannot name the project: no git remote and no package name");
131
+ return pkg.name.replace(/^@.*\//, "").toLowerCase();
132
+ }
133
+
134
+ /** The stage a deploy targets: `--stage`, else the one the current branch deploys. */
135
+ export async function resolveStage(flag: string | undefined, stages = STAGE_BRANCHES, root = process.cwd()) {
136
+ if (flag) return flag;
137
+ const branch = (await $`git -C ${root} rev-parse --abbrev-ref HEAD`.quiet().nothrow().text()).trim();
138
+ const stage = Object.entries(stages).find(([, b]) => b === branch)?.[0];
139
+ if (!stage) {
140
+ const known = Object.entries(stages)
141
+ .map(([s, b]) => `${b} → ${s}`)
142
+ .join(", ");
143
+ throw new CloudError(`Branch "${branch}" deploys no stage (${known}) — pass --stage <name>`);
144
+ }
145
+ return stage;
146
+ }
@@ -0,0 +1,97 @@
1
+ import {
2
+ type CertificateSummary,
3
+ DeleteCertificateCommand,
4
+ DescribeCertificateCommand,
5
+ ListCertificatesCommand,
6
+ ListTagsForCertificateCommand,
7
+ RequestCertificateCommand,
8
+ } from "@aws-sdk/client-acm";
9
+ import { acm, CloudError, log, platformTags, waitFor } from "../aws.ts";
10
+ import { ensureRecord } from "./cloudflare.ts";
11
+
12
+ /**
13
+ * One certificate carries every hostname the distribution answers for (Plan A). A certificate
14
+ * can't gain a name, so adding one means requesting a new certificate and swapping it in.
15
+ */
16
+ export async function ensureCertificate(names: readonly string[]): Promise<string> {
17
+ const wanted = [...new Set(names)].sort();
18
+ const issued = await listIssued();
19
+ const covering = issued.find((cert) => wanted.every((name) => cert.names.includes(name)));
20
+ if (covering) return covering.arn;
21
+
22
+ log(` requesting certificate for ${wanted.join(", ")}`);
23
+ const requested = await acm().send(
24
+ new RequestCertificateCommand({
25
+ DomainName: wanted[0],
26
+ SubjectAlternativeNames: wanted.length > 1 ? wanted.slice(1) : undefined,
27
+ ValidationMethod: "DNS",
28
+ KeyAlgorithm: "EC_prime256v1",
29
+ Tags: platformTags(),
30
+ }),
31
+ );
32
+ const arn = requested.CertificateArn;
33
+ if (!arn) throw new CloudError("ACM returned no certificate ARN");
34
+
35
+ // Validation records appear a few seconds after the request; each one goes into Cloudflare once.
36
+ const written = new Set<string>();
37
+ await waitFor(
38
+ "certificate validation",
39
+ async () => {
40
+ const described = await acm().send(new DescribeCertificateCommand({ CertificateArn: arn }));
41
+ const cert = described.Certificate;
42
+ if (cert?.Status === "ISSUED") return true;
43
+ if (cert?.Status === "FAILED" || cert?.Status === "VALIDATION_TIMED_OUT")
44
+ throw new CloudError(`Certificate ${arn} ${cert.Status}: ${cert.FailureReason ?? ""}`);
45
+ for (const option of cert?.DomainValidationOptions ?? []) {
46
+ const record = option.ResourceRecord;
47
+ if (!record?.Name || !record.Value || written.has(record.Name)) continue;
48
+ written.add(record.Name);
49
+ const outcome = await ensureRecord(record.Name.replace(/\.$/, ""), "CNAME", record.Value.replace(/\.$/, ""));
50
+ log(` validation record ${record.Name} ${outcome}`);
51
+ }
52
+ return undefined;
53
+ },
54
+ { everyMs: 10_000, timeoutMs: 15 * 60 * 1000 },
55
+ );
56
+ log(" certificate issued");
57
+ return arn;
58
+ }
59
+
60
+ /** Issued certificates the platform made, with every name they cover. */
61
+ export async function listIssued() {
62
+ const summaries: CertificateSummary[] = [];
63
+ let NextToken: string | undefined;
64
+ do {
65
+ // Without the filter ACM lists only RSA certificates, and ours are EC.
66
+ const page = await acm().send(
67
+ new ListCertificatesCommand({
68
+ CertificateStatuses: ["ISSUED"],
69
+ Includes: { keyTypes: ["RSA_2048", "EC_prime256v1", "EC_secp384r1"] },
70
+ NextToken,
71
+ }),
72
+ );
73
+ summaries.push(...(page.CertificateSummaryList ?? []));
74
+ NextToken = page.NextToken;
75
+ } while (NextToken);
76
+ return summaries
77
+ .filter((summary) => summary.CertificateArn)
78
+ .map((summary) => ({
79
+ arn: summary.CertificateArn as string,
80
+ names: [...new Set([summary.DomainName ?? "", ...(summary.SubjectAlternativeNameSummaries ?? [])])].filter(
81
+ Boolean,
82
+ ),
83
+ }));
84
+ }
85
+
86
+ /** Drops certificates no distribution uses — the old one after a swap. ACM refuses while one is in use. */
87
+ export async function deleteUnusedCertificates(keepArn: string) {
88
+ for (const cert of await listIssued()) {
89
+ if (cert.arn === keepArn) continue;
90
+ const described = await acm().send(new DescribeCertificateCommand({ CertificateArn: cert.arn }));
91
+ if (described.Certificate?.InUseBy?.length) continue;
92
+ const tags = await acm().send(new ListTagsForCertificateCommand({ CertificateArn: cert.arn }));
93
+ if (!tags.Tags?.some((tag) => tag.Key === "dk")) continue;
94
+ await acm().send(new DeleteCertificateCommand({ CertificateArn: cert.arn }));
95
+ log(` deleted unused certificate ${cert.names.join(", ")}`);
96
+ }
97
+ }
@@ -0,0 +1,103 @@
1
+ import { CloudError } from "../aws.ts";
2
+ import { readParameter } from "../env.ts";
3
+ import { platform } from "../names.ts";
4
+
5
+ /**
6
+ * The few Cloudflare DNS calls the platform needs, over plain `fetch`. The token lives in SSM and
7
+ * must have DNS edit on every zone a project's domain belongs to.
8
+ */
9
+ const API = "https://api.cloudflare.com/client/v4";
10
+
11
+ interface CloudflareRecord {
12
+ id: string;
13
+ type: string;
14
+ name: string;
15
+ content: string;
16
+ proxied: boolean;
17
+ }
18
+
19
+ interface Envelope<T> {
20
+ success: boolean;
21
+ result: T;
22
+ errors: { code: number; message: string }[];
23
+ }
24
+
25
+ let tokenPromise: Promise<string> | undefined;
26
+
27
+ function token() {
28
+ tokenPromise ??= (async () => {
29
+ const fromEnv = process.env.CLOUDFLARE_API_TOKEN;
30
+ if (fromEnv) return fromEnv;
31
+ const stored = await readParameter(platform.cloudflareTokenParameter);
32
+ if (!stored)
33
+ throw new CloudError(
34
+ `No Cloudflare token: set CLOUDFLARE_API_TOKEN or store it at ${platform.cloudflareTokenParameter}`,
35
+ );
36
+ return stored;
37
+ })();
38
+ return tokenPromise;
39
+ }
40
+
41
+ async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
42
+ const response = await fetch(`${API}${path}`, {
43
+ method,
44
+ headers: { authorization: `Bearer ${await token()}`, "content-type": "application/json" },
45
+ body: body === undefined ? undefined : JSON.stringify(body),
46
+ });
47
+ const envelope = (await response.json()) as Envelope<T>;
48
+ if (!envelope.success) {
49
+ const reasons = envelope.errors.map((error) => `${error.code} ${error.message}`).join("; ");
50
+ throw new CloudError(`Cloudflare ${method} ${path} failed: ${reasons}`);
51
+ }
52
+ return envelope.result;
53
+ }
54
+
55
+ const zones = new Map<string, Promise<string>>();
56
+
57
+ /** The zone a hostname belongs to: the longest zone name the token can see that ends the hostname. */
58
+ function zoneFor(hostname: string) {
59
+ const apex = hostname.replace(/^\*\./, "");
60
+ const cached = zones.get(apex);
61
+ if (cached) return cached;
62
+ const lookup = (async () => {
63
+ const all = await call<{ id: string; name: string }[]>("GET", "/zones?per_page=200");
64
+ const zone = all
65
+ .filter((candidate) => apex === candidate.name || apex.endsWith(`.${candidate.name}`))
66
+ .sort((a, b) => b.name.length - a.name.length)[0];
67
+ if (!zone) throw new CloudError(`No Cloudflare zone covers ${hostname} — add the zone or widen the token`);
68
+ return zone.id;
69
+ })();
70
+ zones.set(apex, lookup);
71
+ return lookup;
72
+ }
73
+
74
+ /**
75
+ * Makes one DNS record exist with this content. Never proxied: CloudFront terminates TLS with its
76
+ * own certificate, and Cloudflare in front of it would hide the viewer from the router.
77
+ */
78
+ export async function ensureRecord(name: string, type: "CNAME" | "TXT", content: string) {
79
+ const zone = await zoneFor(name);
80
+ const found = await call<CloudflareRecord[]>(
81
+ "GET",
82
+ `/zones/${zone}/dns_records?type=${type}&name=${encodeURIComponent(name)}`,
83
+ );
84
+ const existing = found[0];
85
+ const body = { type, name, content, proxied: false, ttl: 300, comment: "devkit cloud" };
86
+ if (!existing) {
87
+ await call("POST", `/zones/${zone}/dns_records`, body);
88
+ return "created";
89
+ }
90
+ if (existing.content.replace(/\.$/, "") === content.replace(/\.$/, "") && !existing.proxied) return "unchanged";
91
+ await call("PUT", `/zones/${zone}/dns_records/${existing.id}`, body);
92
+ return "updated";
93
+ }
94
+
95
+ export async function deleteRecord(name: string, type: "CNAME" | "TXT") {
96
+ const zone = await zoneFor(name);
97
+ const found = await call<CloudflareRecord[]>(
98
+ "GET",
99
+ `/zones/${zone}/dns_records?type=${type}&name=${encodeURIComponent(name)}`,
100
+ );
101
+ for (const record of found) await call("DELETE", `/zones/${zone}/dns_records/${record.id}`);
102
+ return found.length;
103
+ }
@@ -0,0 +1,108 @@
1
+ import {
2
+ type DistributionConfig,
3
+ GetDistributionCommand,
4
+ GetDistributionConfigCommand,
5
+ ListDistributionsCommand,
6
+ UpdateDistributionCommand,
7
+ } from "@aws-sdk/client-cloudfront";
8
+ import { CloudError, cloudfront, log, waitFor } from "../aws.ts";
9
+ import { PLATFORM_ALIASES, WILDCARD_DOMAIN } from "../names.ts";
10
+ import { deleteUnusedCertificates, ensureCertificate } from "./acm.ts";
11
+ import { ensureRecord } from "./cloudflare.ts";
12
+
13
+ /** How the one distribution is recognised among any others in the account. */
14
+ export const DISTRIBUTION_COMMENT = "dk-edge";
15
+
16
+ export interface Distribution {
17
+ id: string;
18
+ arn: string;
19
+ domainName: string;
20
+ aliases: readonly string[];
21
+ }
22
+
23
+ export async function findDistribution(): Promise<Distribution | undefined> {
24
+ let Marker: string | undefined;
25
+ do {
26
+ const page = await cloudfront().send(new ListDistributionsCommand({ Marker }));
27
+ const found = page.DistributionList?.Items?.find((item) => item.Comment === DISTRIBUTION_COMMENT);
28
+ if (found?.Id && found.ARN && found.DomainName)
29
+ return { id: found.Id, arn: found.ARN, domainName: found.DomainName, aliases: found.Aliases?.Items ?? [] };
30
+ Marker = page.DistributionList?.NextMarker;
31
+ } while (Marker);
32
+ return undefined;
33
+ }
34
+
35
+ export async function requireDistribution() {
36
+ const distribution = await findDistribution();
37
+ if (!distribution) throw new CloudError("No Devkit Cloud distribution — run `devkit cloud bootstrap` first");
38
+ return distribution;
39
+ }
40
+
41
+ export const isWildcard = (hostname: string) => hostname.startsWith("*.");
42
+
43
+ /** A wildcard alias covers exactly one label under it: `*.desk.example.com` covers `keep.desk.example.com`. */
44
+ const covers = (alias: string, hostname: string) =>
45
+ isWildcard(alias) &&
46
+ !isWildcard(hostname) &&
47
+ hostname.endsWith(alias.slice(1)) &&
48
+ hostname.split(".").length === alias.split(".").length;
49
+
50
+ /** Default hostnames ride the platform's wildcard alias and DNS record; any other hostname needs a DNS record. */
51
+ export const needsDns = (hostname: string) => !isWildcard(hostname) && !covers(WILDCARD_DOMAIN, hostname);
52
+
53
+ /**
54
+ * Adds hostnames as aliases, swapping in a certificate that covers them all when the current one
55
+ * doesn't, and points each at the distribution in DNS. A hostname a wildcard alias already covers
56
+ * (`*.desk.example.com`, listed in a config's `domains` like any host) takes no alias or certificate
57
+ * name of its own, which keeps the certificate under ACM's name quota. Removing works in reverse.
58
+ */
59
+ export async function reconcileAliases(add: readonly string[], remove: readonly string[] = []) {
60
+ const distribution = await requireDistribution();
61
+ const { DistributionConfig: config, ETag } = await cloudfront().send(
62
+ new GetDistributionConfigCommand({ Id: distribution.id }),
63
+ );
64
+ if (!config || !ETag) throw new CloudError("CloudFront returned no distribution config");
65
+
66
+ const current = config.Aliases?.Items ?? [];
67
+ const kept = [...PLATFORM_ALIASES, ...current.filter((alias) => !remove.includes(alias)), ...add.filter(isWildcard)];
68
+ const wanted = [
69
+ ...new Set([...kept, ...add.filter((host) => !kept.includes(host) && !kept.some((alias) => covers(alias, host)))]),
70
+ ].sort();
71
+ const unchanged = wanted.length === current.length && wanted.every((alias) => current.includes(alias));
72
+
73
+ for (const hostname of add.filter(needsDns)) {
74
+ const outcome = await ensureRecord(hostname, "CNAME", distribution.domainName);
75
+ if (outcome !== "unchanged") log(` DNS ${hostname} → ${distribution.domainName} ${outcome}`);
76
+ }
77
+ if (unchanged) return distribution;
78
+
79
+ const certificateArn = await ensureCertificate(wanted);
80
+ const next: DistributionConfig = {
81
+ ...config,
82
+ Aliases: { Quantity: wanted.length, Items: wanted },
83
+ ViewerCertificate: {
84
+ ACMCertificateArn: certificateArn,
85
+ SSLSupportMethod: "sni-only",
86
+ MinimumProtocolVersion: "TLSv1.2_2021",
87
+ CloudFrontDefaultCertificate: false,
88
+ },
89
+ };
90
+ await cloudfront().send(
91
+ new UpdateDistributionCommand({ Id: distribution.id, IfMatch: ETag, DistributionConfig: next }),
92
+ );
93
+ log(` distribution aliases → ${wanted.join(", ")}`);
94
+ await deleteUnusedCertificates(certificateArn);
95
+ return { ...distribution, aliases: wanted };
96
+ }
97
+
98
+ /** A distribution change takes minutes to reach every edge; most callers don't wait, bootstrap does. */
99
+ export async function waitDeployed(id: string) {
100
+ await waitFor(
101
+ "distribution to deploy",
102
+ async () => {
103
+ const result = await cloudfront().send(new GetDistributionCommand({ Id: id }));
104
+ return result.Distribution?.Status === "Deployed" ? true : undefined;
105
+ },
106
+ { everyMs: 15_000, timeoutMs: 20 * 60 * 1000 },
107
+ );
108
+ }
@@ -0,0 +1,112 @@
1
+ import { CreateBudgetCommand, DescribeBudgetCommand } from "@aws-sdk/client-budgets";
2
+ import {
3
+ CreateAnomalyMonitorCommand,
4
+ CreateAnomalySubscriptionCommand,
5
+ GetAnomalyMonitorsCommand,
6
+ GetAnomalySubscriptionsCommand,
7
+ } from "@aws-sdk/client-cost-explorer";
8
+ import { accountId, budgets, costExplorer, log, orUndefined } from "../aws.ts";
9
+ import { platform } from "../names.ts";
10
+
11
+ /** Two monthly budgets are free; the first says "something is running", the second "stop it". */
12
+ export const BUDGETS: readonly { name: string; dollars: number }[] = [
13
+ { name: platform.budgetSmall, dollars: 5 },
14
+ { name: platform.budgetLarge, dollars: 20 },
15
+ ];
16
+
17
+ /** Anomaly alerts fire for an unexpected jump of at least this many dollars. */
18
+ const ANOMALY_DOLLARS = "5";
19
+
20
+ export async function ensureBudgets(email: string) {
21
+ const account = await accountId();
22
+ for (const budget of BUDGETS) {
23
+ const existing = await orUndefined(
24
+ budgets().send(new DescribeBudgetCommand({ AccountId: account, BudgetName: budget.name })),
25
+ "NotFoundException",
26
+ );
27
+ if (existing) continue;
28
+ await budgets().send(
29
+ new CreateBudgetCommand({
30
+ AccountId: account,
31
+ Budget: {
32
+ BudgetName: budget.name,
33
+ BudgetType: "COST",
34
+ TimeUnit: "MONTHLY",
35
+ BudgetLimit: { Amount: String(budget.dollars), Unit: "USD" },
36
+ },
37
+ NotificationsWithSubscribers: [
38
+ {
39
+ Notification: {
40
+ NotificationType: "ACTUAL",
41
+ ComparisonOperator: "GREATER_THAN",
42
+ Threshold: 100,
43
+ ThresholdType: "PERCENTAGE",
44
+ },
45
+ Subscribers: [{ SubscriptionType: "EMAIL", Address: email }],
46
+ },
47
+ {
48
+ Notification: {
49
+ NotificationType: "FORECASTED",
50
+ ComparisonOperator: "GREATER_THAN",
51
+ Threshold: 100,
52
+ ThresholdType: "PERCENTAGE",
53
+ },
54
+ Subscribers: [{ SubscriptionType: "EMAIL", Address: email }],
55
+ },
56
+ ],
57
+ }),
58
+ );
59
+ log(` budget $${budget.dollars}/month → ${email}`);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Cost Anomaly Detection watches every service; a new one appearing on the bill is exactly what it
65
+ * catches. An account may have one per-service monitor, so an existing one is used as is.
66
+ */
67
+ export async function ensureAnomalyAlerts(email: string) {
68
+ const monitors = await costExplorer().send(new GetAnomalyMonitorsCommand({}));
69
+ let monitorArn = monitors.AnomalyMonitors?.find(
70
+ (monitor) => monitor.MonitorType === "DIMENSIONAL" && monitor.MonitorDimension === "SERVICE",
71
+ )?.MonitorArn;
72
+ if (!monitorArn) {
73
+ const created = await costExplorer().send(
74
+ new CreateAnomalyMonitorCommand({
75
+ AnomalyMonitor: {
76
+ MonitorName: platform.anomalyMonitor,
77
+ MonitorType: "DIMENSIONAL",
78
+ MonitorDimension: "SERVICE",
79
+ },
80
+ }),
81
+ );
82
+ monitorArn = created.MonitorArn;
83
+ log(" created cost anomaly monitor");
84
+ }
85
+ if (!monitorArn) return;
86
+ const subscriptions = await costExplorer().send(new GetAnomalySubscriptionsCommand({ MonitorArn: monitorArn }));
87
+ const subscribed = subscriptions.AnomalySubscriptions?.some((subscription) =>
88
+ subscription.Subscribers?.some((subscriber) => subscriber.Address === email),
89
+ );
90
+ if (subscribed) {
91
+ log(` cost anomalies already alert ${email}`);
92
+ return;
93
+ }
94
+ await costExplorer().send(
95
+ new CreateAnomalySubscriptionCommand({
96
+ AnomalySubscription: {
97
+ SubscriptionName: platform.anomalyMonitor,
98
+ MonitorArnList: [monitorArn],
99
+ Subscribers: [{ Type: "EMAIL", Address: email }],
100
+ Frequency: "IMMEDIATE",
101
+ ThresholdExpression: {
102
+ Dimensions: {
103
+ Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
104
+ MatchOptions: ["GREATER_THAN_OR_EQUAL"],
105
+ Values: [ANOMALY_DOLLARS],
106
+ },
107
+ },
108
+ },
109
+ }),
110
+ );
111
+ log(` cost anomalies ≥ $${ANOMALY_DOLLARS} → ${email}`);
112
+ }