carlin 2.0.0 → 2.1.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 (2) hide show
  1. package/dist/index.mjs +233 -6
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -3370,11 +3370,186 @@ const invalidateCloudFront = async ({ outputs }) => {
3370
3370
  } else log.info(logPrefix$5, `Cannot invalidate because distribution does not exist.`);
3371
3371
  };
3372
3372
  //#endregion
3373
+ //#region src/deploy/staticApp/responseHeaders.ts
3374
+ /**
3375
+ * The header names emitted by the `SecurityHeadersConfig` of the baseline
3376
+ * policy, mapped to the config key that emits them. Each key is optional in
3377
+ * `SecurityHeadersConfig`, so a user-defined header of the same name replaces
3378
+ * the baseline one by removing the key.
3379
+ */
3380
+ const SECURITY_HEADERS_CONFIG_KEYS = {
3381
+ "content-security-policy": "ContentSecurityPolicy",
3382
+ "referrer-policy": "ReferrerPolicy",
3383
+ "strict-transport-security": "StrictTransportSecurity",
3384
+ "x-content-type-options": "ContentTypeOptions",
3385
+ "x-frame-options": "FrameOptions",
3386
+ "x-xss-protection": "XSSProtection"
3387
+ };
3388
+ /**
3389
+ * The header names emitted by the `CorsConfig` of the baseline policy.
3390
+ * `CorsConfig` requires its fields as a unit, so a single header cannot be
3391
+ * replaced without inventing semantics for the others. Defining one of these
3392
+ * is an error instead.
3393
+ */
3394
+ const CORS_CONFIG_HEADERS = [
3395
+ "access-control-allow-credentials",
3396
+ "access-control-allow-headers",
3397
+ "access-control-allow-methods",
3398
+ "access-control-allow-origin",
3399
+ "access-control-expose-headers",
3400
+ "access-control-max-age"
3401
+ ];
3402
+ /**
3403
+ * https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
3404
+ */
3405
+ const HEADER_NAME_REGEX = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
3406
+ /**
3407
+ * Configuration of the managed policy
3408
+ * `CORS-with-preflight-and-SecurityHeadersPolicy`
3409
+ * (`eaab4381-ed33-4a86-88ca-d9558dc6cd63`), which every static app deploy has
3410
+ * used since CloudFront support was added.
3411
+ *
3412
+ * A custom policy replaces the managed one instead of extending it, so the
3413
+ * managed settings are reproduced here to keep deploys that define response
3414
+ * headers equivalent to the ones that don't.
3415
+ *
3416
+ * Transcribed 2026-08-22 from
3417
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html
3418
+ *
3419
+ * `AccessControlAllowHeaders` is required by CloudFormation but isn't listed
3420
+ * on that page. It mirrors the `AllowedHeaders` of the bucket CORS rules.
3421
+ *
3422
+ * Note the `Override` flags are not uniform: `X-Content-Type-Options` is the
3423
+ * only header the managed policy overrides the origin for.
3424
+ */
3425
+ const BASELINE_RESPONSE_HEADERS_CONFIG = {
3426
+ CorsConfig: {
3427
+ AccessControlAllowCredentials: false,
3428
+ AccessControlAllowHeaders: { Items: ["*"] },
3429
+ AccessControlAllowMethods: { Items: [
3430
+ "DELETE",
3431
+ "GET",
3432
+ "HEAD",
3433
+ "OPTIONS",
3434
+ "PATCH",
3435
+ "POST",
3436
+ "PUT"
3437
+ ] },
3438
+ AccessControlAllowOrigins: { Items: ["*"] },
3439
+ AccessControlExposeHeaders: { Items: ["*"] },
3440
+ OriginOverride: false
3441
+ },
3442
+ SecurityHeadersConfig: {
3443
+ ReferrerPolicy: {
3444
+ Override: false,
3445
+ ReferrerPolicy: "strict-origin-when-cross-origin"
3446
+ },
3447
+ StrictTransportSecurity: {
3448
+ AccessControlMaxAgeSec: 31536e3,
3449
+ IncludeSubdomains: false,
3450
+ Override: false,
3451
+ Preload: false
3452
+ },
3453
+ ContentTypeOptions: { Override: true },
3454
+ FrameOptions: {
3455
+ FrameOption: "SAMEORIGIN",
3456
+ Override: false
3457
+ },
3458
+ XSSProtection: {
3459
+ ModeBlock: true,
3460
+ Override: false,
3461
+ Protection: true
3462
+ }
3463
+ }
3464
+ };
3465
+ const validateResponseHeaders = (responseHeaders) => {
3466
+ const seen = /* @__PURE__ */ new Set();
3467
+ for (const { header } of responseHeaders) {
3468
+ if (!header || !HEADER_NAME_REGEX.test(header)) throw new Error(`"${header}" is not a valid HTTP header name for the response-headers option.`);
3469
+ const headerLowerCase = header.toLowerCase();
3470
+ if (seen.has(headerLowerCase)) throw new Error(`The response header "${header}" was defined more than once. Header names are case-insensitive.`);
3471
+ seen.add(headerLowerCase);
3472
+ if (CORS_CONFIG_HEADERS.includes(headerLowerCase)) throw new Error(`The response header "${header}" is part of the CORS configuration and cannot be defined by the response-headers option. Use the response-headers-policy option to take full control of the policy.`);
3473
+ }
3474
+ };
3475
+ /**
3476
+ * Normalizes the `response-headers` option into a list of headers.
3477
+ *
3478
+ * Accepts the object form, which is the one to prefer:
3479
+ *
3480
+ * ```ts
3481
+ * {
3482
+ * 'content-security-policy': "default-src 'self'",
3483
+ * }
3484
+ * ```
3485
+ *
3486
+ * And the array form, needed only to set `override` per header:
3487
+ *
3488
+ * ```ts
3489
+ * [
3490
+ * { header: 'content-security-policy', value: "default-src 'self'", override: false },
3491
+ * ]
3492
+ * ```
3493
+ */
3494
+ const parseResponseHeaders = (arg) => {
3495
+ if (!arg) return [];
3496
+ const responseHeaders = Array.isArray(arg) ? arg.map(({ header, value, override = true }) => {
3497
+ return {
3498
+ header,
3499
+ value,
3500
+ override
3501
+ };
3502
+ }) : Object.entries(arg).map(([header, value]) => {
3503
+ return {
3504
+ header,
3505
+ value: String(value),
3506
+ override: true
3507
+ };
3508
+ });
3509
+ validateResponseHeaders(responseHeaders);
3510
+ return responseHeaders;
3511
+ };
3512
+ /**
3513
+ * Builds the `ResponseHeadersPolicyConfig` of the policy created when the
3514
+ * response-headers option is defined: the baseline managed policy settings
3515
+ * with the user-defined headers layered on top.
3516
+ */
3517
+ const getResponseHeadersPolicyConfig = ({ responseHeaders }) => {
3518
+ const securityHeadersConfig = { ...BASELINE_RESPONSE_HEADERS_CONFIG.SecurityHeadersConfig };
3519
+ /**
3520
+ * A user-defined header replaces the baseline one instead of being emitted
3521
+ * alongside it.
3522
+ */
3523
+ for (const { header } of responseHeaders) {
3524
+ const securityHeadersConfigKey = SECURITY_HEADERS_CONFIG_KEYS[header.toLowerCase()];
3525
+ if (securityHeadersConfigKey) delete securityHeadersConfig[securityHeadersConfigKey];
3526
+ }
3527
+ return {
3528
+ Comment: { "Fn::Sub": ["Response headers policy for ${Project} project.", { Project: { Ref: "Project" } }] },
3529
+ CorsConfig: BASELINE_RESPONSE_HEADERS_CONFIG.CorsConfig,
3530
+ CustomHeadersConfig: { Items: responseHeaders.map(({ header, value, override }) => {
3531
+ return {
3532
+ Header: header,
3533
+ Override: override,
3534
+ Value: value
3535
+ };
3536
+ }) },
3537
+ /**
3538
+ * Response headers policy names must be unique per AWS account. Static app
3539
+ * deploys are always in us-east-1, so the stack name cannot collide with a
3540
+ * same-named stack in another region.
3541
+ */
3542
+ Name: { Ref: "AWS::StackName" },
3543
+ ...Object.keys(securityHeadersConfig).length > 0 ? { SecurityHeadersConfig: securityHeadersConfig } : {}
3544
+ };
3545
+ };
3546
+ //#endregion
3373
3547
  //#region src/deploy/staticApp/staticApp.template.ts
