forked from aws-samples/cloudfront-authorization-at-edge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
159 lines (143 loc) · 4.37 KB
/
index.ts
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
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { execSync } from "child_process";
import {
CloudFormationCustomResourceHandler,
CloudFormationCustomResourceResponse,
CloudFormationCustomResourceDeleteEvent,
CloudFormationCustomResourceUpdateEvent,
} from "aws-lambda";
import axios from "axios";
import s3SpaUpload from "s3-spa-upload";
import { existsSync, mkdirSync, writeFileSync } from "fs";
import { ncp } from "ncp";
interface Configuration {
BucketName: string;
ClientId: string;
CognitoAuthDomain: string;
RedirectPathSignIn: string;
RedirectPathSignOut: string;
UserPoolArn: string;
OAuthScopes: string;
SignOutUrl: string;
}
async function buildSpa(config: Configuration) {
const temp_dir = "/tmp/spa";
const home_dir = "/tmp/home";
console.log(
`Copying SPA sources to ${temp_dir} and making dependencies available there ...`
);
[temp_dir, home_dir].forEach((dir) => {
if (!existsSync(dir)) {
mkdirSync(dir);
}
});
await Promise.all(
["src", "public", "package.json", "package-lock.json"].map(
async (path) =>
new Promise((resolve, reject) => {
ncp(`${__dirname}/${path}`, `${temp_dir}/${path}`, (err) =>
err ? reject(err) : resolve()
);
})
)
);
const userPoolId = config.UserPoolArn.split("/")[1];
const userPoolRegion = config.UserPoolArn.split(":")[3];
console.log(`Creating environment file ${temp_dir}/.env ...`);
writeFileSync(
`${temp_dir}/.env`,
`SKIP_PREFLIGHT_CHECK=true
REACT_APP_USER_POOL_ID=${userPoolId}
REACT_APP_USER_POOL_REGION=${userPoolRegion}
REACT_APP_USER_POOL_WEB_CLIENT_ID=${config.ClientId}
REACT_APP_USER_POOL_AUTH_DOMAIN=${config.CognitoAuthDomain}
REACT_APP_USER_POOL_REDIRECT_PATH_SIGN_IN=${config.RedirectPathSignIn}
REACT_APP_USER_POOL_REDIRECT_PATH_SIGN_OUT=${config.RedirectPathSignOut}
REACT_APP_SIGN_OUT_URL=${config.SignOutUrl}
REACT_APP_USER_POOL_SCOPES=${config.OAuthScopes}
INLINE_RUNTIME_CHUNK=false
`
);
console.log(`Installing dependencies to build React app in ${temp_dir} ...`);
execSync("npm ci", {
cwd: temp_dir,
stdio: "inherit",
env: { ...process.env, HOME: home_dir },
});
console.log(`Running build of React app in ${temp_dir} ...`);
execSync("npm run build", {
cwd: temp_dir,
stdio: "inherit",
env: { ...process.env, HOME: home_dir },
});
console.log("Build succeeded");
return `${temp_dir}/build`;
}
async function buildUploadSpa(
action: "Create" | "Update" | "Delete",
config: Configuration,
physicalResourceId?: string
) {
if (action === "Create" || action === "Update") {
const buildDir = await buildSpa(config);
await s3SpaUpload(buildDir, config.BucketName);
} else {
// "Trick" to empty the bucket is to upload an empty dir
mkdirSync("/tmp/empty_directory", { recursive: true });
await s3SpaUpload("/tmp/empty_directory", config.BucketName, {
delete: true,
});
}
return physicalResourceId || "ReactApp";
}
export const handler: CloudFormationCustomResourceHandler = async (
event,
context
) => {
console.log(JSON.stringify(event, undefined, 4));
const {
LogicalResourceId,
RequestId,
StackId,
ResponseURL,
ResourceProperties,
RequestType,
} = event;
const { ServiceToken, ...config } = ResourceProperties;
const { PhysicalResourceId } = event as
| CloudFormationCustomResourceDeleteEvent
| CloudFormationCustomResourceUpdateEvent;
let response: CloudFormationCustomResourceResponse;
try {
const physicalResourceId = await Promise.race([
buildUploadSpa(RequestType, config as Configuration, PhysicalResourceId),
new Promise((_, reject) =>
setTimeout(
() => reject(new Error("Task timeout")),
context.getRemainingTimeInMillis() - 500
)
),
]);
response = {
LogicalResourceId,
PhysicalResourceId: physicalResourceId as string,
Status: "SUCCESS",
RequestId,
StackId,
Data: {},
};
} catch (err) {
console.error(err);
response = {
LogicalResourceId,
PhysicalResourceId:
PhysicalResourceId || `failed-to-create-${Date.now()}`,
Status: "FAILED",
Reason: err.stack || err.message,
RequestId,
StackId,
};
}
await axios.put(ResponseURL, response, { headers: { "content-type": "" } });
};