This repository was archived by the owner on Oct 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp-legacy.js
More file actions
310 lines (266 loc) · 8.06 KB
/
app-legacy.js
File metadata and controls
310 lines (266 loc) · 8.06 KB
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
// IMPORTS
//
const errorHandler = require('koa-better-error-handler');
const Koa = require('koa');
const Router = require('koa-router');
const koa404Handler = require('koa-404-handler');
// const logger = require('koa-logger');
// const cors = require('@koa/cors');
const bodyParser = require('koa-bodyparser');
// const debuggingHandler = require('./middlewares/debugging');
const knex = require('knex');
const axios = require('axios');
const crypto = require('crypto');
const userAgent = require('koa2-useragent');
const { knexSnakeCaseMappers } = require('objection');
const Redis = require('ioredis');
const helmet = require('koa-helmet');
const redisStore = require('koa-redis');
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const session = require('koa-generic-session');
//
// require('@google-cloud/profiler').start({
// serviceContext: {
// service: process.env.SERVICE_NAMESPACE,
// version: '1.0.0',
// },
// });
const {
// DATABASE_URL,
// PG_OPTIONS,
ZOOM_JWT,
REDIS_HOST,
DISABLE_REQUEST_LOGGING,
REDIS_LOGGING_ENABLED,
SESSION_LOGGING_ENABLED
} = require('./config');
// INSTANTIATE APPLICATION
//
const app = new Koa({
proxy: true // so X-Forwarded-Headers are used
});
app.keys = ['verifier!@#', 'issuer!@#', 'holder!@#'];
// override koa's undocumented error handler
app.context.onerror = errorHandler;
// specify that this is our api so that koa-better-error-handler gives text instead of html
app.context.api = true;
// use koa-404-handler
app.use(koa404Handler);
const router = new Router();
// STANDARD MIDDLEWARES FOR SECURITY, ETC
//
// Logging requests
// app.use(debuggingHandler);
//
// if (!DISABLE_REQUEST_LOGGING) {
// app.use(logger()); // help us with logging
// }
app.use(
bodyParser({
extendTypes: {
// needed for Flutter to easily speak to API
json: ['application/x-javascript']
// eventsource: ['text/event-stream']
}
})
);
// app.use(
// helmet({
// hsts: false
// })
// );
app.use(userAgent());
// app.use(
// cors({
// // origin: '*',
// // credentials: true,
// exposeHeaders: ['Access-Control-Allow-Origin', 'ETag'],
// origin: (ctx) => {
// const { origin } = ctx.request.header;
// if (origin) {
// const patterns = [
// /^https?:\/\/(.+\.)?mymedcreds.com$/,
// /^https?:\/\/(.+\.)?medcreds.com$/,
// /^https?:\/\/localhost:\d+$/,
// /^https?:\/\/deploy-preview-\d+--portal-mymedcreds.netlify.app$/,
// /^https?:\/\/(.+\.)?a.run.app$/
// ];
// for (const pattern of patterns) {
// let isMatch = origin.match(pattern);
// if (isMatch) {
// return origin;
// }
// }
// }
// },
// credentials: true
// })
// );
//
app.use(conditional());
app.use(etag());
// random code generators
const randTokenGen = require('rand-token').generator({
chars: 'A-Z',
source: crypto.randomBytes
});
const nonseGen = require('rand-token').generator({
chars: 'default',
source: crypto.randomBytes
});
const rand2fa = require('rand-token').generator({
chars: '0-9',
source: crypto.randomBytes
});
const murmur = require('murmurhash-js');
const fake_2fa_seed = process.env.FAKE_2FA_SEED ? Number(process.env.FAKE_2FA_SEED) : 0;
const twoFactorTokenGen = (ctx, email, length) => {
const nonse = nonseGen.generate(18);
if (email.toLowerCase().match(/7smew\.[a-zA-Z0-9]*@inbox.testmail.app/i)) {
let token = (Math.abs(murmur.murmur3(email, fake_2fa_seed)) % Math.pow(10, length))
.toString()
.padStart(length, '0');
ctx.warn(`Fake 2FA token ${token} generated for user "${email}".`);
return { token: token, nonse: nonse, isFake: true };
} else {
return { token: rand2fa.generate(length), nonse: nonse, isFake: false };
}
};
// register own middleware
app.use(async (ctx, next) => {
ctx.randtoken = randTokenGen;
ctx.generate_2fa_token = (email, length) => twoFactorTokenGen(ctx, email, length);
await next();
});
const redis = new Redis({
host: REDIS_HOST,
maxRetriesPerRequest: 2,
reconnectOnError: ({ message }) => {
if (message.includes('READONLY')) return true;
}
});
redis.on('error', (e) => {
console.error('redis error', e);
console.error('redis unable to connect', REDIS_HOST);
});
if (REDIS_LOGGING_ENABLED) {
redis.on('ready', () => {
console.log('redis ready');
});
redis.on('connect', () => {
console.log('redis connected');
});
redis.on('reconnecting', () => {
console.log('redis reconnecting');
});
redis.on('close', () => {
console.log('redis close');
});
redis.on('end', () => {
console.log('redis end');
});
}
app.context.redis = redis;
const oneHour = 60 * 60 * 1000;
const oneDay = oneHour * 24;
const oneMonth = oneDay * 30;
// this hacky stuff is need to dev on localStorage, i.e. not passing any domain value
const sessConfig = {
rolling: true,
ttl: oneMonth,
store: redisStore({ client: redis }),
cookie: {
httpOnly: true,
overwrite: true,
maxAge: oneMonth
}
};
if (process.env.NODE_ENV === 'production') {
sessConfig.cookie.domain = 'medcreds.com';
sessConfig.cookie.secure = true;
sessConfig.cookie.signed = true;
}
app.use(session(sessConfig));
// API CONNECTIONS
//
const $zoom = axios.create({
baseURL: 'https://api.zoom.us/v2',
headers: {
Authorization: ZOOM_JWT,
'Content-Type': 'application/json'
}
});
app.context.$zoom = $zoom;
app.context.$sender = require('./services/sender');
// deprecated
app.context.sender = app.context.$sender;
app.context.mailgun = require('./services/mailgun');
// DATABASE CONNECTIONS
//
const psql = knex({
client: 'pg',
connection: `${DATABASE_URL}${PG_OPTIONS}`,
...knexSnakeCaseMappers()
});
app.context.psql = psql;
// register street-cred access.
const streetCred = require('./services/streetcred')(psql);
app.use(async (ctx, next) => {
const withOrg = async (orgId, doIt) => ctx.monitor('Trinsic Call', streetCred.withOrg, orgId, doIt);
const withRootOrg = async (doIt) => ctx.monitor('Trinsic Call', streetCred.withRootOrg, doIt);
ctx.$streetcred = { ...streetCred, withOrg, withRootOrg };
ctx.streetcred = ctx.$streetcred;
ctx.trinsic = ctx.$streetcred;
await next();
});
app.context.$google = require('./services/google');
app.context.$metrics = require('./services/metrics')(psql);
app.context.$withers = require('./services/withers');
const { isAuthorized } = require('./services/roles');
app.context.isAuthorized = isAuthorized;
// INSTANTIATE ROUTERS WITH DATABASE CONNECTIONS
//
app.use(require('./routes/health')({ psql }).routes());
app.use(require('./routes/tests')({ psql, knex }).routes());
app.use(require('./routes/db')({ psql }).routes());
app.use(require('./routes/auth')({ psql }).routes());
app.use(require('./routes/webhooks')({ psql, knex }).routes());
// app.use(sse({
// maxClients: 5000,
// pingInterval: 30000
// }))
//
// anything above this will won't require a valid JWT to access
//
// app.use(jwt({ secret: fs.readFileSync('./jwt/server.cert') }))
//
app.use(async (ctx, next) => {
const { user } = ctx.session;
// if (SESSION_LOGGING_ENABLED) {
// console.log(ctx.traceId, 'session', user);
// }
if (user && user.id && user.roles) {
await next();
} else {
// if (SESSION_LOGGING_ENABLED) {
// console.error(ctx.traceId, 'missing session 401');
// }
ctx.session = null;
ctx.throw(401);
}
});
// anything below this will require a valid JWT to access
app.use(require('./routes/metrics')({ psql }).routes());
app.use(require('./routes/user')({ psql, knex, redis }).routes());
app.use(require('./routes/sse')({ psql, knex, redis }).routes());
app.use(require('./routes/ssi')().routes());
app.use(require('./routes/ssi-custodian')().routes());
app.use(require('./routes/organization')({ psql, knex }).routes());
app.use(require('./routes/zoom')({ psql }).routes());
app.use(require('./routes/verification')({ psql, redis }).routes());
app.use(require('./routes/custodian')({ psql }).routes());
app.use(router.routes());
app.use(router.allowedMethods());
// app.use(errorCatcher)
module.exports = app;