/
HttpServer.js
1042 lines (864 loc) · 31 KB
/
HttpServer.js
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Buffer } from 'buffer'
import { readFileSync } from 'fs'
import { join, resolve } from 'path'
import h2o2 from '@hapi/h2o2'
import { Server } from '@hapi/hapi'
import authFunctionNameExtractor from './authFunctionNameExtractor.js'
import createAuthScheme from './createAuthScheme.js'
import Endpoint from './Endpoint.js'
import {
LambdaIntegrationEvent,
LambdaProxyIntegrationEvent,
renderVelocityTemplateObject,
VelocityContext,
} from './lambda-events/index.js'
import parseResources from './parseResources.js'
import debugLog from '../../debugLog.js'
import serverlessLog, { logRoutes } from '../../serverlessLog.js'
import {
detectEncoding,
jsonPath,
splitHandlerPathAndName,
} from '../../utils/index.js'
const { parse, stringify } = JSON
export default class HttpServer {
#lambda = null
#lastRequestOptions = null
#options = null
#serverless = null
#server = null
#terminalInfo = []
constructor(serverless, options, lambda) {
this.#lambda = lambda
this.#options = options
this.#serverless = serverless
const {
enforceSecureCookies,
host,
httpPort,
httpsProtocol,
} = this.#options
const serverOptions = {
host,
port: httpPort,
router: {
// allows for paths with trailing slashes to be the same as without
// e.g. : /my-path is the same as /my-path/
stripTrailingSlash: true,
},
state: enforceSecureCookies
? {
isHttpOnly: true,
isSameSite: false,
isSecure: true,
}
: {
isHttpOnly: false,
isSameSite: false,
isSecure: false,
},
}
// HTTPS support
if (typeof httpsProtocol === 'string' && httpsProtocol.length > 0) {
serverOptions.tls = {
cert: readFileSync(resolve(httpsProtocol, 'cert.pem'), 'ascii'),
key: readFileSync(resolve(httpsProtocol, 'key.pem'), 'ascii'),
}
}
// Hapijs server creation
this.#server = new Server(serverOptions)
// Enable CORS preflight response
this.#server.ext('onPreResponse', (request, h) => {
if (request.headers.origin) {
const response = request.response.isBoom
? request.response.output
: request.response
response.headers['access-control-allow-origin'] = request.headers.origin
response.headers['access-control-allow-credentials'] = 'true'
if (request.method === 'options') {
response.statusCode = 200
response.headers['access-control-expose-headers'] =
'content-type, content-length, etag'
response.headers['access-control-max-age'] = 60 * 10
if (request.headers['access-control-request-headers']) {
response.headers['access-control-allow-headers'] =
request.headers['access-control-request-headers']
}
if (request.headers['access-control-request-method']) {
response.headers['access-control-allow-methods'] =
request.headers['access-control-request-method']
}
}
}
return h.continue
})
}
async start() {
const { host, httpPort, httpsProtocol } = this.#options
try {
await this.#server.start()
} catch (err) {
console.error(
`Unexpected error while starting serverless-offline server on port ${httpPort}:`,
err,
)
process.exit(1)
}
// TODO move the following block
const server = `${httpsProtocol ? 'https' : 'http'}://${host}:${httpPort}`
serverlessLog(`[HTTP] server ready: ${server} 🚀`)
serverlessLog('')
// serverlessLog('OpenAPI/Swagger documentation:')
// logRoute('GET', server, '/documentation')
// serverlessLog('')
serverlessLog('Enter "rp" to replay the last request')
if (process.env.NODE_ENV !== 'test') {
process.openStdin().addListener('data', (data) => {
// note: data is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then trim()
if (data.toString().trim() === 'rp') {
this._injectLastRequest()
}
})
}
}
// stops the server
stop(timeout) {
return this.#server.stop({
timeout,
})
}
async registerPlugins() {
try {
await this.#server.register([h2o2])
} catch (err) {
serverlessLog(err)
}
}
// // TODO unused:
// get server() {
// return this.#server.listener
// }
_printBlankLine() {
if (process.env.NODE_ENV !== 'test') {
console.log()
}
}
_logPluginIssue() {
serverlessLog(
'If you think this is an issue with the plugin please submit it, thanks!',
)
serverlessLog('https://github.com/dherault/serverless-offline/issues')
}
_extractAuthFunctionName(endpoint) {
const result = authFunctionNameExtractor(endpoint)
return result.unsupportedAuth ? null : result.authorizerName
}
_configureAuthorization(endpoint, functionKey, method, path) {
if (!endpoint.authorizer) {
return null
}
const authFunctionName = this._extractAuthFunctionName(endpoint)
if (!authFunctionName) {
return null
}
serverlessLog(`Configuring Authorization: ${path} ${authFunctionName}`)
const authFunction = this.#serverless.service.getFunction(authFunctionName)
if (!authFunction)
return serverlessLog(
`WARNING: Authorization function ${authFunctionName} does not exist`,
)
const authorizerOptions = {
identitySource: 'method.request.header.Authorization',
identityValidationExpression: '(.*)',
resultTtlInSeconds: '300',
}
if (typeof endpoint.authorizer === 'string') {
authorizerOptions.name = authFunctionName
} else {
Object.assign(authorizerOptions, endpoint.authorizer)
}
// Create a unique scheme per endpoint
// This allows the methodArn on the event property to be set appropriately
const authKey = `${functionKey}-${authFunctionName}-${method}-${path}`
const authSchemeName = `scheme-${authKey}`
const authStrategyName = `strategy-${authKey}` // set strategy name for the route config
debugLog(`Creating Authorization scheme for ${authKey}`)
// Create the Auth Scheme for the endpoint
const scheme = createAuthScheme(
authorizerOptions,
this.#serverless.service.provider,
this.#lambda,
)
// Set the auth scheme and strategy on the server
this.#server.auth.scheme(authSchemeName, scheme)
this.#server.auth.strategy(authStrategyName, authSchemeName)
return authStrategyName
}
createRoutes(functionKey, httpEvent, handler) {
const [handlerPath] = splitHandlerPathAndName(handler)
const method = httpEvent.method.toUpperCase()
const endpoint = new Endpoint(
join(this.#serverless.config.servicePath, handlerPath),
httpEvent,
)
const { path } = httpEvent
// path must start with '/'
let hapiPath = path.startsWith('/') ? path : `/${path}`
// prepend stage to path
const stage = this.#options.stage || this.#serverless.service.provider.stage
if (!this.#options.noPrependStageInUrl) {
// prepend stage to path
hapiPath = `/${stage}${hapiPath}`
}
// but must not end with '/'
if (hapiPath !== '/' && hapiPath.endsWith('/')) {
hapiPath = hapiPath.slice(0, -1)
}
hapiPath = hapiPath.replace(/\+}/g, '*}')
const protectedRoutes = []
if (httpEvent.private) {
protectedRoutes.push(`${method}#${hapiPath}`)
}
const { host, httpPort, httpsProtocol } = this.#options
const server = `${httpsProtocol ? 'https' : 'http'}://${host}:${httpPort}`
this.#terminalInfo.push({
method,
path: hapiPath,
server,
stage: this.#options.noPrependStageInUrl ? null : stage,
invokePath: `/2015-03-31/functions/${functionKey}/invocations`,
})
// If the endpoint has an authorization function, create an authStrategy for the route
const authStrategyName = this.#options.noAuth
? null
: this._configureAuthorization(endpoint, functionKey, method, path)
let cors = null
if (endpoint.cors) {
cors = {
credentials:
endpoint.cors.credentials || this.#options.corsConfig.credentials,
exposedHeaders: this.#options.corsConfig.exposedHeaders,
headers: endpoint.cors.headers || this.#options.corsConfig.headers,
origin: endpoint.cors.origins || this.#options.corsConfig.origin,
}
}
const hapiMethod = method === 'ANY' ? '*' : method
const state = this.#options.disableCookieValidation
? {
failAction: 'ignore',
parse: false,
}
: {
failAction: 'error',
parse: true,
}
const hapiOptions = {
auth: authStrategyName,
cors,
state,
timeout: { socket: false },
}
// skip HEAD routes as hapi will fail with 'Method name not allowed: HEAD ...'
// for more details, check https://github.com/dherault/serverless-offline/issues/204
if (hapiMethod === 'HEAD') {
serverlessLog(
'HEAD method event detected. Skipping HAPI server route mapping ...',
)
return
}
if (hapiMethod !== 'HEAD' && hapiMethod !== 'GET') {
// maxBytes: Increase request size from 1MB default limit to 10MB.
// Cf AWS API GW payload limits.
hapiOptions.payload = {
maxBytes: 1024 * 1024 * 10,
parse: false,
}
}
hapiOptions.tags = ['api']
const hapiHandler = async (request, h) => {
// Here we go
// Store current request as the last one
this.#lastRequestOptions = {
headers: request.headers,
method: request.method,
payload: request.payload,
url: request.url.href,
}
const requestPath = request.path.substr(
this.#options.noPrependStageInUrl ? 0 : `/${stage}`.length,
)
if (request.auth.credentials && request.auth.strategy) {
this.#lastRequestOptions.auth = request.auth
}
// Payload processing
const encoding = detectEncoding(request)
request.payload = request.payload && request.payload.toString(encoding)
request.rawPayload = request.payload
// Incomming request message
this._printBlankLine()
serverlessLog(`${method} ${request.path} (λ: ${functionKey})`)
// Check for APIKey
if (
(protectedRoutes.includes(`${hapiMethod}#${hapiPath}`) ||
protectedRoutes.includes(`ANY#${hapiPath}`)) &&
!this.#options.noAuth
) {
const errorResponse = () =>
h
.response({ message: 'Forbidden' })
.code(403)
.type('application/json')
.header('x-amzn-ErrorType', 'ForbiddenException')
const requestToken = request.headers['x-api-key']
if (requestToken) {
if (requestToken !== this.#options.apiKey) {
debugLog(
`Method ${method} of function ${functionKey} token ${requestToken} not valid`,
)
return errorResponse()
}
} else if (
request.auth &&
request.auth.credentials &&
request.auth.credentials.usageIdentifierKey
) {
const { usageIdentifierKey } = request.auth.credentials
if (usageIdentifierKey !== this.#options.apiKey) {
debugLog(
`Method ${method} of function ${functionKey} token ${usageIdentifierKey} not valid`,
)
return errorResponse()
}
} else {
debugLog(`Missing x-api-key on private function ${functionKey}`)
return errorResponse()
}
}
const response = h.response()
const contentType = request.mime || 'application/json' // default content type
const { integration, requestTemplates } = endpoint
// default request template to '' if we don't have a definition pushed in from serverless or endpoint
const requestTemplate =
typeof requestTemplates !== 'undefined' && integration === 'AWS'
? requestTemplates[contentType]
: ''
// https://hapijs.com/api#route-configuration doesn't seem to support selectively parsing
// so we have to do it ourselves
const contentTypesThatRequirePayloadParsing = [
'application/json',
'application/vnd.api+json',
]
if (
contentTypesThatRequirePayloadParsing.includes(contentType) &&
request.payload &&
request.payload.length > 1
) {
try {
if (!request.payload || request.payload.length < 1) {
request.payload = '{}'
}
request.payload = parse(request.payload)
} catch (err) {
debugLog('error in converting request.payload to JSON:', err)
}
}
debugLog('contentType:', contentType)
debugLog('requestTemplate:', requestTemplate)
debugLog('payload:', request.payload)
/* REQUEST TEMPLATE PROCESSING (event population) */
let event = {}
if (integration === 'AWS') {
if (requestTemplate) {
try {
debugLog('_____ REQUEST TEMPLATE PROCESSING _____')
event = new LambdaIntegrationEvent(
request,
this.#serverless.service.provider.stage,
requestTemplate,
requestPath,
).create()
} catch (err) {
return this._reply500(
response,
`Error while parsing template "${contentType}" for ${functionKey}`,
err,
)
}
} else if (typeof request.payload === 'object') {
event = request.payload || {}
}
} else if (integration === 'AWS_PROXY') {
const stageVariables = this.#serverless.service.custom
? this.#serverless.service.custom.stageVariables
: null
const lambdaProxyIntegrationEvent = new LambdaProxyIntegrationEvent(
request,
this.#serverless.service.provider.stage,
requestPath,
stageVariables,
)
event = lambdaProxyIntegrationEvent.create()
}
debugLog('event:', event)
const lambdaFunction = this.#lambda.get(functionKey)
lambdaFunction.setEvent(event)
let result
let err
try {
result = await lambdaFunction.runHandler()
} catch (_err) {
err = _err
}
// const processResponse = (err, data) => {
// Everything in this block happens once the lambda function has resolved
debugLog('_____ HANDLER RESOLVED _____')
let responseName = 'default'
const { contentHandling, responseContentType } = endpoint
/* RESPONSE SELECTION (among endpoint's possible responses) */
// Failure handling
let errorStatusCode = '502'
if (err) {
// Since the --useChildProcesses option loads the handler in
// a separate process and serverless-offline communicates with it
// over IPC, we are unable to catch JavaScript unhandledException errors
// when the handler code contains bad JavaScript. Instead, we "catch"
// it here and reply in the same way that we would have above when
// we lazy-load the non-IPC handler function.
if (this.#options.useChildProcesses && err.ipcException) {
return this._reply500(
response,
`Error while loading ${functionKey}`,
err,
)
}
const errorMessage = (err.message || err).toString()
const re = /\[(\d{3})]/
const found = errorMessage.match(re)
if (found && found.length > 1) {
;[, errorStatusCode] = found
} else {
errorStatusCode = '502'
}
// Mocks Lambda errors
result = {
errorMessage,
errorType: err.constructor.name,
stackTrace: this._getArrayStackTrace(err.stack),
}
serverlessLog(`Failure: ${errorMessage}`)
if (!this.#options.hideStackTraces) {
console.error(err.stack)
}
for (const [key, value] of Object.entries(endpoint.responses)) {
if (
key !== 'default' &&
errorMessage.match(`^${value.selectionPattern || key}$`)
) {
responseName = key
break
}
}
}
debugLog(`Using response '${responseName}'`)
const chosenResponse = endpoint.responses[responseName]
/* RESPONSE PARAMETERS PROCCESSING */
const { responseParameters } = chosenResponse
if (responseParameters) {
const responseParametersKeys = Object.keys(responseParameters)
debugLog('_____ RESPONSE PARAMETERS PROCCESSING _____')
debugLog(
`Found ${responseParametersKeys.length} responseParameters for '${responseName}' response`,
)
// responseParameters use the following shape: "key": "value"
Object.entries(responseParameters).forEach(([key, value]) => {
const keyArray = key.split('.') // eg: "method.response.header.location"
const valueArray = value.split('.') // eg: "integration.response.body.redirect.url"
debugLog(`Processing responseParameter "${key}": "${value}"`)
// For now the plugin only supports modifying headers
if (key.startsWith('method.response.header') && keyArray[3]) {
const headerName = keyArray.slice(3).join('.')
let headerValue
debugLog('Found header in left-hand:', headerName)
if (value.startsWith('integration.response')) {
if (valueArray[2] === 'body') {
debugLog('Found body in right-hand')
headerValue = valueArray[3]
? jsonPath(result, valueArray.slice(3).join('.'))
: result
if (
typeof headerValue === 'undefined' ||
headerValue === null
) {
headerValue = ''
} else {
headerValue = headerValue.toString()
}
} else {
this._printBlankLine()
serverlessLog(
`Warning: while processing responseParameter "${key}": "${value}"`,
)
serverlessLog(
`Offline plugin only supports "integration.response.body[.JSON_path]" right-hand responseParameter. Found "${value}" instead. Skipping.`,
)
this._logPluginIssue()
this._printBlankLine()
}
} else {
headerValue = value.match(/^'.*'$/) ? value.slice(1, -1) : value // See #34
}
// Applies the header;
if (headerValue === '') {
serverlessLog(
`Warning: empty value for responseParameter "${key}": "${value}", it won't be set`,
)
} else {
debugLog(`Will assign "${headerValue}" to header "${headerName}"`)
response.header(headerName, headerValue)
}
} else {
this._printBlankLine()
serverlessLog(
`Warning: while processing responseParameter "${key}": "${value}"`,
)
serverlessLog(
`Offline plugin only supports "method.response.header.PARAM_NAME" left-hand responseParameter. Found "${key}" instead. Skipping.`,
)
this._logPluginIssue()
this._printBlankLine()
}
})
}
let statusCode = 200
if (integration === 'AWS') {
const endpointResponseHeaders =
(endpoint.response && endpoint.response.headers) || {}
Object.entries(endpointResponseHeaders)
.filter(
([, value]) => typeof value === 'string' && /^'.*?'$/.test(value),
)
.forEach(([key, value]) => response.header(key, value.slice(1, -1)))
/* LAMBDA INTEGRATION RESPONSE TEMPLATE PROCCESSING */
// If there is a responseTemplate, we apply it to the result
const { responseTemplates } = chosenResponse
if (typeof responseTemplates === 'object') {
const responseTemplatesKeys = Object.keys(responseTemplates)
if (responseTemplatesKeys.length) {
// BAD IMPLEMENTATION: first key in responseTemplates
const responseTemplate = responseTemplates[responseContentType]
if (responseTemplate && responseTemplate !== '\n') {
debugLog('_____ RESPONSE TEMPLATE PROCCESSING _____')
debugLog(`Using responseTemplate '${responseContentType}'`)
try {
const reponseContext = new VelocityContext(
request,
this.#serverless.service.provider.stage,
result,
).getContext()
result = renderVelocityTemplateObject(
{ root: responseTemplate },
reponseContext,
).root
} catch (error) {
serverlessLog(
`Error while parsing responseTemplate '${responseContentType}' for lambda ${functionKey}:`,
)
console.log(error.stack)
}
}
}
}
/* LAMBDA INTEGRATION HAPIJS RESPONSE CONFIGURATION */
statusCode = chosenResponse.statusCode || 200
if (err) {
statusCode = errorStatusCode
}
if (!chosenResponse.statusCode) {
this._printBlankLine()
serverlessLog(
`Warning: No statusCode found for response "${responseName}".`,
)
}
response.header('Content-Type', responseContentType, {
override: false, // Maybe a responseParameter set it already. See #34
})
response.statusCode = statusCode
if (contentHandling === 'CONVERT_TO_BINARY') {
response.encoding = 'binary'
response.source = Buffer.from(result, 'base64')
response.variety = 'buffer'
} else if (typeof result === 'string') {
response.source = JSON.stringify(result)
} else if (result && result.body && typeof result.body !== 'string') {
return this._reply500(
response,
'According to the API Gateway specs, the body content must be stringified. Check your Lambda response and make sure you are invoking JSON.stringify(YOUR_CONTENT) on your body object',
{},
)
} else {
response.source = result
}
} else if (integration === 'AWS_PROXY') {
/* LAMBDA PROXY INTEGRATION HAPIJS RESPONSE CONFIGURATION */
if (result && !result.errorType) {
statusCode = result.statusCode || 200
} else {
statusCode = 502
}
response.statusCode = statusCode
const headers = {}
if (result && result.headers) {
Object.keys(result.headers).forEach((header) => {
headers[header] = (headers[header] || []).concat(
result.headers[header],
)
})
}
if (result && result.multiValueHeaders) {
Object.keys(result.multiValueHeaders).forEach((header) => {
headers[header] = (headers[header] || []).concat(
result.multiValueHeaders[header],
)
})
}
debugLog('headers', headers)
Object.keys(headers).forEach((header) => {
if (header.toLowerCase() === 'set-cookie') {
headers[header].forEach((headerValue) => {
const cookieName = headerValue.slice(0, headerValue.indexOf('='))
const cookieValue = headerValue.slice(
headerValue.indexOf('=') + 1,
)
h.state(cookieName, cookieValue, {
encoding: 'none',
strictHeader: false,
})
})
} else {
headers[header].forEach((headerValue) => {
// it looks like Hapi doesn't support multiple headers with the same name,
// appending values is the closest we can come to the AWS behavior.
response.header(header, headerValue, { append: true })
})
}
})
response.header('Content-Type', 'application/json', {
duplicate: false,
override: false,
})
if (typeof result === 'string') {
response.source = JSON.stringify(result)
} else if (result && typeof result.body !== 'undefined') {
if (result.isBase64Encoded) {
response.encoding = 'binary'
response.source = Buffer.from(result.body, 'base64')
response.variety = 'buffer'
} else {
if (result && result.body && typeof result.body !== 'string') {
return this._reply500(
response,
'According to the API Gateway specs, the body content must be stringified. Check your Lambda response and make sure you are invoking JSON.stringify(YOUR_CONTENT) on your body object',
{},
)
}
response.source = result.body
}
}
}
// Log response
let whatToLog = result
try {
whatToLog = stringify(result)
} catch (error) {
// nothing
} finally {
if (this.#options.printOutput)
serverlessLog(
err ? `Replying ${statusCode}` : `[${statusCode}] ${whatToLog}`,
)
}
// Bon voyage!
return response
}
this.#server.route({
handler: hapiHandler,
method: hapiMethod,
options: hapiOptions,
path: hapiPath,
})
}
// Bad news
_reply500(response, message, error) {
serverlessLog(message)
console.error(error)
response.header('Content-Type', 'application/json')
response.statusCode = 502 // APIG replies 502 by default on failures;
response.source = {
errorMessage: message,
errorType: error.constructor.name,
offlineInfo:
'If you believe this is an issue with serverless-offline please submit it, thanks. https://github.com/dherault/serverless-offline/issues',
stackTrace: this._getArrayStackTrace(error.stack),
}
return response
}
createResourceRoutes() {
const resourceRoutesOptions = this.#options.resourceRoutes
if (!resourceRoutesOptions) {
return
}
const resourceRoutes = parseResources(this.#serverless.service.resources)
if (!resourceRoutes || !Object.keys(resourceRoutes).length) {
return
}
this._printBlankLine()
serverlessLog('Routes defined in resources:')
Object.entries(resourceRoutes).forEach(([methodId, resourceRoutesObj]) => {
const {
isProxy,
method,
path,
pathResource,
proxyUri,
} = resourceRoutesObj
if (!isProxy) {
serverlessLog(
`WARNING: Only HTTP_PROXY is supported. Path '${pathResource}' is ignored.`,
)
return
}
if (!path) {
serverlessLog(`WARNING: Could not resolve path for '${methodId}'.`)
return
}
let hapiPath = path.startsWith('/') ? path : `/${path}`
if (!this.#options.noPrependStageInUrl) {
const stage =
this.#options.stage || this.#serverless.service.provider.stage
// prepend stage to path
hapiPath = `/${stage}${hapiPath}`
}
if (hapiPath !== '/' && hapiPath.endsWith('/')) {
hapiPath = hapiPath.slice(0, -1)
}
hapiPath = hapiPath.replace(/\+}/g, '*}')
const proxyUriOverwrite = resourceRoutesOptions[methodId] || {}
const proxyUriInUse = proxyUriOverwrite.Uri || proxyUri
if (!proxyUriInUse) {
serverlessLog(`WARNING: Could not load Proxy Uri for '${methodId}'`)
return
}
const hapiMethod = method === 'ANY' ? '*' : method
const state = this.#options.disableCookieValidation
? {
failAction: 'ignore',
parse: false,
}
: {
failAction: 'error',
parse: true,
}
const hapiOptions = {
cors: this.#options.corsConfig,
state,
}
// skip HEAD routes as hapi will fail with 'Method name not allowed: HEAD ...'
// for more details, check https://github.com/dherault/serverless-offline/issues/204
if (hapiMethod === 'HEAD') {
serverlessLog(
'HEAD method event detected. Skipping HAPI server route mapping ...',
)
return
}
if (hapiMethod !== 'GET' && hapiMethod !== 'HEAD') {
hapiOptions.payload = { parse: false }
}
serverlessLog(`${method} ${hapiPath} -> ${proxyUriInUse}`)
// hapiOptions.tags = ['api']
const route = {
handler(request, h) {
const { params } = request
let resultUri = proxyUriInUse
Object.entries(params).forEach(([key, value]) => {
resultUri = resultUri.replace(`{${key}}`, value)
})
if (request.url.search !== null) {
resultUri += request.url.search // search is empty string by default
}
serverlessLog(
`PROXY ${request.method} ${request.url.path} -> ${resultUri}`,
)
return h.proxy({
passThrough: true,
uri: resultUri,
})
},
method: hapiMethod,
options: hapiOptions,
path: hapiPath,
}
this.#server.route(route)
})
}
create404Route() {
// If a {proxy+} route exists, don't conflict with it
if (this.#server.match('*', '/{p*}')) {
return
}
const existingRoutes = this.#server
.table()
// Exclude this (404) route
.filter((route) => route.path !== '/{p*}')
// Sort by path
.sort((a, b) => (a.path <= b.path ? -1 : 1))
// Human-friendly result
.map((route) => `${route.method} - ${route.path}`)
const route = {
handler(request, h) {
const response = h.response({
currentRoute: `${request.method} - ${request.path}`,
error: 'Serverless-offline: route not found.',
existingRoutes,
statusCode: 404,
})
response.statusCode = 404
return response
},
method: '*',