@danhachuel/jobfinder 0.1.13 → 0.1.15
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 +28 -2
- package/README.md +24 -11
- package/package.json +1 -1
- package/scripts/cli.mjs +22 -3
- package/scripts/manual-tests/fase1-ui-e2e.mjs +13 -2
- package/scripts/manual-tests/fase3-seed-env.mjs +130 -0
- package/scripts/manual-tests/fase4-npx-start.mjs +164 -0
- package/src/server/index.mjs +53 -3
- package/src/server/routes/auth.mjs +3 -9
- package/src/server/storage/authStore.mjs +33 -10
- package/src/ui/dist/assets/index-CFAhWKxD.css +2 -0
- package/src/ui/dist/assets/{index-DE0ctLZf.js → index-DtY7qbQR.js} +2 -2
- package/src/ui/dist/index.html +2 -2
- package/src/ui/dist/assets/index-D_t6FNqH.css +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,32 @@ All notable changes to JobFinder are documented in this file.
|
|
|
6
6
|
|
|
7
7
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
8
8
|
|
|
9
|
+
## [0.1.15] — 2026-11-21
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- **Versão `0.0.00` ao rodar via `npx`**: `readPkgVersion()` em `src/server/index.mjs` lia `package.json` com `path.resolve(process.cwd(), 'package.json')`. Sob `npx` o cwd é o diretório do usuário (home do MobaXterm, um path qualquer do PowerShell), a leitura falhava em silêncio e o servidor imprimia `JobFinder v0.0.00 (npm 0.0.0)`. Agora a versão vem de `JOBFINDER_VERSION` (definida pelo launcher, que lê o `package.json` a partir da própria localização do arquivo) ou, na ausência dela, de `createRequire(import.meta.url)` + `require('../../package.json')` — resolvido a partir **deste módulo**, nunca do cwd. O fallback ruidoso (`console.error`) substitui o silencioso.
|
|
14
|
+
- **Retenção do event loop com rastro forense**: `beforeExit` no launcher **e** no servidor registra os handles ativos antes de qualquer saída natural e re-arma um timer de keep-alive **referenciado** (sem `unref()`) quando o socket do servidor não está entre eles — a saída silenciosa agora é impossível sem deixar `[jobfinder] launcher: event loop esvaziando (beforeExit code=…) — handles: …` no terminal. `exit` registra o código final nos dois processos. Nenhum `server.unref()` e nenhum `process.exit(0)` no caminho de startup.
|
|
15
|
+
|
|
16
|
+
### Tests
|
|
17
|
+
|
|
18
|
+
- Nova suíte `scripts/manual-tests/fase4-npx-start.mjs` — **12 verificações, 0 falhas**, rodando o binário de um **diretório estranho** (reprodução do ambiente `npx`/MobaXterm): versão correta na linha do `listen`, processo vivo depois do banner, HTTP 200, caminho `node src/server/index.mjs` direto sem `JOBFINDER_VERSION` (valida o `createRequire`) e caminho completo com worker ativo.
|
|
19
|
+
|
|
20
|
+
## [0.1.14] — 2026-11-20
|
|
21
|
+
|
|
22
|
+
### Security
|
|
23
|
+
|
|
24
|
+
- **Saneamento de credenciais — nenhuma senha em nenhuma superfície**: removido o cartão âmbar de "Primeiro acesso" da tela de login, que exibia e-mail e senha padrão. O terminal já não os exibia (0.1.12) e agora nenhuma rota, resposta de API, log ou documento os expõe.
|
|
25
|
+
- **Rota `GET /api/auth/defaults` descontinuada**: era o canal que alimentava o cartão com o e-mail do usuário semeado. Removida do router — nenhum endpoint devolve mais credenciais.
|
|
26
|
+
- **Onboarding por variável de ambiente**: o first-run account aceita `JOBFINDER_INITIAL_EMAIL` e `JOBFINDER_INITIAL_PASSWORD` (mínimo de 6 caracteres). Sem elas, o seed embutido é usado e a senha deve ser trocada em **Configurações → Segurança** no primeiro acesso. O valor nunca é renderizado em lugar nenhum.
|
|
27
|
+
- **Smoke test do CI sem credenciais no repositório**: `.github/workflows/publish-npm.yml` define as variáveis de seed dentro do step, em vez de embutir e-mail/senha no arquivo versionado.
|
|
28
|
+
- **Documentação**: README e CHANGELOG sem credenciais; a seção "First login" passa a explicar o onboarding (env/`auth.json`) sem citar senha. Nota correspondente adicionada à tela de login.
|
|
29
|
+
|
|
30
|
+
### Notas
|
|
31
|
+
|
|
32
|
+
- A tela de login ficou apenas com o formulário (e-mail, senha, mostrar/ocultar, entrar) e a nota de onboarding em texto simples.
|
|
33
|
+
- Instalações existentes não são afetadas: um `auth.json` já criado é preservado e as env vars só valem na primeira criação.
|
|
34
|
+
|
|
9
35
|
## [0.1.13] — 2026-11-20
|
|
10
36
|
|
|
11
37
|
### Changed
|
|
@@ -26,7 +52,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
26
52
|
|
|
27
53
|
### Security
|
|
28
54
|
|
|
29
|
-
- **Remoção definitiva da senha no terminal**: a linha `Login: <email> / <senha>` foi **deletada** do startup do servidor — o terminal não exibe mais e-mail nem senha (a
|
|
55
|
+
- **Remoção definitiva da senha no terminal**: a linha `Login: <email> / <senha>` foi **deletada** do startup do servidor — o terminal não exibe mais e-mail nem senha (a recomendação de troca de senha continua apenas na UI, em Configurações → Segurança). Verificado em boot real: stdout/stderr sem senha, sem e-mail e sem `Login:`.
|
|
30
56
|
|
|
31
57
|
### Fixed
|
|
32
58
|
|
|
@@ -132,7 +158,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
132
158
|
|
|
133
159
|
### Added
|
|
134
160
|
|
|
135
|
-
- **Sistema de login local (autenticação single-user)**:
|
|
161
|
+
- **Sistema de login local (autenticação single-user)**: conta única criada no primeiro boot em `~/.jobfinder/auth.json` com a senha em **hash scrypt** (salt + verificação em tempo constante — nunca em texto puro). Sessão via token assinado (HMAC-SHA256) em **cookie HTTP-only** (`jobfinder_session`, 7 dias, `SameSite=Lax`), também aceito como `Authorization: Bearer` para testes de API. Novo arquivo `src/server/storage/authStore.mjs` + rotas `POST /api/auth/login`, `POST /api/auth/logout`, `GET /api/auth/session`, `PUT /api/auth/password`, `GET /api/auth/defaults`. *(Nota de 2026-11-20: as credenciais de seed foram removidas desta entrada e a rota `/auth/defaults` foi descontinuada na 0.1.14 — ver “Saneamento de credenciais”.)*
|
|
136
162
|
- **Proteção de rotas**: todo o app (exceto `/login`) exige sessão ativa — sem sessão, a UI redireciona para `/login` e a API responde `401 unauthorized`. Ficam públicos apenas `/api/auth/*`, `/api/health` (smoke test do CI) e `/api/channels/oauth/callback` (redirect do LinkedIn). Um `401` em qualquer request derruba a sessão e volta para o login.
|
|
137
163
|
- **Tela de login** (`src/ui/src/pages/Login.jsx`) no padrão visual da tela de login do ProdMaker, adaptada para a identidade JobFinder (`#1e1b4b`, acento indigo): painel de marca escuro com orbs/partículas animadas e os 4 passos do fluxo (Publique com LLM → Conecte-se → DMs em cascata → Candidate-se), painel de formulário com ícones, mostrar/ocultar senha, caixa de erro e dica de primeiro acesso com as credenciais padrão (a dica desaparece quando a senha deixa de ser a padrão).
|
|
138
164
|
- **Logout e conta na sidebar**: rodapé da sidebar mostra o usuário logado (avatar + e-mail) e o botão **Sair**, ao lado do selo "100% local".
|
package/README.md
CHANGED
|
@@ -31,27 +31,38 @@ A **background worker** (separate Node process) keeps the queues moving even wit
|
|
|
31
31
|
Windows / CMD / MobaXterm:
|
|
32
32
|
|
|
33
33
|
```bash
|
|
34
|
-
npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.
|
|
35
|
-
npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.
|
|
34
|
+
npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.15 install
|
|
35
|
+
npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.15
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
Normal terminal:
|
|
39
39
|
|
|
40
40
|
```bash
|
|
41
|
-
npx --yes @danhachuel/jobfinder@0.1.
|
|
42
|
-
npx --yes @danhachuel/jobfinder@0.1.
|
|
41
|
+
npx --yes @danhachuel/jobfinder@0.1.15 install
|
|
42
|
+
npx --yes @danhachuel/jobfinder@0.1.15
|
|
43
43
|
```
|
|
44
44
|
|
|
45
45
|
`install` creates `~/.jobfinder/` (config, auth, channels, topics, posts, connections, dm-cascades, jobs, applications, resume, logs). It is safe to re-run: existing data is never overwritten.
|
|
46
46
|
|
|
47
47
|
## First login
|
|
48
48
|
|
|
49
|
-
The app is protected by a local session.
|
|
49
|
+
The app is protected by a local session. **Credentials are never displayed** — not on the login screen, not in the terminal, and not in this document.
|
|
50
50
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
51
|
+
The single first-run account is created in `~/.jobfinder/auth.json` on the first boot. Define your own initial credentials through the environment **before** the first start:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
# Windows (PowerShell)
|
|
55
|
+
$env:JOBFINDER_INITIAL_EMAIL = "voce@exemplo.com"
|
|
56
|
+
$env:JOBFINDER_INITIAL_PASSWORD = "sua-senha-forte"
|
|
57
|
+
npx --yes @danhachuel/jobfinder@0.1.15
|
|
58
|
+
|
|
59
|
+
# Linux / macOS
|
|
60
|
+
JOBFINDER_INITIAL_EMAIL="voce@exemplo.com" \
|
|
61
|
+
JOBFINDER_INITIAL_PASSWORD="sua-senha-forte" \
|
|
62
|
+
npx --yes @danhachuel/jobfinder@0.1.15
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Alternative: create the account directly in `~/.jobfinder/auth.json` (see the `user` object) before starting the app.
|
|
55
66
|
|
|
56
67
|
- Without a session every screen redirects to `/login` (and the API answers `401`).
|
|
57
68
|
- The password is stored hashed (scrypt) in `~/.jobfinder/auth.json` — never in plain text. Change it in **Configurações → Segurança** right after the first login.
|
|
@@ -59,7 +70,7 @@ The app is protected by a local session. On the first run a single user is creat
|
|
|
59
70
|
|
|
60
71
|
## Usage
|
|
61
72
|
|
|
62
|
-
1. Start the app →
|
|
73
|
+
1. Start the app → open `http://localhost:4040` → log in with the credentials you configured
|
|
63
74
|
2. **Integrações** → connect LinkedIn:
|
|
64
75
|
- **Recommended:** create your LinkedIn app ([Criar API Oficial do LinkedIn](legal/)) → paste Client ID/Secret → run the OAuth flow
|
|
65
76
|
- **Fallback:** export cookies with ["Get cookies.txt LOCALLY"](https://chromewebstore.google.com/) and upload `cookies.txt`
|
|
@@ -117,8 +128,10 @@ Manual smoke tests (start a temporary server + Playwright for the UI):
|
|
|
117
128
|
node scripts/manual-tests/fase1-auth-dryrun.mjs # API: login, sessão, toggle dry-run, troca de senha
|
|
118
129
|
node scripts/manual-tests/fase1-dryrun-services.mjs # API: flag dry-run aplicada a postagens/convites/DMs
|
|
119
130
|
node scripts/manual-tests/fase1-ui-e2e.mjs # UI (Playwright): login, badges, configurações, logout
|
|
120
|
-
node scripts/manual-tests/startup-keepalive.mjs # runtime: boot, unhandledRejection, EPIPE, sinais
|
|
121
131
|
node scripts/manual-tests/fase2-worker.mjs # worker: spawn, filas, limite de DMs, órfãos, estresse
|
|
132
|
+
node scripts/manual-tests/fase3-seed-env.mjs # segurança: seed por env, nenhuma credencial exposta
|
|
133
|
+
node scripts/manual-tests/fase4-npx-start.mjs # npx/cwd estranho: versão correta, processo vivo, HTTP 200
|
|
134
|
+
node scripts/manual-tests/startup-keepalive.mjs # runtime: boot, unhandledRejection, EPIPE, sinais
|
|
122
135
|
node --test tests/*.js # contratos/concorrência/UI (stubs por enquanto)
|
|
123
136
|
```
|
|
124
137
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@danhachuel/jobfinder",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.15",
|
|
4
4
|
"description": "JobFinder — LinkedIn automation platform (posts, connections/DMs, job matching) with a React + Vite UI. Intelligent workflows, JSON storage.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"linkedin",
|
package/scripts/cli.mjs
CHANGED
|
@@ -200,6 +200,10 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
200
200
|
process.env.JOBFINDER_DATA_DIR = resolved;
|
|
201
201
|
process.env.JOBFINDER_PORT = String(listenPort);
|
|
202
202
|
process.env.JOBFINDER_HOST = listenHost;
|
|
203
|
+
// Version: read from THIS file's package.json (never cwd) and handed to the
|
|
204
|
+
// server via env. Under npx the cwd is the user's directory, so a server
|
|
205
|
+
// that read its own version from cwd would print 0.0.00.
|
|
206
|
+
process.env.JOBFINDER_VERSION = VISUAL_VERSION;
|
|
203
207
|
if (dryRun) process.env.JOBFINDER_DRY_RUN = '1';
|
|
204
208
|
|
|
205
209
|
// Supervisão do worker. O CLI NUNCA depende do worker para viver: ele
|
|
@@ -243,10 +247,25 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
243
247
|
};
|
|
244
248
|
|
|
245
249
|
// Keep-alive inquebrável: timer de 24h SEM unref. Segurança extra — o
|
|
246
|
-
// socket do servidor (abaixo) já é a garantia principal.
|
|
247
|
-
|
|
250
|
+
// socket do servidor (abaixo) já é a garantia principal. Nunca use unref()
|
|
251
|
+
// aqui: um timer solto é o que permite o loop esvaziar e o processo sumir.
|
|
252
|
+
const keepAliveTimer = setInterval(() => {}, 24 * 60 * 60 * 1000);
|
|
248
253
|
|
|
249
|
-
// Forensic trail: se o launcher morrer, o motivo fica visível.
|
|
254
|
+
// Forensic trail: se o launcher morrer, o motivo fica visível. `beforeExit`
|
|
255
|
+
// avisa ANTES de o loop esvaziar (com os handles ativos) e permite re-armar
|
|
256
|
+
// o keep-alive; `exit` registra o código final.
|
|
257
|
+
process.on('beforeExit', (code) => {
|
|
258
|
+
const handles = process.getActiveResourcesInfo?.() ?? [];
|
|
259
|
+
console.error(
|
|
260
|
+
`[jobfinder] launcher: event loop esvaziando (beforeExit code=${code}) — ` +
|
|
261
|
+
`handles: ${handles.join(', ') || 'NENHUM'}`
|
|
262
|
+
);
|
|
263
|
+
if (!stopping) {
|
|
264
|
+
console.error('[jobfinder] launcher: re-armando o keep-alive para nao voltar ao prompt.');
|
|
265
|
+
clearInterval(keepAliveTimer);
|
|
266
|
+
setInterval(() => {}, 24 * 60 * 60 * 1000);
|
|
267
|
+
}
|
|
268
|
+
});
|
|
250
269
|
process.on('exit', (code) => {
|
|
251
270
|
console.error(`[jobfinder] launcher exiting with code ${code}.`);
|
|
252
271
|
});
|
|
@@ -77,8 +77,19 @@ try {
|
|
|
77
77
|
check('tela de login é exibida', loginVisible);
|
|
78
78
|
const brandVisible = await page.locator('h1', { hasText: 'JobFinder' }).isVisible();
|
|
79
79
|
check('painel de marca JobFinder presente', brandVisible);
|
|
80
|
-
|
|
81
|
-
|
|
80
|
+
// REGRESSÃO DE SEGURANÇA (0.1.14): nenhuma credencial pode aparecer na
|
|
81
|
+
// tela de login. A ausência do cartão é obrigatória, não opcional.
|
|
82
|
+
const bodyText = (await page.locator('body').innerText()).toLowerCase();
|
|
83
|
+
check('tela de login NÃO exibe e-mail do usuário semeado', !bodyText.includes('dan.hachuel'));
|
|
84
|
+
check('tela de login NÃO exibe senha padrão', !bodyText.includes('123456'));
|
|
85
|
+
check('tela de login NÃO exibe o cartão de credenciais', !bodyText.includes('usuário pré-criado'));
|
|
86
|
+
// Nenhum elemento <code> (onde o cartão exibia e-mail/senha) pode conter credencial.
|
|
87
|
+
const codes = await page.locator('code').evaluateAll((nodes) => nodes.map((n) => n.textContent || ''));
|
|
88
|
+
check('nenhum bloco <code> contém e-mail ou senha', !codes.some((c) => /@|123456/.test(c)), codes.join(','));
|
|
89
|
+
const onboardingNote = await page.locator('text=JOBFINDER_INITIAL_PASSWORD').count();
|
|
90
|
+
check('nota de onboarding (sem senha) está presente', onboardingNote > 0);
|
|
91
|
+
const inputs = await page.locator('input').evaluateAll((nodes) => nodes.map((n) => n.placeholder || ''));
|
|
92
|
+
check('nenhum placeholder contém credencial', !inputs.some((p) => /dan\.hachuel|123456/.test(p)), inputs.filter(Boolean).join(','));
|
|
82
93
|
|
|
83
94
|
console.log('\n== Credenciais inválidas ==');
|
|
84
95
|
await page.fill('#email', 'dan.hachuel@gmail.com');
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Onboarding do primeiro acesso por variável de ambiente (0.1.14).
|
|
3
|
+
*
|
|
4
|
+
* Prova o comportamento real do seed:
|
|
5
|
+
* 1. com JOBFINDER_INITIAL_EMAIL/PASSWORD definidos, o login usa ESSAS credenciais
|
|
6
|
+
* 2. as credenciais do seed embutido NÃO funcionam mais (override real)
|
|
7
|
+
* 3. nenhuma rota/devolve credencial (a rota /auth/defaults deixou de existir)
|
|
8
|
+
* 4. auth.json guarda apenas o hash — nunca a senha em texto puro
|
|
9
|
+
*
|
|
10
|
+
* Uso: node scripts/manual-tests/fase3-seed-env.mjs
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import process from 'node:process';
|
|
17
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
18
|
+
|
|
19
|
+
const PORT = 4155;
|
|
20
|
+
const HOME = path.join(os.tmpdir(), `jobfinder-fase3-${Date.now()}`);
|
|
21
|
+
const APP = `http://127.0.0.1:${PORT}`;
|
|
22
|
+
const ENV_EMAIL = 'operador@empresa.com';
|
|
23
|
+
const ENV_PASSWORD = 'senha-inicial-forte';
|
|
24
|
+
|
|
25
|
+
let passed = 0;
|
|
26
|
+
let failed = 0;
|
|
27
|
+
|
|
28
|
+
function check(name, condition, extra = '') {
|
|
29
|
+
if (condition) {
|
|
30
|
+
passed += 1;
|
|
31
|
+
console.log(` OK ${name}${extra ? ` — ${extra}` : ''}`);
|
|
32
|
+
} else {
|
|
33
|
+
failed += 1;
|
|
34
|
+
console.log(` FAIL ${name}${extra ? ` — ${extra}` : ''}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function api(method, endpoint, body, cookie = '') {
|
|
39
|
+
const headers = {};
|
|
40
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
41
|
+
if (cookie) headers.Cookie = cookie;
|
|
42
|
+
const res = await fetch(`${APP}/api${endpoint}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
43
|
+
return { status: res.status, json: await res.json().catch(() => null) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function waitUp(attempts = 60) {
|
|
47
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
48
|
+
try {
|
|
49
|
+
if ((await fetch(`${APP}/api/health`)).ok) return true;
|
|
50
|
+
} catch {
|
|
51
|
+
/* not up yet */
|
|
52
|
+
}
|
|
53
|
+
await delay(500);
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const server = spawn(process.execPath, ['src/server/index.mjs'], {
|
|
59
|
+
cwd: process.cwd(),
|
|
60
|
+
env: {
|
|
61
|
+
...process.env,
|
|
62
|
+
JOBFINDER_HOME: HOME,
|
|
63
|
+
JOBFINDER_PORT: String(PORT),
|
|
64
|
+
JOBFINDER_INITIAL_EMAIL: ENV_EMAIL,
|
|
65
|
+
JOBFINDER_INITIAL_PASSWORD: ENV_PASSWORD,
|
|
66
|
+
},
|
|
67
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
68
|
+
});
|
|
69
|
+
let serverOut = '';
|
|
70
|
+
server.stdout.on('data', (d) => { serverOut += String(d); });
|
|
71
|
+
server.stderr.on('data', (d) => { serverOut += String(d); });
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
console.log('\n== Seed por variável de ambiente ==');
|
|
75
|
+
check('servidor subiu', await waitUp());
|
|
76
|
+
|
|
77
|
+
await delay(500);
|
|
78
|
+
const authFile = JSON.parse(fs.readFileSync(path.join(HOME, 'auth.json'), 'utf8'));
|
|
79
|
+
check('auth.json foi criado com o e-mail do ambiente', authFile.user.email === ENV_EMAIL, authFile.user.email);
|
|
80
|
+
check('auth.json NÃO contém a senha em texto puro', !JSON.stringify(authFile).includes(ENV_PASSWORD));
|
|
81
|
+
|
|
82
|
+
const loginEnv = await api('POST', '/auth/login', { email: ENV_EMAIL, password: ENV_PASSWORD });
|
|
83
|
+
check('login com as credenciais do ambiente funciona', loginEnv.status === 200, `status ${loginEnv.status}`);
|
|
84
|
+
|
|
85
|
+
// Re-login capturing the session cookie for the authenticated calls below.
|
|
86
|
+
const cookieRes = await fetch(`${APP}/api/auth/login`, {
|
|
87
|
+
method: 'POST',
|
|
88
|
+
headers: { 'Content-Type': 'application/json' },
|
|
89
|
+
body: JSON.stringify({ email: ENV_EMAIL, password: ENV_PASSWORD }),
|
|
90
|
+
});
|
|
91
|
+
const cookie = cookieRes.headers.get('set-cookie')?.split(';')[0] ?? '';
|
|
92
|
+
|
|
93
|
+
const loginSeed = await api('POST', '/auth/login', { email: 'dan.hachuel@gmail.com', password: '123456' });
|
|
94
|
+
check('credenciais do seed embutido NÃO funcionam mais', loginSeed.status === 401, `status ${loginSeed.status}`);
|
|
95
|
+
|
|
96
|
+
console.log('\n== Nenhuma rota expõe credenciais ==');
|
|
97
|
+
const defaults = await api('GET', '/auth/defaults');
|
|
98
|
+
// A rota foi removida: sem sessão ela cai no guard (401) em vez de responder.
|
|
99
|
+
check('GET /api/auth/defaults não expõe mais credenciais', defaults.status === 401 || defaults.status === 404, `status ${defaults.status}`);
|
|
100
|
+
|
|
101
|
+
const healthNoAuth = await api('GET', '/health');
|
|
102
|
+
const healthRaw = JSON.stringify(healthNoAuth.json ?? {});
|
|
103
|
+
check('resposta do /health não traz e-mail nem senha', !healthRaw.includes(ENV_EMAIL) && !healthRaw.includes(ENV_PASSWORD));
|
|
104
|
+
|
|
105
|
+
const session = await fetch(`${APP}/api/auth/session`, { headers: { Cookie: cookie } }).then((r) => r.json());
|
|
106
|
+
const sessionRaw = JSON.stringify(session);
|
|
107
|
+
check('resposta do /auth/session não traz senha', !sessionRaw.includes(ENV_PASSWORD));
|
|
108
|
+
|
|
109
|
+
console.log('\n== Terminal não expõe credenciais ==');
|
|
110
|
+
check('stdout/stderr do servidor sem e-mail do ambiente', !serverOut.includes(ENV_EMAIL), serverOut.split('\n').filter((l) => l.includes(ENV_EMAIL)).slice(0, 1).join(''));
|
|
111
|
+
check('stdout/stderr do servidor sem a senha', !serverOut.includes(ENV_PASSWORD));
|
|
112
|
+
|
|
113
|
+
console.log('\n== Troca de senha segue funcionando ==');
|
|
114
|
+
const changed = await api('PUT', '/auth/password', {
|
|
115
|
+
currentPassword: ENV_PASSWORD,
|
|
116
|
+
newPassword: 'nova-senha-2026',
|
|
117
|
+
confirmPassword: 'nova-senha-2026',
|
|
118
|
+
}, cookie);
|
|
119
|
+
check('troca de senha com a senha do ambiente', changed.status === 200, `status ${changed.status}`);
|
|
120
|
+
const loginNew = await api('POST', '/auth/login', { email: ENV_EMAIL, password: 'nova-senha-2026' });
|
|
121
|
+
check('nova senha funciona no login seguinte', loginNew.status === 200);
|
|
122
|
+
} catch (err) {
|
|
123
|
+
failed += 1;
|
|
124
|
+
console.log(` FAIL exceção: ${err.message}`);
|
|
125
|
+
} finally {
|
|
126
|
+
server.kill();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
|
|
130
|
+
process.exit(failed ? 1 : 0);
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reprodução do cenário real: `npx @danhachuel/jobfinder@<versão>` rodando a
|
|
3
|
+
* partir de um diretório ESTRANHO (fora do repo), como o usuário faz no
|
|
4
|
+
* MobaXterm / PowerShell.
|
|
5
|
+
*
|
|
6
|
+
* Verifica:
|
|
7
|
+
* 1. a versão impressa é a correta (não 0.0.00)
|
|
8
|
+
* 2. o processo continua vivo depois do banner (event loop retido)
|
|
9
|
+
* 3. o servidor responde HTTP 200
|
|
10
|
+
* 4. o terminal não volta ao prompt sozinho
|
|
11
|
+
*
|
|
12
|
+
* Uso: node scripts/manual-tests/fase4-npx-start.mjs [versao]
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import process from 'node:process';
|
|
19
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
20
|
+
|
|
21
|
+
const VERSION = process.argv[2] ?? '0.1.14';
|
|
22
|
+
const PORT = 4366;
|
|
23
|
+
const HOME = path.join(os.tmpdir(), `jobfinder-npx-${Date.now()}`);
|
|
24
|
+
// Diretório "estranho": fora do repositório, como a home do MobaXterm.
|
|
25
|
+
const FOREIGN_CWD = path.join(os.tmpdir(), `mobaXterm-home-${Date.now()}`);
|
|
26
|
+
fs.mkdirSync(FOREIGN_CWD, { recursive: true });
|
|
27
|
+
|
|
28
|
+
let passed = 0;
|
|
29
|
+
let failed = 0;
|
|
30
|
+
function check(name, condition, extra = '') {
|
|
31
|
+
if (condition) {
|
|
32
|
+
passed += 1;
|
|
33
|
+
console.log(` OK ${name}${extra ? ` — ${extra}` : ''}`);
|
|
34
|
+
} else {
|
|
35
|
+
failed += 1;
|
|
36
|
+
console.log(` FAIL ${name}${extra ? ` — ${extra}` : ''}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
console.log(`\n== JobFinder (build local) em ${FOREIGN_CWD} ==`);
|
|
41
|
+
console.log('(equivalente ao `npx @danhachuel/jobfinder@<versao>`: mesmo cwd estranho, mesmo binário)');
|
|
42
|
+
|
|
43
|
+
// Roda o CLI LOCAL a partir de um diretório estranho — reproduz o ambiente do
|
|
44
|
+
// npx (cwd != raiz do pacote) sem depender de publicação prévia.
|
|
45
|
+
const REPO_ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.slice(1)), '..', '..');
|
|
46
|
+
const cli = spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), 'start', '--port', String(PORT)], {
|
|
47
|
+
cwd: FOREIGN_CWD,
|
|
48
|
+
env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
|
|
49
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
50
|
+
});
|
|
51
|
+
const npx = cli;
|
|
52
|
+
|
|
53
|
+
let out = '';
|
|
54
|
+
let err = '';
|
|
55
|
+
npx.stdout.on('data', (d) => { out += String(d); });
|
|
56
|
+
npx.stderr.on('data', (d) => { err += String(d); });
|
|
57
|
+
|
|
58
|
+
const alive = async () => new Promise((resolve) => {
|
|
59
|
+
if (npx.exitCode !== null || npx.signalCode !== null) return resolve(false);
|
|
60
|
+
npx.kill(0);
|
|
61
|
+
resolve(true);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// 1. espera o servidor subir
|
|
65
|
+
let httpOk = false;
|
|
66
|
+
for (let i = 0; i < 60; i += 1) {
|
|
67
|
+
try {
|
|
68
|
+
if ((await fetch(`http://127.0.0.1:${PORT}/api/health`)).ok) { httpOk = true; break; }
|
|
69
|
+
} catch { /* ainda subindo */ }
|
|
70
|
+
await delay(1000);
|
|
71
|
+
}
|
|
72
|
+
check('servidor respondeu HTTP na porta', httpOk);
|
|
73
|
+
|
|
74
|
+
// 2. versão correta no output (a linha do servidor, não só o banner do CLI)
|
|
75
|
+
const serverLine = out.split('\n').find((l) => l.includes('listening on')) ?? '';
|
|
76
|
+
const versionLine = out.split('\n').find((l) => /^JobFinder\s+v?\d/.test(l.trim())) ?? '';
|
|
77
|
+
check('versão correta (não 0.0.00)', /v0\.1\.\d+/.test(versionLine) && !versionLine.includes('0.0.00'), versionLine.trim());
|
|
78
|
+
check('linha do listen traz a versão correta', /0\.1\.\d+/.test(serverLine) && !serverLine.includes('0.0.00'), serverLine.trim());
|
|
79
|
+
|
|
80
|
+
// 3. o processo PRECISA continuar vivo (não voltar ao prompt)
|
|
81
|
+
await delay(8000);
|
|
82
|
+
const stillAlive = await alive();
|
|
83
|
+
check('processo npx continua vivo após 8s do listen', stillAlive, `exitCode=${npx.exitCode} signal=${npx.signalCode}`);
|
|
84
|
+
|
|
85
|
+
// 4. HTTP continua respondendo depois (prova que não morreu)
|
|
86
|
+
const httpAfter = await fetch(`http://127.0.0.1:${PORT}/api/health`).then((r) => r.ok).catch(() => false);
|
|
87
|
+
check('HTTP 200 depois da espera', httpAfter);
|
|
88
|
+
|
|
89
|
+
// 5. rastro forense: se morreu, o motivo tem que estar visível
|
|
90
|
+
if (!stillAlive) {
|
|
91
|
+
console.log('--- stdout ---'); console.log(out);
|
|
92
|
+
console.log('--- stderr ---'); console.log(err);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
check('nenhum "launcher exiting" prematuro no log', !err.includes('launcher exiting') && !out.includes('launcher exiting'), err.split('\n').filter((l) => l.includes('launcher exiting')).slice(0, 1).join(''));
|
|
96
|
+
|
|
97
|
+
try { npx.kill('SIGTERM'); } catch { /* já morreu */ }
|
|
98
|
+
await delay(500);
|
|
99
|
+
try { npx.kill('SIGKILL'); } catch { /* já morreu */ }
|
|
100
|
+
|
|
101
|
+
// ------------------------------------------------------------------ *
|
|
102
|
+
// Caminho 2: `node src/server/index.mjs` DIRETO, de um cwd estranho e SEM
|
|
103
|
+
// JOBFINDER_VERSION — valida o createRequire(import.meta.url) puro.
|
|
104
|
+
// ------------------------------------------------------------------ *
|
|
105
|
+
console.log('\n== node src/server/index.mjs direto (sem JOBFINDER_VERSION) ==');
|
|
106
|
+
const direct = spawn(process.execPath, [path.join(REPO_ROOT, 'src', 'server', 'index.mjs')], {
|
|
107
|
+
cwd: FOREIGN_CWD,
|
|
108
|
+
env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT + 1), JOBFINDER_NO_WORKER: '1' },
|
|
109
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
110
|
+
});
|
|
111
|
+
let directOut = '';
|
|
112
|
+
direct.stdout.on('data', (d) => { directOut += String(d); });
|
|
113
|
+
direct.stderr.on('data', (d) => { directOut += String(d); });
|
|
114
|
+
let directHttp = false;
|
|
115
|
+
for (let i = 0; i < 40; i += 1) {
|
|
116
|
+
try {
|
|
117
|
+
if ((await fetch(`http://127.0.0.1:${PORT + 1}/api/health`)).ok) { directHttp = true; break; }
|
|
118
|
+
} catch { /* subindo */ }
|
|
119
|
+
await delay(500);
|
|
120
|
+
}
|
|
121
|
+
check('servidor direto respondeu HTTP', directHttp);
|
|
122
|
+
const directLine = directOut.split('\n').find((l) => l.includes('listening on')) ?? '';
|
|
123
|
+
check('versão correta sem env override (createRequire)', /0\.1\.\d+/.test(directLine) && !directLine.includes('0.0.00'), directLine.trim());
|
|
124
|
+
await delay(3000);
|
|
125
|
+
check('servidor direto continua vivo', direct.exitCode === null && direct.signalCode === null, `exitCode=${direct.exitCode}`);
|
|
126
|
+
try { direct.kill('SIGTERM'); } catch { /* já morreu */ }
|
|
127
|
+
await delay(500);
|
|
128
|
+
try { direct.kill('SIGKILL'); } catch { /* já morreu */ }
|
|
129
|
+
|
|
130
|
+
// ------------------------------------------------------------------ *
|
|
131
|
+
// Caminho 3: caminho padrão COMPLETO, com o worker ativo (como o usuário
|
|
132
|
+
// really roda) — o worker não pode derrubar o launcher.
|
|
133
|
+
// ------------------------------------------------------------------ *
|
|
134
|
+
console.log('\n== caminho padrão com worker ativo ==');
|
|
135
|
+
const full = spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), 'start', '--port', String(PORT + 2)], {
|
|
136
|
+
cwd: FOREIGN_CWD,
|
|
137
|
+
env: { ...process.env, JOBFINDER_HOME: HOME },
|
|
138
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
139
|
+
});
|
|
140
|
+
let fullOut = '';
|
|
141
|
+
full.stdout.on('data', (d) => { fullOut += String(d); });
|
|
142
|
+
full.stderr.on('data', (d) => { fullOut += String(d); });
|
|
143
|
+
let fullHttp = false;
|
|
144
|
+
for (let i = 0; i < 40; i += 1) {
|
|
145
|
+
try {
|
|
146
|
+
if ((await fetch(`http://127.0.0.1:${PORT + 2}/api/health`)).ok) { fullHttp = true; break; }
|
|
147
|
+
} catch { /* subindo */ }
|
|
148
|
+
await delay(500);
|
|
149
|
+
}
|
|
150
|
+
check('app completo (com worker) respondeu HTTP', fullHttp);
|
|
151
|
+
await delay(6000);
|
|
152
|
+
check('app completo continua vivo', full.exitCode === null && full.signalCode === null, `exitCode=${full.exitCode} signal=${full.signalCode}`);
|
|
153
|
+
const workerPids = fullOut.split('\n').filter((l) => l.includes('Worker')).slice(0, 1).join('');
|
|
154
|
+
check('worker foi anunciado', /Worker\s+:/.test(fullOut), workerPids.trim());
|
|
155
|
+
try { full.kill('SIGTERM'); } catch { /* já morreu */ }
|
|
156
|
+
await delay(3000);
|
|
157
|
+
try { full.kill('SIGKILL'); } catch { /* já morreu */ }
|
|
158
|
+
|
|
159
|
+
console.log('\n--- saída capturada ---');
|
|
160
|
+
console.log(out.split('\n').filter(Boolean).slice(0, 20).join('\n'));
|
|
161
|
+
if (err.trim()) { console.log('--- stderr ---'); console.log(err.split('\n').filter(Boolean).slice(0, 10).join('\n')); }
|
|
162
|
+
|
|
163
|
+
console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
|
|
164
|
+
process.exit(failed ? 1 : 0);
|
package/src/server/index.mjs
CHANGED
|
@@ -13,11 +13,15 @@
|
|
|
13
13
|
import fs from 'node:fs';
|
|
14
14
|
import path from 'node:path';
|
|
15
15
|
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import { createRequire } from 'node:module';
|
|
16
17
|
|
|
17
18
|
import { createApp } from './app.mjs';
|
|
18
19
|
import { createContext } from './context.mjs';
|
|
19
20
|
import { resolveDataDir, UI_DIST } from './paths.mjs';
|
|
20
21
|
|
|
22
|
+
/** ESM-safe package.json reader: resolved from THIS file, never from cwd. */
|
|
23
|
+
const require = createRequire(import.meta.url);
|
|
24
|
+
|
|
21
25
|
/**
|
|
22
26
|
* Logger used by the global process handlers below. Assigned by start():
|
|
23
27
|
* the handlers are registered before the context exists, but they only
|
|
@@ -78,12 +82,27 @@ function installProcessResilience() {
|
|
|
78
82
|
}
|
|
79
83
|
}
|
|
80
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Version source, in order:
|
|
87
|
+
* 1. JOBFINDER_VERSION (set by the launcher, which reads package.json from
|
|
88
|
+
* its own location — always correct)
|
|
89
|
+
* 2. package.json resolved relative to THIS module
|
|
90
|
+
*
|
|
91
|
+
* `process.cwd()` is NEVER used: under `npx` the cwd is the user's directory
|
|
92
|
+
* (MobaXterm home, a random PowerShell path), so a cwd-relative read fails and
|
|
93
|
+
* the server silently reports 0.0.00.
|
|
94
|
+
*/
|
|
81
95
|
function readPkgVersion() {
|
|
96
|
+
const fromEnv = process.env.JOBFINDER_VERSION;
|
|
82
97
|
try {
|
|
83
|
-
const pkg =
|
|
84
|
-
|
|
98
|
+
const pkg = fromEnv ? { version: fromEnv } : require('../../package.json');
|
|
99
|
+
const resolved = pkg.version;
|
|
100
|
+
if (!resolved || resolved === '0.0.00') throw new Error('versao vazia');
|
|
101
|
+
return { visual: resolved, npm: resolved.split('.').map((p) => String(Number(p))).join('.') };
|
|
85
102
|
} catch {
|
|
86
|
-
|
|
103
|
+
const fallback = '0.0.00';
|
|
104
|
+
console.error(`[jobfinder] nao foi possivel ler a versao do package.json (env=${fromEnv ? 'set' : 'unset'}) — usando ${fallback}`);
|
|
105
|
+
return { visual: fallback, npm: '0.0.0' };
|
|
87
106
|
}
|
|
88
107
|
}
|
|
89
108
|
|
|
@@ -155,6 +174,37 @@ export async function start() {
|
|
|
155
174
|
// this process means closing the browser never pauses the automations.
|
|
156
175
|
|
|
157
176
|
let shuttingDown = false;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* ULTIMATE keep-alive guard (0.1.15).
|
|
180
|
+
*
|
|
181
|
+
* The listening socket is the primary guarantee. This is the backstop for
|
|
182
|
+
* the case where something empties the event loop without closing the
|
|
183
|
+
* server: Node fires `beforeExit` right before exiting naturally, and
|
|
184
|
+
* scheduling new work there CANCELS the exit. If that ever happens we now
|
|
185
|
+
* (a) leave a loud forensic trail with the active handles and (b) re-arm a
|
|
186
|
+
* referenced timer so the process cannot vanish silently.
|
|
187
|
+
*/
|
|
188
|
+
const armKeepAlive = () => setInterval(() => {}, 60_000);
|
|
189
|
+
let keepAlive = armKeepAlive();
|
|
190
|
+
process.on('beforeExit', (code) => {
|
|
191
|
+
const handles = process.getActiveResourcesInfo?.() ?? [];
|
|
192
|
+
const socketAlive = handles.some((handle) => /server|tcp|socket|pipe/i.test(handle));
|
|
193
|
+
if (shuttingDown) return;
|
|
194
|
+
console.error(
|
|
195
|
+
`[jobfinder] event loop esvaziando (beforeExit code=${code}) — ` +
|
|
196
|
+
`socket do servidor ativo: ${socketAlive}; handles: ${handles.join(', ') || 'NENHUM'}`
|
|
197
|
+
);
|
|
198
|
+
if (!socketAlive && server.listening) {
|
|
199
|
+
console.error('[jobfinder] re-armando o keep-alive para evitar encerramento prematuro.');
|
|
200
|
+
clearInterval(keepAlive);
|
|
201
|
+
keepAlive = armKeepAlive();
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
process.on('exit', (code) => {
|
|
205
|
+
console.error(`[jobfinder] processo do servidor encerrando (code=${code}).`);
|
|
206
|
+
});
|
|
207
|
+
|
|
158
208
|
const shutdown = (signal) => {
|
|
159
209
|
if (shuttingDown) return;
|
|
160
210
|
shuttingDown = true;
|
|
@@ -5,8 +5,10 @@
|
|
|
5
5
|
* POST /api/auth/logout clears the cookie and revokes the token
|
|
6
6
|
* GET /api/auth/session { authenticated, user }
|
|
7
7
|
* PUT /api/auth/password { currentPassword, newPassword, confirmPassword }
|
|
8
|
-
* GET /api/auth/defaults first-run hint (default e-mail + flag)
|
|
9
8
|
*
|
|
9
|
+
* No route exposes the seeded credentials: the first-run account is created
|
|
10
|
+
* by the bootstrap (optionally overridden by JOBFINDER_INITIAL_EMAIL /
|
|
11
|
+
* JOBFINDER_INITIAL_PASSWORD) and never returned to the browser.
|
|
10
12
|
* Single local user stored in ~/.jobfinder/auth.json (password hashed with
|
|
11
13
|
* scrypt — see storage/authStore.mjs).
|
|
12
14
|
*/
|
|
@@ -16,7 +18,6 @@ import { asyncRoute, badRequest } from '../middleware/errors.mjs';
|
|
|
16
18
|
import { requireSession } from '../middleware/auth.mjs';
|
|
17
19
|
import {
|
|
18
20
|
AuthStore,
|
|
19
|
-
DEFAULT_EMAIL,
|
|
20
21
|
SESSION_TTL_MS,
|
|
21
22
|
extractToken,
|
|
22
23
|
sessionCookieOptions,
|
|
@@ -88,13 +89,6 @@ export function authRoutes({ store, logger }) {
|
|
|
88
89
|
})
|
|
89
90
|
);
|
|
90
91
|
|
|
91
|
-
router.get(
|
|
92
|
-
'/defaults',
|
|
93
|
-
asyncRoute((req, res) => {
|
|
94
|
-
res.json({ email: DEFAULT_EMAIL, firstRun: auth.usingDefaultPassword() });
|
|
95
|
-
})
|
|
96
|
-
);
|
|
97
|
-
|
|
98
92
|
return router;
|
|
99
93
|
}
|
|
100
94
|
|