@danhachuel/jobfinder 0.1.11 → 0.1.12

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,24 @@ 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.12] — 2026-11-18
10
+
11
+ ### Security
12
+
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 dica de "troque a senha padrão" continua apenas na UI, em Configurações → Segurança). Verificado em boot real: stdout/stderr sem `123456`, sem e-mail e sem `Login:`.
14
+
15
+ ### Fixed
16
+
17
+ - **`EPERM` no `rename` atômico (Windows)**: `JsonStore.write` agora usa `renameAtomic` — em `EPERM`/`EACCES`/`EBUSY` (antivírus, editor ou outro processo segurando o destino) o rename é retentado com backoff (5 × 50 ms) e, se ainda falhar, o destino é removido antes da última tentativa (`unlink` + `rename`); falha definitiva limpa o `.tmp` e propaga o erro. Nenhum `.tmp` órfão em nenhum caminho.
18
+ - **Worker não morre por falha de escrita de estado**: `patchState`/`patchStateSync` envolvem a escrita em try/catch — `EPERM` (ou qualquer erro de I/O) VAI para `worker-error.log` + log + console e a escrita é tentada de novo no próximo tick/heartbeat; `process.exit` não é chamado.
19
+ - **Restart do worker determinístico (fim do falso "outro worker dono")**: (1) detecção de órfão por **pipe** — o supervisor mantém o stdin do worker aberto; quando ele morre (inclusive kill externo), o worker vê EOF e se encerra na hora, sem depender de `ppid` (que o Windows recicla); (2) o launcher passa `JOBFINDER_TAKEOVER=1` em seus spawns — no boot e no restart, uma heartbeat velha de pid reciclado nunca mais bloqueia o worker novo.
20
+ - **Loop do worker à prova de fuga síncrona**: callbacks dos timers (tick e heartbeat) em try/catch, com re-agendamento.
21
+
22
+ ### Tests
23
+
24
+ - `tests/test_atomic_write_concurrency.js` (stub → real, node:test): 40 updates concorrentes sem perder registro, mutator que lança preserva o arquivo anterior, `.tmp` restante não quebra o store, **rename travado com EPERM retentado até dar certo** e **EPERM permanente falhando alto sem .tmp órfão**.
25
+ - `startup-keepalive.mjs`: novo cenário **worker direto com rename sabotado (EPERM permanente)** — sobrevive, registra em `worker-error.log`. Suíte: 32 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E.
26
+
9
27
  ## [0.1.11] — 2026-11-16
10
28
 
11
29
  ### Fixed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
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
@@ -224,7 +224,10 @@ async function commandStart({ port, host, dataDir, dryRun }) {
224
224
  * is NEVER called on this path.
225
225
  */
226
226
  const startWorker = () => {
227
- worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved } });
227
+ // JOBFINDER_TAKEOVER: the launcher either just booted (any previous
228
+ // worker's supervisor is gone by definition) or observed the previous
229
+ // worker exit — a stale heartbeat must never block this spawn.
230
+ worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved, JOBFINDER_TAKEOVER: '1' } });
228
231
  forwardChildOutput(worker, '[worker]');
