Repository navigation
Expand file tree
/
Copy pathmain.ts
More file actions
208 lines (174 loc) · 6.57 KB
/
Copy pathmain.ts
File metadata and controls
208 lines (174 loc) · 6.57 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
// Import this first from sentry instrument!
import '@utils/instrumentSentry';
// Now import other modules
import { ProviderFiles } from '@api/provider/sessions';
import { PrismaRepository } from '@api/repository/repository.service';
import { HttpStatus, router } from '@api/routes/index.router';
import { buildLicenseRouter } from '@api/routes/license.router';
import { eventManager, waMonitor } from '@api/server.module';
import {
Auth,
configService,
Cors,
HttpServer,
ProviderSession,
Sentry as SentryConfig,
Webhook,
} from '@config/env.config';
import { onUnexpectedError } from '@config/error.config';
import { Logger } from '@config/logger.config';
import { ROOT_DIR } from '@config/path.config';
import { gateMiddleware, initializeRuntime, shutdown, startHeartbeat } from '@licensing/runtime';
import { setDB } from '@licensing/store';
import * as Sentry from '@sentry/node';
import { ServerUP } from '@utils/server-up';
import axios from 'axios';
import compression from 'compression';
import cors from 'cors';
import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
import { join } from 'path';
async function initWA() {
await waMonitor.loadInstance();
}
async function bootstrap() {
const logger = new Logger('SERVER');
const app = express();
let providerFiles: ProviderFiles = null;
if (configService.get<ProviderSession>('PROVIDER').ENABLED) {
providerFiles = new ProviderFiles(configService);
await providerFiles.onModuleInit();
logger.info('Provider:Files - ON');
}
const prismaRepository = new PrismaRepository(configService);
await prismaRepository.onModuleInit();
// Licensing — must be initialized after Prisma is connected and BEFORE any
// business router is registered. The gate middleware sits in front of routes
// and returns 503 LICENSE_REQUIRED if the license is not active yet.
setDB(prismaRepository);
const licensingRC = await initializeRuntime({
tier: 'evolution-api',
version: process.env.npm_package_version || 'unknown',
globalApiKey: configService.get<Auth>('AUTHENTICATION').API_KEY.KEY,
});
const startedAt = new Date();
app.use(
cors({
origin(requestOrigin, callback) {
const { ORIGIN } = configService.get<Cors>('CORS');
if (ORIGIN.includes('*')) {
return callback(null, true);
}
if (ORIGIN.indexOf(requestOrigin) !== -1) {
return callback(null, true);
}
return callback(new Error('Not allowed by CORS'));
},
methods: [...configService.get<Cors>('CORS').METHODS],
credentials: configService.get<Cors>('CORS').CREDENTIALS,
}),
urlencoded({ extended: true, limit: '136mb' }),
json({
limit: '136mb',
verify: (req: any, _res, buf) => {
// Captura o RAW body para validação de HMAC (webhook EvoHub X-Hub-Signature-256).
// express.json() re-serializa o body; o HMAC do hub assina os bytes crus.
req.rawBody = buf;
},
}),
compression(),
);
app.set('view engine', 'hbs');
app.set('views', join(ROOT_DIR, 'views'));
app.use(express.static(join(ROOT_DIR, 'public')));
app.use('/store', express.static(join(ROOT_DIR, 'store')));
// Licensing — public routes (always work) and gate middleware (blocks rest).
app.use('/license', buildLicenseRouter(licensingRC));
app.use(gateMiddleware(licensingRC));
app.use('/', router);
app.use(
(err: Error, req: Request, res: Response, next: NextFunction) => {
if (err) {
const webhook = configService.get<Webhook>('WEBHOOK');
if (webhook.EVENTS.ERRORS_WEBHOOK && webhook.EVENTS.ERRORS_WEBHOOK != '' && webhook.EVENTS.ERRORS) {
const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
const localISOTime = new Date(Date.now() - tzoffset).toISOString();
const now = localISOTime;
const globalApiKey = configService.get<Auth>('AUTHENTICATION').API_KEY.KEY;
const serverUrl = configService.get<HttpServer>('SERVER').URL;
const errorData = {
event: 'error',
data: {
error: err['error'] || 'Internal Server Error',
message: err['message'] || 'Internal Server Error',
status: err['status'] || 500,
response: {
message: err['message'] || 'Internal Server Error',
},
},
date_time: now,
api_key: globalApiKey,
server_url: serverUrl,
};
logger.error(errorData);
const baseURL = webhook.EVENTS.ERRORS_WEBHOOK;
const httpService = axios.create({ baseURL });
httpService.post('', errorData);
}
return res.status(err['status'] || 500).json({
status: err['status'] || 500,
error: err['error'] || 'Internal Server Error',
response: {
message: err['message'] || 'Internal Server Error',
},
});
}
next();
},
(req: Request, res: Response, next: NextFunction) => {
const { method, url } = req;
res.status(HttpStatus.NOT_FOUND).json({
status: HttpStatus.NOT_FOUND,
error: 'Not Found',
response: {
message: [`Cannot ${method.toUpperCase()} ${url}`],
},
});
next();
},
);
const httpServer = configService.get<HttpServer>('SERVER');
ServerUP.app = app;
let server = ServerUP[httpServer.TYPE];
if (server === null) {
logger.warn('SSL cert load failed — falling back to HTTP.');
logger.info("Ensure 'SSL_CONF_PRIVKEY' and 'SSL_CONF_FULLCHAIN' env vars point to valid certificate files.");
httpServer.TYPE = 'http';
server = ServerUP[httpServer.TYPE];
}
eventManager.init(server);
const sentryConfig = configService.get<SentryConfig>('SENTRY');
if (sentryConfig.DSN) {
logger.info('Sentry - ON');
// Add this after all routes,
// but before any and other error-handling middlewares are defined
Sentry.setupExpressErrorHandler(app);
}
server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT));
// Start licensing heartbeat (30 min) — fire-and-forget.
startHeartbeat(licensingRC, startedAt);
// Notify the licensing server about graceful shutdown.
const onSignal = async () => {
try {
await shutdown(licensingRC);
} finally {
process.exit(0);
}
};
process.on('SIGTERM', onSignal);
process.on('SIGINT', onSignal);
initWA().catch((error) => {
logger.error('Error loading instances: ' + error);
});
onUnexpectedError();
}
bootstrap();