3374
3548
  const PACKAGE_VERSION = getPackageVersion();
3375
3549
  const STATIC_APP_BUCKET_LOGICAL_ID = "StaticBucket";
3376
3550
  const CLOUDFRONT_DISTRIBUTION_LOGICAL_ID = "CloudFrontDistribution";
3377
3551
  const CLOUDFRONT_ORIGIN_ACCESS_CONTROL_LOGICAL_ID = "OriginAccessControl";
3552
+ const CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID = "ResponseHeadersPolicy";
3378
3553
  const ROUTE_53_RECORD_SET_GROUP_LOGICAL_ID = "Route53RecordSetGroup";
3379
3554
  const ERROR_DOCUMENT = "404/index.html";
3380
3555
  /**
@@ -3393,8 +3568,31 @@ const ORIGIN_REQUEST_POLICY_ID = "88a5eaf4-2fd4-4709-b370-b4c650ea3fcf";
3393
3568
  * Name: CORS-with-preflight-and-SecurityHeadersPolicy
3394
3569
  * ID: eaab4381-ed33-4a86-88ca-d9558dc6cd63
3395
3570
  * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html
3571
+ *
3572
+ * Used when neither the `responseHeaders` nor the `responseHeadersPolicy`
3573
+ * option is defined. Its settings are reproduced in
3574
+ * `BASELINE_RESPONSE_HEADERS_CONFIG` for the policy created by the
3575
+ * `responseHeaders` option.
3396
3576
  */