229
232
  worker.on('exit', (code, signal) => {
230
233
  const reason = signal ? `signal ${signal}` : `code ${code}`;
@@ -13,7 +13,8 @@
13
13
  * 5. worker: sobe com o app, o CLI sobrevive ao crash dele (e o
14
14
  * reinicia), modo JOBFINDER_NO_WORKER=1
15
15
  * 6. worker direto: rejection injetada -> worker-error.log em disco e o
16
- * processo continua vivo; pipes quebrados (EPIPE) não o derrubam
16
+ * processo continua vivo; pipes quebrados (EPIPE) não o derrubam;
17
+ * rename sempre EPERM (arquivo travado no Windows) não o derruba
17
18
  *
18
19
  * Uso: node scripts/manual-tests/startup-keepalive.mjs
19
20
  */
@@ -279,6 +280,51 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
279
280
  fs.rmSync(tmp, { recursive: true, force: true });
280
281
  }
281
282
 
283
+ // 9) worker direto: rename SEMPRE EPERM (antivirus/arquivo travado no
284
+ // Windows) -> o worker NAO morre; o erro vai para worker-error.log e a
285
+ // escrita é tentada de novo no próximo tick/heartbeat.
286
+ {
287
+ console.log('\n== worker direto: EPERM no rename (arquivo travado) ==');
288
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-wperm-'));
289
+ const home = path.join(tmp, 'data');
290
+ ensureDataDir(home);
291
+ const sabotage = path.join(tmp, 'eperm.cjs');
292
+ fs.writeFileSync(
293
+ sabotage,
294
+ `const fs = require('node:fs');\n` +
295
+ `const real = fs.renameSync.bind(fs);\n` +
296
+ `fs.renameSync = (from, to) => {\n` +
297
+ ` if (String(to).endsWith('worker-state.json')) {\n` +
298
+ ` const err = new Error('EPERM: operation not permitted, rename');\n` +
299
+ ` err.code = 'EPERM';\n` +
300
+ ` throw err;\n` +
301
+ ` }\n` +
302
+ ` return real(from, to);\n` +
303
+ `};\n`
304
+ );
305
+ const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
306
+ cwd: ROOT,
307
+ env: { ...process.env, JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000', NODE_OPTIONS: `--require ${sabotage}` },
308
+ stdio: ['ignore', 'pipe', 'pipe'],
309
+ });
310
+ let out = '';
311
+ worker.stdout.on('data', (d) => { out += String(d); });
312
+ worker.stderr.on('data', (d) => { out += String(d); });
313
+ await wait(9000);
314
+ check('worker sobrevive ao EPERM no rename', !dead(worker), dead(worker) ? `exitCode=${worker.exitCode} signal=${worker.signalCode}` : 'vivo');
315
+ let errorLog = '';
316
+ try {
317
+ errorLog = fs.readFileSync(path.join(home, 'worker-error.log'), 'utf8');
318
+ } catch {
319
+ /* arquivo pode nao existir */
320
+ }
321
+ check('EPERM registrado em worker-error.log', /EPERM/.test(errorLog), errorLog.split('\n')[0]?.slice(0, 100) ?? 'vazio');
322
+ check('worker-state write failed registrado (não engolido em silêncio)', /worker-state write failed/i.test(errorLog));
323
+ worker.kill();
324
+ await wait(800);
325
+ fs.rmSync(tmp, { recursive: true, force: true });
326
+ }
327
+
282
328
  // 6) JOBFINDER_NO_WORKER=1: modo sem worker, CLI continua vivo
283
329
  {
284
330
  console.log('\n== boot sem worker (JOBFINDER_NO_WORKER=1) ==');
@@ -127,7 +127,9 @@ export async function start() {
127
127
  } else {
128
128
  console.log('REAL MODE: live LinkedIn actions are enabled (dry-run is OFF).');
129
129
  }
130
- console.log(`Login: ${auth.getUser().email}${auth.usingDefaultPassword() ? ' / 123456 (troque a senha em Configurações)' : ''}`);
130
+ // Credentials are NEVER printed to the terminal (security): the local
131
+ // account is managed in the UI (Configurações → Segurança). A dangling
132
+ // `Login:` line here leaked the default e-mail/password to every console.
131
133
  });
132
134
 
133
135
  // Pin the server handle: the listening socket keeps the event loop (and
@@ -10,6 +10,60 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { randomUUID } from 'node:crypto';
12
12
 
