@danhachuel/jobfinder 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,36 @@ 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.04] — 2026-11-12
10
+
11
+ ### Added
12
+
13
+ - **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`.
14
+ - **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.
15
+ - **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).
16
+ - **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".
17
+ - **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`.
18
+ - **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`.
19
+ - **Rota `/configuracoes`** (alias de `/config`, que continua funcionando) com o item da sidebar apontando para o novo endereço.
20
+ - **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.
21
+
22
+ ### Changed
23
+
24
+ - **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).
25
+ - **`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).
26
+ - 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.
27
+ - 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.
28
+
29
+ ### Fixed
30
+
31
+ - **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).
32
+
33
+ ## [0.1.03] — 2026-11-12
34
+
35
+ ### Fixed
36
+
37
+ - **Versão dinâmica ao lado do logo na sidebar**: a versão agora é injetada no build via `define.__APP_VERSION__` no `vite.config.js`, lida do `package.json` da raiz (fonte única da verdade), e exibida como badge `vX.Y.ZZ` ao lado de "JobFinder" (borda `indigo-400/30`, fundo `indigo-500/10` translúcido, texto `text-[10px]` — padrão visual LeadMaster). Tooltip mostra também a forma canônica do npm (`0.1.03` → `0.1.3`). O rodapé da sidebar deixou de exibir a versão duplicada e mantém apenas "100% local". O workflow faz o build da UI após o bump de versão, então cada release reflete o número correto sem edição manual.
38
+
9
39
  ## [0.1.02] — 2026-11-12
10
40
 
11
41
  ### Fixed
package/README.md CHANGED
@@ -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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.02",
3
+ "version": "0.1.04",
4
4
  "description": "JobFinder — local-first LinkedIn automation (posts, connections/DMs, job matching) with a React + Vite UI. Single-user, JSON storage, no external database.",
5
5
  "keywords": [
6
6
  "linkedin",
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');
@@ -176,11 +204,28 @@ async function commandStart({ port, host, dataDir, open, dryRun }) {
176
204
  console.log(' Press Ctrl+C to stop.\n');
177
205
 
178
206
  const child = spawn(process.execPath, [SERVER_ENTRY], { stdio: 'inherit', env, cwd: ROOT });
207
+
208
+ // The `child` handle keeps this launcher's event loop open for as long as
209
+ // the server runs: the CLI stays in the foreground and the terminal only
210
+ // returns to the prompt when the server itself exits (or on Ctrl+C).
211
+ let stopping = false;
179
212
  const forward = (signal) => () => {
213
+ // A second Ctrl+C must never be ignored: force the exit if the graceful
214
+ // path is stuck.
215
+ if (stopping) {
216
+ process.exit(1);
217
+ }
218
+ stopping = true;
219
+ if (child.exitCode !== null || child.signalCode !== null) {
220
+ process.exit(child.exitCode ?? (child.signalCode ? 1 : 0));
221
+ return;
222
+ }
180
223
  child.kill(signal);
181
224
  };
182
225
  process.on('SIGINT', forward('SIGINT'));
183
226
  process.on('SIGTERM', forward('SIGTERM'));
227
+ // Windows-only (Ctrl+Break) — harmless no-op on other platforms.
228
+ process.on('SIGBREAK', forward('SIGBREAK'));
184
229
 
185
230
  const shouldOpen = open === null ? !process.env.CI && process.env.JOBFINDER_NO_OPEN !== '1' : open;
186
231
  if (shouldOpen) {
@@ -188,6 +233,10 @@ async function commandStart({ port, host, dataDir, open, dryRun }) {
188
233
  }
189
234
 
190
235
  child.on('exit', (code, signal) => {
236
+ // Loud, visible reason: the server ending must never look like a silent
237
+ // crash back at the prompt.
238
+ const reason = signal ? `signal ${signal}` : `code ${code}`;
239
+ console.error(`\n[jobfinder] server exited (${reason}).`);
191
240
  process.exit(code ?? (signal ? 1 : 0));
192
241
  });
193
242
  }
@@ -197,7 +246,11 @@ function openBrowser(url) {
197
246
  const args =
198
247
  process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
199
248
  try {
200
- spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();
249
+ // Best-effort: an 'error' event (e.g. no shell/browser available) must
250
+ // never take the launcher down.
251
+ const opened = spawn(cmd, args, { stdio: 'ignore', detached: true });
252
+ opened.on('error', () => {});
253
+ opened.unref();
201
254
  } catch {
202
255
  /* opening the browser is best-effort */
203
256
  }
@@ -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);
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Capturas de tela da Fase 1 (login, painel, configurações).
3
+ * Uso: node scripts/manual-tests/fase1-screens.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 = 4122;
12
+ const HOME = path.join(os.tmpdir(), `jobfinder-fase1-shot-${Date.now()}`);
13
+ const APP = `http://127.0.0.1:${PORT}`;
14
+ const OUT = path.join(os.tmpdir(), 'opencode', 'jobfinder-fase1');
15
+ fs.mkdirSync(OUT, { recursive: true });
16
+
17
+ const server = spawn(process.execPath, ['src/server/index.mjs'], {
18
+ cwd: process.cwd(),
19
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_OPEN: '1' },
20
+ stdio: ['ignore', 'pipe', 'pipe'],
21
+ });
22
+ server.stdout.on('data', () => {});
23
+ server.stderr.on('data', () => {});
24
+ await new Promise((r) => setTimeout(r, 1800));
25
+
26
+ let browser;
27
+ try {
28
+ const { chromium } = await import('playwright');
29
+ const cache = path.join(os.homedir(), 'AppData', 'Local', 'ms-playwright');
30
+ const existing = fs
31
+ .readdirSync(cache, { withFileTypes: true })
32
+ .filter((e) => e.isDirectory() && e.name.startsWith('chromium-'))
33
+ .map((e) => path.join(cache, e.name, 'chrome-win64', 'chrome.exe'))
34
+ .filter((c) => fs.existsSync(c))
35
+ .sort()
36
+ .pop();
37
+ browser = await chromium.launch({ headless: true, args: ['--no-sandbox'], ...(existing ? { executablePath: existing } : {}) });
38
+ const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
39
+
40
+ await page.goto(`${APP}/login`, { waitUntil: 'networkidle' });
41
+ await page.screenshot({ path: path.join(OUT, '1-login.png') });
42
+
43
+ await page.fill('#email', 'dan.hachuel@gmail.com');
44
+ await page.fill('#password', '123456');
45
+ await page.click('button[type="submit"]');
46
+ await page.waitForURL((u) => u.pathname === '/', { timeout: 15000 });
47
+ await page.waitForTimeout(1200);
48
+ await page.screenshot({ path: path.join(OUT, '2-painel.png') });
49
+
50
+ await page.click('aside a[href="/configuracoes"]');
51
+ await page.waitForSelector('input[aria-label="Desativar dry-run"]', { timeout: 15000 });
52
+ await page.waitForTimeout(600);
53
+ await page.screenshot({ path: path.join(OUT, '3-configuracoes.png'), fullPage: true });
54
+
55
+ await page.click('input[aria-label="Desativar dry-run"]');
56
+ await page.waitForSelector('text=Sim, ativar modo real', { timeout: 8000 });
57
+ await page.screenshot({ path: path.join(OUT, '4-modal-real.png') });
58
+
59
+ console.log(`Screenshots em: ${OUT}`);
60
+ } finally {
61
+ await browser?.close().catch(() => {});
62
+ server.kill();
63
+ }