-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
4112 lines (3844 loc) · 189 KB
/
Copy pathserver.ts
File metadata and controls
4112 lines (3844 loc) · 189 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dotenv/config';
import crypto from 'crypto';
import { execSync } from 'node:child_process';
import express from 'express';
import fs from 'fs';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import multer from 'multer';
import * as pdfParseModule from 'pdf-parse';
import mammoth from 'mammoth';
import { promises as dns } from 'node:dns';
import { readFileSync } from 'node:fs';
async function extractTextFromPdfBuffer(buffer: Buffer): Promise<string> {
try {
const mod: any = pdfParseModule;
if (mod && typeof mod === 'function') {
const res = await mod(buffer);
if (res?.text && res.text.trim().length > 0) return res.text;
}
if (mod && typeof mod.default === 'function') {
const res = await mod.default(buffer);
if (res?.text && res.text.trim().length > 0) return res.text;
}
if (mod && mod.PDFParse) {
const parser = new mod.PDFParse({ data: buffer });
const res = await parser.getText();
if (typeof res === 'string' && res.trim().length > 0) return res;
if (res && typeof res.text === 'string' && res.text.trim().length > 0) return res.text;
}
} catch (err) {
console.warn('pdf-parse encountered an error extracting text:', err);
}
// Raw text stream regex fallback for PDF text extraction if pdf-parse fails or returns empty
try {
const str = buffer.toString('utf-8');
const matches = str.match(/\(([^()]{2,})\)\s*T[jd]/g);
if (matches && matches.length > 0) {
const extracted = matches
.map((m) => m.replace(/^\(/, '').replace(/\)\s*T[jd]$/, '').trim())
.filter((t) => t.length > 1)
.join(' ');
if (extracted.length > 20) {
return extracted;
}
}
} catch (e) {
// ignore
}
return '';
}
import { loadConfig, saveConfig } from './server/config.js';
import {
getDb,
getMasterCv,
saveMasterCv,
createUser,
verifyLogin,
getRecoveryInfo,
resetPasswordWithRecovery,
setRecoveryQuestions,
listUsers,
getUserById,
createSession,
getSessionUser,
deleteSession,
runWithUser,
getCurrentUserId,
getAllJobs,
getJobById,
updateJobInStorage,
deleteJobFromStorage,
deleteAllJobs,
queryJobs,
saveNewJobs,
persistJobsWithUpgrade,
getLpHistory,
mergeLpHistory,
markLpHistorySaved,
clearLpHistory,
runStorageMigration,
fixMislabeledWorkTypes,
repairJobDates,
saveManualAnalysis,
listManualAnalyses,
getManualAnalysis,
deleteManualAnalysis,
saveCvVersion,
listCvVersions,
getCvVersion,
deleteCvVersion,
getCandidateProfile,
saveCandidateProfile,
listPortalBookmarks,
addPortalBookmark,
removePortalBookmark,
listContacts,
getContactById,
recordContactEmail,
recordContactEmailDetail,
listContactCompanies,
listContactsForJob,
setContactHidden,
setContactFollowUp,
setContactFollowedUp,
setContactPipeline,
addContactNote,
listContactEmails,
getContactStats,
listContactsCsv,
backfillContacts,
upsertContactsFromJob,
getPostsDailyUsage,
addPostsDailyUsage,
} from './server/storage/fileStorage.js';
import { hideCurrentUserJob, unhideCurrentUserJob, clearCurrentUserHidden } from './server/storage/hiddenJobs.js';
import { ScraperFactory } from './server/scraper/scraperFactory.js';
import { LinkedInPostsScraper } from './server/scraper/linkedInPostsScraper.js';
import { LlmMatcher } from './server/matcher/llmMatcher.js';
import { hasApiKeyConfigured, mapLlmError } from './server/llm/apiKeyGuard.js';
import { generatePdfBuffer, generatePlainTextCv } from './server/builder/docxGenerator.js';
import { JobFilterQueryParams, Job, MasterCv } from './src/types.js';
import { SOURCES } from './src/constants/sources.js';
import { isEmailFormatValid } from './src/lib/recruiters/emailUtils.js';
import { compressCv } from './server/ai/cvCompressor.js';
import { getMarketData } from './server/ai/marketData.js';
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 15 * 1024 * 1024 }, // 15MB max file size
});
function fallbackParseCvFromText(rawText: string) {
// Deterministic last-resort extraction. NEVER fabricates: fields that
// cannot be found stay empty so the UI shows the truth (and the success
// banner reports exactly what was extracted).
const lines = (rawText || '').split('\n').map((l) => l.trim()).filter(Boolean);
let fullName = '';
let email = '';
let phone = '';
let location = '';
let linkedin = '';
let github = '';
let website = '';
for (const line of lines) {
if (!email && /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(line)) {
const match = line.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/);
if (match) email = match[0];
}
if (!phone && /(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/.test(line)) {
const match = line.match(/(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/);
if (match) phone = match[0];
}
if (!linkedin && /linkedin\.com\/in\/[a-zA-Z0-9_-]+/i.test(line)) {
const match = line.match(/https?:\/\/[^\s]+/i) || line.match(/linkedin\.com\/in\/[a-zA-Z0-9_-]+/i);
if (match) linkedin = match[0];
}
if (!github && /github\.com\/[a-zA-Z0-9_-]+/i.test(line)) {
const match = line.match(/https?:\/\/[^\s]+/i) || line.match(/github\.com\/[a-zA-Z0-9_-]+/i);
if (match) github = match[0];
}
}
for (const line of lines.slice(0, 5)) {
if (line.length < 40 && !line.includes('@') && !line.includes('http') && !line.toLowerCase().includes('resume') && !line.toLowerCase().includes('curriculum')) {
fullName = line;
break;
}
}
const knownSkills = [
'TypeScript', 'JavaScript', 'React', 'Node.js', 'Python', 'Java', 'C++', 'Go',
'AWS', 'Azure', 'GCP', 'Docker', 'Kubernetes', 'SQL', 'PostgreSQL', 'MongoDB',
'GraphQL', 'REST API', 'Git', 'Linux', 'CI/CD', 'Terraform', 'Microservices',
'DevOps', 'HTML', 'CSS', 'Tailwind', 'Redux', 'Next.js', 'Express'
];
const foundSkills: string[] = [];
const textLower = (rawText || '').toLowerCase();
for (const s of knownSkills) {
if (textLower.includes(s.toLowerCase())) {
foundSkills.push(s);
}
}
const paragraphs = (rawText || '').split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
const summary = paragraphs[0] || '';
return {
fullName,
email,
phone,
location,
linkedin,
github,
website,
summary,
experiences: [],
education: [],
skills: foundSkills.length > 0 ? [{ category: 'Core Competencies', items: foundSkills }] : [],
projects: [],
certifications: [],
rawText: rawText || '',
};
}
import { ask } from './server/llm/llmAdapter.js';
import { askJson } from './server/llm/askJson.js';
import { startInterview, askNextQuestion, scoreAnswer, buildScorecard, getInterviewSession, getRoleOptions, getJobsForRole } from './server/interview.js';
import { saveInterviewSession, getInterviewHistory, getInterviewSessionRecord } from './server/storage/fileStorage.js';
import nodemailer from 'nodemailer';
// Convert the stored Master CV into the TailoredCv shape the PDF generator
// consumes (same conversion the master-download route uses).
function masterCvToTailoredCv(m: ReturnType<typeof getMasterCv>): any {
return {
candidateName: m.fullName,
contactInfo: {
email: m.email,
phone: m.phone,
location: m.location,
linkedin: m.linkedin,
github: m.github,
website: m.website,
},
targetRole: m.experiences[0]?.title || '',
professionalSummary: m.summary,
coreCompetencies: m.skills.flatMap((s) => s.items),
workExperience: m.experiences.map((e) => ({
title: e.title,
company: e.company,
location: e.location,
dates: e.dates,
highlights: e.responsibilities,
})),
education: m.education.map((e) => ({
degree: e.degree,
institution: e.institution,
dates: e.dates,
details: e.details || '',
})),
technicalSkills: m.skills.map((s) => ({
category: s.category,
skills: s.items,
})),
projects: m.projects || [],
certifications: (m.certifications || []).map((c) =>
typeof c === 'string' ? c : `${c.name}${c.issuer ? ' (' + c.issuer + ')' : ''}`
),
};
}
async function parseCvWithLLM(
input: string | { buffer: Buffer; mimeType: string; originalName: string }
) {
let rawText = typeof input === 'string' ? input : '';
let fileInfo = typeof input === 'object' ? input : null;
if (fileInfo) {
const { buffer, mimeType, originalName } = fileInfo;
const filenameLower = originalName.toLowerCase();
if (mimeType === 'application/pdf' || filenameLower.endsWith('.pdf')) {
rawText = await extractTextFromPdfBuffer(buffer);
} else if (
mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
filenameLower.endsWith('.docx')
) {
try {
const parsedDocx = await mammoth.extractRawText({ buffer });
rawText = parsedDocx.value || '';
} catch (err) {
console.warn('mammoth docx extraction error:', err);
}
} else {
rawText = buffer.toString('utf-8');
}
}
const { askJson } = await import('./server/llm/askJson.js');
const promptText = `You are an expert ATS resume parser.
Extract every detail from A to Z from the resume into clean, structured JSON.
INSTRUCTIONS:
1. Contact Details: Extract Full Name, Email, Phone Number, Location/Address, LinkedIn URL, GitHub URL, and Portfolio Website.
2. Professional Summary: Extract or formulate a thorough 3-5 sentence master professional summary covering the candidate's core domain, years of experience, and key value proposition.
3. Work History (Experiences): Extract EVERY job role with Title, Company, Location, Dates (e.g., "Jan 2021 - Present"), and an array of individual responsibilities/achievements as bullet points.
4. Education: Extract degrees, university/institution names, graduation dates/years, and any honors or details.
5. Technical Skills: Group skills into logical categories (e.g., "Languages & Frameworks", "Cloud & Infrastructure", "Tools & Methodologies") with an array of individual skill tags.
6. Projects: Extract any key projects mentioned with Project Name, Description, Technologies used (array of strings), Link/URL, and Dates/Period.
7. Certifications: Extract any professional certifications, licenses, or credentials with Certification Name, Issuer (e.g., AWS, Microsoft, Google), Date obtained, and Link if available.
Return valid JSON with these exact fields: fullName, designation, email, phone, location, linkedin, github, website, summary, experiences (array of {title, company, location, dates, responsibilities[]}), education (array of {degree, institution, dates, details}), skills (array of {category, items[]}), projects (array of {name, description, technologies[], link, dates}), certifications (array of {name, issuer, date, link}).
RAW RESUME TEXT:
${rawText || 'No readable text extracted.'}`;
try {
const parsedData = await askJson<any>(promptText, { temperature: 0.1 });
return {
fullName: parsedData.fullName || '',
email: parsedData.email || '',
phone: parsedData.phone || '',
designation: parsedData.designation || '',
location: parsedData.location || '',
linkedin: parsedData.linkedin || '',
github: parsedData.github || '',
website: parsedData.website || '',
summary: parsedData.summary || '',
experiences: (parsedData.experiences || []).map((exp: any, i: number) => ({
id: `exp-${i + 1}`,
title: exp.title || 'Role',
company: exp.company || 'Company',
location: exp.location || '',
dates: exp.dates || '',
responsibilities: Array.isArray(exp.responsibilities) ? exp.responsibilities : [],
})),
education: (parsedData.education || []).map((edu: any, i: number) => ({
id: `edu-${i + 1}`,
degree: edu.degree || 'Degree',
institution: edu.institution || 'University',
dates: edu.dates || '',
details: edu.details || '',
})),
skills: (parsedData.skills || []).map((sk: any) => ({
category: sk.category || 'Core Skills',
items: Array.isArray(sk.items) ? sk.items : [],
})),
projects: (parsedData.projects || []).map((p: any, i: number) => ({
id: `proj-${i + 1}`,
name: p.name || 'Project Name',
description: p.description || '',
technologies: Array.isArray(p.technologies) ? p.technologies : [],
link: p.link || '',
dates: p.dates || '',
})),
certifications: (parsedData.certifications || []).map((c: any, i: number) => {
if (typeof c === 'string') {
return { id: `cert-${i + 1}`, name: c, issuer: '', date: '', link: '' };
}
return {
id: `cert-${i + 1}`,
name: c.name || 'Certification Name',
issuer: c.issuer || '',
date: c.date || '',
link: c.link || '',
};
}),
rawText,
};
} catch (err: any) {
console.warn('LLM parse call failed, using fallback parser:', err?.message || err);
return fallbackParseCvFromText(rawText);
}
}
// Convert a plain-text email body (which may contain the candidate's phone
// and portfolio from the Master CV) into safe HTML with clickable tel: and
// https: links — recipients can tap-to-call or open the portfolio directly
// from the email instead of seeing plain text.
import { textBodyToHtmlWithLinks } from './server/emailHtml.js';
import { buildProfileText } from './server/emailProfile.js';
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json({ limit: '10mb' }));
// One-time data fix: re-derive LinkedIn work-type labels that were
// incorrectly defaulted to "Full-time · Remote" (idempotent).
const fixedTypes = fixMislabeledWorkTypes();
if (fixedTypes > 0) console.log(`[data-fix] Reclassified ${fixedTypes} mislabeled jobs`);
// Repair malformed stored dates (doubled timestamps).
const fixedDates = repairJobDates();
if (fixedDates > 0) console.log(`[data-fix] Repaired ${fixedDates} malformed job dates`);
// Session middleware: resolve the auth cookie to a user and make it
// available to every handler (and storage call) for this request.
app.use((req, _res, next) => {
const cookieHeader = (req.headers.cookie || '').split(';').map((s) => s.trim());
const match = cookieHeader.find((c) => c.startsWith('ats_session='));
const token = match ? match.slice('ats_session='.length) : '';
const userId = token ? getSessionUser(token) : undefined;
if (userId) {
runWithUser(userId, () => next());
} else {
runWithUser('', () => next());
}
});
// Warn if a previously-committed (compromised) API key is still in use
// Compromised keys stored as SHA-256 hashes (never plaintext in the repo).
// Hash of the previously leaked key; compare by hashing the configured key.
const COMPROMISED_KEY_HASHES = new Set(['a2117087d9a8d23cd2b4f14d61139102293d11bfc0faf57552d02b50f402274a']);
const configuredKey = loadConfig().llm.apiKey;
const configuredKeyHash = crypto.createHash('sha256').update(configuredKey || '').digest('hex');
if (COMPROMISED_KEY_HASHES.has(configuredKeyHash)) {
console.warn('\n==========================================================');
console.warn('⚠️ SECURITY WARNING: Your API key was exposed in an old');
console.warn(' public git commit. Anyone with repo history has it.');
console.warn(' Generate a NEW key in your LLM provider dashboard and');
console.warn(' paste it in Settings → LLM API Key (or config.ini).');
console.warn(' Then revoke the old key on the provider side.');
console.warn('==========================================================\n');
}
// Seed sample jobs if store is completely empty on initial startup.
// Runs in the first user's context so the seed lands in a real account.
const { ensureV2Tables, seedCompanyCareerSites } = await import('./server/storage/v2Tables.js');
ensureV2Tables();
seedCompanyCareerSites();
// Local ATS index (flag-gated): schema + in-process background ingestion.
// The scheduler tick is async and never blocks startup or HTTP requests;
// the index lives on the persistent ./data volume and survives restarts.
{
const { ATS_FLAGS } = await import('./server/providers/providerRegistry.js');
if (ATS_FLAGS.ENABLE_LOCAL_ATS_INDEX) {
const { ensureAtsIndexSchema } = await import('./server/ats-index/atsRepository.js');
const { createAtsScheduler } = await import('./server/ats-index/atsScheduler.js');
ensureAtsIndexSchema();
const platforms = (process.env.ATS_INDEX_PLATFORMS ?? 'greenhouse')
.split(',')
.map((s) => s.trim().toLowerCase())
.filter((s) => s === 'greenhouse' || s === 'lever' || s === 'ashby');
const schedulers = platforms.map((p) => createAtsScheduler(p));
for (const s of schedulers) s.start();
console.log(`[ATS Index] local ATS index enabled (platforms: ${platforms.join(', ')})`);
}
}
const seedUser = (getDb().prepare('SELECT id FROM users ORDER BY is_guest ASC, created_at ASC LIMIT 1').get() as any)?.id as string | undefined;
if (seedUser) {
runWithUser(seedUser, () => {
const initialJobs = getAllJobs();
if (initialJobs.length === 0) {
(async () => {
const sampleScrape = await ScraperFactory.runScrape({
keywords: 'Full Stack TypeScript Engineer',
location: 'Remote',
sources: ['LinkedIn'],
maxJobsPerSource: 5,
});
saveNewJobs(sampleScrape);
})();
}
});
}
// --- API ROUTES ---
// Installed version of this app (read from the package.json shipped in the image).
const readInstalledVersion = (): string => {
try {
const pkg = JSON.parse(readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'));
return pkg.version || '0.0.0';
} catch {
return '0.0.0';
}
};
// Compare dotted version strings (with optional leading "v"), e.g. v1.7.0 > v1.6.9.
const versionGt = (a: string, b: string): boolean => {
const parse = (v: string) => String(v).replace(/^v/i, '').split('.').map((n) => parseInt(n, 10) || 0);
const [pa, pb] = [parse(a), parse(b)];
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const diff = (pa[i] || 0) - (pb[i] || 0);
if (diff !== 0) return diff > 0;
}
return false;
};
// Update check: pull the latest version of this repo's main branch straight
// from GitHub (no API key, no CORS). The contents API reads the git blob
// directly, so the banner shows the moment a push lands (raw.githubusercontent
// is CDN-cached and can lag minutes). The client shows a banner whenever
// the installed version is behind the pushed one. GitHub webhooks can't
// reach self-hosted Docker installs (no public inbound URL), so installs
// poll this endpoint instead — same UX, no inbound traffic.
app.get('/api/update-check', async (_req, res) => {
const installed = readInstalledVersion();
const repo = 'https://github.com/Atanub707/Tailor-AI';
try {
const apiRes = await fetch('https://api.github.com/repos/Atanub707/Tailor-AI/contents/package.json?ref=main', {
headers: { 'User-Agent': 'tailor-ai', Accept: 'application/vnd.github+json' },
signal: AbortSignal.timeout(8000),
});
if (apiRes.ok) {
const api = await apiRes.json();
const latest = (JSON.parse(Buffer.from(api.content, 'base64').toString('utf8')).version || '');
return res.json({ updateAvailable: versionGt(latest, installed), installed, latest, repo });
}
// Fallback: raw file (CDN-cached, may lag briefly after a push).
const rawRes = await fetch('https://raw.githubusercontent.com/Atanub707/Tailor-AI/main/package.json', { signal: AbortSignal.timeout(8000) });
if (!rawRes.ok) return res.json({ updateAvailable: false, installed, repo });
const latest = (await rawRes.json()).version || '';
return res.json({ updateAvailable: versionGt(latest, installed), installed, latest, repo });
} catch {
return res.json({ updateAvailable: false, installed, repo });
}
});
// One-click auto-update: pull the latest main from GitHub, reinstall deps if
// the lockfile changed, then exit — Docker's restart:unless-stopped brings
// the app back up on the new code. Data lives outside git (data/, config.ini
// are gitignored), so it is never touched. Works because installs mount the
// live source at /app (docker-compose) — this only runs on git checkouts.
app.post('/api/update', (_req, res) => {
try {
const isRepo = execSync('git -C /app rev-parse --is-inside-work-tree 2>/dev/null || echo no', { encoding: 'utf8' }).trim();
if (isRepo !== 'true') {
return res.status(400).json({ error: 'Auto-update unavailable on this install (not a git checkout). Update manually: git pull && docker compose build && docker compose up -d.' });
}
// Respond first; the heavy work happens after the client got the OK.
res.json({ ok: true, message: 'Updating — the app will restart automatically in a few seconds.' });
const lockBefore = (() => {
try { return crypto.createHash('sha256').update(readFileSync('/app/package-lock.json')).digest('hex'); } catch { return ''; }
})();
execSync('git -C /app fetch origin main && git -C /app reset --hard origin/main', { stdio: 'inherit', timeout: 120000 });
const lockAfter = (() => {
try { return crypto.createHash('sha256').update(readFileSync('/app/package-lock.json')).digest('hex'); } catch { return ''; }
})();
if (lockBefore !== lockAfter) {
execSync('npm install --loglevel=error', { cwd: '/app', stdio: 'inherit', timeout: 600000 });
}
// Rebuild the frontend: the server serves the HOST dist/ folder (the
// compose bind mount shadows the image), so a source-only update would
// leave users on the stale UI (or the 'frontend not built' page).
try {
execSync('npm run build', { cwd: '/app', stdio: 'inherit', timeout: 900000 });
} catch (buildErr: any) {
console.error('Frontend rebuild failed after update:', buildErr?.message || buildErr);
}
// Let the response flush, then hand over to Docker's restart policy.
setTimeout(() => process.exit(0), 2000);
} catch (err: any) {
try { res.status(500).json({ error: `Update failed: ${err?.message || 'unknown error'}` }); } catch { /* response already sent */ }
}
});
// Configuration routes
app.get('/api/config', (req, res) => {
res.json(loadConfig());
});
// Live model catalog — proxies the provider's GET /models (opencode-go,
// openrouter, openai, nvidia) with a 6h server-side cache; falls back to
// the static preset list when the fetch fails, so the Settings model
// dropdown always reflects the provider's current catalog without any
// code edits. Result: { models, fetchedAt, stale, reason?, provider? }.
app.get('/api/models', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const { fetchModelCatalog } = await import('./server/llm/modelCatalog.js');
res.json(await fetchModelCatalog());
} catch (err: any) {
res.status(500).json({ error: String(err?.message || 'Catalog fetch failed.').slice(0, 200) });
}
});
// Source registry — lets clients (and API consumers) see which sources
// are Apify-powered and what each Apify source costs per 1K jobs.
app.get('/api/sources', (_req, res) => {
res.json({ sources: Object.values(SOURCES) });
});
app.post('/api/config', (req, res) => {
try {
saveConfig(req.body);
res.json({ success: true, config: loadConfig() });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// Test an LLM connection with the CURRENT form values (nothing is saved).
app.post('/api/settings/test-llm', async (req, res) => {
try {
const { provider, apiKey, baseUrl, model } = req.body || {};
const p = String(provider || 'opencode-go');
const key = String(apiKey || '').trim();
const mdl = String(model || '').trim();
if (!key) {
res.status(400).json({ ok: false, error: 'Enter an API key first.' });
return;
}
if (!mdl) {
res.status(400).json({ ok: false, error: 'Enter a model name first.' });
return;
}
const started = Date.now();
const TIMEOUT_MS = 20_000; // bounded probe — never hangs the settings UI
const check = async (): Promise<void> => {
if (p === 'gemini') {
const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(mdl)}:generateContent?key=${encodeURIComponent(key)}`;
const r = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: [{ parts: [{ text: 'ping' }] }] }),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
if (!r.ok) throw new Error(`Gemini API error ${r.status}`);
return;
}
if (p === 'anthropic') {
const r = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01' },
body: JSON.stringify({ model: mdl, messages: [{ role: 'user', content: 'ping' }] }),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
if (!r.ok) throw new Error(`Anthropic API error ${r.status}`);
return;
}
const base = String(baseUrl || '').trim().replace(/\/+$/, '');
if (!base) throw new Error('Enter a Base URL first.');
// IMPORTANT: no max_tokens in the probe — the opencode.ai router
// HANGS (never responds) when max_tokens is present, even for a
// valid key. The probe mirrors the working completion shape.
// OpenCode Go also requires x-opencode-session + a real User-Agent
// (else 400 MissingSessionID) — send them for its endpoints.
const isOpencodeGo = base.includes('opencode.ai');
const r = await fetch(`${base}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${key}`,
'Content-Type': 'application/json',
'User-Agent': 'TailorAI/1.0 (local job-search app)',
...(isOpencodeGo ? { 'x-opencode-session': `tailor-ai-${crypto.createHash('sha1').update(key).digest('hex').slice(0, 16)}` } : {}),
},
body: JSON.stringify({ model: mdl, messages: [{ role: 'user', content: 'ping' }] }),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
if (r.status === 404) throw new Error('Model or endpoint not found (404) — check the model name and base URL.');
if (!r.ok) throw new Error(`API error ${r.status}`);
};
await check();
res.json({ ok: true, latencyMs: Date.now() - started });
} catch (err: any) {
console.error('LLM test failed:', err.message);
res.status(502).json({ ok: false, error: String(err?.message || 'Connection failed.').slice(0, 300) });
}
});
// ── Applicant Profile v1 (scoped to logged-in user, local-only) ──────────
app.get('/api/applicant-profile', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const { getApplicantProfile } = await import('./server/storage/applicantProfile.js');
res.json(getApplicantProfile(userId));
} catch (err: any) {
res.status(500).json({ error: err.message || 'Failed to load profile.' });
}
});
app.put('/api/applicant-profile', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const { validateApplicantProfile, saveApplicantProfile, getApplicantProfile } = await import('./server/storage/applicantProfile.js');
const profile = req.body;
const v = validateApplicantProfile(profile);
if (!v.ok) {
res.status(422).json({ error: v.errors[0], details: v.errors });
return;
}
saveApplicantProfile(profile, userId);
// SINGLE SOURCE OF TRUTH: the Applicant Profile owns identity — sync
// it into the Master CV so PDFs, packages, and tailored resumes always
// carry the same name/email/phone/location (never drift).
try {
const { getMasterCv, saveMasterCv } = await import('./server/storage/fileStorage.js');
const cv = getMasterCv(userId);
if (cv) {
const next = {
...cv,
fullName: [profile.personal?.firstName, profile.personal?.lastName].filter(Boolean).join(' ') || cv.fullName,
email: profile.personal?.email || cv.email,
phone: profile.personal?.phone || cv.phone,
location: [profile.contact?.city, profile.contact?.country].filter(Boolean).join(', ') || cv.location,
linkedin: profile.links?.linkedin || cv.linkedin,
github: profile.links?.github || cv.github,
website: profile.links?.website || cv.website,
};
saveMasterCv(next, userId);
}
} catch (cvErr) {
// Profile save still succeeds even if the CV sync hiccups.
console.error('Profile → Master CV identity sync failed:', cvErr);
}
res.json({ success: true, profile: getApplicantProfile(userId) });
} catch (err: any) {
res.status(500).json({ error: err.message || 'Failed to save profile.' });
}
});
// Deterministic import from the structured Master CV — only fills EMPTY
// fields; a populated profile is never silently overwritten.
app.post('/api/applicant-profile/import-master-cv', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const { getApplicantProfile, saveApplicantProfile } = await import('./server/storage/applicantProfile.js');
const { importMasterCvIntoProfile } = await import('./server/profile/cvImporter.js');
const current = getApplicantProfile(userId);
const merged = importMasterCvIntoProfile(current, getMasterCv(userId));
saveApplicantProfile(merged, userId);
res.json({ success: true, profile: merged, filledFromCv: true });
} catch (err: any) {
res.status(500).json({ error: err.message || 'Import failed.' });
}
});
// Local JSON export — profile only; NEVER includes provider secrets.
app.get('/api/applicant-profile/export', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const { getApplicantProfile } = await import('./server/storage/applicantProfile.js');
const profile = getApplicantProfile(userId);
const safe = JSON.parse(JSON.stringify(profile));
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Disposition', 'attachment; filename="applicant-profile.json"');
res.json(safe);
} catch (err: any) {
res.status(500).json({ error: err.message || 'Export failed.' });
}
});
// Master CV routes (scoped to logged-in user)
app.get('/api/cv/master', (req, res) => {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
res.json(getMasterCv(userId));
});
app.post('/api/cv/master', (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
saveMasterCv(req.body, userId);
res.json({ success: true, cv: getMasterCv(userId) });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.get('/api/profile', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const { getApplicantProfile: loadCanonical, saveApplicantProfile: saveCanonical, migrateLegacyCandidateProfile } = await import('./server/storage/applicantProfile.js');
const legacy = getCandidateProfile();
let canonical = loadCanonical(userId);
const migration = canonical ? migrateLegacyCandidateProfile(canonical, legacy) : { migrated: false, conflicts: {} as Record<string, string> };
if (migration.migrated && canonical) {
saveCanonical(canonical, userId);
canonical = loadCanonical(userId);
}
res.json({ profile: canonical, conflicts: migration.conflicts });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.put('/api/profile', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const profile = req.body?.profile;
if (!profile || typeof profile !== 'object') {
return res.status(400).json({ error: 'Profile is required.' });
}
const p = profile as any;
const arr = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []);
const str = (v: unknown): string => (typeof v === 'string' ? v : '');
const bool = (v: unknown): boolean => v === true;
const relocation = (v: unknown): 'yes' | 'no' | 'certain-cities' => (v === 'yes' || v === 'certain-cities' ? v : v === true ? 'yes' : 'no');
const clean = {
workModes: arr(p.workModes), preferredLocations: arr(p.preferredLocations),
noticePeriod: str(p.noticePeriod), availableFrom: str(p.availableFrom),
employmentTypes: arr(p.employmentTypes), yearsExperience: str(p.yearsExperience),
currentRole: str(p.currentRole), currentCompany: str(p.currentCompany),
currentSalary: str(p.currentSalary), expectedSalaryMin: str(p.expectedSalaryMin),
expectedSalaryMax: str(p.expectedSalaryMax), salaryCurrency: str(p.salaryCurrency),
jobSearchStatus: str(p.jobSearchStatus), willingToRelocate: relocation(p.willingToRelocate),
willingToTravelPct: str(p.willingToTravelPct), workAuthorization: str(p.workAuthorization),
needsSponsorship: bool(p.needsSponsorship), languages: arr(p.languages),
preferredCompanySize: str(p.preferredCompanySize), recruiterNote: str(p.recruiterNote),
};
// CANONICAL write-through: legacy CandidateProfile store is no longer an
// independently editable source — the profile PATCH route writes the
// canonical applicant_profile (keep the legacy store untouched for
// backward-compatible reads during the deprecation window).
const { saveApplicantProfile: saveCanonical, getApplicantProfile: loadCanonical, defaultApplicantProfile } = await import('./server/storage/applicantProfile.js');
let canonical = loadCanonical(userId);
if (!canonical) canonical = defaultApplicantProfile();
const applyStr = (k: string, v: string) => {
if (v === undefined) return;
const key = k === 'noticePeriod' ? 'noticePeriod' : k === 'availableFrom' ? 'earliestStartDate' : k;
if (key === 'earliestStartDate' || key === 'jobSearchStatus' || key === 'preferredCompanySize' || key === 'recruiterNote' || key === 'salaryCurrency') {
(canonical as any).preferences = { ...(canonical as any).preferences, [key]: v };
}
};
(canonical as any).preferences = { ...(canonical as any).preferences };
if (clean.noticePeriod) (canonical as any).preferences.noticePeriod = clean.noticePeriod;
if (clean.availableFrom) (canonical as any).preferences.earliestStartDate = clean.availableFrom;
if (clean.jobSearchStatus) (canonical as any).preferences.jobSearchStatus = clean.jobSearchStatus;
if (clean.preferredCompanySize) (canonical as any).preferences.preferredCompanySize = clean.preferredCompanySize;
if (clean.recruiterNote) (canonical as any).preferences.recruiterNote = clean.recruiterNote;
if (clean.salaryCurrency) (canonical as any).preferences.salaryCurrency = clean.salaryCurrency;
if (clean.currentSalary) (canonical as any).preferences.currentSalary = Number(clean.currentSalary) || undefined;
if (clean.expectedSalaryMin) (canonical as any).preferences.minimumSalary = Number(clean.expectedSalaryMin) || undefined;
if (clean.expectedSalaryMax) (canonical as any).preferences.targetSalary = Number(clean.expectedSalaryMax) || undefined;
if (clean.willingToTravelPct) (canonical as any).preferences.travelPercentage = Number(clean.willingToTravelPct) || undefined;
if (clean.languages && clean.languages.length) (canonical as any).preferences.languages = clean.languages;
if (clean.preferredLocations && clean.preferredLocations.length) (canonical as any).locationPrefs = { ...(canonical as any).locationPrefs, preferredLocations: clean.preferredLocations };
if (clean.employmentTypes && clean.employmentTypes.length) (canonical as any).preferences.preferredEmploymentTypes = clean.employmentTypes;
if (clean.willingToRelocate && clean.willingToRelocate !== 'no') (canonical as any).locationPrefs = { ...(canonical as any).locationPrefs, willingToRelocate: clean.willingToRelocate };
if (clean.needsSponsorship !== undefined && clean.needsSponsorship !== null) (canonical as any).workAuthorization = { ...(canonical as any).workAuthorization, requiresSponsorship: clean.needsSponsorship ? 'yes' : 'no' };
if (clean.workAuthorization) (canonical as any).workAuthorization = { ...(canonical as any).workAuthorization, country: clean.workAuthorization };
saveCanonical(canonical, userId);
res.json({ success: true, profile: loadCanonical(userId) });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// ── LinkedIn Posts (job postings, last 24h) ──
// Daily cap (20/day, resets at midnight) applies to the APIFY engine only —
// it protects the user's token spend. The FREE engine is unlimited.
app.post('/api/linkedin-posts/search', async (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const keywords = String(req.body?.keywords || '').trim();
if (!keywords) return res.status(400).json({ error: 'Keywords are required.' });
const engine = req.body?.engine === 'apify' ? 'apify' : 'free';
// Apify: show all ~100 posts the actor fetched. Free: cap at 20.
const limit = Math.min(engine === 'apify' ? 100 : 20, Math.max(1, Number(req.body?.limit) || 20));
const quota = getPostsDailyUsage(userId);
if (engine === 'apify' && quota.used >= quota.quota) {
return res.status(429).json({
valid: false,
error: `Apify daily limit reached: ${quota.quota} search used today. Resets at ${new Date(quota.resetAt).toLocaleTimeString()}. Switch to the Free engine — it has no limit.`,
quota,
});
}
let posts: Job[] = [];
let debug: Record<string, unknown> = {};
{
const scraper = new LinkedInPostsScraper();
posts = await scraper.scrape({
keywords,
location: '',
sources: [],
datePostedFilter: '24h',
jobType: 'all',
maxJobsPerSource: limit,
engine,
} as any);
debug = { ...scraper.lastDebug };
// Job-posting search only — anything else returns "not valid".
if (posts.length === 0) {
const remaining = engine === 'apify' ? Math.max(0, quota.quota - quota.used) : quota.quota;
// RESEARCH: distinguish "engines blocked/rate-limited" from "engines
// found links but none were job postings in the last 24h".
const discoveryFailed = scraper.lastDebug.linksFound === 0;
return res.status(200).json({
valid: false,
discoveryFailed,
message: discoveryFailed
? `Search engines returned no results from this server — likely rate-limited or blocked (${scraper.lastDebug.queriesTried} queries tried). Try again in a minute.`
: 'not valid — engines found posts but none were job postings from the last 24 hours. Try broader keywords.',
debug: scraper.lastDebug,
posts: [],
addedCount: 0,
total: 0,
quota: { ...quota, remaining },
});
}
}
// Apify engine: cap the search at the remaining daily quota (10/day max).
const remaining = engine === 'apify' ? Math.max(0, quota.quota - quota.used) : posts.length;
const cappedPosts = engine === 'apify' ? posts.slice(0, remaining) : posts;
if (engine === 'apify' && cappedPosts.length === 0) {
return res.status(429).json({
valid: false,
error: `Apify daily limit reached: ${quota.quota} search used today. Resets at ${new Date(quota.resetAt).toLocaleTimeString()}. Switch to the Free engine — it has no limit.`,
quota,
});
}
// Search results are NOT auto-saved as jobs — they live on the search
// screen only, persisted per user in the lp_history table so they
// survive refresh/browser/device. Explicit saves go via
// POST /api/linkedin-posts/save.
if (posts.length > 0) {
mergeLpHistory(
userId,
posts.map((p) => ({
id: p.id,
title: p.title,
company: p.company,
url: p.url,
applyUrl: p.applyUrl,
postedDate: p.postedDate,
description: p.description,
hashtags: p.hashtags || [],
}))
);
}
const newUsed = engine === 'apify' ? addPostsDailyUsage(userId, cappedPosts.length) : quota.used;
res.json({
valid: true,
debug,
posts: posts.map((p) => ({
id: p.id,
title: p.title,
company: p.company,
url: p.url,
applyUrl: p.applyUrl,
postedDate: p.postedDate,
description: (p.description || '').slice(0, 500),
hashtags: p.hashtags || [],
})),
addedCount: 0,
upgradedCount: 0,
total: posts.length,
quota: { used: newUsed, quota: quota.quota, remaining: Math.max(0, quota.quota - newUsed), resetAt: quota.resetAt },
});
} catch (err: any) {
console.error('LinkedIn posts search error:', err);
res.status(500).json({ error: err?.message || 'Could not search LinkedIn posts.' });
}
});
// Save ONE LinkedIn post from the search screen to the user's job list
// (dashboard). Idempotent: already-saved posts are skipped.
app.post('/api/linkedin-posts/save', (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
const p = req.body?.post;
if (!p?.title || !p?.url) return res.status(400).json({ error: 'Post is required.' });
const job: Job = {
id: String(p.id || `linkedinpost-${crypto.createHash('sha1').update(String(p.url)).digest('base64url').slice(0, 20)}`),
title: String(p.title).slice(0, 110),
company: String(p.company || 'Unknown Company').slice(0, 100),
url: String(p.url),
applyUrl: String(p.applyUrl || ''),
location: '',
postedDate: String(p.postedDate || new Date().toISOString()),
description: String(p.description || '').slice(0, 3000),
hashtags: Array.isArray(p.hashtags) ? p.hashtags.map(String).slice(0, 10) : [],
source: 'LinkedInPosts',
jobType: 'Post',
state: 'pending',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
const { added } = persistJobsWithUpgrade([job]);
markLpHistorySaved(userId, job.id);
res.json({ saved: added.length > 0, alreadySaved: added.length === 0, id: job.id });
} catch (err: any) {
res.status(500).json({ error: err?.message || 'Could not save post.' });
}
});
// LinkedIn Posts search history — per user, server-side. Returns every post
// found on the search screen so it survives refresh/browser/device.
app.get('/api/linkedin-posts/history', (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
res.json({ posts: getLpHistory(userId) });
} catch (err: any) {
res.status(500).json({ error: err?.message || 'Could not load LinkedIn Posts history.' });
}
});
app.delete('/api/linkedin-posts/history', (req, res) => {
try {
const userId = getCurrentUserId();
if (!userId) return res.status(401).json({ error: 'Not signed in.' });
clearLpHistory(userId);
res.json({ success: true });
} catch (err: any) {
res.status(500).json({ error: err?.message || 'Could not clear LinkedIn Posts history.' });
}
});