13
+ /** Synchronous sleep — the only dependency-free one in Node. */
14
+ function sleepSync(ms) {
15
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
16
+ }
17
+
18
+ /**
19
+ * Atomic replace with Windows patience.
20
+ *
21
+ * On Windows, `rename` over a file that ANY process still holds open —
22
+ * antivirus scanning the data dir, an editor, another node process that
23
+ * opened it without FILE_SHARE_DELETE — fails with EPERM/EACCES/EBUSY.
24
+ * The rename is the LAST step of every atomic write, so the write retries
25
+ * with backoff (5 × 50 ms) and, if the destination is still locked, drops
26
+ * it first: Windows allows deleting a locked file far more often than
27
+ * renaming over it.
28
+ *
29
+ * @param {string} tmp temp file holding the new content
30
+ * @param {string} file destination
31
+ * @throws the OS error when every attempt failed (callers decide how bad
32
+ * that is — a heartbeat failure must never kill a process)
33
+ */
34
+ function renameAtomic(tmp, file) {
35
+ const RETRY_DELAY_MS = 50;
36
+ const MAX_ATTEMPTS = 5;
37
+ let lastErr = null;
38
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
39
+ try {
40
+ fs.renameSync(tmp, file);
41
+ return;
42
+ } catch (err) {
43
+ const code = err?.code;
44
+ if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') throw err;
45
+ lastErr = err;
46
+ if (attempt < MAX_ATTEMPTS) sleepSync(RETRY_DELAY_MS);
47
+ }
48
+ }
49
+ // Fallback: remove the locked destination (best-effort) and rename once more.
50
+ try {
51
+ fs.unlinkSync(file);
52
+ } catch {
53
+ /* the rename below may still succeed: only it can report failure */
54
+ }
55
+ try {
56
+ fs.renameSync(tmp, file);
57
+ } catch (err) {
58
+ try {
59
+ fs.unlinkSync(tmp); // never leave the .tmp behind
60
+ } catch {
61
+ /* best effort */
62
+ }
63
+ throw err ?? lastErr;
64
+ }
65
+ }
66
+
13
67
  export function newId(prefix) {
14
68
  return `${prefix}_${randomUUID().replace(/-/g, '').slice(0, 12)}`;
15
69
  }
@@ -71,7 +125,7 @@ export class JsonStore {
71
125
  const tmp = `${file}.tmp.${process.pid}`;
72
126
  fs.mkdirSync(path.dirname(file), { recursive: true });
73
127
  fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
74
- fs.renameSync(tmp, file);
128
+ renameAtomic(tmp, file);
75
129
  this.cache.set(name, data);
76
130
  return data;
77
131
  }
