@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 +30 -0
- package/README.md +29 -7
- package/package.json +1 -1
- package/scripts/cli.mjs +54 -1
- package/scripts/manual-tests/fase1-auth-dryrun.mjs +171 -0
- package/scripts/manual-tests/fase1-dryrun-services.mjs +130 -0
- package/scripts/manual-tests/fase1-screens.mjs +63 -0
- package/scripts/manual-tests/fase1-ui-e2e.mjs +174 -0
- package/scripts/manual-tests/startup-keepalive.mjs +162 -0
- package/src/server/app.mjs +7 -1
- package/src/server/context.mjs +4 -1
- package/src/server/index.mjs +94 -2
- package/src/server/middleware/auth.mjs +69 -0
- package/src/server/routes/auth.mjs +107 -0
- package/src/server/routes/channels.mjs +2 -0
- package/src/server/routes/config.mjs +16 -4
- package/src/server/services/linkedin/index.mjs +22 -1
- package/src/server/services/outreach/cascades.mjs +16 -2
- package/src/server/services/outreach/invitations.mjs +4 -3
- package/src/server/services/posting/publisher.mjs +6 -3
- package/src/server/storage/authStore.mjs +308 -0
- package/src/server/storage/bootstrap.mjs +4 -0
- package/src/server/storage/configSync.mjs +30 -0
- package/src/ui/dist/assets/index-Dyz0cjaY.js +13 -0
- package/src/ui/dist/assets/index-I2Td16Kp.css +2 -0
- package/src/ui/dist/index.html +2 -2
- package/src/ui/dist/assets/index-C9xCTmfz.css +0 -2
- package/src/ui/dist/assets/index-MtU_hyT-.js +0 -13
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JobFinder — local auth routes (mounted at /api/auth, BEFORE the guard).
|
|
3
|
+
*
|
|
4
|
+
* POST /api/auth/login { email, password } -> sets the session cookie
|
|
5
|
+
* POST /api/auth/logout clears the cookie and revokes the token
|
|
6
|
+
* GET /api/auth/session { authenticated, user }
|
|
7
|
+
* PUT /api/auth/password { currentPassword, newPassword, confirmPassword }
|
|
8
|
+
* GET /api/auth/defaults first-run hint (default e-mail + flag)
|
|
9
|
+
*
|
|
10
|
+
* Single local user stored in ~/.jobfinder/auth.json (password hashed with
|
|
11
|
+
* scrypt — see storage/authStore.mjs).
|
|
12
|
+
*/
|
|
13
|
+
import { Router } from 'express';
|
|
14
|
+
|
|
15
|
+
import { asyncRoute, badRequest } from '../middleware/errors.mjs';
|
|
16
|
+
import { requireSession } from '../middleware/auth.mjs';
|
|
17
|
+
import {
|
|
18
|
+
AuthStore,
|
|
19
|
+
DEFAULT_EMAIL,
|
|
20
|
+
SESSION_TTL_MS,
|
|
21
|
+
extractToken,
|
|
22
|
+
sessionCookieOptions,
|
|
23
|
+
} from '../storage/authStore.mjs';
|
|
24
|
+
|
|
25
|
+
export function authRoutes({ store, logger }) {
|
|
26
|
+
const router = Router();
|
|
27
|
+
const auth = new AuthStore(store);
|
|
28
|
+
|
|
29
|
+
router.post(
|
|
30
|
+
'/login',
|
|
31
|
+
asyncRoute(async (req, res) => {
|
|
32
|
+
const { email, password } = req.body ?? {};
|
|
33
|
+
if (!email || !password) {
|
|
34
|
+
throw badRequest('Informe e-mail e senha.');
|
|
35
|
+
}
|
|
36
|
+
const user = auth.verifyCredentials(email, password);
|
|
37
|
+
if (!user) {
|
|
38
|
+
logger.warn('auth', 'login failed', { email: String(email).toLowerCase() });
|
|
39
|
+
throw unauthorized('E-mail ou senha inválidos.');
|
|
40
|
+
}
|
|
41
|
+
const token = auth.issueToken(user.email);
|
|
42
|
+
res.cookie('jobfinder_session', token, sessionCookieOptions());
|
|
43
|
+
logger.info('auth', 'login ok', { email: user.email });
|
|
44
|
+
res.json({
|
|
45
|
+
user,
|
|
46
|
+
session: { expiresInDays: Math.round(SESSION_TTL_MS / 86_400_000), defaultPasswordInUse: auth.usingDefaultPassword() },
|
|
47
|
+
});
|
|
48
|
+
})
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
router.post(
|
|
52
|
+
'/logout',
|
|
53
|
+
asyncRoute((req, res) => {
|
|
54
|
+
const token = extractToken(req);
|
|
55
|
+
if (token) auth.revokeToken(token);
|
|
56
|
+
res.clearCookie('jobfinder_session', sessionCookieOptions({ maxAge: undefined }));
|
|
57
|
+
logger.info('auth', 'logout', { email: req.user?.email ?? null });
|
|
58
|
+
res.json({ ok: true });
|
|
59
|
+
})
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
router.get(
|
|
63
|
+
'/session',
|
|
64
|
+
asyncRoute((req, res) => {
|
|
65
|
+
const payload = auth.verifyToken(extractToken(req));
|
|
66
|
+
if (!payload) {
|
|
67
|
+
return res.json({ authenticated: false, user: null });
|
|
68
|
+
}
|
|
69
|
+
res.json({
|
|
70
|
+
authenticated: true,
|
|
71
|
+
user: auth.getUser(),
|
|
72
|
+
defaultPasswordInUse: auth.usingDefaultPassword(),
|
|
73
|
+
});
|
|
74
|
+
})
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
router.put(
|
|
78
|
+
'/password',
|
|
79
|
+
requireSession({ store }),
|
|
80
|
+
asyncRoute(async (req, res) => {
|
|
81
|
+
const { currentPassword, newPassword, confirmPassword } = req.body ?? {};
|
|
82
|
+
if (!currentPassword || !newPassword) {
|
|
83
|
+
throw badRequest('Informe a senha atual e a nova senha.');
|
|
84
|
+
}
|
|
85
|
+
const user = auth.changePassword({ currentPassword, newPassword, confirmPassword });
|
|
86
|
+
logger.info('auth', 'password changed', { email: user.email });
|
|
87
|
+
res.json({ user, message: 'Senha alterada. Use a nova senha no próximo login.' });
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
router.get(
|
|
92
|
+
'/defaults',
|
|
93
|
+
asyncRoute((req, res) => {
|
|
94
|
+
res.json({ email: DEFAULT_EMAIL, firstRun: auth.usingDefaultPassword() });
|
|
95
|
+
})
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
return router;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function unauthorized(message) {
|
|
102
|
+
const err = new Error(message);
|
|
103
|
+
err.status = 401;
|
|
104
|
+
err.code = 'invalid_credentials';
|
|
105
|
+
err.expose = true;
|
|
106
|
+
return err;
|
|
107
|
+
}
|
|
@@ -15,6 +15,7 @@ import express, { Router } from 'express';
|
|
|
15
15
|
|
|
16
16
|
import { asyncRoute, badRequest, notFound, conflict } from '../middleware/errors.mjs';
|
|
17
17
|
import { newId } from '../storage/jsonStore.mjs';
|
|
18
|
+
import { syncLiveConfig } from '../storage/configSync.mjs';
|
|
18
19
|
import { parseCookiesText, looksLikeLinkedinSession } from '../services/linkedin/cookies.mjs';
|
|
19
20
|
import { LinkedInOfficialClient } from '../services/linkedin/officialApi.mjs';
|
|
20
21
|
import { VoyagerClient } from '../services/linkedin/voyagerClient.mjs';
|
|
@@ -103,6 +104,7 @@ export function channelsRoutes({ store, logger, config, rateLimiter }) {
|
|
|
103
104
|
...current,
|
|
104
105
|
linkedin: { ...current.linkedin, authMode: 'official', officialClientId: clientId, officialClientSecret: clientSecret },
|
|
105
106
|
}));
|
|
107
|
+
syncLiveConfig(store, config);
|
|
106
108
|
logger.info('linkedin:official', 'channel registered', { id });
|
|
107
109
|
res.status(201).json({ channel: redactChannel(store.find('channels.json', id)) });
|
|
108
110
|
})
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { Router } from 'express';
|
|
8
8
|
|
|
9
9
|
import { asyncRoute, badRequest } from '../middleware/errors.mjs';
|
|
10
|
+
import { syncLiveConfig } from '../storage/configSync.mjs';
|
|
10
11
|
|
|
11
12
|
/** Hide secrets before sending anything to the browser. */
|
|
12
13
|
function redactConfig(config) {
|
|
@@ -24,7 +25,7 @@ function redactConfig(config) {
|
|
|
24
25
|
};
|
|
25
26
|
}
|
|
26
27
|
|
|
27
|
-
export function configRoutes({ store, logger, rateLimiter }) {
|
|
28
|
+
export function configRoutes({ store, logger, rateLimiter, config }) {
|
|
28
29
|
const router = Router();
|
|
29
30
|
|
|
30
31
|
router.get(
|
|
@@ -65,12 +66,23 @@ export function configRoutes({ store, logger, rateLimiter }) {
|
|
|
65
66
|
throw badRequest(`linkedin.authMode must be one of ${allowed.join(', ')}`);
|
|
66
67
|
}
|
|
67
68
|
}
|
|
69
|
+
if (patch.dryRun !== undefined && typeof patch.dryRun !== 'boolean') {
|
|
70
|
+
throw badRequest('dryRun must be a boolean');
|
|
71
|
+
}
|
|
68
72
|
|
|
73
|
+
const disablingDryRun = patch.dryRun === false;
|
|
69
74
|
await store.update('config.json', (current) => ({ ...current, ...deepMerge(current, patch) }));
|
|
70
|
-
const updated = store
|
|
75
|
+
const updated = syncLiveConfig(store, config);
|
|
71
76
|
rateLimiter.setConfig(updated);
|
|
72
|
-
req.app.locals.config =
|
|
73
|
-
|
|
77
|
+
req.app.locals.config = config;
|
|
78
|
+
if (disablingDryRun) {
|
|
79
|
+
logger.warn(
|
|
80
|
+
'config',
|
|
81
|
+
'DRY-RUN DISABLED — real LinkedIn actions (posts, invitations, DMs, applications) are now allowed',
|
|
82
|
+
{}
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
logger.info('config', 'configuration updated', { keys: Object.keys(patch), dryRun: updated.dryRun });
|
|
74
86
|
res.json({ config: redactConfig(updated) });
|
|
75
87
|
})
|
|
76
88
|
);
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
import { DryRunLinkedInClient } from './dryRun.mjs';
|
|
24
24
|
import { VoyagerClient } from './voyagerClient.mjs';
|
|
25
25
|
import { LinkedInOfficialClient } from './officialApi.mjs';
|
|
26
|
+
import { HttpError } from '../../middleware/errors.mjs';
|
|
26
27
|
|
|
27
28
|
/** Records of the active channel used across the app. */
|
|
28
29
|
export function getActiveChannel(store) {
|
|
@@ -32,7 +33,7 @@ export function getActiveChannel(store) {
|
|
|
32
33
|
|
|
33
34
|
export function createLinkedInClient({ store, logger, config, rateLimiter }) {
|
|
34
35
|
const channel = getActiveChannel(store);
|
|
35
|
-
const dryRunEnabled = config
|
|
36
|
+
const dryRunEnabled = (config ?? store.read('config.json', {})).dryRun !== false;
|
|
36
37
|
|
|
37
38
|
if (!channel || dryRunEnabled) {
|
|
38
39
|
const simulated = new DryRunLinkedInClient(logger);
|
|
@@ -131,6 +132,26 @@ export function createLinkedInClient({ store, logger, config, rateLimiter }) {
|
|
|
131
132
|
return { client: facade, mode: 'cookie', channel };
|
|
132
133
|
}
|
|
133
134
|
|
|
135
|
+
/**
|
|
136
|
+
* Client for actions that must NEVER be simulated when dry-run is off
|
|
137
|
+
* (publish a post, send an invitation/DM, apply to a job).
|
|
138
|
+
*
|
|
139
|
+
* Throws 503 `channel_required` when the user disabled dry-run but no
|
|
140
|
+
* LinkedIn channel is connected — instead of silently simulating a real
|
|
141
|
+
* action (which would look real in the UI without reaching LinkedIn).
|
|
142
|
+
*/
|
|
143
|
+
export function requireLiveLinkedInClient(ctx) {
|
|
144
|
+
const { client, mode, channel } = createLinkedInClient(ctx);
|
|
145
|
+
if (mode === 'dry-run' && ctx.config?.dryRun === false) {
|
|
146
|
+
throw new HttpError(
|
|
147
|
+
503,
|
|
148
|
+
'channel_required',
|
|
149
|
+
'Dry-run desativado, mas nenhum canal do LinkedIn está conectado. Conecte um canal em Integrações (API oficial ou cookies.txt) ou reative o dry-run em Configurações.'
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
return { client, mode, channel };
|
|
153
|
+
}
|
|
154
|
+
|
|
134
155
|
/** Build the channel object stored in channels.json (secrets never redacted on disk). */
|
|
135
156
|
export function buildChannel({ id, label, authMode, extra = {} }) {
|
|
136
157
|
return {
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { HttpError } from '../../middleware/errors.mjs';
|
|
14
14
|
import { countToday } from '../../middleware/rateLimiter.mjs';
|
|
15
|
-
import {
|
|
15
|
+
import { requireLiveLinkedInClient } from '../linkedin/index.mjs';
|
|
16
16
|
|
|
17
17
|
export const MAX_STEPS = 5; // hard limit from the PRD (dmsPorDia)
|
|
18
18
|
|
|
@@ -122,7 +122,21 @@ export async function cascadeTick(ctx, now = new Date()) {
|
|
|
122
122
|
const cascades = store.list('dm-cascades.json').filter((c) => c.status === 'active');
|
|
123
123
|
if (!cascades.length) return { processed: 0, sent: 0, skipped: 0, results: [] };
|
|
124
124
|
|
|
125
|
-
|
|
125
|
+
// DMs are real actions: with dry-run OFF a channel is mandatory. When the
|
|
126
|
+
// channel is missing the whole tick is skipped (visible in the UI stats)
|
|
127
|
+
// instead of simulating a message that was never delivered.
|
|
128
|
+
let client;
|
|
129
|
+
try {
|
|
130
|
+
({ client } = requireLiveLinkedInClient({ store, logger, config, rateLimiter }));
|
|
131
|
+
} catch (err) {
|
|
132
|
+
logger.warn('cascades', 'tick skipped', { message: err.message });
|
|
133
|
+
return {
|
|
134
|
+
processed: cascades.length,
|
|
135
|
+
sent: 0,
|
|
136
|
+
skipped: cascades.length,
|
|
137
|
+
results: [{ status: 'skipped', reason: err.message }],
|
|
138
|
+
};
|
|
139
|
+
}
|
|
126
140
|
const daily = dailyDmState(store, config);
|
|
127
141
|
const intervalMs = (config?.limits?.dmIntervalMinutes ?? 30) * 60 * 1000;
|
|
128
142
|
let lastSentAt = lastGlobalSend(store);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import { HttpError } from '../../middleware/errors.mjs';
|
|
13
13
|
import { countThisWeek } from '../../middleware/rateLimiter.mjs';
|
|
14
14
|
import { renderTemplate, sanitizeInvitationMessage } from './templates.mjs';
|
|
15
|
-
import { createLinkedInClient } from '../linkedin/index.mjs';
|
|
15
|
+
import { createLinkedInClient, requireLiveLinkedInClient } from '../linkedin/index.mjs';
|
|
16
16
|
|
|
17
17
|
/** Weekly quota state for the UI (Goal Gradient: "X de 100"). */
|
|
18
18
|
export function invitationsQuota(store, config) {
|
|
@@ -21,7 +21,7 @@ export function invitationsQuota(store, config) {
|
|
|
21
21
|
return { used, limit, remaining: Math.max(limit - used, 0), percentage: limit ? Math.round((used / limit) * 100) : 0 };
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
/** People search through the active client (
|
|
24
|
+
/** People search through the active client (read-only: simulated results are fine). */
|
|
25
25
|
export async function searchProfiles(ctx, keyword, options) {
|
|
26
26
|
const { store, logger, config, rateLimiter } = ctx;
|
|
27
27
|
const { client, mode } = createLinkedInClient({ store, logger, config, rateLimiter });
|
|
@@ -48,7 +48,8 @@ export async function sendInvitations(ctx, input) {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
const quota = invitationsQuota(store, config);
|
|
51
|
-
|
|
51
|
+
// Invitations are real actions: with dry-run OFF a channel is mandatory.
|
|
52
|
+
const { client, mode } = requireLiveLinkedInClient({ store, logger, config, rateLimiter });
|
|
52
53
|
|
|
53
54
|
const results = [];
|
|
54
55
|
let sentCount = 0;
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* the simulation flag for dry-run.
|
|
8
8
|
*/
|
|
9
9
|
import { sanitizePostText, LINKEDIN_POST_LIMIT } from './generator.mjs';
|
|
10
|
-
import {
|
|
10
|
+
import { requireLiveLinkedInClient } from '../linkedin/index.mjs';
|
|
11
11
|
|
|
12
12
|
/** Validate a draft before publishing. Throws HttpError on problems. */
|
|
13
13
|
export function assertPublishable(post) {
|
|
@@ -46,9 +46,12 @@ export async function publishPost(ctx, postId) {
|
|
|
46
46
|
|
|
47
47
|
await store.patch('posts.json', postId, { status: 'publishing', error: null, updatedAt: new Date().toISOString() });
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
let mode = 'dry-run';
|
|
50
50
|
try {
|
|
51
|
-
|
|
51
|
+
// Publishing is a real action: with dry-run OFF a channel is mandatory.
|
|
52
|
+
const live = requireLiveLinkedInClient({ store, logger, config, rateLimiter });
|
|
53
|
+
mode = live.mode;
|
|
54
|
+
const result = await live.client.createPost({ text });
|
|
52
55
|
const updated = await store.patch('posts.json', postId, {
|
|
53
56
|
status: 'published',
|
|
54
57
|
publishedAt: new Date().toISOString(),
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JobFinder — local auth store (~/.jobfinder/auth.json).
|
|
3
|
+
*
|
|
4
|
+
* The app is local-first and single-user: the only account is created here
|
|
5
|
+
* on first run, with the password hashed (scrypt, salt + timingSafeEqual)
|
|
6
|
+
* so nothing sensible is written in plain text. Sessions are stateless
|
|
7
|
+
* tokens (HMAC-SHA256 over base64url header/payload) delivered in an
|
|
8
|
+
* HTTP-only cookie — the same token is also accepted as a Bearer token
|
|
9
|
+
* for API tests (curl).
|
|
10
|
+
*
|
|
11
|
+
* The file lives in the data directory, next to config.json, and is never
|
|
12
|
+
* published: only the password hash and a random session secret are stored.
|
|
13
|
+
*/
|
|
14
|
+
import { createHmac, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
|
|
15
|
+
|
|
16
|
+
import { nowIso } from './jsonStore.mjs';
|
|
17
|
+
|
|
18
|
+
/** Pre-created local user (first run). */
|
|
19
|
+
export const DEFAULT_EMAIL = 'dan.hachuel@gmail.com';
|
|
20
|
+
export const DEFAULT_PASSWORD = '123456';
|
|
21
|
+
export const DEFAULT_USER_NAME = 'Dan';
|
|
22
|
+
|
|
23
|
+
/** Cookie used to keep the local session in the browser. */
|
|
24
|
+
export const SESSION_COOKIE = 'jobfinder_session';
|
|
25
|
+
/** Session lifetime: 7 days (re-issued at every login). */
|
|
26
|
+
export const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
27
|
+
|
|
28
|
+
const SCRYPT_KEYLEN = 64;
|
|
29
|
+
const MIN_PASSWORD_LENGTH = 6;
|
|
30
|
+
|
|
31
|
+
/* ------------------------------------------------------------------ *
|
|
32
|
+
* Password hashing (scrypt — native Node crypto, no dependency) *
|
|
33
|
+
* ------------------------------------------------------------------ */
|
|
34
|
+
|
|
35
|
+
/** Hash a plain password: "scrypt$<salt>$<hash>" (both hex). */
|
|
36
|
+
export function hashPassword(password) {
|
|
37
|
+
const salt = randomBytes(16).toString('hex');
|
|
38
|
+
const hash = scryptSync(String(password), salt, SCRYPT_KEYLEN).toString('hex');
|
|
39
|
+
return `scrypt$${salt}$${hash}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Constant-time verification of a password against a stored hash. */
|
|
43
|
+
export function verifyPassword(password, stored) {
|
|
44
|
+
const parts = String(stored ?? '').split('$');
|
|
45
|
+
if (parts.length !== 3 || parts[0] !== 'scrypt') return false;
|
|
46
|
+
const [, salt, expected] = parts;
|
|
47
|
+
let candidate;
|
|
48
|
+
try {
|
|
49
|
+
candidate = scryptSync(String(password), salt, SCRYPT_KEYLEN);
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
const expectedBuffer = Buffer.from(expected, 'hex');
|
|
54
|
+
if (candidate.length !== expectedBuffer.length) return false;
|
|
55
|
+
return timingSafeEqual(candidate, expectedBuffer);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/* ------------------------------------------------------------------ *
|
|
59
|
+
* Session tokens (JWT-shaped, signed with the local session secret) *
|
|
60
|
+
* ------------------------------------------------------------------ */
|
|
61
|
+
|
|
62
|
+
function base64url(input) {
|
|
63
|
+
return Buffer.from(input).toString('base64url');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function sign(data, secret) {
|
|
67
|
+
return createHmac('sha256', secret).update(data).digest('base64url');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function safeEqual(a, b) {
|
|
71
|
+
const left = Buffer.from(String(a));
|
|
72
|
+
const right = Buffer.from(String(b));
|
|
73
|
+
if (left.length !== right.length) return false;
|
|
74
|
+
return timingSafeEqual(left, right);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Issue a signed session token for the given e-mail. */
|
|
78
|
+
export function createSessionToken(email, secret, { expiresInMs = SESSION_TTL_MS } = {}) {
|
|
79
|
+
const header = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
|
|
80
|
+
const issuedAt = Date.now();
|
|
81
|
+
const payload = base64url(
|
|
82
|
+
JSON.stringify({
|
|
83
|
+
sub: String(email).toLowerCase(),
|
|
84
|
+
iat: Math.floor(issuedAt / 1000),
|
|
85
|
+
exp: Math.floor((issuedAt + expiresInMs) / 1000),
|
|
86
|
+
jti: randomBytes(8).toString('hex'),
|
|
87
|
+
})
|
|
88
|
+
);
|
|
89
|
+
const signature = sign(`${header}.${payload}`, secret);
|
|
90
|
+
return `${header}.${payload}.${signature}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Validate a token: returns the payload or null (tampered/expired). */
|
|
94
|
+
export function verifySessionToken(token, secret) {
|
|
95
|
+
const parts = String(token ?? '').split('.');
|
|
96
|
+
if (parts.length !== 3 || !secret) return null;
|
|
97
|
+
const [header, payload, signature] = parts;
|
|
98
|
+
if (!safeEqual(sign(`${header}.${payload}`, secret), signature)) return null;
|
|
99
|
+
try {
|
|
100
|
+
const data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
|
101
|
+
if (!data?.sub || !data?.exp) return null;
|
|
102
|
+
if (Date.now() >= Number(data.exp) * 1000) return null;
|
|
103
|
+
return data;
|
|
104
|
+
} catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Default content of auth.json (first run). */
|
|
110
|
+
export function defaultAuthPayload() {
|
|
111
|
+
return {
|
|
112
|
+
schemaVersion: 1,
|
|
113
|
+
createdAt: nowIso(),
|
|
114
|
+
sessionSecret: randomBytes(32).toString('hex'),
|
|
115
|
+
user: {
|
|
116
|
+
email: DEFAULT_EMAIL,
|
|
117
|
+
name: DEFAULT_USER_NAME,
|
|
118
|
+
passwordHash: hashPassword(DEFAULT_PASSWORD),
|
|
119
|
+
passwordUpdatedAt: nowIso(),
|
|
120
|
+
},
|
|
121
|
+
/** Revoked token ids (logout) — only the last 50 are kept. */
|
|
122
|
+
revokedTokens: [],
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/* ------------------------------------------------------------------ *
|
|
127
|
+
* AuthStore *
|
|
128
|
+
* ------------------------------------------------------------------ */
|
|
129
|
+
|
|
130
|
+
export class AuthStore {
|
|
131
|
+
/** @param {import('./jsonStore.mjs').JsonStore} store */
|
|
132
|
+
constructor(store) {
|
|
133
|
+
this.store = store;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Raw file content (never sent to the browser). */
|
|
137
|
+
read() {
|
|
138
|
+
return this.store.read('auth.json', null) ?? {};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Idempotent bootstrap/migration: creates auth.json with the default
|
|
143
|
+
* user when missing and fills any gap of an older file (secret/user).
|
|
144
|
+
* Safe to call on every startup.
|
|
145
|
+
* @returns {{ created: boolean }}
|
|
146
|
+
*/
|
|
147
|
+
ensure() {
|
|
148
|
+
const existing = this.store.read('auth.json', null);
|
|
149
|
+
if (existing?.user?.passwordHash && existing.sessionSecret && Array.isArray(existing.revokedTokens)) {
|
|
150
|
+
return { created: false };
|
|
151
|
+
}
|
|
152
|
+
const defaults = defaultAuthPayload();
|
|
153
|
+
this.store.update(
|
|
154
|
+
'auth.json',
|
|
155
|
+
(current) => {
|
|
156
|
+
const base = current && typeof current === 'object' ? { ...defaults, ...current } : defaults;
|
|
157
|
+
const next = { ...base };
|
|
158
|
+
if (!next.user?.passwordHash) next.user = { ...defaults.user, ...(next.user ?? {}) };
|
|
159
|
+
if (!next.sessionSecret) next.sessionSecret = defaults.sessionSecret;
|
|
160
|
+
if (!Array.isArray(next.revokedTokens)) next.revokedTokens = [];
|
|
161
|
+
return next;
|
|
162
|
+
},
|
|
163
|
+
{}
|
|
164
|
+
);
|
|
165
|
+
return { created: !existing };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Public view of the local user (no secrets). */
|
|
169
|
+
getUser() {
|
|
170
|
+
const data = this.read();
|
|
171
|
+
const user = data.user ?? {};
|
|
172
|
+
return {
|
|
173
|
+
email: user.email ?? DEFAULT_EMAIL,
|
|
174
|
+
name: user.name ?? DEFAULT_USER_NAME,
|
|
175
|
+
passwordUpdatedAt: user.passwordUpdatedAt ?? null,
|
|
176
|
+
createdAt: data.createdAt ?? null,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** True when the account still uses the first-run password. */
|
|
181
|
+
usingDefaultPassword() {
|
|
182
|
+
return verifyPassword(DEFAULT_PASSWORD, this.read().user?.passwordHash);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Check credentials; returns the public user or null. */
|
|
186
|
+
verifyCredentials(email, password) {
|
|
187
|
+
const data = this.read();
|
|
188
|
+
const user = data.user ?? {};
|
|
189
|
+
const normalizedEmail = String(email ?? '').trim().toLowerCase();
|
|
190
|
+
if (!normalizedEmail || normalizedEmail !== String(user.email ?? '').toLowerCase()) return null;
|
|
191
|
+
if (!verifyPassword(password, user.passwordHash)) return null;
|
|
192
|
+
return this.getUser();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Change the password of the local user.
|
|
197
|
+
* Throws an Error with status/code (mapped by the error middleware).
|
|
198
|
+
*/
|
|
199
|
+
changePassword({ currentPassword, newPassword, confirmPassword }) {
|
|
200
|
+
if (confirmPassword !== undefined && newPassword !== confirmPassword) {
|
|
201
|
+
throw authError('A nova senha e a confirmação não coincidem.');
|
|
202
|
+
}
|
|
203
|
+
if (typeof newPassword !== 'string' || newPassword.length < MIN_PASSWORD_LENGTH) {
|
|
204
|
+
throw authError(`A nova senha precisa de pelo menos ${MIN_PASSWORD_LENGTH} caracteres.`);
|
|
205
|
+
}
|
|
206
|
+
if (!verifyPassword(currentPassword, this.read().user?.passwordHash)) {
|
|
207
|
+
throw authError('Senha atual incorreta.');
|
|
208
|
+
}
|
|
209
|
+
const passwordHash = hashPassword(newPassword);
|
|
210
|
+
this.store.update(
|
|
211
|
+
'auth.json',
|
|
212
|
+
(current) => ({
|
|
213
|
+
...(current ?? {}),
|
|
214
|
+
user: {
|
|
215
|
+
...(current?.user ?? {}),
|
|
216
|
+
passwordHash,
|
|
217
|
+
passwordUpdatedAt: nowIso(),
|
|
218
|
+
},
|
|
219
|
+
}),
|
|
220
|
+
{}
|
|
221
|
+
);
|
|
222
|
+
return this.getUser();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Issue a session token for the user. */
|
|
226
|
+
issueToken(email = DEFAULT_EMAIL) {
|
|
227
|
+
const data = this.read();
|
|
228
|
+
const secret = data.sessionSecret;
|
|
229
|
+
if (!secret) throw authError('auth.json sem sessionSecret — apague o arquivo para recriá-lo.');
|
|
230
|
+
return createSessionToken(email ?? data.user?.email ?? DEFAULT_EMAIL, secret);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Validate a token: returns the payload or null. */
|
|
234
|
+
verifyToken(token) {
|
|
235
|
+
const data = this.read();
|
|
236
|
+
const payload = verifySessionToken(token, data.sessionSecret);
|
|
237
|
+
if (!payload) return null;
|
|
238
|
+
const revoked = Array.isArray(data.revokedTokens) ? data.revokedTokens : [];
|
|
239
|
+
if (payload.jti && revoked.includes(payload.jti)) return null;
|
|
240
|
+
return payload;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Invalidate a token (logout). */
|
|
244
|
+
revokeToken(token) {
|
|
245
|
+
const payload = verifySessionToken(token, this.read().sessionSecret);
|
|
246
|
+
if (!payload?.jti) return;
|
|
247
|
+
this.store.update(
|
|
248
|
+
'auth.json',
|
|
249
|
+
(current) => {
|
|
250
|
+
const revoked = Array.isArray(current?.revokedTokens) ? current.revokedTokens : [];
|
|
251
|
+
return {
|
|
252
|
+
...(current ?? {}),
|
|
253
|
+
revokedTokens: [...revoked.filter((jti) => jti !== payload.jti), payload.jti].slice(-50),
|
|
254
|
+
};
|
|
255
|
+
},
|
|
256
|
+
{}
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function authError(message) {
|
|
262
|
+
const err = new Error(message);
|
|
263
|
+
err.status = 400;
|
|
264
|
+
err.code = 'bad_request';
|
|
265
|
+
err.expose = true;
|
|
266
|
+
return err;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/* ------------------------------------------------------------------ *
|
|
270
|
+
* HTTP helpers (cookie + bearer) *
|
|
271
|
+
* ------------------------------------------------------------------ */
|
|
272
|
+
|
|
273
|
+
/** Parse a Cookie header into a plain object. */
|
|
274
|
+
export function parseCookieHeader(header) {
|
|
275
|
+
const out = {};
|
|
276
|
+
for (const part of String(header ?? '').split(';')) {
|
|
277
|
+
const index = part.indexOf('=');
|
|
278
|
+
if (index === -1) continue;
|
|
279
|
+
const key = part.slice(0, index).trim();
|
|
280
|
+
if (!key) continue;
|
|
281
|
+
try {
|
|
282
|
+
out[key] = decodeURIComponent(part.slice(index + 1).trim());
|
|
283
|
+
} catch {
|
|
284
|
+
out[key] = part.slice(index + 1).trim();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return out;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Extract the session token from the cookie header or Authorization. */
|
|
291
|
+
export function extractToken(req) {
|
|
292
|
+
const cookies = parseCookieHeader(req.headers?.cookie);
|
|
293
|
+
if (cookies[SESSION_COOKIE]) return cookies[SESSION_COOKIE];
|
|
294
|
+
const authorization = String(req.headers?.authorization ?? '');
|
|
295
|
+
if (authorization.toLowerCase().startsWith('bearer ')) return authorization.slice(7).trim();
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Cookie options for the local session (httpOnly; no Secure: plain http). */
|
|
300
|
+
export function sessionCookieOptions(extra = {}) {
|
|
301
|
+
return {
|
|
302
|
+
httpOnly: true,
|
|
303
|
+
sameSite: 'lax',
|
|
304
|
+
path: '/',
|
|
305
|
+
maxAge: SESSION_TTL_MS,
|
|
306
|
+
...extra,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
@@ -9,10 +9,12 @@ import fs from 'node:fs';
|
|
|
9
9
|
import path from 'node:path';
|
|
10
10
|
|
|
11
11
|
import { resolveDataDir as resolveDataDirPath } from '../paths.mjs';
|
|
12
|
+
import { defaultAuthPayload } from './authStore.mjs';
|
|
12
13
|
|
|
13
14
|
/** Files created on first run, in creation order. */
|
|
14
15
|
export const DATA_FILES = [
|
|
15
16
|
'config.json',
|
|
17
|
+
'auth.json',
|
|
16
18
|
'channels.json',
|
|
17
19
|
'topics.json',
|
|
18
20
|
'posts.json',
|
|
@@ -112,6 +114,8 @@ function initialPayload(file) {
|
|
|
112
114
|
switch (file) {
|
|
113
115
|
case 'config.json':
|
|
114
116
|
return DEFAULT_CONFIG;
|
|
117
|
+
case 'auth.json':
|
|
118
|
+
return defaultAuthPayload();
|
|
115
119
|
case 'topics.json':
|
|
116
120
|
return SEED_TOPICS.map((t) => ({ ...t, createdAt: new Date().toISOString() }));
|
|
117
121
|
case 'resume.json':
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JobFinder — live config synchronization.
|
|
3
|
+
*
|
|
4
|
+
* The server context keeps ONE config object (ctx.config) that every
|
|
5
|
+
* service reads at request time (posting, outreach, jobs, LinkedIn
|
|
6
|
+
* facade). The JSON store, however, replaces the cached object on every
|
|
7
|
+
* write — so without this helper a `PUT /api/config` would leave the
|
|
8
|
+
* services looking at a stale snapshot (e.g. toggling dry-run would not
|
|
9
|
+
* change the runtime behavior until a restart).
|
|
10
|
+
*
|
|
11
|
+
* `syncLiveConfig` copies the freshly persisted values into the live
|
|
12
|
+
* object, keeping every reference in sync.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Read config.json from the store (cached, always current). */
|
|
16
|
+
export function readLiveConfig(store, fallback = {}) {
|
|
17
|
+
return store.read('config.json', fallback);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Merge the persisted config into the live context object in place.
|
|
22
|
+
* @returns the fresh config object
|
|
23
|
+
*/
|
|
24
|
+
export function syncLiveConfig(store, liveConfig) {
|
|
25
|
+
const latest = readLiveConfig(store, {});
|
|
26
|
+
if (liveConfig && typeof liveConfig === 'object') {
|
|
27
|
+
Object.assign(liveConfig, latest);
|
|
28
|
+
}
|
|
29
|
+
return latest;
|
|
30
|
+
}
|