@danhachuel/jobfinder 0.1.3 → 0.1.5

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 CHANGED
@@ -6,6 +6,41 @@ 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.05] — 2026-11-13
10
+
11
+ ### Changed
12
+
13
+ - **Nenhuma abertura automática de navegador**: o launcher (`scripts/cli.mjs`) não abre mais o navegador do sistema ao iniciar. O terminal apenas imprime a URL (`http://127.0.0.1:4040`) e a mensagem `Press Ctrl+C to stop.`, aguardando a ação do usuário — abrir uma janela sem ser pedido não é aceitável para um produto hospedado (SaaS). A função `openBrowser` foi removida, as flags `--open`/`--no-open` viraram no-ops (ainda aceitas por compatibilidade) e a chave `openBrowserOnStart` saiu do config padrão.
14
+ - **Marca reposicionada para SaaS**: removidas todas as menções a "100% local" / "local-first" / "seus dados nunca saem desta máquina" da UI (badge do login, rodapé da sidebar — que fica apenas com o perfil e o botão **Sair** —, rodapé do conteúdo, cartões de Vagas, Candidaturas e Header) e do CLI (subtítulo do banner agora é "LinkedIn Automation • Intelligent Workflows"). A descrição do pacote npm e o README seguem o mesmo reposicionamento.
15
+
16
+ ### Removed
17
+
18
+ - Bloco "100% local" (link para o GitHub) do rodapé da sidebar e badge "100% local" da tela de login; frases de posicionamento exclusivamente local em toda a interface.
19
+
20
+ ## [0.1.04] — 2026-11-12
21
+
22
+ ### Added
23
+
24
+ - **Sistema de login local (autenticação single-user)**: usuário pré-criado `dan.hachuel@gmail.com` / `123456`, com a senha gravada em `~/.jobfinder/auth.json` usando **scrypt** (salt + hash — 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`.
25
+ - **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.
26
+ - **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).
27
+ - **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".
28
+ - **Seção "Execução" nas Configurações**: switch para **desativar o dry-run**, com o aviso *"Ao desativar o modo Dry-run, o JobFinder executará ações reais no LinkedIn (postagens, convites, DMs e candidaturas). Use com responsabilidade."*, modal de confirmação antes de ativar o modo real e persistência imediata da flag em `config.json`.
29
+ - **Seção "Segurança" nas Configurações**: alteração de senha do usuário logado (senha atual, nova senha, confirmação) com validações (mínimo de 6 caracteres, confirmação, senha atual correta) e atualização do hash em `auth.json`.
30
+ - **Rota `/configuracoes`** (alias de `/config`, que continua funcionando) com o item da sidebar apontando para o novo endereço.
31
+ - **Badge "Real Mode"** (vermelho) no topo quando o dry-run está desativado, ao lado do badge âmbar `dry-run` quando está ativo; o avatar do header mostra as iniciais da conta logada.
32
+
33
+ ### Changed
34
+
35
+ - **Flag `dryRun` aplicada de verdade no backend**: novo `src/server/storage/configSync.mjs` mantém o objeto de configuração vivo sincronizado após `PUT /api/config` (antes um toggle só valia após reiniciar o servidor). `createLinkedInClient` passou a respeitar a flag lendo o config atual e o novo `requireLiveLinkedInClient` bloqueia ações reais **sem canal conectado** com `503 channel_required` em vez de simular silenciosamente — usado pelo publisher (postagens), pelos convites e pelas cascatas de DM (o tick é marcado como `skipped` com o motivo, sem travar o worker).
36
+ - **`auth.json` faz parte do skeleton** (`DATA_FILES`): `jobfinder install` e o smoke test do CI criam/validam o arquivo; o `AuthStore` também migra arquivos antigos (preenche `sessionSecret`/usuário).
37
+ - Startup do servidor registra no log e no console o usuário de login e avisa quando a **senha padrão** ainda está em uso.
38
+ - Versão `0.1.02` → `0.1.04` (npm `0.1.4`): a `0.1.03` já tinha sido consumida pelo release do badge de versão dinâmica na sidebar.
39
+
40
+ ### Fixed
41
+
42
+ - **Encerramento prematuro do processo Node.js na inicialização**: o app imprimia o banner de startup (`listening on http://127.0.0.1:4040` + `DRY-RUN mode`) e o processo morria em seguida, devolvendo o terminal ao prompt. Desde o Node 15, qualquer `unhandledRejection` derruba o processo silenciosamente (exit 1) — uma promise solta em qualquer serviço (storage, workers, LLM, LinkedIn) era suficiente para matar o app logo após o banner. Além disso, um `EPIPE` no stdout herdado (terminal/pipe que desaparece — caso do Windows/MobaXterm) também encerrava o processo sem mensagem visível. Agora `src/server/index.mjs` e `scripts/cli.mjs` instalam handlers de processo no topo: `unhandledRejection` é registrado no log (e no console) sem derrubar o servidor; `uncaughtException` encerra de forma visível; erros de `stdout`/`stderr` (EPIPE) são ignorados; o `http.Server` fica pinado em escopo de módulo e em `globalThis.__jobfinder`; o shutdown (SIGINT/SIGTERM/SIGBREAK) é idempotente, para os workers e força a saída após 3 s; o launcher só encerra quando o servidor filho termina e passa a imprimir `[jobfinder] server exited (code/signal)` — a causa do encerramento nunca mais fica invisível. Teste de regressão: `node scripts/manual-tests/startup-keepalive.mjs` (boot via launcher, boot direto, `unhandledRejection` injetado, stdout fechado e shutdown gracioso).
43
+
9
44
  ## [0.1.03] — 2026-11-12
10
45
 
11
46
  ### Fixed
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # JobFinder
2
2
 
3
- **Local-first LinkedIn automation.** Single user, no cloud account, no external database — everything runs on your machine and is stored in JSON.
3
+ **LinkedIn automation platform.** Posts, connections/DMs and job applications — intelligent workflows in one place.
4
4
 
5
5
  [![npm](https://img.shields.io/badge/npm-@danhachuel%2Fjobfinder-indigo)](https://www.npmjs.com/package/@danhachuel/jobfinder)
6
6
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
@@ -29,27 +29,40 @@ Everything is driven from a React dashboard at `http://localhost:4040` — metri
29
29
  Windows / CMD / MobaXterm:
30
30
 
31
31
  ```bash
32
- npx.cmd --yes --prefer-online @danhachuel/jobfinder@<VERSAO> install
33
- npx.cmd --yes --prefer-online @danhachuel/jobfinder@<VERSAO>
32
+ npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.4 install
33
+ npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.4
34
34
  ```
35
35
 
36
36
  Normal terminal:
37
37
 
38
38
  ```bash
39
- npx --yes @danhachuel/jobfinder@<VERSAO> install
40
- npx --yes @danhachuel/jobfinder@<VERSAO>
39
+ npx --yes @danhachuel/jobfinder@0.1.4 install
40
+ npx --yes @danhachuel/jobfinder@0.1.4
41
41
  ```
42
42
 
43
- `install` creates `~/.jobfinder/` (config, channels, topics, posts, connections, dm-cascades, jobs, applications, resume, logs). It is safe to re-run: existing data is never overwritten.
43
+ `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.
44
+
45
+ ## First login
46
+
47
+ The app is protected by a local session. On the first run a single user is created:
48
+
49
+ | Field | Value |
50
+ |---|---|
51
+ | E-mail | `dan.hachuel@gmail.com` |
52
+ | Password | `123456` |
53
+
54
+ - Without a session every screen redirects to `/login` (and the API answers `401`).
55
+ - 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.
56
+ - **Sair** (sidebar footer) ends the session.
44
57
 
45
58
  ## Usage
46
59
 
47
- 1. Start the app → it opens `http://localhost:4040`
60
+ 1. Start the app → it opens `http://localhost:4040` → log in with the local user above
48
61
  2. **Integrações** → connect LinkedIn:
49
62
  - **Recommended:** create your LinkedIn app ([Criar API Oficial do LinkedIn](legal/)) → paste Client ID/Secret → run the OAuth flow
50
63
  - **Fallback:** export cookies with ["Get cookies.txt LOCALLY"](https://chromewebstore.google.com/) and upload `cookies.txt`
51
64
  3. **Configurações** → choose your LLM provider and tune the rate limits (100 invites/week, 5 DMs/day, 20 applications/day by default)
52
- 4. **Dry-run is ON by default** — explore the whole app safely; disable it in Configurações when you are ready
65
+ 4. **Dry-run is ON by default** — explore the whole app safely; disable it in **Configurações → Execução** when you are ready (the header then shows the red `Real Mode` badge)
53
66
  5. Publish posts, connect with people, run DM cascades, match and apply to jobs
54
67
 
55
68
  ### Useful flags
@@ -70,6 +83,7 @@ node scripts/cli.mjs --version # version info
70
83
  ```
71
84
  ~/.jobfinder/
72
85
  ├── config.json # LLM provider, LinkedIn auth, rate limits, dry-run
86
+ ├── auth.json # local user + scrypt password hash + session secret
73
87
  ├── channels.json # LinkedIn accounts (OAuth tokens or cookies — local only)
74
88
  ├── topics.json # themes for automatic posts
75
89
  ├── posts.json # drafts, scheduled, published, failed
@@ -92,6 +106,14 @@ npm run build # builds the UI into src/ui/dist
92
106
  npm start # production-style start (serves the built UI)
93
107
  ```
94
108
 
109
+ Manual smoke tests (start a temporary server + Playwright for the UI):
110
+
111
+ ```bash
112
+ node scripts/manual-tests/fase1-auth-dryrun.mjs # API: login, sessão, toggle dry-run, troca de senha
113
+ node scripts/manual-tests/fase1-dryrun-services.mjs # API: flag dry-run aplicada a postagens/convites/DMs
114
+ node scripts/manual-tests/fase1-ui-e2e.mjs # UI (Playwright): login, badges, configurações, logout
115
+ ```
116
+
95
117
  Layout: `scripts/cli.mjs` (launcher) · `src/server/` (Express API, JSON store, LinkedIn + LLM services, workers) · `src/ui/` (React + Vite + Tailwind v4).
96
118
 
97
119
  ## Publishing
@@ -104,7 +126,7 @@ Releases happen **exclusively via GitHub Actions** (`.github/workflows/publish-n
104
126
 
105
127
  - [Legal index](legal/index.html) · [Privacy Policy](legal/privacy.html) · [Terms of Use](legal/terms.html)
106
128
 
107
- Key points: 100% local storage, no data sent to any JobFinder server, cookies never shared, you are responsible for respecting LinkedIn's rate limits and for every action taken on your account.
129
+ Key points: your data stays in your own JSON store, no data is sent to any JobFinder server, cookies are never shared, you are responsible for respecting LinkedIn's rate limits and for every action taken on your account.
108
130
 
109
131
  ## License
110
132
 
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.03",
4
- "description": "JobFinder — local-first LinkedIn automation (posts, connections/DMs, job matching) with a React + Vite UI. Single-user, JSON storage, no external database.",
3
+ "version": "0.1.05",
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",
7
7
  "automation",
8
8
  "jobs",
9
- "local-first",
9
+ "saas",
10
10
  "cli",
11
11
  "npx"
12
12
  ],
package/scripts/cli.mjs CHANGED
@@ -25,6 +25,34 @@ import { fileURLToPath } from 'node:url';
25
25
 
26
26
  import { ensureDataDir, resolveDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
27
27
 
28
+ /**
29
+ * Process resilience for the launcher — installed before anything else runs
30
+ * so the CLI can never vanish silently (terminal back at the prompt with no
31
+ * explanation):
32
+ *
33
+ * 1. unhandledRejection — since Node 15 any unhandled promise rejection
34
+ * terminates the process immediately. Log it and keep supervising the
35
+ * server child instead of dying without a trace.
36
+ * 2. EPIPE on stdio — when the shell behind stdout disappears (Windows
37
+ * terminals, MobaXterm, redirection), the next console.log throws an
38
+ * unhandled 'error' and kills the launcher.
39
+ * 3. uncaughtException — log loudly and exit with a visible reason.
40
+ */
41
+ process.on('unhandledRejection', (reason) => {
42
+ const message = reason instanceof Error ? reason.message : String(reason);
43
+ console.error(`[jobfinder] unhandled promise rejection ignored: ${message}`);
44
+ });
45
+ process.on('uncaughtException', (err) => {
46
+ console.error('[jobfinder] uncaught exception:', err);
47
+ process.exit(1);
48
+ });
49
+ for (const stream of [process.stdout, process.stderr]) {
50
+ stream?.on?.('error', (err) => {
51
+ if (err?.code === 'EPIPE') return;
52
+ console.error(`[jobfinder] stdio error: ${err?.code ?? ''} ${err?.message ?? err}`);
53
+ });
54
+ }
55
+
28
56
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
57
  const ROOT = path.resolve(__dirname, '..');
30
58
  const SERVER_ENTRY = path.join(ROOT, 'src', 'server', 'index.mjs');
@@ -43,10 +71,10 @@ function normalizeNpmVersion(v) {
43
71
  }
44
72
 
45
73
  const USAGE = `
46
- JobFinder — local-first LinkedIn automation
74
+ JobFinder — LinkedIn automation platform
47
75
 
48
76
  Usage:
49
- jobfinder install Create the local JSON data store (~/.jobfinder/)
77
+ jobfinder install Create the JSON data store (~/.jobfinder/)
50
78
  jobfinder [start] [flags] Start the app at http://localhost:4040
51
79
  jobfinder --version Show version
52
80
  jobfinder --help Show this help
@@ -55,8 +83,6 @@ Flags:
55
83
  --port <n> Port to listen on (default 4040)
56
84
  --host <addr> Bind address (default 127.0.0.1)
57
85
  --data-dir <path> Data directory (default ~/.jobfinder, override with JOBFINDER_HOME)
58
- --open Open the browser after start (default)
59
- --no-open Do not open the browser after start
60
86
  --dry-run Run with automations in dry-run mode (no real LinkedIn actions)
61
87
 
62
88
  Install commands (canonical npm version):
@@ -65,7 +91,7 @@ Install commands (canonical npm version):
65
91
  `;
66
92
 
67
93
  function parseArgs(argv) {
68
- const args = { command: null, port: null, host: null, dataDir: null, open: null, dryRun: false };
94
+ const args = { command: null, port: null, host: null, dataDir: null, dryRun: false };
69
95
  const rest = [...argv];
70
96
  const first = rest[0];
71
97
  if (first && !first.startsWith('-')) {
@@ -87,11 +113,10 @@ function parseArgs(argv) {
87
113
  args.dataDir = rest[i + 1];
88
114
  i += 1;
89
115
  break;
116
+ // Deprecated no-ops: the browser is never opened automatically.
117
+ // The flags are still accepted so existing commands keep working.
90
118
  case '--open':
91
- args.open = true;
92
- break;
93
119
  case '--no-open':
94
- args.open = false;
95
120
  break;
96
121
  case '--dry-run':
97
122
  args.dryRun = true;
@@ -118,7 +143,7 @@ function printBanner() {
118
143
  const line = '-'.repeat(58);
119
144
  console.log(line);
120
145
  console.log(` JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
121
- console.log(' Local-first LinkedIn automation • JSON storage • single user');
146
+ console.log(' LinkedIn Automation • Intelligent Workflows');
122
147
  console.log(line);
123
148
  }
124
149
 
@@ -143,7 +168,7 @@ function commandInstall({ dataDir }) {
143
168
  console.log(` 3. Start the app: npx --yes @danhachuel/jobfinder@${NPM_VERSION}`);
144
169
  }
145
170
 
146
- async function commandStart({ port, host, dataDir, open, dryRun }) {
171
+ async function commandStart({ port, host, dataDir, dryRun }) {
147
172
  const resolved = resolveDataDir(dataDir);
148
173
  ensureDataDir(resolved);
149
174
 
@@ -176,33 +201,42 @@ async function commandStart({ port, host, dataDir, open, dryRun }) {
176
201
  console.log(' Press Ctrl+C to stop.\n');
177
202
 
178
203
  const child = spawn(process.execPath, [SERVER_ENTRY], { stdio: 'inherit', env, cwd: ROOT });
204
+
205
+ // The `child` handle keeps this launcher's event loop open for as long as
206
+ // the server runs: the CLI stays in the foreground and the terminal only
207
+ // returns to the prompt when the server itself exits (or on Ctrl+C).
208
+ let stopping = false;
179
209
  const forward = (signal) => () => {
210
+ // A second Ctrl+C must never be ignored: force the exit if the graceful
211
+ // path is stuck.
212
+ if (stopping) {
213
+ process.exit(1);
214
+ }
215
+ stopping = true;
216
+ if (child.exitCode !== null || child.signalCode !== null) {
217
+ process.exit(child.exitCode ?? (child.signalCode ? 1 : 0));
218
+ return;
219
+ }
180
220
  child.kill(signal);
181
221
  };
182
222
  process.on('SIGINT', forward('SIGINT'));
183
223
  process.on('SIGTERM', forward('SIGTERM'));
224
+ // Windows-only (Ctrl+Break) — harmless no-op on other platforms.
225
+ process.on('SIGBREAK', forward('SIGBREAK'));
184
226
 
185
- const shouldOpen = open === null ? !process.env.CI && process.env.JOBFINDER_NO_OPEN !== '1' : open;
186
- if (shouldOpen) {
187
- setTimeout(() => openBrowser(url), 1200);
188
- }
227
+ // No auto-open: the terminal prints the URL and waits for the user.
228
+ // Opening a browser window on the user's machine without being asked
229
+ // is not acceptable for a hosted (SaaS) product.
189
230
 
190
231
  child.on('exit', (code, signal) => {
232
+ // Loud, visible reason: the server ending must never look like a silent
233
+ // crash back at the prompt.
234
+ const reason = signal ? `signal ${signal}` : `code ${code}`;
235
+ console.error(`\n[jobfinder] server exited (${reason}).`);
191
236
  process.exit(code ?? (signal ? 1 : 0));
192
237
  });
193
238
  }
194
239
 
195
- function openBrowser(url) {
196
- const cmd = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';
197
- const args =
198
- process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
199
- try {
200
- spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();
201
- } catch {
202
- /* opening the browser is best-effort */
203
- }
204
- }
205
-
206
240
  function commandVersion() {
207
241
  console.log(`JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
208
242
  console.log(`os: ${os.type()} ${os.arch()} • node: ${process.version}`);
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Smoke test manual da Fase 1 (auth + dry-run).
3
+ * Uso: node scripts/manual-tests/fase1-auth-dryrun.mjs
4
+ */
5
+ import { spawn } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import process from 'node:process';
10
+
11
+ const PORT = 4077;
12
+ const HOME = path.join(os.tmpdir(), `jobfinder-fase1-${Date.now()}`);
13
+ const BASE = `http://127.0.0.1:${PORT}/api`;
14
+ let cookie = '';
15
+ let passed = 0;
16
+ let failed = 0;
17
+
18
+ /** Wait until a previous run released the port. */
19
+ async function waitPortFree(port) {
20
+ for (let attempt = 0; attempt < 40; attempt += 1) {
21
+ try {
22
+ await fetch(`http://127.0.0.1:${port}/api/health`);
23
+ await new Promise((resolve) => setTimeout(resolve, 250));
24
+ } catch {
25
+ return;
26
+ }
27
+ }
28
+ }
29
+
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
+ async function call(method, endpoint, { body, useCookie = true, raw } = {}) {
41
+ const headers = {};
42
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
43
+ if (useCookie && cookie) headers.Cookie = cookie;
44
+ const res = await fetch(`${BASE}${endpoint}`, {
45
+ method,
46
+ headers,
47
+ body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
48
+ });
49
+ const setCookie = res.headers.get('set-cookie');
50
+ if (setCookie) cookie = setCookie.split(';')[0];
51
+ const text = await res.text();
52
+ let json = null;
53
+ try {
54
+ json = JSON.parse(text);
55
+ } catch {
56
+ json = null;
57
+ }
58
+ return { status: res.status, json, text };
59
+ }
60
+
61
+ const server = spawn(process.execPath, ['src/server/index.mjs'], {
62
+ cwd: process.cwd(),
63
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT) },
64
+ stdio: ['ignore', 'pipe', 'pipe'],
65
+ });
66
+ server.stdout.on('data', (d) => process.stdout.write(` [server] ${d}`));
67
+ server.stderr.on('data', (d) => process.stdout.write(` [server:err] ${d}`));
68
+
69
+ await waitPortFree(PORT);
70
+ await new Promise((resolve) => setTimeout(resolve, 1500));
71
+
72
+ try {
73
+ console.log('\n== 1. Acesso sem sessão ==');
74
+ const health = await call('GET', '/health');
75
+ check('GET /api/health responde 200 (público)', health.status === 200, `status ${health.status}`);
76
+ check('health reporta dryRun=true', health.json?.dryRun === true);
77
+
78
+ const blocked = await call('GET', '/config');
79
+ check('GET /api/config sem login -> 401', blocked.status === 401, `status ${blocked.status}`);
80
+ check('código do erro é "unauthorized"', blocked.json?.error?.code === 'unauthorized');
81
+
82
+ const blockedUi = await fetch(`http://127.0.0.1:${PORT}/postagens`);
83
+ check('rota da UI sem login serve o app (SPA -> /login)', blockedUi.status === 200);
84
+
85
+ console.log('\n== 2. Login ==');
86
+ const bad = await call('POST', '/auth/login', { body: { email: 'dan.hachuel@gmail.com', password: 'errada' }, useCookie: false });
87
+ check('senha errada -> 401', bad.status === 401 && bad.json?.error?.code === 'invalid_credentials', `status ${bad.status}`);
88
+
89
+ const wrongEmail = await call('POST', '/auth/login', { body: { email: 'x@y.com', password: '123456' }, useCookie: false });
90
+ check('e-mail inexistente -> 401', wrongEmail.status === 401);
91
+
92
+ const ok = await call('POST', '/auth/login', { body: { email: 'dan.hachuel@gmail.com', password: '123456' }, useCookie: false });
93
+ check('login padrão -> 200', ok.status === 200, `status ${ok.status}`);
94
+ check('cookie de sessão foi setado', cookie.includes('jobfinder_session='), cookie);
95
+ check('resposta traz o usuário', ok.json?.user?.email === 'dan.hachuel@gmail.com');
96
+ check('aviso de senha padrão em uso', ok.json?.session?.defaultPasswordInUse === true);
97
+
98
+ const session = await call('GET', '/auth/session');
99
+ check('GET /api/auth/session autenticado', session.json?.authenticated === true);
100
+
101
+ const configOk = await call('GET', '/config');
102
+ check('GET /api/config com sessão -> 200', configOk.status === 200);
103
+ check('config.json existe no data dir', fs.existsSync(path.join(HOME, 'auth.json')));
104
+
105
+ console.log('\n== 3. Toggle de dry-run ==');
106
+ const live = await call('PUT', '/config', { body: { dryRun: false } });
107
+ check('PUT dryRun=false -> 200', live.status === 200 && live.json?.config?.dryRun === false);
108
+
109
+ const healthLive = await call('GET', '/health');
110
+ check('health passa a reportar dryRun=false (sem restart)', healthLive.json?.dryRun === false);
111
+
112
+ const statusLive = await call('GET', '/linkedin/status');
113
+ check('linkedin/status reporta modo real', statusLive.json?.dryRun === false);
114
+
115
+ const onDisk = JSON.parse(fs.readFileSync(path.join(HOME, 'config.json'), 'utf8'));
116
+ check('config.json em disco tem dryRun=false', onDisk.dryRun === false);
117
+
118
+ // Sem canal conectado, publicar em modo real deve ser bloqueado (não simulado).
119
+ const posts = await call('GET', '/posts');
120
+ const postId = posts.json?.posts?.[0]?.id ?? null;
121
+ if (postId) {
122
+ const publish = await call('POST', `/posts/${postId}/publish`, { body: {} });
123
+ check('publicar em modo real sem canal -> 503/erro claro', publish.status >= 400, `status ${publish.status} ${publish.json?.error?.message ?? ''}`);
124
+ }
125
+
126
+ const backToDry = await call('PUT', '/config', { body: { dryRun: 'sim' } });
127
+ check('PUT dryRun inválido -> 400', backToDry.status === 400, `status ${backToDry.status}`);
128
+
129
+ await call('PUT', '/config', { body: { dryRun: true } });
130
+ check('volta para dry-run=true', (await call('GET', '/health')).json?.dryRun === true);
131
+
132
+ console.log('\n== 4. Troca de senha ==');
133
+ const badCurrent = await call('PUT', '/auth/password', { body: { currentPassword: 'nao-sei', newPassword: 'nova123', confirmPassword: 'nova123' } });
134
+ check('senha atual incorreta -> 400', badCurrent.status === 400, badCurrent.json?.error?.message);
135
+
136
+ const mismatch = await call('PUT', '/auth/password', { body: { currentPassword: '123456', newPassword: 'nova123', confirmPassword: 'diferente' } });
137
+ check('confirmação divergente -> 400', mismatch.status === 400);
138
+
139
+ const short = await call('PUT', '/auth/password', { body: { currentPassword: '123456', newPassword: '123', confirmPassword: '123' } });
140
+ check('senha curta -> 400', short.status === 400);
141
+
142
+ const changed = await call('PUT', '/auth/password', { body: { currentPassword: '123456', newPassword: 'nova123', confirmPassword: 'nova123' } });
143
+ check('troca de senha -> 200', changed.status === 200, changed.json?.message);
144
+
145
+ const authFile = JSON.parse(fs.readFileSync(path.join(HOME, 'auth.json'), 'utf8'));
146
+ check('hash em auth.json não é texto puro', typeof authFile.user.passwordHash === 'string' && authFile.user.passwordHash.startsWith('scrypt$'));
147
+ check('sessionSecret gerado e persistido', typeof authFile.sessionSecret === 'string' && authFile.sessionSecret.length >= 32);
148
+
149
+ console.log('\n== 5. Nova senha + logout ==');
150
+ cookie = '';
151
+ const oldLogin = await call('POST', '/auth/login', { body: { email: 'dan.hachuel@gmail.com', password: '123456' }, useCookie: false });
152
+ check('senha antiga não funciona mais', oldLogin.status === 401);
153
+
154
+ const newLogin = await call('POST', '/auth/login', { body: { email: 'dan.hachuel@gmail.com', password: 'nova123' }, useCookie: false });
155
+ check('nova senha funciona', newLogin.status === 200, `status ${newLogin.status}`);
156
+ check('aviso de senha padrão desapareceu', newLogin.json?.session?.defaultPasswordInUse === false);
157
+
158
+ const logout = await call('POST', '/auth/logout', { body: {} });
159
+ check('logout -> 200', logout.status === 200);
160
+
161
+ const afterLogout = await call('GET', '/config', { useCookie: true });
162
+ check('após logout /api/config -> 401', afterLogout.status === 401, `status ${afterLogout.status}`);
163
+
164
+ const revoked = await call('POST', '/auth/login', { body: { email: 'dan.hachuel@gmail.com', password: 'nova123' }, useCookie: false });
165
+ check('novo login após logout -> 200', revoked.status === 200);
166
+ } finally {
167
+ server.kill();
168
+ }
169
+
170
+ console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
171
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Smoke test: flag dry-run aplicada aos serviços (postagens/convites/DMs).
3
+ * Uso: node scripts/manual-tests/fase1-dryrun-services.mjs
4
+ */
5
+ import { spawn } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import process from 'node:process';
10
+
11
+ const PORT = 4099;
12
+ const HOME = path.join(os.tmpdir(), `jobfinder-fase1-svc-${Date.now()}`);
13
+ const BASE = `http://127.0.0.1:${PORT}/api`;
14
+ let cookie = '';
15
+ let passed = 0;
16
+ let failed = 0;
17
+
18
+ /** Wait until a previous run released the port. */
19
+ async function waitPortFree(port) {
20
+ for (let attempt = 0; attempt < 40; attempt += 1) {
21
+ try {
22
+ await fetch(`http://127.0.0.1:${port}/api/health`);
23
+ await new Promise((resolve) => setTimeout(resolve, 250));
24
+ } catch {
25
+ return;
26
+ }
27
+ }
28
+ }
29
+
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
+ async function call(method, endpoint, body) {
41
+ const headers = { Cookie: cookie };
42
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
43
+ const res = await fetch(`${BASE}${endpoint}`, {
44
+ method,
45
+ headers,
46
+ body: body === undefined ? undefined : JSON.stringify(body),
47
+ });
48
+ const setCookie = res.headers.get('set-cookie');
49
+ if (setCookie) cookie = setCookie.split(';')[0];
50
+ const json = await res.json().catch(() => null);
51
+ return { status: res.status, json };
52
+ }
53
+
54
+ const server = spawn(process.execPath, ['src/server/index.mjs'], {
55
+ cwd: process.cwd(),
56
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT) },
57
+ stdio: ['ignore', 'pipe', 'pipe'],
58
+ });
59
+ server.stdout.on('data', () => {});
60
+ server.stderr.on('data', (d) => console.log(' [server:err]', String(d)));
61
+ await waitPortFree(PORT);
62
+ await new Promise((r) => setTimeout(r, 1500));
63
+
64
+ try {
65
+ await call('POST', '/auth/login', { email: 'dan.hachuel@gmail.com', password: '123456' });
66
+
67
+ console.log('\n== dry-run ATIVO: ações são simuladas ==');
68
+ const created = await call('POST', '/posts', { text: 'Post de teste do modo dry-run do JobFinder.' });
69
+ check('cria rascunho', created.status === 201, `status ${created.status}`);
70
+ const postId = created.json?.post?.id;
71
+
72
+ const published = await call('POST', `/posts/${postId}/publish`, {});
73
+ check('publicação em dry-run -> 200', published.status === 200, `status ${published.status}`);
74
+ check('post fica published + simulated', published.json?.post?.status === 'published' && published.json?.post?.simulated === true);
75
+
76
+ const search = await call('POST', '/connections/search', { keyword: 'tech recruiter' });
77
+ check('busca de pessoas em dry-run -> 200', search.status === 200 && Array.isArray(search.json?.profiles));
78
+ check('resultados marcados como simulados', search.json?.profiles?.[0]?.simulated === true);
79
+
80
+ const invites = await call('POST', '/connections/invitations', {
81
+ message: 'Olá {{nome}}, vamos nos conectar?',
82
+ profiles: [{ profileId: 'p1', profileUrn: 'urn:li:person:p1', firstName: 'Ana', lastName: 'Silva', headline: 'Recruiter' }],
83
+ });
84
+ check('convite em dry-run -> 200', invites.status === 200 && invites.json?.results?.[0]?.status === 'sent');
85
+ check('convite marcado como simulado', invites.json?.results?.[0]?.simulated === true);
86
+
87
+ console.log('\n== dry-run DESATIVADO sem canal: ações reais são bloqueadas ==');
88
+ await call('PUT', '/config', { dryRun: false });
89
+ const created2 = await call('POST', '/posts', { text: 'Segundo post de teste (modo real).' });
90
+ const postId2 = created2.json?.post?.id;
91
+ const publishLive = await call('POST', `/posts/${postId2}/publish`, {});
92
+ check('publicar sem canal em modo real -> erro claro', publishLive.status >= 400, `status ${publishLive.status} · ${publishLive.json?.error?.message ?? ''}`);
93
+ check('mensagem menciona conectar um canal', /canal/i.test(publishLive.json?.error?.message ?? ''));
94
+
95
+ const postsFile = JSON.parse(fs.readFileSync(path.join(HOME, 'posts.json'), 'utf8'));
96
+ const stuck = postsFile.find((p) => p.id === postId2);
97
+ check('post não fica preso em "publishing"', stuck?.status === 'failed', `status ${stuck?.status}`);
98
+
99
+ const invitesLive = await call('POST', '/connections/invitations', {
100
+ message: 'Olá {{nome}}, vamos nos conectar?',
101
+ profiles: [{ profileId: 'p2', profileUrn: 'urn:li:person:p2', firstName: 'Bruno', lastName: 'Costa' }],
102
+ });
103
+ check('convite sem canal em modo real -> erro claro', invitesLive.status >= 400, `status ${invitesLive.status} · ${invitesLive.json?.error?.message ?? ''}`);
104
+
105
+ const cascade = await call('POST', '/cascades', {
106
+ profileId: 'p3',
107
+ profileUrn: 'urn:li:person:p3',
108
+ contactName: 'Carla Dias',
109
+ sequence: [{ text: 'Oi Carla, tudo bem?' }],
110
+ });
111
+ check('cria cascata de DM', cascade.status === 201, `status ${cascade.status}`);
112
+
113
+ const tick = await call('POST', '/cascades/tick', {});
114
+ check('tick de DM sem canal em modo real -> skipped (não simula)', tick.json?.skipped >= 1 && tick.json?.sent === 0, JSON.stringify(tick.json).slice(0, 160));
115
+
116
+ const searchLive = await call('POST', '/connections/search', { keyword: 'tech recruiter' });
117
+ check('busca continua funcionando em modo real (leitura)', searchLive.status === 200);
118
+
119
+ console.log('\n== volta para dry-run ==');
120
+ await call('PUT', '/config', { dryRun: true });
121
+ const searchDry = await call('POST', '/connections/search', { keyword: 'tech recruiter' });
122
+ check('busca volta a simular', searchDry.json?.profiles?.[0]?.simulated === true);
123
+ const publishDry = await call('POST', `/posts/${postId2}/publish`, {});
124
+ check('publicação volta a ser dry-run (200)', publishDry.status === 200, `status ${publishDry.status}`);
125
+ } finally {
126
+ server.kill();
127
+ }
128
+
129
+ console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
130
+ process.exit(failed ? 1 : 0);