@@ -127,11 +127,18 @@ function nowIso() {
127
127
  * Used for every normal-path write.
128
128
  */
129
129
  async function patchState(patch) {
130
- return store.update(
131
- STATE_FILE,
132
- (current) => ({ ...defaultWorkerState(), ...(current ?? {}), ...patch }),
133
- {}
134
- );
130
+ try {
131
+ return await store.update(
132
+ STATE_FILE,
133
+ (current) => ({ ...defaultWorkerState(), ...(current ?? {}), ...patch }),
134
+ {}
135
+ );
136
+ } catch (err) {
137
+ // A locked state file (Windows EPERM/EACCES) must never kill the worker:
138
+ // record it and let the next tick/heartbeat try again.
139
+ reportUnexpected('worker-state write failed', err);
140
+ return null;
141
+ }
135
142
  }
136
143
 
137
144
  /**
@@ -139,8 +146,13 @@ async function patchState(patch) {
139
146
  * handlers, where awaiting is not possible.
140
147
  */
141
148
  function patchStateSync(patch) {
142
- const current = store.read(STATE_FILE, {}) ?? {};
143
- return store.write(STATE_FILE, { ...defaultWorkerState(), ...current, ...patch });
149
+ try {
150
+ const current = store.read(STATE_FILE, {}) ?? {};
151
+ return store.write(STATE_FILE, { ...defaultWorkerState(), ...current, ...patch });
152
+ } catch (err) {
153
+ reportUnexpected('worker-state write failed (sync)', err);
154
+ return null;
155
+ }
144
156
  }
145
157
 
146
158
  /** Append an action line and persist it. */
@@ -156,8 +168,16 @@ async function writeLog(level, message, data) {
156
168
  * kill (TerminateProcess, exit 0xFFFFFFFF) skips the worker's exit handler,
157
169
  * so the heartbeat stays fresh for a few seconds after the process is gone.
158
170
  * Without the pid check, a crash-restart would be rejected as a duplicate.
171
+ *
172
+ * JOBFINDER_TAKEOVER=1 is set by a SUPERVISOR that is spawning us after
173
+ * having observed the previous lifecycle end (the launcher's restart path,
174
+ * or its own boot): the supervisor owns the lifecycle — when it dies, its
175
+ * workers die with it (stdin EOF) — so a stale heartbeat must never block
176
+ * its spawn. This is what makes an automatic restart deterministic even
177
+ * when Windows recycled the dead worker's pid.
159
178
  */
160
179
  function anotherWorkerOwnsState() {
180
+ if (process.env.JOBFINDER_TAKEOVER === '1') return false;
161
181
  const state = readWorkerState(store);
162
182
  if (!state.pid || state.pid === process.pid || !state.heartbeatAt) return false;
163
183
  const age = Date.now() - new Date(state.heartbeatAt).getTime();
@@ -393,6 +413,26 @@ async function main() {
393
413
  // Crash/forensic log: the only artifact that survives a dead pipe.
394
414
  errorLogPath = path.join(dataDir, 'worker-error.log');
395
415
 
416
+ // Orphan detection by PIPE (primary). The supervisor keeps our stdin pipe
417
+ // open for as long as it lives; when it dies (any reason, hard kill
418
+ // included) the pipe closes and stdin reaches EOF — immediately and
419
+ // without depending on pids, which Windows recycles. `parentIsGone()`
420
+ // stays as the heartbeat backstop.
421
+ //
422
+ // Armed ONLY when the supervisor said so (JOBFINDER_SUPERVISED_STDIN):
423
+ // a manual run's fd 0 may be the NUL device, which EOFs instantly.
424
+ if (process.env.JOBFINDER_SUPERVISED_STDIN === '1') {
425
+ try {
426
+ process.stdin?.resume?.();
427
+ process.stdin?.on?.('end', () => stop('parent launcher closed the pipe (EOF)'));
428
+ process.stdin?.on?.('error', (err) => {
429
+ if (err?.code !== 'EPIPE') appendErrorLog(`stdin error: ${err?.code ?? ''} ${err?.message ?? err}`);
430
+ });
431
+ } catch {
432
+ /* no pipe to watch: the heartbeat backstop still applies */
433
+ }
434
+ }
435
+
396
436
  context = createContext(dataDir);
397
437
  store = context.store;
398
438
  logger = context.logger;
@@ -31,6 +31,12 @@ export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
31
31
  * independent from the terminal: the supervisor forwards the output and its
32
32
  * own EPIPE handlers absorb a dead pipe.
33
33
  *
34
+ * stdin is a pipe that the supervisor NEVER writes: when the supervisor
35
+ * dies, its end closes and the child sees EOF on stdin — a deterministic
36
+ * "parent is gone" signal that does not depend on pid recycling (which
37
+ * breaks the classic `process.kill(ppid, 0)` check on Windows). The worker
38
+ * uses it to self-terminate; the server ignores it.
39
+ *
34
40
  * @param {string} entry absolute path of the child entrypoint
35
41
  * @param {{ env?: object, cwd?: string }} [options]
36
42
  * @returns {import('node:child_process').ChildProcess}
@@ -38,8 +44,15 @@ export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
38
44
  export function spawnSupervised(entry, options = {}) {
39
45
  return spawn(process.execPath, [entry], {
40
46
  cwd: options.cwd ?? path.resolve(__dirname, '..', '..'),
41
- env: { ...process.env, ...(options.env ?? {}) },
42
- stdio: ['ignore', 'pipe', 'pipe'],
47
+ env: {
48
+ ...process.env,
49
+ // Tells a supervised worker that fd 0 is a REAL pipe to this supervisor
50
+ // (never the NUL device of a manual run): EOF on stdin then means
51
+ // "the supervisor died". A manual run must not arm the detector.
52
+ JOBFINDER_SUPERVISED_STDIN: '1',
53
+ ...(options.env ?? {}),
54
+ },
55
+ stdio: ['pipe', 'pipe', 'pipe'],
43
56
  windowsHide: true,
44
57
  creationFlags: process.platform === 'win32' ? CREATE_NEW_PROCESS_GROUP : 0,
45
58
  });