3397
3577
  const ORIGIN_RESPONSE_POLICY_ID = "eaab4381-ed33-4a86-88ca-d9558dc6cd63";
3578
+ /**
3579
+ * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-responseheaderspolicy.html
3580
+ */
3581
+ const RESPONSE_HEADERS_POLICY_ID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3582
+ /**
3583
+ * The distribution takes a single response headers policy id, so the three
3584
+ * sources are mutually exclusive:
3585
+ *
3586
+ * 1. `responseHeadersPolicy`: an existing policy id, or the name of an
3587
+ * exported value whose value is a policy id.
3588
+ * 1. `responseHeaders`: the policy created by this template.
3589
+ * 1. Neither: the managed policy used by every deploy so far.
3590
+ */
3591
+ const getResponseHeadersPolicyId = ({ responseHeaders = [], responseHeadersPolicy }) => {
3592
+ if (responseHeadersPolicy) return RESPONSE_HEADERS_POLICY_ID_REGEX.test(responseHeadersPolicy) ? responseHeadersPolicy : { "Fn::ImportValue": responseHeadersPolicy };
3593
+ if (responseHeaders.length > 0) return { "Fn::GetAtt": [CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID, "Id"] };
3594
+ return ORIGIN_RESPONSE_POLICY_ID;
3595
+ };
3398
3596
  const getBucketStaticWebsiteTemplate = ({ spa }) => {
3399
3597
  return {
3400
3598
  AWSTemplateFormatVersion: "2010-09-09",
@@ -3439,7 +3637,7 @@ const getBucketStaticWebsiteTemplate = ({ spa }) => {
3439
3637
  } }
3440
3638
  };
3441
3639
  };
3442
- const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hostedZoneName }) => {
3640
+ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName }) => {
3443
3641
  const template = {
3444
3642
  AWSTemplateFormatVersion: "2010-09-09",
3445
3643
  Resources: {
@@ -3517,7 +3715,10 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3517
3715
  * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-cachepolicyid
3518
3716
  */
3519
3717
  CachePolicyId: CACHE_POLICY_ID,
3520
- ResponseHeadersPolicyId: ORIGIN_RESPONSE_POLICY_ID,
3718
+ ResponseHeadersPolicyId: getResponseHeadersPolicyId({
3719
+ responseHeaders,
3720
+ responseHeadersPolicy
3721
+ }),
3521
3722
  TargetOriginId: { Ref: STATIC_APP_BUCKET_LOGICAL_ID },
3522
3723
  ViewerProtocolPolicy: "redirect-to-https"
3523
3724
  },
@@ -3544,7 +3745,11 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3544
3745
  SigningBehavior: "always",
3545
3746
  SigningProtocol: "sigv4"
3546
3747
  } }
3547
- }
3748
+ },
3749
+ ...responseHeaders.length > 0 ? { [CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID]: {
3750
+ Type: "AWS::CloudFront::ResponseHeadersPolicy",
3751
+ Properties: { ResponseHeadersPolicyConfig: getResponseHeadersPolicyConfig({ responseHeaders }) }
3752
+ } } : {}
3548
3753
  };
