forked from jinty/prerender-cloudfront
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprerender-cloudfront.yaml
More file actions
205 lines (196 loc) · 8.2 KB
/
prerender-cloudfront.yaml
File metadata and controls
205 lines (196 loc) · 8.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
Parameters:
DeploymentName:
Description: Unique name used to create OAC and cache policy.
Type: String
PrerenderToken:
Type: String
Description: Prerender.io token
Resources:
LambdaEdgeExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
- edgelambda.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: logging
PolicyDocument:
Version: 2012-10-17
Statement:
- Resource: "*"
Effect: Allow
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
SetPrerenderHeader:
Type: "AWS::Lambda::Function"
Properties:
Handler: "index.handler"
Role:
Fn::GetAtt:
- "LambdaEdgeExecutionRole"
- "Arn"
Code:
ZipFile:
!Sub |
'use strict';
/* change the version number below whenever this code is modified */
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const user_agent = headers['user-agent'];
const host = headers['host'];
if (user_agent && host) {
var prerender = /googlebot|adsbot\-google|Feedfetcher\-Google|bingbot|yandex|baiduspider|Facebot|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|redditbot|applebot|whatsapp|flipboard|tumblr|bitlybot|skypeuripreview|nuzzel|discordbot|google page speed|qwantify|pinterestbot|bitrix link preview|xing\-contenttabreceiver|chrome\-lighthouse|telegrambot|Perplexity|OAI-SearchBot|ChatGPT|GPTBot|ClaudeBot|Amazonbot|integration-test/i.test(user_agent[0].value);
prerender = prerender || /_escaped_fragment_/.test(request.querystring);
prerender = prerender && ! /\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)$/i.test(request.uri);
if (prerender) {
headers['x-prerender-token'] = [{ key: 'X-Prerender-Token', value: '${PrerenderToken}'}];
headers['x-prerender-host'] = [{ key: 'X-Prerender-Host', value: host[0].value}];
headers['x-prerender-cachebuster'] = [{ key: 'X-Prerender-Cachebuster', value: Date.now().toString()}];
headers['x-query-string'] = [{ key: 'X-Query-String', value: request.querystring}];
headers['x-user-agent'] = [{ key: 'X-User-Agent', value: user_agent }];
}
}
callback(null, request);
};
Runtime: "nodejs22.x"
SetPrerenderHeaderVersion1:
Type: "AWS::Lambda::Version"
Properties:
FunctionName:
Ref: "SetPrerenderHeader"
Description: "SetPrerenderHeader"
RedirectToPrerender:
Type: "AWS::Lambda::Function"
Properties:
Handler: "index.handler"
Role:
Fn::GetAtt:
- "LambdaEdgeExecutionRole"
- "Arn"
Code:
ZipFile: |
'use strict';
/* change the version number below whenever this code is modified */
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
if (request.headers['x-prerender-token'] && request.headers['x-prerender-host'] && request.headers['x-query-string']) {
request.querystring = request.headers['x-query-string'][0].value;
request.origin = {
custom: {
domainName: 'service.prerender.io',
port: 443,
protocol: 'https',
readTimeout: 20,
keepaliveTimeout: 5,
customHeaders: {},
sslProtocols: ['TLSv1', 'TLSv1.1'],
path: '/https%3A%2F%2F' + request.headers['x-prerender-host'][0].value
}
};
}
callback(null, request);
};
Runtime: "nodejs22.x"
RedirectToPrerenderVersion1:
Type: "AWS::Lambda::Version"
Properties:
FunctionName:
Ref: "RedirectToPrerender"
Description: "RedirectToPrerender"
# Creates a new origin access control. The signing behavior "always" is the most common use case.
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-originaccesscontrol-originaccesscontrolconfig.html
CloudFrontOriginAccessControl:
Type: AWS::CloudFront::OriginAccessControl
Properties:
OriginAccessControlConfig:
Name: !Ref DeploymentName
OriginAccessControlOriginType: s3
SigningBehavior: always
SigningProtocol: sigv4
CloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
CustomErrorResponses:
- ErrorCode: 404
ResponseCode: 404
ResponsePagePath: /404.html
DefaultRootObject: index.html
DefaultCacheBehavior:
Compress: true
# NOTE: we let cloudfront cache heavily the resurces of the SPA. Your deploy
# step will need to include an invalidation of the cloudfromt cache.
# The requests to prerender.io are NOT cached thanks to the X-Prerender-Cachebuster
# header.
MinTTL: 31536000
DefaultTTL: 31536000
ForwardedValues:
QueryString: true
Headers:
- "X-Prerender-Token"
- "X-Prerender-Host"
- "X-Prerender-Cachebuster"
- "X-Query-String"
- "User-Agent"
TargetOriginId: thisS3Origin
ViewerProtocolPolicy: allow-all
LambdaFunctionAssociations:
- EventType: viewer-request
LambdaFunctionARN: !Join [ ":", [ !GetAtt [ SetPrerenderHeader, Arn ], !GetAtt [ SetPrerenderHeaderVersion1, Version ] ] ]
- EventType: origin-request
LambdaFunctionARN: !Join [ ":", [ !GetAtt [ RedirectToPrerender, Arn ], !GetAtt [ RedirectToPrerenderVersion1, Version ] ] ]
Origins:
- DomainName: !GetAtt Bucket.DomainName
Id: thisS3Origin
OriginAccessControlId: !Ref CloudFrontOriginAccessControl
S3OriginConfig:
OriginAccessIdentity: ""
# Creates a new S3 bucket with SSE and public access blocked.
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- BucketKeyEnabled: true
ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
# Creates a bucket policy giving OAC read-only access to the S3 bucket.
# https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref Bucket
PolicyDocument:
Version: 2008-10-17
Statement:
- Sid: AllowCloudFrontServicePrincipalReadOnly
Action:
- 's3:GetObject'
Effect: Allow
Principal:
Service: cloudfront.amazonaws.com
Resource: !Sub "${Bucket.Arn}/*"
Condition:
StringEquals:
AWS:SourceArn: !Sub "arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution.Id}"
Outputs:
CloudFrontDomain:
Description: URL of CloudFront distribution.
Value: !GetAtt CloudFrontDistribution.DomainName