blogwright 0.4.0 → 0.6.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.
Files changed (56) hide show
  1. package/README.md +4 -1
  2. package/agent/agent-manifest.json +1 -1
  3. package/agent/server.js +2610 -616
  4. package/dist/adapters/node-dns.d.ts +20 -0
  5. package/dist/adapters/node-dns.js +49 -0
  6. package/dist/adapters/process-aws-login.d.ts +19 -0
  7. package/dist/adapters/process-aws-login.js +28 -0
  8. package/dist/agent-package.js +2 -3
  9. package/dist/artifacts.d.ts +73 -0
  10. package/dist/artifacts.js +218 -0
  11. package/dist/aws-session.d.ts +118 -0
  12. package/dist/aws-session.js +360 -0
  13. package/dist/bin.js +6 -2
  14. package/dist/cache-control.d.ts +66 -0
  15. package/dist/cache-control.js +176 -0
  16. package/dist/cli.d.ts +22 -3
  17. package/dist/cli.js +128 -31
  18. package/dist/commands.d.ts +41 -9
  19. package/dist/commands.js +135 -126
  20. package/dist/context.d.ts +42 -5
  21. package/dist/context.js +81 -19
  22. package/dist/deploy.d.ts +78 -6
  23. package/dist/deploy.js +136 -52
  24. package/dist/domains.d.ts +46 -0
  25. package/dist/domains.js +125 -0
  26. package/dist/init.d.ts +14 -2
  27. package/dist/init.js +145 -4
  28. package/dist/known-commands.d.ts +11 -9
  29. package/dist/known-commands.js +15 -9
  30. package/dist/live-release.d.ts +78 -0
  31. package/dist/live-release.js +159 -0
  32. package/dist/lock.d.ts +50 -0
  33. package/dist/lock.js +120 -0
  34. package/dist/nodes.d.ts +18 -0
  35. package/dist/nodes.js +721 -76
  36. package/dist/plugin-commands.d.ts +21 -0
  37. package/dist/plugin-commands.js +54 -3
  38. package/dist/plugins.d.ts +11 -9
  39. package/dist/plugins.js +29 -16
  40. package/dist/ports.d.ts +37 -1
  41. package/dist/releases.d.ts +54 -0
  42. package/dist/releases.js +527 -0
  43. package/dist/render.d.ts +18 -1
  44. package/dist/render.js +38 -6
  45. package/dist/repo.js +2 -3
  46. package/dist/rkey.d.ts +4 -3
  47. package/dist/rkey.js +4 -3
  48. package/dist/router-function.d.ts +24 -0
  49. package/dist/router-function.js +71 -0
  50. package/dist/serving.d.ts +28 -0
  51. package/dist/serving.js +47 -0
  52. package/dist/verify.d.ts +45 -0
  53. package/dist/verify.js +183 -0
  54. package/dist/whoami.d.ts +23 -0
  55. package/dist/whoami.js +88 -0
  56. package/package.json +8 -8
package/dist/nodes.js CHANGED
@@ -1,6 +1,8 @@
1
- import { ALL_VIEWER_EXCEPT_HOST_HEADER, AwsError, CACHING_DISABLED, CACHING_OPTIMIZED, CLOUDFRONT_ALIAS_ZONE_ID, MICROVM_CPU_ARCHITECTURE, pollUntil, REPRODUCIBLE_ZIP_MTIME, textTag, WEB_FUNCTION_RUNTIME, withRetry, } from 'blogwright-core';
2
- import { strToU8, zipSync } from 'fflate';
1
+ import { createHash } from 'node:crypto';
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';
3
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';
4
6
  /** Lambda-managed MicroVM base image (Amazon Linux 2023) for the primary region. */
5
7
  function microvmBaseImageArn(region) {
6
8
  return `arn:aws:lambda:${region}:aws:microvm-image:al2023-1`;
@@ -137,6 +139,32 @@ function webArtifactWriteStatements(ctx) {
137
139
  },
138
140
  ];
139
141
  }