3549
3754
  if (acm) {
3550
3755
  const acmCertificateArn = /^arn:aws:acm:[-a-z0-9]+:\d{12}:certificate\/[-a-z0-9]+$/.test(acm) ? acm : { "Fn::ImportValue": acm };
@@ -3637,12 +3842,14 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, spa, hosted
3637
3842
  };
3638
3843
  return template;
3639
3844
  };
3640
- const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, spa, hostedZoneName, region }) => {
3845
+ const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region }) => {
3641
3846
  if (cloudfront) return getCloudFrontTemplate({
3642
3847
  acm,
3643
3848
  aliases,
3644
3849
  appendIndexHtml,
3645
3850
  cloudfront,
3851
+ responseHeaders,
3852
+ responseHeadersPolicy,
3646
3853
  spa,
3647
3854
  hostedZoneName,
3648
3855
  region
@@ -3717,7 +3924,7 @@ const logPrefix$4 = "static-app";
3717
3924
  * 1. Upload static files to the host bucket S3.
3718
3925
  * 1. Remove old deployment versions. Keep only the 3 most recent ones.
3719
3926
  */
3720
- const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, spa, hostedZoneName, region, skipUpload, uploadSourceMaps }) => {
3927
+ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps }) => {
3721
3928
  try {
3722
3929
  const { stackName } = await handleDeployInitialization({ logPrefix: logPrefix$4 });
3723
3930
  const params = { StackName: stackName };
@@ -3726,6 +3933,8 @@ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, clo
3726
3933
  aliases,
3727
3934
  appendIndexHtml,
3728
3935
  cloudfront,
3936
+ responseHeaders,
3937
+ responseHeadersPolicy,
3729
3938
  spa,
3730
3939
  hostedZoneName,
3731
3940
  region
@@ -3816,6 +4025,15 @@ const options$4 = {
3816
4025
  hidden: true,
3817
4026
  type: "string"
3818
4027
  },
4028
+ "response-headers": {
4029
+ coerce: parseResponseHeaders,
4030
+ default: [],
4031
+ describe: "Headers added by CloudFront to every response sent to viewers. Pass an object whose keys are header names and values are header values."
4032
+ },
4033
+ "response-headers-policy": {
4034
+ describe: "The id of an existing CloudFront response headers policy, or the name of the exported variable whose value is the id, that will be associated to the distribution instead of the default one.",
4035
+ type: "string"
4036
+ },
3819
4037
  "skip-upload": {
3820
4038
  default: false,
3821
4039
  describe: "Skip files upload to S3. Useful when wanting update only CloudFormation.",
@@ -3844,7 +4062,16 @@ const deployStaticAppCommand = {
3844
4062
  command: "static-app",
3845
4063
  describe: "Deploy static app.",
3846
4064
  builder: (yargs) => {
3847
- return yargs.options(addGroupToOptions(options$4, "Deploy Static App Options")).middleware(() => {
4065
+ return yargs.options(addGroupToOptions(options$4, "Deploy Static App Options")).check(({ cloudfront, responseHeaders, responseHeadersPolicy }) => {
4066
+ const hasResponseHeaders = responseHeaders?.length > 0;
4067
+ if (hasResponseHeaders && responseHeadersPolicy) throw new Error("The response-headers and response-headers-policy options are mutually exclusive. The distribution takes a single response headers policy.");
4068
+ /**
4069
+ * Response headers are applied by CloudFront, so a bucket only
4070
+ * deploy has nothing to attach them to.
4071
+ */
4072
+ if (!cloudfront && (hasResponseHeaders || responseHeadersPolicy)) throw new Error(`The ${hasResponseHeaders ? "response-headers" : "response-headers-policy"} option requires the cloudfront option.`);
4073
+ return true;
4074
+ }).middleware(() => {
3848
4075
  AWS.config.region = CLOUDFRONT_REGION;
3849
4076
  });
3850
4077
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlin",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "homepage": "https://ttoss.dev/docs/carlin/",
@@ -57,8 +57,8 @@
57
57
  "ts-node": "^10.9.2",
58
58
  "uglify-js": "^3.19.3",
59
59
  "yargs": "^17.7.2",
60
- "@ttoss/config": "^1.37.17",
61
60
  "@ttoss/cloudformation": "^0.13.11",
61
+ "@ttoss/config": "^1.37.17",
62
62
  "@ttoss/read-config-file": "^2.2.20"
63
63
  },
64
64
  "devDependencies": {