canopycms-cdk 0.0.67 → 0.0.68-int.101
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/constructs/asset-support.d.ts +103 -81
- package/dist/constructs/asset-support.js +193 -196
- package/dist/constructs/cms-distribution.d.ts +7 -7
- package/dist/constructs/cms-distribution.js +19 -67
- package/dist/constructs/cms-service.d.ts +55 -8
- package/dist/constructs/cms-service.js +67 -15
- package/dist/constructs/editor-routing.d.ts +131 -0
- package/dist/constructs/editor-routing.js +313 -0
- package/dist/index.d.ts +1 -0
- package/lambda/asset-transform/dist/handler.js +1336 -650
- package/package.json +4 -4
- package/worker/dist/index.js +1739 -800
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Construct } from 'constructs';
|
|
2
|
-
import {
|
|
3
|
-
import { DEFAULT_CMS_LAMBDA_TIMEOUT
|
|
2
|
+
import { Stack, Token, aws_cloudfront as cloudfront, aws_cloudfront_origins as origins, aws_certificatemanager as acm, aws_route53 as route53, aws_route53_targets as targets, } from 'aws-cdk-lib';
|
|
3
|
+
import { DEFAULT_CMS_LAMBDA_TIMEOUT } from './cms-service.js';
|
|
4
|
+
import { assertOriginReadTimeout, createEditorResponseHeadersPolicy, createForwardedHostFunction, createStaticCachePolicy, lambdaBehaviorOptions, } from './editor-routing.js';
|
|
4
5
|
import { ASSETS_PATH_PATTERN, ASSETS_TRANSFORM_PATH_PATTERN, ASSET_BEHAVIOR_SPREAD_MISTAKE_KEYS, } from './asset-support.js';
|
|
5
6
|
/**
|
|
6
7
|
* Merge caller behaviors over this construct's own, preserving THE CALLER'S
|
|
@@ -60,9 +61,8 @@ function normalizePathPattern(pattern) {
|
|
|
60
61
|
* type-checks and deploys clean, synthesizing two behaviors matching the
|
|
61
62
|
* literal patterns `assets` and `assetsTransform`, which nothing requests.
|
|
62
63
|
* 2. `/assets/*` listed before `/assets/t/*`: CloudFront's first-match-wins
|
|
63
|
-
* ordering serves every transform request off the broader
|
|
64
|
-
*
|
|
65
|
-
* computed (an OAC-signed S3 miss reports 403).
|
|
64
|
+
* ordering serves every transform request off the broader `/assets/*`
|
|
65
|
+
* behavior, so with `lazyPublicTransforms` no miss reaches the Lambda.
|
|
66
66
|
* 3. Either asset pattern in `merged` WHILE the `assetSupport` prop is also
|
|
67
67
|
* passed: both wiring routes are active at once, so each pattern is attached
|
|
68
68
|
* twice. Hazard 2 cannot catch it, because the hand-written order is usually
|
|
@@ -118,9 +118,9 @@ function assertNoAssetBehaviorOrderingHazards(merged, attachingAssetSupport) {
|
|
|
118
118
|
throw new Error(`CanopyCmsDistribution: additionalBehaviors lists '${ASSETS_PATH_PATTERN}' before ` +
|
|
119
119
|
`'${ASSETS_TRANSFORM_PATH_PATTERN}'. CloudFront matches path patterns in the order given ` +
|
|
120
120
|
`and stops at the first match, so every '${ASSETS_TRANSFORM_PATH_PATTERN}' request would ` +
|
|
121
|
-
`be served by the broader
|
|
122
|
-
|
|
123
|
-
`
|
|
121
|
+
`be served by the broader '${ASSETS_PATH_PATTERN}' behavior, and with ` +
|
|
122
|
+
`\`lazyPublicTransforms\` no miss would ever reach the transform Lambda. List ` +
|
|
123
|
+
`'${ASSETS_TRANSFORM_PATH_PATTERN}' first, or use ` +
|
|
124
124
|
`assetSupport.attachTo(distribution) / this construct's \`assetSupport\` prop, which get ` +
|
|
125
125
|
`the order right automatically.`);
|
|
126
126
|
}
|
|
@@ -128,17 +128,18 @@ function assertNoAssetBehaviorOrderingHazards(merged, attachingAssetSupport) {
|
|
|
128
128
|
/**
|
|
129
129
|
* Optional CDK construct for CanopyCMS CloudFront distribution.
|
|
130
130
|
*
|
|
131
|
-
* Use this
|
|
132
|
-
*
|
|
133
|
-
* and wire it into your own CloudFront setup.
|
|
131
|
+
* Use this when the CMS gets a domain of its own. To serve the editor from a
|
|
132
|
+
* distribution you already own, use `CanopyCmsService.attachTo` instead.
|
|
134
133
|
*
|
|
135
134
|
* Creates:
|
|
136
135
|
* - ACM certificate (DNS validated) — unless provided
|
|
137
136
|
* - CloudFront distribution with Function URL origin
|
|
138
137
|
* - Route53 A/AAAA alias records
|
|
139
|
-
* - Cache policies: no-cache
|
|
138
|
+
* - Cache policies: no-cache default behavior, cache /_next/static/*
|
|
140
139
|
* - Viewer-request CloudFront Function setting x-forwarded-host (redirect-URL
|
|
141
140
|
* derivation behind the Host-stripping OAC origin)
|
|
141
|
+
* - The editor's response headers policy (framing protection, `noindex`) on
|
|
142
|
+
* both of its own behaviors
|
|
142
143
|
* - `AssetSupport`'s `/assets/*` and `/assets/t/*` behaviors, in the required
|
|
143
144
|
* order, when the `assetSupport` prop is passed
|
|
144
145
|
*/
|
|
@@ -193,75 +194,26 @@ export class CanopyCmsDistribution extends Construct {
|
|
|
193
194
|
// entirely when unset, so CloudFront's 30s service default applies and
|
|
194
195
|
// silently halves the CMS Lambda's 60s budget. See the prop's doc comment.
|
|
195
196
|
const readTimeout = props.originReadTimeout ?? DEFAULT_CMS_LAMBDA_TIMEOUT;
|
|
196
|
-
|
|
197
|
-
throw new Error(`CanopyCmsDistribution: originReadTimeout is ${readTimeout.toSeconds()}s, but CloudFront ` +
|
|
198
|
-
`allows at most ${MAX_CLOUDFRONT_ORIGIN_READ_TIMEOUT.toSeconds()}s without a service-quota ` +
|
|
199
|
-
`increase. Either lower the CMS Lambda's timeout to match, or request a quota increase for ` +
|
|
200
|
-
`"Origin response timeout" and pass the higher value explicitly. Deploying with a shorter ` +
|
|
201
|
-
`origin timeout than the Lambda's would 504 at the edge on requests that actually succeed.`);
|
|
202
|
-
}
|
|
197
|
+
assertOriginReadTimeout(readTimeout, 'CanopyCmsDistribution');
|
|
203
198
|
const origin = origins.FunctionUrlOrigin.withOriginAccessControl(props.functionUrl, {
|
|
204
199
|
readTimeout,
|
|
205
200
|
});
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
// cookieBehavior/queryStringBehavior `all()` ("The parameter CookieBehavior
|
|
210
|
-
// is invalid for policy with caching disabled"). With TTL 0 the cache key is
|
|
211
|
-
// meaningless anyway, and the origin still receives the full viewer request
|
|
212
|
-
// (headers/cookies/query string, minus Host - forwarding Host would break
|
|
213
|
-
// the OAC-signed Function URL) via the ALL_VIEWER_EXCEPT_HOST_HEADER origin
|
|
214
|
-
// request policy on the behavior.
|
|
215
|
-
const noCachePolicy = cloudfront.CachePolicy.CACHING_DISABLED;
|
|
216
|
-
const staticCachePolicy = new cloudfront.CachePolicy(this, 'StaticCachePolicy', {
|
|
217
|
-
defaultTtl: Duration.days(365),
|
|
218
|
-
maxTtl: Duration.days(365),
|
|
219
|
-
minTtl: Duration.days(365),
|
|
220
|
-
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
|
|
221
|
-
queryStringBehavior: cloudfront.CacheQueryStringBehavior.none(),
|
|
222
|
-
cookieBehavior: cloudfront.CacheCookieBehavior.none(),
|
|
223
|
-
});
|
|
224
|
-
// CloudFront gives the origin the Function URL's own Host (forwarding the
|
|
225
|
-
// viewer Host would break the OAC SigV4 signature), and Lambda Web Adapter
|
|
226
|
-
// forwards no `x-forwarded-*` headers of its own - so without this function,
|
|
227
|
-
// Clerk/Next derive sign-in redirect URLs from the IAM-authed Function URL
|
|
228
|
-
// host instead of the public domain, and the redirect 403s (direct Function
|
|
229
|
-
// URL hits are rejected).
|
|
230
|
-
//
|
|
231
|
-
// ONLY x-forwarded-host: x-forwarded-proto is on CloudFront Functions'
|
|
232
|
-
// DISALLOWED header list and setting it fails every request with 502
|
|
233
|
-
// FunctionValidationError. Proto is unambiguous anyway - viewer-facing
|
|
234
|
-
// CloudFront is HTTPS-only via REDIRECT_TO_HTTPS.
|
|
235
|
-
const forwardedHostFunction = new cloudfront.Function(this, 'ForwardedHostFunction', {
|
|
236
|
-
code: cloudfront.FunctionCode.fromInline([
|
|
237
|
-
'function handler(event) {',
|
|
238
|
-
' var request = event.request;',
|
|
239
|
-
" request.headers['x-forwarded-host'] = { value: request.headers.host.value };",
|
|
240
|
-
' return request;',
|
|
241
|
-
'}',
|
|
242
|
-
].join('\n')),
|
|
243
|
-
});
|
|
201
|
+
const staticCachePolicy = createStaticCachePolicy(this, 'StaticCachePolicy');
|
|
202
|
+
const forwardedHostFunction = createForwardedHostFunction(this, 'ForwardedHostFunction');
|
|
203
|
+
const responseHeadersPolicy = createEditorResponseHeadersPolicy(this, 'EditorResponseHeadersPolicy');
|
|
244
204
|
this.distribution = new cloudfront.Distribution(this, 'Distribution', {
|
|
245
205
|
domainNames: [props.domainName],
|
|
246
206
|
certificate,
|
|
247
207
|
defaultBehavior: {
|
|
248
208
|
origin,
|
|
249
|
-
|
|
250
|
-
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
|
|
251
|
-
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
|
|
252
|
-
originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
|
|
253
|
-
functionAssociations: [
|
|
254
|
-
{
|
|
255
|
-
function: forwardedHostFunction,
|
|
256
|
-
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
|
|
257
|
-
},
|
|
258
|
-
],
|
|
209
|
+
...lambdaBehaviorOptions(forwardedHostFunction, responseHeadersPolicy),
|
|
259
210
|
},
|
|
260
211
|
additionalBehaviors: mergeBehaviors({
|
|
261
212
|
'/_next/static/*': {
|
|
262
213
|
origin,
|
|
263
214
|
cachePolicy: staticCachePolicy,
|
|
264
215
|
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
|
|
216
|
+
responseHeadersPolicy,
|
|
265
217
|
},
|
|
266
218
|
}, props.additionalBehaviors, props.assetSupport !== undefined),
|
|
267
219
|
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Construct } from 'constructs';
|
|
2
|
-
import { Duration, RemovalPolicy, aws_ec2 as ec2, aws_efs as efs, aws_iam as iam, aws_lambda as lambda, aws_autoscaling as autoscaling, aws_logs as logs } from 'aws-cdk-lib';
|
|
2
|
+
import { Duration, RemovalPolicy, aws_ec2 as ec2, aws_efs as efs, aws_cloudfront as cloudfront, aws_iam as iam, aws_lambda as lambda, aws_autoscaling as autoscaling, aws_logs as logs } from 'aws-cdk-lib';
|
|
3
3
|
import type { IBucket } from 'aws-cdk-lib/aws-s3';
|
|
4
|
+
import type { CanopyCmsAttachOptions } from './editor-routing.js';
|
|
4
5
|
/**
|
|
5
6
|
* Default CMS Lambda timeout.
|
|
6
7
|
*
|
|
@@ -20,8 +21,15 @@ import type { IBucket } from 'aws-cdk-lib/aws-s3';
|
|
|
20
21
|
* than deploying a configuration that would 504.
|
|
21
22
|
*/
|
|
22
23
|
export declare const DEFAULT_CMS_LAMBDA_TIMEOUT: Duration;
|
|
23
|
-
/**
|
|
24
|
-
|
|
24
|
+
/**
|
|
25
|
+
* The cap below which synth warns. With nothing cached, a cold editor load on
|
|
26
|
+
* the example app sends the Lambda about 25 requests, 14 of them chunks
|
|
27
|
+
* requested together, and each invocation holds an execution environment
|
|
28
|
+
* through its cold start.
|
|
29
|
+
*/
|
|
30
|
+
export declare const MIN_CMS_RESERVED_CONCURRENCY = 20;
|
|
31
|
+
/** Default `reservedConcurrency`; see that prop for what it caps and costs. */
|
|
32
|
+
export declare const DEFAULT_CMS_RESERVED_CONCURRENCY = 50;
|
|
25
33
|
export interface CanopyCmsServiceProps {
|
|
26
34
|
/** Docker image for the CMS Lambda function */
|
|
27
35
|
cmsDockerImage: lambda.DockerImageCode;
|
|
@@ -31,11 +39,28 @@ export interface CanopyCmsServiceProps {
|
|
|
31
39
|
memorySize?: number;
|
|
32
40
|
/** Lambda timeout (default: 60 seconds) */
|
|
33
41
|
timeout?: Duration;
|
|
34
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* Cap on the CMS Lambda's concurrent invocations (default: 50).
|
|
44
|
+
*
|
|
45
|
+
* Everything the Lambda serves counts against it, including the editor's
|
|
46
|
+
* static chunks (`editorAssetPrefix` on `attachTo`, `/_next/static/*` on
|
|
47
|
+
* `CanopyCmsDistribution`) whenever CloudFront misses them. CloudFront caches
|
|
48
|
+
* per regional edge cache, so after a deploy the first editor load behind
|
|
49
|
+
* each one requests every chunk together, and an invocation over the cap is
|
|
50
|
+
* answered 429: the
|
|
51
|
+
* browser refuses that as a script and the editor fails with
|
|
52
|
+
* `ChunkLoadError`. Synth warns below {@link MIN_CMS_RESERVED_CONCURRENCY}.
|
|
53
|
+
*
|
|
54
|
+
* A reservation costs nothing while idle; it is a ceiling, and a share of
|
|
55
|
+
* the account's concurrency set aside so other functions cannot use it.
|
|
56
|
+
* Lambda keeps 100 of the account's limit unreserved, so this plus every
|
|
57
|
+
* other reservation (AssetSupport's lazy transform Lambda reserves 10) must fit
|
|
58
|
+
* within the account limit minus 100.
|
|
59
|
+
*/
|
|
35
60
|
reservedConcurrency?: number;
|
|
36
61
|
/**
|
|
37
62
|
* Lambda architecture (default: `Architecture.ARM_64`, matching the EC2
|
|
38
|
-
* worker and AssetSupport's transform Lambda).
|
|
63
|
+
* worker and AssetSupport's lazy transform Lambda).
|
|
39
64
|
*
|
|
40
65
|
* This also decides the image's architecture for
|
|
41
66
|
* `DockerImageCode.fromImageAsset`: the construct always passes a resolved
|
|
@@ -62,11 +87,12 @@ export interface CanopyCmsServiceProps {
|
|
|
62
87
|
/**
|
|
63
88
|
* Environment variables for the Lambda function.
|
|
64
89
|
*
|
|
65
|
-
*
|
|
90
|
+
* Three keys are not free-form here, because the construct configures the
|
|
66
91
|
* worker from the same values and the two halves must agree:
|
|
67
92
|
* `CANOPYCMS_DEPLOYMENT_NAME` is folded into `deploymentName` (validated,
|
|
68
|
-
* and mirrored into the worker's `.env`),
|
|
69
|
-
* `'prod'
|
|
93
|
+
* and mirrored into the worker's `.env`), `CANOPY_MODE` accepts only
|
|
94
|
+
* `'prod'`, and `CANOPYCMS_WORKSPACE_ROOT` accepts only the shared EFS mount
|
|
95
|
+
* path, `/mnt/efs`. Everything else is passed through untouched.
|
|
70
96
|
*/
|
|
71
97
|
environment?: Record<string, string>;
|
|
72
98
|
/** EFS removal policy (default: RETAIN) */
|
|
@@ -360,4 +386,25 @@ export declare class CanopyCmsService extends Construct {
|
|
|
360
386
|
/** The EC2 worker's CloudWatch log group (worker stdout/stderr) */
|
|
361
387
|
readonly workerLogGroup: logs.LogGroup;
|
|
362
388
|
constructor(scope: Construct, id: string, props: CanopyCmsServiceProps);
|
|
389
|
+
/**
|
|
390
|
+
* Serve the editor from a CloudFront distribution you already own, such as
|
|
391
|
+
* the site's: adds `/edit`, `/edit/*` and `/api/canopycms/*` behaviors
|
|
392
|
+
* (plus any `previewPrefix` and `editorAssetPrefix` routes) to this
|
|
393
|
+
* service's Function URL, behind OAC, with
|
|
394
|
+
* an origin read timeout equal to {@link timeout}, no caching, the whole
|
|
395
|
+
* viewer request forwarded, an `x-forwarded-host` viewer-request function and
|
|
396
|
+
* the editor's response headers policy (framing protection, `noindex`).
|
|
397
|
+
*
|
|
398
|
+
* The behaviors are appended. Synth fails if a behavior listed before them
|
|
399
|
+
* matches an editor route, since CloudFront would never reach the editor's.
|
|
400
|
+
* It warns when the distribution has custom error responses, which also
|
|
401
|
+
* rewrite the API's errors.
|
|
402
|
+
*
|
|
403
|
+
* Pass `editorAssetPrefix` with the CMS build's Next `assetPrefix`, so the
|
|
404
|
+
* editor's chunks stay out of the site's `/_next/static/*`, and
|
|
405
|
+
* `previewPrefix` with a static-export site's preview route.
|
|
406
|
+
* `AssetSupport.attachTo` adds `/assets/*`. Use `CanopyCmsDistribution`
|
|
407
|
+
* instead when the CMS gets a domain of its own.
|
|
408
|
+
*/
|
|
409
|
+
attachTo(distribution: cloudfront.Distribution, options?: CanopyCmsAttachOptions): void;
|
|
363
410
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import * as path from 'node:path';
|
|
2
2
|
import { fileURLToPath } from 'node:url';
|
|
3
3
|
import { Construct } from 'constructs';
|
|
4
|
-
import { Duration, RemovalPolicy, Stack, Token, aws_ec2 as ec2, aws_efs as efs, aws_iam as iam, aws_lambda as lambda, aws_autoscaling as autoscaling, aws_s3_assets as s3assets, aws_logs as logs, } from 'aws-cdk-lib';
|
|
4
|
+
import { Annotations, Duration, RemovalPolicy, Stack, Token, aws_ec2 as ec2, aws_efs as efs, aws_iam as iam, aws_lambda as lambda, aws_autoscaling as autoscaling, aws_s3_assets as s3assets, aws_logs as logs, } from 'aws-cdk-lib';
|
|
5
5
|
import { attachLambdaExecutionPolicies } from './lambda-execution-role.js';
|
|
6
|
+
import { attachEditorBehaviors } from './editor-routing.js';
|
|
6
7
|
// This package (`canopycms-cdk`) is `"type": "module"`, so its compiled output
|
|
7
8
|
// is real ESM and `__dirname` is not a global there - the worker asset path
|
|
8
9
|
// below throws `__dirname is not defined` under a real ESM runtime (e.g. `tsx`)
|
|
@@ -34,6 +35,15 @@ const isValidDeploymentName = (name) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name
|
|
|
34
35
|
!name.includes('..') &&
|
|
35
36
|
!name.endsWith('.') &&
|
|
36
37
|
!name.endsWith('.lock');
|
|
38
|
+
/**
|
|
39
|
+
* Where the Lambda AND the worker mount the `WorkspaceAP` access point (rooted
|
|
40
|
+
* at EFS:/workspace), and so the workspace root of both.
|
|
41
|
+
*
|
|
42
|
+
* One path string, not merely one directory: git records absolute paths on
|
|
43
|
+
* EFS (a workspace clone's `origin` is `<root>/remote.git`), and a path written
|
|
44
|
+
* by one process must resolve for the other.
|
|
45
|
+
*/
|
|
46
|
+
const EFS_MOUNT_PATH = '/mnt/efs';
|
|
37
47
|
/**
|
|
38
48
|
* The heredoc delimiter user-data uses to write the worker's `.env` (see the
|
|
39
49
|
* `cat > … << 'ENVEOF'` block below).
|
|
@@ -455,8 +465,15 @@ function assertGitHubAuthProps(props) {
|
|
|
455
465
|
* than deploying a configuration that would 504.
|
|
456
466
|
*/
|
|
457
467
|
export const DEFAULT_CMS_LAMBDA_TIMEOUT = Duration.seconds(60);
|
|
458
|
-
/**
|
|
459
|
-
|
|
468
|
+
/**
|
|
469
|
+
* The cap below which synth warns. With nothing cached, a cold editor load on
|
|
470
|
+
* the example app sends the Lambda about 25 requests, 14 of them chunks
|
|
471
|
+
* requested together, and each invocation holds an execution environment
|
|
472
|
+
* through its cold start.
|
|
473
|
+
*/
|
|
474
|
+
export const MIN_CMS_RESERVED_CONCURRENCY = 20;
|
|
475
|
+
/** Default `reservedConcurrency`; see that prop for what it caps and costs. */
|
|
476
|
+
export const DEFAULT_CMS_RESERVED_CONCURRENCY = 50;
|
|
460
477
|
/**
|
|
461
478
|
* Core CDK construct for CanopyCMS deployment.
|
|
462
479
|
*
|
|
@@ -563,6 +580,14 @@ export class CanopyCmsService extends Construct {
|
|
|
563
580
|
`(dev mode resolves its workspace to <cwd>/.canopy-dev, which is read-only on Lambda). ` +
|
|
564
581
|
`Omit it to get the default.`);
|
|
565
582
|
}
|
|
583
|
+
const envWorkspaceRootOverride = props.environment?.['CANOPYCMS_WORKSPACE_ROOT'];
|
|
584
|
+
if (envWorkspaceRootOverride !== undefined && envWorkspaceRootOverride !== EFS_MOUNT_PATH) {
|
|
585
|
+
throw new Error(`CanopyCmsService: invalid environment.CANOPYCMS_WORKSPACE_ROOT ` +
|
|
586
|
+
`${JSON.stringify(envWorkspaceRootOverride)}. The Lambda and the worker both mount the ` +
|
|
587
|
+
`workspace at ${EFS_MOUNT_PATH}, and git paths one writes on EFS must resolve for the ` +
|
|
588
|
+
`other, so the only supported value is ${JSON.stringify(EFS_MOUNT_PATH)}. ` +
|
|
589
|
+
`Omit it to get the default.`);
|
|
590
|
+
}
|
|
566
591
|
this.vpc =
|
|
567
592
|
props.vpc ??
|
|
568
593
|
new ec2.Vpc(this, 'Vpc', {
|
|
@@ -670,6 +695,14 @@ export class CanopyCmsService extends Construct {
|
|
|
670
695
|
// Silicon, amd64 on an x86 CI runner) while the function stays x86_64, and
|
|
671
696
|
// the mismatch only shows at invoke. See `architecture`'s doc comment.
|
|
672
697
|
const architecture = props.architecture ?? lambda.Architecture.ARM_64;
|
|
698
|
+
const reservedConcurrency = props.reservedConcurrency ?? DEFAULT_CMS_RESERVED_CONCURRENCY;
|
|
699
|
+
if (!Token.isUnresolved(reservedConcurrency) &&
|
|
700
|
+
reservedConcurrency < MIN_CMS_RESERVED_CONCURRENCY) {
|
|
701
|
+
Annotations.of(this).addWarningV2('canopycms:cms-reserved-concurrency-low', `reservedConcurrency is ${reservedConcurrency}, below ${MIN_CMS_RESERVED_CONCURRENCY}. ` +
|
|
702
|
+
`The editor's static chunks are served by this Lambda until CloudFront caches them, ` +
|
|
703
|
+
`and a cold editor load requests them together, so a throttled chunk fails the ` +
|
|
704
|
+
`editor with ChunkLoadError. See the reservedConcurrency prop.`);
|
|
705
|
+
}
|
|
673
706
|
this.lambdaFunction = new lambda.DockerImageFunction(this, 'CmsFunction', {
|
|
674
707
|
code: props.cmsDockerImage,
|
|
675
708
|
// Default (unset) leaves CDK to create the execution role, with its own
|
|
@@ -677,26 +710,21 @@ export class CanopyCmsService extends Construct {
|
|
|
677
710
|
role: props.lambdaRole,
|
|
678
711
|
memorySize: props.memorySize ?? 2048,
|
|
679
712
|
timeout: this.timeout,
|
|
680
|
-
reservedConcurrentExecutions:
|
|
713
|
+
reservedConcurrentExecutions: reservedConcurrency,
|
|
681
714
|
architecture,
|
|
682
715
|
vpc: this.vpc,
|
|
683
716
|
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
|
|
684
717
|
securityGroups: [lambdaSg],
|
|
685
|
-
filesystem: lambda.FileSystem.fromEfsAccessPoint(accessPoint,
|
|
718
|
+
filesystem: lambda.FileSystem.fromEfsAccessPoint(accessPoint, EFS_MOUNT_PATH),
|
|
686
719
|
// Pass the pre-created group via `logGroup`, NOT `logRetention` (CDK
|
|
687
720
|
// throws LogRetentionLogGroupConflict/ConflictingLogPolicyOptions if
|
|
688
721
|
// both are set on the same function) - the removal policy lives on the
|
|
689
722
|
// LogGroup construct above instead.
|
|
690
723
|
logGroup: this.cmsLogGroup,
|
|
691
724
|
environment: {
|
|
692
|
-
//
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
// /mnt/efs (see UserData below) and reaches the same directory via
|
|
696
|
-
// /mnt/efs/workspace. Both paths must resolve to EFS:/workspace, or the
|
|
697
|
-
// Lambda and worker silently operate on different directories.
|
|
698
|
-
CANOPYCMS_WORKSPACE_ROOT: '/mnt/efs',
|
|
699
|
-
CANOPY_AUTH_CACHE_PATH: '/mnt/efs/.cache',
|
|
725
|
+
// The worker's `.env` gets the same root; see EFS_MOUNT_PATH.
|
|
726
|
+
CANOPYCMS_WORKSPACE_ROOT: EFS_MOUNT_PATH,
|
|
727
|
+
CANOPY_AUTH_CACHE_PATH: `${EFS_MOUNT_PATH}/.cache`,
|
|
700
728
|
// git >= 2.35.2 refuses repos owned by another uid (the access point
|
|
701
729
|
// forces uid 1000; Lambda containers run as a different user).
|
|
702
730
|
// Env-based GIT_CONFIG_* CANNOT fix this - simple-git hard-blocks env
|
|
@@ -820,7 +848,7 @@ export class CanopyCmsService extends Construct {
|
|
|
820
848
|
// through `assertEnvSafe` in the single `map` below, so a value added here
|
|
821
849
|
// later is guarded whether or not whoever adds it remembers to.
|
|
822
850
|
const envEntries = [
|
|
823
|
-
['CANOPYCMS_WORKSPACE_ROOT',
|
|
851
|
+
['CANOPYCMS_WORKSPACE_ROOT', EFS_MOUNT_PATH],
|
|
824
852
|
['CANOPYCMS_GITHUB_OWNER', props.githubOwner],
|
|
825
853
|
['CANOPYCMS_GITHUB_REPO', props.githubRepo],
|
|
826
854
|
['CANOPYCMS_BASE_BRANCH', baseBranch],
|
|
@@ -885,8 +913,9 @@ export class CanopyCmsService extends Construct {
|
|
|
885
913
|
const envFileContent = envEntries
|
|
886
914
|
.map(([name, value]) => `${name}=${assertEnvSafe(name, value)}`)
|
|
887
915
|
.join('\n');
|
|
916
|
+
const efsMountOptions = `tls,accesspoint=${accessPoint.accessPointId}`;
|
|
888
917
|
const userData = ec2.UserData.forLinux();
|
|
889
|
-
userData.addCommands('#!/bin/bash', 'set -euo pipefail', '', '# FAIL-FAST. Every step below is required for the worker to exist at', '# all, and until this trap existed a failure in any of them aborted', '# user-data BEFORE the systemd unit was written -- leaving an instance', "# that runs, passes the ASG's EC2-only health check indefinitely, and", '# does nothing. cfn-signal is deliberately not used here (it would', '# prove nothing about READINESS, which is the argument recorded below),', '# but that argument never covered a boot-SCRIPT failure: `cdk deploy`', '# reported success while publishes queued on EFS, the auth cache went', '# stale and PRs stopped being created, until a human noticed the admin', '# panel showing the worker absent.', '#', '# Shutting down makes the instance fail its EC2 health check, so the ASG', '# replaces it -- which is the only automatic recovery available in this', '# topology. The echo lands in the console log, readable via', '# `aws ec2 get-console-output`, because the CloudWatch agent is itself', '# configured further down and cannot be relied on to exist yet.', 'trap \'echo "canopy-worker user-data FAILED at line $LINENO (exit $?)" >&2; shutdown -h now\' ERR', '', '# Bounded retry for the network-dependent steps. Package mirrors and S3', '# have transient failures; a single flake should cost seconds, not an', '# instance replacement.', 'retry() {', ' local n=0', ' until "$@"; do', ' n=$((n + 1))', ' if [ "$n" -ge 5 ]; then', ' echo "canopy-worker: command failed after $n attempts: $*" >&2', ' return 1', ' fi', ' sleep $((n * 5))', ' done', '}', '', '# Install dependencies (unzip is not guaranteed in the AL2023 AMI)', 'retry dnf install -y git unzip', "# Node comes from AL2023's own repos, NOT a piped third-party installer.", '# The previous boot curled the NodeSource RPM setup script straight into', '# bash, so every instance replacement -- which the ASG performs on every', '# `cdk deploy`, plus every spot interruption -- depended on a third party', '# being reachable. cms-deploy.test.ts asserts that URL never comes back,', '# which is why it is not spelled out here.', '#', '# nodejs22, not 20: Node 20 reached upstream EOL on 2026-04-30, and this', '# repo declares `engines.node: ">=22"` with .nvmrc `v22`, so the worker', '# was running an EOL runtime BELOW the floor its own code is tested at.', "# 22 (EOL 2027-04-30) matches .nvmrc, CI, and the transform Lambda's", '# NODEJS_22_X, so one runtime is tested everywhere.', '#', '# ExecStart uses the NAMESPACED /usr/bin/node-22 (see the systemd unit', '# below), not the bare `node`: AL2023 installs versioned binaries and', '# points `/usr/bin/node` at one of them through `alternatives`, whose', '# selection AWS documents as able to change at any time.', 'retry dnf install -y nodejs22', '', '# Mount EFS', 'retry dnf install -y amazon-efs-utils',
|
|
918
|
+
userData.addCommands('#!/bin/bash', 'set -euo pipefail', '', '# FAIL-FAST. Every step below is required for the worker to exist at', '# all, and until this trap existed a failure in any of them aborted', '# user-data BEFORE the systemd unit was written -- leaving an instance', "# that runs, passes the ASG's EC2-only health check indefinitely, and", '# does nothing. cfn-signal is deliberately not used here (it would', '# prove nothing about READINESS, which is the argument recorded below),', '# but that argument never covered a boot-SCRIPT failure: `cdk deploy`', '# reported success while publishes queued on EFS, the auth cache went', '# stale and PRs stopped being created, until a human noticed the admin', '# panel showing the worker absent.', '#', '# Shutting down makes the instance fail its EC2 health check, so the ASG', '# replaces it -- which is the only automatic recovery available in this', '# topology. The echo lands in the console log, readable via', '# `aws ec2 get-console-output`, because the CloudWatch agent is itself', '# configured further down and cannot be relied on to exist yet.', 'trap \'echo "canopy-worker user-data FAILED at line $LINENO (exit $?)" >&2; shutdown -h now\' ERR', '', '# Bounded retry for the network-dependent steps. Package mirrors and S3', '# have transient failures; a single flake should cost seconds, not an', '# instance replacement.', 'retry() {', ' local n=0', ' until "$@"; do', ' n=$((n + 1))', ' if [ "$n" -ge 5 ]; then', ' echo "canopy-worker: command failed after $n attempts: $*" >&2', ' return 1', ' fi', ' sleep $((n * 5))', ' done', '}', '', '# Install dependencies (unzip is not guaranteed in the AL2023 AMI)', 'retry dnf install -y git unzip', "# Node comes from AL2023's own repos, NOT a piped third-party installer.", '# The previous boot curled the NodeSource RPM setup script straight into', '# bash, so every instance replacement -- which the ASG performs on every', '# `cdk deploy`, plus every spot interruption -- depended on a third party', '# being reachable. cms-deploy.test.ts asserts that URL never comes back,', '# which is why it is not spelled out here.', '#', '# nodejs22, not 20: Node 20 reached upstream EOL on 2026-04-30, and this', '# repo declares `engines.node: ">=22"` with .nvmrc `v22`, so the worker', '# was running an EOL runtime BELOW the floor its own code is tested at.', "# 22 (EOL 2027-04-30) matches .nvmrc, CI, and the transform Lambda's", '# NODEJS_22_X, so one runtime is tested everywhere.', '#', '# ExecStart uses the NAMESPACED /usr/bin/node-22 (see the systemd unit', '# below), not the bare `node`: AL2023 installs versioned binaries and', '# points `/usr/bin/node` at one of them through `alternatives`, whose', '# selection AWS documents as able to change at any time.', 'retry dnf install -y nodejs22', '', '# Mount EFS through the same access point, at the same path, as the', '# Lambda (see EFS_MOUNT_PATH). amazon-efs-utils refuses an access-point', '# mount without tls (efs_utils_common/mount_options.py).', 'retry dnf install -y amazon-efs-utils', `mkdir -p ${EFS_MOUNT_PATH}`, `mount -t efs -o ${efsMountOptions} ${this.fileSystem.fileSystemId}:/ ${EFS_MOUNT_PATH}`, '# Persist the mount across instance reboots: user-data runs once per', '# instance, so without an fstab entry a plain reboot leaves /mnt/efs an', '# empty local dir and the worker would clone a divergent remote.git', '# onto the instance disk, invisible to the Lambda.', `echo '${this.fileSystem.fileSystemId}:/ ${EFS_MOUNT_PATH} efs _netdev,${efsMountOptions} 0 0' >> /etc/fstab`, '', '# Download worker from CDK S3 Asset', `retry aws s3 cp s3://${workerAsset.s3BucketName}/${workerAsset.s3ObjectKey} /tmp/canopy-worker.zip`, 'mkdir -p /opt/canopy-worker', 'cd /opt/canopy-worker', 'unzip -o /tmp/canopy-worker.zip', '# The worker bundle is ESM (esbuild --format=esm). Without this marker a', '# .js file is CommonJS by default and the import statement fails.', '# Node >=22.7 auto-detects module syntax and would mask its absence, and', '# this instance now runs node-22 -- so the marker is kept BECAUSE that', '# auto-detection is a fallback we should not depend on, not because the', '# runtime here still needs it.', `echo '{"type":"module"}' > /opt/canopy-worker/package.json`, '', '# Write environment file for systemd service', `cat > /opt/canopy-worker/.env << 'ENVEOF'`, envFileContent, 'ENVEOF', '', '# Create systemd service', `cat > /etc/systemd/system/canopy-worker.service << 'SVCEOF'`, '[Unit]', 'Description=CanopyCMS Worker Daemon', 'After=network.target', '# Never run against an unmounted /mnt/efs (see the fstab note above).', `RequiresMountsFor=${EFS_MOUNT_PATH}`, '', '[Service]', 'Type=simple', 'User=ec2-user', 'WorkingDirectory=/opt/canopy-worker', '# Namespaced binary, not bare `node`: AL2023 points /usr/bin/node at', '# an installed version through `alternatives`, and AWS documents that', '# selection as able to change at any time. node-22 always means 22.', 'ExecStart=/usr/bin/node-22 index.js', 'Restart=always', 'RestartSec=5', 'TimeoutStartSec=300', '# File output, not journal: the CloudWatch agent cannot read journald,', '# so it tails this file instead (see the agent config below).', '# CAUTION: /var/log/canopy-worker must exist BEFORE first start. systemd', '# opens append: targets before it creates LogsDirectory= dirs', '# (systemd#27591), so without the pre-created dir the exec fails with', '# 209/STDOUT and Restart=always crash-loops forever. User-data runs', '# mkdir before systemctl start; LogsDirectory= is kept for ownership.', 'LogsDirectory=canopy-worker', 'StandardOutput=append:/var/log/canopy-worker/worker.log', 'StandardError=append:/var/log/canopy-worker/worker.log', 'EnvironmentFile=/opt/canopy-worker/.env', '', '[Install]', 'WantedBy=multi-user.target', 'SVCEOF', '', '# Set ownership for ec2-user', 'chown -R ec2-user:ec2-user /opt/canopy-worker', '', '# Pre-create the worker log dir (crash-loop guard, MUST precede the', '# first systemctl start): systemd opens StandardOutput=append: files', '# BEFORE it creates LogsDirectory= dirs (systemd#27591), so on a fresh', '# instance the unit would fail exec with 209/STDOUT and crash-loop', '# forever without this. The unit keeps LogsDirectory= for ownership', '# management on subsequent starts.', 'mkdir -p /var/log/canopy-worker', 'chown ec2-user:ec2-user /var/log/canopy-worker', '', '# Start worker', 'systemctl daemon-reload', 'systemctl enable canopy-worker', 'systemctl start canopy-worker', '', '# ---- CloudWatch log shipping ----', '# Placed AFTER worker start: with set -euo pipefail, a package/agent', '# failure here must not prevent the worker from running (shipping is', '# best-effort).', '#', '# DISARM THE FAIL-FAST TRAP AND errexit FIRST. Everything above this line', '# is required for the worker to exist at all, so a failure there should', '# replace the instance. Nothing below it is: the worker is already', '# running and healthy by this point. Leaving the trap armed would let a', '# package-mirror outage during the agent install shut down a perfectly', '# good worker -- and the ASG would relaunch straight into the same', '# outage, turning degraded log shipping into a replacement loop with the', '# worker down for its duration. That is strictly worse than the', '# best-effort behaviour this section has always documented.', 'trap - ERR', 'set +e', 'retry dnf install -y amazon-cloudwatch-agent logrotate', '', '# Bound on-disk growth; copytruncate keeps the fd the CW agent tails valid', '# (tiny copy->truncate loss window is acceptable for diagnostic logs).', `cat > /etc/logrotate.d/canopy-worker << 'ROTEOF'`, '/var/log/canopy-worker/worker.log {', ' size 10M', ' rotate 5', ' compress', ' copytruncate', ' missingok', ' notifempty', '}', 'ROTEOF', '# The config above only fires when logrotate actually runs; AL2023', '# presets may leave logrotate.timer disabled, and without it the size', '# cap never triggers and worker.log grows until the nano disk fills.', '# --now is idempotent if the timer is already enabled/running.', 'systemctl enable --now logrotate.timer', '', '# No retention_in_days here: CDK owns retention on the pre-created group.', `cat > /opt/aws/amazon-cloudwatch-agent/etc/canopy-worker-logs.json << 'CWEOF'`, '{', ' "logs": {', ' "logs_collected": {', ' "files": {', ' "collect_list": [', ' {', ' "file_path": "/var/log/canopy-worker/worker.log",', ` "log_group_name": "${this.workerLogGroup.logGroupName}",`, ' "log_stream_name": "{instance_id}",',
|
|
890
919
|
// The worker prefixes every line with an ISO-8601 timestamp
|
|
891
920
|
// (packages/canopycms/src/worker/log.ts). Parsing it here is what makes
|
|
892
921
|
// CloudWatch show the time the WORKER emitted a line rather than the
|
|
@@ -986,4 +1015,27 @@ export class CanopyCmsService extends Construct {
|
|
|
986
1015
|
// EC2-health-checked ASG never notices.
|
|
987
1016
|
this.workerAsg.node.addDependency(this.fileSystem.mountTargetsAvailable);
|
|
988
1017
|
}
|
|
1018
|
+
/**
|
|
1019
|
+
* Serve the editor from a CloudFront distribution you already own, such as
|
|
1020
|
+
* the site's: adds `/edit`, `/edit/*` and `/api/canopycms/*` behaviors
|
|
1021
|
+
* (plus any `previewPrefix` and `editorAssetPrefix` routes) to this
|
|
1022
|
+
* service's Function URL, behind OAC, with
|
|
1023
|
+
* an origin read timeout equal to {@link timeout}, no caching, the whole
|
|
1024
|
+
* viewer request forwarded, an `x-forwarded-host` viewer-request function and
|
|
1025
|
+
* the editor's response headers policy (framing protection, `noindex`).
|
|
1026
|
+
*
|
|
1027
|
+
* The behaviors are appended. Synth fails if a behavior listed before them
|
|
1028
|
+
* matches an editor route, since CloudFront would never reach the editor's.
|
|
1029
|
+
* It warns when the distribution has custom error responses, which also
|
|
1030
|
+
* rewrite the API's errors.
|
|
1031
|
+
*
|
|
1032
|
+
* Pass `editorAssetPrefix` with the CMS build's Next `assetPrefix`, so the
|
|
1033
|
+
* editor's chunks stay out of the site's `/_next/static/*`, and
|
|
1034
|
+
* `previewPrefix` with a static-export site's preview route.
|
|
1035
|
+
* `AssetSupport.attachTo` adds `/assets/*`. Use `CanopyCmsDistribution`
|
|
1036
|
+
* instead when the CMS gets a domain of its own.
|
|
1037
|
+
*/
|
|
1038
|
+
attachTo(distribution, options) {
|
|
1039
|
+
attachEditorBehaviors(distribution, this.functionUrl, this.timeout, options);
|
|
1040
|
+
}
|
|
989
1041
|
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Construct } from 'constructs';
|
|
2
|
+
import { Duration, aws_cloudfront as cloudfront, aws_lambda as lambda } from 'aws-cdk-lib';
|
|
3
|
+
/** CloudFront's maximum origin read timeout without a service-quota increase. */
|
|
4
|
+
export declare const MAX_CLOUDFRONT_ORIGIN_READ_TIMEOUT: Duration;
|
|
5
|
+
/**
|
|
6
|
+
* The routes the editor needs from the CMS Lambda on a distribution it shares
|
|
7
|
+
* with a site: the editor page and the catch-all API route `canopycms init`
|
|
8
|
+
* scaffolds. `/edit` and `/edit/*` rather than `/edit*`, which also matches
|
|
9
|
+
* `/editorial` and `/edit-assets/…` and so takes site pages away from the site.
|
|
10
|
+
*
|
|
11
|
+
* Not included, because on a shared distribution they belong to the site:
|
|
12
|
+
* `/_next/static/*` (the CMS build moves its chunks out of it with Next's
|
|
13
|
+
* `assetPrefix`; see `editorAssetPrefix`) and `/assets/*`
|
|
14
|
+
* (`AssetSupport.attachTo` owns it).
|
|
15
|
+
*/
|
|
16
|
+
export declare const EDITOR_PATH_PATTERNS: readonly ["/edit", "/edit/*", "/api/canopycms/*"];
|
|
17
|
+
/**
|
|
18
|
+
* Whether a CloudFront path pattern matches a request path: `*` is any run of
|
|
19
|
+
* characters, `?` exactly one, matching is case-sensitive, and the pattern's
|
|
20
|
+
* leading `/` is optional.
|
|
21
|
+
*/
|
|
22
|
+
export declare function cloudFrontPathPatternMatches(pattern: string, path: string): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Throws when the origin read timeout exceeds the 60s CloudFront accepts
|
|
25
|
+
* without a quota increase, which it would reject at deploy. Neither construct
|
|
26
|
+
* takes a higher, quota-raised value.
|
|
27
|
+
*/
|
|
28
|
+
export declare function assertOriginReadTimeout(readTimeout: Duration, owner: string): void;
|
|
29
|
+
/**
|
|
30
|
+
* The viewer-request function every Lambda behavior needs. CloudFront gives
|
|
31
|
+
* the origin the Function URL's own Host (forwarding the viewer Host would
|
|
32
|
+
* break the OAC SigV4 signature), and Lambda Web Adapter adds no
|
|
33
|
+
* `x-forwarded-*` headers, so without this Clerk/Next derive sign-in redirect
|
|
34
|
+
* URLs from the IAM-authed Function URL host and the redirect 403s.
|
|
35
|
+
*
|
|
36
|
+
* Only `x-forwarded-host`: `x-forwarded-proto` is on CloudFront Functions'
|
|
37
|
+
* disallowed list and setting it fails every request with a 502. The viewer
|
|
38
|
+
* side is HTTPS-only, so proto is unambiguous anyway.
|
|
39
|
+
*/
|
|
40
|
+
export declare function createForwardedHostFunction(scope: Construct, id: string): cloudfront.Function;
|
|
41
|
+
/**
|
|
42
|
+
* Response headers for everything the CMS Lambda serves.
|
|
43
|
+
*
|
|
44
|
+
* - `frame-ancestors 'self'` (plus `X-Frame-Options: SAMEORIGIN` for browsers
|
|
45
|
+
* that ignore it) stops other sites framing the editor. `'self'` keeps the
|
|
46
|
+
* editor's own preview iframe working, which frames same-origin site pages.
|
|
47
|
+
* - Both framing headers have `override: false`, so an origin that sends its
|
|
48
|
+
* own CSP keeps it whole; when that CSP has no `frame-ancestors` and the
|
|
49
|
+
* origin sends no `X-Frame-Options`, this one applies.
|
|
50
|
+
* - `X-Robots-Tag: noindex` overrides: nothing the Lambda serves is meant to
|
|
51
|
+
* be indexed.
|
|
52
|
+
* - No `Cross-Origin-Opener-Policy`: it can cut the `window.opener` link a
|
|
53
|
+
* popup-based OAuth sign-in reports back through.
|
|
54
|
+
*/
|
|
55
|
+
export declare function createEditorResponseHeadersPolicy(scope: Construct, id: string): cloudfront.ResponseHeadersPolicy;
|
|
56
|
+
/**
|
|
57
|
+
* A year-long cache for content-hashed build output. The cache key carries no
|
|
58
|
+
* header, cookie or query string, so every viewer shares one copy.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createStaticCachePolicy(scope: Construct, id: string): cloudfront.CachePolicy;
|
|
61
|
+
/**
|
|
62
|
+
* Behavior options for a route the CMS Lambda serves. The managed
|
|
63
|
+
* CACHING_DISABLED policy as it is: CloudFront rejects any non-none cache-key
|
|
64
|
+
* setting on a caching-disabled policy, and the origin still gets the whole
|
|
65
|
+
* viewer request (headers, cookies, query string, minus Host, which would
|
|
66
|
+
* break the OAC signature) through ALL_VIEWER_EXCEPT_HOST_HEADER.
|
|
67
|
+
*/
|
|
68
|
+
export declare function lambdaBehaviorOptions(viewerRequestFunction: cloudfront.FunctionAssociation['function'] | undefined, responseHeadersPolicy: NonNullable<cloudfront.AddBehaviorOptions['responseHeadersPolicy']>): cloudfront.AddBehaviorOptions;
|
|
69
|
+
/** Options for `CanopyCmsService.attachTo`. */
|
|
70
|
+
export interface CanopyCmsAttachOptions {
|
|
71
|
+
/**
|
|
72
|
+
* Viewer-request function for the editor behaviors, in place of the
|
|
73
|
+
* `x-forwarded-host` function `attachTo` otherwise creates. CloudFront allows
|
|
74
|
+
* one per behavior, so pass this when the distribution's own function must
|
|
75
|
+
* run on every route.
|
|
76
|
+
*
|
|
77
|
+
* It must set `x-forwarded-host` from the viewer's Host, or sign-in
|
|
78
|
+
* redirects point at the Function URL and 403. It must not gate on HTTP
|
|
79
|
+
* Basic auth: the API answers 401 without `WWW-Authenticate`, and a browser
|
|
80
|
+
* that sees that drops its cached Basic credential and prompts again.
|
|
81
|
+
*
|
|
82
|
+
* @default - a function that sets `x-forwarded-host` and nothing else
|
|
83
|
+
*/
|
|
84
|
+
viewerRequestFunction?: cloudfront.IFunction;
|
|
85
|
+
/**
|
|
86
|
+
* Options merged into the editor and preview behaviors, after this construct's
|
|
87
|
+
* own; keys whose value is `undefined` are ignored. A `responseHeadersPolicy`
|
|
88
|
+
* here replaces the editor's framing protection, so it must carry its own.
|
|
89
|
+
* `functionAssociations` here replaces the viewer-request function as well,
|
|
90
|
+
* which is why it cannot be combined with `viewerRequestFunction`.
|
|
91
|
+
*
|
|
92
|
+
* @default - no overrides
|
|
93
|
+
*/
|
|
94
|
+
behaviorOverrides?: Partial<cloudfront.AddBehaviorOptions>;
|
|
95
|
+
/**
|
|
96
|
+
* The CMS build's Next `assetPrefix`, such as `'/edit-assets'`: adds a
|
|
97
|
+
* `/<prefix>/*` behavior to the Lambda with a year-long cache, since the
|
|
98
|
+
* chunks under it are content-hashed.
|
|
99
|
+
*
|
|
100
|
+
* A CMS build that shares a distribution with a static site needs one.
|
|
101
|
+
* Without it the editor page loads its chunks from `/_next/static/*`, which
|
|
102
|
+
* the site serves, and they 404. Set `assetPrefix` in the CMS build's
|
|
103
|
+
* `next.config` only (not the static export's) and pass the same value here.
|
|
104
|
+
*
|
|
105
|
+
* A path starting with `/`, without a trailing `/` or wildcards, and
|
|
106
|
+
* overlapping neither the editor's routes, `/_next/*` nor AssetSupport's
|
|
107
|
+
* `/assets/*`. Of `behaviorOverrides`, only `responseHeadersPolicy` applies
|
|
108
|
+
* to this behavior.
|
|
109
|
+
*
|
|
110
|
+
* @default - no asset-prefix behavior
|
|
111
|
+
*/
|
|
112
|
+
editorAssetPrefix?: string;
|
|
113
|
+
/**
|
|
114
|
+
* The path of the CMS-only preview route, the same value as
|
|
115
|
+
* `editor.previewPrefix` in the CanopyCMS config (e.g. `'/preview'`): adds
|
|
116
|
+
* `<prefix>` and `<prefix>/*` behaviors with the editor routes' options, so
|
|
117
|
+
* the editor's preview pane reaches the CMS rather than the site.
|
|
118
|
+
*
|
|
119
|
+
* Validated like `editorAssetPrefix`, and must not overlap it either. An
|
|
120
|
+
* absolute `https://` `previewPrefix` is another origin and needs nothing
|
|
121
|
+
* here.
|
|
122
|
+
*
|
|
123
|
+
* @default - no preview behaviors
|
|
124
|
+
*/
|
|
125
|
+
previewPrefix?: string;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Attach the editor's behaviors to a distribution. See
|
|
129
|
+
* `CanopyCmsService.attachTo`, which is the public entry point.
|
|
130
|
+
*/
|
|
131
|
+
export declare function attachEditorBehaviors(distribution: cloudfront.Distribution, functionUrl: lambda.IFunctionUrl, readTimeout: Duration, options?: CanopyCmsAttachOptions): void;
|