@clagentic/console 1.0.4 → 1.1.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.
package/lib/audit.js ADDED
@@ -0,0 +1,57 @@
1
+ // audit.js — Append-only audit log for privileged actions.
2
+ // Writes JSON lines to ~/.clagentic/audit.log (mode 0o600).
3
+ // Never throws into callers: all errors are logged to stderr only.
4
+
5
+ var fs = require("fs");
6
+ var path = require("path");
7
+ var config = require("./config");
8
+
9
+ var AUDIT_LOG_PATH = path.join(config.CONFIG_DIR, "audit.log");
10
+ var _logFd = null;
11
+
12
+ function _getLogFd() {
13
+ if (_logFd !== null) return _logFd;
14
+ try {
15
+ _logFd = fs.openSync(AUDIT_LOG_PATH, "a", 0o600);
16
+ // Enforce mode on existing files — openSync mode flag may not apply when the file already exists.
17
+ try { fs.chmodSync(AUDIT_LOG_PATH, 0o600); } catch (_) {}
18
+ } catch (e) {
19
+ console.error("[audit] Failed to open audit log:", e.message);
20
+ }
21
+ return _logFd;
22
+ }
23
+
24
+ /**
25
+ * Log a privileged action.
26
+ *
27
+ * @param {string} action Action identifier, e.g. "user.create", "auth.lockout"
28
+ * @param {object} ctx Optional context fields:
29
+ * actorId {string} ID of the user performing the action (or "system")
30
+ * actorName {string} Username of the actor
31
+ * target {string} ID of the affected user/resource
32
+ * metadata {object} Additional non-secret metadata (never log passwords/tokens/PINs)
33
+ */
34
+ function log(action, ctx) {
35
+ ctx = ctx || {};
36
+ var entry = {
37
+ ts: new Date().toISOString(),
38
+ action: action,
39
+ actorId: ctx.actorId || null,
40
+ actorName: ctx.actorName || null,
41
+ target: ctx.target || null,
42
+ metadata: ctx.metadata || null,
43
+ };
44
+ var line = JSON.stringify(entry) + "\n";
45
+ // Non-blocking: defer write so callers are never stalled by I/O.
46
+ setImmediate(function () {
47
+ var fd = _getLogFd();
48
+ if (!fd) return;
49
+ try {
50
+ fs.writeSync(fd, line);
51
+ } catch (e) {
52
+ console.error("[audit] Failed to write audit entry:", e.message);
53
+ }
54
+ });
55
+ }
56
+
57
+ module.exports = { log: log };
package/lib/config.js CHANGED
@@ -3,6 +3,7 @@ var path = require("path");
3
3
  var os = require("os");
4
4
  var net = require("net");
5
5
  var execFileSync = require("child_process").execFileSync;
6
+ var _store = null; // lazy to avoid circular-require at module load time
6
7
 
