clay-server 5.1.1-beta.1 → 5.2.0-beta.2

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.
Files changed (61) hide show
  1. package/lib/account-auth-policy.js +21 -0
  2. package/lib/account-auth-socket.js +29 -0
  3. package/lib/account-auth-throttle.js +44 -0
  4. package/lib/account-auth-transport.js +48 -0
  5. package/lib/account-login-page.js +28 -0
  6. package/lib/account-passkey-challenges.js +31 -0
  7. package/lib/account-passkey-page.js +89 -0
  8. package/lib/account-passkey-policy.js +39 -0
  9. package/lib/account-password-page.js +69 -0
  10. package/lib/account-passwords.js +36 -0
  11. package/lib/account-remembered.js +77 -0
  12. package/lib/account-session-page.js +51 -0
  13. package/lib/account-session-store.js +82 -0
  14. package/lib/daemon.js +2 -0
  15. package/lib/migrate-single-user.js +3 -23
  16. package/lib/project-connection.js +1 -1
  17. package/lib/project-server-settings.js +1 -0
  18. package/lib/project-sessions.js +3 -1
  19. package/lib/project-user-knowledge.js +2 -1
  20. package/lib/public/app.js +2 -0
  21. package/lib/public/auth/account-login.css +98 -0
  22. package/lib/public/auth/account-login.js +104 -0
  23. package/lib/public/css/command-palette.css +12 -33
  24. package/lib/public/css/user-settings-sessions.css +42 -0
  25. package/lib/public/index.html +17 -5
  26. package/lib/public/modules/account-auth-settings.js +71 -0
  27. package/lib/public/modules/account-transport-settings.js +51 -0
  28. package/lib/public/modules/app-header.js +3 -2
  29. package/lib/public/modules/app-messages.js +16 -4
  30. package/lib/public/modules/app-rendering.js +4 -3
  31. package/lib/public/modules/chat-render-runtime.js +8 -0
  32. package/lib/public/modules/clay-log-links.js +23 -0
  33. package/lib/public/modules/command-palette.js +94 -5
  34. package/lib/public/modules/markdown.js +1 -1
  35. package/lib/public/modules/passkey-browser.js +69 -0
  36. package/lib/public/modules/passkey-server-settings.js +57 -0
  37. package/lib/public/modules/project-logs-render.js +3 -2
  38. package/lib/public/modules/server-settings-controls.js +10 -0
  39. package/lib/public/modules/server-settings.js +7 -2
  40. package/lib/public/modules/user-settings-account.js +14 -1
  41. package/lib/public/modules/user-settings-sessions.js +120 -0
  42. package/lib/public/modules/user-settings.js +3 -0
  43. package/lib/public/modules/you-activity.js +3 -1
  44. package/lib/public/modules/you.js +91 -6
  45. package/lib/public/style.css +1 -0
  46. package/lib/server-account-passkeys.js +186 -0
  47. package/lib/server-account-passwords.js +127 -0
  48. package/lib/server-account-security.js +53 -0
  49. package/lib/server-auth.js +107 -79
  50. package/lib/server-home-chat.js +3 -3
  51. package/lib/server-home-clay-session-links.js +17 -9
  52. package/lib/server-settings.js +2 -1
  53. package/lib/server.js +3 -1
  54. package/lib/sessions.js +3 -1
  55. package/lib/user-knowledge-service.js +23 -1
  56. package/lib/users-auth.js +38 -3
  57. package/lib/users-create.js +97 -0
  58. package/lib/users-server-pin.js +37 -0
  59. package/lib/users.js +11 -84
  60. package/lib/workspace-query-service.js +13 -2
  61. package/package.json +2 -1
