@elumixor/devkit 0.12.12 → 0.12.13

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.
package/README.md CHANGED
@@ -279,6 +279,11 @@ A `domains` entry starting with `*.` (say `*.desk.atmagaming.com`) only adds a w
279
279
  distribution: every hostname under it then rides one certificate name, which keeps the shared
280
280
  certificate under ACM's per-certificate name quota. List it next to the hosts it covers.
281
281
 
282
+ A domain whose DNS isn't on Cloudflare still works: the deploy prints the certificate's validation
283
+ CNAME and the record to point at the distribution, waits for the validation, and serves the host once
284
+ its DNS points there. Crons call their path with `Authorization: Bearer $CRON_SECRET`, made on the
285
+ first deploy.
286
+
282
287
  `devkit deploy` builds, then: reconciles the function, role, log group, URL, schedules and domains;
283
288
  uploads the static files (unchanged files are copied server-side); publishes a new function
284
289
  version; runs `predeploy` with the stage's env; invokes the new version's `/api/health`; and only
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elumixor/devkit",
3
- "version": "0.12.12",
3
+ "version": "0.12.13",
4
4
  "description": "Dev orchestrator for bun monorepos — free ports, run apps side-by-side, open the browser when ready",
5
5
  "author": "elumixor",
6
6
  "license": "ISC",
@@ -6,7 +6,7 @@ import { ensureCertificate } from "./reconcile/acm.ts";
6
6
  import { ensureRecord } from "./reconcile/cloudflare.ts";
7
7
  import { findDistribution, reconcileAliases, waitDeployed } from "./reconcile/edge.ts";
8
8
  import { ensureAnomalyAlerts, ensureBudgets } from "./reconcile/guardrails.ts";
9
- import { ensureDeployRole, ensureLocalDeployProfile, ensureSchedulerRole } from "./reconcile/iam.ts";
9
+ import { ensureDeployRole, ensureLocalDeployProfile, ensureSchedulerRole, GITHUB_OWNERS } from "./reconcile/iam.ts";
10
10
  import { putEdgeSecret } from "./reconcile/kvs.ts";
