forked from aws-samples/cloudfront-authorization-at-edge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
177 lines (161 loc) · 5.72 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { execSync } from "child_process";
import {
CloudFormationCustomResourceHandler,
CloudFormationCustomResourceDeleteEvent,
CloudFormationCustomResourceUpdateEvent,
} from "aws-lambda";
import s3SpaUpload from "s3-spa-upload";
import { existsSync, mkdirSync, writeFileSync } from "fs";
import { ncp } from "ncp";
import { sendCfnResponse, Status } from "./cfn-response";
interface Configuration {
BucketName: string;
ClientId: string;
CognitoAuthDomain: string;
RedirectPathSignIn: string;
RedirectPathSignOut: string;
UserPoolArn: string;
OAuthScopes: string;
SignOutUrl: string;
CookieSettings: 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<void>((resolve, reject) => {
ncp(`${__dirname}/react-app/${path}`, `${temp_dir}/${path}`, (err) =>
err ? reject(err) : resolve()
);
})
)
);
const userPoolId = config.UserPoolArn.split("/")[1];
const userPoolRegion = config.UserPoolArn.split(":")[3];
const cookieSettings = JSON.parse(config.CookieSettings).idToken as
| string
| null;
let cookieDomain = cookieSettings
?.split(";")
.map((part) => {
const match = part.match(/domain(\s*)=(\s*)(?<domain>.+)/i);
return match?.groups?.domain;
})
.find((domain) => !!domain);
if (!cookieDomain) {
// Cookies without a domain, are called host-only cookies, and are perfectly normal.
// However, AmplifyJS requires to be passed a value for domain, when using cookie storage.
// We'll use " " as a trick to satisfy this check by AmplifyJS, and support host-only cookies.
//
// Note that you do not want to add an exact domain name to a cookie, if you want to have a host-only cookie,
// because a cookie that's explicitly set for e.g. example.com is also readable by subdomain.example.com.
// (In a cookie domain, example.com is treated the same as .example.com)
// The ONLY way to get a host-only cookie, is by NOT including the domain attribute for the cookie at all.
//
// Note that if the cookie storage used in Amplify specifies a domain, this must match 1:1 the domain that
// is used for the cookie by Auth@Edge, otherwise Amplify will have trouble setting that cookie
// (and then e.g. signing out via Amplify no longer works, as that sets the cookies to expire them)
cookieDomain = " ";
}
const reactEnv = `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}
REACT_APP_COOKIE_DOMAIN="${cookieDomain}"
INLINE_RUNTIME_CHUNK=false
`;
console.log("React env:\n", reactEnv);
console.log(`Creating React environment file ${temp_dir}/.env ...`);
writeFileSync(`${temp_dir}/.env`, reactEnv);
console.log("NPM version:");
execSync("npm -v", {
cwd: temp_dir,
stdio: "inherit",
env: { ...process.env, HOME: home_dir },
});
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 { ResourceProperties, RequestType } = event;
const { ServiceToken, ...config } = ResourceProperties;
const { PhysicalResourceId } = event as
| CloudFormationCustomResourceDeleteEvent
| CloudFormationCustomResourceUpdateEvent;
let status = Status.SUCCESS;
let physicalResourceId: string | undefined;
let data: { [key: string]: any } | undefined;
let reason: string | undefined;
try {
physicalResourceId = await Promise.race([
buildUploadSpa(RequestType, config as Configuration, PhysicalResourceId),
new Promise<undefined>((_, reject) =>
setTimeout(
() => reject(new Error("Task timeout")),
context.getRemainingTimeInMillis() - 500
)
),
]);
} catch (err) {
console.error(err);
status = Status.FAILED;
reason = `${err}`;
}
await sendCfnResponse({
event,
status,
data,
physicalResourceId,
reason,
});
};