carlin 2.1.0 → 2.2.1

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 +182 -9
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -3462,6 +3462,39 @@ const BASELINE_RESPONSE_HEADERS_CONFIG = {
3462
3462
  }
3463
3463
  }
3464
3464
  };
3465
+ /**
3466
+ * The headers of `BASELINE_RESPONSE_HEADERS_CONFIG.CorsConfig` expressed as
3467
+ * custom headers.
3468
+ *
3469
+ * CloudFront's CORS handling owns `Vary`: with a `CorsConfig` in the policy it
3470
+ * sends `Vary: Origin` on a plain request and removes `Vary` altogether on a
3471
+ * cross-origin one, so a caller-defined `Vary` only survives when the policy
3472
+ * has no `CorsConfig`. The baseline allows a static `*`, which nothing varies
3473
+ * by, so the same headers can be emitted as custom headers and the caller's
3474
+ * `Vary` becomes both true and stable.
3475
+ *
3476
+ * `Access-Control-Allow-Credentials` is omitted because the baseline sets it
3477
+ * to `false`, which is the absence of the header, and `Access-Control-Max-Age`
3478
+ * because the baseline doesn't set it.
3479
+ */
3480
+ const CORS_AS_CUSTOM_HEADERS = [
3481
+ {
3482
+ header: "access-control-allow-origin",
3483
+ value: "*"
3484
+ },
3485
+ {
3486
+ header: "access-control-allow-methods",
3487
+ value: "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT"
3488
+ },
3489
+ {
3490
+ header: "access-control-allow-headers",
3491
+ value: "*"
3492
+ },
3493
+ {
3494
+ header: "access-control-expose-headers",
3495
+ value: "*"
3496
+ }
3497
+ ];
3465
3498
  const validateResponseHeaders = (responseHeaders) => {
3466
3499
  const seen = /* @__PURE__ */ new Set();
3467
3500
  for (const { header } of responseHeaders) {
@@ -3524,10 +3557,27 @@ const getResponseHeadersPolicyConfig = ({ responseHeaders }) => {
3524
3557
  const securityHeadersConfigKey = SECURITY_HEADERS_CONFIG_KEYS[header.toLowerCase()];
3525
3558
  if (securityHeadersConfigKey) delete securityHeadersConfig[securityHeadersConfigKey];
3526
3559
  }
3560
+ /**
3561
+ * A `CorsConfig` makes CloudFront manage `Vary` itself, which silently
3562
+ * discards a user-defined one, so the CORS headers move to
3563
+ * `CustomHeadersConfig` when `vary` is defined. The one behavior lost is the
3564
+ * automatic `OPTIONS` preflight response of `CorsConfig`; simple
3565
+ * cross-origin requests, which is what a static app serves, don't preflight.
3566
+ */
3567
+ const definesVary = responseHeaders.some(({ header }) => {
3568
+ return header.toLowerCase() === "vary";
3569
+ });
3570
+ const customHeaders = definesVary ? [...responseHeaders, ...CORS_AS_CUSTOM_HEADERS.map(({ header, value }) => {
3571
+ return {
3572
+ header,
3573
+ override: true,
3574
+ value
3575
+ };
3576
+ })] : responseHeaders;
3527
3577
  return {
3528
3578
  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 }) => {
3579
+ ...definesVary ? {} : { CorsConfig: BASELINE_RESPONSE_HEADERS_CONFIG.CorsConfig },
3580
+ CustomHeadersConfig: { Items: customHeaders.map(({ header, value, override }) => {
3531
3581
  return {
3532
3582
  Header: header,
3533
3583
  Override: override,
@@ -3544,12 +3594,82 @@ const getResponseHeadersPolicyConfig = ({ responseHeaders }) => {
3544
3594
  };
3545
3595
  };
3546
3596
  //#endregion
3597
+ //#region src/deploy/staticApp/viewerRequestFunction.ts
3598
+ /**
3599
+ * Maximum size of a CloudFront Function, in bytes.
3600
+ *
3601
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-function-quotas.html
3602
+ */
3603
+ const MAX_FUNCTION_SIZE_BYTES = 10 * 1024;
3604
+ /**
3605
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/writing-function-code.html
3606
+ */
3607
+ const FUNCTION_RUNTIME = "cloudfront-js-2.0";
3608
+ /**
3609
+ * `appendIndexHtml` injected into every app-supplied viewer request function.
3610
+ *
3611
+ * A cache behavior takes a single viewer request function, so an app that
3612
+ * supplies its own cannot also associate the shared `AppendIndexDotHtml` of the
3613
+ * base stack. Composing the two by concatenating their sources would not work
3614
+ * either: both would declare `handler`, and the later declaration would win
3615
+ * silently, dropping one of the behaviors.
3616
+ *
3617
+ * Injecting the logic as a named helper instead leaves a single `handler` in the
3618
+ * composed source and makes the order explicit at the call site, which is where
3619
+ * it matters — a function rewriting `/docs/x` to `/docs/x.md` must run before
3620
+ * the index appending, one rewriting `/docs/x` to `/x/docs` after it.
3621
+ *
3622
+ * The body is the base stack `AppendIndexDotHtml` function
3623
+ * (`getCloudFrontTemplate.ts`) with the event unwrapping removed, so both
3624
+ * behave the same. `tests/unit/deploy/staticApp/viewerRequestFunction.test.ts`
3625
+ * asserts they don't drift.
3626
+ */
3627
+ const APPEND_INDEX_HTML_HELPER = `function appendIndexHtml(request) {
3628
+ var uri = request.uri;
3629
+ if (uri.endsWith('/')) {
3630
+ request.uri += 'index.html';
3631
+ } else if (!uri.includes('.')) {
3632
+ request.uri += '/index.html';
3633
+ }
3634
+ return request;
3635
+ }`;
3636
+ /**
3637
+ * The entry point CloudFront calls. A function whose code doesn't declare it
3638
+ * fails at deploy time with an opaque error, so it's checked at synth time.
3639
+ */
3640
+ const HANDLER_DECLARATION_REGEX = /function\s+handler\s*\(/;
3641
+ /**
3642
+ * Reads the file the `viewerRequestFunctionCode` option points to.
3643
+ */
3644
+ const readViewerRequestFunctionCode = ({ filePath }) => {
3645
+ const resolvedPath = path.resolve(filePath);
3646
+ if (!fs.existsSync(resolvedPath)) throw new Error(`The viewer-request-function-code option points to "${filePath}", which doesn't exist.`);
3647
+ return fs.readFileSync(resolvedPath, "utf8");
3648
+ };
3649
+ /**
3650
+ * Composes the source of the per-app `AWS::CloudFront::Function`: the
3651
+ * `appendIndexHtml` helper followed by the app code, which owns the `handler`.
3652
+ */
3653
+ const getViewerRequestFunctionCode = ({ code }) => {
3654
+ if (!code.trim()) throw new Error("The viewer-request-function-code option points to an empty file.");
3655
+ if (!HANDLER_DECLARATION_REGEX.test(code)) throw new Error("The viewer request function code must declare a `function handler(event)`, which is the entry point CloudFront calls.");
3656
+ const functionCode = `${APPEND_INDEX_HTML_HELPER}\n\n${code.trim()}\n`;
3657
+ /**
3658
+ * The helper counts against the app budget, so the size of the composed
3659
+ * source is what CloudFront rejects.
3660
+ */
3661
+ const size = Buffer.byteLength(functionCode, "utf8");
3662
+ if (size > 10240) throw new Error(`The viewer request function is ${size} bytes, above the ${MAX_FUNCTION_SIZE_BYTES} bytes CloudFront allows. The \`appendIndexHtml\` helper carlin injects counts against this budget.`);
3663
+ return functionCode;
3664
+ };
3665
+ //#endregion
3547
3666
  //#region src/deploy/staticApp/staticApp.template.ts
3548
3667
  const PACKAGE_VERSION = getPackageVersion();
3549
3668
  const STATIC_APP_BUCKET_LOGICAL_ID = "StaticBucket";
3550
3669
  const CLOUDFRONT_DISTRIBUTION_LOGICAL_ID = "CloudFrontDistribution";
3551
3670
  const CLOUDFRONT_ORIGIN_ACCESS_CONTROL_LOGICAL_ID = "OriginAccessControl";
3552
3671
  const CLOUDFRONT_RESPONSE_HEADERS_POLICY_LOGICAL_ID = "ResponseHeadersPolicy";
3672
+ const CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID = "ViewerRequestFunction";
3553
3673
  const ROUTE_53_RECORD_SET_GROUP_LOGICAL_ID = "Route53RecordSetGroup";
3554
3674
  const ERROR_DOCUMENT = "404/index.html";
3555
3675
  /**
@@ -3637,7 +3757,7 @@ const getBucketStaticWebsiteTemplate = ({ spa }) => {
3637
3757
  } }
3638
3758
  };
3639
3759
  };
3640
- const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName }) => {
3760
+ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHeaders = [], responseHeadersPolicy, spa, hostedZoneName, viewerRequestFunctionCode }) => {
3641
3761
  const template = {
3642
3762
  AWSTemplateFormatVersion: "2010-09-09",
3643
3763
  Resources: {
@@ -3819,7 +3939,37 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3819
3939
  [`Alias${index}URL`]: { Value: `https://${alias}` }
3820
3940
  };
3821
3941
  }, {});
3822
- if (appendIndexHtml) {
3942
+ /**
3943
+ * A cache behavior takes a single viewer request function, so the app
3944
+ * supplied one replaces the shared base stack one instead of being appended
3945
+ * to it. `appendIndexHtml` is available to the app code as a helper, which is
3946
+ * why the two options are mutually exclusive.
3947
+ *
3948
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html
3949
+ */
3950
+ if (appendIndexHtml && viewerRequestFunctionCode) throw new Error("The append-index-html and viewer-request-function-code options are mutually exclusive. A cache behavior takes a single viewer request function. Call `appendIndexHtml(request)` from your function instead, which carlin injects for you.");
3951
+ if (viewerRequestFunctionCode) template.Resources[CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID] = {
3952
+ Type: "AWS::CloudFront::Function",
3953
+ Properties: {
3954
+ /**
3955
+ * Function names must be unique per AWS account. Static app deploys are
3956
+ * always in us-east-1, so the stack name cannot collide with a
3957
+ * same-named stack in another region.
3958
+ */
3959
+ Name: { Ref: "AWS::StackName" },
3960
+ FunctionConfig: {
3961
+ Comment: { "Fn::Sub": ["Viewer request function for the ${Project} project.", { Project: { Ref: "Project" } }] },
3962
+ Runtime: FUNCTION_RUNTIME
3963
+ },
3964
+ FunctionCode: getViewerRequestFunctionCode({ code: viewerRequestFunctionCode }),
3965
+ AutoPublish: true
3966
+ }
3967
+ };
3968
+ const viewerRequestFunctionArn = (() => {
3969
+ if (viewerRequestFunctionCode) return { "Fn::GetAtt": [CLOUDFRONT_VIEWER_REQUEST_FUNCTION_LOGICAL_ID, "FunctionMetadata.FunctionARN"] };
3970
+ if (appendIndexHtml) return { "Fn::ImportValue": BASE_STACK_CLOUDFRONT_FUNCTION_APPEND_INDEX_HTML_ARN_EXPORTED_NAME };
3971
+ })();
3972
+ if (viewerRequestFunctionArn) {
3823
3973
  if (!template.Resources["CloudFrontDistribution"].Properties) template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties = {};
3824
3974
  template.Resources[CLOUDFRONT_DISTRIBUTION_LOGICAL_ID].Properties.DistributionConfig.DefaultCacheBehavior.FunctionAssociations = [(
3825
3975
  /**
@@ -3827,7 +3977,7 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3827
3977
  */
3828
3978
  {
3829
3979
  EventType: "viewer-request",
3830
- FunctionARN: { "Fn::ImportValue": BASE_STACK_CLOUDFRONT_FUNCTION_APPEND_INDEX_HTML_ARN_EXPORTED_NAME }
3980
+ FunctionARN: viewerRequestFunctionArn
3831
3981
  })];
3832
3982
  }
3833
3983
  /**
@@ -3842,7 +3992,7 @@ const getCloudFrontTemplate = ({ acm, aliases = [], appendIndexHtml, responseHea
3842
3992
  };
3843
3993
  return template;
3844
3994
  };
3845
- const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region }) => {
3995
+ const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, viewerRequestFunctionCode }) => {
3846
3996
  if (cloudfront) return getCloudFrontTemplate({
3847
3997
  acm,
3848
3998
  aliases,
@@ -3852,7 +4002,8 @@ const getStaticAppTemplate = ({ acm, aliases, appendIndexHtml, cloudfront, respo
3852
4002
  responseHeadersPolicy,
3853
4003
  spa,
3854
4004
  hostedZoneName,
3855
- region
4005
+ region,
4006
+ viewerRequestFunctionCode
3856
4007
  });
3857
4008
  return getBucketStaticWebsiteTemplate({ spa });
3858
4009
  };
@@ -3924,7 +4075,7 @@ const logPrefix$4 = "static-app";
3924
4075
  * 1. Upload static files to the host bucket S3.
3925
4076
  * 1. Remove old deployment versions. Keep only the 3 most recent ones.
3926
4077
  */
3927
- const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps }) => {
4078
+ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, cloudfront, responseHeaders, responseHeadersPolicy, spa, hostedZoneName, region, skipUpload, uploadSourceMaps, viewerRequestFunctionCode }) => {
3928
4079
  try {
3929
4080
  const { stackName } = await handleDeployInitialization({ logPrefix: logPrefix$4 });
3930
4081
  const params = { StackName: stackName };
@@ -3937,7 +4088,8 @@ const deployStaticApp = async ({ acm, aliases, appendIndexHtml, buildFolder, clo
3937
4088
  responseHeadersPolicy,
3938
4089
  spa,
3939
4090
  hostedZoneName,
3940
- region
4091
+ region,
4092
+ viewerRequestFunctionCode: viewerRequestFunctionCode ? readViewerRequestFunctionCode({ filePath: viewerRequestFunctionCode }) : void 0
3941
4093
  });
3942
4094
  const bucket = await getStaticAppBucket({ stackName });
3943
4095
  /**
@@ -4056,6 +4208,10 @@ const options$4 = {
4056
4208
  describe: "Upload source map (`.map`) files to S3. They are excluded by default because the bucket is public and source maps expose the application source.",
4057
4209
  require: false,
4058
4210
  type: "boolean"
4211
+ },
4212
+ "viewer-request-function-code": {
4213
+ describe: "Path to a file whose code runs as the CloudFront viewer request function of the distribution. The file must declare a `function handler(event)`, and may call the `appendIndexHtml(request)` helper carlin injects.",
4214
+ type: "string"
4059
4215
  }
4060
4216
  };
4061
4217
  const deployStaticAppCommand = {
@@ -4071,6 +4227,23 @@ const deployStaticAppCommand = {
4071
4227
  */
4072
4228
  if (!cloudfront && (hasResponseHeaders || responseHeadersPolicy)) throw new Error(`The ${hasResponseHeaders ? "response-headers" : "response-headers-policy"} option requires the cloudfront option.`);
4073
4229
  return true;
4230
+ }).check(({ appendIndexHtml, cloudfront, viewerRequestFunctionCode }) => {
4231
+ if (!viewerRequestFunctionCode) return true;
4232
+ /**
4233
+ * A cache behavior takes a single viewer request function, and the
4234
+ * shared base stack one is what append-index-html associates. The app
4235
+ * supplied function gets the same behavior by calling the
4236
+ * `appendIndexHtml` helper carlin injects.
4237
+ *
4238
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html
4239
+ */
4240
+ if (appendIndexHtml) throw new Error("The append-index-html and viewer-request-function-code options are mutually exclusive. A cache behavior takes a single viewer request function. Call `appendIndexHtml(request)` from your function instead, which carlin injects for you.");
4241
+ /**
4242
+ * The function is associated to a cache behavior, so a bucket only
4243
+ * deploy has nothing to attach it to.
4244
+ */
4245
+ if (!cloudfront) throw new Error("The viewer-request-function-code option requires the cloudfront option.");
4246
+ return true;
4074
4247
  }).middleware(() => {
4075
4248
  AWS.config.region = CLOUDFRONT_REGION;
4076
4249
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlin",
3
- "version": "2.1.0",
3
+ "version": "2.2.1",
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/cloudformation": "^0.13.11",
61
60
  "@ttoss/config": "^1.37.17",
61
+ "@ttoss/cloudformation": "^0.13.11",
62
62
  "@ttoss/read-config-file": "^2.2.20"
63
63
  },
64
64
  "devDependencies": {