@@ -0,0 +1,127 @@
1
+ var crypto = require('crypto');
2
+ var passwords = require('./account-passwords');
3
+ var attachPolicy = require('./account-auth-policy').attachPolicy;
4
+
5
+ function attachAccountPasswords(ctx) {
6
+ var users = ctx.users;
7
+ var policy = attachPolicy(users);
8
+ var pending = new Map();
9
+
10
+ var cookieName = ctx.devMode ? 'clay_password_transition_dev' : 'clay_password_transition';
11
+ function reply(res, code, data, cookies) {
12
+ var headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
13
+ if (cookies) headers['Set-Cookie'] = cookies;
14
+ res.writeHead(code, headers); res.end(JSON.stringify(data));
15
+ }
16
+ function transitionCookie(token, req) {
17
+ return cookieName + '=' + token + '; Path=/; HttpOnly; SameSite=Strict; Max-Age=' + (token ? '600' : '0') + (ctx.tlsOptions || req && ctx.transport.info(req).secure ? '; Secure' : '');
18
+ }
19
+ function read(req, res, action, maxBytes) {
20
+ if ((req.headers['content-type'] || '').split(';')[0] !== 'application/json') { reply(res, 415, { error: 'JSON required.' }); return; }
21
+ var body = ''; var oversized = false;
22
+ req.on('data', function (chunk) { if (oversized) return; body += chunk; if (Buffer.byteLength(body) > (maxBytes || 4096)) { oversized = true; reply(res, 413, { error: 'Request too large.' }); } });
23
+ req.on('end', function () {
24
+ if (oversized) return;
25
+ var data; try { data = JSON.parse(body); } catch (error) { reply(res, 400, { error: 'Invalid request.' }); return; }
26
+ if (!data || typeof data !== 'object' || Array.isArray(data)) { reply(res, 400, { error: 'Invalid request.' }); return; }
27
+ Promise.resolve().then(function () { return action(data); }).catch(function (error) { reply(res, error.status || 400, { error: error.message || 'Could not complete sign-in.' }); });
28
+ });
29
+ }
30
+ function throttle(req, username) { ctx.throttle.consume(req, username); }
31
+ function clearAttempts(req, username) { ctx.throttle.success(req, username); }
32
+ function grant(user, res, req) {
33
+ var session = ctx.createSession(user.id, user.passwordHash, null, ctx.transport.info(req).secure, req);
34
+ reply(res, 200, { ok: true }, session.cookies.concat([transitionCookie('', req)]));
35
+ }
36
+ function startTransition(user, res, req) {
37
+ var now = Date.now();
38
+ pending.forEach(function (entry, key) { if (entry.until <= now) pending.delete(key); });
39
+ if (pending.size >= 1000) throw new Error('Sign-in is busy. Please retry shortly.');
40
+ var token = crypto.randomBytes(32).toString('hex');
41
+ pending.set(token, { userId: user.id, pinHash: user.pinHash, until: now + 600000, busy: false });
42
+ reply(res, 200, { ok: true, passwordRequired: true }, transitionCookie(token, req));
43
+ }
44
+ function handleRequest(req, res, url) {
45
+ if (req.method === 'POST' && url === '/auth/logout') pending.delete(ctx.parseCookies(req)[cookieName]);
46
+ if (url === '/api/account-auth-policy') {
47
+ var admin = ctx.getUser(req);
48
+ if (!admin || admin.role !== 'admin') { reply(res, 403, { error: 'Administrator access required.' }); return true; }
49
+ if (req.method === 'GET') { reply(res, 200, { method: policy.enabled() ? 'password' : 'pin', available: policy.available() }); return true; }
50
+ if (req.method !== 'PUT') { reply(res, 405, { error: 'Method not allowed.' }); return true; }
51
+ read(req, res, function (data) {
52
+ if (data.method !== 'password') throw new Error('Only the password transition is supported.');
53
+ policy.activate();
54
+ reply(res, 200, { ok: true, method: 'password' });
55
+ if (ctx.onPolicyChanged) ctx.onPolicyChanged();
56
+ });
57
+ return true;
58
+ }
59
+ if (!policy.enabled()) return false;
60
+ if (req.method === 'GET' && url === '/account/password') {
61
+ var signedIn = ctx.getUser(req);
62
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
63
+ res.end(signedIn ? require('./account-password-page').render(true) : require('./account-login-page').render({ password: true }));
64
+ return true;
65
+ }
66
+ if (req.method === 'POST' && url === '/auth/password-change') {
67
+ read(req, res, async function (data) {
68
+ var user = ctx.getUser(req);
69
+ if (!user) throw new Error('Sign in again to change your password.');
70
+ throttle(req, user.username);
71
+ if (!await passwords.verify(data.currentPassword, user.passwordHash)) throw new Error('Current password is incorrect.');
72
+ if (data.password !== data.confirmPassword) throw new Error('Passwords do not match.');
73
+ var hash = await passwords.hash(data.password);
74
+ var state = users.loadUsers();
75
+ var current = state.users.find(function (entry) { return entry.id === user.id; });
76
+ if (!current || current.passwordHash !== user.passwordHash || current.mustChangePin) throw new Error('Credentials changed. Sign in again.');
77
+ current.passwordHash = hash; users.saveUsers(state);
78
+ ctx.revokeSessions(user.id); clearAttempts(req, user.username); grant(current, res, req);
79
+ });
80
+ return true;
81
+ }
82
+ if (url === '/api/user/pin') {
83
+ reply(res, 409, { error: 'This server uses account passwords. Contact an administrator for credential recovery.' });
84
+ return true;
85
+ }
86
+ if (req.method === 'POST' && url === '/auth/login') {
87
+ read(req, res, async function (data) {
88
+ throttle(req, data.username);
89
+ var user = typeof data.username === 'string' ? users.findUserByUsername(data.username) : null;
90
+ if (data.pin !== undefined) {
91
+ if (!user || user.passwordHash && !user.mustChangePin || typeof data.pin !== 'string' || !/^\d{6}$/.test(data.pin) || !users.verifyPin(data.pin, user.pinHash, user)) throw new Error('Invalid username or account PIN.');
92
+ clearAttempts(req, user.username); startTransition(user, res, req); return;
93
+ }
94
+ var originalHash = user && user.passwordHash;
95
+ if (!await passwords.verify(data.password, originalHash)) throw new Error('Invalid username or password.');
96
+ user = users.findUserById(user.id);
97
+ if (!user || user.passwordHash !== originalHash || user.mustChangePin) throw new Error('Account credentials changed. Please sign in again.');
98
+ clearAttempts(req, user.username); grant(user, res, req);
99
+ });
100
+ return true;
101
+ }
102
+ if (req.method === 'POST' && url === '/auth/password-transition') {
103
+ read(req, res, async function (data) {
104
+ var token = ctx.parseCookies(req)[cookieName];
105
+ var proof = pending.get(token);
106
+ if (!proof || proof.until <= Date.now() || proof.busy) throw new Error('Verify your account PIN again.');
107
+ proof.busy = true;
108
+ try {
109
+ if (data.password !== data.confirmPassword) throw new Error('Passwords do not match.');
110
+ var hash = await passwords.hash(data.password);
111
+ var state = users.loadUsers();
112
+ var user = state.users.find(function (entry) { return entry.id === proof.userId; });
113
+ if (!user || user.pinHash !== proof.pinHash || user.passwordHash && !user.mustChangePin || proof.until <= Date.now()) throw new Error('Account credentials changed. Verify your PIN again.');
114
+ user.passwordHash = hash; user.pinHash = null; user.mustChangePin = false;
115
+ users.saveUsers(state);
116
+ pending.delete(token);
117
+ ctx.revokeSessions(user.id);
118
+ grant(user, res, req);
119
+ } finally { proof.busy = false; }
120
+ });
121
+ return true;
122
+ }
123
+ return false;
124
+ }
125
+ return { handleRequest: handleRequest, policy: policy, http: { read: read, reply: reply, throttle: throttle, clearAttempts: clearAttempts } };
126
+ }
127
+ module.exports = { attachAccountPasswords: attachAccountPasswords };
@@ -0,0 +1,53 @@
1
+ var passwords = require('./account-passwords');
2
+ function attachAccountSecurity(ctx) {
3
+ function sessionList(req, user) {
4
+ var current = ctx.sessions.get(ctx.sessionToken(req), false);
5
+ return ctx.sessions.list(user.id).filter(function (entry) { return !!ctx.validSessionUser(entry); }).map(function (entry) {
6
+ return { id: entry.id, current: !!current && entry.id === current.id, userAgent: entry.userAgent || '',
7
+ address: entry.address, createdAt: entry.migrated ? null : entry.createdAt,
8
+ lastSeenAt: entry.migrated ? entry.observedAt || null : entry.lastSeenAt,
9
+ unknownDevice: !!entry.migrated && !entry.observedAt,
10
+ expiresAt: entry.expiresAt, method: entry.passkeyId ? 'Passkey' : entry.credentialVersion ? 'Password' : 'Account sign-in', migrated: !!entry.migrated };
11
+ }).sort(function (a, b) { return Number(b.current) - Number(a.current) || (b.lastSeenAt || 0) - (a.lastSeenAt || 0); });
12
+ }
13
+ async function verify(req, data, original) {
14
+ ctx.http.throttle(req, original.username);
15
+ if (!original.passwordHash || !await passwords.verify(data.currentPassword, original.passwordHash)) throw new Error('Current password is incorrect.');
16
+ var current = ctx.getUser(req);
17
+ if (!current || current.id !== original.id || current.passwordHash !== original.passwordHash) throw new Error('Sign in again to continue.');
18
+ ctx.http.clearAttempts(req, current.username); return current;
19
+ }
20
+ function handleRequest(req, res, url) {
21
+ if (url !== '/api/account-sessions' && url !== '/api/account-transport' && url !== '/account/sessions') return false;
22
+ var user = ctx.getUser(req);
23
+ if (!user) { ctx.http.reply(res, 401, { error: 'Sign in again to manage your account.' }); return true; }
24
+ if (url === '/account/sessions' && req.method === 'GET') {
25
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "frame-ancestors 'none'" });
26
+ res.end(require('./account-session-page').render()); return true;
27
+ }
28
+ if (url === '/api/account-transport') {
29
+ if (user.role !== 'admin') { ctx.http.reply(res, 403, { error: 'Administrator access required.' }); return true; }
30
+ if (req.method === 'GET') { ctx.http.reply(res, 200, ctx.transport.settings()); return true; }
31
+ if (req.method !== 'PUT') { ctx.http.reply(res, 405, { error: 'Method not allowed.' }); return true; }
32
+ ctx.http.read(req, res, async function (data) {
33
+ var admin = await verify(req, data, user);
34
+ if (admin.role !== 'admin') throw new Error('Administrator access required.');
35
+ var saved = ctx.transport.save(data); ctx.http.reply(res, 200, Object.assign({ ok: true }, saved));
36
+ }); return true;
37
+ }
38
+ if (req.method === 'GET') { ctx.http.reply(res, 200, { sessions: sessionList(req, user), maximumDays: 30, idleDays: 7 }); return true; }
39
+ if (req.method !== 'POST') { ctx.http.reply(res, 405, { error: 'Method not allowed.' }); return true; }
40
+ ctx.http.read(req, res, function (data) {
41
+ var active = ctx.getUser(req);
42
+ if (!active || active.id !== user.id) throw new Error('Sign in again to manage sessions.');
43
+ var current = ctx.sessions.get(ctx.sessionToken(req), false);
44
+ if (!current || typeof data.id !== 'string') throw new Error('Invalid session.');
45
+ if (data.id !== 'others' && !ctx.sessions.list(user.id).some(function (entry) { return entry.id === data.id; })) throw new Error('Session not found.');
46
+ ctx.sessions.revoke(user.id, data.id, current.id);
47
+ ctx.http.reply(res, 200, { ok: true, signedOut: data.id === current.id, sessions: sessionList(req, user) });
48
+ });
49
+ return true;
50
+ }
51
+ return { handleRequest: handleRequest };
52
+ }
53
+ module.exports = { attachAccountSecurity: attachAccountSecurity };
@@ -66,71 +66,54 @@ function attachAuth(ctx) {
66
66
  // --- Multi-user auth tokens (persisted to disk) ---
67
67
  var TOKENS_FILE = path.join(CONFIG_DIR, _isDevMode ? "auth-tokens-dev.json" : "auth-tokens.json");
68
68
  var MULTI_USER_COOKIE = _isDevMode ? "relay_auth_user_dev" : "relay_auth_user";
69
- var multiUserTokens = {};
70
-
71
- function loadTokens() {
72
- try {
73
- var raw = fs.readFileSync(TOKENS_FILE, "utf8");
74
- var data = JSON.parse(raw);
75
- if (data && typeof data === "object") {
76
- multiUserTokens = data;
77
- }
78
- } catch (e) {
79
- multiUserTokens = {};
80
- }
69
+ var accountPolicy = require('./account-auth-policy').attachPolicy(users);
70
+ var transport = require('./account-auth-transport').attachTransport({ users: users, tlsOptions: tlsOptions });
71
+ var sessionStore = require('./account-session-store').attachSessionStore({
72
+ file: TOKENS_FILE, managed: accountPolicy.available, clientAddress: transport.clientAddress,
73
+ });
74
+ var throttle = require('./account-auth-throttle').attachThrottle({
75
+ file: path.join(CONFIG_DIR, _isDevMode ? 'auth-attempts-dev.json' : 'auth-attempts.json'), clientAddress: transport.clientAddress,
76
+ });
77
+ function sessionToken(req) { return parseCookies(req)[MULTI_USER_COOKIE]; }
78
+ function createMultiUserSession(userId, credential, passkeyId, secure, req) {
79
+ var created = sessionStore.create(userId, credential, passkeyId, req, req && sessionToken(req));
80
+ var age = created.entry.expiresAt ? Math.max(0, Math.floor((created.entry.expiresAt - Date.now()) / 1000)) : 31536000;
81
+ var cookie = MULTI_USER_COOKIE + '=' + created.token + '; Path=/; HttpOnly; SameSite=Strict; Max-Age=' + age +
82
+ (tlsOptions || secure || req && transport.info(req).secure ? '; Secure' : '');
83
+ var rememberedCookie = rememberedAccounts.remember(userId, req);
84
+ return { token: created.token, cookie: cookie, cookies: rememberedCookie ? [cookie, rememberedCookie] : [cookie] };
81
85
  }
82
-
83
- function saveTokens() {
84
- try {
85
- fs.mkdirSync(path.dirname(TOKENS_FILE), { recursive: true });
86
- var tmpPath = TOKENS_FILE + ".tmp";
87
- fs.writeFileSync(tmpPath, JSON.stringify(multiUserTokens));
88
- fs.renameSync(tmpPath, TOKENS_FILE);
89
- } catch (e) {}
86
+ function validSessionUser(record) {
87
+ var user = record && users.findUserById(record.userId);
88
+ if (!user) return null;
89
+ if (record.passkeyId && (!require('./account-passkey-policy').configured(users.loadUsers()) ||
90
+ !(user.passkeys || []).some(function (key) { return key.id === record.passkeyId; }))) return null;
91
+ if (accountPolicy.requiresPassword(user) && (!user.passwordHash || user.mustChangePin ||
92
+ record.credentialVersion !== require('./account-session-store').digest(user.passwordHash))) return null;
93
+ return user;
90
94
  }
91
-
92
- loadTokens();
93
-
94
- function createMultiUserSession(userId) {
95
- var token = users.generateUserAuthToken(userId);
96
- multiUserTokens[token] = userId;
97
- saveTokens();
98
- var cookie = MULTI_USER_COOKIE + "=" + token + "; Path=/; HttpOnly; SameSite=Strict; Max-Age=31536000" + (tlsOptions ? "; Secure" : "");
99
- return { token: token, cookie: cookie };
100
- }
101
-
102
95
  function getMultiUserFromReq(req) {
103
- var cookies = parseCookies(req);
104
- var token = cookies[MULTI_USER_COOKIE];
105
- if (token) {
106
- var userId = multiUserTokens[token];
107
- if (userId) {
108
- var user = users.findUserById(userId);
109
- if (user) return user;
110
- }
96
+ if (accountPolicy.enabled() && !transport.allows(req, false)) return null;
97
+ var token = sessionToken(req);
98
+ var record = sessionStore.get(token, false);
99
+ var user = validSessionUser(record);
100
+ if (user) {
101
+ if (!req.claySessionPassive) sessionStore.get(token, true, req);
102
+ return user;
111
103
  }
112
- // Solo auto-login: exactly one user with no PIN => frictionless access, no
113
- // login wall. Mirrors the old single-user onramp once single-user mode is
114
- // absorbed into multi-user. Disabled the moment a PIN is set or a second
115
- // user is added (then the normal token/login flow applies).
116
- var solo = users.getSoloNoPinUser();
117
- if (solo) return solo;
118
- return null;
104
+ return users.getSoloNoPinUser() || null;
119
105
  }
120
-
121
- function isMultiUserAuthed(req) {
122
- return !!getMultiUserFromReq(req);
106
+ function touchSession(req) {
107
+ if (getMultiUserFromReq(req)) sessionStore.get(sessionToken(req), true, req);
123
108
  }
124
-
125
- function revokeUserTokens(userId) {
126
- var changed = false;
127
- for (var token in multiUserTokens) {
128
- if (multiUserTokens[token] === userId) {
129
- delete multiUserTokens[token];
130
- changed = true;
131
- }
109
+ function isMultiUserAuthed(req) { return !!getMultiUserFromReq(req); }
110
+ function revokeUserTokens(userId) { sessionStore.revokeUser(userId); }
111
+ function allowAttempt(req, res, username) {
112
+ try { throttle.consume(req, username); return true; }
113
+ catch (error) {
114
+ res.writeHead(error.status || 503, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
115
+ res.end(JSON.stringify({ error: error.message })); return false;
132
116
  }
133
- if (changed) saveTokens();
134
117
  }
135
118
 
136
119
  // --- PIN rate limiting (per-instance state) ---
@@ -163,7 +146,7 @@ function attachAuth(ctx) {
163
146
  var recovery = null;
164
147
 
165
148
  function setRecovery(urlPath, password) {
166
- recovery = { urlPath: urlPath, password: password };
149
+ recovery = { urlPath: urlPath, password: password, until: Date.now() + 15 * 60000 };
167
150
  }
168
151
 
169
152
  function clearRecovery() {
@@ -246,14 +229,11 @@ function attachAuth(ctx) {
246
229
  // --- Auth page selection ---
247
230
  var pinPage = pages.pinPageHtml();
248
231
  var adminSetupPage = pages.adminSetupPageHtml();
249
- var loginPage = pages.multiUserLoginPageHtml();
250
- var smtpLoginPage = pages.smtpLoginPageHtml();
251
232
 
252
233
  function getAuthPage() {
253
234
  if (!users.isMultiUser()) return pinPage;
254
235
  if (!users.hasAdmin()) return adminSetupPage;
255
- if (smtp.isEmailLoginEnabled()) return smtpLoginPage;
256
- return loginPage;
236
+ return require('./account-login-page').render({ password: accountPolicy.enabled(), email: !accountPolicy.enabled() && smtp.isEmailLoginEnabled() });
257
237
  }
258
238
 
259
239
  function isRequestAuthed(req) {
@@ -268,8 +248,22 @@ function attachAuth(ctx) {
268
248
  // --- Route handler ---
269
249
 
270
250
  function handleRequest(req, res, fullUrl) {
251
+ if (require('./account-login-page').handleAsset(req, res, fullUrl)) return true;
252
+ if (accountPolicy.enabled() && transport.info(req).secure && typeof res.setHeader === 'function') res.setHeader('Strict-Transport-Security', 'max-age=31536000');
253
+ if ((accountPolicy.enabled() || fullUrl === '/api/account-auth-policy' && req.method === 'PUT') && /^(?:\/auth\/(?!passkey-browser\.js)|\/api\/(?:account-auth-policy|passkey-policy|passkeys|account-sessions|account-transport|user\/pin|admin\/users|profile)|\/recover\/)/.test(fullUrl) &&
254
+ !transport.allows(req, ['GET', 'HEAD', 'OPTIONS'].indexOf(req.method) === -1)) {
255
+ res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
256
+ res.end(JSON.stringify({ error: 'Use HTTPS and the same Clay address for account requests. Reverse proxies must be explicitly configured.' })); return true;
257
+ }
258
+ if (rememberedAccounts.handleRequest(req, res, fullUrl)) return true;
259
+ if (accountSecurity.handleRequest(req, res, fullUrl)) return true;
260
+ if (accountPasskeys.handleRequest(req, res, fullUrl)) return true;
261
+ if (accountPasswords.handleRequest(req, res, fullUrl)) return true;
271
262
  // Admin password recovery
272
263
  if (recovery && fullUrl === "/recover/" + recovery.urlPath) {
264
+ if (recovery.until <= Date.now()) {
265
+ recovery = null; res.writeHead(410, { 'Content-Type': 'application/json' }); res.end('{"error":"Recovery expired. Enable a new recovery link from the server terminal."}'); return true;
266
+ }
273
267
  if (req.method === "GET") {
274
268
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
275
269
  res.end(recoveryPageHtml());
@@ -288,6 +282,8 @@ function attachAuth(ctx) {
288
282
  req.on("end", function () {
289
283
  try {
290
284
  var data = JSON.parse(body);
285
+ if (!allowAttempt(req, res, 'admin-recovery')) return;
286
+ if (!recovery || recovery.until <= Date.now()) throw new Error('Recovery expired.');
291
287
  if (data.step === "verify") {
292
288
  if (!data.password || data.password !== recovery.password) {
293
289
  recordPinFailure(ip);
@@ -315,7 +311,9 @@ function attachAuth(ctx) {
315
311
  res.end('{"error":"No admin account found"}');
316
312
  return;
317
313
  }
318
- users.updateUserPin(admin.id, data.pin);
314
+ var reset = users.updateUserPin(admin.id, data.pin);
315
+ if (!reset.ok) throw new Error('Could not reset the administrator account.');
316
+ revokeUserTokens(admin.id);
319
317
  recovery = null;
320
318
  res.writeHead(200, { "Content-Type": "application/json" });
321
319
  res.end('{"ok":true}');
@@ -334,6 +332,11 @@ function attachAuth(ctx) {
334
332
 
335
333
  // Global auth endpoint (single-user PIN)
336
334
  if (req.method === "POST" && req.url === "/auth") {
335
+ if (users.isMultiUser()) {
336
+ res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
337
+ res.end(JSON.stringify({ ok: false, error: 'Server PIN sign-in is unavailable. Sign in with your account.' }));
338
+ return true;
339
+ }
337
340
  var ip = req.socket.remoteAddress || "";
338
341
  var remaining = checkPinRateLimit(ip);
339
342
  if (remaining !== null) {
@@ -439,9 +442,9 @@ function attachAuth(ctx) {
439
442
  }
440
443
  }
441
444
  users.clearSetupCode();
442
- var session = createMultiUserSession(result.user.id);
445
+ var session = createMultiUserSession(result.user.id, null, null, false, req);
443
446
  res.writeHead(200, {
444
- "Set-Cookie": session.cookie,
447
+ "Set-Cookie": session.cookies,
445
448
  "Content-Type": "application/json",
446
449
  });
447
450
  res.end(JSON.stringify({ ok: true, user: { id: result.user.id, username: result.user.username, role: result.user.role } }));
@@ -472,6 +475,7 @@ function attachAuth(ctx) {
472
475
  req.on("end", function () {
473
476
  try {
474
477
  var data = JSON.parse(body);
478
+ if (!allowAttempt(req, res, data.username)) return;
475
479
  var user = users.authenticateUser(data.username, data.pin);
476
480
  if (!user) {
477
481
  recordPinFailure(ip);
@@ -481,11 +485,12 @@ function attachAuth(ctx) {
481
485
  return;
482
486
  }
483
487
  clearPinFailures(ip);
484
- var session = createMultiUserSession(user.id);
488
+ throttle.success(req, data.username);
489
+ var session = createMultiUserSession(user.id, null, null, false, req);
485
490
  var loginResp = { ok: true, user: { id: user.id, username: user.username, role: user.role } };
486
491
  if (user.mustChangePin) loginResp.mustChangePin = true;
487
492
  res.writeHead(200, {
488
- "Set-Cookie": session.cookie,
493
+ "Set-Cookie": session.cookies,
489
494
  "Content-Type": "application/json",
490
495
  });
491
496
  res.end(JSON.stringify(loginResp));
@@ -528,6 +533,7 @@ function attachAuth(ctx) {
528
533
  res.end('{"ok":true}');
529
534
  return;
530
535
  }
536
+ if (!allowAttempt(req, res, 'email:' + String(data.email).toLowerCase())) return;
531
537
  var result = smtp.requestOtp(data.email);
532
538
  if (result.error) {
533
539
  res.writeHead(429, { "Content-Type": "application/json" });
@@ -573,6 +579,7 @@ function attachAuth(ctx) {
573
579
  res.end('{"error":"Email and code are required"}');
574
580
  return;
575
581
  }
582
+ if (!allowAttempt(req, res, 'email:' + String(data.email).toLowerCase())) return;
576
583
  var otpResult = smtp.verifyOtp(data.email, data.code);
577
584
  if (!otpResult.valid) {
578
585
  recordPinFailure(ip);
@@ -587,9 +594,9 @@ function attachAuth(ctx) {
587
594
  return;
588
595
  }
589
596
  clearPinFailures(ip);
590
- var session = createMultiUserSession(user.id);
597
+ var session = createMultiUserSession(user.id, null, null, false, req);
591
598
  res.writeHead(200, {
592
- "Set-Cookie": session.cookie,
599
+ "Set-Cookie": session.cookies,
593
600
  "Content-Type": "application/json",
594
601
  });
595
602
  res.end(JSON.stringify({ ok: true, user: { id: user.id, username: user.username, role: user.role } }));
@@ -625,7 +632,7 @@ function attachAuth(ctx) {
625
632
  return;
626
633
  }
627
634
  var result;
628
- if (smtp.isEmailLoginEnabled() && !data.pin) {
635
+ if (smtp.isEmailLoginEnabled() && !data.pin && !accountPasswords.policy.enabled()) {
629
636
  // SMTP mode: username + email required, no PIN
630
637
  if (!data.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
631
638
  res.writeHead(400, { "Content-Type": "application/json" });
@@ -667,9 +674,9 @@ function attachAuth(ctx) {
667
674
  }
668
675
  }
669
676
  users.markInviteUsed(data.inviteCode);
670
- var session = createMultiUserSession(result.user.id);
677
+ var session = createMultiUserSession(result.user.id, null, null, false, req);
671
678
  res.writeHead(200, {
672
- "Set-Cookie": session.cookie,
679
+ "Set-Cookie": session.cookies,
673
680
  "Content-Type": "application/json",
674
681
  });
675
682
  res.end(JSON.stringify({ ok: true, user: { id: result.user.id, username: result.user.username, role: result.user.role } }));
@@ -686,17 +693,16 @@ function attachAuth(ctx) {
686
693
  if (users.isMultiUser()) {
687
694
  var cookies = parseCookies(req);
688
695
  var token = cookies[MULTI_USER_COOKIE];
689
- if (token && multiUserTokens[token]) {
690
- delete multiUserTokens[token];
691
- saveTokens();
696
+ try { sessionStore.revokeToken(token); } catch (error) {
697
+ res.writeHead(503, { 'Content-Type': 'application/json' }); res.end('{"error":"Could not persist sign-out. Please retry."}'); return true;
692
698
  }
693
699
  res.writeHead(200, {
694
- "Set-Cookie": MULTI_USER_COOKIE + "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" + (tlsOptions ? "; Secure" : ""),
700
+ "Set-Cookie": MULTI_USER_COOKIE + "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" + (tlsOptions || transport.info(req).secure ? "; Secure" : ""),
695
701
  "Content-Type": "application/json",
696
702
  });
697
703
  } else {
698
704
  res.writeHead(200, {
699
- "Set-Cookie": "relay_auth=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" + (tlsOptions ? "; Secure" : ""),
705
+ "Set-Cookie": "relay_auth=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" + (tlsOptions || transport.info(req).secure ? "; Secure" : ""),
700
706
  "Content-Type": "application/json",
701
707
  });
702
708
  }
@@ -722,14 +728,36 @@ function attachAuth(ctx) {
722
728
  return true;
723
729
  }
724
730
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
725
- res.end(smtp.isEmailLoginEnabled() ? pages.smtpInvitePageHtml(inviteCode) : pages.invitePageHtml(inviteCode));
731
+ res.end(smtp.isEmailLoginEnabled() && !accountPasswords.policy.enabled() ? pages.smtpInvitePageHtml(inviteCode) : pages.invitePageHtml(inviteCode));
726
732
  return true;
727
733
  }
728
734
 
729
735
  return false;
730
736
  }
731
737
 
738
+ var accountPasswords = require('./server-account-passwords').attachAccountPasswords({
739
+ users: users, devMode: _isDevMode, tlsOptions: tlsOptions, parseCookies: parseCookies,
740
+ getUser: getMultiUserFromReq, createSession: createMultiUserSession, revokeSessions: revokeUserTokens,
741
+ onPolicyChanged: ctx.onAccountPolicyChanged, throttle: throttle, transport: transport,
742
+ });
743
+ var accountPasskeys = require('./server-account-passkeys').attachAccountPasskeys({
744
+ users: users, devMode: _isDevMode, parseCookies: parseCookies, http: accountPasswords.http,
745
+ getUser: getMultiUserFromReq, createSession: createMultiUserSession,
746
+ sessionToken: sessionToken, clientAddress: transport.clientAddress,
747
+ });
748
+
749
+ var rememberedAccounts = require('./account-remembered').attachRemembered({
750
+ users: users, devMode: _isDevMode, parseCookies: parseCookies, transport: transport,
751
+ file: path.join(CONFIG_DIR, _isDevMode ? 'remembered-accounts-dev.json' : 'remembered-accounts.json'), read: accountPasswords.http.read,
752
+ });
753
+
754
+ var accountSecurity = require('./server-account-security').attachAccountSecurity({
755
+ users: users, getUser: getMultiUserFromReq, sessionToken: sessionToken, sessions: sessionStore,
756
+ validSessionUser: validSessionUser, http: accountPasswords.http, transport: transport,
757
+ });
758
+
732
759
  return {
760
+ touchSession: touchSession,
733
761
  handleRequest: handleRequest,
734
762
  getMultiUserFromReq: getMultiUserFromReq,
735
763
  isRequestAuthed: isRequestAuthed,
@@ -418,7 +418,7 @@ function attachHomeChat(deps) {
418
418
  return sessionReferenceValue;
419
419
  }
420
420
 
421
- function handleMessage(ws, msg) {
421
+ function handleMessage(ws, msg, routedProjectSlug) {
422
422
  if (!msg || typeof msg.type !== "string") return false;
423
423
  if (msg.type === "home_mate_stop" || msg.type === "home_mate_permission_response") {
424
424
  var controlUserId = ws._clayUser ? ws._clayUser.id : null;
@@ -477,8 +477,8 @@ function attachHomeChat(deps) {
477
477
  if (msg.type === "issue_reference_resolve") { resolveIssueLink(ws, msg); return true; }
478
478
  if (homeDebates.handle(ws, userId, msg)) return true;
479
479
  if (msg.type === "home_clay_ask") { homeClayEntry.start(ws, userId, msg); return true; }
480
- if (msg.type === "home_clay_session_resolve") { homeClaySessionLinks.resolve(ws, msg); return true; }
481
- if (msg.type === "home_clay_log_resolve") { homeClaySessionLinks.resolveLog(ws, msg); return true; }
480
+ if (msg.type === "home_clay_session_resolve") { homeClaySessionLinks.resolve(ws, msg, routedProjectSlug); return true; }
481
+ if (msg.type === "home_clay_log_resolve") { homeClaySessionLinks.resolveLog(ws, msg, routedProjectSlug); return true; }
482
482
 
483
483
  if (msg.type === "home_mate_debate_plan") {
484
484
  homeDebate.start(ws, userId, msg);
@@ -2,23 +2,31 @@
2
2
  // owner-bound source session.
3
3
 
4
4
  function attachHomeClaySessionLinks(ctx) {
5
- function source(ws, msg) {
5
+ function source(ws, msg, routedProjectSlug) {
6
6
  var tap = msg.surface === "search" ? ws._searchClayTap : ws._homeChatTap;
7
+ if (!tap && routedProjectSlug) {
8
+ var routedProject = ctx.projects.get(routedProjectSlug);
9
+ var routedManager = routedProject && routedProject.getSessionManager ? routedProject.getSessionManager() : null;
10
+ var routedSession = routedManager && ws._clayActiveSession ? routedManager.sessions.get(ws._clayActiveSession) : null;
11
+ return { tap: { mateSlug: routedProjectSlug, sessionId: ws._clayActiveSession }, project: routedProject, session: routedSession };
12
+ }
7
13
  var sourceProject = tap && tap.mateSlug ? ctx.projects.get(tap.mateSlug) : null;
8
14
  var sourceManager = sourceProject && sourceProject.getSessionManager ? sourceProject.getSessionManager() : null;
9
15
  var sourceSession = sourceManager && tap ? sourceManager.sessions.get(tap.sessionId) : null;
10
16
  return { tap: tap, project: sourceProject, session: sourceSession };
11
17
  }
12
18
 
13
- function resolve(ws, msg) {
14
- var selected = source(ws, msg);
15
- var bound = ctx.workspaceQueryService && selected.session
16
- ? ctx.workspaceQueryService.bindProjectSession({ projectSlug: selected.tap.mateSlug, session: selected.session })
17
- : null;
19
+ function resolve(ws, msg, routedProjectSlug) {
20
+ var selected = source(ws, msg, routedProjectSlug);
18
21
  var payload = { type: "home_clay_session_target", requestId: msg.requestId || null, sessionRef: msg.sessionRef || null, status: "error" };
19
22
  try {
23
+ var binding = selected.session ? { projectSlug: selected.tap.mateSlug, session: selected.session } : null;
24
+ if (binding && ws && ws._clayUser) binding.viewerId = ws._clayUser.id;
25
+ var bound = ctx.workspaceQueryService && binding
26
+ ? ctx.workspaceQueryService.bindProjectSession(binding)
27
+ : null;
20
28
  if (!bound) throw new Error("The source conversation is no longer available.");
21
- payload.target = bound.resolveSessionNavigation({ sessionRef: msg.sessionRef });
29
+ payload.target = bound.resolveSessionNavigation({ sessionRef: msg.sessionRef, entryIndex: msg.entryIndex });
22
30
  payload.status = "ready";
23
31
  } catch (error) {
24
32
  payload.error = error.message || "Session not available.";
@@ -26,8 +34,8 @@ function attachHomeClaySessionLinks(ctx) {
26
34
  ctx.sendMessage(ws, payload);
27
35
  }
28
36
 
29
- function resolveLog(ws, msg) {
30
- var selected = source(ws, msg);
37
+ function resolveLog(ws, msg, routedProjectSlug) {
38
+ var selected = source(ws, msg, routedProjectSlug);
31
39
  var status = selected.project && selected.project.getStatus ? selected.project.getStatus() : null;
32
40
  var bound = ctx.projectLogsService && selected.session && status
33
41
  ? ctx.projectLogsService.bindMate({
@@ -56,6 +56,7 @@ function attachSettings(ctx) {
56
56
  profile.userId = mu.id;
57
57
  profile.role = mu.role;
58
58
  profile.pinEnabled = !!mu.pinHash;
59
+ profile.passwordEnabled = !!mu.passwordHash;
59
60
  profile.autoContinueOnRateLimit = !!mu.autoContinueOnRateLimit;
60
61
  profile.chatLayout = mu.chatLayout || "channel";
61
62
  profile.projectMateFilterMode = users.getProjectMateFilterMode(mu.id);
@@ -395,7 +396,7 @@ function attachSettings(ctx) {
395
396
  res.end('{"error":"Current PIN is required"}');
396
397
  return;
397
398
  }
398
- if (mu.pinHash !== users.hashPin(data.currentPin)) {
399
+ if (!users.verifyPin(data.currentPin, mu.pinHash, mu)) {
399
400
  res.writeHead(400, { "Content-Type": "application/json" });
400
401
  res.end('{"error":"Current PIN is incorrect"}');
401
402
  return;
package/lib/server.js CHANGED
@@ -1182,6 +1182,7 @@ function createServer(opts) {
1182
1182
  }
1183
1183
  var globalUser = users.isMultiUser() ? getMultiUserFromReq(req) : null;
1184
1184
  wss.handleUpgrade(req, socket, head, function (ws) {
1185
+ if (!require('./account-auth-socket').guardSocket(ws, req, isRequestAuthed, auth.touchSession)) return;
1185
1186
  ws._clayPane = wsRequest.pane;
1186
1187
  ws._clayPaneSession = wsRequest.paneSession;
1187
1188
  globalWs.handleConnection(ws, globalUser);
@@ -1223,6 +1224,7 @@ function createServer(opts) {
1223
1224
  }
1224
1225
 
1225
1226
  wss.handleUpgrade(req, socket, head, function (ws) {
1227
+ if (!require('./account-auth-socket').guardSocket(ws, req, isRequestAuthed, auth.touchSession)) return;
1226
1228
  // Apply rate limiting to WS messages
1227
1229
  applyWsRateLimit(ws, WS_RATE_LIMIT);
1228
1230
  ws._clayUser = wsUser; // attach user context
@@ -1628,7 +1630,7 @@ function createServer(opts) {
1628
1630
  if (dmHandler.handleMessage(ws, msg)) return true;
1629
1631
  if (mateHandler && mateHandler.handleMessage(ws, msg)) return true;
1630
1632
  if (emailHandler.handleMessage(ws, msg)) return true;
1631
- if (homeChatHandler.handleMessage(ws, msg)) return true;
1633
+ if (homeChatHandler.handleMessage(ws, msg, routedProjectSlug)) return true;
1632
1634
  if (homePreferencesHandler.handleMessage(ws, msg)) return true;
1633
1635
  if (toolsHandler.handleMessage(ws, msg)) return true;
1634
1636
  return false;
package/lib/sessions.js CHANGED
@@ -864,7 +864,9 @@ function createSessionManager(opts) {
864
864
  if (_item && (_item.type === "mention_user" || _item.type === "mention_response")) {
865
865
  console.log("[DEBUG replayHistory] sending mention at index=" + i + " from=" + fromIndex + " total=" + total + " type=" + _item.type + " mate=" + (_item.mateName || ""));
866
866
  }
867
- _send(transform ? transform(_item) : _item);
867
+ var replayItem = transform ? transform(_item) : _item;
868
+ if (replayItem && typeof replayItem === "object") replayItem = Object.assign({}, replayItem, { _historyIndex: i });
869
+ _send(replayItem);
868
870
  }
869
871
 
870
872
  // Find the last result message in the full history for accurate context data