-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
315 lines (276 loc) · 9.98 KB
/
Copy pathserver.js
File metadata and controls
315 lines (276 loc) · 9.98 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
311
312
313
314
315
const express = require('express');
const rateLimit = require('express-rate-limit');
const puppeteer = require('puppeteer');
const app = express();
const path = require('path');
const fs = require('fs').promises;
const bootstrapCV = require('./bootstrap');
const Outlooks = require('./outlooks');
const { getAiResponse, preSyncVectorCache } = require('./ai-rep');
const { getJSON } = require('./data-cache');
require('dotenv').config();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static('public'));
app.use(express.json({ limit: '64kb' }));
// API Rate Limiting (60 requests per IP every 10 minutes)
const apiLimiter = rateLimit({
windowMs: 10 * 60 * 1000,
max: 60,
message: { error: 'Too many requests. Please try again in 10 minutes.' },
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', apiLimiter);
// Custom Frontend Token Middleware to block non-app requests
app.use('/api/', (req, res, next) => {
const appKey = req.headers['x-application-key'];
const expectedKey = process.env.APP_FRONTEND_TOKEN;
if (!expectedKey || appKey !== expectedKey) {
return res.status(403).json({ error: 'Direct API access is not allowed.' });
}
next();
});
const LANGUAGES = ['en', 'nl', 'fr'];
const PORT = process.env.PORT || 3000;
/**
* Language detection middleware.
* Extracts language from route param (:lang) or query string (?lang=).
* If :lang is present but invalid, skips to next matching route.
*/
function detectLanguage(req, res, next) {
if (req.params.lang) {
if (!LANGUAGES.includes(req.params.lang)) {
return next('route');
}
req.lang = req.params.lang;
} else {
req.lang = (req.query.lang && LANGUAGES.includes(req.query.lang))
? req.query.lang
: 'nl';
}
next();
}
// Central data preparer (async) with cached referrers
const getCommonData = async (lang, refKey = 'default') => {
const referrers = await getJSON(path.join(__dirname, './data/referrers.json'));
const config = referrers[refKey] || referrers['default'];
const cv = await bootstrapCV(lang, refKey);
return {
ui: cv.ui,
general: cv.general,
colors: config.colors || referrers['default'].colors,
personaIds: cv.ui.nav && cv.ui.nav.personas ? Object.keys(cv.ui.nav.personas) : [],
config,
cv,
currentLang: lang,
availableLanguages: LANGUAGES,
appFrontendToken: process.env.APP_FRONTEND_TOKEN || ""
};
};
/**
* AI Proxy Route
*/
app.post('/api/ai/ask', async (req, res) => {
const { query, pass, ref, lang } = req.body;
const onStatus = (status) => {
if (!res.headersSent) {
res.setHeader('Content-Type', 'application/x-ndjson');
res.setHeader('Transfer-Encoding', 'chunked');
}
res.write(JSON.stringify({ status }) + '\n');
};
try {
const answer = await getAiResponse(query, pass, ref, lang, onStatus);
if (!res.headersSent) {
res.setHeader('Content-Type', 'application/x-ndjson');
res.setHeader('Transfer-Encoding', 'chunked');
}
res.write(JSON.stringify({ answer }) + '\n');
res.end();
} catch (err) {
if (!res.headersSent) {
if (err.message === 'Unauthorized') {
return res.status(403).json({ error: 'Access denied. Incorrect key.' });
}
if (err.message === 'QUOTA_EXHAUSTED') {
return res.status(429).json({ error: 'QUOTA_EXHAUSTED' });
}
console.error('AI ROUTE ERROR:', err);
res.status(500).json({ error: 'The proxy is temporarily offline.' });
} else {
console.error('AI STREAM ERROR:', err);
res.write(JSON.stringify({ error: err.message === 'QUOTA_EXHAUSTED' ? 'QUOTA_EXHAUSTED' : 'The proxy is temporarily offline.' }) + '\n');
res.end();
}
}
});
/**
* 1. Outlooks Route
*/
app.get(['/outlooks/:slug?', '/:lang/outlooks/:slug?'], detectLanguage, async (req, res) => {
try {
const lang = req.lang;
const slug = req.params.slug;
const common = await getCommonData(lang, 'default');
const viewData = { ...common, currentRef: 'outlooks' };
if (slug) {
viewData.post = await Outlooks.getBySlug(slug, lang);
if (!viewData.post) return res.status(404).render('404', common);
return res.render('outlooks_post', viewData);
}
viewData.posts = await Outlooks.getAll(lang);
res.render('outlooks_index', viewData);
} catch (err) {
console.error('OUTLOOKS ERROR:', err);
res.status(500).send('Something went wrong.');
}
});
/**
* 2. PDF Export Route
*/
app.get(['/:lang/export-pdf/:ref', '/export-pdf/:ref'], async (req, res) => {
try {
let lang = req.params.lang || 'nl';
if (!LANGUAGES.includes(lang)) {
if (LANGUAGES.includes(req.query.lang)) {
lang = req.query.lang;
} else {
lang = 'nl';
}
}
const ref = req.params.ref || 'default';
const common = await getCommonData(lang, ref);
const { config, cv } = common;
const profile = cv.profile;
const subName = (config.company_name && config.company_name.trim()) || profile.job_title;
const sanitizedSubName = subName.replace(/[^a-z0-9]/gi, '_');
const filename = `CV-${sanitizedSubName}.pdf`;
console.log(`Generating PDF for ${lang}/${ref}...`);
const browser = await puppeteer.launch({
headless: 'new',
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || null,
protocolTimeout: 60000,
pipe: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu'
]
});
const page = await browser.newPage();
const targetUrl = `http://127.0.0.1:${PORT}/${lang}/${ref}`;
await page.goto(targetUrl, {
waitUntil: 'networkidle2',
timeout: 60000
});
await page.emulateMediaType('screen');
await page.addStyleTag({
content: `
nav, #greeting-section, .no-print, #ai-unlock-container, #ai-chat-interface {
display: none !important;
}
body {
margin: 0 !important;
padding-bottom: 0 !important;
background-attachment: scroll !important;
}
main {
margin-bottom: 0 !important;
padding-bottom: 40px !important;
}
html, body {
height: auto !important;
overflow: visible !important;
}
`
});
await new Promise(resolve => setTimeout(resolve, 500));
const bodyHeight = await page.evaluate(() => {
return Math.max(
document.body.scrollHeight,
document.body.offsetHeight,
document.documentElement.clientHeight,
document.documentElement.scrollHeight,
document.documentElement.offsetHeight
);
});
const pdf = await page.pdf({
width: '210mm',
height: (bodyHeight + 50) + 'px',
printBackground: true,
margin: { top: '0', right: '0', bottom: '0', left: '0' },
displayHeaderFooter: false,
preferCSSPageSize: false
});
await browser.close();
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.send(pdf);
console.log(`PDF generated: ${filename}`);
} catch (err) {
console.error('PDF EXPORT ERROR:', err);
res.status(500).send('Something went wrong.');
}
});
/**
* 3. Contact Route
*/
app.get(['/:lang/contact', '/contact'], detectLanguage, async (req, res) => {
try {
const common = await getCommonData(req.lang, 'default');
res.render('contact', {
...common,
currentRef: 'contact'
});
} catch (err) {
console.error('CONTACT ERROR:', err);
res.status(500).send('Something went wrong.');
}
});
/**
* 4. CV Catch-all Route
*/
app.get('/:param1?/:param2?', async (req, res) => {
try {
let lang = 'nl';
let ref = 'default';
if (LANGUAGES.includes(req.params.param1)) {
lang = req.params.param1;
ref = req.params.param2 || 'default';
} else {
ref = req.params.param1 || 'default';
if (req.query.lang && LANGUAGES.includes(req.query.lang)) lang = req.query.lang;
}
if (ref.includes('.') || ref === 'outlooks') {
return res.status(404).render('404', await getCommonData(lang, 'default'));
}
const common = await getCommonData(lang, ref);
res.render('index', {
...common,
currentRef: ref,
jobs: common.cv.jobs,
jobGroups: common.cv.jobGroups || null,
grouped: common.cv.grouped || false,
featuredProject: common.cv.featuredProject || null,
education: common.cv.education,
projects: common.cv.projects,
profile: common.cv.profile,
languages: common.cv.languages
});
} catch (err) {
console.error('SERVER ERROR:', err);
res.status(500).send('Something went wrong.');
}
});
app.listen(PORT, async () => {
console.log(`CV Engine running at http://localhost:${PORT}`);
try {
console.log('Synchronizing vector cache...');
await preSyncVectorCache();
console.log('Vector cache synchronized.');
} catch (err) {
console.error('Startup cache sync failed:', err);
}
});