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
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { Construct } from 'constructs';
|
|
2
|
+
import { Annotations, Duration, Stack, aws_cloudfront as cloudfront, aws_cloudfront_origins as origins, } from 'aws-cdk-lib';
|
|
3
|
+
import { ASSETS_PATH_PATTERN, ASSETS_TRANSFORM_PATH_PATTERN } from './asset-support.js';
|
|
4
|
+
/** CloudFront's maximum origin read timeout without a service-quota increase. */
|
|
5
|
+
export const MAX_CLOUDFRONT_ORIGIN_READ_TIMEOUT = Duration.seconds(60);
|
|
6
|
+
/**
|
|
7
|
+
* The routes the editor needs from the CMS Lambda on a distribution it shares
|
|
8
|
+
* with a site: the editor page and the catch-all API route `canopycms init`
|
|
9
|
+
* scaffolds. `/edit` and `/edit/*` rather than `/edit*`, which also matches
|
|
10
|
+
* `/editorial` and `/edit-assets/…` and so takes site pages away from the site.
|
|
11
|
+
*
|
|
12
|
+
* Not included, because on a shared distribution they belong to the site:
|
|
13
|
+
* `/_next/static/*` (the CMS build moves its chunks out of it with Next's
|
|
14
|
+
* `assetPrefix`; see `editorAssetPrefix`) and `/assets/*`
|
|
15
|
+
* (`AssetSupport.attachTo` owns it).
|
|
16
|
+
*/
|
|
17
|
+
export const EDITOR_PATH_PATTERNS = ['/edit', '/edit/*', '/api/canopycms/*'];
|
|
18
|
+
/**
|
|
19
|
+
* One request path per editor pattern that only that pattern serves. A
|
|
20
|
+
* behavior listed earlier that matches any of these takes the request first.
|
|
21
|
+
*/
|
|
22
|
+
const EDITOR_PROBE_PATHS = {
|
|
23
|
+
'/edit': ['/edit'],
|
|
24
|
+
'/edit/*': ['/edit/', '/edit/x'],
|
|
25
|
+
'/api/canopycms/*': ['/api/canopycms/x'],
|
|
26
|
+
};
|
|
27
|
+
const EDITOR_ROUTES = EDITOR_PATH_PATTERNS.map((pattern) => ({
|
|
28
|
+
pattern,
|
|
29
|
+
probes: EDITOR_PROBE_PATHS[pattern],
|
|
30
|
+
}));
|
|
31
|
+
/** Patterns a prefix option must not overlap in either direction. */
|
|
32
|
+
const RESERVED_ROUTES = [
|
|
33
|
+
...EDITOR_ROUTES,
|
|
34
|
+
{ pattern: '/_next/*', probes: ['/_next/x'] },
|
|
35
|
+
{ pattern: ASSETS_TRANSFORM_PATH_PATTERN, probes: ['/assets/t/x'] },
|
|
36
|
+
{ pattern: ASSETS_PATH_PATTERN, probes: ['/assets/x'] },
|
|
37
|
+
];
|
|
38
|
+
/** Id of the marker construct `attachEditorBehaviors` adds to the distribution. */
|
|
39
|
+
const EDITOR_ATTACHED_MARKER_ID = 'CanopyEditorBehaviorsAttached';
|
|
40
|
+
/**
|
|
41
|
+
* Whether a CloudFront path pattern matches a request path: `*` is any run of
|
|
42
|
+
* characters, `?` exactly one, matching is case-sensitive, and the pattern's
|
|
43
|
+
* leading `/` is optional.
|
|
44
|
+
*/
|
|
45
|
+
export function cloudFrontPathPatternMatches(pattern, path) {
|
|
46
|
+
const glob = pattern.startsWith('/') ? pattern : `/${pattern}`;
|
|
47
|
+
// Greedy wildcard match: on a mismatch, let the most recent `*` absorb one
|
|
48
|
+
// more character and retry from there.
|
|
49
|
+
let g = 0;
|
|
50
|
+
let p = 0;
|
|
51
|
+
let star = -1;
|
|
52
|
+
let resume = 0;
|
|
53
|
+
while (p < path.length) {
|
|
54
|
+
if (g < glob.length && (glob[g] === '?' || glob[g] === path[p])) {
|
|
55
|
+
g++;
|
|
56
|
+
p++;
|
|
57
|
+
}
|
|
58
|
+
else if (g < glob.length && glob[g] === '*') {
|
|
59
|
+
star = g++;
|
|
60
|
+
resume = p;
|
|
61
|
+
}
|
|
62
|
+
else if (star !== -1) {
|
|
63
|
+
g = star + 1;
|
|
64
|
+
p = ++resume;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
while (glob[g] === '*')
|
|
71
|
+
g++;
|
|
72
|
+
return g === glob.length;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Throws when the origin read timeout exceeds the 60s CloudFront accepts
|
|
76
|
+
* without a quota increase, which it would reject at deploy. Neither construct
|
|
77
|
+
* takes a higher, quota-raised value.
|
|
78
|
+
*/
|
|
79
|
+
export function assertOriginReadTimeout(readTimeout, owner) {
|
|
80
|
+
if (readTimeout.toSeconds() > MAX_CLOUDFRONT_ORIGIN_READ_TIMEOUT.toSeconds()) {
|
|
81
|
+
throw new Error(`${owner}: originReadTimeout is ${readTimeout.toSeconds()}s, but CloudFront ` +
|
|
82
|
+
`allows at most ${MAX_CLOUDFRONT_ORIGIN_READ_TIMEOUT.toSeconds()}s without a service-quota ` +
|
|
83
|
+
`increase, and these constructs do not take a higher value. Lower the CMS Lambda's ` +
|
|
84
|
+
`timeout to ${MAX_CLOUDFRONT_ORIGIN_READ_TIMEOUT.toSeconds()}s or less. A shorter origin ` +
|
|
85
|
+
`timeout than the Lambda's would 504 at the edge on requests that actually succeed.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The viewer-request function every Lambda behavior needs. CloudFront gives
|
|
90
|
+
* the origin the Function URL's own Host (forwarding the viewer Host would
|
|
91
|
+
* break the OAC SigV4 signature), and Lambda Web Adapter adds no
|
|
92
|
+
* `x-forwarded-*` headers, so without this Clerk/Next derive sign-in redirect
|
|
93
|
+
* URLs from the IAM-authed Function URL host and the redirect 403s.
|
|
94
|
+
*
|
|
95
|
+
* Only `x-forwarded-host`: `x-forwarded-proto` is on CloudFront Functions'
|
|
96
|
+
* disallowed list and setting it fails every request with a 502. The viewer
|
|
97
|
+
* side is HTTPS-only, so proto is unambiguous anyway.
|
|
98
|
+
*/
|
|
99
|
+
export function createForwardedHostFunction(scope, id) {
|
|
100
|
+
return new cloudfront.Function(scope, id, {
|
|
101
|
+
code: cloudfront.FunctionCode.fromInline([
|
|
102
|
+
'function handler(event) {',
|
|
103
|
+
' var request = event.request;',
|
|
104
|
+
" request.headers['x-forwarded-host'] = { value: request.headers.host.value };",
|
|
105
|
+
' return request;',
|
|
106
|
+
'}',
|
|
107
|
+
].join('\n')),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Response headers for everything the CMS Lambda serves.
|
|
112
|
+
*
|
|
113
|
+
* - `frame-ancestors 'self'` (plus `X-Frame-Options: SAMEORIGIN` for browsers
|
|
114
|
+
* that ignore it) stops other sites framing the editor. `'self'` keeps the
|
|
115
|
+
* editor's own preview iframe working, which frames same-origin site pages.
|
|
116
|
+
* - Both framing headers have `override: false`, so an origin that sends its
|
|
117
|
+
* own CSP keeps it whole; when that CSP has no `frame-ancestors` and the
|
|
118
|
+
* origin sends no `X-Frame-Options`, this one applies.
|
|
119
|
+
* - `X-Robots-Tag: noindex` overrides: nothing the Lambda serves is meant to
|
|
120
|
+
* be indexed.
|
|
121
|
+
* - No `Cross-Origin-Opener-Policy`: it can cut the `window.opener` link a
|
|
122
|
+
* popup-based OAuth sign-in reports back through.
|
|
123
|
+
*/
|
|
124
|
+
export function createEditorResponseHeadersPolicy(scope, id) {
|
|
125
|
+
return new cloudfront.ResponseHeadersPolicy(scope, id, {
|
|
126
|
+
securityHeadersBehavior: {
|
|
127
|
+
contentSecurityPolicy: { contentSecurityPolicy: "frame-ancestors 'self'", override: false },
|
|
128
|
+
frameOptions: { frameOption: cloudfront.HeadersFrameOption.SAMEORIGIN, override: false },
|
|
129
|
+
contentTypeOptions: { override: true },
|
|
130
|
+
strictTransportSecurity: {
|
|
131
|
+
accessControlMaxAge: Duration.days(365),
|
|
132
|
+
includeSubdomains: false,
|
|
133
|
+
override: false,
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
customHeadersBehavior: {
|
|
137
|
+
customHeaders: [{ header: 'X-Robots-Tag', value: 'noindex', override: true }],
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* A year-long cache for content-hashed build output. The cache key carries no
|
|
143
|
+
* header, cookie or query string, so every viewer shares one copy.
|
|
144
|
+
*/
|
|
145
|
+
export function createStaticCachePolicy(scope, id) {
|
|
146
|
+
return new cloudfront.CachePolicy(scope, id, {
|
|
147
|
+
defaultTtl: Duration.days(365),
|
|
148
|
+
maxTtl: Duration.days(365),
|
|
149
|
+
minTtl: Duration.days(365),
|
|
150
|
+
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
|
|
151
|
+
queryStringBehavior: cloudfront.CacheQueryStringBehavior.none(),
|
|
152
|
+
cookieBehavior: cloudfront.CacheCookieBehavior.none(),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Behavior options for a route the CMS Lambda serves. The managed
|
|
157
|
+
* CACHING_DISABLED policy as it is: CloudFront rejects any non-none cache-key
|
|
158
|
+
* setting on a caching-disabled policy, and the origin still gets the whole
|
|
159
|
+
* viewer request (headers, cookies, query string, minus Host, which would
|
|
160
|
+
* break the OAC signature) through ALL_VIEWER_EXCEPT_HOST_HEADER.
|
|
161
|
+
*/
|
|
162
|
+
export function lambdaBehaviorOptions(viewerRequestFunction, responseHeadersPolicy) {
|
|
163
|
+
return {
|
|
164
|
+
cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
|
|
165
|
+
originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
|
|
166
|
+
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
|
|
167
|
+
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
|
|
168
|
+
responseHeadersPolicy,
|
|
169
|
+
functionAssociations: viewerRequestFunction && [
|
|
170
|
+
{ function: viewerRequestFunction, eventType: cloudfront.FunctionEventType.VIEWER_REQUEST },
|
|
171
|
+
],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* The routes a prefix option adds, after refusing a prefix that is not a
|
|
176
|
+
* plain path below the root or that overlaps `reserved` in either direction.
|
|
177
|
+
*/
|
|
178
|
+
function prefixRoutes(option, prefix, reserved) {
|
|
179
|
+
const fail = (reason) => new Error(`CanopyCmsService.attachTo: ${option} '${prefix}' ${reason}.`);
|
|
180
|
+
if (!prefix.startsWith('/') || prefix === '/') {
|
|
181
|
+
throw fail("must start with '/' and name a path below the root");
|
|
182
|
+
}
|
|
183
|
+
if (prefix.endsWith('/'))
|
|
184
|
+
throw fail("must not end with a trailing '/'");
|
|
185
|
+
// CloudFront collapses `//` in request paths, so a pattern holding one never matches.
|
|
186
|
+
if (prefix.includes('//'))
|
|
187
|
+
throw fail("must not contain '//'");
|
|
188
|
+
if (/[*?]/.test(prefix))
|
|
189
|
+
throw fail('must not contain * or ?, which CloudFront reads as wildcards');
|
|
190
|
+
if (!/^[A-Za-z0-9_\-.$/~"'@:+&]+$/.test(prefix)) {
|
|
191
|
+
throw fail(`may hold only the characters CloudFront allows in a path pattern: A-Z a-z 0-9 _-.$/~"'@:+&`);
|
|
192
|
+
}
|
|
193
|
+
const routes = option === 'previewPrefix'
|
|
194
|
+
? [
|
|
195
|
+
{ pattern: prefix, probes: [prefix] },
|
|
196
|
+
{ pattern: `${prefix}/*`, probes: [`${prefix}/`, `${prefix}/x`] },
|
|
197
|
+
]
|
|
198
|
+
: [{ pattern: `${prefix}/*`, probes: [`${prefix}/x`] }];
|
|
199
|
+
const overlaps = (a, b) => b.probes.some((path) => cloudFrontPathPatternMatches(a.pattern, path));
|
|
200
|
+
const clash = reserved.find((route) => routes.some((own) => overlaps(route, own) || overlaps(own, route)));
|
|
201
|
+
if (clash) {
|
|
202
|
+
throw fail(`overlaps '${clash.pattern}', so CloudFront would send one route's requests to the ` +
|
|
203
|
+
`other's behavior. Pick a prefix of its own, such as '/edit-assets' or '/preview'`);
|
|
204
|
+
}
|
|
205
|
+
return routes;
|
|
206
|
+
}
|
|
207
|
+
function isRecord(value) {
|
|
208
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
209
|
+
}
|
|
210
|
+
/** One list from a distribution's L1 config, resolved but still camelCased. */
|
|
211
|
+
function resolvedConfigList(distribution, field) {
|
|
212
|
+
const cfn = distribution.node.defaultChild;
|
|
213
|
+
if (!(cfn instanceof cloudfront.CfnDistribution))
|
|
214
|
+
return [];
|
|
215
|
+
const config = cfn.distributionConfig;
|
|
216
|
+
if (!isRecord(config))
|
|
217
|
+
return [];
|
|
218
|
+
const list = Stack.of(distribution).resolve(config[field]);
|
|
219
|
+
return Array.isArray(list) ? list.filter(isRecord) : [];
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Error messages for every behavior that CloudFront would match before one of
|
|
223
|
+
* the editor's, which leaves that editor route unreachable.
|
|
224
|
+
*/
|
|
225
|
+
function shadowedEditorRoutes(distribution, routes) {
|
|
226
|
+
const patterns = resolvedConfigList(distribution, 'cacheBehaviors')
|
|
227
|
+
.map((behavior) => behavior.pathPattern)
|
|
228
|
+
.filter((pattern) => typeof pattern === 'string');
|
|
229
|
+
const errors = [];
|
|
230
|
+
for (const { pattern: editorPattern, probes } of routes) {
|
|
231
|
+
// The last occurrence, so a duplicate of an editor pattern on either side
|
|
232
|
+
// of it is reported too.
|
|
233
|
+
const index = patterns.lastIndexOf(editorPattern);
|
|
234
|
+
const shadow = patterns
|
|
235
|
+
.slice(0, index)
|
|
236
|
+
.find((earlier) => probes.some((path) => cloudFrontPathPatternMatches(earlier, path)));
|
|
237
|
+
if (index !== -1 && shadow !== undefined) {
|
|
238
|
+
errors.push(`CanopyCmsService.attachTo: the distribution's '${shadow}' behavior is listed before ` +
|
|
239
|
+
`the editor's '${editorPattern}' and matches the same requests, so CloudFront never ` +
|
|
240
|
+
`reaches the editor behavior. Remove hand-wired editor behaviors (such as '/edit*') ` +
|
|
241
|
+
`and let attachTo add them.`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return errors;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* The status codes of custom error responses that replace the origin's
|
|
248
|
+
* response. A TTL-only entry changes caching, not the response.
|
|
249
|
+
*/
|
|
250
|
+
function rewrittenErrorCodes(distribution) {
|
|
251
|
+
return resolvedConfigList(distribution, 'customErrorResponses')
|
|
252
|
+
.filter((entry) => entry.responseCode !== undefined || entry.responsePagePath !== undefined)
|
|
253
|
+
.map((entry) => entry.errorCode)
|
|
254
|
+
.filter((code) => typeof code === 'number');
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Attach the editor's behaviors to a distribution. See
|
|
258
|
+
* `CanopyCmsService.attachTo`, which is the public entry point.
|
|
259
|
+
*/
|
|
260
|
+
export function attachEditorBehaviors(distribution, functionUrl, readTimeout, options = {}) {
|
|
261
|
+
if (distribution.node.tryFindChild(EDITOR_ATTACHED_MARKER_ID)) {
|
|
262
|
+
throw new Error('CanopyCmsService: attachTo() was already called for this distribution. Each editor ' +
|
|
263
|
+
'pattern would be attached twice and CloudFront rejects duplicate path patterns at ' +
|
|
264
|
+
'deploy time.');
|
|
265
|
+
}
|
|
266
|
+
if (options.viewerRequestFunction && options.behaviorOverrides?.functionAssociations) {
|
|
267
|
+
throw new Error('CanopyCmsService.attachTo: pass viewerRequestFunction or ' +
|
|
268
|
+
'behaviorOverrides.functionAssociations, not both. The overrides replace the whole ' +
|
|
269
|
+
'functionAssociations list, so the viewerRequestFunction would be silently dropped.');
|
|
270
|
+
}
|
|
271
|
+
assertOriginReadTimeout(readTimeout, 'CanopyCmsService.attachTo');
|
|
272
|
+
const assetRoutes = options.editorAssetPrefix === undefined
|
|
273
|
+
? []
|
|
274
|
+
: prefixRoutes('editorAssetPrefix', options.editorAssetPrefix, RESERVED_ROUTES);
|
|
275
|
+
const previewRoutes = options.previewPrefix === undefined
|
|
276
|
+
? []
|
|
277
|
+
: prefixRoutes('previewPrefix', options.previewPrefix, [...RESERVED_ROUTES, ...assetRoutes]);
|
|
278
|
+
const marker = new Construct(distribution, EDITOR_ATTACHED_MARKER_ID);
|
|
279
|
+
// Scoped to the distribution so everything lands in its stack, which may
|
|
280
|
+
// not be the service's.
|
|
281
|
+
// None at all when the overrides bring their own associations, which would
|
|
282
|
+
// otherwise leave a deployed function associated with nothing.
|
|
283
|
+
const viewerRequestFunction = options.viewerRequestFunction ??
|
|
284
|
+
(options.behaviorOverrides?.functionAssociations
|
|
285
|
+
? undefined
|
|
286
|
+
: createForwardedHostFunction(distribution, 'CanopyEditorForwardedHostFunction'));
|
|
287
|
+
const responseHeadersPolicy = options.behaviorOverrides?.responseHeadersPolicy ??
|
|
288
|
+
createEditorResponseHeadersPolicy(distribution, 'CanopyEditorResponseHeadersPolicy');
|
|
289
|
+
const behavior = lambdaBehaviorOptions(viewerRequestFunction, responseHeadersPolicy);
|
|
290
|
+
const definedOverrides = Object.fromEntries(Object.entries(options.behaviorOverrides ?? {}).filter(([, value]) => value !== undefined));
|
|
291
|
+
const origin = origins.FunctionUrlOrigin.withOriginAccessControl(functionUrl, { readTimeout });
|
|
292
|
+
for (const { pattern } of [...EDITOR_ROUTES, ...previewRoutes]) {
|
|
293
|
+
distribution.addBehavior(pattern, origin, { ...behavior, ...definedOverrides });
|
|
294
|
+
}
|
|
295
|
+
for (const { pattern } of assetRoutes) {
|
|
296
|
+
distribution.addBehavior(pattern, origin, {
|
|
297
|
+
cachePolicy: createStaticCachePolicy(distribution, 'CanopyEditorAssetCachePolicy'),
|
|
298
|
+
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
|
|
299
|
+
responseHeadersPolicy,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
const routes = [...EDITOR_ROUTES, ...previewRoutes, ...assetRoutes];
|
|
303
|
+
// Custom error responses are fixed at construction, so they are known now.
|
|
304
|
+
const rewritten = rewrittenErrorCodes(distribution);
|
|
305
|
+
if (rewritten.length > 0) {
|
|
306
|
+
Annotations.of(distribution).addWarningV2('canopycms:editor-custom-error-responses', `This distribution rewrites ${rewritten.join(', ')} responses, and CloudFront custom ` +
|
|
307
|
+
`error responses are distribution-wide: they also replace the editor API's JSON errors, ` +
|
|
308
|
+
`so the editor reports "Unexpected response from server" instead of the real error. ` +
|
|
309
|
+
`See "Custom error responses" in docs/deploying-to-aws.md.`);
|
|
310
|
+
}
|
|
311
|
+
// Behaviors can still be added after this call, so shadowing is checked at synth.
|
|
312
|
+
marker.node.addValidation({ validate: () => shadowedEditorRoutes(distribution, routes) });
|
|
313
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export { CmsWorker } from './worker.js';
|
|
|
2
2
|
export type { CmsWorkerConfig } from './worker.js';
|
|
3
3
|
export { CanopyCmsService } from './constructs/cms-service.js';
|
|
4
4
|
export type { CanopyCmsServiceProps } from './constructs/cms-service.js';
|
|
5
|
+
export type { CanopyCmsAttachOptions } from './constructs/editor-routing.js';
|
|
5
6
|
export { CanopyCmsDistribution } from './constructs/cms-distribution.js';
|
|
6
7
|
export type { CanopyCmsDistributionProps } from './constructs/cms-distribution.js';
|
|
7
8
|
export { AssetSupport, assetUploadBehavior } from './constructs/asset-support.js';
|