@sassoftware/viya-serverjs 0.2.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.babelrc +6 -6
  2. package/.dockerignore +2 -2
  3. package/.env +29 -29
  4. package/.env.proxy +32 -32
  5. package/.env.server +30 -30
  6. package/.eslintignore +3 -3
  7. package/.eslintrc.json +42 -42
  8. package/Dockerfile +44 -44
  9. package/README.md +99 -99
  10. package/cli.js +9 -9
  11. package/lib/config.js +16 -16
  12. package/lib/handlers/appCallback.js +23 -24
  13. package/lib/handlers/codeAuth.js +17 -18
  14. package/lib/handlers/decodeJwt.js +3 -3
  15. package/lib/handlers/favicon.js +22 -25
  16. package/lib/handlers/getApp.js +20 -21
  17. package/lib/handlers/getApp2.js +22 -25
  18. package/lib/handlers/getUser.js +14 -17
  19. package/lib/handlers/index.js +3 -3
  20. package/lib/handlers/keepAlive.js +28 -31
  21. package/lib/handlers/keepAlive2.js +9 -12
  22. package/lib/handlers/logon.js +12 -15
  23. package/lib/handlers/logout.js +24 -28
  24. package/lib/handlers/proxyMapUri.js +6 -11
  25. package/lib/handlers/proxyOnResponse.js +6 -7
  26. package/lib/handlers/reactDev.js +22 -25
  27. package/lib/handlers/setCookies.js +52 -53
  28. package/lib/iService.js +106 -104
  29. package/lib/index.js +23 -21
  30. package/lib/parseDocker.js +3 -3
  31. package/lib/plugins/SASauth.js +30 -32
  32. package/lib/plugins/appCookie.js +36 -38
  33. package/lib/plugins/setContext.js +22 -25
  34. package/lib/plugins/setDefaultRoutes.js +61 -58
  35. package/lib/plugins/setupAuth.js +35 -38
  36. package/lib/plugins/setupUserRoutes.js +16 -16
  37. package/lib/plugins/token.js +9 -10
  38. package/lib/schemes/SASTokenScheme.js +24 -27
  39. package/package.json +85 -79
  40. package/public/data/Cluster_SDOH1.sas +181 -181
  41. package/public/data/Cluster_SDOH6.sas +179 -179
  42. package/public/data/NeuralNetwork_High_med.sas +2408 -2408
  43. package/public/data/NeuralNetwork_high_med1.sas +2408 -2408
  44. package/public/data/cars.csv +429 -429
  45. package/public/data/cmdList.txt +15 -15
  46. package/public/data/iris.csv +151 -151
  47. package/public/index.html +355 -360
  48. package/public/indexProxy.html +351 -351
  49. package/public/simplesubmit.html +233 -0
  50. package/server.js +362 -362
  51. package/src/config.js +90 -90
  52. package/src/handlers/appCallback.js +40 -40
  53. package/src/handlers/codeAuth.js +31 -31
  54. package/src/handlers/decodeJwt.js +10 -10
  55. package/src/handlers/favicon.js +23 -23
  56. package/src/handlers/getApp.js +52 -52
  57. package/src/handlers/getApp2.js +25 -25
  58. package/src/handlers/getUser.js +20 -20
  59. package/src/handlers/index.js +36 -36
  60. package/src/handlers/keepAlive.js +53 -53
  61. package/src/handlers/keepAlive2.js +12 -12
  62. package/src/handlers/logon.js +23 -23
  63. package/src/handlers/logout.js +42 -42
  64. package/src/handlers/proxyMapUri.js +25 -25
  65. package/src/handlers/proxyOnResponse.js +11 -11
  66. package/src/handlers/reactDev.js +29 -29
  67. package/src/handlers/setCookies.js +81 -79
  68. package/src/iService.js +346 -347
  69. package/src/index.js +251 -249
  70. package/src/parseDocker.js +32 -32
  71. package/src/plugins/SASauth.js +78 -78
  72. package/src/plugins/appCookie.js +51 -49
  73. package/src/plugins/setContext.js +33 -33
  74. package/src/plugins/setDefaultRoutes.js +256 -253
  75. package/src/plugins/setupAuth.js +49 -49
  76. package/src/plugins/setupUserRoutes.js +47 -47
  77. package/src/plugins/token.js +10 -10
  78. package/src/schemes/SASTokenScheme.js +43 -43
  79. package/src/visionIndex.html +23 -23
  80. package/start.sh +14 -14
  81. package/tls/viyatls.sh +2 -2
