-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
340 lines (311 loc) · 10.4 KB
/
auth.js
File metadata and controls
340 lines (311 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { authenticator } = require('otplib');
const QRCode = require('qrcode');
const CONFIG_PATH = path.join(__dirname, '.auth.json');
const SESSION_DURATION = 24 * 60 * 60 * 1000; // 24 hours
const MAX_ATTEMPTS = 5;
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
const SERVICE_NAME = 'PocketShell';
// --- Active session store (in-memory) ---
const activeSessions = new Set();
// --- Rate limiting (in-memory) ---
const rateLimitMap = new Map();
function checkRateLimit(ip) {
const entry = rateLimitMap.get(ip);
if (!entry) return { allowed: true };
if (entry.lockedUntil && Date.now() < entry.lockedUntil) {
const remaining = Math.ceil((entry.lockedUntil - Date.now()) / 1000);
return { allowed: false, remaining };
}
if (entry.lockedUntil && Date.now() >= entry.lockedUntil) {
rateLimitMap.delete(ip);
return { allowed: true };
}
return { allowed: true };
}
function recordFailedAttempt(ip) {
const entry = rateLimitMap.get(ip) || { count: 0 };
entry.count++;
if (entry.count >= MAX_ATTEMPTS) {
entry.lockedUntil = Date.now() + LOCKOUT_DURATION;
entry.count = 0;
}
rateLimitMap.set(ip, entry);
}
function clearAttempts(ip) {
rateLimitMap.delete(ip);
}
// --- Config persistence ---
function loadConfig() {
try {
const data = fs.readFileSync(CONFIG_PATH, 'utf8');
return JSON.parse(data);
} catch (e) {
return null;
}
}
function saveConfig(config) {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
}
function isSetupComplete() {
const config = loadConfig();
return config && config.setupComplete === true;
}
// --- Password hashing (pbkdf2) ---
function hashPassword(password) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
return `${salt}:${hash}`;
}
function verifyPassword(password, stored) {
const [salt, hash] = stored.split(':');
const verify = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
return crypto.timingSafeEqual(Buffer.from(hash, 'hex'), Buffer.from(verify, 'hex'));
}
// --- TOTP ---
function generateTotpSecret() {
return authenticator.generateSecret();
}
function verifyTotp(token, secret) {
try {
return authenticator.verify({ token, secret });
} catch (e) {
return false;
}
}
async function generateQrDataUrl(secret, label) {
const otpauthUrl = authenticator.keyuri(label || 'user', SERVICE_NAME, secret);
return QRCode.toDataURL(otpauthUrl);
}
// --- Session tokens (HMAC-signed) ---
function createSessionToken(sessionSecret) {
const payload = JSON.stringify({ ts: Date.now() });
const data = Buffer.from(payload).toString('base64url');
const sig = crypto.createHmac('sha256', sessionSecret).update(data).digest('hex');
const token = `${data}.${sig}`;
activeSessions.add(token);
return token;
}
function verifySessionToken(token, sessionSecret) {
if (!token || typeof token !== 'string') return false;
const parts = token.split('.');
if (parts.length !== 2) return false;
const [data, sig] = parts;
const expected = crypto.createHmac('sha256', sessionSecret).update(data).digest('hex');
const sigBuf = Buffer.from(sig, 'hex');
const expectedBuf = Buffer.from(expected, 'hex');
if (sigBuf.length !== expectedBuf.length) return false;
if (!crypto.timingSafeEqual(sigBuf, expectedBuf)) return false;
if (!activeSessions.has(token)) return false;
try {
const payload = JSON.parse(Buffer.from(data, 'base64url').toString());
return (Date.now() - payload.ts) < SESSION_DURATION;
} catch (e) {
return false;
}
}
// --- Cookie parsing ---
function parseCookies(cookieHeader) {
const cookies = {};
if (!cookieHeader) return cookies;
cookieHeader.split(';').forEach(c => {
const [key, ...vals] = c.trim().split('=');
if (key) cookies[key.trim()] = vals.join('=');
});
return cookies;
}
// --- Express middleware ---
function authMiddleware(req, res, next) {
const config = loadConfig();
if (!config || !config.setupComplete) {
return res.redirect('/login.html');
}
const cookies = parseCookies(req.headers.cookie);
const token = cookies.session;
if (verifySessionToken(token, config.sessionSecret)) {
return next();
}
return res.redirect('/login.html');
}
// --- WebSocket auth check ---
function authenticateWs(req) {
const config = loadConfig();
if (!config || !config.setupComplete) return false;
const cookies = parseCookies(req.headers.cookie);
const token = cookies.session;
return verifySessionToken(token, config.sessionSecret);
}
// --- Route setup ---
function setupRoutes(app, setupToken) {
// Helper: validate setup token from query param or header
function requireSetupToken(req, res) {
const token = req.query.token || req.headers['x-setup-token'];
if (token !== setupToken) {
res.status(403).json({ error: 'Invalid or missing setup token' });
return false;
}
return true;
}
// GET /auth/status — public, returns setup state
app.get('/auth/status', (req, res) => {
const config = loadConfig();
const setupComplete = config && config.setupComplete === true;
let isAuthenticated = false;
if (setupComplete) {
const cookies = parseCookies(req.headers.cookie);
isAuthenticated = verifySessionToken(cookies.session, config.sessionSecret);
}
res.json({ setupComplete, isAuthenticated });
});
// GET /auth/setup-info — returns QR code (only before setup is complete)
app.get('/auth/setup-info', async (req, res) => {
if (isSetupComplete()) {
return res.status(403).json({ error: 'Setup already complete' });
}
if (!requireSetupToken(req, res)) return;
// Generate a temporary secret (stored in memory until confirmed)
if (!app.locals._pendingSecret) {
app.locals._pendingSecret = generateTotpSecret();
}
try {
const qrDataUrl = await generateQrDataUrl(app.locals._pendingSecret);
res.json({
qrDataUrl,
secret: app.locals._pendingSecret, // show for manual entry
});
} catch (e) {
res.status(500).json({ error: 'Failed to generate QR code' });
}
});
// POST /auth/setup — complete first-time setup
app.post('/auth/setup', (req, res) => {
if (isSetupComplete()) {
return res.status(403).json({ error: 'Setup already complete' });
}
if (!requireSetupToken(req, res)) return;
const { password, totpCode } = req.body;
if (!password || password.length < 6) {
return res.status(400).json({ error: 'Password must be at least 6 characters' });
}
if (!totpCode) {
return res.status(400).json({ error: 'TOTP code required' });
}
const secret = app.locals._pendingSecret;
if (!secret) {
return res.status(400).json({ error: 'No pending setup. Refresh the page.' });
}
if (!verifyTotp(totpCode, secret)) {
return res.status(400).json({ error: 'Invalid TOTP code. Check your authenticator app.' });
}
// Save config
const sessionSecret = crypto.randomBytes(32).toString('hex');
const config = {
passwordHash: hashPassword(password),
totpSecret: secret,
sessionSecret,
setupComplete: true,
createdAt: new Date().toISOString(),
};
saveConfig(config);
delete app.locals._pendingSecret;
// Auto-login after setup
const token = createSessionToken(sessionSecret);
const isSecure = req.protocol === 'https' || req.get('x-forwarded-proto') === 'https';
res.cookie('session', token, {
httpOnly: true,
sameSite: 'strict',
maxAge: SESSION_DURATION,
secure: isSecure,
});
res.json({ success: true });
});
// POST /auth/login — authenticate
app.post('/auth/login', (req, res) => {
const config = loadConfig();
if (!config || !config.setupComplete) {
return res.status(400).json({ error: 'Setup not complete' });
}
const ip = req.ip || req.connection.remoteAddress;
const rateCheck = checkRateLimit(ip);
if (!rateCheck.allowed) {
return res.status(429).json({
error: `Too many attempts. Try again in ${rateCheck.remaining}s`,
});
}
const { password, totpCode } = req.body;
if (!password || !totpCode) {
return res.status(400).json({ error: 'Password and TOTP code required' });
}
if (!verifyPassword(password, config.passwordHash)) {
recordFailedAttempt(ip);
return res.status(401).json({ error: 'Invalid password or TOTP code' });
}
if (!verifyTotp(totpCode, config.totpSecret)) {
recordFailedAttempt(ip);
return res.status(401).json({ error: 'Invalid password or TOTP code' });
}
clearAttempts(ip);
const token = createSessionToken(config.sessionSecret);
const isSecure = req.protocol === 'https' || req.get('x-forwarded-proto') === 'https';
res.cookie('session', token, {
httpOnly: true,
sameSite: 'strict',
maxAge: SESSION_DURATION,
secure: isSecure,
});
res.json({ success: true });
});
// POST /auth/logout
app.post('/auth/logout', (req, res) => {
const cookies = parseCookies(req.headers.cookie);
if (cookies.session) activeSessions.delete(cookies.session);
res.clearCookie('session');
res.json({ success: true });
});
// POST /auth/reset — reset setup (requires current password + TOTP)
app.post('/auth/reset', (req, res) => {
const config = loadConfig();
if (!config || !config.setupComplete) {
return res.json({ success: true });
}
const { password, totpCode } = req.body;
if (!verifyPassword(password, config.passwordHash) || !verifyTotp(totpCode, config.totpSecret)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
try {
fs.unlinkSync(CONFIG_PATH);
} catch (e) { /* ignore */ }
activeSessions.clear();
res.clearCookie('session');
res.json({ success: true });
});
}
module.exports = {
setupRoutes,
authMiddleware,
authenticateWs,
isSetupComplete,
loadConfig,
parseCookies,
};
if (process.env.NODE_ENV === 'test') {
module.exports._internals = {
checkRateLimit,
recordFailedAttempt,
clearAttempts,
hashPassword,
verifyPassword,
generateTotpSecret,
verifyTotp,
createSessionToken,
verifySessionToken,
rateLimitMap,
activeSessions,
CONFIG_PATH,
SESSION_DURATION,
MAX_ATTEMPTS,
LOCKOUT_DURATION,
};
}