clay-server 5.1.0 → 5.2.0-beta.1

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 (48) 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-server-settings.js +1 -0
  17. package/lib/project-user-knowledge.js +2 -1
  18. package/lib/public/auth/account-login.css +98 -0
  19. package/lib/public/auth/account-login.js +104 -0
  20. package/lib/public/css/mate-conversation.css +2 -2
  21. package/lib/public/css/user-settings-sessions.css +42 -0
  22. package/lib/public/index.html +17 -5
  23. package/lib/public/modules/account-auth-settings.js +71 -0
  24. package/lib/public/modules/account-transport-settings.js +51 -0
  25. package/lib/public/modules/app-messages.js +4 -0
  26. package/lib/public/modules/passkey-browser.js +69 -0
  27. package/lib/public/modules/passkey-server-settings.js +57 -0
  28. package/lib/public/modules/project-logs-render.js +3 -2
  29. package/lib/public/modules/server-settings-controls.js +10 -0
  30. package/lib/public/modules/server-settings.js +7 -2
  31. package/lib/public/modules/user-settings-account.js +14 -1
  32. package/lib/public/modules/user-settings-sessions.js +120 -0
  33. package/lib/public/modules/user-settings.js +3 -0
  34. package/lib/public/modules/you-activity.js +3 -1
  35. package/lib/public/modules/you.js +91 -6
  36. package/lib/public/style.css +1 -0
  37. package/lib/server-account-passkeys.js +186 -0
  38. package/lib/server-account-passwords.js +127 -0
  39. package/lib/server-account-security.js +53 -0
  40. package/lib/server-auth.js +107 -79
  41. package/lib/server-settings.js +2 -1
  42. package/lib/server.js +2 -0
  43. package/lib/user-knowledge-service.js +23 -1
  44. package/lib/users-auth.js +38 -3
  45. package/lib/users-create.js +97 -0
  46. package/lib/users-server-pin.js +37 -0
  47. package/lib/users.js +11 -84
  48. package/package.json +2 -1
@@ -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,
@@ -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
@@ -22,6 +22,7 @@ function attachUserKnowledgeService(deps) {
22
22
  if (record.seen) result.seen[record.seen.ref] = Math.max(result.seen[record.seen.ref] || 0, record.seen.revision);
23
23
  if (record.entry) result.entries[record.entry.ref] = record.entry;
24
24
  if (record.report) result.reports[record.report.ref] = record.report;
25
+ (Array.isArray(record.reports) ? record.reports : []).forEach(function (report) { result.reports[report.ref] = report; });
25
26
  if (record.activity) result.activity.push(record.activity);
26
27
  });
27
28
  return result;
@@ -73,6 +74,26 @@ function attachUserKnowledgeService(deps) {
73
74
  });
74
75
  return Object.assign({}, entry, { comments: comments, commentCount: comments.length });
75
76
  }