7
8
  function isSafeSystemUserName(name) {
8
9
  return typeof name === "string" && /^[a-z_][a-z0-9_-]*[$]?$/.test(name);
@@ -99,12 +100,13 @@ function loadConfig() {
99
100
  }
100
101
 
101
102
  function saveConfig(config) {
103
+ // Async atomic write through store.js (queued per path, 0o600). Fire-and-forget.
104
+ // The daemon.json path varies by dev mode, so we use writeJsonAt with the full path.
102
105
  ensureConfigDir();
103
- var tmpPath = configPath() + ".tmp";
104
- fs.writeFileSync(tmpPath, JSON.stringify(config, null, 2));
105
- chmodSafe(tmpPath, 0o600);
106
- fs.renameSync(tmpPath, configPath());
107
- chmodSafe(configPath(), 0o600);
106
+ if (!_store) _store = require("./store");
107
+ _store.writeJsonAt(configPath(), config).catch(function (err) {
108
+ process.stderr.write("[config] saveConfig failed: " + (err && err.message ? err.message : err) + "\n");
109
+ });
108
110
  }
109
111
 
110
112
  function isPidAlive(pid) {
@@ -171,16 +173,14 @@ function generateSlug(projectPath, existingSlugs) {
171
173
  }
172
174
 
173
175
  function clearStaleConfig() {
174
- // Clear pid from config instead of deleting the file (preserves project settings)
176
+ // Clear pid from config instead of deleting the file (preserves project settings).
177
+ // Write via store.js (async, queued, 0o600). Fire-and-forget.
175
178
  try {
176
179
  var data = fs.readFileSync(configPath(), "utf8");
177
180
  var cfg = JSON.parse(data);
178
181
  cfg.pid = null;
179
- var tmpPath = configPath() + ".tmp";
180
- fs.writeFileSync(tmpPath, JSON.stringify(cfg, null, 2));
181
- chmodSafe(tmpPath, 0o600);
182
- fs.renameSync(tmpPath, configPath());
183
- chmodSafe(configPath(), 0o600);
182
+ if (!_store) _store = require("./store");
183
+ _store.writeJsonAt(configPath(), cfg).catch(function () {});
184
184
  } catch (e) {}
185
185
  if (process.platform !== "win32") {
186
186
  try { fs.unlinkSync(socketPath()); } catch (e) {}
package/lib/os-users.js CHANGED
@@ -5,6 +5,7 @@ var fs = require("fs");
5
5
  var path = require("path");
6
6
  var execFileSync = require("child_process").execFileSync;
7
7
  var _aclGrantCache = Object.create(null);
8
+ var audit = require("./audit");
8
9
 
9
10
  function aclCacheKey(projectPath, linuxUser) {
10
11
  return path.resolve(projectPath) + "::" + linuxUser;
@@ -407,6 +408,10 @@ function provisionLinuxUser(clayUsername) {
407
408
  ensureLinger(linuxName);
408
409
  console.log("[os-users] Provisioned Linux user: " + linuxName + " (Clay user: " + clayUsername + ")");
409
410
  installClaudeCli(linuxName);
411
+ audit.log("osuser.create", {
412
+ actorId: "system",
413
+ metadata: { clayUsername: clayUsername, linuxUser: linuxName },
414
+ });
410
415
  return { ok: true, linuxUser: linuxName };
411
416
  } catch (e) {
412
417
  var msg = (e.stderr || e.message || "").trim();
@@ -24,6 +24,7 @@ function attachConnection(ctx) {
24
24
  var osUsers = ctx.osUsers;
25
25
  var debug = ctx.debug;
26
26
  var dangerouslySkipPermissions = ctx.dangerouslySkipPermissions;
27
+ var dangerouslySkipPermissionsConfigured = ctx.dangerouslySkipPermissionsConfigured || false;
27
28
  var currentVersion = ctx.currentVersion;
28
29
  var lanHost = ctx.lanHost;
29
30
  var sm = ctx.sm;
@@ -128,7 +129,13 @@ function attachConnection(ctx) {
128
129
  var restoredActive = restoredState.active;
129
130
  var initialVendor = (restoredActive && restoredActive.vendor) || sm.defaultVendor || "claude";
130
131
  var initialModels = (sm.modelsByVendor && sm.modelsByVendor[initialVendor]) || sm.availableModels || [];
131
- sendTo(ws, { type: "info", cwd: cwd, slug: slug, project: title || project, version: currentVersion, debug: !!debug, dangerouslySkipPermissions: dangerouslySkipPermissions, osUsers: osUsers, lanHost: lanHost, projectCount: _filteredProjects.length, projects: _filteredProjects, projectOwnerId: projectOwnerId, ownerLocked: ownerLocked });
132
+ var infoMsg = { type: "info", cwd: cwd, slug: slug, project: title || project, version: currentVersion, debug: !!debug, dangerouslySkipPermissions: dangerouslySkipPermissions, osUsers: osUsers, lanHost: lanHost, projectCount: _filteredProjects.length, projects: _filteredProjects, projectOwnerId: projectOwnerId, ownerLocked: ownerLocked };
133
+ // When dangerouslySkipPermissions is set in config but suppressed because
134
+ // multi-user mode is active, tell the client so it can surface a warning.
135
+ if (dangerouslySkipPermissionsConfigured && !dangerouslySkipPermissions) {
136
+ infoMsg.dangerouslySkipPermissionsBlocked = true;
137
+ }
138
+ sendTo(ws, infoMsg);
132
139
  // Update notifications are pushed on a scheduled interval (see
133
140
  // scheduleUpdateBroadcast). We no longer push on connect to avoid
134
141
  // re-triggering the banner on every page refresh.
@@ -140,7 +147,7 @@ function attachConnection(ctx) {
140
147
  }
141
148
  sendTo(ws, { type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
142
149
  sendTo(ws, Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
143
- sendTo(ws, { type: "term_list", terminals: tm.list() });
150
+ sendTo(ws, { type: "term_list", terminals: tm.list(ws) });
144
151
  // Context sources sent after session is resolved (per-session storage)
145
152
  sendTo(ws, { type: "notes_list", notes: nm.list() });
146
153
  sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules() });
@@ -164,6 +171,9 @@ function attachConnection(ctx) {
164
171
  if (!active) {
165
172
  var autoOpts = {};
166
173
  if (wsUser && usersModule.isMultiUser()) autoOpts.ownerId = wsUser.id;
174
+ // TODO(lr-f311): defer createSession until first user message — every
175
+ // network blip or browser reload creates an empty session file here.
176
+ // The reconnect/presence path is subtle; fix deferred to a follow-up PR.
167
177
  active = sm.createSession(autoOpts, ws);
168
178
  autoCreated = true;
169
179
  }
@@ -3,6 +3,8 @@ var path = require("path");
3
3
  var crypto = require("crypto");
4
4
  var { execFileSync } = require("child_process");
5
5
  var { createLoopRegistry } = require("./scheduler");
6
+ var store = require("./store");
7
+ var usersModule = require("./users");
6
8
 
7
9
  /**
8
10
  * Attach loop engine to a project context.
@@ -65,26 +67,22 @@ function attachLoop(ctx) {
65
67
  var _loopStatePath = path.join(_loopDir, _loopEncodedCwd + ".json");
66
68
 
67
69
  function saveLoopState() {
68
- try {
69
- fs.mkdirSync(_loopDir, { recursive: true });
70
- var data = {
71
- phase: loopState.phase,
72
- active: loopState.active,
73
- iteration: loopState.iteration,
74
- maxIterations: loopState.maxIterations,
75
- baseCommit: loopState.baseCommit,
76
- results: loopState.results,
77
- wizardData: loopState.wizardData,
78
- startedAt: loopState.startedAt,
79
- loopId: loopState.loopId,
80
- loopFilesId: loopState.loopFilesId || null,
81
- };
82
- var tmpPath = _loopStatePath + ".tmp";
83
- fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2));
84
- fs.renameSync(tmpPath, _loopStatePath);
85
- } catch (e) {
86
- console.error("[ralph-loop] Failed to save state:", e.message);
87
- }
70
+ // Async atomic write through store.js (queued per path, 0o600). Fire-and-forget.
71
+ var data = {
72
+ phase: loopState.phase,
73
+ active: loopState.active,
74
+ iteration: loopState.iteration,
75
+ maxIterations: loopState.maxIterations,
76
+ baseCommit: loopState.baseCommit,
77
+ results: loopState.results,
78
+ wizardData: loopState.wizardData,
79
+ startedAt: loopState.startedAt,
80
+ loopId: loopState.loopId,
81
+ loopFilesId: loopState.loopFilesId || null,
82
+ };
83
+ store.writeJsonAt(_loopStatePath, data).catch(function (err) {
84
+ console.error("[ralph-loop] Failed to save state:", err && err.message ? err.message : err);
85
+ });
88
86
  }
89
87
 
90
88
  function loadLoopState() {
@@ -653,12 +651,15 @@ function attachLoop(ctx) {
653
651
  function finishLoop(reason) {
654
652
  console.log("[ralph-loop] finishLoop called, reason: " + reason + ", iteration: " + loopState.iteration);
655
653
 
656
- // Unlock the last coder session so users can continue interacting with it
654
+ // Unlock the last coder session so users can continue interacting with it.
655
+ // Capture owner before clearing state so push routing still works.
656
+ var _loopOwnerUserId = null;
657
657
  if (loopState.currentSessionId) {
658
658
  var lastCoderSession = sm.sessions.get(loopState.currentSessionId);
659
659
  if (lastCoderSession) {
660
660
  lastCoderSession.singleTurn = false;
661
661
  lastCoderSession.loop.active = false;
662
+ _loopOwnerUserId = lastCoderSession.ownerId || null;
662
663
  }
663
664
  }
664
665
 
@@ -695,9 +696,15 @@ function attachLoop(ctx) {
695
696
  : reason === "max_iterations"
696
697
  ? "Reached max iterations (" + loopState.maxIterations + ")"
697
698
  : reason === "stopped" ? "Stopped by user" : "Ended due to error";
698
- pushModule.sendPush({
699
+ var _loopDonePayload = {
699
700
  type: "done", slug: slug, title: "Loop Complete", body: _finishBody, tag: "ralph-loop-done",
700
- });
701
+ };
702
+ // Route to loop session owner only — body carries iteration status.
703
+ if (usersModule.isMultiUser() && _loopOwnerUserId && pushModule.sendPushToUser) {
704
+ pushModule.sendPushToUser(_loopOwnerUserId, _loopDonePayload);
705
+ } else {
706
+ pushModule.sendPush(_loopDonePayload);
707
+ }
701
708
  }
702
709
 
703
710
  if (notificationsModule) {
@@ -112,6 +112,7 @@ function attachNotifications(ctx) {
112
112
  var broadcastAll = ctx.broadcastAll;
113
113
  var sendToUser = ctx.sendToUser || null; // (userId, msg) -> void; iterates all project clients
114
114
  var pushModule = ctx.pushModule;
115
+ var isMultiUser = ctx.isMultiUser || function () { return false; };
115
116
 
116
117
  var notifications = loadNotifications();
117
118
  var reminderTimer = null;
@@ -207,6 +208,10 @@ function attachNotifications(ctx) {
207
208
  function startReminder() {
208
209
  if (reminderTimer) return;
209
210
  reminderTimer = setInterval(function () {
211
+ // In multi-user mode, skip the broadcast reminder push.
212
+ // The body (unread count) is per-project state that would leak to all
213
+ // push subscribers regardless of which user owns the notifications.
214
+ if (isMultiUser()) return;
210
215
  var count = getUnreadCount();
211
216
  if (count > 0 && pushModule) {
212
217
  pushModule.sendPush({
@@ -70,6 +70,22 @@ function attachUserMessage(ctx) {
70
70
 
71
71
  var adapter = ctx.adapter;
72
72
 
73
+ // --------------- Terminal list broadcast ---------------
74
+
75
+ // In multi-user mode each client only sees their own terminals, so we
76
+ // send filtered term_list messages individually instead of broadcasting one.
77
+ function broadcastTermList() {
78
+ if (usersModule.isMultiUser()) {
79
+ for (var bws of clients) {
80
+ if (bws.readyState === 1) {
81
+ sendTo(bws, { type: "term_list", terminals: tm.list(bws) });
82
+ }
83
+ }
84
+ } else {
85
+ send({ type: "term_list", terminals: tm.list() });
86
+ }
87
+ }
88
+
73
89
  // --------------- Sticky notes ---------------
74
90
 
75
91
  function syncNotesKnowledge() {
@@ -135,13 +151,18 @@ function attachUserMessage(ctx) {
135
151
  return true;
136
152
  }
137
153
  tm.attach(t.id, ws);
138
- send({ type: "term_list", terminals: tm.list() });
154
+ broadcastTermList();
139
155
  sendTo(ws, { type: "term_created", id: t.id });
140
156
  return true;
141
157
  }
142
158
 
143
159
  if (msg.type === "term_attach") {
144
- if (msg.id) tm.attach(msg.id, ws);
160
+ if (msg.id) {
161
+ var attached = tm.attach(msg.id, ws);
162
+ if (!attached) {
163
+ sendTo(ws, { type: "term_error", error: "Terminal not found or access denied" });
164
+ }
165
+ }
145
166
  return true;
146
167
  }
147
168
 
@@ -151,7 +172,7 @@ function attachUserMessage(ctx) {
151
172
  }
152
173
 
153
174
  if (msg.type === "term_input") {
154
- if (msg.id) tm.write(msg.id, msg.data);
175
+ if (msg.id) tm.write(msg.id, msg.data, ws);
155
176
  return true;
156
177
  }
157
178
 
@@ -164,8 +185,8 @@ function attachUserMessage(ctx) {
164
185
 
165
186
  if (msg.type === "term_close") {
166
187
  if (msg.id) {
167
- tm.close(msg.id);
168
- send({ type: "term_list", terminals: tm.list() });
188
+ tm.close(msg.id, ws);
189
+ broadcastTermList();
169
190
  // Remove closed terminal from context sources
170
191
  var _termSessionId = ws._clayActiveSession || null;
171
192
  var saved = loadContextSources(slug, _termSessionId);
@@ -181,8 +202,8 @@ function attachUserMessage(ctx) {
181
202
 
182
203
  if (msg.type === "term_rename") {
183
204
  if (msg.id && msg.title) {
184
- tm.rename(msg.id, msg.title);
185
- send({ type: "term_list", terminals: tm.list() });
205
+ tm.rename(msg.id, msg.title, ws);
206
+ broadcastTermList();
186
207
  }
187
208
  return true;
188
209
  }
@@ -190,6 +211,14 @@ function attachUserMessage(ctx) {
190
211
  // --- Context Sources ---
191
212
  if (msg.type === "context_sources_save") {
192
213
  var activeIds = msg.active || [];
214
+ // In multi-user mode, strip any term:N IDs the caller does not own.
215
+ // This prevents User B from saving A's terminal into their context and
216
+ // reading A's scrollback on the next message via getScrollback.
217
+ activeIds = activeIds.filter(function(srcId) {
218
+ if (!srcId.startsWith("term:")) return true;
219
+ var tid = parseInt(srcId.split(":")[1], 10);
220
+ return tm.getScrollback(tid, ws) !== null;
221
+ });
193
222
  var _saveSessionId = ws._clayActiveSession || null;
194
223
  saveContextSources(slug, _saveSessionId, activeIds);
195
224
  return true;
@@ -367,7 +396,7 @@ function attachUserMessage(ctx) {
367
396
  var srcId = ctxSources[ci];
368
397
  if (srcId.startsWith("term:")) {
369
398
  var termId = parseInt(srcId.split(":")[1], 10);
370
- var sb = tm.getScrollback(termId);
399
+ var sb = tm.getScrollback(termId, ws);
371
400
  if (sb) {
372
401
  var lastCursor;
373
402
  if (termId in session._termContextCursors) {
@@ -418,7 +447,7 @@ function attachUserMessage(ctx) {
418
447
  }
419
448
  var delta = lines.join("").trim();
420
449
  if (!delta) continue;
421
- var termInfo = tm.list().find(function(t) { return t.id === termId; });
450
+ var termInfo = tm.list(ws).find(function(t) { return t.id === termId; });
422
451
  var termTitle = termInfo ? termInfo.title : "Terminal " + termId;
423
452
  var header;
424
453
  if (delta.length > TERM_CONTEXT_MAX) {
package/lib/project.js CHANGED
@@ -135,7 +135,13 @@ function createProjectContext(opts) {
135
135
  var preferredAgent = opts.preferredAgent || null;
136
136
  var pushModule = opts.pushModule || null;
137
137
  var debug = opts.debug || false;
138
- var dangerouslySkipPermissions = opts.dangerouslySkipPermissions || false;
138
+ // dangerouslySkipPermissions is a global bypass that disables tool-call approval
139
+ // for EVERY user in the daemon. In multi-user mode this is unsafe: an admin enabling
140
+ // it for convenience removes approval gates for all users simultaneously.
141
+ // We hard-disable it when multi-user mode is active so the per-user permission
142
+ // model remains intact. Admins who want bypassPermissions must do so per-session.
143
+ var dangerouslySkipPermissionsConfigured = opts.dangerouslySkipPermissions || false;
144
+ var dangerouslySkipPermissions = dangerouslySkipPermissionsConfigured && !usersModule.isMultiUser();
139
145
  var currentVersion = opts.currentVersion;
140
146
  var lanHost = opts.lanHost || null;
141
147
  var getProjectCount = opts.getProjectCount || function () { return 1; };
@@ -589,7 +595,24 @@ function createProjectContext(opts) {
589
595
  var resumeLoop = _loop.resumeLoop;
590
596
 
591
597
  // --- Terminal manager ---
592
- var tm = createTerminalManager({ cwd: cwd, send: send, sendTo: sendTo });
598
+ // broadcastTermList sends each connected client only the terminals they own.
599
+ // In single-user mode the terminal manager falls back to the bare send() broadcast,
600
+ // so this closure is only exercised when isMultiUser() is true at startup.
601
+ var tm;
602
+ function broadcastTermListToAll() {
603
+ for (var bws of clients) {
604
+ if (bws.readyState === 1) {
605
+ sendTo(bws, { type: "term_list", terminals: tm.list(bws) });
606
+ }
607
+ }
608
+ }
609
+ tm = createTerminalManager({
610
+ cwd: cwd,
611
+ send: send,
612
+ sendTo: sendTo,
613
+ isMultiUser: usersModule.isMultiUser(),
614
+ broadcastTermList: usersModule.isMultiUser() ? broadcastTermListToAll : null,
615
+ });
593
616
  var nm = createNotesManager({ cwd: cwd, send: send, sendTo: sendTo });
594
617
 
595
618
  // Update checks disabled — this is a fork, not a chadbyte/clay release track.
@@ -1079,6 +1102,7 @@ function createProjectContext(opts) {
1079
1102
  osUsers: osUsers,
1080
1103
  debug: debug,
1081
1104
  dangerouslySkipPermissions: dangerouslySkipPermissions,
1105
+ dangerouslySkipPermissionsConfigured: dangerouslySkipPermissionsConfigured,
1082
1106
  currentVersion: currentVersion,
1083
1107
  lanHost: lanHost,
1084
1108
  sm: sm,
package/lib/public/app.js CHANGED
@@ -5,7 +5,7 @@ import { renderMarkdown, highlightCodeBlocks, renderMermaidBlocks, closeMermaidM
5
5
  import { initSidebar, updatePageTitle, spawnDustParticles } from './modules/sidebar.js';
6
6
  import {
7
7
  renderSessionList, handleSearchResults, updateSessionPresence,
8
- updateSessionBadge, populateCliSessionList
8
+ updateSessionBadge, populateCliSessionList, resetSessionList
9
9
  } from './modules/sidebar-sessions.js';
10
10
  import {
11
11
  renderIconStrip, updateProjectBadge
@@ -59,7 +59,7 @@ import { initLoopWizard, openRalphWizard as _loopOpenRalphWizard, closeRalphWiza
59
59
  import { initAppNotifications, handleNotificationsState as _notifHandleState, handleNotificationCreated as _notifHandleCreated, handleNotificationDismissed as _notifHandleDismissed, handleNotificationDismissedAll as _notifHandleDismissedAll } from './modules/app-notifications.js';
60
60
  import { createStore, store } from './modules/store.js';
61
61
  import { initPanels, updateConfigChip as _panUpdateConfigChip, getModelEffortLevels as _panGetModelEffortLevels, accumulateUsage as _panAccumulateUsage, updateUsagePanel as _panUpdateUsagePanel, resetUsage as _panResetUsage, toggleUsagePanel as _panToggleUsagePanel, formatTokens as _panFormatTokens, updateStatusPanel as _panUpdateStatusPanel, requestProcessStats as _panRequestProcessStats, toggleStatusPanel as _panToggleStatusPanel, accumulateContext as _panAccumulateContext, updateContextPanel as _panUpdateContextPanel, resetContext as _panResetContext, resetContextData as _panResetContextData, minimizeContext as _panMinimizeContext, expandContext as _panExpandContext, toggleContextPanel as _panToggleContextPanel, getContextView as _panGetContextView, renderCtxPopover as _panRenderCtxPopover, hideCtxPopover as _panHideCtxPopover, formatBytes as _panFormatBytes, formatUptime as _panFormatUptime, getModelSupportsEffort as _panGetModelSupportsEffort, getSessionUsage, setSessionUsage, getContextData, setContextData, setContextView as _panSetContextView, applyContextView as _panApplyContextView } from './modules/app-panels.js';
62
- import { initProjects, onProjectListUpdated, updateProjectList as _projUpdateProjectList, renderProjectList as _projRenderProjectList, renderTopbarPresence as _projRenderTopbarPresence, switchProject as _projSwitchProject, resetClientState as _projResetClientState, confirmRemoveProject as _projConfirmRemoveProject, handleRemoveProjectCheckResult as _projHandleRemoveProjectCheckResult, handleRemoveProjectResult as _projHandleRemoveProjectResult, openAddProjectModal as _projOpenAddProjectModal, closeAddProjectModal as _projCloseAddProjectModal, handleBrowseDirResult as _projHandleBrowseDirResult, handleAddProjectResult as _projHandleAddProjectResult, handleCloneProgress as _projHandleCloneProgress, showUpdateAvailable as _projShowUpdateAvailable, getCachedProjects, setCachedProjects, getCachedProjectCount, getCachedRemovedProjects, setCachedRemovedProjects } from './modules/app-projects.js';
62
+ import { initProjects, onProjectListUpdated, onResetClientState, updateProjectList as _projUpdateProjectList, renderProjectList as _projRenderProjectList, renderTopbarPresence as _projRenderTopbarPresence, switchProject as _projSwitchProject, resetClientState as _projResetClientState, confirmRemoveProject as _projConfirmRemoveProject, handleRemoveProjectCheckResult as _projHandleRemoveProjectCheckResult, handleRemoveProjectResult as _projHandleRemoveProjectResult, openAddProjectModal as _projOpenAddProjectModal, closeAddProjectModal as _projCloseAddProjectModal, handleBrowseDirResult as _projHandleBrowseDirResult, handleAddProjectResult as _projHandleAddProjectResult, handleCloneProgress as _projHandleCloneProgress, showUpdateAvailable as _projShowUpdateAvailable, getCachedProjects, setCachedProjects, getCachedProjectCount, getCachedRemovedProjects, setCachedRemovedProjects } from './modules/app-projects.js';
63
63
  import { initRendering, addToMessages as _renAddToMessages, scrollToBottom as _renScrollToBottom, forceScrollToBottom as _renForceScrollToBottom, addUserMessage as _renAddUserMessage, getMsgTime as _renGetMsgTime, shouldGroupMessage as _renShouldGroupMessage, ensureAssistantBlock as _renEnsureAssistantBlock, addCopyHandler as _renAddCopyHandler, appendDelta as _renAppendDelta, flushStreamBuffer as _renFlushStreamBuffer, finalizeAssistantBlock as _renFinalizeAssistantBlock, addSystemMessage as _renAddSystemMessage, addConflictMessage as _renAddConflictMessage, addContextOverflowMessage as _renAddContextOverflowMessage, showClaudePreThinking as _renShowClaudePreThinking, showSuggestionChips as _renShowSuggestionChips, hideSuggestionChips as _renHideSuggestionChips, getGhostSuggestion as _renGetGhostSuggestion, getTurnCounter, setTurnCounter, getPrependAnchor, setPrependAnchor, getActivityEl, setActivityEl, getIsUserScrolledUp, setIsUserScrolledUp, getStickyBottom, armStickyBottom, disarmStickyBottom } from './modules/app-rendering.js';
64
64
  import { initDm, openDm as _dmOpenDm, enterDmMode as _dmEnterDmMode, exitDmMode as _dmExitDmMode, appendDmMessage as _dmAppendDmMessage, showDmTypingIndicator as _dmShowDmTypingIndicator, handleDmSend as _dmHandleDmSend } from './modules/app-dm.js';
65
65
  import { initMention, handleMentionStart, handleMentionStream, handleMentionDone, handleMentionError, handleMentionActivity, renderMentionUser, renderMentionResponse } from './modules/mention.js';
@@ -1006,6 +1006,7 @@ import { initMention, handleMentionStart, handleMentionStream, handleMentionDone
1006
1006
  // --- Projects module ---
1007
1007
  initProjects();
1008
1008
  onProjectListUpdated(function (projects) { updateMobileProjectsTabBadge(projects); });
1009
+ onResetClientState(function () { resetSessionList(); });
1009
1010
 
1010
1011
  // --- Home Hub module ---
1011
1012
  initHomeHub();
@@ -207,6 +207,14 @@ export function processMessage(msg) {
207
207
  var spBanner = document.getElementById("skip-perms-pill");
208
208
  if (spBanner) spBanner.classList.remove("hidden");
209
209
  }
210
+ if (msg.dangerouslySkipPermissionsBlocked) {
211
+ // The server config has dangerouslySkipPermissions=true but it is disabled
212
+ // because multi-user mode is active. Warn admins so they know the config
213
+ // flag has no effect and remove it to avoid confusion.
214
+ if (store.get('isMultiUserMode') && store.get('permissions') && store.get('permissions').projectSettings !== false) {
215
+ showToast("dangerouslySkipPermissions is set in config but is disabled in multi-user mode. All users have normal tool-approval rules.", "warn");
216
+ }
217
+ }
210
218
  updateProjectList(msg);
211
219
  break;
212
220
 
@@ -33,6 +33,9 @@ import { closeSessionInfoPopover } from './app-header.js';
33
33
  var _onProjectListUpdated = null;
34
34
  export function onProjectListUpdated(fn) { _onProjectListUpdated = fn; }
35
35
 
36
+ var _onResetClientState = null;
37
+ export function onResetClientState(fn) { _onResetClientState = fn; }
38
+
36
39
  var cachedProjects = [];
37
40
  var cachedProjectCount = 0;
38
41
  var cachedRemovedProjects = [];
@@ -423,6 +426,10 @@ export function resetClientState() {
423
426
  // Clear vendor state so the incoming model_info for the new project is never
424
427
  // blocked by a lock that was set during the previous project's session.
425
428
  store.set({ currentVendor: null, vendorSelectionLocked: false, codexApproval: null, codexSandbox: null, codexWebSearch: null });
429
+ // Clear the session list immediately so the sidebar doesn't show the previous
430
+ // project's sessions while waiting for the new project's session_list from
431
+ // the server. Resets the fingerprint too so the incoming list is never skipped.
432
+ if (typeof _onResetClientState === "function") _onResetClientState();
426
433
  }
427
434
 
428
435
  export function switchProject(slug) {
@@ -181,7 +181,7 @@ export function renderMermaidBlocks(el) {
181
181
 
182
182
  try {
183
183
  mermaid.render(id, source.trim()).then(function (result) {
184
- container.innerHTML = result.svg;
184
+ container.innerHTML = DOMPurify.sanitize(result.svg, { USE_PROFILES: { svg: true, svgFilters: true } });
185
185
  container.addEventListener("click", function () {
186
186
  showMermaidModal(container.innerHTML);
187
187
  });
@@ -238,7 +238,10 @@ export function showMermaidModal(svgHtml) {
238
238
  var modal = document.getElementById("mermaid-modal");
239
239
  var body = document.getElementById("mermaid-modal-body");
240
240
  if (!modal || !body) return;
241
- body.innerHTML = svgHtml;
241
+ // svgHtml originates from container.innerHTML after mermaid render — sanitize
242
+ // defensively here too since showMermaidModal is also exported and callable
243
+ // from other paths.
244
+ body.innerHTML = DOMPurify.sanitize(svgHtml, { USE_PROFILES: { svg: true, svgFilters: true } });
242
245
  modal.classList.remove("hidden");
243
246
  refreshIcons();
244
247
 
@@ -37,7 +37,7 @@ import {
37
37
  import { store } from './store.js';
38
38
  import { getWs } from './ws-ref.js';
39
39
  import { dismissOverlayPanels, closeSidebar } from './sidebar.js';
40
- import { switchProject, getCachedProjects } from './app-projects.js';
40
+ import { switchProject, getCachedProjects, openAddProjectModal } from './app-projects.js';
41
41
  import { openDm } from './app-dm.js';
42
42
  import { showHomeHub } from './app-home-hub.js';
43
43
  import { openTerminal } from './terminal.js';
@@ -131,8 +131,7 @@ function renderSheetProjects(listEl) {
131
131
  addBtn.addEventListener("click", function () {
132
132
  closeMobileSheet();
133
133
  setTimeout(function () {
134
- var btn = document.getElementById("add-project-btn");
135
- if (btn) btn.click();
134
+ openAddProjectModal();
136
135
  }, 250);
137
136
  });
138
137
  header.appendChild(addBtn);
@@ -582,6 +582,15 @@ export function getCachedSessions() {
582
582
  return cachedSessions;
583
583
  }
584
584
 
585
+ // Called by resetClientState() on project switch. Clears the cached session
586
+ // list and resets the fingerprint so the next session_list from the new
587
+ // project is always rendered (never skipped by the fingerprint guard).
588
+ export function resetSessionList() {
589
+ cachedSessions = [];
590
+ _sessionListFingerprint = "";
591
+ renderSessionList(null);
592
+ }
593
+
585
594
  export function getSearchQuery() {
586
595
  return searchQuery;
587
596
  }
package/lib/push.js CHANGED
@@ -2,24 +2,24 @@ var webpush = require("web-push");
2
2
  var fs = require("fs");
3
3
  var path = require("path");
4
4
  var config = require("./config");
5
+ var store = require("./store");
5
6
 
6
7
  function loadOrCreateVapidKeys() {
7
8
  var dir = config.CONFIG_DIR;
8
9
  var keyFile = path.join(dir, "vapid.json");
9
10
 
11
+ // Synchronous read at startup so initPush() can return keys immediately.
10
12
  try {
11
13
  var data = fs.readFileSync(keyFile, "utf8");
12
14
  return JSON.parse(data);
13
15
  } catch (e) {
14
- // Generate new keys
16
+ // Generate new keys and write via store.js (async, 0o600).
15
17
  }
16
18
 
17
19
  var keys = webpush.generateVAPIDKeys();
18
- fs.mkdirSync(dir, { recursive: true });
19
- fs.writeFileSync(keyFile, JSON.stringify(keys, null, 2));
20
- if (process.platform !== "win32") {
21
- try { fs.chmodSync(keyFile, 0o600); } catch (e) {}
22
- }
20
+ store.writeJson("vapid.json", keys).catch(function (err) {
21
+ process.stderr.write("[push] Failed to write vapid.json: " + (err && err.message ? err.message : err) + "\n");
22
+ });
23
23
  return keys;
24
24
  }
25
25
 
@@ -36,7 +36,7 @@ function initPush() {
36
36
  var subFile = path.join(dir, "push-subs.json");
37
37
  var subscriptions = new Map();
38
38
 
39
- // Load persisted subscriptions, but clear if VAPID key changed
39
+ // Load persisted subscriptions synchronously at startup; writes go through store.js.
40
40
  try {
41
41
  var saved = JSON.parse(fs.readFileSync(subFile, "utf8"));
42
42
  if (saved.vapidKey && saved.vapidKey !== keys.publicKey) {
@@ -51,15 +51,13 @@ function initPush() {
51
51
  } catch (e) {}
52
52
 
53
53
  function save() {
54
- try {
55
- fs.writeFileSync(subFile, JSON.stringify({
56
- vapidKey: keys.publicKey,
57
- subs: [...subscriptions.values()],
58
- }));
59
- if (process.platform !== "win32") {
60
- try { fs.chmodSync(subFile, 0o600); } catch (e2) {}
61
- }
62
- } catch (e) {}
54
+ // Async atomic write through store.js (queued, 0o600). Fire-and-forget.
55
+ store.writeJson("push-subs.json", {
56
+ vapidKey: keys.publicKey,
57
+ subs: Array.from(subscriptions.values()),
58
+ }).catch(function (err) {
59
+ process.stderr.write("[push] save failed: " + (err && err.message ? err.message : err) + "\n");
60
+ });
63
61
  }
64
62
 
65
63
  save();