blogwright 0.4.0-beta.5 → 0.5.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 (50) 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/process-aws-login.d.ts +19 -0
  5. package/dist/adapters/process-aws-login.js +28 -0
  6. package/dist/agent-package.js +2 -3
  7. package/dist/artifacts.d.ts +73 -0
  8. package/dist/artifacts.js +218 -0
  9. package/dist/aws-session.d.ts +118 -0
  10. package/dist/aws-session.js +360 -0
  11. package/dist/bin.js +6 -2
  12. package/dist/cache-control.d.ts +66 -0
  13. package/dist/cache-control.js +176 -0
  14. package/dist/cli.d.ts +22 -3
  15. package/dist/cli.js +122 -31
  16. package/dist/commands.d.ts +41 -9
  17. package/dist/commands.js +135 -126
  18. package/dist/context.d.ts +27 -5
  19. package/dist/context.js +59 -19
  20. package/dist/deploy.d.ts +78 -6
  21. package/dist/deploy.js +136 -52
  22. package/dist/init.d.ts +14 -2
  23. package/dist/init.js +145 -4
  24. package/dist/known-commands.d.ts +11 -9
  25. package/dist/known-commands.js +15 -9
  26. package/dist/live-release.d.ts +78 -0
  27. package/dist/live-release.js +159 -0
  28. package/dist/lock.d.ts +50 -0
  29. package/dist/lock.js +120 -0
  30. package/dist/nodes.d.ts +18 -0
  31. package/dist/nodes.js +405 -30
  32. package/dist/plugin-commands.d.ts +21 -0
  33. package/dist/plugin-commands.js +54 -3
  34. package/dist/plugins.d.ts +11 -9
  35. package/dist/plugins.js +29 -16
  36. package/dist/ports.d.ts +22 -1
  37. package/dist/releases.d.ts +54 -0
  38. package/dist/releases.js +527 -0
  39. package/dist/render.d.ts +18 -1
  40. package/dist/render.js +38 -6
  41. package/dist/repo.js +2 -3
  42. package/dist/rkey.d.ts +4 -3
  43. package/dist/rkey.js +4 -3
  44. package/dist/serving.d.ts +28 -0
  45. package/dist/serving.js +47 -0
  46. package/dist/verify.d.ts +45 -0
  47. package/dist/verify.js +183 -0
  48. package/dist/whoami.d.ts +23 -0
  49. package/dist/whoami.js +88 -0
  50. package/package.json +8 -8
package/dist/nodes.js CHANGED
@@ -1,5 +1,4 @@
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 { 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
2
  import { packageAndUploadAgent } from './agent-package.js';
4
3
  /** Lambda-managed MicroVM base image (Amazon Linux 2023) for the primary region. */
5
4
  function microvmBaseImageArn(region) {
@@ -137,6 +136,32 @@ function webArtifactWriteStatements(ctx) {
137
136
  },
138
137
  ];
139
138
  }