142
+ /**
143
+ * The agent records each static build's artifact manifest at its own
144
+ * `build/artifacts/<hash>/<buildId>.json`. The grant stops at that depth on
145
+ * purpose: a revision's original record, `build/artifacts/<hash>.json`, is
146
+ * written once by the CLI and is out of the builder's reach. `blogwright
147
+ * stage` has the agent publish a release under `releases/<hash>/` instead of
148
+ * `site/` - tagged like the site, and re-staging a hash deletes what the new
149
+ * build no longer contains. The shared preview stack and SSR environments do
150
+ * neither.
151
+ */
152
+ function releaseWriteStatements(ctx) {
153
+ if (ctx.preview || ctx.config.ssr)
154
+ return [];
155
+ return [
156
+ {
157
+ Effect: 'Allow',
158
+ Action: ['s3:PutObject'],
159
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/build/artifacts/*/*`,
160
+ },
161
+ {
162
+ Effect: 'Allow',
163
+ Action: ['s3:PutObject', 's3:PutObjectTagging', 's3:DeleteObject'],
164
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/${STAGED_RELEASES_PREFIX}*`,
165
+ },
166
+ ];
167
+ }
140
168
  /** Apply the build role's inline policy (idempotent - used by create + update). */
141
169
  async function applyBuildRolePolicy(ctx) {
142
170
  // The build role is BOTH the image-build role AND the MicroVM's ambient runtime
@@ -162,6 +190,7 @@ async function applyBuildRolePolicy(ctx) {
162
190
  Resource: `arn:aws:s3:::${ctx.names.bucket}/build/changed/*`,
163
191
  },
164
192
  ...webArtifactWriteStatements(ctx),
193
+ ...releaseWriteStatements(ctx),
165
194
  {
166
195
  Effect: 'Allow',
167
196
  Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
@@ -194,6 +223,15 @@ function buildRoleNode() {
194
223
  },
195
224
  };
196
225
  }
226
+ /**
227
+ * Recorded on the exec role's outputs whenever its policy is applied - true
228
+ * when that policy grants release staging - so `stage` can refuse up front on
229
+ * a stack bootstrapped before it existed rather than fail inside the MicroVM
230
+ * after a full build. A flag rather than a read of the policy itself: the CI
231
+ * deploy role that runs `stage` has no IAM read access, and granting it
232
+ * `iam:GetRolePolicy` to check one statement would widen it for little gain.
233
+ */
234
+ export const RELEASE_STAGING_OUTPUT = 'releaseStaging';
197
235
  async function applyExecRolePolicy(ctx) {
198
236
  await ctx.clients.iam.putRolePolicy(ctx.names.execRole, 'exec', {
199
237
  Version: '2012-10-17',
@@ -219,6 +257,7 @@ async function applyExecRolePolicy(ctx) {
219
257
  ],
220
258
  },
221
259
  ...webArtifactWriteStatements(ctx),
260
+ ...releaseWriteStatements(ctx),
222
261
  {
223
262
  Effect: 'Allow',
224
263
  Action: ['s3:ListBucket'],
@@ -231,6 +270,9 @@ async function applyExecRolePolicy(ctx) {
231
270
  },
232
271
  ],
233
272
  });
273
+ // Recorded either way, so a stack whose policy stopped granting staging (it
274
+ // switched to SSR) stops claiming it.
275
+ output(ctx, 'iam-exec-role')[RELEASE_STAGING_OUTPUT] = !ctx.preview && !ctx.config.ssr;
234
276
  }
235
277
  /** IAM role the running builder MicroVM assumes to read source + write the site. */
236
278
  function execRoleNode() {
@@ -390,7 +432,16 @@ function microvmImageNode() {
390
432
  },
391
433
  };
392
434
  }
393
- /** ACM certificate (us-east-1) - only present when a custom domain is configured. */
435
+ /**
436
+ * ACM certificate (us-east-1) - only present when a custom domain is configured.
437
+ *
438
+ * Production carries one certificate for every hostname the site serves (the
439
+ * primary as `DomainName`, the rest as subject alternative names), because a
440
+ * distribution takes a single viewer certificate. ACM cannot change the names
441
+ * on an issued certificate, so a changed name set requests a replacement; the
442
+ * old certificate stays attached and is retired by `retirePreviousCertificate`
443
+ * once the distribution carries the new one. Previews keep one wildcard name.
444
+ */
394
445
  function certificateNode() {
395
446
  return {
396
447
  id: 'acm-certificate',
@@ -402,6 +453,10 @@ function certificateNode() {
402
453
  const arn = output(ctx, 'acm-certificate').arn;
403
454
  if (typeof arn !== 'string')
404
455
  return false;
456
+ // A name set that no longer matches needs a replacement, which `create` does.
457
+ if (!ctx.preview && !sameSet(recordedDomains(ctx), await desiredHostnames(ctx))) {
458
+ return false;
459
+ }
405
460
  try {
406
461
  const status = await ctx.clients.acm.describeCertificate(arn);
407
462
  return status.status === 'ISSUED';
@@ -417,15 +472,15 @@ function certificateNode() {
417
472
  const domain = ctx.domain;
418
473
  if (!domain)
419
474
  throw new Error('certificate node requires a domain');
475
+ const out = output(ctx, 'acm-certificate');
420
476
  // Previews are served at <pr-id>.<domain>, so the cert must be wildcard.
421
- const certDomain = ctx.preview ? `*.${domain}` : domain;
422
- let arn = output(ctx, 'acm-certificate').arn;
423
- if (!arn) {
424
- // ACM idempotency token must match \w+ (no dashes).
425
- const token = `${ctx.config.siteName}${ctx.env}`.replace(/\W/g, '');
426
- arn = await ctx.clients.acm.requestCertificate(certDomain, token, ctx.tags);
427
- output(ctx, 'acm-certificate').arn = arn;
428
- await ctx.save();
477
+ const names = ctx.preview ? [`*.${domain}`] : await desiredHostnames(ctx);
478
+ let arn = out.arn;
479
+ if (arn && !ctx.preview && !sameSet(recordedDomains(ctx), names)) {
480
+ arn = await replaceCertificate(ctx, arn, names);
481
+ }
482
+ else if (!arn) {
483
+ arn = await requestCertificate(ctx, names);
429
484
  }
430
485
  let initial = await ctx.clients.acm.describeCertificate(arn);
431
486
  if (initial.status === 'PENDING_VALIDATION' && initial.validation.length === 0) {
@@ -454,11 +509,7 @@ function certificateNode() {
454
509
  ctx.logger.step('created ACM validation records in Route53; waiting for ISSUED…');
455
510
  }
456
511
  else {
457
- ctx.logger.warn('Add these DNS records at your registrar to validate the certificate:');
458
- for (const r of initial.validation) {
459
- ctx.logger.info(` ${r.type} ${r.name} -> ${r.value}`);
460
- }
461
- ctx.logger.step('waiting for certificate to be ISSUED (Ctrl-C to background)…');
512
+ await validateProduction(ctx, initial.validation);
462
513
  }
463
514
  }
464
515
  const settled = await pollUntil(() => ctx.clients.acm.describeCertificate(arn), (s) => s.status === 'ISSUED' || s.status === 'FAILED', { intervalMs: 15_000, timeoutMs: 30 * 60_000 });
@@ -467,12 +518,130 @@ function certificateNode() {
467
518
  }
468
519
  },
469
520
  async delete(ctx) {
470
- const arn = output(ctx, 'acm-certificate').arn;
471
- if (typeof arn === 'string')
472
- await ctx.clients.acm.deleteCertificate(arn);
521
+ const out = output(ctx, 'acm-certificate');
522
+ for (const arn of [out.arn, out.previousArn]) {
523
+ if (typeof arn === 'string')
524
+ await ctx.clients.acm.deleteCertificate(arn);
525
+ }
473
526
  },
474
527
  };
475
528
  }
529
+ /**
530
+ * Request a certificate for `names` (the first is its subject) and record it.
531
+ * `previousArn`, when given, is recorded in the same save as the new ARN, so
532
+ * state never names a superseded certificate that a failed request left
533
+ * without a replacement.
534
+ */
535
+ async function requestCertificate(ctx, names, previousArn) {
536
+ const [subject, ...alternatives] = names;
537
+ if (!subject)
538
+ throw new Error('certificate node requires a domain');
539
+ const out = output(ctx, 'acm-certificate');
540
+ // ACM idempotency token must match \w+ (no dashes) and fit 32 characters.
541
+ const token = ctx.preview
542
+ ? `${ctx.config.siteName}${ctx.env}`.replace(/\W/g, '')
543
+ : certificateToken(ctx.config.siteName, ctx.env, names);
544
+ const arn = await ctx.clients.acm.requestCertificate(subject, token, ctx.tags, alternatives);
545
+ if (previousArn !== undefined)
546
+ out.previousArn = previousArn;
547
+ out.arn = arn;
548
+ out.domains = ctx.preview ? names : [...names].sort();
549
+ await ctx.save();
550
+ return arn;
551
+ }
552
+ /**
553
+ * Swap the recorded certificate for one covering `names`. The certificate the
554
+ * distribution may still be serving is remembered as `previousArn`. When the
555
+ * recorded certificate is not the one attached, it never served and is
556
+ * dropped; when it is attached (an earlier swap finished but ACM refused to
557
+ * delete its predecessor), it becomes the one to retire and the older
558
+ * predecessor is deleted now, since nothing serves it.
559
+ */
560
+ async function replaceCertificate(ctx, current, names) {
561
+ const out = output(ctx, 'acm-certificate');
562
+ ctx.logger.info(` certificate names changed; requesting a replacement for ${names.join(', ')}`);
563
+ const earlier = typeof out.previousArn === 'string' ? out.previousArn : undefined;
564
+ if (earlier === undefined)
565
+ return requestCertificate(ctx, names, current);
566
+ const distributionId = output(ctx, 'cloudfront-distribution').id;
567
+ const live = typeof distributionId === 'string'
568
+ ? await ctx.clients.cloudfront.getDistributionAliases(distributionId)
569
+ : undefined;
570
+ const stale = live?.certificateArn === current ? earlier : current;
571
+ try {
572
+ await ctx.clients.acm.deleteCertificate(stale);
573
+ }
574
+ catch (err) {
575
+ ctx.logger.warn(`could not delete the superseded certificate ${stale}: ${String(err)}`);
576
+ }
577
+ return requestCertificate(ctx, names, stale === current ? earlier : current);
578
+ }
579
+ /**
580
+ * Production DNS validation. With `manageDns` the records whose zone is in the
581
+ * account's Route 53 are created; every other still-pending record is printed,
582
+ * grouped by hostname. A record ACM already marks validated is skipped (the
583
+ * validation CNAME is per hostname, so an apex validated by an earlier
584
+ * certificate needs nothing new).
585
+ */
586
+ async function validateProduction(ctx, records) {
587
+ const pending = new Map();
588
+ for (const r of records) {
589
+ if (r.status !== 'SUCCESS')
590
+ pending.set(`${r.type} ${r.name}`, r);
591
+ }
592
+ const unmanaged = [];
593
+ for (const r of pending.values()) {
594
+ const zone = ctx.config.manageDns
595
+ ? await findHostedZone(ctx.clients.route53, r.domain ?? r.name)
596
+ : undefined;
597
+ if (zone) {
598
+ await ctx.clients.route53.upsertRecord(zone.zoneId, {
599
+ name: r.name,
600
+ type: r.type,
601
+ value: r.value,
602
+ });
603
+ ctx.logger.info(` ${r.domain ?? r.name}: validation record created in Route 53`);
604
+ }
605
+ else {
606
+ unmanaged.push(r);
607
+ }
608
+ }
609
+ if (unmanaged.length > 0) {
610
+ ctx.logger.warn('Add these DNS records at your registrar to validate the certificate:');
611
+ for (const r of unmanaged) {
612
+ ctx.logger.info(` ${r.domain ?? r.name}: ${r.type} ${r.name} -> ${r.value}`);
613
+ }
614
+ ctx.logger.step('waiting for certificate to be ISSUED (Ctrl-C to background)…');
615
+ }
616
+ else {
617
+ ctx.logger.step(pending.size > 0
618
+ ? 'created ACM validation records in Route53; waiting for ISSUED…'
619
+ : 'no validation records pending; waiting for ISSUED…');
620
+ }
621
+ }
622
+ /**
623
+ * Delete the certificate a replacement superseded, once the distribution
624
+ * carries the current one. ACM refuses to delete a certificate CloudFront still
625
+ * references (its update is eventually consistent), so a refusal is kept in
626
+ * state and retried on the next run instead of failing the bootstrap.
627
+ */
628
+ async function retirePreviousCertificate(ctx, distributionId) {
629
+ const out = output(ctx, 'acm-certificate');
630
+ const previous = out.previousArn;
631
+ if (typeof previous !== 'string' || previous === out.arn)
632
+ return;
633
+ const live = await ctx.clients.cloudfront.getDistributionAliases(distributionId);
634
+ if (live?.certificateArn !== out.arn)
635
+ return;
636
+ try {
637
+ await ctx.clients.acm.deleteCertificate(previous);
638
+ Reflect.deleteProperty(out, 'previousArn');
639
+ ctx.logger.ok('superseded certificate deleted');
640
+ }
641
+ catch (err) {
642
+ ctx.logger.warn(`superseded certificate not deleted yet (${String(err)}); it will be retried on the next bootstrap`);
643
+ }
644
+ }
476
645
  /** CloudFront Origin Access Control granting the distribution private read on S3. */
477
646
  function oacNode() {
478
647
  return {
@@ -551,7 +720,7 @@ export function placeholderPackageZip() {
551
720
  ` res.writeHead(503, { 'content-type': 'text/plain' });\n` +
552
721
  ` res.end('blogwright: waiting for the first SSR deploy\\n');\n` +
553
722
  `}).listen(port, host);\n`;
554
- return zipSync({ 'index.js': strToU8(code) }, { level: 6, mtime: REPRODUCIBLE_ZIP_MTIME });
723
+ return createZip({ 'index.js': new TextEncoder().encode(code) }, { mtime: REPRODUCIBLE_ZIP_MTIME });
555
724
  }
556
725
  /**
557
726
  * The SSR cache policy's desired shape: cache only what the application marks
@@ -609,6 +778,264 @@ function webCachePolicyNode() {
609
778
  },
610
779
  };
611
780
  }
781
+ /** The `headers` config as the Blogwright-owned policy document. */
782
+ function responseHeadersPolicyInput(ctx, headers) {
783
+ return {
784
+ name: ctx.names.responseHeadersPolicy,
785
+ comment: `${ctx.config.siteName} ${ctx.env} response headers`,
786
+ headers,
787
+ };
788
+ }
789
+ const RESPONSE_HEADERS_POLICY = 'response-headers-policy';
790
+ /** Read without `output()`, which would record an empty entry for a policy that never existed. */
791
+ function responseHeadersPolicyRecord(ctx) {
792
+ const record = ctx.state.resources[RESPONSE_HEADERS_POLICY];
793
+ if (typeof record?.id !== 'string')
794
+ return undefined;
795
+ return {
796
+ id: record.id,
797
+ attachedTo: typeof record.attachedTo === 'string' ? record.attachedTo : undefined,
798
+ pendingDelete: record.pendingDelete === true,
799
+ };
800
+ }
801
+ function recordedResponseHeadersPolicyId(ctx) {
802
+ return responseHeadersPolicyRecord(ctx)?.id;
803
+ }
804
+ /** Replace the record whole, so a new state never inherits an earlier flag. */
805
+ function recordResponseHeadersPolicy(ctx, record) {
806
+ ctx.state.resources[RESPONSE_HEADERS_POLICY] = record;
807
+ }
808
+ function forgetResponseHeadersPolicy(ctx) {
809
+ delete ctx.state.resources[RESPONSE_HEADERS_POLICY];
810
+ }
811
+ /** The policy every cache behavior should carry: the configured, created one - or none. */
812
+ function desiredResponseHeadersPolicyId(ctx) {
813
+ return ctx.config.headers ? recordedResponseHeadersPolicyId(ctx) : undefined;
814
+ }
815
+ /**
816
+ * Record that the configured policy is on the distribution's behaviors, which
817
+ * is what lets `deploy` tell an attached policy from one an interrupted
818
+ * bootstrap created but never attached - without any distribution read.
819
+ */
820
+ function recordResponseHeadersPolicyAttached(ctx, distributionId) {
821
+ const policyId = desiredResponseHeadersPolicyId(ctx);
822
+ if (policyId !== undefined) {
823
+ recordResponseHeadersPolicy(ctx, { id: policyId, attachedTo: distributionId });
824
+ }
825
+ }
826
+ /**
827
+ * Send a create or update, translating CloudFront's refusal of an adjustable
828
+ * quota - which config load leaves alone, since an account may have raised it
829
+ * - into what to change.
830
+ */
831
+ async function withResponseHeadersQuotas(headers, send) {
832
+ try {
833
+ return await send();
834
+ }
835
+ catch (cause) {
836
+ const code = cause instanceof AwsError ? cause.code : '';
837
+ if (code === 'TooManyCustomHeadersInResponseHeadersPolicy') {
838
+ throw new Error(`config.headers.custom lists ${headers.custom.length} headers, more than this account's ` +
839
+ `CloudFront quota of custom headers per response headers policy ` +
840
+ `(${CUSTOM_RESPONSE_HEADERS_DEFAULT_QUOTA} by default): list fewer, or request a ` +
841
+ 'higher quota in Service Quotas', { cause });
842
+ }
843
+ if (code === 'TooLongCSPInResponseHeadersPolicy') {
844
+ const length = headers.security.contentSecurityPolicy?.length ?? 0;
845
+ throw new Error(`config.headers.security.contentSecurityPolicy is ${length} characters, over this ` +
846
+ `account's CloudFront quota for its length (${CONTENT_SECURITY_POLICY_DEFAULT_QUOTA} ` +
847
+ 'by default): shorten it, or request a higher quota in Service Quotas', { cause });
848
+ }
849
+ throw cause;
850
+ }
851
+ }
852
+ /**
853
+ * Bring a live policy's headers in line with the config, in place: the policy
854
+ * id - and with it every behavior's association - is unchanged, so this needs
855
+ * no distribution update. `missing` means the recorded policy is gone.
856
+ */
857
+ async function convergeResponseHeadersPolicy(ctx, id, headers) {
858
+ const desired = responseHeadersPolicyInput(ctx, headers);
859
+ const policy = await ctx.clients.cloudfront.getResponseHeadersPolicy(id);
860
+ if (!policy)
861
+ return 'missing';
862
+ if (ctx.clients.cloudfront.responseHeadersPolicyMatches(policy.config, desired)) {
863
+ ctx.logger.ok('response headers up to date');
864
+ return 'current';
865
+ }
866
+ await withResponseHeadersQuotas(headers, () => ctx.clients.cloudfront.updateResponseHeadersPolicy(id, desired, policy.etag));
867
+ ctx.logger.ok('updated the response headers policy');
868
+ return 'updated';
869
+ }
870
+ /**
871
+ * Create the policy, or adopt the one an interrupted run created under the
872
+ * same derived name but never recorded: CloudFront refuses a second policy of
873
+ * that name, and policy names are unique per account.
874
+ */
875
+ async function createOrAdoptResponseHeadersPolicy(ctx, headers) {
876
+ const input = responseHeadersPolicyInput(ctx, headers);
877
+ let id;
878
+ try {
879
+ id = await withResponseHeadersQuotas(headers, () => ctx.clients.cloudfront.createResponseHeadersPolicy(input));
880
+ }
881
+ catch (err) {
882
+ if (!(err instanceof AwsError && err.code === 'ResponseHeadersPolicyAlreadyExists'))
883
+ throw err;
884
+ const existing = await ctx.clients.cloudfront.findResponseHeadersPolicyId(input.name);
885
+ if (existing === undefined)
886
+ throw err;
887
+ recordResponseHeadersPolicy(ctx, { id: existing });
888
+ ctx.logger.ok(`adopted response headers policy ${input.name} (${existing}), left by an earlier run`);
889
+ await convergeResponseHeadersPolicy(ctx, existing, headers);
890
+ return;
891
+ }
892
+ recordResponseHeadersPolicy(ctx, { id });
893
+ }
894
+ /**
895
+ * CloudFront refused to delete a policy just detached from this site's
896
+ * distribution. Either it has not caught up with the detach - the next
897
+ * bootstrap deletes it - or another distribution uses the policy, which no
898
+ * bootstrap of this site can change: that is said once, and the policy is
899
+ * left to its other user rather than retried forever.
900
+ */
901
+ async function reportResponseHeadersPolicyInUse(ctx, policyId, distributionId) {
902
+ const others = (await ctx.clients.cloudfront.listDistributionIdsUsingResponseHeadersPolicy(policyId)).filter((id) => id !== distributionId);
903
+ if (others.length > 0) {
904
+ forgetResponseHeadersPolicy(ctx);
905
+ ctx.logger.warn(`response headers policy ${policyId} is detached from this site's distribution but is ` +
906
+ `also attached to ${others.join(', ')}, so it was not deleted. Blogwright no longer ` +
907
+ 'manages it: if those distributions do not need it, detach it from them and delete it ' +
908
+ 'in the CloudFront console');
909
+ return;
910
+ }
911
+ recordResponseHeadersPolicy(ctx, { id: policyId, pendingDelete: true });
912
+ ctx.logger.warn(`response headers policy ${policyId} is detached from the distribution, but CloudFront has ` +
913
+ 'not released it yet, so it was not deleted; the next bootstrap deletes it');
914
+ }
915
+ /**
916
+ * `headers` was removed: detach the policy from the distribution, then delete
917
+ * it. A policy already gone from AWS only leaves its record to clear.
918
+ */
919
+ async function retireResponseHeadersPolicy(ctx, policyId) {
920
+ if (!(await ctx.clients.cloudfront.getResponseHeadersPolicy(policyId))) {
921
+ forgetResponseHeadersPolicy(ctx);
922
+ ctx.logger.ok(`response headers policy ${policyId} no longer exists; cleared its record`);
923
+ return;
924
+ }
925
+ const distributionId = ctx.state.resources['cloudfront-distribution']?.id;
926
+ const ownDistribution = typeof distributionId === 'string' ? distributionId : undefined;
927
+ if (ownDistribution !== undefined) {
928
+ const detached = await ctx.clients.cloudfront.detachResponseHeadersPolicy(ownDistribution, policyId);
929
+ if (detached)
930
+ ctx.logger.ok('detached the response headers policy from the distribution');
931
+ }
932
+ try {
933
+ await ctx.clients.cloudfront.deleteResponseHeadersPolicy(policyId);
934
+ }
935
+ catch (err) {
936
+ if (err instanceof AwsError && err.code === 'ResponseHeadersPolicyInUse') {
937
+ await reportResponseHeadersPolicyInUse(ctx, policyId, ownDistribution);
938
+ return;
939
+ }
940
+ throw err;
941
+ }
942
+ forgetResponseHeadersPolicy(ctx);
943
+ ctx.logger.ok('deleted the response headers policy (config.headers was removed)');
944
+ }
945
+ /**
946
+ * The Blogwright-owned response headers policy (`<prefix>-headers`) carrying
947
+ * the `headers` config. Created before the distribution so a new distribution
948
+ * is born with it attached; a later config change updates it in place.
949
+ * In the graph whenever `headers` is configured or a policy is recorded, so
950
+ * removing the key retires the policy and `destroy` deletes it.
951
+ */
952
+ function responseHeadersPolicyNode() {
953
+ return {
954
+ id: RESPONSE_HEADERS_POLICY,
955
+ dependsOn: [],
956
+ title: 'CloudFront response headers policy',
957
+ async read(ctx) {
958
+ const id = recordedResponseHeadersPolicyId(ctx);
959
+ if (id === undefined)
960
+ return false;
961
+ // Unconfigured, there is nothing to create: `update` retires the record,
962
+ // whether or not the policy is still in AWS.
963
+ if (!ctx.config.headers)
964
+ return true;
965
+ // Existence only: changed headers are `update`'s to converge. Reporting
966
+ // the policy absent would send the graph to `create`, which CloudFront
967
+ // refuses for a taken name.
968
+ return Boolean(await ctx.clients.cloudfront.getResponseHeadersPolicy(id));
969
+ },
970
+ async create(ctx) {
971
+ const headers = ctx.config.headers;
972
+ // `read` reports a recorded policy present whenever `headers` is unset,
973
+ // and the node is only in the graph when one of the two holds.
974
+ if (!headers)
975
+ throw new Error('the response headers policy is created only from config.headers');
976
+ await createOrAdoptResponseHeadersPolicy(ctx, headers);
977
+ },
978
+ async update(ctx) {
979
+ const id = recordedResponseHeadersPolicyId(ctx);
980
+ if (id === undefined)
981
+ return;
982
+ const headers = ctx.config.headers;
983
+ if (headers)
984
+ await convergeResponseHeadersPolicy(ctx, id, headers);
985
+ else
986
+ await retireResponseHeadersPolicy(ctx, id);
987
+ },
988
+ async delete(ctx) {
989
+ const id = recordedResponseHeadersPolicyId(ctx);
990
+ if (id !== undefined)
991
+ await ctx.clients.cloudfront.deleteResponseHeadersPolicy(id);
992
+ },
993
+ };
994
+ }
995
+ /** What `deploy` says about a policy whose `headers` key was removed. */
996
+ function retiredHeadersWarning(record, bootstrap) {
997
+ if (record.pendingDelete) {
998
+ return (`config.headers was removed and response headers policy ${record.id} is already ` +
999
+ `detached from the distribution; run \`${bootstrap}\` to delete it`);
1000
+ }
1001
+ if (record.attachedTo !== undefined) {
1002
+ return (`config.headers was removed but response headers policy ${record.id} is still attached ` +
1003
+ `to the distribution; run \`${bootstrap}\` to detach and delete it`);
1004
+ }
1005
+ return `config.headers was removed; run \`${bootstrap}\` to delete response headers policy ${record.id}`;
1006
+ }
1007
+ /**
1008
+ * The deploy-time half of the `headers` reconcile: converge the recorded
1009
+ * policy's headers in place. Attaching, detaching, creating and deleting the
1010
+ * policy change the distribution, which stays a `bootstrap` action (the CI
1011
+ * deploy role cannot update the distribution), so those cases warn with the
1012
+ * command that applies them instead. Whether the policy is attached comes from
1013
+ * the record bootstrap keeps, so the deploy role needs no distribution read.
1014
+ */
1015
+ export async function reconcileResponseHeadersOnDeploy(ctx) {
1016
+ const headers = ctx.config.headers;
1017
+ const record = responseHeadersPolicyRecord(ctx);
1018
+ const bootstrap = `blogwright bootstrap ${ctx.env}`;
1019
+ if (!headers) {
1020
+ if (record)
1021
+ ctx.logger.warn(retiredHeadersWarning(record, bootstrap));
1022
+ return;
1023
+ }
1024
+ if (!record) {
1025
+ ctx.logger.warn(`config.headers is set but no response headers policy exists yet; ` +
1026
+ `run \`${bootstrap}\` to create it and attach it to the distribution`);
1027
+ return;
1028
+ }
1029
+ const distributionId = ctx.state.resources['cloudfront-distribution']?.id;
1030
+ if (record.attachedTo === undefined || record.attachedTo !== distributionId) {
1031
+ ctx.logger.warn(`response headers policy ${record.id} is not attached to the distribution, so no ` +
1032
+ `response carries its headers yet; run \`${bootstrap}\` to attach it`);
1033
+ return;
1034
+ }
1035
+ if ((await convergeResponseHeadersPolicy(ctx, record.id, headers)) === 'missing') {
1036
+ ctx.logger.warn(`response headers policy ${record.id} no longer exists; run \`${bootstrap}\` to recreate it`);
1037
+ }
1038
+ }
612
1039
  /**
613
1040
  * Merge one named statement into the bucket's policy, preserving every other
614
1041
  * statement - so `bucket-policy`'s `AllowCloudFrontRead` and
@@ -894,26 +1321,38 @@ const PREVIEW_FUNCTION_CODE = `function handler(event) {
894
1321
  return request;
895
1322
  }`;
896
1323
  /**
897
- * CloudFront Function (viewer-request) for staging/production: resolve a directory URL
898
- * to its index document (`/projects/` → `/projects/index.html`). Required because the S3
899
- * origin is the private REST endpoint (via OAC), which - unlike an S3 website endpoint -
900
- * does no index-document resolution, so `DefaultRootObject` only covers the apex. The
901
- * `/site` origin path is applied by the distribution, so this function must not add it.
1324
+ * The alias redirect this environment runs, or undefined when none applies:
1325
+ * `redirectToPrimary` needs a primary domain and at least one alias.
902
1326
  */
903
- const STATIC_ROUTER_CODE = `function handler(event) {
904
- var request = event.request;
905
- var uri = request.uri;
906
- if (uri.endsWith('/')) { uri += 'index.html'; }
907
- else if (uri.lastIndexOf('.') < uri.lastIndexOf('/')) { uri += '/index.html'; }
908
- request.uri = uri;
909
- return request;
910
- }`;
1327
+ function aliasRedirect(ctx) {
1328
+ const { aliases, redirectToPrimary } = ctx.config;
1329
+ if (!redirectToPrimary || !ctx.domain || aliases.length === 0)
1330
+ return undefined;
1331
+ return { primary: ctx.domain, aliases };
1332
+ }
911
1333
  /**
912
1334
  * CloudFront viewer-request function. Preview stacks route a subdomain to its S3 prefix
913
1335
  * (and resolve index documents); staging/production just resolve directory URLs to their
914
1336
  * index document. Both are needed because the OAC/REST S3 origin does no index resolution.
915
1337
  */
916
1338
  function routerFunctionNode(preview) {
1339
+ /**
1340
+ * The source this environment should run. Staging/production resolve
1341
+ * directory URLs and, with `redirectToPrimary`, also 301 alias hosts to the
1342
+ * primary. SSR sites run the redirect alone, since the application owns its
1343
+ * routing; without a redirect the SSR function is unattached.
1344
+ */
1345
+ function desiredCode(ctx) {
1346
+ if (preview)
1347
+ return PREVIEW_FUNCTION_CODE;
1348
+ const redirect = aliasRedirect(ctx);
1349
+ if (ctx.config.ssr && redirect)
1350
+ return ssrRouterCode(redirect);
1351
+ return staticRouterCode(redirect);
1352
+ }
1353
+ function comment(ctx) {
1354
+ return `${ctx.config.siteName} ${ctx.env} ${preview ? 'preview host router' : 'directory-index router'}`;
1355
+ }
917
1356
  return {
918
1357
  id: 'cloudfront-function',
919
1358
  dependsOn: [],
@@ -922,13 +1361,28 @@ function routerFunctionNode(preview) {
922
1361
  return typeof output(ctx, 'cloudfront-function').arn === 'string';
923
1362
  },
924
1363
  async create(ctx) {
925
- const arn = await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, preview ? PREVIEW_FUNCTION_CODE : STATIC_ROUTER_CODE, `${ctx.config.siteName} ${ctx.env} ${preview ? 'preview host router' : 'directory-index router'}`);
926
- output(ctx, 'cloudfront-function').arn = arn;
1364
+ const code = desiredCode(ctx);
1365
+ const out = output(ctx, 'cloudfront-function');
1366
+ out.arn = await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, comment(ctx));
1367
+ out.codeHash = routerCodeHash(code);
927
1368
  },
928
- async update() {
929
- // The router code is static; leave the already-published function as-is (updating +
930
- // re-publishing hits CloudFront's ETag/stage preconditions). To change the router,
931
- // delete the function (teardown) and re-bootstrap.
1369
+ async update(ctx) {
1370
+ // Preview code is static. Production code varies with the alias redirect, so
1371
+ // republish when the source differs from the one last published. A site
1372
+ // bootstrapped before the hash was recorded, and still on the plain
1373
+ // directory-index router, is left alone: republishing it would change nothing.
1374
+ if (preview)
1375
+ return;
1376
+ const code = desiredCode(ctx);
1377
+ const hash = routerCodeHash(code);
1378
+ const out = output(ctx, 'cloudfront-function');
1379
+ if (out.codeHash === hash)
1380
+ return;
1381
+ if (out.codeHash === undefined && code === staticRouterCode())
1382
+ return;
1383
+ await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, comment(ctx));
1384
+ out.codeHash = hash;
1385
+ ctx.logger.ok('CloudFront routing function republished');
932
1386
  },
933
1387
  async delete(ctx) {
934
1388
  await ctx.clients.cloudfront.deleteFunction(`${ctx.names.prefix}-router`);
@@ -974,11 +1428,15 @@ function distributionShape(ctx, mode, preview) {
974
1428
  const shared = {
975
1429
  callerReference: `${ctx.names.prefix}-${ctx.accountId}`,
976
1430
  comment: `${ctx.config.siteName} ${ctx.env}`,
977
- aliases: ctx.domain ? [preview ? `*.${ctx.domain}` : ctx.domain] : [],
1431
+ aliases: ctx.domain ? (preview ? [`*.${ctx.domain}`] : siteHostnames(ctx)) : [],
978
1432
  acmCertificateArn: ctx.domain ? String(output(ctx, 'acm-certificate').arn) : undefined,
979
1433
  };
1434
+ const responseHeadersPolicyId = desiredResponseHeadersPolicyId(ctx);
980
1435
  if (mode === 'ssr') {
981
1436
  const config = ssrConfig(ctx);
1437
+ // Aliases must redirect on every path, static or dynamic, so the function
1438
+ // is on each behavior; without a redirect nothing is attached.
1439
+ const functionArn = !preview && aliasRedirect(ctx) ? String(output(ctx, 'cloudfront-function').arn) : undefined;
982
1440
  return {
983
1441
  ...shared,
984
1442
  // The app answers `/`; a root object would only intercept it.
@@ -1000,11 +1458,16 @@ function distributionShape(ctx, mode, preview) {
1000
1458
  cachePolicyId: String(output(ctx, 'web-cache-policy').id),
1001
1459
  originRequestPolicyId: ALL_VIEWER_EXCEPT_HOST_HEADER,
1002
1460
  allowedMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'PATCH', 'DELETE'],
1461
+ ...(functionArn ? { functionArn } : {}),
1462
+ responseHeadersPolicyId,
1003
1463
  },
1464
+ // The static paths carry the headers too: they are the same site's responses.
1004
1465
  orderedBehaviors: config.staticPaths.map((pathPattern) => ({
1005
1466
  pathPattern,
1006
1467
  targetOriginId: 's3-site',
1007
1468
  cachePolicyId: CACHING_OPTIMIZED,
1469
+ ...(functionArn ? { functionArn } : {}),
1470
+ responseHeadersPolicyId,
1008
1471
  })),
1009
1472
  // No custom error responses: the application owns 404s, and error
1010
1473
  // responses are distribution-wide, so the static behaviors have none either.
@@ -1020,6 +1483,7 @@ function distributionShape(ctx, mode, preview) {
1020
1483
  // keep the default cache policy.
1021
1484
  cachePolicyId: preview ? CACHING_DISABLED : CACHING_OPTIMIZED,
1022
1485
  functionArn: String(output(ctx, 'cloudfront-function').arn),
1486
+ responseHeadersPolicyId,
1023
1487
  },
1024
1488
  // Non-preview stacks map the S3 REST origin's 403/404 (a missing key) to the
1025
1489
  // site's 404 page - or, in SPA mode, to /index.html with a 200 so
@@ -1035,8 +1499,46 @@ function distributionShape(ctx, mode, preview) {
1035
1499
  }),
1036
1500
  };
1037
1501
  }
1502
+ /**
1503
+ * Attach the configured response headers policy on a static stack, whose
1504
+ * other distribution settings stay creation-time. With no policy to attach
1505
+ * the distribution is left alone, so a policy attached by hand survives; with
1506
+ * one, a behavior carrying a hand-attached policy is refused, not overwritten
1507
+ * (`attachResponseHeadersPolicy` in core says how to resolve it).
1508
+ */
1509
+ async function attachResponseHeadersPolicy(ctx, distributionId) {
1510
+ const policyId = desiredResponseHeadersPolicyId(ctx);
1511
+ if (policyId === undefined)
1512
+ return;
1513
+ const attached = await ctx.clients.cloudfront.attachResponseHeadersPolicy(distributionId, policyId);
1514
+ recordResponseHeadersPolicyAttached(ctx, distributionId);
1515
+ ctx.logger.ok(attached
1516
+ ? 'attached the response headers policy to the distribution'
1517
+ : 'response headers policy already attached');
1518
+ }
1519
+ /**
1520
+ * A domain added (or changed) after the first bootstrap must reach the
1521
+ * existing distribution - the certificate node validates the cert, but only
1522
+ * this reconcile attaches the alias + viewer certificate.
1523
+ */
1524
+ async function reconcileStaticAliases(ctx, distributionId, preview) {
1525
+ if (!ctx.domain) {
1526
+ // Deliberately no automatic alias removal: dropping --domain from a
1527
+ // later run must not detach a live site's hostname.
1528
+ ctx.logger.ok('no domain configured - existing aliases left as-is');
1529
+ return;
1530
+ }
1531
+ // Production: the configured names plus any attached alias config does not
1532
+ // name (kept unless `--prune-aliases`); the certificate node computed the same
1533
+ // set, so the certificate covers whatever is attached.
1534
+ const aliases = preview ? [`*.${ctx.domain}`] : siteHostnames(ctx);
1535
+ const certArn = String(output(ctx, 'acm-certificate').arn);
1536
+ const changed = await ctx.clients.cloudfront.setDistributionAliases(distributionId, aliases, certArn);
1537
+ ctx.logger.ok(changed ? `aliases set to ${aliases.join(', ')}` : 'aliases up to date');
1538
+ }
1038
1539
  /** The CloudFront distribution. Preview stacks use a host-routing function + no caching. */
1039
- function distributionNode(hasDomain, preview, ssr) {
1540
+ function distributionNode(options) {
1541
+ const { hasDomain, preview, ssr, responseHeaders } = options;
1040
1542
  const dependsOn = [
1041
1543
  'bucket',
1042
1544
  'oac',
@@ -1045,6 +1547,9 @@ function distributionNode(hasDomain, preview, ssr) {
1045
1547
  // The SSR shapes read the function's endpoint domain, the `lambda` OAC and
1046
1548
  // the cache policy, so all three must exist first.
1047
1549
  ...(ssr ? ['web-function', 'web-oac', 'web-cache-policy'] : []),
1550
+ // Every shape carries the policy's id, and a removed `headers` key must
1551
+ // detach the policy before the shape stops naming it.
1552
+ ...(responseHeaders ? ['response-headers-policy'] : []),
1048
1553
  ];
1049
1554
  return {
1050
1555
  id: 'cloudfront-distribution',
@@ -1062,6 +1567,9 @@ function distributionNode(hasDomain, preview, ssr) {
1062
1567
  const comment = `${ctx.config.siteName} ${ctx.env}`;
1063
1568
  // What create and adopt agree on: enough identity to record outputs and tag.
1064
1569
  let dist;
1570
+ // An adopted orphan carries whatever shape its own run gave it, so only a
1571
+ // distribution created here is known to carry the response headers policy.
1572
+ let createdFromShape = true;
1065
1573
  try {
1066
1574
  dist = await ctx.clients.cloudfront.createDistribution(distributionShape(ctx, servingMode(ctx), preview));
1067
1575
  }
@@ -1088,7 +1596,10 @@ function distributionNode(hasDomain, preview, ssr) {
1088
1596
  throw err;
1089
1597
  ctx.logger.ok(`adopted existing distribution ${adopted.id} (created by an earlier run)`);
1090
1598
  dist = adopted;
1599
+ createdFromShape = false;
1091
1600
  }
1601
+ if (createdFromShape)
1602
+ recordResponseHeadersPolicyAttached(ctx, dist.id);
1092
1603
  const out = output(ctx, 'cloudfront-distribution');
1093
1604
  out.id = dist.id;
1094
1605
  out.arn = dist.arn;
@@ -1098,11 +1609,8 @@ function distributionNode(hasDomain, preview, ssr) {
1098
1609
  out.mode = servingMode(ctx);
1099
1610
  await ctx.clients.cloudfront.tagResource(dist.arn, ctx.tags);
1100
1611
  ctx.logger.info(` CloudFront domain: ${dist.domainName}`);
1101
- if (ctx.domain && !preview) {
1102
- // Preview stacks create the wildcard record themselves (preview-dns
1103
- // node, next in the graph); only the main site may be DNS'd elsewhere.
1104
- ctx.logger.info(` point ${ctx.domain} (CNAME/ALIAS) at ${dist.domainName}`);
1105
- }
1612
+ // Production routing records are the site-dns node's (next in the graph);
1613
+ // preview stacks create their wildcard record in the preview-dns node.
1106
1614
  },
1107
1615
  async update(ctx) {
1108
1616
  const id = output(ctx, 'cloudfront-distribution').id;
@@ -1113,45 +1621,27 @@ function distributionNode(hasDomain, preview, ssr) {
1113
1621
  const recorded = out.mode === 'ssr' || out.mode === 'static' ? out.mode : undefined;
1114
1622
  // Full reconcile on every SSR bootstrap (so a later config change converges)
1115
1623
  // and on either side of a mode switch (so the origins/behaviors move with the
1116
- // mode). A static stack that stays static keeps the alias-only update below:
1117
- // `spa` and `defaultRootObject` remain creation-time settings there.
1624
+ // mode). A static stack that stays static keeps the narrow updates below -
1625
+ // aliases and the response headers policy: `spa` and `defaultRootObject`
1626
+ // remain creation-time settings there.
1118
1627
  if (configured === 'ssr' || (recorded !== undefined && recorded !== configured)) {
1119
1628
  const changed = await ctx.clients.cloudfront.reconcileDistribution(id, distributionShape(ctx, configured, preview));
1120
1629
  out.mode = configured;
1630
+ recordResponseHeadersPolicyAttached(ctx, id);
1121
1631
  if (changed) {
1122
1632
  ctx.logger.ok(`reconciled the distribution for ${configured} serving`);
1123
- const domainName = out.domainName;
1124
- if (ctx.domain && !preview && typeof domainName === 'string') {
1125
- ctx.logger.info(` point ${ctx.domain} (CNAME/ALIAS) at ${domainName}`);
1126
- }
1127
1633
  }
1128
1634
  else {
1129
1635
  ctx.logger.ok(`distribution already matches ${configured} serving`);
1130
1636
  }
1637
+ if (!preview)
1638
+ await retirePreviousCertificate(ctx, id);
1131
1639
  return;
1132
1640
  }
1133
- // A domain added (or changed) after the first bootstrap must reach the
1134
- // existing distribution - the certificate node validates the cert, but
1135
- // only this reconcile attaches the alias + viewer certificate.
1136
- if (!ctx.domain) {
1137
- // Deliberately no automatic alias removal: dropping --domain from a
1138
- // later run must not detach a live site's hostname.
1139
- ctx.logger.ok('no domain configured - existing aliases left as-is');
1140
- return;
1141
- }
1142
- const alias = preview ? `*.${ctx.domain}` : ctx.domain;
1143
- const certArn = String(output(ctx, 'acm-certificate').arn);
1144
- const changed = await ctx.clients.cloudfront.setDistributionAliases(id, [alias], certArn);
1145
- if (changed) {
1146
- ctx.logger.ok(`attached ${alias} to the distribution`);
1147
- const domainName = output(ctx, 'cloudfront-distribution').domainName;
1148
- if (typeof domainName === 'string') {
1149
- ctx.logger.info(` point ${alias} (CNAME/ALIAS) at ${domainName}`);
1150
- }
1151
- }
1152
- else {
1153
- ctx.logger.ok('aliases up to date');
1154
- }
1641
+ await reconcileStaticAliases(ctx, id, preview);
1642
+ await attachResponseHeadersPolicy(ctx, id);
1643
+ if (!preview)
1644
+ await retirePreviousCertificate(ctx, id);
1155
1645
  },
1156
1646
  async delete(ctx) {
1157
1647
  const id = output(ctx, 'cloudfront-distribution').id;
@@ -1368,7 +1858,9 @@ function githubOidcRoleNode(preview, ssr) {
1368
1858
  const roleName = (ctx) => ctx.names.githubRole;
1369
1859
  return {
1370
1860
  id: 'gh-oidc-role',
1371
- // Production deploys invalidate the distribution, so its ARN must be in state.
1861
+ // Production deploys invalidate the distribution, so its ARN must be in state
1862
+ // (and, through the distribution's own dependency, the response headers
1863
+ // policy's id the deploy grant names).
1372
1864
  // In SSR mode the policy also names the Web Function role's ARN and the
1373
1865
  // function and endpoint ARNs the service answered with.
1374
1866
  dependsOn: preview
@@ -1449,6 +1941,28 @@ function webFunctionDeployStatements(ctx) {
1449
1941
  },
1450
1942
  ];
1451
1943
  }
1944
+ /**
1945
+ * `promote` copies a staged release's object tags into site/: reading them
1946
+ * needs s3:GetObjectTagging on the staged copy, and writing them
1947
+ * s3:PutObjectTagging on the live one - nothing wider. Only static, non-preview
1948
+ * environments stage and promote.
1949
+ */
1950
+ function promoteTaggingStatements(ctx) {
1951
+ if (ctx.preview || ctx.config.ssr)
1952
+ return [];
1953
+ return [
1954
+ {
1955
+ Effect: 'Allow',
1956
+ Action: ['s3:GetObjectTagging'],
1957
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/${STAGED_RELEASES_PREFIX}*`,
1958
+ },
1959
+ {
1960
+ Effect: 'Allow',
1961
+ Action: ['s3:PutObjectTagging'],
1962
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/site/*`,
1963
+ },
1964
+ ];
1965
+ }
1452
1966
  /** The deploy role's inline policy statements (exported for tests). */
1453
1967
  export function oidcRolePolicyStatements(ctx) {
1454
1968
  const statements = [
@@ -1464,6 +1978,7 @@ export function oidcRolePolicyStatements(ctx) {
1464
1978
  ],
1465
1979
  Resource: `arn:aws:s3:::${ctx.names.bucket}/*`,
1466
1980
  },
1981
+ ...promoteTaggingStatements(ctx),
1467
1982
  { Effect: 'Allow', Action: ['s3:ListBucket'], Resource: `arn:aws:s3:::${ctx.names.bucket}` },
1468
1983
  {
1469
1984
  Effect: 'Allow',
@@ -1507,6 +2022,16 @@ export function oidcRolePolicyStatements(ctx) {
1507
2022
  Action: ['cloudfront:CreateInvalidation'],
1508
2023
  Resource: String(output(ctx, 'cloudfront-distribution').arn),
1509
2024
  });
2025
+ // Deploys converge the response headers in place - this one policy only,
2026
+ // never the distribution (`reconcileResponseHeadersOnDeploy`).
2027
+ const policyId = recordedResponseHeadersPolicyId(ctx);
2028
+ if (policyId !== undefined) {
2029
+ statements.push({
2030
+ Effect: 'Allow',
2031
+ Action: ['cloudfront:GetResponseHeadersPolicy', 'cloudfront:UpdateResponseHeadersPolicy'],
2032
+ Resource: `arn:aws:cloudfront::${ctx.accountId}:response-headers-policy/${policyId}`,
2033
+ });
2034
+ }
1510
2035
  }
1511
2036
  return statements;
1512
2037
  }
@@ -1620,6 +2145,121 @@ function previewDnsNode() {
1620
2145
  },
1621
2146
  };
1622
2147
  }
2148
+ /**
2149
+ * Routing for the production hostnames: the records that point each name at
2150
+ * the distribution. With `manageDns`, hosts whose hosted zone is in the
2151
+ * account's Route 53 get A and AAAA alias records (recorded in state so a
2152
+ * teardown or a prune removes them); every other host is printed, as an
2153
+ * apex or a sub-domain according to what DNS says its zone is. Guidance is
2154
+ * printed when it changes, not on every run.
2155
+ */
2156
+ function siteDnsNode() {
2157
+ const TYPES = ['A', 'AAAA'];
2158
+ async function reconcile(ctx) {
2159
+ const target = output(ctx, 'cloudfront-distribution').domainName;
2160
+ if (typeof target !== 'string')
2161
+ return;
2162
+ const out = output(ctx, 'site-dns');
2163
+ const hosts = siteHostnames(ctx);
2164
+ const previousHosts = Array.isArray(out.hosts) ? out.hosts : [];
2165
+ const previousZones = Array.isArray(out.zoneIds) ? out.zoneIds : [];
2166
+ const managedHosts = [];
2167
+ const managedZones = [];
2168
+ const guidance = [];
2169
+ for (const host of hosts) {
2170
+ const zone = ctx.config.manageDns
2171
+ ? await findHostedZone(ctx.clients.route53, host)
2172
+ : undefined;
2173
+ if (zone) {
2174
+ try {
2175
+ for (const type of TYPES) {
2176
+ await ctx.clients.route53.upsertRecord(zone.zoneId, {
2177
+ name: host,
2178
+ type,
2179
+ value: target,
2180
+ aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
2181
+ });
2182
+ }
2183
+ managedHosts.push(host);
2184
+ managedZones.push(zone.zoneId);
2185
+ ctx.logger.info(` ${host} -> ${target} (Route 53 alias)`);
2186
+ continue;
2187
+ }
2188
+ catch (err) {
2189
+ // A CNAME already at the name is the usual cause; fall back to guidance.
2190
+ ctx.logger.warn(`could not write Route 53 records for ${host}: ${String(err)}`);
2191
+ }
2192
+ }
2193
+ guidance.push(await routingGuidance(ctx.ports.dns, host, target));
2194
+ }
2195
+ // Records this node wrote for a host that is no longer served.
2196
+ for (const [i, host] of previousHosts.entries()) {
2197
+ const zoneId = previousZones[i];
2198
+ if (hosts.includes(host) || zoneId === undefined)
2199
+ continue;
2200
+ for (const type of TYPES) {
2201
+ await ctx.clients.route53.deleteRecord(zoneId, {
2202
+ name: host,
2203
+ type,
2204
+ value: target,
2205
+ aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
2206
+ });
2207
+ }
2208
+ }
2209
+ // A host still served but not written this run (manageDns turned off, or a
2210
+ // write that fell back to guidance) keeps its record of what was written,
2211
+ // so a later prune or teardown still removes the records.
2212
+ for (const [i, host] of previousHosts.entries()) {
2213
+ const zoneId = previousZones[i];
2214
+ if (zoneId === undefined || !hosts.includes(host) || managedHosts.includes(host))
2215
+ continue;
2216
+ managedHosts.push(host);
2217
+ managedZones.push(zoneId);
2218
+ }
2219
+ out.hosts = managedHosts;
2220
+ out.zoneIds = managedZones;
2221
+ const signature = createHash('sha256')
2222
+ .update([target, ...hosts, ...guidance].join('\n'))
2223
+ .digest('hex');
2224
+ if (guidance.length > 0 && out.signature !== signature) {
2225
+ ctx.logger.warn(`Point these hostnames at ${target}:`);
2226
+ for (const line of guidance)
2227
+ ctx.logger.info(` ${line}`);
2228
+ }
2229
+ out.signature = signature;
2230
+ }
2231
+ return {
2232
+ id: 'site-dns',
2233
+ dependsOn: ['cloudfront-distribution'],
2234
+ title: 'Site DNS routing',
2235
+ async read(ctx) {
2236
+ return typeof output(ctx, 'site-dns').signature === 'string';
2237
+ },
2238
+ create: reconcile,
2239
+ update: reconcile,
2240
+ async delete(ctx) {
2241
+ const out = output(ctx, 'site-dns');
2242
+ const target = output(ctx, 'cloudfront-distribution').domainName;
2243
+ const hosts = Array.isArray(out.hosts) ? out.hosts : [];
2244
+ const zones = Array.isArray(out.zoneIds) ? out.zoneIds : [];
2245
+ if (typeof target !== 'string')
2246
+ return;
2247
+ for (const [i, host] of hosts.entries()) {
2248
+ const zoneId = zones[i];
2249
+ if (zoneId === undefined)
2250
+ continue;
2251
+ for (const type of TYPES) {
2252
+ await ctx.clients.route53.deleteRecord(zoneId, {
2253
+ name: host,
2254
+ type,
2255
+ value: target,
2256
+ aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
2257
+ });
2258
+ }
2259
+ }
2260
+ },
2261
+ };
2262
+ }
1623
2263
  /** Build the full node set for the current context (production or preview stack). */
1624
2264
  export function buildNodes(ctx) {
1625
2265
  const hasDomain = Boolean(ctx.domain);
@@ -1636,6 +2276,9 @@ export function buildNodes(ctx) {
1636
2276
  oacNode(),
1637
2277
  routerFunctionNode(ctx.preview),
1638
2278
  ];
2279
+ const responseHeaders = ctx.config.headers !== undefined || recordedResponseHeadersPolicyId(ctx) !== undefined;
2280
+ if (responseHeaders)
2281
+ nodes.push(responseHeadersPolicyNode());
1639
2282
  if (ssr) {
1640
2283
  nodes.push(
1641
2284
  // The `.local` companion first: Lambda writes in-Region logs there before
@@ -1643,11 +2286,13 @@ export function buildNodes(ctx) {
1643
2286
  // retention and outside the graph.
1644
2287
  logGroupNode('web-local-log-group', 'Web Function local log group', (c) => c.names.webLocalLogGroup, (c) => c.config.retention.webFunctionDays), logGroupNode('web-log-group', 'Web Function log group', (c) => c.names.webLogGroup, (c) => c.config.retention.webFunctionDays), webRoleNode(), webOacNode(), webCachePolicyNode(), webCodeBucketPolicyNode(), webFunctionNode());
1645
2288
  }
1646
- nodes.push(distributionNode(hasDomain, ctx.preview, ssr), logDeliveryNode(), bucketPolicyNode());
2289
+ nodes.push(distributionNode({ hasDomain, preview: ctx.preview, ssr, responseHeaders }), logDeliveryNode(), bucketPolicyNode());
1647
2290
  if (ssr)
1648
2291
  nodes.push(webFunctionPolicyNode());
1649
2292
  if (hasDomain)
1650
2293
  nodes.push(certificateNode());
2294
+ if (hasDomain && !ctx.preview)
2295
+ nodes.push(siteDnsNode());
1651
2296
  if (ctx.preview) {
1652
2297
  nodes.push(previewDnsNode(), githubOidcRoleNode(true, false));
1653
2298
  }