11
11
  import {
12
12
  allowDistribution,
@@ -43,7 +43,7 @@ export async function bootstrap(options: BootstrapOptions = {}) {
43
43
 
44
44
  log("\nbuckets");
45
45
  const { sites, blobs } = await buckets();
46
- await Promise.all([ensureBucket(sites), ensureBucket(blobs)]);
46
+ await Promise.all([ensureBucket(sites), ensureBucket(blobs, { browserUploads: true })]);
47
47
 
48
48
  log("\nedge");
49
49
  const [oacId, cachePolicyId, kvsArn] = await Promise.all([
@@ -82,7 +82,7 @@ export async function bootstrap(options: BootstrapOptions = {}) {
82
82
  const local = await ensureLocalDeployProfile();
83
83
  log(` role ${platform.schedulerRole} ${scheduler.created ? "created" : "ok"}`);
84
84
  log(
85
- ` role ${platform.deployRole} ${deploy.created ? "created" : "ok"} (GitHub OIDC, elumixor/* on ${Object.values(STAGE_BRANCHES).join(", ")})`,
85
+ ` role ${platform.deployRole} ${deploy.created ? "created" : "ok"} (GitHub OIDC, ${GITHUB_OWNERS.map((owner) => `${owner.name}/*`).join(", ")} on ${Object.values(STAGE_BRANCHES).join(", ")})`,
86
86
  );
87
87
  log(` profile ${platform.localProfile} ${local.profile} (user ${platform.localDeployUser})`);
88
88
 
@@ -23,6 +23,8 @@ const nitro = await nitroModule.createNitro({
23
23
  dev: false,
24
24
  preset: "aws-lambda",
25
25
  awsLambda: { streaming: true },
26
+ // devkit ships TypeScript (`@elumixor/devkit/blob`, `/runtime`), and Nitro's esbuild skips node_modules.
27
+ esbuild: { options: { exclude: /node_modules\/(?!\.bun\/@elumixor\+devkit|@elumixor\/devkit)/ } },
26
28
  });
27
29
  await nitroModule.prepare(nitro);
28
30
  await nitroModule.copyPublicAssets(nitro);
@@ -7,7 +7,7 @@ import {
7
7
  RequestCertificateCommand,
8
8
  } from "@aws-sdk/client-acm";
9
9
  import { acm, CloudError, log, platformTags, waitFor } from "../aws.ts";
10
- import { ensureRecord } from "./cloudflare.ts";
10
+ import { ExternalDnsError, ensureRecord } from "./cloudflare.ts";
11
11
 
12
12
  /**
13
13
  * One certificate carries every hostname the distribution answers for (Plan A). A certificate
@@ -48,8 +48,15 @@ export async function ensureCertificate(names: readonly string[]): Promise<strin
48
48
  const record = option.ResourceRecord;
49
49
  if (!record?.Name || !record.Value || written.has(record.Name)) continue;
50
50
  written.add(record.Name);
51
- const outcome = await ensureRecord(record.Name.replace(/\.$/, ""), "CNAME", record.Value.replace(/\.$/, ""));
52
- log(` validation record ${record.Name} ${outcome}`);
51
+ const name = record.Name.replace(/\.$/, "");
52
+ const value = record.Value.replace(/\.$/, "");
53
+ try {
54
+ log(` validation record ${name} ${await ensureRecord(name, "CNAME", value)}`);
55
+ } catch (error) {
56
+ if (!(error instanceof ExternalDnsError)) throw error;
57
+ // DNS hosted elsewhere: whoever runs the deploy adds the record there while this waits.
58
+ log(` add at ${option.DomainName}'s DNS provider: ${name} CNAME ${value}`);
59
+ }
53
60
  }
54
61
  return undefined;
55
62
  },
@@ -52,6 +52,9 @@ async function call<T>(method: string, path: string, body?: unknown): Promise<T>
52
52
  return envelope.result;
53
53
  }
54
54
 
55
+ /** The hostname's DNS is hosted elsewhere: its records have to be added at that provider by hand. */
56
+ export class ExternalDnsError extends CloudError {}
57
+
55
58
  const zones = new Map<string, Promise<string>>();
56
59
 
57
60
  /** The zone a hostname belongs to: the longest zone name the token can see that ends the hostname. */
@@ -64,7 +67,7 @@ function zoneFor(hostname: string) {
64
67
  const zone = all
65
68
  .filter((candidate) => apex === candidate.name || apex.endsWith(`.${candidate.name}`))
66
69
  .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`);
70
+ if (!zone) throw new ExternalDnsError(`No Cloudflare zone covers ${hostname} — add the zone or widen the token`);
68
71
  return zone.id;
69
72
  })();
70
73
  zones.set(apex, lookup);
@@ -121,8 +124,13 @@ export async function recordPointsAt(name: string, type: "CNAME" | "TXT", conten
121
124
  return existing !== undefined && matches(existing, content);
122
125
  }
123
126
 
127
+ /** Deletes the record; one at a DNS provider other than Cloudflare is left for its owner to remove. */
124
128
  export async function deleteRecord(name: string, type: "CNAME" | "TXT") {
125
- const zone = await zoneFor(name);
129
+ const zone = await zoneFor(name).catch((error: unknown) => {
130
+ if (error instanceof ExternalDnsError) return undefined;
131
+ throw error;
132
+ });
133
+ if (!zone) return 0;
126
134
  const found = await call<CloudflareRecord[]>(
127
135
  "GET",
128
136
  `/zones/${zone}/dns_records?type=${type}&name=${encodeURIComponent(name)}`,
@@ -1,3 +1,4 @@
1
+ import { resolve4, resolveCname } from "node:dns/promises";
1
2
  import {
2
3
  type DistributionConfig,
3
4
  GetDistributionCommand,
@@ -8,7 +9,7 @@ import {
8
9
  import { CloudError, cloudfront, log, waitFor } from "../aws.ts";
9
10
  import { PLATFORM_ALIASES, WILDCARD_DOMAIN } from "../names.ts";
10
11
  import { deleteUnusedCertificates, ensureCertificate } from "./acm.ts";
11
- import { ensureRecord, recordPointsAt } from "./cloudflare.ts";
12
+ import { ExternalDnsError, ensureRecord, recordPointsAt } from "./cloudflare.ts";
12
13
 
13
14
  /** How the one distribution is recognised among any others in the account. */
14
15
  export const DISTRIBUTION_COMMENT = "dk-edge";
@@ -104,7 +105,13 @@ export async function pointDns(hostnames: readonly string[], aliasesChanged: boo
104
105
  const distribution = await requireDistribution();
105
106
  const pending = [];
106
107
  for (const hostname of hostnames.filter(needsDns))
107
- if (!(await recordPointsAt(hostname, "CNAME", distribution.domainName))) pending.push(hostname);
108
+ try {
109
+ if (!(await recordPointsAt(hostname, "CNAME", distribution.domainName))) pending.push(hostname);
110
+ } catch (error) {
111
+ if (!(error instanceof ExternalDnsError)) throw error;
112
+ if (await resolvesTo(hostname, distribution.domainName)) continue;
113
+ log(` point ${hostname} at ${distribution.domainName} at its DNS provider (CNAME, or ALIAS for an apex)`);
114
+ }
108
115
  if (!pending.length) return;
109
116
  if (aliasesChanged) await waitDeployed(distribution.id);
110
117
  log(` waiting ${ROUTE_PROPAGATION_MS / 1000}s for routes to reach every edge before DNS`);
@@ -115,6 +122,14 @@ export async function pointDns(hostnames: readonly string[], aliasesChanged: boo
115
122
  }
116
123
  }
117
124
 
125
+ /** Whether public DNS already sends the hostname to the distribution: by CNAME, or by an apex ALIAS's addresses. */
126
+ async function resolvesTo(hostname: string, target: string) {
127
+ const cnames = await resolveCname(hostname).catch((): string[] => []);
128
+ if (cnames.some((name) => name.replace(/\.$/, "") === target)) return true;
129
+ const [mine, theirs] = await Promise.all([resolve4(hostname).catch((): string[] => []), resolve4(target).catch((): string[] => [])]);
130
+ return mine.some((address) => theirs.includes(address));
131
+ }
132
+
118
133
  /** A distribution change takes minutes to reach every edge; most callers don't wait, bootstrap does. */
119
134
  export async function waitDeployed(id: string) {
120
135
  await waitFor(
@@ -266,12 +266,18 @@ export async function deployPolicy(): Promise<PolicyDocument> {
266
266
  };
267
267
  }
268
268
 
269
- /** elumixor's GitHub account id, which repos made since GitHub's immutable OIDC subjects name instead of a path. */
270
- const GITHUB_OWNER_ID = 12294750;
269
+ /**
270
+ * The GitHub accounts whose repos may deploy. The id is what repos made since GitHub's immutable OIDC
271
+ * subjects name instead of a path.
272
+ */
273
+ export const GITHUB_OWNERS = [
274
+ { name: "elumixor", id: 12294750 },
275
+ { name: "atmagaming", id: 213760613 },
276
+ ] as const;
271
277
 
272
278
  /**
273
- * The role GitHub Actions assumes: only `elumixor/*` repos, only on the branches that deploy. Older repos send
274
- * `repo:elumixor/<repo>:…`, newer ones `repo:elumixor@<owner id>/<repo>@<repo id>:…`.
279
+ * The role GitHub Actions assumes: only the owners' repos, only on the branches that deploy. Older repos send
280
+ * `repo:<owner>/<repo>:…`, newer ones `repo:<owner>@<owner id>/<repo>@<repo id>:…`.
275
281
  */
276
282
  export async function ensureDeployRole(branches: readonly string[]) {
277
283
  const account = await accountId();
@@ -288,10 +294,12 @@ export async function ensureDeployRole(branches: readonly string[]) {
288
294
  Condition: {
289
295
  StringEquals: { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
290
296
  StringLike: {
291
- "token.actions.githubusercontent.com:sub": branches.flatMap((branch) => [
292
- `repo:elumixor/*:ref:refs/heads/${branch}`,
293
- `repo:elumixor@${GITHUB_OWNER_ID}/*:ref:refs/heads/${branch}`,
294
- ]),
297
+ "token.actions.githubusercontent.com:sub": branches.flatMap((branch) =>
298
+ GITHUB_OWNERS.flatMap((owner) => [
299
+ `repo:${owner.name}/*:ref:refs/heads/${branch}`,
300
+ `repo:${owner.name}@${owner.id}/*:ref:refs/heads/${branch}`,
301
+ ]),
302
+ ),
295
303
  },
296
304
  },
297
305
  },
@@ -17,6 +17,7 @@ import {
17
17
  import {
18
18
  CreateBucketCommand,
19
19
  HeadBucketCommand,
20
+ PutBucketCorsCommand,
20
21
  PutBucketLifecycleConfigurationCommand,
21
22
  PutBucketPolicyCommand,
22
23
  PutPublicAccessBlockCommand,
@@ -25,8 +26,11 @@ import { CloudError, cloudfront, log, orUndefined, platformTags, s3, waitFor } f
25
26
  import { ORIGINS, PLATFORM_ALIASES, PROJECT_HEADER, platform, REGION } from "../names.ts";
26
27
  import { DISTRIBUTION_COMMENT, type Distribution } from "./edge.ts";
27
28
 
28
- /** A private bucket in the home region; nothing in it is reachable except through CloudFront or the SDK. */
29
- export async function ensureBucket(name: string) {
29
+ /**
30
+ * A private bucket in the home region; nothing in it is reachable except through CloudFront or the SDK.
31
+ * `browserUploads` lets pages PUT to presigned URLs (`createUploadUrl`) from any origin.
32
+ */
33
+ export async function ensureBucket(name: string, { browserUploads = false } = {}) {
30
34
  const exists = await orUndefined(s3().send(new HeadBucketCommand({ Bucket: name })), "NotFound", "NoSuchBucket");
31
35
  if (!exists) {
32
36
  await s3().send(
@@ -60,6 +64,23 @@ export async function ensureBucket(name: string) {
60
64
  },
61
65
  }),
62
66
  );
67
+ if (browserUploads)
68
+ await s3().send(
69
+ new PutBucketCorsCommand({
70
+ Bucket: name,
71
+ CORSConfiguration: {
72
+ CORSRules: [
73
+ {
74
+ AllowedHeaders: ["*"],
75
+ AllowedMethods: ["PUT", "GET", "HEAD"],
76
+ AllowedOrigins: ["*"],
77
+ ExposeHeaders: ["ETag"],
78
+ MaxAgeSeconds: 3600,
79
+ },
80
+ ],
81
+ },
82
+ }),
83
+ );
63
84
  return { created: !exists };
64
85
  }
65
86