package/src/iService.js CHANGED
@@ -1,347 +1,346 @@
1
- /*
2
- * ------------------------------------------------------------------------------------
3
- * * Copyright (c) SAS Institute Inc.
4
- * * Licensed under the Apache License, Version 2.0 (the "License");
5
- * * you may not use this file except in compliance with the License.
6
- * * You may obtain a copy of the License at
7
- * *
8
- * * http://www.apache.org/licenses/LICENSE-2.0
9
- * *
10
- * * Unless required by applicable law or agreed to in writing, software
11
- * * distributed under the License is distributed on an "AS IS" BASIS,
12
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- * ----------------------------------------------------------------------------------------
16
- *
17
- */
18
-
19
- let fs = require('fs');
20
- let debug = require('debug')('service');
21
- let debug2 = require('debug')('tls');
22
- // let isDocker = require('is-docker');
23
- let Hapi = require('@hapi/hapi');
24
- let H202 = require('@hapi/h2o2');
25
- // const { isSameSiteNoneCompatible } = require('should-send-same-site-none');
26
- let NodeCache = require("node-cache-promise");
27
- let Vision = require('@hapi/vision');
28
- let inert = require('@hapi/inert');
29
- let selfsigned = require('selfsigned');
30
- import setupAuth from './plugins/setupAuth';
31
-
32
- let os = require('os');
33
-
34
- function iService (userRouteTable, useDefault, asset, allAppEnv, serverMode, userInfo) {
35
- // process.env.APPHOST_ADDR = process.env.APPHOST;
36
- const init = async () => {
37
-
38
- if (process.env.APPHOST === '*') {
39
- process.env.APPHOST = os.hostname();
40
- }
41
- let defaultMaxBytes = 10485760;
42
- let maxBytes;
43
- if (isNaN(process.env.PAYLOADMAXBYTES)) {
44
- maxBytes = defaultMaxBytes;
45
- } else {
46
- maxBytes = Number(process.env.PAYLOADMAXBYTES);
47
- }
48
- let isSameSite = 'None';
49
- let isSecure = false;
50
-
51
- if (process.env.SAMESITE != null) {
52
- let [s1, s2] = process.env.SAMESITE.split(',');
53
- isSameSite = s1;
54
- isSecure = s2 === 'secure' ? true : false;
55
- if (process.env.HTTPS !== 'true') {
56
- isSecure = false;
57
- }
58
- }
59
-
60
-
61
- let sConfig = {
62
- port: process.env.APPPORT,
63
- host: process.env.APPHOST,
64
-
65
- state: {
66
- isSameSite: isSameSite,
67
- isSecure : isSecure,
68
-
69
- },
70
-
71
-
72
- routes: {
73
- payload: {
74
- maxBytes: maxBytes
75
- },
76
- cors: {
77
- origin : ['*'],
78
- credentials: true,
79
-
80
- "headers": ["Accept", "Authorization", "Content-Type", "If-None-Match", "Accept-language"]
81
- /*
82
- 'Access-Control-Allow-Methods': ['GET', 'POST', 'OPTIONS'],
83
- additionalHeaders : ['multipart/form-data', 'content-disposition'],
84
- additionalExposedHeaders : ['location'],
85
- */
86
- }
87
-
88
- },
89
- };
90
- if (process.env.HAPIDEBUG === 'YES') {
91
- sConfig.debug = { request: '*' };
92
- }
93
- debug(JSON.stringify(sConfig, null,4));
94
- if (process.env.HTTPS === 'true') {
95
- sConfig.tls = await getCertificates();
96
- debug('Setup of SSL certificates completed');
97
- } else {
98
- debug('Running with no SSL certificates');
99
- }
100
- if (asset !== null) {
101
- sConfig.routes.files= { relativeTo: asset };
102
- }
103
-
104
- debug2(
105
- `Application information:
106
- APPLOC : ${process.env.APPLOC}
107
- APPENTRY: ${process.env.APPENTRY}
108
- `
109
- );
110
-
111
- let hapiServer = Hapi.server(sConfig);
112
-
113
- /*
114
- const cache = hapiServer.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });
115
- hapiServer.app.cache = cache;
116
- */
117
-
118
- let nodeCacheOptions = {
119
- stdTTL : 24*60*60*1000,
120
- checkPeriod : 3600,
121
- errorOnMissing: true,
122
- useClones : false,
123
- deleteOnExpire: true,
124
- };
125
- let storeCache = new NodeCache(nodeCacheOptions);
126
- hapiServer.app.cache = storeCache;
127
-
128
- // common plugins
129
- let visionOptions = {
130
- engines : { html: require('handlebars') },
131
- relativeTo: __dirname,
132
- path : '.',
133
- };
134
- await hapiServer.register(Vision);
135
- hapiServer.views(visionOptions);
136
- await hapiServer.register(inert);
137
- if (process.env.HTTPS === 'true') {
138
- await hapiServer.register({ plugin: require('hapi-require-https'), options: {} });
139
- }
140
- // register H202 for proxy handling
141
- // https://hapi.dev/module/h2o2/api/?v=10.0.1
142
-
143
- await hapiServer.register(H202);
144
- /*
145
- await hapiServer.register({
146
- plugin : require('hapi-pino'),
147
- options: {
148
- prettyPrint: process.env.NODE_ENV !== 'production',
149
- level : process.env.LOGLEVEL == null ? 'silent' : process.env.LOGLEVEL,
150
- },
151
- });
152
- */
153
-
154
- // setup authentication related plugins
155
-
156
- let options = {
157
- serverMode : serverMode,
158
- authFlow : process.env.AUTHFLOW,
159
- host : process.env.VIYA_SERVER,
160
- isSameSite : isSameSite,
161
- isSecure : isSecure,
162
- ns : (allAppEnv.LOGONPAYLOAD != null) ? allAppEnv.LOGONPAYLOAD.ns : null,
163
- nsHost : (allAppEnv.LOGONPAYLOAD != null) ? allAppEnv.LOGONPAYLOAD.nsHost : null,
164
- redirect : process.env.REDIRECT,
165
- clientId : process.env.CLIENTID,
166
- clientSecret : process.env.CLIENTSECRET,
167
- redirectTo : `/${process.env.APPNAME}/logon`,
168
- allAppEnv : allAppEnv,
169
- useHapiCookie : true,
170
- appName : process.env.APPNAME,
171
- appHost : process.env.APPHOST,
172
- appPort : process.env.APPPORT,
173
- userRouteTable: userRouteTable,
174
- useDefault : useDefault, /* not used - left here for potential reuse */
175
- userInfo : userInfo,
176
- https : process.env.HTTPS,
177
- authDefault : false, /* set later in setDefaultRoutes */
178
- authLogon : false /* set later in setDefaultRoutes */
179
-
180
- };
181
-
182
- debug2('Options',options);
183
- if (process.env.AUTHFLOW != null) {
184
- await setupAuth(hapiServer, options);
185
- if (process.env.PREAUTH === 'YES') {
186
- console.log('Preauth enabled');
187
- hapiServer.ext('onPreAuth', (request, h) => {
188
- debugger;
189
- if (!request.auth.isAuthenticated && !request.path.startsWith(`/login`)) {
190
- const redirectTo = `${request.path}?${new URLSearchParams(request.query).toString()}`;
191
- console.log('Redirect to login', {redirectTo});
192
- debugger;
193
- return h.redirect(`/login`).takeover();
194
- }
195
- return h.continue;
196
- });
197
- }
198
- }
199
- hapiServer.log('Plugin', process.env.PLUGIN);
200
-
201
- if (process.env.PLUGIN === 'hapi-swagger' && serverMode ==='api') {
202
- let swaggerOptions = {
203
- "info": {
204
- "title" : `API for ${process.env.APPNAME}`,
205
- "version" : "0.0.1",
206
- "description": "This document was auto-generated at run time"
207
- },
208
- "schemes" : ["http", "https"],
209
- "cors" : true,
210
- "debug" : true,
211
- "jsonPath" : `/${options.appName}/swagger.json`,
212
- "jsonRoutePath" : `/${options.appName}/swagger.json`,
213
- "documentationPage": true,
214
- "documentationPath": `/${options.appName}/documentation`,
215
- "swaggerUI" : true,
216
- "swaggerUIPath" : `/${options.appName}/swaggerui`,
217
- auth : options.authDefault
218
- };
219
-
220
- if (userInfo != null) {
221
- let override = userInfo(options, 'SWAGGEROPTIONS');
222
- swaggerOptions = {...swaggerOptions, ...override};
223
- }
224
-
225
- debug('Swagger Options:' ,swaggerOptions);
226
- await hapiServer.register({ plugin: serverMode, options: swaggerOptions });
227
- } else if (process.env.PLUGIN == 'hapi-openapi' && serverMode === 'api') {
228
- console.log('hapi-openapi', 'coming soon');
229
- }
230
-
231
-
232
- //
233
- // Start server
234
- //
235
- // eslint-disable-next-line no-unused-vars
236
- let allRoutes = hapiServer.table();
237
- await hapiServer.start();
238
- let hh = hapiServer.info.uri;
239
- hh = hh.replace(/0.0.0.0/, 'localhost');
240
- console.log('====================================================================================');
241
- console.log('Server Start Time: ', Date());
242
- let msg =
243
- options.serverMode === 'app'
244
- ? `Visit ${hh}/${process.env.APPNAME} to access application`
245
- : `Visit ${hh}/${process.env.APPNAME}/api to access swagger`;
246
- console.log('\x1b[1m%s\x1b[0m',msg);
247
- console.log('NOTE: If running in container use the exported port');
248
- process.env.APPSERVER = `${hh}/${process.env.APPNAME}`;
249
- process.env.HEALTH = 'true';
250
- console.log('====================================================================================');
251
- };
252
-
253
- process.on('unhandledRejection', (err) => {
254
- console.log(err);
255
- process.exit(1);
256
- });
257
- init();
258
- }
259
-
260
- async function getCertificates () {
261
-
262
- let tls = {};
263
- debug2('TLS_CRT', process.env.TLS_CRT != null);
264
- debug2('TLS_CREATE', process.env.TLS_CREATE != null);
265
- if (process.env.TLS_CRT != null && process.env.TLS_CRT.length > 0) {
266
- if (fs.existsSync(process.env.TLS_CRT) && fs.existsSync(process.env.TLS_KEY)) {
267
- console.log('TLS_CRT and TLS_KEY exist');
268
- tls.cert = fs.readFileSync(process.env.TLS_CRT);
269
- tls.key = fs.readFileSync(process.env.TLS_KEY);
270
- }
271
-
272
- }
273
- if (tls.cert == null && process.env.TLS_CREATE != null) {
274
- /* unsigned certificate */
275
- console.log('Creating selfsigned certificate');
276
- debug2('TLS set: TLS_CREATE=', process.env.TLS_CREATE);
277
- tls = await getTls();
278
- }
279
- if (Object.keys(tls).length === 0){
280
- console.log('Warning: The current host protocol is https: No TLS certificate information has been specified.');
281
- }
282
- return tls;
283
- }
284
-
285
- async function getTls () {
286
- let options = {
287
- keySize : 2048,
288
- days : 360,
289
- algorithm : "sha256",
290
- clientCertificate: true,
291
- extensions : {},
292
- };
293
- let subjt = process.env.TLS_CREATE.replaceAll('"', '').trim();
294
- let subj = subjt.split(',');
295
-
296
- let d = {};
297
- subj.map(c => {
298
- let r = c.split(':');
299
- d[ r[ 0 ] ] = r[ 1 ];
300
- return { value: r[ 1 ] };
301
- });
302
-
303
- // TLS_CREATE=C:US,ST:NC,L:Cary,O:SAS Institute,OU:STO,CN:localhost,ALT:na.sas.com
304
- let attr = [
305
- {
306
- name : 'commonName',
307
- value: d.CN /*process.env.APPHOST*/,
308
- },
309
- {
310
- name : 'countryName',
311
- value: d.C
312
- }, {
313
- shortName: 'ST',
314
- value : d.ST
315
- }, {
316
- name : 'localityName',
317
- value: d.L,
318
- }, {
319
- name : 'organizationName',
320
- value: d.O
321
- },
322
- {
323
- shortName: 'OU',
324
- value : d.OU
325
- }
326
- ];
327
-
328
- options.extensions.altNames = [
329
- // { type: 6, value: `http://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}` },
330
- { type: 6, value: `https://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}` },
331
- { type: 6, value: `https://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}/api` },
332
- { type: 6, value: `https://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}/logon` },
333
- { type: 6, value: `https://${process.env.APPHOST}/${process.env.APPNAME}` },
334
- { type: 6, value: `https://${process.env.APPHOST}/${process.env.APPNAME}/api` },
335
- { type: 6, value: `https://${process.env.APPHOST}/${process.env.APPNAME}/logon` },
336
- ];
337
- debug('tls options ', JSON.stringify(options, null,4));
338
- let pems = selfsigned.generate(attr, options);
339
- let tls = {
340
- cert: pems.cert,
341
- key : pems.private
342
- };
343
- return tls;
344
-
345
-
346
- }
347
- export default iService;
1
+ /*
2
+ * ------------------------------------------------------------------------------------
3
+ * * Copyright (c) SAS Institute Inc.
4
+ * * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * * you may not use this file except in compliance with the License.
6
+ * * You may obtain a copy of the License at
7
+ * *
8
+ * * http://www.apache.org/licenses/LICENSE-2.0
9
+ * *
10
+ * * Unless required by applicable law or agreed to in writing, software
11
+ * * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ * ----------------------------------------------------------------------------------------
16
+ *
17
+ */
18
+
19
+ let fs = require('fs');
20
+ let debug = require('debug')('service');
21
+ let debug2 = require('debug')('tls');
22
+ // let isDocker = require('is-docker');
23
+ let Hapi = require('@hapi/hapi');
24
+ let H202 = require('@hapi/h2o2');
25
+ // const { isSameSiteNoneCompatible } = require('should-send-same-site-none');
26
+ let NodeCache = require("node-cache-promise");
27
+ let Vision = require('@hapi/vision');
28
+ let inert = require('@hapi/inert');
29
+ let selfsigned = require('selfsigned');
30
+ import { response } from '@hapi/inert/lib/file';
31
+ import setupAuth from './plugins/setupAuth';
32
+
33
+ let os = require('os');
34
+
35
+ function iService (userRouteTable, useDefault, asset, allAppEnv, serverMode, userInfo) {
36
+ // process.env.APPHOST_ADDR = process.env.APPHOST;
37
+ const init = async () => {
38
+
39
+ if (process.env.APPHOST === '*') {
40
+ process.env.APPHOST = os.hostname();
41
+ }
42
+ let defaultMaxBytes = 10485760;
43
+ let maxBytes;
44
+ if (isNaN(process.env.PAYLOADMAXBYTES)) {
45
+ maxBytes = defaultMaxBytes;
46
+ } else {
47
+ maxBytes = Number(process.env.PAYLOADMAXBYTES);
48
+ }
49
+ let isSameSite = 'None';
50
+ let isSecure = false;
51
+
52
+ if (process.env.SAMESITE != null) {
53
+ let [s1, s2] = process.env.SAMESITE.split(',');
54
+ isSameSite = s1;
55
+ isSecure = s2 === 'secure' ? true : false;
56
+ if (process.env.HTTPS !== 'true') {
57
+ isSecure = false;
58
+ }
59
+ }
60
+
61
+
62
+ let sConfig = {
63
+ port: process.env.APPPORT,
64
+ host: process.env.APPHOST,
65
+
66
+ state: {
67
+ isSameSite: isSameSite,
68
+ isSecure : isSecure,
69
+
70
+ },
71
+
72
+
73
+ routes: {
74
+ payload: {
75
+ maxBytes: maxBytes
76
+ },
77
+ cors: {
78
+ origin : ['*'],
79
+ credentials: true,
80
+
81
+ "headers": ["Accept", "Authorization", "Content-Type", "If-None-Match", "Accept-language"]
82
+ /*
83
+ 'Access-Control-Allow-Methods': ['GET', 'POST', 'OPTIONS'],
84
+ additionalHeaders : ['multipart/form-data', 'content-disposition'],
85
+ additionalExposedHeaders : ['location'],
86
+ */
87
+ }
88
+
89
+ },
90
+ };
91
+ if (process.env.HAPIDEBUG === 'YES') {
92
+ sConfig.debug = { request: '*' };
93
+ }
94
+ debug(JSON.stringify(sConfig, null,4));
95
+ if (process.env.HTTPS === 'true') {
96
+ sConfig.tls = await getCertificates();
97
+ debug('Setup of SSL certificates completed');
98
+ } else {
99
+ debug('Running with no SSL certificates');
100
+ }
101
+ if (asset !== null) {
102
+ sConfig.routes.files= { relativeTo: asset };
103
+ }
104
+
105
+ debug2(
106
+ `Application information:
107
+ APPLOC : ${process.env.APPLOC}
108
+ APPENTRY: ${process.env.APPENTRY}
109
+ `
110
+ );
111
+
112
+ let hapiServer = Hapi.server(sConfig);
113
+
114
+ /*
115
+ const cache = hapiServer.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });
116
+ hapiServer.app.cache = cache;
117
+ */
118
+
119
+ let nodeCacheOptions = {
120
+ stdTTL : 24*60*60*1000,
121
+ checkPeriod : 3600,
122
+ errorOnMissing: true,
123
+ useClones : false,
124
+ deleteOnExpire: true,
125
+ };
126
+ let storeCache = new NodeCache(nodeCacheOptions);
127
+ hapiServer.app.cache = storeCache;
128
+
129
+ // common plugins
130
+ let visionOptions = {
131
+ engines : { html: require('handlebars') },
132
+ relativeTo: __dirname,
133
+ path : '.',
134
+ };
135
+ await hapiServer.register(Vision);
136
+ hapiServer.views(visionOptions);
137
+ await hapiServer.register(inert);
138
+ if (process.env.HTTPS === 'true') {
139
+ await hapiServer.register({ plugin: require('hapi-require-https'), options: {} });
140
+ }
141
+ // register H202 for proxy handling
142
+ // https://hapi.dev/module/h2o2/api/?v=10.0.1
143
+
144
+ await hapiServer.register(H202);
145
+ /*
146
+ await hapiServer.register({
147
+ plugin : require('hapi-pino'),
148
+ options: {
149
+ prettyPrint: process.env.NODE_ENV !== 'production',
150
+ level : process.env.LOGLEVEL == null ? 'silent' : process.env.LOGLEVEL,
151
+ },
152
+ });
153
+ */
154
+
155
+ // setup authentication related plugins
156
+
157
+ let options = {
158
+ serverMode : serverMode,
159
+ authFlow : process.env.AUTHFLOW,
160
+ host : process.env.VIYA_SERVER,
161
+ isSameSite : isSameSite,
162
+ isSecure : isSecure,
163
+ ns : (allAppEnv.LOGONPAYLOAD != null) ? allAppEnv.LOGONPAYLOAD.ns : null,
164
+ nsHost : (allAppEnv.LOGONPAYLOAD != null) ? allAppEnv.LOGONPAYLOAD.nsHost : null,
165
+ redirect : process.env.REDIRECT,
166
+ clientId : process.env.CLIENTID,
167
+ clientSecret : process.env.CLIENTSECRET,
168
+ redirectTo : `/${process.env.APPNAME}/logon`,
169
+ allAppEnv : allAppEnv,
170
+ useHapiCookie : true,
171
+ appName : process.env.APPNAME,
172
+ appHost : process.env.APPHOST,
173
+ appPort : process.env.APPPORT,
174
+ userRouteTable: userRouteTable,
175
+ useDefault : useDefault, /* not used - left here for potential reuse */
176
+ userInfo : userInfo,
177
+ https : process.env.HTTPS,
178
+ authDefault : false, /* set later in setDefaultRoutes */
179
+ authLogon : false /* set later in setDefaultRoutes */
180
+
181
+ };
182
+
183
+ debug2('Options',options);
184
+ if (process.env.AUTHFLOW != null) {
185
+ await setupAuth(hapiServer, options);
186
+ if (process.env.PREAUTH === 'YES') {
187
+ console.log('Preauth enabled');
188
+ hapiServer.ext('onPreAuth', (request, h) => {
189
+ debugger;
190
+ if (!request.auth.isAuthenticated && !request.path.startsWith(`/login`)) {
191
+ const redirectTo = `${request.path}?${new URLSearchParams(request.query).toString()}`;
192
+ console.log('Redirect to login', {redirectTo});
193
+ debugger;
194
+ return h.redirect(`/login`).takeover();
195
+ }
196
+ return h.continue;
197
+ });
198
+ }
199
+ }
200
+ console.log('Plugin', process.env.PLUGIN);
201
+
202
+ if (process.env.PLUGIN === 'hapi-swagger' && serverMode ==='api') {
203
+ let swaggerOptions = {
204
+ "info": {
205
+ "title" : `API for ${process.env.APPNAME}`,
206
+ "version" : "0.0.1",
207
+ "description": "This document was auto-generated at run time"
208
+ },
209
+ "schemes" : ["http", "https"],
210
+ "cors" : true,
211
+ "debug" : true,
212
+ "jsonPath" : `/${options.appName}/swagger.json`,
213
+ "jsonRoutePath" : `/${options.appName}/swagger.json`,
214
+ "documentationPage": true,
215
+ "documentationPath": `/${options.appName}/documentation`,
216
+ "swaggerUI" : true,
217
+ "swaggerUIPath" : `/${options.appName}/swaggerui`,
218
+ auth : options.authDefault
219
+ };
220
+
221
+ if (userInfo != null) {
222
+ let override = userInfo(options, 'SWAGGEROPTIONS');
223
+ swaggerOptions = {...swaggerOptions, ...override};
224
+ }
225
+
226
+ debug('Swagger Options:' ,swaggerOptions);
227
+ await hapiServer.register({ plugin: serverMode, options: swaggerOptions });
228
+ } else if (process.env.PLUGIN == 'hapi-openapi' && serverMode === 'api') {
229
+ console.log('hapi-openapi', 'coming soon');
230
+ }
231
+
232
+
233
+ //
234
+ // Start server
235
+ //
236
+ // eslint-disable-next-line no-unused-vars
237
+ let allRoutes = hapiServer.table();
238
+ await hapiServer.start();
239
+ let hh = hapiServer.info.uri;
240
+ hh = hh.replace(/0.0.0.0/, 'localhost');
241
+ console.log('====================================================================================');
242
+ console.log('Server Start Time: ', Date());
243
+ let msg =
244
+ options.serverMode === 'app'
245
+ ? `Visit ${hh}/${process.env.APPNAME} to access application`
246
+ : `Visit ${hh}/${process.env.APPNAME}/api to access swagger`;
247
+ console.log('\x1b[1m%s\x1b[0m',msg);
248
+ console.log('NOTE: If running in container use the exported port');
249
+ process.env.APPSERVER = `${hh}/${process.env.APPNAME}`;
250
+ process.env.HEALTH = 'true';
251
+ console.log('====================================================================================');
252
+ };
253
+
254
+ process.on('unhandledRejection', (err) => {
255
+ console.log(err);
256
+ process.exit(1);
257
+ });
258
+ init();
259
+ }
260
+
261
+ async function getCertificates () {
262
+
263
+ let options = null;
264
+ let tlsdir = process.env.SSLCERT;
265
+ if (tlsdir != null && tlsdir.trim().length > 0) {
266
+ console.log('ssl CERTIFICATES', tlsdir);
267
+ if (fs.existsSync(`${tlsdir}/key.pem`) === true) {
268
+ options = {};
269
+ options.key = fs.readFileSync(`${tlsdir}/key.pem`, { encoding: 'utf8' });
270
+ options.cert = fs.readFileSync(`${tlsdir}/crt.pem`, { encoding: 'utf8' });
271
+ if (fs.existsSync(`${tlsdir}/ca.pem`) === true) {
272
+ options.ca = fs.readFileSync(`${tlsdir}/ca.pem`, { encoding: 'utf8' });
273
+ }
274
+ options.rejectUnauthorized= true;
275
+ }
276
+ } else {
277
+ console.log('No SSL certificates found, generating self-signed certificates');
278
+ options = await getTls();
279
+ options.rejectUnauthorized= false;
280
+ }
281
+ return options;
282
+ }
283
+
284
+ async function getTls () {
285
+ let options = {
286
+ keySize : 2048,
287
+ days : 360,
288
+ algorithm : "sha256",
289
+ clientCertificate: true,
290
+ extensions : {},
291
+ };
292
+ let subjt = process.env.TLS_CREATE.replaceAll('"', '').trim();
293
+ let subj = subjt.split(',');
294
+
295
+ let d = {};
296
+ subj.map(c => {
297
+ let r = c.split(':');
298
+ d[ r[ 0 ] ] = r[ 1 ];
299
+ return { value: r[ 1 ] };
300
+ });
301
+
302
+ // TLS_CREATE=C:US,ST:NC,L:Cary,O:SAS Institute,OU:STO,CN:localhost,ALT:na.sas.com
303
+ let attr = [
304
+ {
305
+ name : 'commonName',
306
+ value: d.CN /*process.env.APPHOST*/,
307
+ },
308
+ {
309
+ name : 'countryName',
310
+ value: d.C
311
+ }, {
312
+ shortName: 'ST',
313
+ value : d.ST
314
+ }, {
315
+ name : 'localityName',
316
+ value: d.L,
317
+ }, {
318
+ name : 'organizationName',
319
+ value: d.O
320
+ },
321
+ {
322
+ shortName: 'OU',
323
+ value : d.OU
324
+ }
325
+ ];
326
+
327
+ options.extensions.altNames = [
328
+ // { type: 6, value: `http://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}` },
329
+ { type: 6, value: `https://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}` },
330
+ { type: 6, value: `https://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}/api` },
331
+ { type: 6, value: `https://${process.env.APPHOST}:${process.env.APPPORT}/${process.env.APPNAME}/logon` },
332
+ { type: 6, value: `https://${process.env.APPHOST}/${process.env.APPNAME}` },
333
+ { type: 6, value: `https://${process.env.APPHOST}/${process.env.APPNAME}/api` },
334
+ { type: 6, value: `https://${process.env.APPHOST}/${process.env.APPNAME}/logon` },
335
+ ];
336
+ debug('tls options ', JSON.stringify(options, null,4));
337
+ let pems = selfsigned.generate(attr, options);
338
+ let tls = {
339
+ cert: pems.cert,
340
+ key : pems.private
341
+ };
342
+ return tls;
343
+
344
+
345
+ }
346
+ export default iService;