-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
299 lines (249 loc) · 12.5 KB
/
Copy pathserver.js
File metadata and controls
299 lines (249 loc) · 12.5 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
// server.js — Resume Evaluator Backend (multi-user, per-user Claude API keys)
//
// npm install express better-sqlite3 bcryptjs jsonwebtoken cors dotenv @anthropic-ai/sdk pdf-parse mammoth multer
import express from 'express';
import cors from 'cors';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import Database from 'better-sqlite3';
import Anthropic from '@anthropic-ai/sdk';
import mammoth from 'mammoth';
import 'dotenv/config';
import fs from 'fs';
import path from 'path';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const pdfParse = require('pdf-parse');
const PDFDocument = require('pdfkit');
const app = express();
const db = new Database('evaluator.db');
// ── DB Setup ────────────────────────────────────────────────
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
api_key_enc TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
// ── Simple reversible encryption for stored API keys ────────
// Uses AES-256-GCM via Node's built-in crypto module
import crypto from 'crypto';
const ENC_KEY = Buffer.from(
(process.env.ENCRYPTION_KEY || 'default-32-char-key-change-this!!').padEnd(32).slice(0, 32)
);
function encryptKey(text) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', ENC_KEY, iv);
const enc = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return iv.toString('hex') + ':' + tag.toString('hex') + ':' + enc.toString('hex');
}
function decryptKey(stored) {
const [ivHex, tagHex, encHex] = stored.split(':');
const decipher = crypto.createDecipheriv('aes-256-gcm', ENC_KEY, Buffer.from(ivHex, 'hex'));
decipher.setAuthTag(Buffer.from(tagHex, 'hex'));
return decipher.update(Buffer.from(encHex, 'hex')) + decipher.final('utf8');
}
// ── Middleware ──────────────────────────────────────────────
app.use(cors({ origin: process.env.FRONTEND_URL || '*' }));
app.use(express.json({ limit: '20mb' }));
// ── Auth Middleware ─────────────────────────────────────────
function requireAuth(req, res, next) {
const header = req.headers.authorization;
if (!header?.startsWith('Bearer ')) return res.status(401).json({ error: 'Unauthorized' });
try {
req.user = jwt.verify(header.slice(7), process.env.JWT_SECRET || 'dev-secret');
next();
} catch {
res.status(401).json({ error: 'Invalid or expired token' });
}
}
// ── Auth Routes ─────────────────────────────────────────────
// Register — set ALLOW_REGISTRATION=false in .env to disable public sign-ups
app.post('/auth/register', (req, res) => {
if (process.env.ALLOW_REGISTRATION === 'false')
return res.status(403).json({ error: 'Registration is currently closed.' });
const { username, password } = req.body;
if (!username || !password) return res.status(400).json({ error: 'Missing fields' });
if (password.length < 8) return res.status(400).json({ error: 'Password must be 8+ characters' });
if (username.length < 3) return res.status(400).json({ error: 'Username must be 3+ characters' });
try {
const hash = bcrypt.hashSync(password, 12);
db.prepare('INSERT INTO users (username, password_hash) VALUES (?, ?)').run(username, hash);
res.json({ success: true });
} catch (e) {
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'Username already taken' });
res.status(500).json({ error: 'Registration failed' });
}
});
// Login
app.post('/auth/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) return res.status(400).json({ error: 'Missing fields' });
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
if (!user || !bcrypt.compareSync(password, user.password_hash))
return res.status(401).json({ error: 'Invalid credentials' });
const token = jwt.sign(
{ id: user.id, username: user.username },
process.env.JWT_SECRET || 'dev-secret',
{ expiresIn: '7d' }
);
res.json({ token, username: user.username });
});
// Change password
app.post('/auth/change-password', requireAuth, (req, res) => {
const { currentPassword, newPassword } = req.body;
if (!currentPassword || !newPassword) return res.status(400).json({ error: 'Missing fields' });
if (newPassword.length < 8) return res.status(400).json({ error: 'Password must be 8+ chars' });
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.user.id);
if (!bcrypt.compareSync(currentPassword, user.password_hash))
return res.status(401).json({ error: 'Current password incorrect' });
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?')
.run(bcrypt.hashSync(newPassword, 12), req.user.id);
res.json({ success: true });
});
// ── API Key Routes ──────────────────────────────────────────
// Save (or update) user's Claude API key
app.post('/user/api-key', requireAuth, (req, res) => {
const { apiKey } = req.body;
if (!apiKey?.startsWith('sk-ant-'))
return res.status(400).json({ error: 'Invalid Anthropic API key format' });
const enc = encryptKey(apiKey);
db.prepare('UPDATE users SET api_key_enc = ? WHERE id = ?').run(enc, req.user.id);
res.json({ success: true });
});
// Check whether user has a key saved (without revealing it)
app.get('/user/api-key-status', requireAuth, (req, res) => {
const user = db.prepare('SELECT api_key_enc FROM users WHERE id = ?').get(req.user.id);
res.json({ hasKey: !!user?.api_key_enc });
});
// ── Text Extraction ─────────────────────────────────────────
async function extractText(base64Data) {
const buf = Buffer.from(base64Data.split(',')[1] || base64Data, 'base64');
if (base64Data.includes('application/pdf')) {
return (await pdfParse(buf)).text;
}
if (base64Data.includes('officedocument') || base64Data.includes('msword')) {
return (await mammoth.extractRawText({ buffer: buf })).value;
}
throw new Error('Unsupported file type. Use PDF or Word.');
}
// ── Evaluate Route ──────────────────────────────────────────
app.post('/evaluate', requireAuth, async (req, res) => {
// Get user's stored API key
const user = db.prepare('SELECT api_key_enc FROM users WHERE id = ?').get(req.user.id);
if (!user?.api_key_enc)
return res.status(402).json({ error: 'No API key saved. Add your Claude API key in Settings.' });
let apiKey;
try { apiKey = decryptKey(user.api_key_enc); }
catch { return res.status(500).json({ error: 'Failed to retrieve API key.' }); }
try {
let { jdText, resumeText, jdFile, resumeFile } = req.body;
if (jdFile) jdText = await extractText(jdFile);
if (resumeFile) resumeText = await extractText(resumeFile);
if (!jdText?.trim() || !resumeText?.trim())
return res.status(400).json({ error: 'Both job description and resume are required.' });
const anthropic = new Anthropic({ apiKey });
const prompt = `You are an expert HR analyst and resume coach. Analyze the following job description and resume, then return a JSON object with this exact structure:
{
"score": <integer 0-100>,
"presentSkills": [<skills/keywords found in BOTH jd and resume>],
"missingSkills": [<skills/keywords in jd but NOT in resume>],
"comparison": [
{ "requirement": "<key requirement>", "resumeNote": "<how resume addresses it>", "status": "<present|partial|missing>" }
],
"suggestions": ["<actionable suggestion 1>", ...]
}
Return ONLY valid JSON. No markdown, no explanation.
JOB DESCRIPTION:
${jdText}
RESUME:
${resumeText}`;
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 4096,
messages: [{ role: 'user', content: prompt }]
});
const raw = message.content[0].text.trim().replace(/^```json\s*/,'').replace(/```$/,'').trim();
res.json(JSON.parse(raw));
} catch (err) {
console.error('Evaluate error:', err);
// Surface Anthropic auth errors clearly
if (err.status === 401) return res.status(400).json({ error: 'Invalid Claude API key. Please update it in Settings.' });
res.status(500).json({ error: err.message || 'Evaluation failed' });
}
});
// ── Export PDF Route ────────────────────────────────────────
app.post('/export/pdf', requireAuth, (req, res) => {
const { score, presentSkills, missingSkills, comparison, suggestions } = req.body;
if (score === undefined) return res.status(400).json({ error: 'No result data provided.' });
const reportsDir = path.join(process.cwd(), 'reports');
if (!fs.existsSync(reportsDir)) fs.mkdirSync(reportsDir);
const filename = `resume-evaluation-${Date.now()}.pdf`;
const filepath = path.join(reportsDir, filename);
const doc = new PDFDocument({ margin: 50, size: 'A4' });
const stream = fs.createWriteStream(filepath);
doc.pipe(stream);
const W = doc.page.width - 100;
// Header
doc.fontSize(22).font('Helvetica-Bold').fillColor('#1a1a1a').text('Resume Evaluation Report', 50, 50);
doc.moveDown(0.3);
const label = score >= 70 ? 'Strong match' : score >= 40 ? 'Moderate match' : 'Weak match';
doc.fontSize(14).font('Helvetica').fillColor('#555555').text(`Score: ${score}/100 — ${label}`);
doc.moveDown(0.5);
doc.moveTo(50, doc.y).lineTo(doc.page.width - 50, doc.y).strokeColor('#dddddd').stroke();
doc.moveDown(0.8);
const section = (title) => {
doc.moveDown(0.5);
doc.rect(50, doc.y, W, 20).fill('#f5f5f3');
doc.fontSize(11).font('Helvetica-Bold').fillColor('#1a1a1a').text(title, 55, doc.y - 17);
doc.moveDown(0.8);
};
const safeLine = (text, opts = {}) => {
if (doc.y > 750) doc.addPage();
doc.text(text, opts);
};
// Present skills
section('Skills & Keywords Found in Both');
doc.fontSize(10).font('Helvetica').fillColor('#1a7a45');
safeLine((presentSkills || []).join(' · '), { width: W });
doc.moveDown(0.5);
// Missing skills
section('Missing from Resume');
doc.fontSize(10).font('Helvetica').fillColor('#c0392b');
safeLine((missingSkills || []).join(' · '), { width: W });
doc.moveDown(0.5);
// Comparison
section('Side-by-Side Comparison');
(comparison || []).forEach(row => {
if (doc.y > 730) doc.addPage();
const color = row.status === 'present' ? '#1a7a45' : row.status === 'partial' ? '#b46400' : '#c0392b';
const statusLabel = row.status === 'present' ? 'Present' : row.status === 'partial' ? 'Partial' : 'Missing';
doc.fontSize(10).font('Helvetica-Bold').fillColor('#1a1a1a').text(row.requirement, 50, doc.y, { width: W * 0.4, continued: false });
const afterReq = doc.y;
doc.fontSize(10).font('Helvetica').fillColor('#555555').text(row.resumeNote || '—', 50 + W * 0.42, afterReq - doc.currentLineHeight(), { width: W * 0.42, continued: false });
doc.fontSize(10).font('Helvetica-Bold').fillColor(color).text(statusLabel, 50 + W * 0.88, afterReq - doc.currentLineHeight(), { width: W * 0.12 });
doc.moveDown(0.3);
doc.moveTo(50, doc.y).lineTo(doc.page.width - 50, doc.y).strokeColor('#f0f0ee').stroke();
doc.moveDown(0.3);
});
// Suggestions
section('Improvement Suggestions');
(suggestions || []).forEach((s, i) => {
if (doc.y > 730) doc.addPage();
doc.fontSize(10).font('Helvetica-Bold').fillColor('#1a1a1a').text(`${i + 1}.`, 50, doc.y, { continued: true, width: 20 });
doc.font('Helvetica').fillColor('#333333').text(` ${s}`, { width: W - 20 });
doc.moveDown(0.3);
});
doc.end();
stream.on('finish', () => {
console.log(`PDF saved: ${filepath}`);
res.json({ success: true, file: filename, path: filepath });
});
stream.on('error', (err) => res.status(500).json({ error: 'PDF generation failed.' }));
});
// ── Start ───────────────────────────────────────────────────
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`));