Repository navigation
Expand file tree
/
Copy pathauth.js
More file actions
273 lines (244 loc) · 12.1 KB
/
Copy pathauth.js
File metadata and controls
273 lines (244 loc) · 12.1 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
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const path = require('path');
const fs = require('fs');
const net = require('net');
const APP_DIR = process.env.APP_DIR || __dirname;
const AUTH_FILE = path.join(APP_DIR, 'data', 'auth.json');
const SESSIONS_FILE = path.join(APP_DIR, 'data', 'sessions-auth.json');
const TOKEN_TTL = 30 * 24 * 60 * 60 * 1000; // 30 days
const MAX_SESSIONS = 20; // cap concurrent sessions per installation
// lastUsed is updated in-memory on every request but only flushed to disk at
// this interval — avoids a writeFileSync on every single authenticated request
// (including frequent /api/auth/status polls).
const LAST_USED_FLUSH_INTERVAL = 5 * 60 * 1000; // 5 minutes
function loadAuth() {
try { return JSON.parse(fs.readFileSync(AUTH_FILE, 'utf-8')); }
catch { return null; }
}
function atomicWrite(filePath, content) {
const tmp = filePath + '.tmp';
// 0600: auth.json / sessions-auth.json hold the password hash and live bearer
// tokens — must not be world-readable on multi-user hosts (audit MEDIUM).
fs.writeFileSync(tmp, content, { mode: 0o600 });
try { fs.chmodSync(tmp, 0o600); } catch {}
fs.renameSync(tmp, filePath);
}
function saveAuth(data) {
const dir = path.dirname(AUTH_FILE);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
atomicWrite(AUTH_FILE, JSON.stringify(data, null, 2));
}
// In-memory sessions cache — single source of truth for the current process.
// Eliminates stale-read windows: concurrent callers (e.g. two simultaneous
// logins whose bcrypt.compare() awaits interleave) always work against the
// latest in-process state, not a potentially stale on-disk snapshot.
let _sessionsCache = null;
function loadSessions() {
if (_sessionsCache !== null) return _sessionsCache;
// Tokens are dictionary keys, never properties inherited from Object.prototype.
// Accept only the records this module writes; malformed JSON must fail closed.
_sessionsCache = Object.create(null);
try {
const stored = JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf-8'));
if (stored && typeof stored === 'object' && !Array.isArray(stored)) {
for (const [token, record] of Object.entries(stored)) {
if (isTokenString(token) && isSessionRecord(record)) _sessionsCache[token] = record;
}
}
} catch {}
return _sessionsCache;
}
function isTokenString(token) {
return typeof token === 'string' && /^[0-9a-f]{64}$/.test(token);
}
function isSessionRecord(record) {
return record !== null && typeof record === 'object' && !Array.isArray(record) &&
Object.prototype.hasOwnProperty.call(record, 'created') &&
Number.isFinite(record.created) && record.created > 0;
}
function saveSessions(data) {
_sessionsCache = data; // update cache before disk write so next read is always current
const dir = path.dirname(SESSIONS_FILE);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
// Strip internal metadata (_lastFlushed) before persisting — it's process-local state
const toWrite = {};
for (const [k, v] of Object.entries(_sessionsCache)) {
const { _lastFlushed, ...rest } = v;
toWrite[k] = rest;
}
atomicWrite(SESSIONS_FILE, JSON.stringify(toWrite));
}
function isSetupDone() { return loadAuth() !== null; }
// AUTH-4: guards against two concurrent setup requests both passing the isSetupDone() check
// before either finishes bcrypt.hash(). Set synchronously so Node's single-threaded event
// loop prevents the second request from proceeding past the check.
let _setupInProgress = false;
/** Validate password strength. Throws on failure. */
function validatePassword(password) {
if (!password || typeof password !== 'string') throw new Error('Password is required');
if (password.length < 8) throw new Error('Password must be at least 8 characters');
// bcrypt silently truncates at 72 bytes — enforce by byte count, not char count,
// to prevent silent truncation of multi-byte (UTF-8) passwords.
if (Buffer.byteLength(password, 'utf8') > 72) throw new Error('Password must not exceed 72 bytes when UTF-8 encoded');
}
/** Sanitize display name: trim, max 64 chars, strip control characters. */
function sanitizeDisplayName(name) {
if (!name || typeof name !== 'string') return 'Admin';
// Strip ASCII controls, C1 controls, zero-width chars, bidi overrides, BOM
// eslint-disable-next-line no-control-regex
return name.trim().replace(/[\x00-\x1F\x7F\u0080-\u009F\u200B-\u200F\u2028\u2029\u202A-\u202E\uFEFF]/g, '').slice(0, 64) || 'Admin';
}
async function setupUser(password, displayName) {
if (isSetupDone() || _setupInProgress) throw new Error('Already configured');
_setupInProgress = true;
try {
validatePassword(password);
const safeName = sanitizeDisplayName(displayName);
const hash = await bcrypt.hash(password, 12);
// Re-check after the async await — another concurrent request may have finished first
if (isSetupDone()) throw new Error('Already configured');
saveAuth({
passwordHash: hash,
displayName: safeName,
sessionSecret: process.env.SESSION_SECRET || crypto.randomBytes(32).toString('hex'),
createdAt: new Date().toISOString(),
});
return createToken();
} finally {
_setupInProgress = false;
}
}
async function login(password) {
const auth = loadAuth();
// Generic message: do not distinguish 'not configured' from 'wrong password'
// to prevent user-enumeration via error message differences.
if (!auth || typeof password !== 'string' || !(await bcrypt.compare(password, auth.passwordHash))) throw new Error('Invalid credentials');
// bcrypt yields. A password change can revoke all tokens while this comparison
// is in flight; do not mint a new session from the now-obsolete password hash.
if (loadAuth()?.passwordHash !== auth.passwordHash) throw new Error('Invalid credentials');
return createToken();
}
function createToken() {
const token = crypto.randomBytes(32).toString('hex');
const sessions = loadSessions();
const now = Date.now();
// Prune expired tokens
for (const [t, d] of Object.entries(sessions)) { if (now - d.created > TOKEN_TTL) delete sessions[t]; }
// Enforce session cap: evict least-recently-used sessions over the limit
const entries = Object.entries(sessions);
if (entries.length >= MAX_SESSIONS) {
entries.sort((a, b) => (a[1].lastUsed || 0) - (b[1].lastUsed || 0));
for (const [t] of entries.slice(0, entries.length - MAX_SESSIONS + 1)) delete sessions[t];
}
sessions[token] = { created: now, lastUsed: now };
saveSessions(sessions);
return token;
}
function validateToken(token) {
if (!isTokenString(token)) return false;
const sessions = loadSessions();
if (!Object.prototype.hasOwnProperty.call(sessions, token)) return false;
const s = sessions[token];
if (!isSessionRecord(s)) return false;
if (Date.now() - s.created > TOKEN_TTL) { delete sessions[token]; saveSessions(sessions); return false; }
const now = Date.now();
// Always update lastUsed in the in-memory cache (loadSessions returns _sessionsCache,
// so s is a direct reference — mutation is visible immediately to all callers).
// Only flush to disk when the previous disk write was more than LAST_USED_FLUSH_INTERVAL
// ago: eliminates writeFileSync on every authenticated request / status poll.
s.lastUsed = now;
if (now - (s._lastFlushed || 0) > LAST_USED_FLUSH_INTERVAL) {
s._lastFlushed = now;
saveSessions(sessions);
}
return true;
}
function revokeToken(token) {
try { const s = loadSessions(); delete s[token]; saveSessions(s); }
catch (e) { console.error('[auth] revokeToken write failed:', e.message); }
}
function revokeAll() {
try { saveSessions({}); }
catch (e) { console.error('[auth] revokeAll write failed:', e.message); }
}
async function changePassword(oldPassword, newPassword) {
const auth = loadAuth();
if (!auth) throw new Error('Not configured');
if (typeof oldPassword !== 'string' || !(await bcrypt.compare(oldPassword, auth.passwordHash))) throw new Error('Invalid current password');
validatePassword(newPassword);
const passwordHash = await bcrypt.hash(newPassword, 12);
// Two concurrent changes must not let the later writer overwrite a password
// after authenticating against a hash the earlier change already retired.
if (loadAuth()?.passwordHash !== auth.passwordHash) throw new Error('Invalid current password');
auth.passwordHash = passwordHash;
saveAuth(auth);
revokeAll();
return createToken();
}
// ─── First-run setup gate ─────────────────────────────────────────────────
// While no account exists, POST /api/auth/setup is necessarily unauthenticated —
// and whoever reaches it first owns an instance that runs `claude
// --dangerously-skip-permissions` with Bash in $HOME. From loopback that is the
// owner by definition. From anywhere else we additionally require a code that is
// only ever printed to the server console, so reaching the port is not enough.
let _setupCode = null;
function isLoopbackAddress(addr) {
if (!addr) return false;
const a = String(addr).replace(/^::ffff:/, '');
return a === '::1' || a === 'localhost' || /^127\./.test(a);
}
// Loopback socket addresses alone do not prove a browser is local: a DNS-rebound
// attacker hostname and a local reverse proxy both arrive from 127.0.0.1. Auth
// bypasses (desktop mode and first-run setup) also need a literal local Host and
// no evidence that the request was forwarded. A proxy that rewrites Host and strips
// every forwarding header remains indistinguishable from a local client; never
// expose desktop mode through such a proxy. Do not use isLoopbackAddress() on
// a hostname: its address-only prefix check would trust 127.attacker.example.
function isDirectLoopbackRequest(req) {
if (!isLoopbackAddress(req.socket?.remoteAddress)) return false;
if (['x-forwarded-for', 'x-real-ip', 'forwarded'].some(h => h in req.headers)) return false;
if (typeof req.headers.host !== 'string') return false;
let url;
try { url = new URL('http://' + req.headers.host); } catch { return false; }
if (url.username || url.password || url.pathname !== '/' || url.search || url.hash) return false;
const host = url.hostname;
return host === 'localhost' || host === '[::1]' ||
(net.isIP(host) === 4 && host.startsWith('127.'));
}
// Generated lazily and only while setup is pending, so a finished install keeps
// no live code around.
function getSetupCode() {
if (isSetupDone()) return null;
if (!_setupCode) _setupCode = crypto.randomBytes(4).toString('hex').toUpperCase();
return _setupCode;
}
function checkSetupCode(given) {
const want = getSetupCode();
if (!want || !given) return false;
const a = Buffer.from(String(given).trim().toUpperCase(), 'utf8');
const b = Buffer.from(want, 'utf8');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
function clearSetupCode() { _setupCode = null; }
const PUBLIC_PATHS = [
'/api/auth/setup', '/api/auth/login', '/api/auth/status', '/api/health',
'/login', '/setup',
];
function authMiddleware(req, res, next) {
// Desktop (Electron) runs as a single local user bound to 127.0.0.1 — no auth wall.
if (process.env.CCS_DESKTOP === '1') return next();
const reqPath = req.path.replace(/\/+$/, '') || '/';
if (PUBLIC_PATHS.includes(reqPath)) return next();
if (!isSetupDone()) {
if (req.accepts('html')) return res.redirect('/setup');
return res.status(401).json({ error: 'setup_required' });
}
const token = req.cookies?.token || req.headers['x-auth-token'] ||
(req.headers.authorization?.startsWith('Bearer ') ? req.headers.authorization.slice(7) : null);
if (validateToken(token)) { req.authToken = token; return next(); }
if (req.accepts('html') && !req.path.startsWith('/api/')) return res.redirect('/login');
return res.status(401).json({ error: 'unauthorized' });
}
function validateWsToken(token) { if (process.env.CCS_DESKTOP === '1') return true; return validateToken(token); }
module.exports = { isSetupDone, setupUser, login, validateToken, revokeToken, revokeAll, changePassword, authMiddleware, validateWsToken, loadAuth, isLoopbackAddress, isDirectLoopbackRequest, getSetupCode, checkSetupCode, clearSetupCode };