-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathframework.ts
353 lines (328 loc) · 12.5 KB
/
framework.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
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import type {
APIGatewayProxyEventV2,
APIGatewayProxyEvent,
APIGatewayProxyResult,
APIGatewayProxyStructuredResultV2,
Handler,
Context,
Callback,
} from "aws-lambda";
import { HTTPMethod } from "../../types";
import { normaliseHttpMethod } from "../../utils";
import { BaseRequest } from "../request";
import { BaseResponse } from "../response";
import { normalizeHeaderValue, getCookieValueFromHeaders, serializeCookieValue } from "../utils";
import { COOKIE_HEADER } from "../constants";
import { SessionContainerInterface } from "../../recipe/session/types";
import SuperTokens from "../../supertokens";
import { Framework } from "../types";
import { parse } from "querystring";
export class AWSRequest extends BaseRequest {
private event: APIGatewayProxyEventV2 | APIGatewayProxyEvent;
private parsedJSONBody: Object | undefined;
private parsedUrlEncodedFormData: Object | undefined;
constructor(event: APIGatewayProxyEventV2 | APIGatewayProxyEvent) {
super();
this.original = event;
this.event = event;
this.parsedJSONBody = undefined;
this.parsedUrlEncodedFormData = undefined;
}
getFormData = async (): Promise<any> => {
if (this.parsedUrlEncodedFormData === undefined) {
if (this.event.body === null || this.event.body === undefined) {
this.parsedUrlEncodedFormData = {};
} else {
this.parsedUrlEncodedFormData = parse(this.event.body);
if (this.parsedUrlEncodedFormData === undefined) {
this.parsedUrlEncodedFormData = {};
}
}
}
return this.parsedUrlEncodedFormData;
};
getKeyValueFromQuery = (key: string): string | undefined => {
if (this.event.queryStringParameters === undefined || this.event.queryStringParameters === null) {
return undefined;
}
let value = this.event.queryStringParameters[key];
if (value === undefined || typeof value !== "string") {
return undefined;
}
return value;
};
getJSONBody = async (): Promise<any> => {
if (this.parsedJSONBody === undefined) {
if (this.event.body === null || this.event.body === undefined) {
this.parsedJSONBody = {};
} else {
this.parsedJSONBody = JSON.parse(this.event.body);
if (this.parsedJSONBody === undefined) {
this.parsedJSONBody = {};
}
}
}
return this.parsedJSONBody;
};
getMethod = (): HTTPMethod => {
let rawMethod = (this.event as APIGatewayProxyEvent).httpMethod;
if (rawMethod !== undefined) {
return normaliseHttpMethod(rawMethod);
}
return normaliseHttpMethod((this.event as APIGatewayProxyEventV2).requestContext.http.method);
};
getCookieValue = (key: string): string | undefined => {
let cookies = (this.event as APIGatewayProxyEventV2).cookies;
if (
(this.event.headers === undefined || this.event.headers === null) &&
(cookies === undefined || cookies === null)
) {
return undefined;
}
let value = getCookieValueFromHeaders(this.event.headers, key);
if (value === undefined && cookies !== undefined && cookies !== null) {
value = getCookieValueFromHeaders(
{
cookie: cookies.join(";"),
},
key
);
}
return value;
};
getHeaderValue = (key: string): string | undefined => {
if (this.event.headers === undefined || this.event.headers === null) {
return undefined;
}
return normalizeHeaderValue(this.event.headers[key]);
};
getOriginalURL = (): string => {
let path = (this.event as APIGatewayProxyEvent).path;
if (path === undefined) {
path = (this.event as APIGatewayProxyEventV2).requestContext.http.path;
let stage = (this.event as APIGatewayProxyEventV2).requestContext.stage;
if (stage !== undefined && path.startsWith(`/${stage}`)) {
path = path.slice(stage.length + 1);
}
}
return path;
};
}
interface SupertokensLambdaEvent extends APIGatewayProxyEvent {
supertokens: {
response: {
headers: { key: string; value: boolean | number | string; allowDuplicateKey: boolean }[];
cookies: string[];
};
};
}
interface SupertokensLambdaEventV2 extends APIGatewayProxyEventV2 {
supertokens: {
response: {
headers: { key: string; value: boolean | number | string; allowDuplicateKey: boolean }[];
cookies: string[];
};
};
}
export class AWSResponse extends BaseResponse {
private statusCode: number;
private event: SupertokensLambdaEvent | SupertokensLambdaEventV2;
private content: string;
public responseSet: boolean;
public statusSet: boolean;
constructor(event: SupertokensLambdaEvent | SupertokensLambdaEventV2) {
super();
this.original = event;
this.event = event;
this.statusCode = 200;
this.content = JSON.stringify({});
this.responseSet = false;
this.statusSet = false;
this.event.supertokens = {
response: {
headers: [],
cookies: [],
},
};
}
sendHTMLResponse = (html: string) => {
if (!this.responseSet) {
this.content = html;
this.setHeader("Content-Type", "text/html", false);
this.responseSet = true;
}
};
setHeader = (key: string, value: string, allowDuplicateKey: boolean) => {
this.event.supertokens.response.headers.push({
key,
value,
allowDuplicateKey,
});
};
setCookie = (
key: string,
value: string,
domain: string | undefined,
secure: boolean,
httpOnly: boolean,
expires: number,
path: string,
sameSite: "strict" | "lax" | "none"
) => {
let serialisedCookie = serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite);
this.event.supertokens.response.cookies.push(serialisedCookie);
};
/**
* @param {number} statusCode
*/
setStatusCode = (statusCode: number) => {
if (!this.statusSet) {
this.statusCode = statusCode;
this.statusSet = true;
}
};
sendJSONResponse = (content: any) => {
if (!this.responseSet) {
this.content = JSON.stringify(content);
this.setHeader("Content-Type", "application/json", false);
this.responseSet = true;
}
};
sendResponse = (response?: APIGatewayProxyResult | APIGatewayProxyStructuredResultV2) => {
if (response === undefined) {
response = {};
}
let headers:
| {
[header: string]: boolean | number | string;
}
| undefined = response.headers;
if (headers === undefined) {
headers = {};
}
let body = response.body;
let statusCode = response.statusCode;
if (this.responseSet) {
statusCode = this.statusCode;
body = this.content;
}
let supertokensHeaders = this.event.supertokens.response.headers;
let supertokensCookies = this.event.supertokens.response.cookies;
for (let i = 0; i < supertokensHeaders.length; i++) {
let currentValue = undefined;
let currentHeadersSet = Object.keys(headers === undefined ? [] : headers);
for (let j = 0; j < currentHeadersSet.length; j++) {
if (currentHeadersSet[j].toLowerCase() === supertokensHeaders[i].key.toLowerCase()) {
supertokensHeaders[i].key = currentHeadersSet[j];
currentValue = headers[currentHeadersSet[j]];
break;
}
}
if (supertokensHeaders[i].allowDuplicateKey && currentValue !== undefined) {
let newValue = `${currentValue}, ${supertokensHeaders[i].value}`;
headers[supertokensHeaders[i].key] = newValue;
} else {
headers[supertokensHeaders[i].key] = supertokensHeaders[i].value;
}
}
if ((this.event as APIGatewayProxyEventV2).version !== undefined) {
let cookies = (response as APIGatewayProxyStructuredResultV2).cookies;
if (cookies === undefined) {
cookies = [];
}
cookies.push(...supertokensCookies);
let result: APIGatewayProxyStructuredResultV2 = {
...(response as APIGatewayProxyStructuredResultV2),
cookies,
body,
statusCode,
headers,
};
return result;
} else {
let multiValueHeaders = (response as APIGatewayProxyResult).multiValueHeaders;
if (multiValueHeaders === undefined) {
multiValueHeaders = {};
}
let headsersInMultiValueHeaders = Object.keys(multiValueHeaders);
let cookieHeader = headsersInMultiValueHeaders.find((h) => h.toLowerCase() === COOKIE_HEADER.toLowerCase());
if (cookieHeader === undefined) {
multiValueHeaders[COOKIE_HEADER] = supertokensCookies;
} else {
multiValueHeaders[cookieHeader].push(...supertokensCookies);
}
let result: APIGatewayProxyResult = {
...(response as APIGatewayProxyResult),
multiValueHeaders,
body: body as string,
statusCode: statusCode as number,
headers,
};
return result;
}
};
}
export interface SessionEventV2 extends SupertokensLambdaEventV2 {
session?: SessionContainerInterface;
}
export interface SessionEvent extends SupertokensLambdaEvent {
session?: SessionContainerInterface;
}
export const middleware = (handler?: Handler): Handler => {
return async (event: SessionEvent | SessionEventV2, context: Context, callback: Callback) => {
let supertokens = SuperTokens.getInstanceOrThrowError();
let request = new AWSRequest(event);
let response = new AWSResponse(event);
try {
let result = await supertokens.middleware(request, response);
if (result) {
return response.sendResponse();
}
if (handler !== undefined) {
let handlerResult = await handler(event, context, callback);
return response.sendResponse(handlerResult);
}
/**
* it reaches this point only if the API route was not exposed by
* the SDK and user didn't provide a handler
*/
response.setStatusCode(404);
response.sendJSONResponse({
error: `The middleware couldn't serve the API path ${request.getOriginalURL()}, method: ${request.getMethod()}. If this is an unexpected behaviour, please create an issue here: https://github.com/supertokens/supertokens-node/issues`,
});
return response.sendResponse();
} catch (err) {
await supertokens.errorHandler(err, request, response);
if (response.responseSet) {
return response.sendResponse();
}
throw err;
}
};
};
export interface AWSFramework extends Framework {
middleware: (handler?: Handler) => Handler;
}
export const AWSWrapper: AWSFramework = {
middleware,
wrapRequest: (unwrapped) => {
return new AWSRequest(unwrapped);
},
wrapResponse: (unwrapped) => {
return new AWSResponse(unwrapped);
},
};