@danhachuel/jobfinder 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +29 -7
- package/package.json +1 -1
- package/scripts/cli.mjs +54 -1
- package/scripts/manual-tests/fase1-auth-dryrun.mjs +171 -0
- package/scripts/manual-tests/fase1-dryrun-services.mjs +130 -0
- package/scripts/manual-tests/fase1-screens.mjs +63 -0
- package/scripts/manual-tests/fase1-ui-e2e.mjs +174 -0
- package/scripts/manual-tests/startup-keepalive.mjs +162 -0
- package/src/server/app.mjs +7 -1
- package/src/server/context.mjs +4 -1
- package/src/server/index.mjs +94 -2
- package/src/server/middleware/auth.mjs +69 -0
- package/src/server/routes/auth.mjs +107 -0
- package/src/server/routes/channels.mjs +2 -0
- package/src/server/routes/config.mjs +16 -4
- package/src/server/services/linkedin/index.mjs +22 -1
- package/src/server/services/outreach/cascades.mjs +16 -2
- package/src/server/services/outreach/invitations.mjs +4 -3
- package/src/server/services/posting/publisher.mjs +6 -3
- package/src/server/storage/authStore.mjs +308 -0
- package/src/server/storage/bootstrap.mjs +4 -0
- package/src/server/storage/configSync.mjs +30 -0
- package/src/ui/dist/assets/index-Dyz0cjaY.js +13 -0
- package/src/ui/dist/assets/index-I2Td16Kp.css +2 -0
- package/src/ui/dist/index.html +2 -2
- package/src/ui/dist/assets/index-Bpm_FEKz.css +0 -2
- package/src/ui/dist/assets/index-Enbh5cVz.js +0 -13
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Teste E2E da UI (Playwright) da Fase 1: login, proteção de rotas,
|
|
3
|
+
* toggle de dry-run, badge Real Mode, troca de senha e logout.
|
|
4
|
+
*
|
|
5
|
+
* Uso: node scripts/manual-tests/fase1-ui-e2e.mjs
|
|
6
|
+
* (o Playwright é uma dependência opcional do projeto)
|
|
7
|
+
*/
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import process from 'node:process';
|
|
13
|
+
|
|
14
|
+
const PORT = 4111;
|
|
15
|
+
const HOME = path.join(os.tmpdir(), `jobfinder-fase1-ui-${Date.now()}`);
|
|
16
|
+
const APP = `http://127.0.0.1:${PORT}`;
|
|
17
|
+
let passed = 0;
|
|
18
|
+
let failed = 0;
|
|
19
|
+
|
|
20
|
+
/** Wait until a previous run released the port. */
|
|
21
|
+
async function waitPortFree(port) {
|
|
22
|
+
for (let attempt = 0; attempt < 40; attempt += 1) {
|
|
23
|
+
try {
|
|
24
|
+
await fetch(`http://127.0.0.1:${port}/api/health`);
|
|
25
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
26
|
+
} catch {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function check(name, condition, extra = '') {
|
|
33
|
+
if (condition) {
|
|
34
|
+
passed += 1;
|
|
35
|
+
console.log(` OK ${name}${extra ? ` — ${extra}` : ''}`);
|
|
36
|
+
} else {
|
|
37
|
+
failed += 1;
|
|
38
|
+
console.log(` FAIL ${name}${extra ? ` — ${extra}` : ''}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const server = spawn(process.execPath, ['src/server/index.mjs'], {
|
|
43
|
+
cwd: process.cwd(),
|
|
44
|
+
env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_OPEN: '1' },
|
|
45
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
46
|
+
});
|
|
47
|
+
server.stdout.on('data', () => {});
|
|
48
|
+
server.stderr.on('data', (d) => console.log(' [server:err]', String(d)));
|
|
49
|
+
await waitPortFree(PORT);
|
|
50
|
+
await new Promise((resolve) => setTimeout(resolve, 1800));
|
|
51
|
+
|
|
52
|
+
let browser;
|
|
53
|
+
try {
|
|
54
|
+
const { chromium } = await import('playwright');
|
|
55
|
+
// Reuse any chromium build already on the machine (the optional Playwright
|
|
56
|
+
// dependency may not match the browser cache version).
|
|
57
|
+
const cache = path.join(os.homedir(), 'AppData', 'Local', 'ms-playwright');
|
|
58
|
+
const existing = fs
|
|
59
|
+
.readdirSync(cache, { withFileTypes: true })
|
|
60
|
+
.filter((entry) => entry.isDirectory() && entry.name.startsWith('chromium-'))
|
|
61
|
+
.map((entry) => path.join(cache, entry.name, 'chrome-win64', 'chrome.exe'))
|
|
62
|
+
.filter((candidate) => fs.existsSync(candidate))
|
|
63
|
+
.sort()
|
|
64
|
+
.pop();
|
|
65
|
+
browser = await chromium.launch({ headless: true, args: ['--no-sandbox'], ...(existing ? { executablePath: existing } : {}) });
|
|
66
|
+
console.log(` (chromium: ${existing ?? 'padrao do playwright'})`);
|
|
67
|
+
const page = await browser.newPage();
|
|
68
|
+
const errors = [];
|
|
69
|
+
page.on('pageerror', (err) => errors.push(String(err)));
|
|
70
|
+
|
|
71
|
+
console.log('\n== Proteção de rotas ==');
|
|
72
|
+
await page.goto(`${APP}/vagas`, { waitUntil: 'networkidle' });
|
|
73
|
+
await page.waitForURL('**/login', { timeout: 8000 });
|
|
74
|
+
check('acesso sem login redireciona para /login', page.url().endsWith('/login'), page.url());
|
|
75
|
+
|
|
76
|
+
const loginVisible = await page.locator('h2', { hasText: 'Bem-vindo de volta!' }).isVisible();
|
|
77
|
+
check('tela de login é exibida', loginVisible);
|
|
78
|
+
const brandVisible = await page.locator('h1', { hasText: 'JobFinder' }).isVisible();
|
|
79
|
+
check('painel de marca JobFinder presente', brandVisible);
|
|
80
|
+
const hintVisible = await page.locator('text=dan.hachuel@gmail.com').isVisible();
|
|
81
|
+
check('dica de primeiro acesso com o usuário padrão', hintVisible);
|
|
82
|
+
|
|
83
|
+
console.log('\n== Credenciais inválidas ==');
|
|
84
|
+
await page.fill('#email', 'dan.hachuel@gmail.com');
|
|
85
|
+
await page.fill('#password', 'errada');
|
|
86
|
+
await page.click('button[type="submit"]');
|
|
87
|
+
await page.waitForSelector('[role="alert"]', { timeout: 8000 });
|
|
88
|
+
check('erro de credencial é exibido', (await page.locator('[role="alert"]').innerText()).includes('inválidos'));
|
|
89
|
+
check('continua na tela de login', page.url().endsWith('/login'));
|
|
90
|
+
|
|
91
|
+
console.log('\n== Login válido ==');
|
|
92
|
+
await page.fill('#email', 'dan.hachuel@gmail.com');
|
|
93
|
+
await page.fill('#password', '123456');
|
|
94
|
+
await page.click('button[type="submit"]');
|
|
95
|
+
// Volta para a rota pedida antes do login (/vagas) ou para o Painel.
|
|
96
|
+
await page.waitForURL((url) => url.pathname === '/vagas' || url.pathname === '/', { timeout: 15000 });
|
|
97
|
+
check('login redireciona para a rota pedida', /\/vagas$|\/$/.test(new URL(page.url()).pathname), page.url());
|
|
98
|
+
|
|
99
|
+
await page.waitForSelector('aside p:has-text("dan.hachuel@gmail.com")', { timeout: 15000 });
|
|
100
|
+
const sidebarEmail = await page
|
|
101
|
+
.locator('aside p', { hasText: 'dan.hachuel@gmail.com' })
|
|
102
|
+
.count();
|
|
103
|
+
check('sidebar mostra a conta logada', sidebarEmail > 0);
|
|
104
|
+
|
|
105
|
+
const dryBadge = page.locator('header span', { hasText: 'dry-run' });
|
|
106
|
+
check('badge dry-run aparece no topo', (await dryBadge.count()) > 0);
|
|
107
|
+
|
|
108
|
+
console.log('\n== Configuracoes: execucao e seguranca ==');
|
|
109
|
+
await page.click('aside a[href="/configuracoes"]');
|
|
110
|
+
await page.waitForURL('**/configuracoes', { timeout: 8000 });
|
|
111
|
+
await page.waitForSelector('input[aria-label="Desativar dry-run"]', { timeout: 15000 });
|
|
112
|
+
const warning = await page.locator('text=/Use com responsabilidade/').isVisible();
|
|
113
|
+
check('aviso de modo real está presente', warning);
|
|
114
|
+
|
|
115
|
+
await page.click('input[aria-label="Desativar dry-run"]');
|
|
116
|
+
await page.waitForSelector('text=Desativar o dry-run?', { timeout: 8000 });
|
|
117
|
+
check('modal de confirmação é exibido', true);
|
|
118
|
+
await page.click('text=Sim, ativar modo real');
|
|
119
|
+
await page.waitForSelector('header span:has-text("Real Mode")', { timeout: 10000 });
|
|
120
|
+
check('badge Real Mode (vermelho) aparece no topo', true);
|
|
121
|
+
|
|
122
|
+
const configOnDisk = JSON.parse(fs.readFileSync(path.join(HOME, 'config.json'), 'utf8'));
|
|
123
|
+
check('config.json em disco tem dryRun=false', configOnDisk.dryRun === false);
|
|
124
|
+
const health = await (await fetch(`${APP}/api/health`)).json();
|
|
125
|
+
check('API confirma dryRun=false (sem restart)', health.dryRun === false);
|
|
126
|
+
|
|
127
|
+
// Volta para dry-run (toggle agora rotulado "Ativar dry-run").
|
|
128
|
+
await page.click('input[aria-label="Ativar dry-run"]');
|
|
129
|
+
await page.waitForSelector('header span:has-text("dry-run")', { timeout: 10000 });
|
|
130
|
+
check('badge dry-run volta a aparecer', true);
|
|
131
|
+
|
|
132
|
+
console.log('\n== Troca de senha ==');
|
|
133
|
+
await page.fill('#currentPassword', '123456');
|
|
134
|
+
await page.fill('#newPassword', 'novaSenha123');
|
|
135
|
+
await page.fill('#confirmPassword', 'novaSenha123');
|
|
136
|
+
await page.click('button:has-text("Alterar senha")');
|
|
137
|
+
await page.waitForSelector('text=Senha alterada', { timeout: 10000 });
|
|
138
|
+
check('toast confirma a troca de senha', true);
|
|
139
|
+
const authFile = JSON.parse(fs.readFileSync(path.join(HOME, 'auth.json'), 'utf8'));
|
|
140
|
+
check('auth.json guarda apenas o hash', authFile.user.passwordHash.startsWith('scrypt$') && !JSON.stringify(authFile).includes('novaSenha123'));
|
|
141
|
+
|
|
142
|
+
console.log('\n== Logout e novo login ==');
|
|
143
|
+
await page.click('aside button:has-text("Sair")');
|
|
144
|
+
await page.waitForURL('**/login', { timeout: 10000 });
|
|
145
|
+
check('logout volta para /login', page.url().endsWith('/login'));
|
|
146
|
+
|
|
147
|
+
await page.goto(`${APP}/config`, { waitUntil: 'networkidle' });
|
|
148
|
+
await page.waitForURL('**/login', { timeout: 8000 });
|
|
149
|
+
check('rota protegida volta a redirecionar para /login', page.url().endsWith('/login'));
|
|
150
|
+
|
|
151
|
+
await page.fill('#email', 'dan.hachuel@gmail.com');
|
|
152
|
+
await page.fill('#password', '123456');
|
|
153
|
+
await page.click('button[type="submit"]');
|
|
154
|
+
await page.waitForSelector('[role="alert"]', { timeout: 8000 });
|
|
155
|
+
check('senha antiga é rejeitada', (await page.locator('[role="alert"]').innerText()).includes('inválidos'));
|
|
156
|
+
|
|
157
|
+
await page.fill('#email', 'dan.hachuel@gmail.com');
|
|
158
|
+
await page.fill('#password', 'novaSenha123');
|
|
159
|
+
await page.click('button[type="submit"]');
|
|
160
|
+
await page.waitForURL((url) => url.pathname === '/' || url.pathname === '/config', { timeout: 15000 });
|
|
161
|
+
check('nova senha permite o login', /\/$|\/config$/.test(new URL(page.url()).pathname), page.url());
|
|
162
|
+
|
|
163
|
+
const consoleErrors = errors.filter((e) => !e.includes('ResizeObserver'));
|
|
164
|
+
check('sem erros de console relevantes', consoleErrors.length === 0, consoleErrors.slice(0, 2).join(' | '));
|
|
165
|
+
} catch (err) {
|
|
166
|
+
failed += 1;
|
|
167
|
+
console.log(` FAIL exceção no teste: ${err.message}`);
|
|
168
|
+
} finally {
|
|
169
|
+
await browser?.close().catch(() => {});
|
|
170
|
+
server.kill();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
|
|
174
|
+
process.exit(failed ? 1 : 0);
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Teste de regressão: o processo do JobFinder NÃO pode encerrar sozinho.
|
|
3
|
+
*
|
|
4
|
+
* Cobre:
|
|
5
|
+
* 1. boot via launcher (node scripts/cli.mjs start) — o terminal deve
|
|
6
|
+
* ficar preso rodando o servidor; a API responde em localhost
|
|
7
|
+
* 2. boot direto (node src/server/index.mjs) — mesmo comportamento
|
|
8
|
+
* 3. injeção de falha: um unhandledRejection proposital após o boot
|
|
9
|
+
* NÃO pode matar o processo (era o killer silencioso no Node >= 15)
|
|
10
|
+
* 4. SIGTERM encerra de forma limpa — verificado emitindo o sinal dentro
|
|
11
|
+
* do próprio processo (no Windows, child.kill() sempre vira
|
|
12
|
+
* TerminateProcess e os handlers graceful nunca rodam)
|
|
13
|
+
*
|
|
14
|
+
* Uso: node scripts/manual-tests/startup-keepalive.mjs
|
|
15
|
+
*/
|
|
16
|
+
import { spawn } from 'node:child_process';
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import http from 'node:http';
|
|
19
|
+
import os from 'node:os';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import process from 'node:process';
|
|
22
|
+
|
|
23
|
+
const ROOT = process.cwd();
|
|
24
|
+
let passed = 0;
|
|
25
|
+
let failed = 0;
|
|
26
|
+
|
|
27
|
+
function check(name, condition, extra = '') {
|
|
28
|
+
if (condition) {
|
|
29
|
+
passed += 1;
|
|
30
|
+
console.log(` OK ${name}${extra ? ` — ${extra}` : ''}`);
|
|
31
|
+
} else {
|
|
32
|
+
failed += 1;
|
|
33
|
+
console.log(` FAIL ${name}${extra ? ` — ${extra}` : ''}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
38
|
+
|
|
39
|
+
function getStatus(port, urlPath) {
|
|
40
|
+
return new Promise((resolve) => {
|
|
41
|
+
const req = http.get({ host: '127.0.0.1', port, path: urlPath }, (res) => {
|
|
42
|
+
res.resume();
|
|
43
|
+
resolve(res.statusCode);
|
|
44
|
+
});
|
|
45
|
+
req.on('error', () => resolve(null));
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const dead = (child) => child.exitCode !== null || child.signalCode !== null;
|
|
50
|
+
|
|
51
|
+
/** Sobe o app e observa por `observeMs` sem enviar nenhum sinal. */
|
|
52
|
+
async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
53
|
+
console.log(`\n== ${label} ==`);
|
|
54
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-'));
|
|
55
|
+
const home = path.join(tmp, 'data');
|
|
56
|
+
const child = spawn(process.execPath, args, {
|
|
57
|
+
cwd: ROOT,
|
|
58
|
+
env: { ...process.env, JOBFINDER_PORT: String(port), JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', ...env },
|
|
59
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
60
|
+
});
|
|
61
|
+
let out = '';
|
|
62
|
+
child.stdout.on('data', (d) => { out += String(d); });
|
|
63
|
+
child.stderr.on('data', (d) => { out += String(d); });
|
|
64
|
+
await wait(observeMs);
|
|
65
|
+
check('processo continua rodando após o startup (event loop aberto)', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : `vivo após ${observeMs}ms`);
|
|
66
|
+
const status = await getStatus(port, '/api/health');
|
|
67
|
+
check('API responde em localhost', status === 200, `HTTP ${status ?? 'sem resposta'}`);
|
|
68
|
+
return { child, out, home };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 1) launcher: o terminal precisa ficar preso rodando o servidor
|
|
72
|
+
{
|
|
73
|
+
const { child } = await bootAndObserve('boot via launcher (node scripts/cli.mjs start)', {
|
|
74
|
+
args: [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'],
|
|
75
|
+
port: 4181,
|
|
76
|
+
observeMs: 9000,
|
|
77
|
+
});
|
|
78
|
+
child.kill();
|
|
79
|
+
await wait(5000);
|
|
80
|
+
check('processo encerra ao receber sinal (não fica pendurado)', dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'ainda vivo');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 2) boot direto: mesma garantia, com encerramento gracioso verificado
|
|
84
|
+
{
|
|
85
|
+
const { child } = await bootAndObserve('boot direto (node src/server/index.mjs)', {
|
|
86
|
+
args: [path.join(ROOT, 'src', 'server', 'index.mjs')],
|
|
87
|
+
port: 4182,
|
|
88
|
+
observeMs: 7000,
|
|
89
|
+
});
|
|
90
|
+
child.kill();
|
|
91
|
+
await wait(500);
|
|
92
|
+
|
|
93
|
+
// Sinal emitido dentro do processo (preload): os handlers graceful rodam
|
|
94
|
+
// em qualquer plataforma — no Windows, child.kill() vira TerminateProcess.
|
|
95
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-sig-'));
|
|
96
|
+
const home = path.join(tmp, 'data');
|
|
97
|
+
const preload = path.join(tmp, 'sigterm.cjs');
|
|
98
|
+
fs.writeFileSync(preload, "setTimeout(() => process.emit('SIGTERM'), 8000);\n");
|
|
99
|
+
const second = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'index.mjs')], {
|
|
100
|
+
cwd: ROOT,
|
|
101
|
+
env: { ...process.env, JOBFINDER_PORT: '4182', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', NODE_OPTIONS: `--require ${preload}` },
|
|
102
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
103
|
+
});
|
|
104
|
+
await wait(9500);
|
|
105
|
+
check('encerramento gracioso ao receber SIGTERM (exit 0)', second.exitCode === 0, second.exitCode !== null || second.signalCode !== null ? `exitCode=${second.exitCode} signal=${second.signalCode}` : 'ainda vivo');
|
|
106
|
+
const logs = fs.existsSync(path.join(home, 'logs'))
|
|
107
|
+
? fs.readdirSync(path.join(home, 'logs')).map((f) => fs.readFileSync(path.join(home, 'logs', f), 'utf8')).join('\n')
|
|
108
|
+
: '';
|
|
109
|
+
check('shutdown gracioso registrado no log', /"shutdown"/.test(logs), logs.split('\n').filter((l) => /shutdown/.test(l))[0] ?? '');
|
|
110
|
+
if (second.exitCode === null && second.signalCode === null) second.kill();
|
|
111
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 3) injeção de falha: unhandledRejection após o boot não pode matar o processo
|
|
115
|
+
{
|
|
116
|
+
console.log('\n== boot com unhandledRejection injetado (killer silencioso) ==');
|
|
117
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-fault-'));
|
|
118
|
+
const home = path.join(tmp, 'data');
|
|
119
|
+
const fault = path.join(tmp, 'fault.cjs');
|
|
120
|
+
fs.writeFileSync(fault, "setTimeout(() => { Promise.reject(new Error('fault-injection: unhandled rejection')); }, 1200);\n");
|
|
121
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
|
|
122
|
+
cwd: ROOT,
|
|
123
|
+
env: { ...process.env, JOBFINDER_PORT: '4183', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', NODE_OPTIONS: `--require ${fault}` },
|
|
124
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
125
|
+
});
|
|
126
|
+
let out = '';
|
|
127
|
+
child.stdout.on('data', (d) => { out += String(d); });
|
|
128
|
+
child.stderr.on('data', (d) => { out += String(d); });
|
|
129
|
+
await wait(9000);
|
|
130
|
+
check('processo sobrevive ao unhandledRejection', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
131
|
+
check('API responde em localhost', (await getStatus(4183, '/api/health')) === 200);
|
|
132
|
+
check('rejeição foi registrada no log (não engolida em silêncio)', /unhandled promise rejection ignored/i.test(out), out.split('\n').filter((l) => /rejection/i.test(l))[0] ?? '');
|
|
133
|
+
child.kill();
|
|
134
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// 4) stdout quebrado (EPIPE) — ex.: pipe fechado, terminal que some,
|
|
138
|
+
// redirecionamento no Windows/MobaXterm. Não pode matar o processo.
|
|
139
|
+
{
|
|
140
|
+
console.log('\n== boot com stdout fechado (EPIPE) ==');
|
|
141
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-epipe-'));
|
|
142
|
+
const home = path.join(tmp, 'data');
|
|
143
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
|
|
144
|
+
cwd: ROOT,
|
|
145
|
+
env: { ...process.env, JOBFINDER_PORT: '4184', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1' },
|
|
146
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
147
|
+
});
|
|
148
|
+
child.stdout.on('data', () => {});
|
|
149
|
+
child.stderr.on('data', () => {});
|
|
150
|
+
await wait(3000);
|
|
151
|
+
// Fecha a ponta de leitura: os próximos console.log geram EPIPE.
|
|
152
|
+
child.stdout.destroy();
|
|
153
|
+
child.stderr.destroy();
|
|
154
|
+
await wait(6000);
|
|
155
|
+
check('processo sobrevive ao stdout quebrado', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
156
|
+
check('API responde em localhost', (await getStatus(4184, '/api/health')) === 200);
|
|
157
|
+
child.kill();
|
|
158
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
|
|
162
|
+
process.exit(failed ? 1 : 0);
|
package/src/server/app.mjs
CHANGED
|
@@ -11,6 +11,8 @@ import path from 'node:path';
|
|
|
11
11
|
|
|
12
12
|
import { UI_DIST, REPO_ROOT } from './paths.mjs';
|
|
13
13
|
import { createApiRouter } from './routes/index.mjs';
|
|
14
|
+
import { authRoutes } from './routes/auth.mjs';
|
|
15
|
+
import { requireAuth } from './middleware/auth.mjs';
|
|
14
16
|
|
|
15
17
|
function readPkgVersion() {
|
|
16
18
|
try {
|
|
@@ -39,8 +41,12 @@ export function createApp({ store, logger, config, rateLimiter, dataDir }) {
|
|
|
39
41
|
next();
|
|
40
42
|
});
|
|
41
43
|
|
|
44
|
+
// Public auth routes (login/logout/session) — mounted before the guard.
|
|
45
|
+
app.use('/api/auth', authRoutes({ store, logger, config }));
|
|
46
|
+
|
|
47
|
+
// Everything else under /api requires an active local session.
|
|
42
48
|
const api = createApiRouter({ store, logger, config, rateLimiter, dataDir });
|
|
43
|
-
app.use('/api', api);
|
|
49
|
+
app.use('/api', requireAuth({ store, logger }), api);
|
|
44
50
|
|
|
45
51
|
// Static UI (built by Vite). In dev, the Vite server proxies /api here.
|
|
46
52
|
if (fs.existsSync(UI_DIST)) {
|
package/src/server/context.mjs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { JsonStore } from './storage/jsonStore.mjs';
|
|
9
9
|
import { Logger } from './storage/logger.mjs';
|
|
10
10
|
import { RateLimiter } from './middleware/rateLimiter.mjs';
|
|
11
|
+
import { AuthStore } from './storage/authStore.mjs';
|
|
11
12
|
import { ensureDataDir } from './storage/bootstrap.mjs';
|
|
12
13
|
|
|
13
14
|
export function createContext(dataDir) {
|
|
@@ -16,5 +17,7 @@ export function createContext(dataDir) {
|
|
|
16
17
|
const logger = new Logger(dataDir);
|
|
17
18
|
const config = store.read('config.json', {});
|
|
18
19
|
const rateLimiter = new RateLimiter({ config, logger });
|
|
19
|
-
|
|
20
|
+
const auth = new AuthStore(store);
|
|
21
|
+
auth.ensure();
|
|
22
|
+
return { dataDir, store, logger, config, rateLimiter, auth };
|
|
20
23
|
}
|
package/src/server/index.mjs
CHANGED
|
@@ -19,6 +19,66 @@ import { createContext } from './context.mjs';
|
|
|
19
19
|
import { resolveDataDir, UI_DIST } from './paths.mjs';
|
|
20
20
|
import { startWorkers } from './services/workers.mjs';
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Logger used by the global process handlers below. Assigned by start():
|
|
24
|
+
* the handlers are registered before the context exists, but they only
|
|
25
|
+
* ever fire once the server is running.
|
|
26
|
+
*/
|
|
27
|
+
let activeLogger = null;
|
|
28
|
+
let resilienceInstalled = false;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Process resilience — installed before anything else can fail.
|
|
32
|
+
*
|
|
33
|
+
* The server keeps the Node event loop open through its listening socket
|
|
34
|
+
* for as long as it runs. What can still kill the process *silently*
|
|
35
|
+
* (terminal returns to the prompt, no visible reason):
|
|
36
|
+
*
|
|
37
|
+
* 1. unhandledRejection — since Node 15 an unhandled promise rejection
|
|
38
|
+
* terminates the process immediately (exit 1). Any floating promise
|
|
39
|
+
* (services, workers, storage) rejecting on the user's machine would
|
|
40
|
+
* therefore take the whole app down right after the startup banner.
|
|
41
|
+
* 2. EPIPE on stdio — when the shell/pipe behind the inherited
|
|
42
|
+
* stdout/stderr disappears (Windows terminals, MobaXterm, output
|
|
43
|
+
* redirection), the next console.log throws an unhandled 'error'
|
|
44
|
+
* event on process.stdout and the process dies without a message.
|
|
45
|
+
* 3. uncaughtException — must never be swallowed silently; log it and
|
|
46
|
+
* exit loudly instead of vanishing without a trace.
|
|
47
|
+
*/
|
|
48
|
+
function installProcessResilience() {
|
|
49
|
+
if (resilienceInstalled) return;
|
|
50
|
+
resilienceInstalled = true;
|
|
51
|
+
|
|
52
|
+
// Keep the process alive after a stray async failure instead of dying
|
|
53
|
+
// silently right after startup.
|
|
54
|
+
process.on('unhandledRejection', (reason) => {
|
|
55
|
+
const message = reason instanceof Error ? `${reason.message}` : String(reason);
|
|
56
|
+
activeLogger?.error('startup', 'unhandled promise rejection ignored', {
|
|
57
|
+
message,
|
|
58
|
+
stack: reason instanceof Error ? reason.stack : undefined,
|
|
59
|
+
});
|
|
60
|
+
console.error(`[jobfinder] unhandled promise rejection ignored: ${message}`);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
process.on('uncaughtException', (err) => {
|
|
64
|
+
activeLogger?.error('startup', 'uncaught exception — shutting down', {
|
|
65
|
+
message: err?.message,
|
|
66
|
+
stack: err?.stack,
|
|
67
|
+
});
|
|
68
|
+
console.error('[jobfinder] uncaught exception:', err);
|
|
69
|
+
process.exit(1);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// A closed/broken stdout (EPIPE) must not kill the server: the server
|
|
73
|
+
// keeps running headless and stays reachable at http://127.0.0.1:PORT.
|
|
74
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
75
|
+
stream?.on?.('error', (err) => {
|
|
76
|
+
if (err?.code === 'EPIPE') return;
|
|
77
|
+
activeLogger?.error('startup', 'stdio error', { code: err?.code, message: err?.message });
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
22
82
|
function readPkgVersion() {
|
|
23
83
|
try {
|
|
24
84
|
const pkg = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), 'package.json'), 'utf8'));
|
|
@@ -28,10 +88,20 @@ function readPkgVersion() {
|
|
|
28
88
|
}
|
|
29
89
|
}
|
|
30
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Module-level handle: start() returns it, but the entrypoint discards it.
|
|
93
|
+
* Keeping the reference here guarantees the http.Server object itself can
|
|
94
|
+
* never be collected while the app is serving.
|
|
95
|
+
*/
|
|
96
|
+
let moduleScopeServer = null;
|
|
97
|
+
|
|
31
98
|
export async function start() {
|
|
99
|
+
installProcessResilience();
|
|
100
|
+
|
|
32
101
|
const dataDir = resolveDataDir();
|
|
33
102
|
const context = createContext(dataDir);
|
|
34
|
-
const { store, logger, config } = context;
|
|
103
|
+
const { store, logger, config, auth } = context;
|
|
104
|
+
activeLogger = logger;
|
|
35
105
|
|
|
36
106
|
if (process.env.JOBFINDER_DRY_RUN === '1') {
|
|
37
107
|
context.config.dryRun = true;
|
|
@@ -55,9 +125,19 @@ export async function start() {
|
|
|
55
125
|
console.log(`Data directory: ${dataDir}`);
|
|
56
126
|
if (context.config.dryRun) {
|
|
57
127
|
console.log('DRY-RUN mode: no real LinkedIn actions will be sent.');
|
|
128
|
+
} else {
|
|
129
|
+
console.log('REAL MODE: live LinkedIn actions are enabled (dry-run is OFF).');
|
|
58
130
|
}
|
|
131
|
+
console.log(`Login: ${auth.getUser().email}${auth.usingDefaultPassword() ? ' / 123456 (troque a senha em Configurações)' : ''}`);
|
|
59
132
|
});
|
|
60
133
|
|
|
134
|
+
// Pin the server handle: the listening socket keeps the event loop (and
|
|
135
|
+
// therefore the process) open for as long as the app runs. Holding the
|
|
136
|
+
// reference at module and global scope also guarantees it can never be
|
|
137
|
+
// collected while the app is serving.
|
|
138
|
+
moduleScopeServer = server;
|
|
139
|
+
globalThis.__jobfinder = { app, server, context };
|
|
140
|
+
|
|
61
141
|
server.on('error', (err) => {
|
|
62
142
|
if (err.code === 'EADDRINUSE') {
|
|
63
143
|
console.error(`Port ${port} is already in use. Start JobFinder with another port:`);
|
|
@@ -69,15 +149,27 @@ export async function start() {
|
|
|
69
149
|
});
|
|
70
150
|
|
|
71
151
|
// Background workers: post scheduler + DM cascade engine + inbox monitoring.
|
|
72
|
-
startWorkers(context);
|
|
152
|
+
const workers = startWorkers(context);
|
|
73
153
|
|
|
154
|
+
let shuttingDown = false;
|
|
74
155
|
const shutdown = (signal) => {
|
|
156
|
+
if (shuttingDown) return;
|
|
157
|
+
shuttingDown = true;
|
|
75
158
|
logger.info('shutdown', `received ${signal}`);
|
|
159
|
+
try {
|
|
160
|
+
workers?.stop?.();
|
|
161
|
+
} catch {
|
|
162
|
+
/* stopping workers is best-effort */
|
|
163
|
+
}
|
|
76
164
|
server.close(() => process.exit(0));
|
|
165
|
+
// Never hang on a stuck keep-alive connection: force the exit.
|
|
77
166
|
setTimeout(() => process.exit(0), 3000).unref();
|
|
78
167
|
};
|
|
79
168
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
80
169
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
170
|
+
// Windows-only signal (Ctrl+Break), e.g. MobaXterm terminals. Registering
|
|
171
|
+
// it elsewhere is a harmless no-op.
|
|
172
|
+
process.on('SIGBREAK', () => shutdown('SIGBREAK'));
|
|
81
173
|
|
|
82
174
|
return { app, server, context };
|
|
83
175
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JobFinder — auth guard.
|
|
3
|
+
*
|
|
4
|
+
* Every /api route (and therefore every UI screen) requires an active
|
|
5
|
+
* local session. Exceptions:
|
|
6
|
+
* /api/auth/* login / logout / session check
|
|
7
|
+
* /api/health public liveness (used by the CI smoke test)
|
|
8
|
+
* /api/channels/oauth/callback LinkedIn redirects the browser here
|
|
9
|
+
*
|
|
10
|
+
* The session token travels in an HTTP-only cookie (browser) or as a
|
|
11
|
+
* Bearer token (curl/API tests).
|
|
12
|
+
*/
|
|
13
|
+
import { AuthStore, extractToken } from '../storage/authStore.mjs';
|
|
14
|
+
|
|
15
|
+
/** API paths reachable without a session. */
|
|
16
|
+
const PUBLIC_PATHS = ['/health', '/channels/oauth/callback'];
|
|
17
|
+
|
|
18
|
+
function isPublic(req) {
|
|
19
|
+
const candidates = [req.path, req.originalUrl?.split('?')[0]?.replace(/^\/api/, '')];
|
|
20
|
+
return candidates.some((path) => path && PUBLIC_PATHS.includes(path));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Resolve the session user of a request, or null. */
|
|
24
|
+
export function sessionUser(auth, req) {
|
|
25
|
+
const token = extractToken(req);
|
|
26
|
+
if (!token) return null;
|
|
27
|
+
const payload = auth.verifyToken(token);
|
|
28
|
+
if (!payload) return null;
|
|
29
|
+
return { email: payload.sub, jti: payload.jti };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Middleware: 401 `unauthorized` when there is no valid session.
|
|
34
|
+
* @param {{ store: import('../storage/jsonStore.mjs').JsonStore, logger: object }} ctx
|
|
35
|
+
*/
|
|
36
|
+
export function requireAuth({ store, logger }) {
|
|
37
|
+
const auth = new AuthStore(store);
|
|
38
|
+
auth.ensure();
|
|
39
|
+
return (req, res, next) => {
|
|
40
|
+
if (isPublic(req)) return next();
|
|
41
|
+
const user = sessionUser(auth, req);
|
|
42
|
+
if (!user) {
|
|
43
|
+
logger?.warn('auth', 'unauthorized request', { url: req.originalUrl });
|
|
44
|
+
return res
|
|
45
|
+
.status(401)
|
|
46
|
+
.json({ error: { code: 'unauthorized', message: 'Sessão não encontrada ou expirada. Faça login novamente.' } });
|
|
47
|
+
}
|
|
48
|
+
req.user = user;
|
|
49
|
+
return next();
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Small helper for routes mounted outside the guard (the /api/auth router
|
|
55
|
+
* is registered before it): rejects the request when there is no session.
|
|
56
|
+
*/
|
|
57
|
+
export function requireSession({ store }) {
|
|
58
|
+
const auth = new AuthStore(store);
|
|
59
|
+
return (req, res, next) => {
|
|
60
|
+
const user = sessionUser(auth, req);
|
|
61
|
+
if (!user) {
|
|
62
|
+
return res
|
|
63
|
+
.status(401)
|
|
64
|
+
.json({ error: { code: 'unauthorized', message: 'Sessão não encontrada ou expirada. Faça login novamente.' } });
|
|
65
|
+
}
|
|
66
|
+
req.user = user;
|
|
67
|
+
return next();
|
|
68
|
+
};
|
|
69
|
+
}
|