@danhachuel/jobfinder 0.1.12 → 0.1.14
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 +33 -2
- package/README.md +20 -8
- package/package.json +1 -1
- package/scripts/cli.mjs +59 -83
- package/scripts/manual-tests/fase1-ui-e2e.mjs +13 -2
- package/scripts/manual-tests/fase3-seed-env.mjs +130 -0
- package/scripts/manual-tests/startup-keepalive.mjs +56 -0
- package/src/server/routes/auth.mjs +3 -9
- package/src/server/routes/worker.mjs +3 -2
- package/src/server/storage/authStore.mjs +33 -10
- package/src/server/worker.mjs +27 -8
- package/src/server/workerRuntime.mjs +18 -67
- package/src/ui/dist/assets/index-CFAhWKxD.css +2 -0
- package/src/ui/dist/assets/{index-Jg7CthP-.js → index-DQO-z4ME.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,11 +6,42 @@ 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.14] — 2026-11-20
|
|
10
|
+
|
|
11
|
+
### Security
|
|
12
|
+
|
|
13
|
+
- **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.
|
|
14
|
+
- **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.
|
|
15
|
+
- **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.
|
|
16
|
+
- **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.
|
|
17
|
+
- **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.
|
|
18
|
+
|
|
19
|
+
### Notas
|
|
20
|
+
|
|
21
|
+
- A tela de login ficou apenas com o formulário (e-mail, senha, mostrar/ocultar, entrar) e a nota de onboarding em texto simples.
|
|
22
|
+
- Instalações existentes não são afetadas: um `auth.json` já criado é preservado e as env vars só valem na primeira criação.
|
|
23
|
+
|
|
24
|
+
## [0.1.13] — 2026-11-20
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- **Arquitetura: servidor Express embutido no processo do CLI (fim do `spawn`)**: `scripts/cli.mjs` agora importa `start()` de `src/server/index.mjs` diretamente e roda o `app.listen()` **no próprio processo**. Um socket de servidor escutando na porta mantém o event loop do Node aberto **matematicamente** — nenhum comportamento de terminal hostil (MobaXterm, wrapper do npx, redirecionamento, pipes fechados) pode mais esvaziá-lo. Esta é a correção definitiva para o encerramento prematuro que perseguia o Windows desde a 0.1.7.
|
|
29
|
+
- **Worker desacoplado e silencioso**: o worker continua sendo processo filho (tarefas pesadas não travam a UI), mas agora com `stdio: ['ignore','ignore','ignore']` — ele **grava seus logs em arquivo** (`worker.log` para o ciclo de vida e `worker-error.log` para falhas). Um terminal que engasga ao ler os pipes do worker não tem mais como perturbá-lo. A detecção de órfão por `stdin` EOF e o `JOBFINDER_TAKEOVER` permanecem.
|
|
30
|
+
- **Sinais**: o CLI encerra o worker no primeiro Ctrl+C e o shutdown gracioso do servidor (mesmo processo) assume a partir daí; o segundo sinal força a saída.
|
|
31
|
+
|
|
32
|
+
### Fixed
|
|
33
|
+
|
|
34
|
+
- **Resiliência inquebrável do launcher**: `keep-alive` de 24 h sem `unref()` no `start`, handlers de `unhandledRejection`/`uncaughtException`/EPIPE no topo e o registro `[jobfinder] launcher exiting with code N` — nenhuma morte futura fica sem explicação.
|
|
35
|
+
|
|
36
|
+
### Tests
|
|
37
|
+
|
|
38
|
+
- **Novo teste de estresse** (`startup-keepalive.mjs`, ambiente hostil): sobe o app pelo CLI, **destrói o `stdout`/`stderr` do launcher** (simulando a queda do MobaXterm) e **mata o worker à força** — o CLI continua vivo, o servidor responde HTTP 200 em todos os pontos e o worker é reiniciado. Suíte completa: 38 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E + 5 unit.
|
|
39
|
+
|
|
9
40
|
## [0.1.12] — 2026-11-18
|
|
10
41
|
|
|
11
42
|
### Security
|
|
12
43
|
|
|
13
|
-
- **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
|
|
44
|
+
- **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:`.
|
|
14
45
|
|
|
15
46
|
### Fixed
|
|
16
47
|
|
|
@@ -116,7 +147,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
116
147
|
|
|
117
148
|
### Added
|
|
118
149
|
|
|
119
|
-
- **Sistema de login local (autenticação single-user)**:
|
|
150
|
+
- **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”.)*
|
|
120
151
|
- **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.
|
|
121
152
|
- **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).
|
|
122
153
|
- **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
|
@@ -46,12 +46,23 @@ npx --yes @danhachuel/jobfinder@0.1.7
|
|
|
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.14
|
|
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.14
|
|
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,9 @@ 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/startup-keepalive.mjs # runtime: boot, unhandledRejection, EPIPE, sinais
|
|
122
134
|
node --test tests/*.js # contratos/concorrência/UI (stubs por enquanto)
|
|
123
135
|
```
|
|
124
136
|
|
|
@@ -130,7 +142,7 @@ session per repository, surgical scope (no unrequested refactors), atomic JSON w
|
|
|
130
142
|
the store, Windows runtime resilience, contract tests that exercise real behavior, and
|
|
131
143
|
predictable React state.
|
|
132
144
|
|
|
133
|
-
Layout: `scripts/cli.mjs` (launcher) · `src/server/` (Express API, JSON store, LinkedIn + LLM services,
|
|
145
|
+
Layout: `scripts/cli.mjs` (launcher — embute o Express via import: o `app.listen()` roda no próprio processo) · `src/server/` (Express API, JSON store, LinkedIn + LLM services, worker autônomo) · `src/ui/` (React + Vite + Tailwind v4) · `.agents/skills/` (regression rules) · `tests/` (contract/concurrency/UI stubs).
|
|
134
146
|
|
|
135
147
|
## Publishing
|
|
136
148
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@danhachuel/jobfinder",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
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
|
@@ -16,7 +16,6 @@
|
|
|
16
16
|
* --open / --no-open open/do not open the browser on start
|
|
17
17
|
* --dry-run start with automation in dry-run mode (nothing is really sent)
|
|
18
18
|
*/
|
|
19
|
-
import { spawn } from 'node:child_process';
|
|
20
19
|
import fs from 'node:fs';
|
|
21
20
|
import path from 'node:path';
|
|
22
21
|
import os from 'node:os';
|
|
@@ -24,7 +23,7 @@ import process from 'node:process';
|
|
|
24
23
|
import { fileURLToPath } from 'node:url';
|
|
25
24
|
|
|
26
25
|
import { ensureDataDir, resolveDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
|
|
27
|
-
import { spawnWorker
|
|
26
|
+
import { spawnWorker } from '../src/server/workerRuntime.mjs';
|
|
28
27
|
|
|
29
28
|
/**
|
|
30
29
|
* Process resilience for the launcher — installed before anything else runs
|
|
@@ -32,8 +31,8 @@ import { spawnWorker, spawnSupervised, forwardChildOutput } from '../src/server/
|
|
|
32
31
|
* explanation):
|
|
33
32
|
*
|
|
34
33
|
* 1. unhandledRejection — since Node 15 any unhandled promise rejection
|
|
35
|
-
* terminates the process immediately. Log it
|
|
36
|
-
*
|
|
34
|
+
* terminates the process immediately. Log it instead of dying without
|
|
35
|
+
* a trace.
|
|
37
36
|
* 2. EPIPE on stdio — when the shell behind stdout disappears (Windows
|
|
38
37
|
* terminals, MobaXterm, redirection), the next console.log throws an
|
|
39
38
|
* unhandled 'error' and kills the launcher.
|
|
@@ -56,7 +55,6 @@ for (const stream of [process.stdout, process.stderr]) {
|
|
|
56
55
|
|
|
57
56
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
58
57
|
const ROOT = path.resolve(__dirname, '..');
|
|
59
|
-
const SERVER_ENTRY = path.join(ROOT, 'src', 'server', 'index.mjs');
|
|
60
58
|
const UI_DIST = path.join(ROOT, 'src', 'ui', 'dist');
|
|
61
59
|
|
|
62
60
|
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
|
@@ -173,10 +171,6 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
173
171
|
const resolved = resolveDataDir(dataDir);
|
|
174
172
|
ensureDataDir(resolved);
|
|
175
173
|
|
|
176
|
-
if (!fs.existsSync(SERVER_ENTRY)) {
|
|
177
|
-
console.error(`[jobfinder] server entry not found at ${SERVER_ENTRY}`);
|
|
178
|
-
process.exit(1);
|
|
179
|
-
}
|
|
180
174
|
if (!fs.existsSync(path.join(UI_DIST, 'index.html'))) {
|
|
181
175
|
console.warn(
|
|
182
176
|
'[jobfinder] UI build not found (src/ui/dist). The API will run, but the UI will be blank.\n' +
|
|
@@ -184,14 +178,6 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
184
178
|
);
|
|
185
179
|
}
|
|
186
180
|
|
|
187
|
-
const env = {
|
|
188
|
-
...process.env,
|
|
189
|
-
JOBFINDER_DATA_DIR: resolved,
|
|
190
|
-
JOBFINDER_DRY_RUN: dryRun ? '1' : process.env.JOBFINDER_DRY_RUN || '',
|
|
191
|
-
};
|
|
192
|
-
if (port) env.JOBFINDER_PORT = String(port);
|
|
193
|
-
if (host) env.JOBFINDER_HOST = host;
|
|
194
|
-
|
|
195
181
|
printBanner();
|
|
196
182
|
const listenPort = port || Number(process.env.JOBFINDER_PORT) || 4040;
|
|
197
183
|
const listenHost = host || process.env.JOBFINDER_HOST || '127.0.0.1';
|
|
@@ -201,43 +187,53 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
201
187
|
console.log(` URL : ${url}`);
|
|
202
188
|
console.log(' Press Ctrl+C to stop.\n');
|
|
203
189
|
|
|
204
|
-
//
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
|
|
208
|
-
|
|
190
|
+
// ------------------------------------------------------------------ *
|
|
191
|
+
// ARCHITECTURE (0.1.13): the Express server runs INSIDE this process.
|
|
192
|
+
//
|
|
193
|
+
// `start()` imports src/server/index.mjs in-process and app.listen()
|
|
194
|
+
// opens a real TCP socket on 4040. A listening server socket keeps the
|
|
195
|
+
// Node event loop open MATHEMATICALLY — nothing about the terminal
|
|
196
|
+
// (MobaXterm, the npx wrapper, output redirection, closed pipes) can
|
|
197
|
+
// empty the loop and take the process down anymore. The worker stays a
|
|
198
|
+
// separate child so its heavy tasks never block the server.
|
|
199
|
+
// ------------------------------------------------------------------ *
|
|
200
|
+
process.env.JOBFINDER_DATA_DIR = resolved;
|
|
201
|
+
process.env.JOBFINDER_PORT = String(listenPort);
|
|
202
|
+
process.env.JOBFINDER_HOST = listenHost;
|
|
203
|
+
if (dryRun) process.env.JOBFINDER_DRY_RUN = '1';
|
|
209
204
|
|
|
210
|
-
//
|
|
211
|
-
//
|
|
212
|
-
//
|
|
213
|
-
// 'inherit'). Disable with JOBFINDER_NO_WORKER=1.
|
|
205
|
+
// Supervisão do worker. O CLI NUNCA depende do worker para viver: ele
|
|
206
|
+
// roda com stdio ['ignore','ignore','ignore'] (logs em arquivo) e, se
|
|
207
|
+
// morrer, o launcher apenas registra e reinicia — o servidor segue.
|
|
214
208
|
let worker = null;
|
|
215
209
|
let workerRestarts = 0;
|
|
216
210
|
let stopping = false;
|
|
211
|
+
let serverRef = null;
|
|
212
|
+
|
|
213
|
+
const stopChildren = () => {
|
|
214
|
+
if (worker && worker.exitCode === null && worker.signalCode === null) {
|
|
215
|
+
worker.kill('SIGTERM');
|
|
216
|
+
// Hard deadline: a worker that ignores SIGTERM must not linger.
|
|
217
|
+
setTimeout(() => {
|
|
218
|
+
if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
|
|
219
|
+
}, 2000).unref();
|
|
220
|
+
}
|
|
221
|
+
};
|
|
217
222
|
|
|
218
|
-
/**
|
|
219
|
-
* Supervise the worker.
|
|
220
|
-
*
|
|
221
|
-
* THE LAUNCHER NEVER DIES BECAUSE OF THE WORKER. An exit here only logs
|
|
222
|
-
* (the server keeps serving) and, while the server is still up, starts a
|
|
223
|
-
* fresh worker so the automation queues never stop silently. process.exit
|
|
224
|
-
* is NEVER called on this path.
|
|
225
|
-
*/
|
|
226
223
|
const startWorker = () => {
|
|
227
|
-
// JOBFINDER_TAKEOVER:
|
|
228
|
-
//
|
|
229
|
-
//
|
|
224
|
+
// JOBFINDER_TAKEOVER: o launcher acabou de subir (o supervisor anterior
|
|
225
|
+
// já se foi) ou observou a saída do worker — heartbeat velha não pode
|
|
226
|
+
// bloquear este spawn.
|
|
230
227
|
worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved, JOBFINDER_TAKEOVER: '1' } });
|
|
231
|
-
forwardChildOutput(worker, '[worker]');
|
|
232
228
|
worker.on('exit', (code, signal) => {
|
|
233
229
|
const reason = signal ? `signal ${signal}` : `code ${code}`;
|
|
234
230
|
console.error(`\n[jobfinder] worker encerrou (${reason}). O servidor web continua rodando.`);
|
|
235
|
-
const serverAlive =
|
|
231
|
+
const serverAlive = Boolean(serverRef?.listening);
|
|
236
232
|
if (!stopping && serverAlive && workerRestarts < 5) {
|
|
237
233
|
workerRestarts += 1;
|
|
238
234
|
console.error(`[jobfinder] reiniciando o worker (tentativa ${workerRestarts}/5)...`);
|
|
239
|
-
// Re-check `stopping`:
|
|
240
|
-
//
|
|
235
|
+
// Re-check `stopping`: um shutdown que começa enquanto este timer
|
|
236
|
+
// está pendente nunca pode deixar um órfão para trás.
|
|
241
237
|
setTimeout(() => {
|
|
242
238
|
if (!stopping) startWorker();
|
|
243
239
|
}, 3000);
|
|
@@ -246,52 +242,23 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
246
242
|
return worker;
|
|
247
243
|
};
|
|
248
244
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
252
|
-
startWorker();
|
|
253
|
-
console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
|
|
254
|
-
}
|
|
245
|
+
// Keep-alive inquebrável: timer de 24h SEM unref. Segurança extra — o
|
|
246
|
+
// socket do servidor (abaixo) já é a garantia principal.
|
|
247
|
+
setInterval(() => {}, 24 * 60 * 60 * 1000);
|
|
255
248
|
|
|
256
|
-
//
|
|
257
|
-
// the server runs: the CLI stays in the foreground and the terminal only
|
|
258
|
-
// returns to the prompt when the server itself exits (or on Ctrl+C).
|
|
259
|
-
//
|
|
260
|
-
// Independent keep-alive: the launcher must NEVER depend on a child handle
|
|
261
|
-
// to stay alive (regression 0.1.7 — an empty event loop makes Node exit
|
|
262
|
-
// with code 0, silently, right after the startup banner). This referenced
|
|
263
|
-
// timer holds the loop open by itself; explicit process.exit() calls in
|
|
264
|
-
// the signal/exit handlers below still terminate immediately.
|
|
265
|
-
const keepAlive = setInterval(() => {}, 60_000);
|
|
266
|
-
void keepAlive;
|
|
267
|
-
|
|
268
|
-
// Forensic trail: if the launcher ever dies, the reason is visible.
|
|
249
|
+
// Forensic trail: se o launcher morrer, o motivo fica visível.
|
|
269
250
|
process.on('exit', (code) => {
|
|
270
251
|
console.error(`[jobfinder] launcher exiting with code ${code}.`);
|
|
271
252
|
});
|
|
272
253
|
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
worker.kill('SIGTERM');
|
|
276
|
-
// Hard deadline: a worker that ignores SIGTERM must not linger.
|
|
277
|
-
setTimeout(() => {
|
|
278
|
-
if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
|
|
279
|
-
}, 2000).unref();
|
|
280
|
-
}
|
|
281
|
-
};
|
|
254
|
+
// Sinais: o primeiro encerra o worker e deixa o shutdown gracioso do
|
|
255
|
+
// servidor (registrado dentro de start(), abaixo) rodar; o segundo força.
|
|
282
256
|
const forward = (signal) => () => {
|
|
283
|
-
// A second Ctrl+C must never be ignored: force the exit if the graceful
|
|
284
|
-
// path is stuck.
|
|
285
257
|
if (stopping) {
|
|
286
258
|
process.exit(1);
|
|
287
259
|
}
|
|
288
260
|
stopping = true;
|
|
289
261
|
stopChildren();
|
|
290
|
-
if (child.exitCode !== null || child.signalCode !== null) {
|
|
291
|
-
process.exit(child.exitCode ?? (child.signalCode ? 1 : 0));
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
|
-
child.kill(signal);
|
|
295
262
|
};
|
|
296
263
|
process.on('SIGINT', forward('SIGINT'));
|
|
297
264
|
process.on('SIGTERM', forward('SIGTERM'));
|
|
@@ -302,14 +269,23 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
302
269
|
// Opening a browser window on the user's machine without being asked
|
|
303
270
|
// is not acceptable for a hosted (SaaS) product.
|
|
304
271
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
const
|
|
309
|
-
|
|
272
|
+
// Sobe o servidor Express NO PRÓPRIO PROCESSO (dinâmico: mantém --help,
|
|
273
|
+
// --version e install leves, sem carregar o Express).
|
|
274
|
+
try {
|
|
275
|
+
const { start } = await import('../src/server/index.mjs');
|
|
276
|
+
({ server: serverRef } = await start());
|
|
277
|
+
} catch (err) {
|
|
278
|
+
console.error('[jobfinder] falha ao iniciar o servidor:', err?.message ?? err);
|
|
310
279
|
stopChildren();
|
|
311
|
-
process.exit(
|
|
312
|
-
}
|
|
280
|
+
process.exit(1);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (process.env.JOBFINDER_NO_WORKER === '1') {
|
|
284
|
+
console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
|
|
285
|
+
} else {
|
|
286
|
+
startWorker();
|
|
287
|
+
console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
|
|
288
|
+
}
|
|
313
289
|
}
|
|
314
290
|
|
|
315
291
|
function commandVersion() {
|
|
@@ -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);
|
|
@@ -15,6 +15,10 @@
|
|
|
15
15
|
* 6. worker direto: rejection injetada -> worker-error.log em disco e o
|
|
16
16
|
* processo continua vivo; pipes quebrados (EPIPE) não o derrubam;
|
|
17
17
|
* rename sempre EPERM (arquivo travado no Windows) não o derruba
|
|
18
|
+
* 7. ambiente hostil (arquitetura 0.1.13): servidor Express embutido no
|
|
19
|
+
* processo do CLI, stdout/stderr destruídos (queda do MobaXterm) e
|
|
20
|
+
* worker morto — o socket do app.listen() mantém tudo vivo e o HTTP
|
|
21
|
+
* continua 200, com o worker reiniciado
|
|
18
22
|
*
|
|
19
23
|
* Uso: node scripts/manual-tests/startup-keepalive.mjs
|
|
20
24
|
*/
|
|
@@ -347,5 +351,57 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
347
351
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
348
352
|
}
|
|
349
353
|
|
|
354
|
+
// 10) ARQUITETURA 0.1.13: servidor DENTRO do processo do CLI + ambiente
|
|
355
|
+
// hostil. Destrói o stdout/stderr do launcher (simulando a queda do
|
|
356
|
+
// MobaXterm) e mata o worker à força: o socket do app.listen() mantém
|
|
357
|
+
// o processo vivo e respondendo HTTP 200 — e o worker é reiniciado.
|
|
358
|
+
{
|
|
359
|
+
console.log('\n== ambiente hostil: stdout destruído + worker morto (servidor embutido) ==');
|
|
360
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-hostil-'));
|
|
361
|
+
const home = path.join(tmp, 'data');
|
|
362
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
|
|
363
|
+
cwd: ROOT,
|
|
364
|
+
env: { ...process.env, JOBFINDER_PORT: '4190', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1' },
|
|
365
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
366
|
+
});
|
|
367
|
+
let out = '';
|
|
368
|
+
child.stdout.on('data', (d) => { out += String(d); });
|
|
369
|
+
child.stderr.on('data', (d) => { out += String(d); });
|
|
370
|
+
|
|
371
|
+
const workerPid = async () => {
|
|
372
|
+
try {
|
|
373
|
+
return JSON.parse(fs.readFileSync(path.join(home, 'worker-state.json'), 'utf8')).pid ?? null;
|
|
374
|
+
} catch {
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
await wait(5000);
|
|
380
|
+
const pid0 = await workerPid();
|
|
381
|
+
check('servidor embutido subiu pelo CLI (HTTP 200 antes do caos)', (await getStatus(4190, '/api/health')) === 200, `worker pid=${pid0}`);
|
|
382
|
+
|
|
383
|
+
// Queda do terminal: a ponta de leitura dos pipes do launcher é destruída.
|
|
384
|
+
child.stdout.destroy();
|
|
385
|
+
child.stderr.destroy();
|
|
386
|
+
await wait(1000);
|
|
387
|
+
check('CLI sobrevive à destruição do stdout/stderr', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
388
|
+
check('servidor continua respondendo após o stdout cair', (await getStatus(4190, '/api/health')) === 200);
|
|
389
|
+
|
|
390
|
+
// Morte forçada do worker (Task Manager / kill externo).
|
|
391
|
+
try {
|
|
392
|
+
process.kill(Number(pid0), 'SIGTERM');
|
|
393
|
+
} catch {
|
|
394
|
+
/* processo pode ja ter saido */
|
|
395
|
+
}
|
|
396
|
+
await wait(6000);
|
|
397
|
+
check('CLI sobrevive à morte do worker', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
398
|
+
check('servidor continua respondendo após a morte do worker', (await getStatus(4190, '/api/health')) === 200);
|
|
399
|
+
const pid1 = await workerPid();
|
|
400
|
+
check('worker foi reiniciado pelo launcher', pid1 !== null && pid1 !== pid0, `antes=${pid0} depois=${pid1}`);
|
|
401
|
+
child.kill();
|
|
402
|
+
await wait(800);
|
|
403
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
404
|
+
}
|
|
405
|
+
|
|
350
406
|
console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
|
|
351
407
|
process.exit(failed ? 1 : 0);
|
|
@@ -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
|
|
|
@@ -14,7 +14,7 @@ import { Router } from 'express';
|
|
|
14
14
|
|
|
15
15
|
import { asyncRoute } from '../middleware/errors.mjs';
|
|
16
16
|
import { runWorkerPass } from '../services/workers.mjs';
|
|
17
|
-
import { spawnWorker
|
|
17
|
+
import { spawnWorker } from '../workerRuntime.mjs';
|
|
18
18
|
import {
|
|
19
19
|
readWorkerControl,
|
|
20
20
|
readWorkerState,
|
|
@@ -49,8 +49,9 @@ export function workerRoutes({ store, logger, config, rateLimiter }) {
|
|
|
49
49
|
let spawned = false;
|
|
50
50
|
if (!alive) {
|
|
51
51
|
try {
|
|
52
|
+
// stdio ignore: o worker escreve logs em arquivo (worker.log,
|
|
53
|
+
// worker-error.log), nunca no pipe do servidor.
|
|
52
54
|
const child = spawnWorker({ env: { JOBFINDER_DATA_DIR: store.dataDir } });
|
|
53
|
-
forwardChildOutput(child, '[jobfinder:worker]');
|
|
54
55
|
child.on('exit', (code, signal) => {
|
|
55
56
|
logger.info('worker', 'worker process exited', { reason: signal ? `signal ${signal}` : `code ${code}` });
|
|
56
57
|
});
|