77
+ function remove(id,args) {
78
+ var state = snapshot(id);
79
+ var previous = state.entries[args.ref];
80
+ if (!previous || previous.archived || previous.deleted) throw new Error('User knowledge not found.');
81
+ if (!Number.isInteger(args.expectedRevision) || args.expectedRevision !== previous.revisions) throw new Error('Knowledge changed. Read it again before deleting.');
82
+ var now = Date.now();
83
+ var entry = Object.assign({}, previous, { archived: true, deleted: true, deletedAt: now, updatedAt: now,
84
+ revisions: previous.revisions + 1, updatedBy: { type: 'user', displayName: 'You' }, reason: 'Deleted by the account owner.' });
85
+ var reports = Object.values(state.reports).filter(function (report) {
86
+ return report.status === 'pending' && (report.entryRef === previous.ref || report.commentEntryRef === previous.ref);
87
+ });
88
+ var reportUpdates = reports.map(function (report) { return Object.assign({}, report, {
89
+ status: 'declined', reviewedAt: now, reason: 'The knowledge entry was deleted by the account owner.'
90
+ }); });
91
+ var activity = { id: crypto.randomBytes(12).toString('hex'), ref: previous.ref, title: previous.title,
92
+ summary: previous.summary, at: now, action: 'delete', revision: entry.revisions, deleted: true };
93
+ storage(id).append({ kind: 'user-knowledge', entry: entry, reports: reportUpdates, activity: activity });
94
+ try { deps.onChange(owner(id), activity); } catch (error) { /* The deletion survives notification failures. */ }
95
+ return { entry: entry, activity: activity };
96
+ }
76
97
  function comment(id,args,source) {
77
98
  var entry = read(id,args.ref);
78
99
  return report(id,{observation:args.body,evidence:'Comment on '+entry.ref+': '+args.body,evidenceType:'explicit'},source,entry.ref);
@@ -141,6 +162,7 @@ function attachUserKnowledgeService(deps) {
141
162
  var reason=text(args.reason,2000,true);
142
163
  var previous=args.ref ? state.entries[args.ref]:null;
143
164
  if (args.ref && !previous) throw new Error('User knowledge not found.');
165
+ if (previous && (previous.archived || previous.deleted)) throw new Error('User knowledge not found.');
144
166
  if (previous && args.expectedRevision!==previous.revisions) throw new Error('Knowledge changed. Read it again before updating.');
145
167
  var entry=null;
146
168
  var now=Date.now();
@@ -162,6 +184,6 @@ function attachUserKnowledgeService(deps) {
162
184
  }
163
185
  };
164
186
  }
165
- return {bind:bind,list:list,read:read,report:report,comment:comment,attention:attention,acknowledge:acknowledge,activity:function(id,args){return page(snapshot(id).activity.slice().reverse(),args);},pendingCount:function(id){return Object.values(snapshot(id).reports).filter(function(r){return r.status==='pending';}).length;}};
187
+ return {bind:bind,list:list,read:read,remove:remove,report:report,comment:comment,attention:attention,acknowledge:acknowledge,activity:function(id,args){return page(snapshot(id).activity.slice().reverse(),args);},pendingCount:function(id){return Object.values(snapshot(id).reports).filter(function(r){return r.status==='pending';}).length;}};
166
188
  }
167
189
  module.exports={attachUserKnowledgeService:attachUserKnowledgeService};
package/lib/users-auth.js CHANGED
@@ -1,4 +1,5 @@
1
1
  var crypto = require("crypto");
2
+ var serverPin = require('./users-server-pin');
2
3
 
