-
Notifications
You must be signed in to change notification settings - Fork 27.5k
/
Copy pathapi-utils.ts
598 lines (533 loc) · 15.8 KB
/
api-utils.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
import { IncomingMessage, ServerResponse } from 'http'
import { parse } from 'next/dist/compiled/content-type'
import { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import generateETag from 'next/dist/compiled/etag'
import fresh from 'next/dist/compiled/fresh'
import getRawBody from 'next/dist/compiled/raw-body'
import { PageConfig } from 'next/types'
import { Stream } from 'stream'
import { isResSent, NextApiRequest, NextApiResponse } from '../lib/utils'
import { decryptWithSecret, encryptWithSecret } from './crypto-utils'
import { interopDefault } from './load-components'
import { Params } from './router'
export type NextApiRequestCookies = { [key: string]: string }
export type NextApiRequestQuery = { [key: string]: string | string[] }
export type __ApiPreviewProps = {
previewModeId: string
previewModeEncryptionKey: string
previewModeSigningKey: string
}
export async function apiResolver(
req: IncomingMessage,
res: ServerResponse,
query: any,
resolverModule: any,
apiContext: __ApiPreviewProps,
propagateError: boolean,
onError?: ({ err }: { err: any }) => Promise<void>
) {
const apiReq = req as NextApiRequest
const apiRes = res as NextApiResponse
try {
if (!resolverModule) {
res.statusCode = 404
res.end('Not Found')
return
}
const config: PageConfig = resolverModule.config || {}
const bodyParser = config.api?.bodyParser !== false
const externalResolver = config.api?.externalResolver || false
// Parsing of cookies
setLazyProp({ req: apiReq }, 'cookies', getCookieParser(req))
// Parsing query string
apiReq.query = query
// Parsing preview data
setLazyProp({ req: apiReq }, 'previewData', () =>
tryGetPreviewData(req, res, apiContext)
)
// Checking if preview mode is enabled
setLazyProp({ req: apiReq }, 'preview', () =>
apiReq.previewData !== false ? true : undefined
)
// Parsing of body
if (bodyParser) {
apiReq.body = await parseBody(
apiReq,
config.api && config.api.bodyParser && config.api.bodyParser.sizeLimit
? config.api.bodyParser.sizeLimit
: '1mb'
)
}
apiRes.status = (statusCode) => sendStatusCode(apiRes, statusCode)
apiRes.send = (data) => sendData(apiReq, apiRes, data)
apiRes.json = (data) => sendJson(apiRes, data)
apiRes.redirect = (statusOrUrl: number | string, url?: string) =>
redirect(apiRes, statusOrUrl, url)
apiRes.setPreviewData = (data, options = {}) =>
setPreviewData(apiRes, data, Object.assign({}, apiContext, options))
apiRes.clearPreviewData = () => clearPreviewData(apiRes)
const resolver = interopDefault(resolverModule)
let wasPiped = false
if (process.env.NODE_ENV !== 'production') {
// listen for pipe event and don't show resolve warning
res.once('pipe', () => (wasPiped = true))
}
// Call API route method
await resolver(req, res)
if (
process.env.NODE_ENV !== 'production' &&
!externalResolver &&
!isResSent(res) &&
!wasPiped
) {
console.warn(
`API resolved without sending a response for ${req.url}, this may result in stalled requests.`
)
}
} catch (err) {
if (err instanceof ApiError) {
sendError(apiRes, err.statusCode, err.message)
} else {
console.error(err)
if (onError) await onError({ err })
if (propagateError) {
throw err
}
sendError(apiRes, 500, 'Internal Server Error')
}
}
}
/**
* Parse incoming message like `json` or `urlencoded`
* @param req request object
*/
export async function parseBody(
req: NextApiRequest,
limit: string | number
): Promise<any> {
const contentType = parse(req.headers['content-type'] || 'text/plain')
const { type, parameters } = contentType
const encoding = parameters.charset || 'utf-8'
let buffer
try {
buffer = await getRawBody(req, { encoding, limit })
} catch (e) {
if (e.type === 'entity.too.large') {
throw new ApiError(413, `Body exceeded ${limit} limit`)
} else {
throw new ApiError(400, 'Invalid body')
}
}
const body = buffer.toString()
if (type === 'application/json' || type === 'application/ld+json') {
return parseJson(body)
} else if (type === 'application/x-www-form-urlencoded') {
const qs = require('querystring')
return qs.decode(body)
} else {
return body
}
}
/**
* Parse `JSON` and handles invalid `JSON` strings
* @param str `JSON` string
*/
function parseJson(str: string): object {
if (str.length === 0) {
// special-case empty json body, as it's a common client-side mistake
return {}
}
try {
return JSON.parse(str)
} catch (e) {
throw new ApiError(400, 'Invalid JSON')
}
}
/**
* Parsing query arguments from request `url` string
* @param url of request
* @returns Object with key name of query argument and its value
*/
export function getQueryParser({ url }: IncomingMessage) {
return function parseQuery(): NextApiRequestQuery {
const { URL } = require('url')
// we provide a placeholder base url because we only want searchParams
const params = new URL(url, 'https://n').searchParams
const query: { [key: string]: string | string[] } = {}
for (const [key, value] of params) {
if (query[key]) {
if (Array.isArray(query[key])) {
;(query[key] as string[]).push(value)
} else {
query[key] = [query[key], value]
}
} else {
query[key] = value
}
}
return query
}
}
/**
* Parse cookies from `req` header
* @param req request object
*/
export function getCookieParser(req: IncomingMessage) {
return function parseCookie(): NextApiRequestCookies {
const header: undefined | string | string[] = req.headers.cookie
if (!header) {
return {}
}
const { parse: parseCookieFn } = require('next/dist/compiled/cookie')
return parseCookieFn(Array.isArray(header) ? header.join(';') : header)
}
}
/**
*
* @param res response object
* @param statusCode `HTTP` status code of response
*/
export function sendStatusCode(
res: NextApiResponse,
statusCode: number
): NextApiResponse<any> {
res.statusCode = statusCode
return res
}
/**
*
* @param res response object
* @param [statusOrUrl] `HTTP` status code of redirect
* @param url URL of redirect
*/
export function redirect(
res: NextApiResponse,
statusOrUrl: string | number,
url?: string
): NextApiResponse<any> {
if (typeof statusOrUrl === 'string') {
url = statusOrUrl
statusOrUrl = 307
}
if (typeof statusOrUrl !== 'number' || typeof url !== 'string') {
throw new Error(
`Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`
)
}
res.writeHead(statusOrUrl, { Location: url }).end()
return res
}
function sendEtagResponse(
req: NextApiRequest,
res: NextApiResponse,
body: string | Buffer
): boolean {
const etag = generateETag(body)
if (fresh(req.headers, { etag })) {
res.statusCode = 304
res.end()
return true
}
res.setHeader('ETag', etag)
return false
}
/**
* Send `any` body to response
* @param req request object
* @param res response object
* @param body of response
*/
export function sendData(
req: NextApiRequest,
res: NextApiResponse,
body: any
): void {
if (body === null) {
res.end()
return
}
const contentType = res.getHeader('Content-Type')
if (body instanceof Stream) {
if (!contentType) {
res.setHeader('Content-Type', 'application/octet-stream')
}
body.pipe(res)
return
}
const isJSONLike = ['object', 'number', 'boolean'].includes(typeof body)
const stringifiedBody = isJSONLike ? JSON.stringify(body) : body
if (sendEtagResponse(req, res, stringifiedBody)) {
return
}
if (Buffer.isBuffer(body)) {
if (!contentType) {
res.setHeader('Content-Type', 'application/octet-stream')
}
res.setHeader('Content-Length', body.length)
res.end(body)
return
}
if (isJSONLike) {
res.setHeader('Content-Type', 'application/json; charset=utf-8')
}
res.setHeader('Content-Length', Buffer.byteLength(stringifiedBody))
res.end(stringifiedBody)
}
/**
* Send `JSON` object
* @param res response object
* @param jsonBody of data
*/
export function sendJson(res: NextApiResponse, jsonBody: any): void {
// Set header to application/json
res.setHeader('Content-Type', 'application/json; charset=utf-8')
// Use send to handle request
res.send(jsonBody)
}
const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`
export const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA)
const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)
export function tryGetPreviewData(
req: IncomingMessage,
res: ServerResponse,
options: __ApiPreviewProps
): object | string | false {
// Read cached preview data if present
if (SYMBOL_PREVIEW_DATA in req) {
return (req as any)[SYMBOL_PREVIEW_DATA] as any
}
const getCookies = getCookieParser(req)
let cookies: NextApiRequestCookies
try {
cookies = getCookies()
} catch {
// TODO: warn
return false
}
const hasBypass = COOKIE_NAME_PRERENDER_BYPASS in cookies
const hasData = COOKIE_NAME_PRERENDER_DATA in cookies
// Case: neither cookie is set.
if (!(hasBypass || hasData)) {
return false
}
// Case: one cookie is set, but not the other.
if (hasBypass !== hasData) {
clearPreviewData(res as NextApiResponse)
return false
}
// Case: preview session is for an old build.
if (cookies[COOKIE_NAME_PRERENDER_BYPASS] !== options.previewModeId) {
clearPreviewData(res as NextApiResponse)
return false
}
const tokenPreviewData = cookies[COOKIE_NAME_PRERENDER_DATA]
const jsonwebtoken = require('next/dist/compiled/jsonwebtoken') as typeof import('jsonwebtoken')
let encryptedPreviewData: {
data: string
}
try {
encryptedPreviewData = jsonwebtoken.verify(
tokenPreviewData,
options.previewModeSigningKey
) as typeof encryptedPreviewData
} catch {
// TODO: warn
clearPreviewData(res as NextApiResponse)
return false
}
const decryptedPreviewData = decryptWithSecret(
Buffer.from(options.previewModeEncryptionKey),
encryptedPreviewData.data
)
try {
// TODO: strict runtime type checking
const data = JSON.parse(decryptedPreviewData)
// Cache lookup
Object.defineProperty(req, SYMBOL_PREVIEW_DATA, {
value: data,
enumerable: false,
})
return data
} catch {
return false
}
}
function setPreviewData<T>(
res: NextApiResponse<T>,
data: object | string, // TODO: strict runtime type checking
options: {
maxAge?: number
} & __ApiPreviewProps
): NextApiResponse<T> {
if (
typeof options.previewModeId !== 'string' ||
options.previewModeId.length < 16
) {
throw new Error('invariant: invalid previewModeId')
}
if (
typeof options.previewModeEncryptionKey !== 'string' ||
options.previewModeEncryptionKey.length < 16
) {
throw new Error('invariant: invalid previewModeEncryptionKey')
}
if (
typeof options.previewModeSigningKey !== 'string' ||
options.previewModeSigningKey.length < 16
) {
throw new Error('invariant: invalid previewModeSigningKey')
}
const jsonwebtoken = require('next/dist/compiled/jsonwebtoken') as typeof import('jsonwebtoken')
const payload = jsonwebtoken.sign(
{
data: encryptWithSecret(
Buffer.from(options.previewModeEncryptionKey),
JSON.stringify(data)
),
},
options.previewModeSigningKey,
{
algorithm: 'HS256',
...(options.maxAge !== undefined
? { expiresIn: options.maxAge }
: undefined),
}
)
// limit preview mode cookie to 2KB since we shouldn't store too much
// data here and browsers drop cookies over 4KB
if (payload.length > 2048) {
throw new Error(
`Preview data is limited to 2KB currently, reduce how much data you are storing as preview data to continue`
)
}
const {
serialize,
} = require('next/dist/compiled/cookie') as typeof import('cookie')
const previous = res.getHeader('Set-Cookie')
res.setHeader(`Set-Cookie`, [
...(typeof previous === 'string'
? [previous]
: Array.isArray(previous)
? previous
: []),
serialize(COOKIE_NAME_PRERENDER_BYPASS, options.previewModeId, {
httpOnly: true,
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',
secure: process.env.NODE_ENV !== 'development',
path: '/',
...(options.maxAge !== undefined
? ({ maxAge: options.maxAge } as CookieSerializeOptions)
: undefined),
}),
serialize(COOKIE_NAME_PRERENDER_DATA, payload, {
httpOnly: true,
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',
secure: process.env.NODE_ENV !== 'development',
path: '/',
...(options.maxAge !== undefined
? ({ maxAge: options.maxAge } as CookieSerializeOptions)
: undefined),
}),
])
return res
}
function clearPreviewData<T>(res: NextApiResponse<T>): NextApiResponse<T> {
if (SYMBOL_CLEARED_COOKIES in res) {
return res
}
const {
serialize,
} = require('next/dist/compiled/cookie') as typeof import('cookie')
const previous = res.getHeader('Set-Cookie')
res.setHeader(`Set-Cookie`, [
...(typeof previous === 'string'
? [previous]
: Array.isArray(previous)
? previous
: []),
serialize(COOKIE_NAME_PRERENDER_BYPASS, '', {
// To delete a cookie, set `expires` to a date in the past:
// https://tools.ietf.org/html/rfc6265#section-4.1.1
// `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.
expires: new Date(0),
httpOnly: true,
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',
secure: process.env.NODE_ENV !== 'development',
path: '/',
}),
serialize(COOKIE_NAME_PRERENDER_DATA, '', {
// To delete a cookie, set `expires` to a date in the past:
// https://tools.ietf.org/html/rfc6265#section-4.1.1
// `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.
expires: new Date(0),
httpOnly: true,
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',
secure: process.env.NODE_ENV !== 'development',
path: '/',
}),
])
Object.defineProperty(res, SYMBOL_CLEARED_COOKIES, {
value: true,
enumerable: false,
})
return res
}
/**
* Custom error class
*/
export class ApiError extends Error {
readonly statusCode: number
constructor(statusCode: number, message: string) {
super(message)
this.statusCode = statusCode
}
}
/**
* Sends error in `response`
* @param res response object
* @param statusCode of response
* @param message of response
*/
export function sendError(
res: NextApiResponse,
statusCode: number,
message: string
): void {
res.statusCode = statusCode
res.statusMessage = message
res.end(message)
}
interface LazyProps {
req: NextApiRequest
params?: Params | boolean
}
/**
* Execute getter function only if its needed
* @param LazyProps `req` and `params` for lazyProp
* @param prop name of property
* @param getter function to get data
*/
export function setLazyProp<T>(
{ req, params }: LazyProps,
prop: string,
getter: () => T
): void {
const opts = { configurable: true, enumerable: true }
const optsReset = { ...opts, writable: true }
Object.defineProperty(req, prop, {
...opts,
get: () => {
let value = getter()
if (params && typeof params !== 'boolean') {
value = { ...value, ...params }
}
// we set the property on the object to avoid recalculating it
Object.defineProperty(req, prop, { ...optsReset, value })
return value
},
set: (value) => {
Object.defineProperty(req, prop, { ...optsReset, value })
},
})
}