139
+ /**
140
+ * The agent records each static build's artifact manifest at its own
141
+ * `build/artifacts/<hash>/<buildId>.json`. The grant stops at that depth on
142
+ * purpose: a revision's original record, `build/artifacts/<hash>.json`, is
143
+ * written once by the CLI and is out of the builder's reach. `blogwright
144
+ * stage` has the agent publish a release under `releases/<hash>/` instead of
145
+ * `site/` - tagged like the site, and re-staging a hash deletes what the new
146
+ * build no longer contains. The shared preview stack and SSR environments do
147
+ * neither.
148
+ */
149
+ function releaseWriteStatements(ctx) {
150
+ if (ctx.preview || ctx.config.ssr)
151
+ return [];
152
+ return [
153
+ {
154
+ Effect: 'Allow',
155
+ Action: ['s3:PutObject'],
156
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/build/artifacts/*/*`,
157
+ },
158
+ {
159
+ Effect: 'Allow',
160
+ Action: ['s3:PutObject', 's3:PutObjectTagging', 's3:DeleteObject'],
161
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/${STAGED_RELEASES_PREFIX}*`,
162
+ },
163
+ ];
164
+ }
140
165
  /** Apply the build role's inline policy (idempotent - used by create + update). */
141
166
  async function applyBuildRolePolicy(ctx) {
142
167
  // The build role is BOTH the image-build role AND the MicroVM's ambient runtime
@@ -162,6 +187,7 @@ async function applyBuildRolePolicy(ctx) {
162
187
  Resource: `arn:aws:s3:::${ctx.names.bucket}/build/changed/*`,
163
188
  },
164
189
  ...webArtifactWriteStatements(ctx),
190
+ ...releaseWriteStatements(ctx),
165
191
  {
166
192
  Effect: 'Allow',
167
193
  Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
@@ -194,6 +220,15 @@ function buildRoleNode() {
194
220
  },
195
221
  };
196
222
  }
223
+ /**
224
+ * Recorded on the exec role's outputs whenever its policy is applied - true
225
+ * when that policy grants release staging - so `stage` can refuse up front on
226
+ * a stack bootstrapped before it existed rather than fail inside the MicroVM
227
+ * after a full build. A flag rather than a read of the policy itself: the CI
228
+ * deploy role that runs `stage` has no IAM read access, and granting it
229
+ * `iam:GetRolePolicy` to check one statement would widen it for little gain.
230
+ */
231
+ export const RELEASE_STAGING_OUTPUT = 'releaseStaging';
197
232
  async function applyExecRolePolicy(ctx) {
198
233
  await ctx.clients.iam.putRolePolicy(ctx.names.execRole, 'exec', {
199
234
  Version: '2012-10-17',
@@ -219,6 +254,7 @@ async function applyExecRolePolicy(ctx) {
219
254
  ],
220
255
  },
221
256
  ...webArtifactWriteStatements(ctx),
257
+ ...releaseWriteStatements(ctx),
222
258
  {
223
259
  Effect: 'Allow',
224
260
  Action: ['s3:ListBucket'],
@@ -231,6 +267,9 @@ async function applyExecRolePolicy(ctx) {
231
267
  },
232
268
  ],
233
269
  });
270
+ // Recorded either way, so a stack whose policy stopped granting staging (it
271
+ // switched to SSR) stops claiming it.
272
+ output(ctx, 'iam-exec-role')[RELEASE_STAGING_OUTPUT] = !ctx.preview && !ctx.config.ssr;
234
273
  }
235
274
  /** IAM role the running builder MicroVM assumes to read source + write the site. */
236
275
  function execRoleNode() {
@@ -551,7 +590,7 @@ export function placeholderPackageZip() {
551
590
  ` res.writeHead(503, { 'content-type': 'text/plain' });\n` +
552
591
  ` res.end('blogwright: waiting for the first SSR deploy\\n');\n` +
553
592
  `}).listen(port, host);\n`;
554
- return zipSync({ 'index.js': strToU8(code) }, { level: 6, mtime: REPRODUCIBLE_ZIP_MTIME });
593
+ return createZip({ 'index.js': new TextEncoder().encode(code) }, { mtime: REPRODUCIBLE_ZIP_MTIME });
555
594
  }
556
595
  /**
557
596
  * The SSR cache policy's desired shape: cache only what the application marks
@@ -609,6 +648,264 @@ function webCachePolicyNode() {
609
648
  },
610
649
  };
611
650
  }
651
+ /** The `headers` config as the Blogwright-owned policy document. */
652
+ function responseHeadersPolicyInput(ctx, headers) {
653
+ return {
654
+ name: ctx.names.responseHeadersPolicy,
655
+ comment: `${ctx.config.siteName} ${ctx.env} response headers`,
656
+ headers,
657
+ };
658
+ }
659
+ const RESPONSE_HEADERS_POLICY = 'response-headers-policy';
660
+ /** Read without `output()`, which would record an empty entry for a policy that never existed. */
661
+ function responseHeadersPolicyRecord(ctx) {
662
+ const record = ctx.state.resources[RESPONSE_HEADERS_POLICY];
663
+ if (typeof record?.id !== 'string')
664
+ return undefined;
665
+ return {
666
+ id: record.id,
667
+ attachedTo: typeof record.attachedTo === 'string' ? record.attachedTo : undefined,
668
+ pendingDelete: record.pendingDelete === true,
669
+ };
670
+ }
671
+ function recordedResponseHeadersPolicyId(ctx) {
672
+ return responseHeadersPolicyRecord(ctx)?.id;
673
+ }
674
+ /** Replace the record whole, so a new state never inherits an earlier flag. */
675
+ function recordResponseHeadersPolicy(ctx, record) {
676
+ ctx.state.resources[RESPONSE_HEADERS_POLICY] = record;
677
+ }
678
+ function forgetResponseHeadersPolicy(ctx) {
679
+ delete ctx.state.resources[RESPONSE_HEADERS_POLICY];
680
+ }
681
+ /** The policy every cache behavior should carry: the configured, created one - or none. */
682
+ function desiredResponseHeadersPolicyId(ctx) {
683
+ return ctx.config.headers ? recordedResponseHeadersPolicyId(ctx) : undefined;
684
+ }
685
+ /**
686
+ * Record that the configured policy is on the distribution's behaviors, which
687
+ * is what lets `deploy` tell an attached policy from one an interrupted
688
+ * bootstrap created but never attached - without any distribution read.
689
+ */
690
+ function recordResponseHeadersPolicyAttached(ctx, distributionId) {
691
+ const policyId = desiredResponseHeadersPolicyId(ctx);
692
+ if (policyId !== undefined) {
693
+ recordResponseHeadersPolicy(ctx, { id: policyId, attachedTo: distributionId });
694
+ }
695
+ }
696
+ /**
697
+ * Send a create or update, translating CloudFront's refusal of an adjustable
698
+ * quota - which config load leaves alone, since an account may have raised it
699
+ * - into what to change.
700
+ */
701
+ async function withResponseHeadersQuotas(headers, send) {
702
+ try {
703
+ return await send();
704
+ }
705
+ catch (cause) {
706
+ const code = cause instanceof AwsError ? cause.code : '';
707
+ if (code === 'TooManyCustomHeadersInResponseHeadersPolicy') {
708
+ throw new Error(`config.headers.custom lists ${headers.custom.length} headers, more than this account's ` +
709
+ `CloudFront quota of custom headers per response headers policy ` +
710
+ `(${CUSTOM_RESPONSE_HEADERS_DEFAULT_QUOTA} by default): list fewer, or request a ` +
711
+ 'higher quota in Service Quotas', { cause });
712
+ }
713
+ if (code === 'TooLongCSPInResponseHeadersPolicy') {
714
+ const length = headers.security.contentSecurityPolicy?.length ?? 0;
715
+ throw new Error(`config.headers.security.contentSecurityPolicy is ${length} characters, over this ` +
716
+ `account's CloudFront quota for its length (${CONTENT_SECURITY_POLICY_DEFAULT_QUOTA} ` +
717
+ 'by default): shorten it, or request a higher quota in Service Quotas', { cause });
718
+ }
719
+ throw cause;
720
+ }
721
+ }
722
+ /**
723
+ * Bring a live policy's headers in line with the config, in place: the policy
724
+ * id - and with it every behavior's association - is unchanged, so this needs
725
+ * no distribution update. `missing` means the recorded policy is gone.
726
+ */
727
+ async function convergeResponseHeadersPolicy(ctx, id, headers) {
728
+ const desired = responseHeadersPolicyInput(ctx, headers);
729
+ const policy = await ctx.clients.cloudfront.getResponseHeadersPolicy(id);
730
+ if (!policy)
731
+ return 'missing';
732
+ if (ctx.clients.cloudfront.responseHeadersPolicyMatches(policy.config, desired)) {
733
+ ctx.logger.ok('response headers up to date');
734
+ return 'current';
735
+ }
736
+ await withResponseHeadersQuotas(headers, () => ctx.clients.cloudfront.updateResponseHeadersPolicy(id, desired, policy.etag));
737
+ ctx.logger.ok('updated the response headers policy');
738
+ return 'updated';
739
+ }
740
+ /**
741
+ * Create the policy, or adopt the one an interrupted run created under the
742
+ * same derived name but never recorded: CloudFront refuses a second policy of
743
+ * that name, and policy names are unique per account.
744
+ */
745
+ async function createOrAdoptResponseHeadersPolicy(ctx, headers) {
746
+ const input = responseHeadersPolicyInput(ctx, headers);
747
+ let id;
748
+ try {
749
+ id = await withResponseHeadersQuotas(headers, () => ctx.clients.cloudfront.createResponseHeadersPolicy(input));
750
+ }
751
+ catch (err) {
752
+ if (!(err instanceof AwsError && err.code === 'ResponseHeadersPolicyAlreadyExists'))
753
+ throw err;
754
+ const existing = await ctx.clients.cloudfront.findResponseHeadersPolicyId(input.name);
755
+ if (existing === undefined)
756
+ throw err;
757
+ recordResponseHeadersPolicy(ctx, { id: existing });
758
+ ctx.logger.ok(`adopted response headers policy ${input.name} (${existing}), left by an earlier run`);
759
+ await convergeResponseHeadersPolicy(ctx, existing, headers);
760
+ return;
761
+ }
762
+ recordResponseHeadersPolicy(ctx, { id });
763
+ }
764
+ /**
765
+ * CloudFront refused to delete a policy just detached from this site's
766
+ * distribution. Either it has not caught up with the detach - the next
767
+ * bootstrap deletes it - or another distribution uses the policy, which no
768
+ * bootstrap of this site can change: that is said once, and the policy is
769
+ * left to its other user rather than retried forever.
770
+ */
771
+ async function reportResponseHeadersPolicyInUse(ctx, policyId, distributionId) {
772
+ const others = (await ctx.clients.cloudfront.listDistributionIdsUsingResponseHeadersPolicy(policyId)).filter((id) => id !== distributionId);
773
+ if (others.length > 0) {
774
+ forgetResponseHeadersPolicy(ctx);
775
+ ctx.logger.warn(`response headers policy ${policyId} is detached from this site's distribution but is ` +
776
+ `also attached to ${others.join(', ')}, so it was not deleted. Blogwright no longer ` +
777
+ 'manages it: if those distributions do not need it, detach it from them and delete it ' +
778
+ 'in the CloudFront console');
779
+ return;
780
+ }
781
+ recordResponseHeadersPolicy(ctx, { id: policyId, pendingDelete: true });
782
+ ctx.logger.warn(`response headers policy ${policyId} is detached from the distribution, but CloudFront has ` +
783
+ 'not released it yet, so it was not deleted; the next bootstrap deletes it');
784
+ }
785
+ /**
786
+ * `headers` was removed: detach the policy from the distribution, then delete
787
+ * it. A policy already gone from AWS only leaves its record to clear.
788
+ */
789
+ async function retireResponseHeadersPolicy(ctx, policyId) {
790
+ if (!(await ctx.clients.cloudfront.getResponseHeadersPolicy(policyId))) {
791
+ forgetResponseHeadersPolicy(ctx);
792
+ ctx.logger.ok(`response headers policy ${policyId} no longer exists; cleared its record`);
793
+ return;
794
+ }
795
+ const distributionId = ctx.state.resources['cloudfront-distribution']?.id;
796
+ const ownDistribution = typeof distributionId === 'string' ? distributionId : undefined;
797
+ if (ownDistribution !== undefined) {
798
+ const detached = await ctx.clients.cloudfront.detachResponseHeadersPolicy(ownDistribution, policyId);
799
+ if (detached)
800
+ ctx.logger.ok('detached the response headers policy from the distribution');
801
+ }
802
+ try {
803
+ await ctx.clients.cloudfront.deleteResponseHeadersPolicy(policyId);
804
+ }
805
+ catch (err) {
806
+ if (err instanceof AwsError && err.code === 'ResponseHeadersPolicyInUse') {
807
+ await reportResponseHeadersPolicyInUse(ctx, policyId, ownDistribution);
808
+ return;
809
+ }
810
+ throw err;
811
+ }
812
+ forgetResponseHeadersPolicy(ctx);
813
+ ctx.logger.ok('deleted the response headers policy (config.headers was removed)');
814
+ }
815
+ /**
816
+ * The Blogwright-owned response headers policy (`<prefix>-headers`) carrying
817
+ * the `headers` config. Created before the distribution so a new distribution
818
+ * is born with it attached; a later config change updates it in place.
819
+ * In the graph whenever `headers` is configured or a policy is recorded, so
820
+ * removing the key retires the policy and `destroy` deletes it.
821
+ */
822
+ function responseHeadersPolicyNode() {
823
+ return {
824
+ id: RESPONSE_HEADERS_POLICY,
825
+ dependsOn: [],
826
+ title: 'CloudFront response headers policy',
827
+ async read(ctx) {
828
+ const id = recordedResponseHeadersPolicyId(ctx);
829
+ if (id === undefined)
830
+ return false;
831
+ // Unconfigured, there is nothing to create: `update` retires the record,
832
+ // whether or not the policy is still in AWS.
833
+ if (!ctx.config.headers)
834
+ return true;
835
+ // Existence only: changed headers are `update`'s to converge. Reporting
836
+ // the policy absent would send the graph to `create`, which CloudFront
837
+ // refuses for a taken name.
838
+ return Boolean(await ctx.clients.cloudfront.getResponseHeadersPolicy(id));
839
+ },
840
+ async create(ctx) {
841
+ const headers = ctx.config.headers;
842
+ // `read` reports a recorded policy present whenever `headers` is unset,
843
+ // and the node is only in the graph when one of the two holds.
844
+ if (!headers)
845
+ throw new Error('the response headers policy is created only from config.headers');
846
+ await createOrAdoptResponseHeadersPolicy(ctx, headers);
847
+ },
848
+ async update(ctx) {
849
+ const id = recordedResponseHeadersPolicyId(ctx);
850
+ if (id === undefined)
851
+ return;
852
+ const headers = ctx.config.headers;
853
+ if (headers)
854
+ await convergeResponseHeadersPolicy(ctx, id, headers);
855
+ else
856
+ await retireResponseHeadersPolicy(ctx, id);
857
+ },
858
+ async delete(ctx) {
859
+ const id = recordedResponseHeadersPolicyId(ctx);
860
+ if (id !== undefined)
861
+ await ctx.clients.cloudfront.deleteResponseHeadersPolicy(id);
862
+ },
863
+ };
864
+ }
865
+ /** What `deploy` says about a policy whose `headers` key was removed. */
866
+ function retiredHeadersWarning(record, bootstrap) {
867
+ if (record.pendingDelete) {
868
+ return (`config.headers was removed and response headers policy ${record.id} is already ` +
869
+ `detached from the distribution; run \`${bootstrap}\` to delete it`);
870
+ }
871
+ if (record.attachedTo !== undefined) {
872
+ return (`config.headers was removed but response headers policy ${record.id} is still attached ` +
873
+ `to the distribution; run \`${bootstrap}\` to detach and delete it`);
874
+ }
875
+ return `config.headers was removed; run \`${bootstrap}\` to delete response headers policy ${record.id}`;
876
+ }
877
+ /**
878
+ * The deploy-time half of the `headers` reconcile: converge the recorded
879
+ * policy's headers in place. Attaching, detaching, creating and deleting the
880
+ * policy change the distribution, which stays a `bootstrap` action (the CI
881
+ * deploy role cannot update the distribution), so those cases warn with the
882
+ * command that applies them instead. Whether the policy is attached comes from
883
+ * the record bootstrap keeps, so the deploy role needs no distribution read.
884
+ */
885
+ export async function reconcileResponseHeadersOnDeploy(ctx) {
886
+ const headers = ctx.config.headers;
887
+ const record = responseHeadersPolicyRecord(ctx);
888
+ const bootstrap = `blogwright bootstrap ${ctx.env}`;
889
+ if (!headers) {
890
+ if (record)
891
+ ctx.logger.warn(retiredHeadersWarning(record, bootstrap));
892
+ return;
893
+ }
894
+ if (!record) {
895
+ ctx.logger.warn(`config.headers is set but no response headers policy exists yet; ` +
896
+ `run \`${bootstrap}\` to create it and attach it to the distribution`);
897
+ return;
898
+ }
899
+ const distributionId = ctx.state.resources['cloudfront-distribution']?.id;
900
+ if (record.attachedTo === undefined || record.attachedTo !== distributionId) {
901
+ ctx.logger.warn(`response headers policy ${record.id} is not attached to the distribution, so no ` +
902
+ `response carries its headers yet; run \`${bootstrap}\` to attach it`);
903
+ return;
904
+ }
905
+ if ((await convergeResponseHeadersPolicy(ctx, record.id, headers)) === 'missing') {
906
+ ctx.logger.warn(`response headers policy ${record.id} no longer exists; run \`${bootstrap}\` to recreate it`);
907
+ }
908
+ }
612
909
  /**
613
910
  * Merge one named statement into the bucket's policy, preserving every other
614
911
  * statement - so `bucket-policy`'s `AllowCloudFrontRead` and
@@ -977,6 +1274,7 @@ function distributionShape(ctx, mode, preview) {
977
1274
  aliases: ctx.domain ? [preview ? `*.${ctx.domain}` : ctx.domain] : [],
978
1275
  acmCertificateArn: ctx.domain ? String(output(ctx, 'acm-certificate').arn) : undefined,
979
1276
  };
1277
+ const responseHeadersPolicyId = desiredResponseHeadersPolicyId(ctx);
980
1278
  if (mode === 'ssr') {
981
1279
  const config = ssrConfig(ctx);
982
1280
  return {
@@ -1000,11 +1298,14 @@ function distributionShape(ctx, mode, preview) {
1000
1298
  cachePolicyId: String(output(ctx, 'web-cache-policy').id),
1001
1299
  originRequestPolicyId: ALL_VIEWER_EXCEPT_HOST_HEADER,
1002
1300
  allowedMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'PATCH', 'DELETE'],
1301
+ responseHeadersPolicyId,
1003
1302
  },
1303
+ // The static paths carry the headers too: they are the same site's responses.
1004
1304
  orderedBehaviors: config.staticPaths.map((pathPattern) => ({
1005
1305
  pathPattern,
1006
1306
  targetOriginId: 's3-site',
1007
1307
  cachePolicyId: CACHING_OPTIMIZED,
1308
+ responseHeadersPolicyId,
1008
1309
  })),
1009
1310
  // No custom error responses: the application owns 404s, and error
1010
1311
  // responses are distribution-wide, so the static behaviors have none either.
@@ -1020,6 +1321,7 @@ function distributionShape(ctx, mode, preview) {
1020
1321
  // keep the default cache policy.
1021
1322
  cachePolicyId: preview ? CACHING_DISABLED : CACHING_OPTIMIZED,
1022
1323
  functionArn: String(output(ctx, 'cloudfront-function').arn),
1324
+ responseHeadersPolicyId,
1023
1325
  },
1024
1326
  // Non-preview stacks map the S3 REST origin's 403/404 (a missing key) to the
1025
1327
  // site's 404 page - or, in SPA mode, to /index.html with a 200 so
@@ -1035,8 +1337,52 @@ function distributionShape(ctx, mode, preview) {
1035
1337
  }),
1036
1338
  };
1037
1339
  }
1340
+ /**
1341
+ * Attach the configured response headers policy on a static stack, whose
1342
+ * other distribution settings stay creation-time. With no policy to attach
1343
+ * the distribution is left alone, so a policy attached by hand survives; with
1344
+ * one, a behavior carrying a hand-attached policy is refused, not overwritten
1345
+ * (`attachResponseHeadersPolicy` in core says how to resolve it).
1346
+ */
1347
+ async function attachResponseHeadersPolicy(ctx, distributionId) {
1348
+ const policyId = desiredResponseHeadersPolicyId(ctx);
1349
+ if (policyId === undefined)
1350
+ return;
1351
+ const attached = await ctx.clients.cloudfront.attachResponseHeadersPolicy(distributionId, policyId);
1352
+ recordResponseHeadersPolicyAttached(ctx, distributionId);
1353
+ ctx.logger.ok(attached
1354
+ ? 'attached the response headers policy to the distribution'
1355
+ : 'response headers policy already attached');
1356
+ }
1357
+ /**
1358
+ * A domain added (or changed) after the first bootstrap must reach the
1359
+ * existing distribution - the certificate node validates the cert, but only
1360
+ * this reconcile attaches the alias + viewer certificate.
1361
+ */
1362
+ async function reconcileStaticAliases(ctx, distributionId, preview) {
1363
+ if (!ctx.domain) {
1364
+ // Deliberately no automatic alias removal: dropping --domain from a
1365
+ // later run must not detach a live site's hostname.
1366
+ ctx.logger.ok('no domain configured - existing aliases left as-is');
1367
+ return;
1368
+ }
1369
+ const alias = preview ? `*.${ctx.domain}` : ctx.domain;
1370
+ const certArn = String(output(ctx, 'acm-certificate').arn);
1371
+ const changed = await ctx.clients.cloudfront.setDistributionAliases(distributionId, [alias], certArn);
1372
+ if (changed) {
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
+ }
1382
+ }
1038
1383
  /** The CloudFront distribution. Preview stacks use a host-routing function + no caching. */
1039
- function distributionNode(hasDomain, preview, ssr) {
1384
+ function distributionNode(options) {
1385
+ const { hasDomain, preview, ssr, responseHeaders } = options;
1040
1386
  const dependsOn = [
1041
1387
  'bucket',
1042
1388
  'oac',
@@ -1045,6 +1391,9 @@ function distributionNode(hasDomain, preview, ssr) {
1045
1391
  // The SSR shapes read the function's endpoint domain, the `lambda` OAC and
1046
1392
  // the cache policy, so all three must exist first.
1047
1393
  ...(ssr ? ['web-function', 'web-oac', 'web-cache-policy'] : []),
1394
+ // Every shape carries the policy's id, and a removed `headers` key must
1395
+ // detach the policy before the shape stops naming it.
1396
+ ...(responseHeaders ? ['response-headers-policy'] : []),
1048
1397
  ];
1049
1398
  return {
1050
1399
  id: 'cloudfront-distribution',
@@ -1062,6 +1411,9 @@ function distributionNode(hasDomain, preview, ssr) {
1062
1411
  const comment = `${ctx.config.siteName} ${ctx.env}`;
1063
1412
  // What create and adopt agree on: enough identity to record outputs and tag.
1064
1413
  let dist;
1414
+ // An adopted orphan carries whatever shape its own run gave it, so only a
1415
+ // distribution created here is known to carry the response headers policy.
1416
+ let createdFromShape = true;
1065
1417
  try {
1066
1418
  dist = await ctx.clients.cloudfront.createDistribution(distributionShape(ctx, servingMode(ctx), preview));
1067
1419
  }
@@ -1088,7 +1440,10 @@ function distributionNode(hasDomain, preview, ssr) {
1088
1440
  throw err;
1089
1441
  ctx.logger.ok(`adopted existing distribution ${adopted.id} (created by an earlier run)`);
1090
1442
  dist = adopted;
1443
+ createdFromShape = false;
1091
1444
  }
1445
+ if (createdFromShape)
1446
+ recordResponseHeadersPolicyAttached(ctx, dist.id);
1092
1447
  const out = output(ctx, 'cloudfront-distribution');
1093
1448
  out.id = dist.id;
1094
1449
  out.arn = dist.arn;
@@ -1113,11 +1468,13 @@ function distributionNode(hasDomain, preview, ssr) {
1113
1468
  const recorded = out.mode === 'ssr' || out.mode === 'static' ? out.mode : undefined;
1114
1469
  // Full reconcile on every SSR bootstrap (so a later config change converges)
1115
1470
  // 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.
1471
+ // mode). A static stack that stays static keeps the narrow updates below -
1472
+ // aliases and the response headers policy: `spa` and `defaultRootObject`
1473
+ // remain creation-time settings there.
1118
1474
  if (configured === 'ssr' || (recorded !== undefined && recorded !== configured)) {
1119
1475
  const changed = await ctx.clients.cloudfront.reconcileDistribution(id, distributionShape(ctx, configured, preview));
1120
1476
  out.mode = configured;
1477
+ recordResponseHeadersPolicyAttached(ctx, id);
1121
1478
  if (changed) {
1122
1479
  ctx.logger.ok(`reconciled the distribution for ${configured} serving`);
1123
1480
  const domainName = out.domainName;
@@ -1130,28 +1487,8 @@ function distributionNode(hasDomain, preview, ssr) {
1130
1487
  }
1131
1488
  return;
1132
1489
  }
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
- }
1490
+ await reconcileStaticAliases(ctx, id, preview);
1491
+ await attachResponseHeadersPolicy(ctx, id);
1155
1492
  },
1156
1493
  async delete(ctx) {
1157
1494
  const id = output(ctx, 'cloudfront-distribution').id;
@@ -1368,7 +1705,9 @@ function githubOidcRoleNode(preview, ssr) {
1368
1705
  const roleName = (ctx) => ctx.names.githubRole;
1369
1706
  return {
1370
1707
  id: 'gh-oidc-role',
1371
- // Production deploys invalidate the distribution, so its ARN must be in state.
1708
+ // Production deploys invalidate the distribution, so its ARN must be in state
1709
+ // (and, through the distribution's own dependency, the response headers
1710
+ // policy's id the deploy grant names).
1372
1711
  // In SSR mode the policy also names the Web Function role's ARN and the
1373
1712
  // function and endpoint ARNs the service answered with.
1374
1713
  dependsOn: preview
@@ -1449,6 +1788,28 @@ function webFunctionDeployStatements(ctx) {
1449
1788
  },
1450
1789
  ];
1451
1790
  }
1791
+ /**
1792
+ * `promote` copies a staged release's object tags into site/: reading them
1793
+ * needs s3:GetObjectTagging on the staged copy, and writing them
1794
+ * s3:PutObjectTagging on the live one - nothing wider. Only static, non-preview
1795
+ * environments stage and promote.
1796
+ */
1797
+ function promoteTaggingStatements(ctx) {
1798
+ if (ctx.preview || ctx.config.ssr)
1799
+ return [];
1800
+ return [
1801
+ {
1802
+ Effect: 'Allow',
1803
+ Action: ['s3:GetObjectTagging'],
1804
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/${STAGED_RELEASES_PREFIX}*`,
1805
+ },
1806
+ {
1807
+ Effect: 'Allow',
1808
+ Action: ['s3:PutObjectTagging'],
1809
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/site/*`,
1810
+ },
1811
+ ];
1812
+ }
1452
1813
  /** The deploy role's inline policy statements (exported for tests). */
1453
1814
  export function oidcRolePolicyStatements(ctx) {
1454
1815
  const statements = [
@@ -1464,6 +1825,7 @@ export function oidcRolePolicyStatements(ctx) {
1464
1825
  ],
1465
1826
  Resource: `arn:aws:s3:::${ctx.names.bucket}/*`,
1466
1827
  },
1828
+ ...promoteTaggingStatements(ctx),
1467
1829
  { Effect: 'Allow', Action: ['s3:ListBucket'], Resource: `arn:aws:s3:::${ctx.names.bucket}` },
1468
1830
  {
1469
1831
  Effect: 'Allow',
@@ -1507,6 +1869,16 @@ export function oidcRolePolicyStatements(ctx) {
1507
1869
  Action: ['cloudfront:CreateInvalidation'],
1508
1870
  Resource: String(output(ctx, 'cloudfront-distribution').arn),
1509
1871
  });
1872
+ // Deploys converge the response headers in place - this one policy only,
1873
+ // never the distribution (`reconcileResponseHeadersOnDeploy`).
1874
+ const policyId = recordedResponseHeadersPolicyId(ctx);
1875
+ if (policyId !== undefined) {
1876
+ statements.push({
1877
+ Effect: 'Allow',
1878
+ Action: ['cloudfront:GetResponseHeadersPolicy', 'cloudfront:UpdateResponseHeadersPolicy'],
1879
+ Resource: `arn:aws:cloudfront::${ctx.accountId}:response-headers-policy/${policyId}`,
1880
+ });
1881
+ }
1510
1882
  }
1511
1883
  return statements;
1512
1884
  }
@@ -1636,6 +2008,9 @@ export function buildNodes(ctx) {
1636
2008
  oacNode(),
1637
2009
  routerFunctionNode(ctx.preview),
1638
2010
  ];
2011
+ const responseHeaders = ctx.config.headers !== undefined || recordedResponseHeadersPolicyId(ctx) !== undefined;
2012
+ if (responseHeaders)
2013
+ nodes.push(responseHeadersPolicyNode());
1639
2014
  if (ssr) {
1640
2015
  nodes.push(
1641
2016
  // The `.local` companion first: Lambda writes in-Region logs there before
@@ -1643,7 +2018,7 @@ export function buildNodes(ctx) {
1643
2018
  // retention and outside the graph.
1644
2019
  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
2020
  }
1646
- nodes.push(distributionNode(hasDomain, ctx.preview, ssr), logDeliveryNode(), bucketPolicyNode());
2021
+ nodes.push(distributionNode({ hasDomain, preview: ctx.preview, ssr, responseHeaders }), logDeliveryNode(), bucketPolicyNode());
1647
2022
  if (ssr)
1648
2023
  nodes.push(webFunctionPolicyNode());
1649
2024
  if (hasDomain)
@@ -138,6 +138,8 @@ export interface PluginValues {
138
138
  hash?: string | undefined;
139
139
  id?: string | undefined;
140
140
  identifier?: string | undefined;
141
+ /** Session-level like `plain`: it shapes the context's credentials and is never forwarded. */
142
+ profile?: string | undefined;
141
143
  plain: boolean;
142
144
  refresh: boolean;
143
145
  yes: boolean;
@@ -258,6 +260,25 @@ export declare function genericLifecycleActions(plugin: Plugin<unknown>): {
258
260
  * return the SPI has nowhere to carry.
259
261
  */
260
262
  export declare function runPlugin(command: string, rest: string[], values: PluginValues, terminal: Terminal, logger: Logger, makeContext: (opts: ContextOptions) => Promise<OpsContext>, ports: Pick<Ports, 'fs' | 'loader'>): Promise<number>;
263
+ /**
264
+ * Run every installed plugin's `afterDeploy` hook (`blogwright-core`'s
265
+ * `plugin.ts`) once `deploy` has published the site - the one point at which
266
+ * a built-in command runs discovery, and only after its own work is done, so
267
+ * a deploy that fails never loads a plugin.
268
+ *
269
+ * Nothing here is fatal, at any step: the site is already live, so a
270
+ * discovery precondition failing, a plugin failing to load, a plugin's config
271
+ * block being refused, and a hook rejecting are each reported as one warning
272
+ * and the deploy still exits 0 - the same contract the pds sync has always
273
+ * had (`syncAfterDeploy`, `packages/pds/src/commands.ts`). One plugin's
274
+ * failure never stops the next plugin's hook.
275
+ *
276
+ * Each hook gets the same context a dispatched command does: the plugin's own
277
+ * block resolved through {@link resolvePluginConfig} and the scoped
278
+ * {@link toPluginContext}, so a hook reads `pluginConfig` and its own state
279
+ * exactly as its commands do.
280
+ */
281
+ export declare function runAfterDeployHooks(ops: OpsContext, ports: Pick<Ports, 'fs' | 'loader'>): Promise<void>;
261
282
  /**
262
283
  * What `add` and `remove` need beyond the `fs`/`loader` pair `list` runs on.
263
284
  * A single object rather than four more positional parameters, and every