3
4
  function attachAuth(deps) {
4
5
  var loadUsers = deps.loadUsers;
@@ -80,7 +81,29 @@ function attachAuth(deps) {
80
81
  // --- Pin hashing ---
81
82
 
82
83
  function hashPin(pin) {
83
- return crypto.createHash("sha256").update("clay-user:" + pin).digest("hex");
84
+ var salt = crypto.randomBytes(16).toString("hex");
85
+ var hash = crypto.scryptSync("clay-user:" + pin, salt, 64, { N: 16384, r: 8, p: 1 }).toString("hex");
86
+ return "scrypt-v1:" + salt + ":" + hash;
87
+ }
88
+
89
+ function verifyPin(pin, storedHash, user) {
90
+ // Older JSON clients could submit a numeric PIN; preserve that spelling.
91
+ if (typeof pin === "number" && Number.isSafeInteger(pin) && pin >= 0) pin = String(pin);
92
+ if (typeof pin !== "string" || typeof storedHash !== "string") return false;
93
+ var migratedHash = serverPin.resolve(storedHash, user, deps.loadConfig);
94
+ if (migratedHash) return serverPin.verify(pin, migratedHash);
95
+ var expected;
96
+ var actual;
97
+ if (/^[a-f0-9]{64}$/.test(storedHash)) {
98
+ expected = Buffer.from(storedHash, "hex");
99
+ actual = crypto.createHash("sha256").update("clay-user:" + pin).digest();
100
+ } else {
101
+ var parts = /^scrypt-v1:([a-f0-9]{32}):([a-f0-9]{128})$/.exec(storedHash);
102
+ if (!parts) return false;
103
+ expected = Buffer.from(parts[2], "hex");
104
+ actual = crypto.scryptSync("clay-user:" + pin, parts[1], 64, { N: 16384, r: 8, p: 1 });
105
+ }
106
+ return crypto.timingSafeEqual(actual, expected);
84
107
  }
85
108
 
86
109
  // Generate a random 6-digit PIN
@@ -96,6 +119,7 @@ function attachAuth(deps) {
96
119
  // --- Authentication ---
97
120
 
98
121
  function authenticateUser(username, pin) {
122
+ if (typeof username !== "string") return null;
99
123
  var data = loadUsers();
100
124
  var user = null;
101
125
  for (var i = 0; i < data.users.length; i++) {
@@ -105,8 +129,18 @@ function attachAuth(deps) {
105
129
  }
106
130
  }
107
131
  if (!user) return null;
108
- var pinH = hashPin(pin);
109
- if (user.pinHash !== pinH) return null;
132
+ if (!verifyPin(pin, user.pinHash, user)) return null;
133
+ if (user.pinHash.indexOf('scrypt-v1:') !== 0) {
134
+ var previousHash = user.pinHash;
135
+ try {
136
+ user.pinHash = hashPin(pin);
137
+ saveUsers(data);
138
+ } catch (e) {
139
+ // A best-effort upgrade must never reject a verified existing PIN.
140
+ user.pinHash = previousHash;
141
+ console.error("[users] PIN hash upgrade could not be saved; it will be retried on login.");
142
+ }
143
+ }
110
144
  return user;
111
145
  }
112
146
 
@@ -136,6 +170,7 @@ function attachAuth(deps) {
136
170
  clearSetupCode: clearSetupCode,
137
171
  validateSetupCode: validateSetupCode,
138
172
  hashPin: hashPin,
173
+ verifyPin: verifyPin,
139
174
  generatePin: generatePin,
140
175
  authenticateUser: authenticateUser,
141
176
  generateUserAuthToken: generateUserAuthToken,
@@ -0,0 +1,97 @@
1
+ var crypto = require("crypto");
2
+ var serverPin = require("./users-server-pin");
3
+
4
+ function attachCreation(deps) {
5
+ var loadUsers = deps.loadUsers;
6
+ var saveUsers = deps.saveUsers;
7
+ var generateUserId = deps.generateUserId;
8
+ var ensureUserBuiltinMates = deps.ensureUserBuiltinMates;
9
+ var auth = deps.auth;
10
+
11
+ function createUser(opts) {
12
+ var data = loadUsers();
13
+ // Check username uniqueness
14
+ for (var i = 0; i < data.users.length; i++) {
15
+ if (data.users[i].username.toLowerCase() === opts.username.toLowerCase()) {
16
+ return { error: "This username is already taken" };
17
+ }
18
+ }
19
+ // Check email uniqueness (when provided)
20
+ if (opts.email) {
21
+ for (var i = 0; i < data.users.length; i++) {
22
+ if (data.users[i].email && data.users[i].email.toLowerCase() === opts.email.toLowerCase()) {
23
+ return { error: "This email is already registered" };
24
+ }
25
+ }
26
+ }
27
+ var user = {
28
+ id: generateUserId(),
29
+ username: opts.username,
30
+ email: opts.email || null,
31
+ displayName: opts.displayName || opts.username,
32
+ pinHash: auth.hashPin(opts.pin),
33
+ role: opts.role || "user",
34
+ mustChangePin: !!opts.mustChangePin,
35
+ createdAt: Date.now(),
36
+ linuxUser: opts.linuxUser || null,
37
+ profile: opts.profile || {
38
+ name: opts.displayName || opts.username,
39
+ lang: "en-US",
40
+ avatarColor: "#5857fc",
41
+ avatarStyle: "imprint",
42
+ avatarSeed: crypto.randomBytes(4).toString("hex"),
43
+ },
44
+ };
45
+ data.users.push(user);
46
+ saveUsers(data);
47
+
48
+ // Seed immediately for ordinary multi-user storage. OS-user provisioning
49
+ // calls this again after the Linux mapping exists, targeting its final home.
50
+ ensureUserBuiltinMates(user.id);
51
+
52
+ return { ok: true, user: user };
53
+ }
54
+
55
+ function createUserWithoutPin(opts, migration) {
56
+ var data = loadUsers();
57
+ for (var i = 0; i < data.users.length; i++) {
58
+ if (data.users[i].username.toLowerCase() === opts.username.toLowerCase()) {
59
+ return { error: "This username is already taken" };
60
+ }
61
+ }
62
+ if (opts.email) {
63
+ for (var i = 0; i < data.users.length; i++) {
64
+ if (data.users[i].email && data.users[i].email.toLowerCase() === opts.email.toLowerCase()) {
65
+ return { error: "This email is already registered" };
66
+ }
67
+ }
68
+ }
69
+ var user = {
70
+ id: generateUserId(),
71
+ username: opts.username,
72
+ email: opts.email || null,
73
+ displayName: opts.displayName || opts.username,
74
+ pinHash: migration && migration.pinHash ? serverPin.tag(migration.pinHash) : null,
75
+ role: opts.role || "user",
76
+ createdAt: Date.now(),
77
+ profile: opts.profile || {
78
+ name: opts.displayName || opts.username,
79
+ lang: "en-US",
80
+ avatarColor: "#5857fc",
81
+ avatarStyle: "imprint",
82
+ avatarSeed: crypto.randomBytes(4).toString("hex"),
83
+ },
84
+ };
85
+ data.users.push(user);
86
+ if (migration) { data.multiUser = true; data.setupCode = null; }
87
+ saveUsers(data);
88
+
89
+ ensureUserBuiltinMates(user.id);
90
+
91
+ return { ok: true, user: user };
92
+ }
93
+
94
+ return { createUser: createUser, createUserWithoutPin: createUserWithoutPin };
95
+ }
96
+
97
+ module.exports = { attachCreation: attachCreation };
@@ -0,0 +1,37 @@
1
+ var crypto = require('crypto');
2
+ var PREFIX = 'server-pin-v1:';
3
+
4
+ function isServerHash(hash) {
5
+ return typeof hash === 'string' && (/^[a-f0-9]{64}$/.test(hash) || /^[a-f0-9]{32}:[a-f0-9]{128}$/.test(hash));
6
+ }
7
+
8
+ function tag(hash) {
9
+ if (!isServerHash(hash)) throw new Error('Invalid legacy server PIN hash');
10
+ return PREFIX + hash;
11
+ }
12
+
13
+ function resolve(hash, user, loadConfig) {
14
+ if (typeof hash !== 'string') return null;
15
+ if (hash.indexOf(PREFIX) === 0) {
16
+ var original = hash.slice(PREFIX.length);
17
+ return isServerHash(original) ? original : null;
18
+ }
19
+ if (!user || !isServerHash(hash) || typeof loadConfig !== 'function') return null;
20
+ // Only the recorded migrated owner may use an untagged server credential.
21
+ var config;
22
+ try { config = loadConfig(); } catch (e) { return null; }
23
+ if (config && config.singleUserMigratedAt && config.singleUserMigratedUserId === user.id && config.pinHash === hash) return hash;
24
+ return null;
25
+ }
26
+
27
+ function verify(pin, hash) {
28
+ if (!isServerHash(hash)) return false;
29
+ var parts = hash.split(':');
30
+ var expected = Buffer.from(parts.length === 2 ? parts[1] : hash, 'hex');
31
+ var actual = parts.length === 2
32
+ ? crypto.scryptSync('clay:' + pin, parts[0], 64)
33
+ : crypto.createHash('sha256').update('clay:' + pin).digest();
34
+ return crypto.timingSafeEqual(actual, expected);
35
+ }
36
+
37
+ module.exports = { tag: tag, resolve: resolve, verify: verify };