blogwright 0.5.0 → 0.7.0
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/agent/agent-manifest.json +1 -1
- package/dist/adapters/node-dns.d.ts +20 -0
- package/dist/adapters/node-dns.js +49 -0
- package/dist/cli.js +6 -0
- package/dist/commands.js +29 -5
- package/dist/context.d.ts +20 -0
- package/dist/context.js +47 -0
- package/dist/domains.d.ts +46 -0
- package/dist/domains.js +125 -0
- package/dist/nodes.d.ts +11 -0
- package/dist/nodes.js +442 -66
- package/dist/ports.d.ts +15 -0
- package/dist/router-function.d.ts +29 -0
- package/dist/router-function.js +149 -0
- package/package.json +3 -3
package/dist/nodes.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { ALL_VIEWER_EXCEPT_HOST_HEADER, AwsError, CACHING_DISABLED, CACHING_OPTIMIZED, CLOUDFRONT_ALIAS_ZONE_ID, CONTENT_SECURITY_POLICY_DEFAULT_QUOTA, CUSTOM_RESPONSE_HEADERS_DEFAULT_QUOTA, MICROVM_CPU_ARCHITECTURE, pollUntil, REPRODUCIBLE_ZIP_MTIME, STAGED_RELEASES_PREFIX, createZip, textTag, WEB_FUNCTION_RUNTIME, withRetry, } from 'blogwright-core';
|
|
2
3
|
import { packageAndUploadAgent } from './agent-package.js';
|
|
4
|
+
import { certificateToken, desiredHostnames, findHostedZone, recordedDomains, routingGuidance, sameSet, siteHostnames, } from './domains.js';
|
|
5
|
+
import { routerCodeHash, ssrRouterCode, staticRouterCode, } from './router-function.js';
|
|
3
6
|
/** Lambda-managed MicroVM base image (Amazon Linux 2023) for the primary region. */
|
|
4
7
|
function microvmBaseImageArn(region) {
|
|
5
8
|
return `arn:aws:lambda:${region}:aws:microvm-image:al2023-1`;
|
|
@@ -170,8 +173,16 @@ async function applyBuildRolePolicy(ctx) {
|
|
|
170
173
|
await ctx.clients.iam.putRolePolicy(ctx.names.buildRole, 'build', {
|
|
171
174
|
Version: '2012-10-17',
|
|
172
175
|
Statement: [
|
|
173
|
-
{
|
|
174
|
-
|
|
176
|
+
{
|
|
177
|
+
Effect: 'Allow',
|
|
178
|
+
Action: ['s3:GetObject'],
|
|
179
|
+
Resource: `arn:aws:s3:::${ctx.names.bucket}/*`,
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
Effect: 'Allow',
|
|
183
|
+
Action: ['s3:ListBucket'],
|
|
184
|
+
Resource: `arn:aws:s3:::${ctx.names.bucket}`,
|
|
185
|
+
},
|
|
175
186
|
{
|
|
176
187
|
// s3:PutObjectTagging is required even though the tags ride on the PUT
|
|
177
188
|
// itself (x-amz-tagging header) - AWS checks it as a distinct action, and
|
|
@@ -311,7 +322,10 @@ async function imageInput(ctx) {
|
|
|
311
322
|
// Bucket + region for the agent, which polls s3://<bucket>/build/pending.json and
|
|
312
323
|
// resolves credentials from IMDS (→ the build role identity). Hookless: hooks are
|
|
313
324
|
// delivered over TLS which the agent can't satisfy, and are unnecessary here.
|
|
314
|
-
environmentVariables: {
|
|
325
|
+
environmentVariables: {
|
|
326
|
+
BUILD_BUCKET: ctx.names.bucket,
|
|
327
|
+
BUILD_REGION: ctx.config.region,
|
|
328
|
+
},
|
|
315
329
|
// Arm64 in every environment, so what the build compiles or installs matches
|
|
316
330
|
// the Web Function runtime (and `ARM_64` is the API's only value). Sent on
|
|
317
331
|
// create AND update, because `imageBody` emits it either way.
|
|
@@ -429,7 +443,16 @@ function microvmImageNode() {
|
|
|
429
443
|
},
|
|
430
444
|
};
|
|
431
445
|
}
|
|
432
|
-
/**
|
|
446
|
+
/**
|
|
447
|
+
* ACM certificate (us-east-1) - only present when a custom domain is configured.
|
|
448
|
+
*
|
|
449
|
+
* Production carries one certificate for every hostname the site serves (the
|
|
450
|
+
* primary as `DomainName`, the rest as subject alternative names), because a
|
|
451
|
+
* distribution takes a single viewer certificate. ACM cannot change the names
|
|
452
|
+
* on an issued certificate, so a changed name set requests a replacement; the
|
|
453
|
+
* old certificate stays attached and is retired by `retirePreviousCertificate`
|
|
454
|
+
* once the distribution carries the new one. Previews keep one wildcard name.
|
|
455
|
+
*/
|
|
433
456
|
function certificateNode() {
|
|
434
457
|
return {
|
|
435
458
|
id: 'acm-certificate',
|
|
@@ -441,6 +464,10 @@ function certificateNode() {
|
|
|
441
464
|
const arn = output(ctx, 'acm-certificate').arn;
|
|
442
465
|
if (typeof arn !== 'string')
|
|
443
466
|
return false;
|
|
467
|
+
// A name set that no longer matches needs a replacement, which `create` does.
|
|
468
|
+
if (!ctx.preview && !sameSet(recordedDomains(ctx), await desiredHostnames(ctx))) {
|
|
469
|
+
return false;
|
|
470
|
+
}
|
|
444
471
|
try {
|
|
445
472
|
const status = await ctx.clients.acm.describeCertificate(arn);
|
|
446
473
|
return status.status === 'ISSUED';
|
|
@@ -456,15 +483,15 @@ function certificateNode() {
|
|
|
456
483
|
const domain = ctx.domain;
|
|
457
484
|
if (!domain)
|
|
458
485
|
throw new Error('certificate node requires a domain');
|
|
486
|
+
const out = output(ctx, 'acm-certificate');
|
|
459
487
|
// Previews are served at <pr-id>.<domain>, so the cert must be wildcard.
|
|
460
|
-
const
|
|
461
|
-
let arn =
|
|
462
|
-
if (!
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
await ctx.save();
|
|
488
|
+
const names = ctx.preview ? [`*.${domain}`] : await desiredHostnames(ctx);
|
|
489
|
+
let arn = out.arn;
|
|
490
|
+
if (arn && !ctx.preview && !sameSet(recordedDomains(ctx), names)) {
|
|
491
|
+
arn = await replaceCertificate(ctx, arn, names);
|
|
492
|
+
}
|
|
493
|
+
else if (!arn) {
|
|
494
|
+
arn = await requestCertificate(ctx, names);
|
|
468
495
|
}
|
|
469
496
|
let initial = await ctx.clients.acm.describeCertificate(arn);
|
|
470
497
|
if (initial.status === 'PENDING_VALIDATION' && initial.validation.length === 0) {
|
|
@@ -493,11 +520,7 @@ function certificateNode() {
|
|
|
493
520
|
ctx.logger.step('created ACM validation records in Route53; waiting for ISSUED…');
|
|
494
521
|
}
|
|
495
522
|
else {
|
|
496
|
-
ctx.
|
|
497
|
-
for (const r of initial.validation) {
|
|
498
|
-
ctx.logger.info(` ${r.type} ${r.name} -> ${r.value}`);
|
|
499
|
-
}
|
|
500
|
-
ctx.logger.step('waiting for certificate to be ISSUED (Ctrl-C to background)…');
|
|
523
|
+
await validateProduction(ctx, initial.validation);
|
|
501
524
|
}
|
|
502
525
|
}
|
|
503
526
|
const settled = await pollUntil(() => ctx.clients.acm.describeCertificate(arn), (s) => s.status === 'ISSUED' || s.status === 'FAILED', { intervalMs: 15_000, timeoutMs: 30 * 60_000 });
|
|
@@ -506,12 +529,130 @@ function certificateNode() {
|
|
|
506
529
|
}
|
|
507
530
|
},
|
|
508
531
|
async delete(ctx) {
|
|
509
|
-
const
|
|
510
|
-
|
|
511
|
-
|
|
532
|
+
const out = output(ctx, 'acm-certificate');
|
|
533
|
+
for (const arn of [out.arn, out.previousArn]) {
|
|
534
|
+
if (typeof arn === 'string')
|
|
535
|
+
await ctx.clients.acm.deleteCertificate(arn);
|
|
536
|
+
}
|
|
512
537
|
},
|
|
513
538
|
};
|
|
514
539
|
}
|
|
540
|
+
/**
|
|
541
|
+
* Request a certificate for `names` (the first is its subject) and record it.
|
|
542
|
+
* `previousArn`, when given, is recorded in the same save as the new ARN, so
|
|
543
|
+
* state never names a superseded certificate that a failed request left
|
|
544
|
+
* without a replacement.
|
|
545
|
+
*/
|
|
546
|
+
async function requestCertificate(ctx, names, previousArn) {
|
|
547
|
+
const [subject, ...alternatives] = names;
|
|
548
|
+
if (!subject)
|
|
549
|
+
throw new Error('certificate node requires a domain');
|
|
550
|
+
const out = output(ctx, 'acm-certificate');
|
|
551
|
+
// ACM idempotency token must match \w+ (no dashes) and fit 32 characters.
|
|
552
|
+
const token = ctx.preview
|
|
553
|
+
? `${ctx.config.siteName}${ctx.env}`.replace(/\W/g, '')
|
|
554
|
+
: certificateToken(ctx.config.siteName, ctx.env, names);
|
|
555
|
+
const arn = await ctx.clients.acm.requestCertificate(subject, token, ctx.tags, alternatives);
|
|
556
|
+
if (previousArn !== undefined)
|
|
557
|
+
out.previousArn = previousArn;
|
|
558
|
+
out.arn = arn;
|
|
559
|
+
out.domains = ctx.preview ? names : [...names].sort();
|
|
560
|
+
await ctx.save();
|
|
561
|
+
return arn;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Swap the recorded certificate for one covering `names`. The certificate the
|
|
565
|
+
* distribution may still be serving is remembered as `previousArn`. When the
|
|
566
|
+
* recorded certificate is not the one attached, it never served and is
|
|
567
|
+
* dropped; when it is attached (an earlier swap finished but ACM refused to
|
|
568
|
+
* delete its predecessor), it becomes the one to retire and the older
|
|
569
|
+
* predecessor is deleted now, since nothing serves it.
|
|
570
|
+
*/
|
|
571
|
+
async function replaceCertificate(ctx, current, names) {
|
|
572
|
+
const out = output(ctx, 'acm-certificate');
|
|
573
|
+
ctx.logger.info(` certificate names changed; requesting a replacement for ${names.join(', ')}`);
|
|
574
|
+
const earlier = typeof out.previousArn === 'string' ? out.previousArn : undefined;
|
|
575
|
+
if (earlier === undefined)
|
|
576
|
+
return requestCertificate(ctx, names, current);
|
|
577
|
+
const distributionId = output(ctx, 'cloudfront-distribution').id;
|
|
578
|
+
const live = typeof distributionId === 'string'
|
|
579
|
+
? await ctx.clients.cloudfront.getDistributionAliases(distributionId)
|
|
580
|
+
: undefined;
|
|
581
|
+
const stale = live?.certificateArn === current ? earlier : current;
|
|
582
|
+
try {
|
|
583
|
+
await ctx.clients.acm.deleteCertificate(stale);
|
|
584
|
+
}
|
|
585
|
+
catch (err) {
|
|
586
|
+
ctx.logger.warn(`could not delete the superseded certificate ${stale}: ${String(err)}`);
|
|
587
|
+
}
|
|
588
|
+
return requestCertificate(ctx, names, stale === current ? earlier : current);
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Production DNS validation. With `manageDns` the records whose zone is in the
|
|
592
|
+
* account's Route 53 are created; every other still-pending record is printed,
|
|
593
|
+
* grouped by hostname. A record ACM already marks validated is skipped (the
|
|
594
|
+
* validation CNAME is per hostname, so an apex validated by an earlier
|
|
595
|
+
* certificate needs nothing new).
|
|
596
|
+
*/
|
|
597
|
+
async function validateProduction(ctx, records) {
|
|
598
|
+
const pending = new Map();
|
|
599
|
+
for (const r of records) {
|
|
600
|
+
if (r.status !== 'SUCCESS')
|
|
601
|
+
pending.set(`${r.type} ${r.name}`, r);
|
|
602
|
+
}
|
|
603
|
+
const unmanaged = [];
|
|
604
|
+
for (const r of pending.values()) {
|
|
605
|
+
const zone = ctx.config.manageDns
|
|
606
|
+
? await findHostedZone(ctx.clients.route53, r.domain ?? r.name)
|
|
607
|
+
: undefined;
|
|
608
|
+
if (zone) {
|
|
609
|
+
await ctx.clients.route53.upsertRecord(zone.zoneId, {
|
|
610
|
+
name: r.name,
|
|
611
|
+
type: r.type,
|
|
612
|
+
value: r.value,
|
|
613
|
+
});
|
|
614
|
+
ctx.logger.info(` ${r.domain ?? r.name}: validation record created in Route 53`);
|
|
615
|
+
}
|
|
616
|
+
else {
|
|
617
|
+
unmanaged.push(r);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
if (unmanaged.length > 0) {
|
|
621
|
+
ctx.logger.warn('Add these DNS records at your registrar to validate the certificate:');
|
|
622
|
+
for (const r of unmanaged) {
|
|
623
|
+
ctx.logger.info(` ${r.domain ?? r.name}: ${r.type} ${r.name} -> ${r.value}`);
|
|
624
|
+
}
|
|
625
|
+
ctx.logger.step('waiting for certificate to be ISSUED (Ctrl-C to background)…');
|
|
626
|
+
}
|
|
627
|
+
else {
|
|
628
|
+
ctx.logger.step(pending.size > 0
|
|
629
|
+
? 'created ACM validation records in Route53; waiting for ISSUED…'
|
|
630
|
+
: 'no validation records pending; waiting for ISSUED…');
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Delete the certificate a replacement superseded, once the distribution
|
|
635
|
+
* carries the current one. ACM refuses to delete a certificate CloudFront still
|
|
636
|
+
* references (its update is eventually consistent), so a refusal is kept in
|
|
637
|
+
* state and retried on the next run instead of failing the bootstrap.
|
|
638
|
+
*/
|
|
639
|
+
async function retirePreviousCertificate(ctx, distributionId) {
|
|
640
|
+
const out = output(ctx, 'acm-certificate');
|
|
641
|
+
const previous = out.previousArn;
|
|
642
|
+
if (typeof previous !== 'string' || previous === out.arn)
|
|
643
|
+
return;
|
|
644
|
+
const live = await ctx.clients.cloudfront.getDistributionAliases(distributionId);
|
|
645
|
+
if (live?.certificateArn !== out.arn)
|
|
646
|
+
return;
|
|
647
|
+
try {
|
|
648
|
+
await ctx.clients.acm.deleteCertificate(previous);
|
|
649
|
+
Reflect.deleteProperty(out, 'previousArn');
|
|
650
|
+
ctx.logger.ok('superseded certificate deleted');
|
|
651
|
+
}
|
|
652
|
+
catch (err) {
|
|
653
|
+
ctx.logger.warn(`superseded certificate not deleted yet (${String(err)}); it will be retried on the next bootstrap`);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
515
656
|
/** CloudFront Origin Access Control granting the distribution private read on S3. */
|
|
516
657
|
function oacNode() {
|
|
517
658
|
return {
|
|
@@ -690,7 +831,10 @@ function desiredResponseHeadersPolicyId(ctx) {
|
|
|
690
831
|
function recordResponseHeadersPolicyAttached(ctx, distributionId) {
|
|
691
832
|
const policyId = desiredResponseHeadersPolicyId(ctx);
|
|
692
833
|
if (policyId !== undefined) {
|
|
693
|
-
recordResponseHeadersPolicy(ctx, {
|
|
834
|
+
recordResponseHeadersPolicy(ctx, {
|
|
835
|
+
id: policyId,
|
|
836
|
+
attachedTo: distributionId,
|
|
837
|
+
});
|
|
694
838
|
}
|
|
695
839
|
}
|
|
696
840
|
/**
|
|
@@ -1066,7 +1210,9 @@ function webFunctionNode() {
|
|
|
1066
1210
|
timeoutSeconds: config.timeoutSeconds,
|
|
1067
1211
|
maxConcurrencyPerEnvironment: config.maxConcurrencyPerEnvironment,
|
|
1068
1212
|
environmentVariables: { NODE_ENV: 'production', ...config.env },
|
|
1069
|
-
telemetryConfig: {
|
|
1213
|
+
telemetryConfig: {
|
|
1214
|
+
loggingConfig: { logGroup: ctx.names.webLogGroup },
|
|
1215
|
+
},
|
|
1070
1216
|
},
|
|
1071
1217
|
},
|
|
1072
1218
|
endpointConfig: {
|
|
@@ -1124,7 +1270,11 @@ function webFunctionPolicyStatement(ctx) {
|
|
|
1124
1270
|
Principal: { Service: 'cloudfront.amazonaws.com' },
|
|
1125
1271
|
Action: 'lambda:InvokeWebFunctionEndpoint',
|
|
1126
1272
|
Resource: String(output(ctx, 'web-function').endpointArn),
|
|
1127
|
-
Condition: {
|
|
1273
|
+
Condition: {
|
|
1274
|
+
ArnLike: {
|
|
1275
|
+
'AWS:SourceArn': String(output(ctx, 'cloudfront-distribution').arn),
|
|
1276
|
+
},
|
|
1277
|
+
},
|
|
1128
1278
|
};
|
|
1129
1279
|
}
|
|
1130
1280
|
function webFunctionPolicyNode() {
|
|
@@ -1191,26 +1341,106 @@ const PREVIEW_FUNCTION_CODE = `function handler(event) {
|
|
|
1191
1341
|
return request;
|
|
1192
1342
|
}`;
|
|
1193
1343
|
/**
|
|
1194
|
-
*
|
|
1195
|
-
*
|
|
1196
|
-
* origin is the private REST endpoint (via OAC), which - unlike an S3 website endpoint -
|
|
1197
|
-
* does no index-document resolution, so `DefaultRootObject` only covers the apex. The
|
|
1198
|
-
* `/site` origin path is applied by the distribution, so this function must not add it.
|
|
1344
|
+
* The alias redirect this environment runs, or undefined when none applies:
|
|
1345
|
+
* `redirectToPrimary` needs a primary domain and at least one alias.
|
|
1199
1346
|
*/
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1347
|
+
function aliasRedirect(ctx) {
|
|
1348
|
+
const { aliases, redirectToPrimary } = ctx.config;
|
|
1349
|
+
if (!redirectToPrimary || !ctx.domain || aliases.length === 0)
|
|
1350
|
+
return undefined;
|
|
1351
|
+
return { primary: ctx.domain, aliases };
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* The source of the production/staging router function this environment
|
|
1355
|
+
* should run: path redirects, then the alias host check, then (static only)
|
|
1356
|
+
* the directory-index rewrite.
|
|
1357
|
+
*/
|
|
1358
|
+
function productionRouterCode(ctx) {
|
|
1359
|
+
const redirect = aliasRedirect(ctx);
|
|
1360
|
+
const paths = ctx.config.redirects;
|
|
1361
|
+
if (ctx.config.ssr && ssrNeedsRouter(ctx))
|
|
1362
|
+
return ssrRouterCode(redirect, paths);
|
|
1363
|
+
return staticRouterCode(redirect, paths);
|
|
1364
|
+
}
|
|
1365
|
+
/** True when an SSR distribution needs the viewer-request router attached. */
|
|
1366
|
+
export function ssrNeedsRouter(ctx) {
|
|
1367
|
+
return Boolean(aliasRedirect(ctx)) || ctx.config.redirects.length > 0;
|
|
1368
|
+
}
|
|
1369
|
+
/** Whether the viewer-request router is associated for this mode. */
|
|
1370
|
+
function routerAttached(ctx, mode, preview) {
|
|
1371
|
+
return preview || mode === 'static' || ssrNeedsRouter(ctx);
|
|
1372
|
+
}
|
|
1373
|
+
const ROUTER_COMMENT = (ctx) => `${ctx.config.siteName} ${ctx.env} directory-index router`;
|
|
1374
|
+
/**
|
|
1375
|
+
* Deploy-time half of the router function: republish the source when the
|
|
1376
|
+
* config now produces different code than the recorded `codeHash`, never
|
|
1377
|
+
* touching the distribution. Returns what happened, for the deploy summary.
|
|
1378
|
+
*/
|
|
1379
|
+
export async function reconcileRouterFunction(ctx) {
|
|
1380
|
+
const redirects = ctx.config.redirects.length;
|
|
1381
|
+
const out = output(ctx, 'cloudfront-function');
|
|
1382
|
+
const bootstrap = `blogwright bootstrap ${ctx.env}`;
|
|
1383
|
+
if (typeof out.arn !== 'string') {
|
|
1384
|
+
ctx.logger.warn(`no router function exists yet, so redirects are not live; run \`${bootstrap}\` to create it`);
|
|
1385
|
+
return { status: 'not-bootstrapped', redirects };
|
|
1386
|
+
}
|
|
1387
|
+
if (ctx.config.ssr && !ssrNeedsRouter(ctx)) {
|
|
1388
|
+
// The config no longer needs the router, but the distribution may still run
|
|
1389
|
+
// it; publishing the static rewrite there would break the application's
|
|
1390
|
+
// routes. Leave the code to the bootstrap, which detaches it first.
|
|
1391
|
+
if (output(ctx, 'cloudfront-distribution').routerAttached === true) {
|
|
1392
|
+
ctx.logger.warn(`the router function is still associated with the distribution; run \`${bootstrap}\` to detach it`);
|
|
1393
|
+
}
|
|
1394
|
+
return { status: 'unchanged', redirects };
|
|
1395
|
+
}
|
|
1396
|
+
const code = productionRouterCode(ctx);
|
|
1397
|
+
const hash = routerCodeHash(code);
|
|
1398
|
+
if (ctx.config.ssr) {
|
|
1399
|
+
const attached = output(ctx, 'cloudfront-distribution').routerAttached === true;
|
|
1400
|
+
if (ssrNeedsRouter(ctx) && !attached) {
|
|
1401
|
+
ctx.logger.warn(`the router function is not associated with the distribution, so redirects are not live; ` +
|
|
1402
|
+
`run \`${bootstrap}\` to attach it`);
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
if (out.codeHash === hash)
|
|
1406
|
+
return { status: 'unchanged', redirects };
|
|
1407
|
+
if (out.codeHash === undefined && code === staticRouterCode()) {
|
|
1408
|
+
return { status: 'unchanged', redirects };
|
|
1409
|
+
}
|
|
1410
|
+
try {
|
|
1411
|
+
await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, ROUTER_COMMENT(ctx));
|
|
1412
|
+
}
|
|
1413
|
+
catch (err) {
|
|
1414
|
+
if (err instanceof AwsError && /AccessDenied|not authorized/i.test(err.message)) {
|
|
1415
|
+
throw new Error(`the deploy role may not publish the router function; run \`${bootstrap}\` to update it: ${err.message}`, { cause: err });
|
|
1416
|
+
}
|
|
1417
|
+
throw new Error(`the site is live but the router function failed to publish; run \`${bootstrap}\` to retry: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
1418
|
+
}
|
|
1419
|
+
out.codeHash = hash;
|
|
1420
|
+
await ctx.save();
|
|
1421
|
+
ctx.logger.ok('CloudFront routing function republished');
|
|
1422
|
+
return { status: 'republished', redirects };
|
|
1423
|
+
}
|
|
1208
1424
|
/**
|
|
1209
1425
|
* CloudFront viewer-request function. Preview stacks route a subdomain to its S3 prefix
|
|
1210
1426
|
* (and resolve index documents); staging/production just resolve directory URLs to their
|
|
1211
1427
|
* index document. Both are needed because the OAC/REST S3 origin does no index resolution.
|
|
1212
1428
|
*/
|
|
1213
1429
|
function routerFunctionNode(preview) {
|
|
1430
|
+
/**
|
|
1431
|
+
* The source this environment should run. Staging/production resolve
|
|
1432
|
+
* directory URLs and, with `redirectToPrimary`, also 301 alias hosts to the
|
|
1433
|
+
* primary. SSR sites run the redirect alone, since the application owns its
|
|
1434
|
+
* routing; without a redirect the SSR function is unattached.
|
|
1435
|
+
*/
|
|
1436
|
+
function desiredCode(ctx) {
|
|
1437
|
+
if (preview)
|
|
1438
|
+
return PREVIEW_FUNCTION_CODE;
|
|
1439
|
+
return productionRouterCode(ctx);
|
|
1440
|
+
}
|
|
1441
|
+
function comment(ctx) {
|
|
1442
|
+
return `${ctx.config.siteName} ${ctx.env} ${preview ? 'preview host router' : 'directory-index router'}`;
|
|
1443
|
+
}
|
|
1214
1444
|
return {
|
|
1215
1445
|
id: 'cloudfront-function',
|
|
1216
1446
|
dependsOn: [],
|
|
@@ -1219,13 +1449,28 @@ function routerFunctionNode(preview) {
|
|
|
1219
1449
|
return typeof output(ctx, 'cloudfront-function').arn === 'string';
|
|
1220
1450
|
},
|
|
1221
1451
|
async create(ctx) {
|
|
1222
|
-
const
|
|
1223
|
-
output(ctx, 'cloudfront-function')
|
|
1452
|
+
const code = desiredCode(ctx);
|
|
1453
|
+
const out = output(ctx, 'cloudfront-function');
|
|
1454
|
+
out.arn = await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, comment(ctx));
|
|
1455
|
+
out.codeHash = routerCodeHash(code);
|
|
1224
1456
|
},
|
|
1225
|
-
async update() {
|
|
1226
|
-
//
|
|
1227
|
-
//
|
|
1228
|
-
//
|
|
1457
|
+
async update(ctx) {
|
|
1458
|
+
// Preview code is static. Production code varies with the alias redirect, so
|
|
1459
|
+
// republish when the source differs from the one last published. A site
|
|
1460
|
+
// bootstrapped before the hash was recorded, and still on the plain
|
|
1461
|
+
// directory-index router, is left alone: republishing it would change nothing.
|
|
1462
|
+
if (preview)
|
|
1463
|
+
return;
|
|
1464
|
+
const code = desiredCode(ctx);
|
|
1465
|
+
const hash = routerCodeHash(code);
|
|
1466
|
+
const out = output(ctx, 'cloudfront-function');
|
|
1467
|
+
if (out.codeHash === hash)
|
|
1468
|
+
return;
|
|
1469
|
+
if (out.codeHash === undefined && code === staticRouterCode())
|
|
1470
|
+
return;
|
|
1471
|
+
await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, comment(ctx));
|
|
1472
|
+
out.codeHash = hash;
|
|
1473
|
+
ctx.logger.ok('CloudFront routing function republished');
|
|
1229
1474
|
},
|
|
1230
1475
|
async delete(ctx) {
|
|
1231
1476
|
await ctx.clients.cloudfront.deleteFunction(`${ctx.names.prefix}-router`);
|
|
@@ -1271,12 +1516,15 @@ function distributionShape(ctx, mode, preview) {
|
|
|
1271
1516
|
const shared = {
|
|
1272
1517
|
callerReference: `${ctx.names.prefix}-${ctx.accountId}`,
|
|
1273
1518
|
comment: `${ctx.config.siteName} ${ctx.env}`,
|
|
1274
|
-
aliases: ctx.domain ?
|
|
1519
|
+
aliases: ctx.domain ? (preview ? [`*.${ctx.domain}`] : siteHostnames(ctx)) : [],
|
|
1275
1520
|
acmCertificateArn: ctx.domain ? String(output(ctx, 'acm-certificate').arn) : undefined,
|
|
1276
1521
|
};
|
|
1277
1522
|
const responseHeadersPolicyId = desiredResponseHeadersPolicyId(ctx);
|
|
1278
1523
|
if (mode === 'ssr') {
|
|
1279
1524
|
const config = ssrConfig(ctx);
|
|
1525
|
+
// Aliases must redirect on every path, static or dynamic, so the function
|
|
1526
|
+
// is on each behavior; without a redirect nothing is attached.
|
|
1527
|
+
const functionArn = !preview && ssrNeedsRouter(ctx) ? String(output(ctx, 'cloudfront-function').arn) : undefined;
|
|
1280
1528
|
return {
|
|
1281
1529
|
...shared,
|
|
1282
1530
|
// The app answers `/`; a root object would only intercept it.
|
|
@@ -1298,6 +1546,7 @@ function distributionShape(ctx, mode, preview) {
|
|
|
1298
1546
|
cachePolicyId: String(output(ctx, 'web-cache-policy').id),
|
|
1299
1547
|
originRequestPolicyId: ALL_VIEWER_EXCEPT_HOST_HEADER,
|
|
1300
1548
|
allowedMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'PATCH', 'DELETE'],
|
|
1549
|
+
...(functionArn ? { functionArn } : {}),
|
|
1301
1550
|
responseHeadersPolicyId,
|
|
1302
1551
|
},
|
|
1303
1552
|
// The static paths carry the headers too: they are the same site's responses.
|
|
@@ -1305,6 +1554,7 @@ function distributionShape(ctx, mode, preview) {
|
|
|
1305
1554
|
pathPattern,
|
|
1306
1555
|
targetOriginId: 's3-site',
|
|
1307
1556
|
cachePolicyId: CACHING_OPTIMIZED,
|
|
1557
|
+
...(functionArn ? { functionArn } : {}),
|
|
1308
1558
|
responseHeadersPolicyId,
|
|
1309
1559
|
})),
|
|
1310
1560
|
// No custom error responses: the application owns 404s, and error
|
|
@@ -1366,19 +1616,13 @@ async function reconcileStaticAliases(ctx, distributionId, preview) {
|
|
|
1366
1616
|
ctx.logger.ok('no domain configured - existing aliases left as-is');
|
|
1367
1617
|
return;
|
|
1368
1618
|
}
|
|
1369
|
-
|
|
1619
|
+
// Production: the configured names plus any attached alias config does not
|
|
1620
|
+
// name (kept unless `--prune-aliases`); the certificate node computed the same
|
|
1621
|
+
// set, so the certificate covers whatever is attached.
|
|
1622
|
+
const aliases = preview ? [`*.${ctx.domain}`] : siteHostnames(ctx);
|
|
1370
1623
|
const certArn = String(output(ctx, 'acm-certificate').arn);
|
|
1371
|
-
const changed = await ctx.clients.cloudfront.setDistributionAliases(distributionId,
|
|
1372
|
-
|
|
1373
|
-
ctx.logger.ok(`attached ${alias} to the distribution`);
|
|
1374
|
-
const domainName = output(ctx, 'cloudfront-distribution').domainName;
|
|
1375
|
-
if (typeof domainName === 'string') {
|
|
1376
|
-
ctx.logger.info(` point ${alias} (CNAME/ALIAS) at ${domainName}`);
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
else {
|
|
1380
|
-
ctx.logger.ok('aliases up to date');
|
|
1381
|
-
}
|
|
1624
|
+
const changed = await ctx.clients.cloudfront.setDistributionAliases(distributionId, aliases, certArn);
|
|
1625
|
+
ctx.logger.ok(changed ? `aliases set to ${aliases.join(', ')}` : 'aliases up to date');
|
|
1382
1626
|
}
|
|
1383
1627
|
/** The CloudFront distribution. Preview stacks use a host-routing function + no caching. */
|
|
1384
1628
|
function distributionNode(options) {
|
|
@@ -1451,13 +1695,11 @@ function distributionNode(options) {
|
|
|
1451
1695
|
// The mode the live distribution was left serving, so a later bootstrap can
|
|
1452
1696
|
// tell a routine re-run from a serving cutover.
|
|
1453
1697
|
out.mode = servingMode(ctx);
|
|
1698
|
+
out.routerAttached = routerAttached(ctx, servingMode(ctx), preview);
|
|
1454
1699
|
await ctx.clients.cloudfront.tagResource(dist.arn, ctx.tags);
|
|
1455
1700
|
ctx.logger.info(` CloudFront domain: ${dist.domainName}`);
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
// node, next in the graph); only the main site may be DNS'd elsewhere.
|
|
1459
|
-
ctx.logger.info(` point ${ctx.domain} (CNAME/ALIAS) at ${dist.domainName}`);
|
|
1460
|
-
}
|
|
1701
|
+
// Production routing records are the site-dns node's (next in the graph);
|
|
1702
|
+
// preview stacks create their wildcard record in the preview-dns node.
|
|
1461
1703
|
},
|
|
1462
1704
|
async update(ctx) {
|
|
1463
1705
|
const id = output(ctx, 'cloudfront-distribution').id;
|
|
@@ -1474,21 +1716,22 @@ function distributionNode(options) {
|
|
|
1474
1716
|
if (configured === 'ssr' || (recorded !== undefined && recorded !== configured)) {
|
|
1475
1717
|
const changed = await ctx.clients.cloudfront.reconcileDistribution(id, distributionShape(ctx, configured, preview));
|
|
1476
1718
|
out.mode = configured;
|
|
1719
|
+
out.routerAttached = routerAttached(ctx, configured, preview);
|
|
1477
1720
|
recordResponseHeadersPolicyAttached(ctx, id);
|
|
1478
1721
|
if (changed) {
|
|
1479
1722
|
ctx.logger.ok(`reconciled the distribution for ${configured} serving`);
|
|
1480
|
-
const domainName = out.domainName;
|
|
1481
|
-
if (ctx.domain && !preview && typeof domainName === 'string') {
|
|
1482
|
-
ctx.logger.info(` point ${ctx.domain} (CNAME/ALIAS) at ${domainName}`);
|
|
1483
|
-
}
|
|
1484
1723
|
}
|
|
1485
1724
|
else {
|
|
1486
1725
|
ctx.logger.ok(`distribution already matches ${configured} serving`);
|
|
1487
1726
|
}
|
|
1727
|
+
if (!preview)
|
|
1728
|
+
await retirePreviousCertificate(ctx, id);
|
|
1488
1729
|
return;
|
|
1489
1730
|
}
|
|
1490
1731
|
await reconcileStaticAliases(ctx, id, preview);
|
|
1491
1732
|
await attachResponseHeadersPolicy(ctx, id);
|
|
1733
|
+
if (!preview)
|
|
1734
|
+
await retirePreviousCertificate(ctx, id);
|
|
1492
1735
|
},
|
|
1493
1736
|
async delete(ctx) {
|
|
1494
1737
|
const id = output(ctx, 'cloudfront-distribution').id;
|
|
@@ -1826,7 +2069,11 @@ export function oidcRolePolicyStatements(ctx) {
|
|
|
1826
2069
|
Resource: `arn:aws:s3:::${ctx.names.bucket}/*`,
|
|
1827
2070
|
},
|
|
1828
2071
|
...promoteTaggingStatements(ctx),
|
|
1829
|
-
{
|
|
2072
|
+
{
|
|
2073
|
+
Effect: 'Allow',
|
|
2074
|
+
Action: ['s3:ListBucket'],
|
|
2075
|
+
Resource: `arn:aws:s3:::${ctx.names.bucket}`,
|
|
2076
|
+
},
|
|
1830
2077
|
{
|
|
1831
2078
|
Effect: 'Allow',
|
|
1832
2079
|
Action: [
|
|
@@ -1869,6 +2116,16 @@ export function oidcRolePolicyStatements(ctx) {
|
|
|
1869
2116
|
Action: ['cloudfront:CreateInvalidation'],
|
|
1870
2117
|
Resource: String(output(ctx, 'cloudfront-distribution').arn),
|
|
1871
2118
|
});
|
|
2119
|
+
// Deploys republish the router function's code (`reconcileRouterFunction`).
|
|
2120
|
+
statements.push({
|
|
2121
|
+
Effect: 'Allow',
|
|
2122
|
+
Action: [
|
|
2123
|
+
'cloudfront:DescribeFunction',
|
|
2124
|
+
'cloudfront:UpdateFunction',
|
|
2125
|
+
'cloudfront:PublishFunction',
|
|
2126
|
+
],
|
|
2127
|
+
Resource: `arn:aws:cloudfront::${ctx.accountId}:function/${ctx.names.prefix}-router`,
|
|
2128
|
+
});
|
|
1872
2129
|
// Deploys converge the response headers in place - this one policy only,
|
|
1873
2130
|
// never the distribution (`reconcileResponseHeadersOnDeploy`).
|
|
1874
2131
|
const policyId = recordedResponseHeadersPolicyId(ctx);
|
|
@@ -1899,7 +2156,9 @@ async function applyOidcRole(ctx, roleName) {
|
|
|
1899
2156
|
Action: 'sts:AssumeRoleWithWebIdentity',
|
|
1900
2157
|
Condition: {
|
|
1901
2158
|
StringEquals: { [`${GITHUB_OIDC_URL}:aud`]: 'sts.amazonaws.com' },
|
|
1902
|
-
StringLike: {
|
|
2159
|
+
StringLike: {
|
|
2160
|
+
[`${GITHUB_OIDC_URL}:sub`]: oidcSubClaim(repo, ctx.env, ctx.preview),
|
|
2161
|
+
},
|
|
1903
2162
|
},
|
|
1904
2163
|
},
|
|
1905
2164
|
],
|
|
@@ -1992,6 +2251,121 @@ function previewDnsNode() {
|
|
|
1992
2251
|
},
|
|
1993
2252
|
};
|
|
1994
2253
|
}
|
|
2254
|
+
/**
|
|
2255
|
+
* Routing for the production hostnames: the records that point each name at
|
|
2256
|
+
* the distribution. With `manageDns`, hosts whose hosted zone is in the
|
|
2257
|
+
* account's Route 53 get A and AAAA alias records (recorded in state so a
|
|
2258
|
+
* teardown or a prune removes them); every other host is printed, as an
|
|
2259
|
+
* apex or a sub-domain according to what DNS says its zone is. Guidance is
|
|
2260
|
+
* printed when it changes, not on every run.
|
|
2261
|
+
*/
|
|
2262
|
+
function siteDnsNode() {
|
|
2263
|
+
const TYPES = ['A', 'AAAA'];
|
|
2264
|
+
async function reconcile(ctx) {
|
|
2265
|
+
const target = output(ctx, 'cloudfront-distribution').domainName;
|
|
2266
|
+
if (typeof target !== 'string')
|
|
2267
|
+
return;
|
|
2268
|
+
const out = output(ctx, 'site-dns');
|
|
2269
|
+
const hosts = siteHostnames(ctx);
|
|
2270
|
+
const previousHosts = Array.isArray(out.hosts) ? out.hosts : [];
|
|
2271
|
+
const previousZones = Array.isArray(out.zoneIds) ? out.zoneIds : [];
|
|
2272
|
+
const managedHosts = [];
|
|
2273
|
+
const managedZones = [];
|
|
2274
|
+
const guidance = [];
|
|
2275
|
+
for (const host of hosts) {
|
|
2276
|
+
const zone = ctx.config.manageDns
|
|
2277
|
+
? await findHostedZone(ctx.clients.route53, host)
|
|
2278
|
+
: undefined;
|
|
2279
|
+
if (zone) {
|
|
2280
|
+
try {
|
|
2281
|
+
for (const type of TYPES) {
|
|
2282
|
+
await ctx.clients.route53.upsertRecord(zone.zoneId, {
|
|
2283
|
+
name: host,
|
|
2284
|
+
type,
|
|
2285
|
+
value: target,
|
|
2286
|
+
aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
managedHosts.push(host);
|
|
2290
|
+
managedZones.push(zone.zoneId);
|
|
2291
|
+
ctx.logger.info(` ${host} -> ${target} (Route 53 alias)`);
|
|
2292
|
+
continue;
|
|
2293
|
+
}
|
|
2294
|
+
catch (err) {
|
|
2295
|
+
// A CNAME already at the name is the usual cause; fall back to guidance.
|
|
2296
|
+
ctx.logger.warn(`could not write Route 53 records for ${host}: ${String(err)}`);
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
guidance.push(await routingGuidance(ctx.ports.dns, host, target));
|
|
2300
|
+
}
|
|
2301
|
+
// Records this node wrote for a host that is no longer served.
|
|
2302
|
+
for (const [i, host] of previousHosts.entries()) {
|
|
2303
|
+
const zoneId = previousZones[i];
|
|
2304
|
+
if (hosts.includes(host) || zoneId === undefined)
|
|
2305
|
+
continue;
|
|
2306
|
+
for (const type of TYPES) {
|
|
2307
|
+
await ctx.clients.route53.deleteRecord(zoneId, {
|
|
2308
|
+
name: host,
|
|
2309
|
+
type,
|
|
2310
|
+
value: target,
|
|
2311
|
+
aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
|
|
2312
|
+
});
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
// A host still served but not written this run (manageDns turned off, or a
|
|
2316
|
+
// write that fell back to guidance) keeps its record of what was written,
|
|
2317
|
+
// so a later prune or teardown still removes the records.
|
|
2318
|
+
for (const [i, host] of previousHosts.entries()) {
|
|
2319
|
+
const zoneId = previousZones[i];
|
|
2320
|
+
if (zoneId === undefined || !hosts.includes(host) || managedHosts.includes(host))
|
|
2321
|
+
continue;
|
|
2322
|
+
managedHosts.push(host);
|
|
2323
|
+
managedZones.push(zoneId);
|
|
2324
|
+
}
|
|
2325
|
+
out.hosts = managedHosts;
|
|
2326
|
+
out.zoneIds = managedZones;
|
|
2327
|
+
const signature = createHash('sha256')
|
|
2328
|
+
.update([target, ...hosts, ...guidance].join('\n'))
|
|
2329
|
+
.digest('hex');
|
|
2330
|
+
if (guidance.length > 0 && out.signature !== signature) {
|
|
2331
|
+
ctx.logger.warn(`Point these hostnames at ${target}:`);
|
|
2332
|
+
for (const line of guidance)
|
|
2333
|
+
ctx.logger.info(` ${line}`);
|
|
2334
|
+
}
|
|
2335
|
+
out.signature = signature;
|
|
2336
|
+
}
|
|
2337
|
+
return {
|
|
2338
|
+
id: 'site-dns',
|
|
2339
|
+
dependsOn: ['cloudfront-distribution'],
|
|
2340
|
+
title: 'Site DNS routing',
|
|
2341
|
+
async read(ctx) {
|
|
2342
|
+
return typeof output(ctx, 'site-dns').signature === 'string';
|
|
2343
|
+
},
|
|
2344
|
+
create: reconcile,
|
|
2345
|
+
update: reconcile,
|
|
2346
|
+
async delete(ctx) {
|
|
2347
|
+
const out = output(ctx, 'site-dns');
|
|
2348
|
+
const target = output(ctx, 'cloudfront-distribution').domainName;
|
|
2349
|
+
const hosts = Array.isArray(out.hosts) ? out.hosts : [];
|
|
2350
|
+
const zones = Array.isArray(out.zoneIds) ? out.zoneIds : [];
|
|
2351
|
+
if (typeof target !== 'string')
|
|
2352
|
+
return;
|
|
2353
|
+
for (const [i, host] of hosts.entries()) {
|
|
2354
|
+
const zoneId = zones[i];
|
|
2355
|
+
if (zoneId === undefined)
|
|
2356
|
+
continue;
|
|
2357
|
+
for (const type of TYPES) {
|
|
2358
|
+
await ctx.clients.route53.deleteRecord(zoneId, {
|
|
2359
|
+
name: host,
|
|
2360
|
+
type,
|
|
2361
|
+
value: target,
|
|
2362
|
+
aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
|
|
2363
|
+
});
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
},
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
1995
2369
|
/** Build the full node set for the current context (production or preview stack). */
|
|
1996
2370
|
export function buildNodes(ctx) {
|
|
1997
2371
|
const hasDomain = Boolean(ctx.domain);
|
|
@@ -2023,6 +2397,8 @@ export function buildNodes(ctx) {
|
|
|
2023
2397
|
nodes.push(webFunctionPolicyNode());
|
|
2024
2398
|
if (hasDomain)
|
|
2025
2399
|
nodes.push(certificateNode());
|
|
2400
|
+
if (hasDomain && !ctx.preview)
|
|
2401
|
+
nodes.push(siteDnsNode());
|
|
2026
2402
|
if (ctx.preview) {
|
|
2027
2403
|
nodes.push(previewDnsNode(), githubOidcRoleNode(true, false));
|
|
2028
2404
|
}
|