@clagentic/console 1.0.4 → 1.0.5-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/config.js +11 -11
- package/lib/project-connection.js +9 -2
- package/lib/project-loop.js +30 -23
- package/lib/project-notifications.js +5 -0
- package/lib/project-user-message.js +38 -9
- package/lib/project.js +26 -2
- package/lib/public/modules/app-messages.js +8 -0
- package/lib/public/modules/sidebar-mobile.js +2 -3
- package/lib/push.js +14 -16
- package/lib/sdk-bridge.js +19 -4
- package/lib/sdk-message-processor.js +16 -4
- package/lib/sdk-message-queue.js +6 -8
- package/lib/sdk-worker.js +34 -11
- package/lib/server-auth.js +9 -8
- package/lib/server.js +1 -0
- package/lib/store.js +137 -0
- package/lib/terminal-manager.js +56 -11
- package/lib/users.js +11 -4
- package/lib/yoke/adapters/claude-worker.js +34 -11
- package/package.json +1 -1
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
-
|
|
180
|
-
|
|
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) {}
|
|
@@ -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
|
-
|
|
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() });
|
package/lib/project-loop.js
CHANGED
|
@@ -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
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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)
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
@@ -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
|
|
|
@@ -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
|
-
|
|
135
|
-
if (btn) btn.click();
|
|
134
|
+
openAddProjectModal();
|
|
136
135
|
}, 250);
|
|
137
136
|
});
|
|
138
137
|
header.appendChild(addBtn);
|
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
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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
|
|
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
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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();
|
package/lib/sdk-bridge.js
CHANGED
|
@@ -369,13 +369,19 @@ function createSDKBridge(opts) {
|
|
|
369
369
|
});
|
|
370
370
|
|
|
371
371
|
if (pushModule) {
|
|
372
|
-
|
|
372
|
+
var _elicitPayload = {
|
|
373
373
|
type: "elicitation",
|
|
374
374
|
slug: slug,
|
|
375
375
|
title: (request.serverName || "MCP Server") + " needs input",
|
|
376
376
|
body: request.message || "Waiting for your response",
|
|
377
377
|
tag: "claude-elicitation",
|
|
378
|
-
}
|
|
378
|
+
};
|
|
379
|
+
// Route to session owner only — body carries MCP message text.
|
|
380
|
+
if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
|
|
381
|
+
pushModule.sendPushToUser(session.ownerId, _elicitPayload);
|
|
382
|
+
} else {
|
|
383
|
+
pushModule.sendPush(_elicitPayload);
|
|
384
|
+
}
|
|
379
385
|
}
|
|
380
386
|
|
|
381
387
|
if (opts.signal) {
|
|
@@ -619,13 +625,19 @@ function createSDKBridge(opts) {
|
|
|
619
625
|
onProcessingChanged(); // update cross-project permission badge
|
|
620
626
|
|
|
621
627
|
if (pushModule) {
|
|
622
|
-
|
|
628
|
+
var _permPayload = {
|
|
623
629
|
type: "permission_request",
|
|
624
630
|
slug: slug,
|
|
625
631
|
requestId: requestId,
|
|
626
632
|
title: permissionPushTitle(toolName, input),
|
|
627
633
|
body: permissionPushBody(toolName, input),
|
|
628
|
-
}
|
|
634
|
+
};
|
|
635
|
+
// Route to session owner only — body carries tool name and input (may contain paths/code).
|
|
636
|
+
if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
|
|
637
|
+
pushModule.sendPushToUser(session.ownerId, _permPayload);
|
|
638
|
+
} else {
|
|
639
|
+
pushModule.sendPush(_permPayload);
|
|
640
|
+
}
|
|
629
641
|
}
|
|
630
642
|
|
|
631
643
|
var _nm = getNotificationsModule();
|
|
@@ -1343,6 +1355,9 @@ function createSDKBridge(opts) {
|
|
|
1343
1355
|
|
|
1344
1356
|
session.lastActivityAt = Date.now();
|
|
1345
1357
|
session.streamPromise = processQueryStream(session).catch(function(err) {
|
|
1358
|
+
console.error("[sdk-bridge] Unhandled stream error for session " + session.localId + ":", err && err.message || err);
|
|
1359
|
+
sendToSession(session, { type: "error", text: "Stream error: " + (err && err.message || String(err)) });
|
|
1360
|
+
sendToSession(session, { type: "done", code: 1 });
|
|
1346
1361
|
});
|
|
1347
1362
|
}
|
|
1348
1363
|
|
|
@@ -278,13 +278,19 @@ function attachMessageProcessor(ctx) {
|
|
|
278
278
|
|
|
279
279
|
if (pushModule && block.name === "AskUserQuestion" && input.questions) {
|
|
280
280
|
var q = input.questions[0];
|
|
281
|
-
|
|
281
|
+
var _askPayload = {
|
|
282
282
|
type: "ask_user",
|
|
283
283
|
slug: slug,
|
|
284
284
|
title: "Claude has a question",
|
|
285
285
|
body: q ? q.question : "Waiting for your response",
|
|
286
286
|
tag: "claude-ask",
|
|
287
|
-
}
|
|
287
|
+
};
|
|
288
|
+
// Route to session owner only — content carries prompt text.
|
|
289
|
+
if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
|
|
290
|
+
pushModule.sendPushToUser(session.ownerId, _askPayload);
|
|
291
|
+
} else {
|
|
292
|
+
pushModule.sendPush(_askPayload);
|
|
293
|
+
}
|
|
288
294
|
}
|
|
289
295
|
} else if (block && block.type === "thinking") {
|
|
290
296
|
var duration = block.startTime ? (Date.now() - block.startTime) / 1000 : 0;
|
|
@@ -500,13 +506,19 @@ function attachMessageProcessor(ctx) {
|
|
|
500
506
|
var _doneTitle = session.title || "Claude";
|
|
501
507
|
|
|
502
508
|
if (pushModule) {
|
|
503
|
-
|
|
509
|
+
var _donePayload = {
|
|
504
510
|
type: "done",
|
|
505
511
|
slug: slug,
|
|
506
512
|
title: _doneTitle,
|
|
507
513
|
body: _donePreviewText || "Response ready",
|
|
508
514
|
tag: "claude-done",
|
|
509
|
-
}
|
|
515
|
+
};
|
|
516
|
+
// Route to session owner only — body carries response preview text.
|
|
517
|
+
if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
|
|
518
|
+
pushModule.sendPushToUser(session.ownerId, _donePayload);
|
|
519
|
+
} else {
|
|
520
|
+
pushModule.sendPush(_donePayload);
|
|
521
|
+
}
|
|
510
522
|
}
|
|
511
523
|
|
|
512
524
|
var _nm = getNotificationsModule();
|
package/lib/sdk-message-queue.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
// Async message queue for streaming input to SDK
|
|
2
2
|
function createMessageQueue() {
|
|
3
3
|
var queue = [];
|
|
4
|
-
var
|
|
4
|
+
var waitingResolvers = [];
|
|
5
5
|
var ended = false;
|
|
6
6
|
return {
|
|
7
7
|
push: function(msg) {
|
|
8
|
-
if (
|
|
9
|
-
var resolve =
|
|
10
|
-
waiting = null;
|
|
8
|
+
if (waitingResolvers.length > 0) {
|
|
9
|
+
var resolve = waitingResolvers.shift();
|
|
11
10
|
resolve({ value: msg, done: false });
|
|
12
11
|
} else {
|
|
13
12
|
queue.push(msg);
|
|
@@ -15,9 +14,8 @@ function createMessageQueue() {
|
|
|
15
14
|
},
|
|
16
15
|
end: function() {
|
|
17
16
|
ended = true;
|
|
18
|
-
|
|
19
|
-
var resolve =
|
|
20
|
-
waiting = null;
|
|
17
|
+
while (waitingResolvers.length > 0) {
|
|
18
|
+
var resolve = waitingResolvers.shift();
|
|
21
19
|
resolve({ value: undefined, done: true });
|
|
22
20
|
}
|
|
23
21
|
},
|
|
@@ -31,7 +29,7 @@ function createMessageQueue() {
|
|
|
31
29
|
return Promise.resolve({ value: undefined, done: true });
|
|
32
30
|
}
|
|
33
31
|
return new Promise(function(resolve) {
|
|
34
|
-
|
|
32
|
+
waitingResolvers.push(resolve);
|
|
35
33
|
});
|
|
36
34
|
},
|
|
37
35
|
};
|
package/lib/sdk-worker.js
CHANGED
|
@@ -42,13 +42,12 @@ var buffer = "";
|
|
|
42
42
|
// --- Message queue (same implementation as sdk-bridge.js) ---
|
|
43
43
|
function createMessageQueue() {
|
|
44
44
|
var queue = [];
|
|
45
|
-
var
|
|
45
|
+
var waitingResolvers = [];
|
|
46
46
|
var ended = false;
|
|
47
47
|
return {
|
|
48
48
|
push: function(msg) {
|
|
49
|
-
if (
|
|
50
|
-
var resolve =
|
|
51
|
-
waiting = null;
|
|
49
|
+
if (waitingResolvers.length > 0) {
|
|
50
|
+
var resolve = waitingResolvers.shift();
|
|
52
51
|
resolve({ value: msg, done: false });
|
|
53
52
|
} else {
|
|
54
53
|
queue.push(msg);
|
|
@@ -56,9 +55,8 @@ function createMessageQueue() {
|
|
|
56
55
|
},
|
|
57
56
|
end: function() {
|
|
58
57
|
ended = true;
|
|
59
|
-
|
|
60
|
-
var resolve =
|
|
61
|
-
waiting = null;
|
|
58
|
+
while (waitingResolvers.length > 0) {
|
|
59
|
+
var resolve = waitingResolvers.shift();
|
|
62
60
|
resolve({ value: undefined, done: true });
|
|
63
61
|
}
|
|
64
62
|
},
|
|
@@ -72,7 +70,7 @@ function createMessageQueue() {
|
|
|
72
70
|
return Promise.resolve({ value: undefined, done: true });
|
|
73
71
|
}
|
|
74
72
|
return new Promise(function(resolve) {
|
|
75
|
-
|
|
73
|
+
waitingResolvers.push(resolve);
|
|
76
74
|
});
|
|
77
75
|
},
|
|
78
76
|
};
|
|
@@ -158,11 +156,23 @@ function canUseTool(toolName, input, opts) {
|
|
|
158
156
|
decisionReason: opts.decisionReason || "",
|
|
159
157
|
});
|
|
160
158
|
return new Promise(function(resolve) {
|
|
161
|
-
|
|
159
|
+
var timeoutId = setTimeout(function() {
|
|
160
|
+
if (pendingPermissions[requestId]) {
|
|
161
|
+
delete pendingPermissions[requestId];
|
|
162
|
+
resolve({ behavior: "deny", message: "Permission request timed out after 30s" });
|
|
163
|
+
}
|
|
164
|
+
}, 30000);
|
|
165
|
+
pendingPermissions[requestId] = function(result) {
|
|
166
|
+
clearTimeout(timeoutId);
|
|
167
|
+
resolve(result);
|
|
168
|
+
};
|
|
162
169
|
if (opts.signal) {
|
|
163
170
|
opts.signal.addEventListener("abort", function() {
|
|
164
|
-
|
|
165
|
-
|
|
171
|
+
if (pendingPermissions[requestId]) {
|
|
172
|
+
clearTimeout(timeoutId);
|
|
173
|
+
delete pendingPermissions[requestId];
|
|
174
|
+
resolve({ behavior: "deny", message: "Cancelled" });
|
|
175
|
+
}
|
|
166
176
|
});
|
|
167
177
|
}
|
|
168
178
|
});
|
|
@@ -492,12 +502,25 @@ async function handleQueryStart(msg) {
|
|
|
492
502
|
stderr: err.stderr || null,
|
|
493
503
|
});
|
|
494
504
|
} finally {
|
|
505
|
+
for (var k in pendingPermissions) {
|
|
506
|
+
try { pendingPermissions[k]({ behavior: "deny", message: "Worker shutting down" }); } catch(e) {}
|
|
507
|
+
}
|
|
508
|
+
for (var k in pendingMcpCalls) {
|
|
509
|
+
try { pendingMcpCalls[k].reject(new Error("Worker shutting down")); } catch(e) {}
|
|
510
|
+
}
|
|
511
|
+
for (var k in pendingAskUser) {
|
|
512
|
+
try { pendingAskUser[k](new Error("Worker shutting down")); } catch(e) {}
|
|
513
|
+
}
|
|
514
|
+
for (var k in pendingElicitations) {
|
|
515
|
+
try { pendingElicitations[k](new Error("Worker shutting down")); } catch(e) {}
|
|
516
|
+
}
|
|
495
517
|
queryInstance = null;
|
|
496
518
|
messageQueue = null;
|
|
497
519
|
abortController = null;
|
|
498
520
|
pendingPermissions = {};
|
|
499
521
|
pendingAskUser = {};
|
|
500
522
|
pendingElicitations = {};
|
|
523
|
+
pendingMcpCalls = {};
|
|
501
524
|
}
|
|
502
525
|
}
|
|
503
526
|
|
package/lib/server-auth.js
CHANGED
|
@@ -3,6 +3,7 @@ var fs = require("fs");
|
|
|
3
3
|
var path = require("path");
|
|
4
4
|
var { CONFIG_DIR } = require("./config");
|
|
5
5
|
var _isDevMode = require("./config").isDevMode;
|
|
6
|
+
var store = require("./store");
|
|
6
7
|
|
|
7
8
|
// --- PIN hashing ---
|
|
8
9
|
|
|
@@ -64,13 +65,15 @@ function attachAuth(ctx) {
|
|
|
64
65
|
var authToken = ctx.pinHash || null;
|
|
65
66
|
|
|
66
67
|
// --- Multi-user auth tokens (persisted to disk) ---
|
|
67
|
-
var
|
|
68
|
+
var TOKENS_NAME = _isDevMode ? "auth-tokens-dev.json" : "auth-tokens.json";
|
|
68
69
|
var MULTI_USER_COOKIE = _isDevMode ? "relay_auth_user_dev" : "relay_auth_user";
|
|
69
70
|
var multiUserTokens = {};
|
|
70
71
|
|
|
71
72
|
function loadTokens() {
|
|
73
|
+
// Synchronous at startup: read directly so the server is ready before accepting
|
|
74
|
+
// connections. store.js is used for all subsequent writes.
|
|
72
75
|
try {
|
|
73
|
-
var raw = fs.readFileSync(
|
|
76
|
+
var raw = fs.readFileSync(path.join(CONFIG_DIR, TOKENS_NAME), "utf8");
|
|
74
77
|
var data = JSON.parse(raw);
|
|
75
78
|
if (data && typeof data === "object") {
|
|
76
79
|
multiUserTokens = data;
|
|
@@ -81,12 +84,10 @@ function attachAuth(ctx) {
|
|
|
81
84
|
}
|
|
82
85
|
|
|
83
86
|
function saveTokens() {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
fs.renameSync(tmpPath, TOKENS_FILE);
|
|
89
|
-
} catch (e) {}
|
|
87
|
+
// Async atomic write through store.js (queued per file, 0o600).
|
|
88
|
+
store.writeJson(TOKENS_NAME, multiUserTokens).catch(function (err) {
|
|
89
|
+
process.stderr.write("[server-auth] saveTokens failed: " + (err && err.message ? err.message : err) + "\n");
|
|
90
|
+
});
|
|
90
91
|
}
|
|
91
92
|
|
|
92
93
|
loadTokens();
|
package/lib/server.js
CHANGED
|
@@ -269,6 +269,7 @@ function createServer(opts) {
|
|
|
269
269
|
broadcastAll: function (msg) { broadcastAll(msg); },
|
|
270
270
|
sendToUser: function (userId, msg) { sendToUser(userId, msg); },
|
|
271
271
|
pushModule: pushModule,
|
|
272
|
+
isMultiUser: function () { return users.isMultiUser(); },
|
|
272
273
|
});
|
|
273
274
|
|
|
274
275
|
// --- External trigger watcher (global singleton) ---
|
package/lib/store.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* store.js — async JSON persistence with per-file write serialization.
|
|
3
|
+
*
|
|
4
|
+
* Provides two call patterns:
|
|
5
|
+
* readJson(name, defaultValue) — name is bare filename, resolved against CONFIG_DIR
|
|
6
|
+
* writeJson(name, value, opts) — same resolution; writes are queued per name
|
|
7
|
+
*
|
|
8
|
+
* readJsonAt(fullPath, defaultValue) — full path variant for per-project state
|
|
9
|
+
* writeJsonAt(fullPath, value, opts) — same; queued per resolved path
|
|
10
|
+
*
|
|
11
|
+
* Writes are atomic: data goes to {path}.tmp.{pid}, then renamed to {path}.
|
|
12
|
+
* After rename, chmod is applied (default 0o600).
|
|
13
|
+
* Concurrent writes to the same name/path are serialized in call order.
|
|
14
|
+
* Concurrent writes to different names/paths are independent.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
"use strict";
|
|
18
|
+
|
|
19
|
+
var fs = require("fs");
|
|
20
|
+
var path = require("path");
|
|
21
|
+
var { CONFIG_DIR } = require("./config");
|
|
22
|
+
|
|
23
|
+
// --- Per-path write queues ---
|
|
24
|
+
// Key: resolved absolute path. Value: Promise (tail of the chain).
|
|
25
|
+
var _queues = new Map();
|
|
26
|
+
|
|
27
|
+
function _enqueue(resolvedPath, fn) {
|
|
28
|
+
var tail = _queues.get(resolvedPath) || Promise.resolve();
|
|
29
|
+
var next = tail.then(fn, fn); // always advance the chain even if fn rejects
|
|
30
|
+
_queues.set(resolvedPath, next);
|
|
31
|
+
// Clean up the map entry once the chain reaches this point so the Map
|
|
32
|
+
// doesn't grow unboundedly for one-shot paths.
|
|
33
|
+
next.then(function () {
|
|
34
|
+
if (_queues.get(resolvedPath) === next) _queues.delete(resolvedPath);
|
|
35
|
+
}, function () {
|
|
36
|
+
if (_queues.get(resolvedPath) === next) _queues.delete(resolvedPath);
|
|
37
|
+
});
|
|
38
|
+
return next;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// --- Core I/O ---
|
|
42
|
+
|
|
43
|
+
function _read(resolvedPath, defaultValue) {
|
|
44
|
+
return fs.promises.readFile(resolvedPath, "utf8").then(function (raw) {
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(raw);
|
|
47
|
+
} catch (e) {
|
|
48
|
+
process.stderr.write("[store] Warning: corrupt JSON at " + resolvedPath + " — returning default\n");
|
|
49
|
+
return defaultValue;
|
|
50
|
+
}
|
|
51
|
+
}, function (err) {
|
|
52
|
+
if (err.code === "ENOENT") return defaultValue;
|
|
53
|
+
throw err;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function _write(resolvedPath, value, mode) {
|
|
58
|
+
var tmpPath = resolvedPath + ".tmp." + process.pid;
|
|
59
|
+
var json;
|
|
60
|
+
try {
|
|
61
|
+
json = JSON.stringify(value, null, 2);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
return Promise.reject(new Error("[store] Cannot serialize value for " + resolvedPath + ": " + e.message));
|
|
64
|
+
}
|
|
65
|
+
return fs.promises.mkdir(path.dirname(resolvedPath), { recursive: true })
|
|
66
|
+
.then(function () {
|
|
67
|
+
return fs.promises.writeFile(tmpPath, json, { encoding: "utf8" });
|
|
68
|
+
})
|
|
69
|
+
.then(function () {
|
|
70
|
+
return fs.promises.rename(tmpPath, resolvedPath);
|
|
71
|
+
})
|
|
72
|
+
.then(function () {
|
|
73
|
+
if (process.platform === "win32") return;
|
|
74
|
+
return fs.promises.chmod(resolvedPath, mode).catch(function () {});
|
|
75
|
+
})
|
|
76
|
+
.catch(function (err) {
|
|
77
|
+
// Best-effort cleanup of tmp file on failure
|
|
78
|
+
fs.promises.unlink(tmpPath).catch(function () {});
|
|
79
|
+
throw err;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// --- Public API ---
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Read a named JSON store from CONFIG_DIR.
|
|
87
|
+
* @param {string} name - Bare filename, e.g. "users.json"
|
|
88
|
+
* @param {*} defaultValue - Returned when file is missing or contains corrupt JSON
|
|
89
|
+
*/
|
|
90
|
+
function readJson(name, defaultValue) {
|
|
91
|
+
if (defaultValue === undefined) defaultValue = {};
|
|
92
|
+
var resolvedPath = path.join(CONFIG_DIR, name);
|
|
93
|
+
return _read(resolvedPath, defaultValue);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Write a named JSON store to CONFIG_DIR atomically.
|
|
98
|
+
* Serializes concurrent writes to the same name in call order.
|
|
99
|
+
* @param {string} name - Bare filename, e.g. "users.json"
|
|
100
|
+
* @param {*} value - JSON-serializable value
|
|
101
|
+
* @param {object} [opts]
|
|
102
|
+
* @param {number} [opts.mode=0o600] - File permission mode after write
|
|
103
|
+
*/
|
|
104
|
+
function writeJson(name, value, opts) {
|
|
105
|
+
var mode = (opts && opts.mode !== undefined) ? opts.mode : 0o600;
|
|
106
|
+
var resolvedPath = path.join(CONFIG_DIR, name);
|
|
107
|
+
return _enqueue(resolvedPath, function () {
|
|
108
|
+
return _write(resolvedPath, value, mode);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Read JSON from an arbitrary full path (for per-project state files).
|
|
114
|
+
* @param {string} fullPath - Absolute path to the JSON file
|
|
115
|
+
* @param {*} defaultValue - Returned when file is missing or contains corrupt JSON
|
|
116
|
+
*/
|
|
117
|
+
function readJsonAt(fullPath, defaultValue) {
|
|
118
|
+
if (defaultValue === undefined) defaultValue = {};
|
|
119
|
+
return _read(fullPath, defaultValue);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Write JSON to an arbitrary full path atomically.
|
|
124
|
+
* Serializes concurrent writes to the same path in call order.
|
|
125
|
+
* @param {string} fullPath - Absolute path to the JSON file
|
|
126
|
+
* @param {*} value - JSON-serializable value
|
|
127
|
+
* @param {object} [opts]
|
|
128
|
+
* @param {number} [opts.mode=0o600] - File permission mode after write
|
|
129
|
+
*/
|
|
130
|
+
function writeJsonAt(fullPath, value, opts) {
|
|
131
|
+
var mode = (opts && opts.mode !== undefined) ? opts.mode : 0o600;
|
|
132
|
+
return _enqueue(fullPath, function () {
|
|
133
|
+
return _write(fullPath, value, mode);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = { readJson: readJson, writeJson: writeJson, readJsonAt: readJsonAt, writeJsonAt: writeJsonAt };
|
package/lib/terminal-manager.js
CHANGED
|
@@ -6,16 +6,42 @@ var SCROLLBACK_MAX = 50 * 1024; // 50 KB per terminal
|
|
|
6
6
|
/**
|
|
7
7
|
* Create a terminal manager for a project.
|
|
8
8
|
* Manages persistent PTY sessions with scrollback buffering.
|
|
9
|
-
* opts: { cwd, send, sendTo }
|
|
9
|
+
* opts: { cwd, send, sendTo, isMultiUser }
|
|
10
|
+
*
|
|
11
|
+
* isMultiUser: optional boolean — when true, ownership enforcement is active.
|
|
12
|
+
* Each terminal records ownerUserId from ws._clayUser.id at creation time.
|
|
13
|
+
* Operations that mutate or read private output (attach, write, close, rename)
|
|
14
|
+
* are restricted to the owning user or admins (ws._clayUser.role === "admin").
|
|
15
|
+
* term_list results are filtered to the requesting user's own terminals;
|
|
16
|
+
* admins see all with an ownerUserId field attached.
|
|
10
17
|
*/
|
|
11
18
|
function createTerminalManager(opts) {
|
|
12
19
|
var cwd = opts.cwd;
|
|
13
20
|
var send = opts.send;
|
|
14
21
|
var sendTo = opts.sendTo;
|
|
22
|
+
var isMultiUser = opts.isMultiUser || false;
|
|
23
|
+
// broadcastTermList(callerWs): optional callback for filtered list broadcasts.
|
|
24
|
+
// When provided, replaces the bare send({ type: "term_list" }) on exit so that
|
|
25
|
+
// each connected client only sees their own terminals in multi-user mode.
|
|
26
|
+
// Signature: function(callerWs) — callerWs is null to mean "broadcast to all clients".
|
|
27
|
+
var broadcastTermList = opts.broadcastTermList || null;
|
|
15
28
|
|
|
16
29
|
var nextId = 1;
|
|
17
30
|
var terminals = new Map(); // id -> terminal session
|
|
18
31
|
|
|
32
|
+
// Returns true if callerWs is authorized for the given terminal session.
|
|
33
|
+
// In single-user mode, always authorized.
|
|
34
|
+
// In multi-user mode, authorized if: no owner set, same user, or caller is admin.
|
|
35
|
+
function isAuthorized(session, callerWs) {
|
|
36
|
+
if (!isMultiUser) return true;
|
|
37
|
+
if (!callerWs) return true;
|
|
38
|
+
if (!session.ownerUserId) return true; // legacy terminal with no owner
|
|
39
|
+
var caller = callerWs._clayUser;
|
|
40
|
+
if (!caller) return true; // unauthenticated caller — no user context, allow (single-user compat)
|
|
41
|
+
if (caller.role === "admin") return true;
|
|
42
|
+
return caller.id === session.ownerUserId;
|
|
43
|
+
}
|
|
44
|
+
|
|
19
45
|
function create(cols, rows, osUserInfo, ownerWs) {
|
|
20
46
|
if (terminals.size >= MAX_TERMINALS) return null;
|
|
21
47
|
|
|
@@ -36,6 +62,7 @@ function createTerminalManager(opts) {
|
|
|
36
62
|
exitCode: null,
|
|
37
63
|
subscribers: new Set(),
|
|
38
64
|
ownerWs: ownerWs || null,
|
|
65
|
+
ownerUserId: (ownerWs && ownerWs._clayUser && ownerWs._clayUser.id) ? ownerWs._clayUser.id : null,
|
|
39
66
|
};
|
|
40
67
|
|
|
41
68
|
pty.onData(function (data) {
|
|
@@ -66,8 +93,12 @@ function createTerminalManager(opts) {
|
|
|
66
93
|
if (ws.readyState === 1) ws.send(msg);
|
|
67
94
|
}
|
|
68
95
|
|
|
69
|
-
// Broadcast updated list
|
|
70
|
-
|
|
96
|
+
// Broadcast updated list (filtered per-user in multi-user mode)
|
|
97
|
+
if (broadcastTermList) {
|
|
98
|
+
broadcastTermList(null);
|
|
99
|
+
} else {
|
|
100
|
+
send({ type: "term_list", terminals: list() });
|
|
101
|
+
}
|
|
71
102
|
});
|
|
72
103
|
|
|
73
104
|
terminals.set(id, session);
|
|
@@ -78,6 +109,9 @@ function createTerminalManager(opts) {
|
|
|
78
109
|
var session = terminals.get(id);
|
|
79
110
|
if (!session) return false;
|
|
80
111
|
|
|
112
|
+
// Ownership check: only the owner (or an admin) may attach to a terminal.
|
|
113
|
+
if (!isAuthorized(session, ws)) return false;
|
|
114
|
+
|
|
81
115
|
// Skip scrollback replay if already subscribed (e.g. create then activate)
|
|
82
116
|
var alreadySubscribed = session.subscribers.has(ws);
|
|
83
117
|
session.subscribers.add(ws);
|
|
@@ -113,9 +147,11 @@ function createTerminalManager(opts) {
|
|
|
113
147
|
}
|
|
114
148
|
}
|
|
115
149
|
|
|
116
|
-
function write(id, data) {
|
|
150
|
+
function write(id, data, callerWs) {
|
|
117
151
|
var session = terminals.get(id);
|
|
118
|
-
if (session
|
|
152
|
+
if (!session) return;
|
|
153
|
+
if (!isAuthorized(session, callerWs)) return;
|
|
154
|
+
if (session.pty) {
|
|
119
155
|
session.pty.write(data);
|
|
120
156
|
}
|
|
121
157
|
}
|
|
@@ -140,9 +176,10 @@ function createTerminalManager(opts) {
|
|
|
140
176
|
}
|
|
141
177
|
}
|
|
142
178
|
|
|
143
|
-
function close(id) {
|
|
179
|
+
function close(id, callerWs) {
|
|
144
180
|
var session = terminals.get(id);
|
|
145
181
|
if (!session) return;
|
|
182
|
+
if (!isAuthorized(session, callerWs)) return;
|
|
146
183
|
|
|
147
184
|
if (session.pty) {
|
|
148
185
|
try { session.pty.kill(); } catch (e) {}
|
|
@@ -161,27 +198,35 @@ function createTerminalManager(opts) {
|
|
|
161
198
|
if (terminals.size === 0) nextId = 1;
|
|
162
199
|
}
|
|
163
200
|
|
|
164
|
-
function rename(id, title) {
|
|
201
|
+
function rename(id, title, callerWs) {
|
|
165
202
|
var session = terminals.get(id);
|
|
166
203
|
if (!session) return;
|
|
204
|
+
if (!isAuthorized(session, callerWs)) return;
|
|
167
205
|
session.title = String(title).substring(0, 50);
|
|
168
206
|
}
|
|
169
207
|
|
|
170
|
-
function list() {
|
|
208
|
+
function list(callerWs) {
|
|
171
209
|
var result = [];
|
|
172
210
|
for (var session of terminals.values()) {
|
|
173
|
-
|
|
211
|
+
if (!isAuthorized(session, callerWs)) continue;
|
|
212
|
+
var entry = {
|
|
174
213
|
id: session.id,
|
|
175
214
|
title: session.title,
|
|
176
215
|
exited: session.exited,
|
|
177
|
-
}
|
|
216
|
+
};
|
|
217
|
+
// Admins see the owner label so they can distinguish whose terminal it is.
|
|
218
|
+
if (isMultiUser && callerWs && callerWs._clayUser && callerWs._clayUser.role === "admin" && session.ownerUserId) {
|
|
219
|
+
entry.ownerUserId = session.ownerUserId;
|
|
220
|
+
}
|
|
221
|
+
result.push(entry);
|
|
178
222
|
}
|
|
179
223
|
return result;
|
|
180
224
|
}
|
|
181
225
|
|
|
182
|
-
function getScrollback(id) {
|
|
226
|
+
function getScrollback(id, callerWs) {
|
|
183
227
|
var session = terminals.get(id);
|
|
184
228
|
if (!session) return null;
|
|
229
|
+
if (!isAuthorized(session, callerWs)) return null;
|
|
185
230
|
var content = session.scrollback.map(function(c) { return c.data; }).join("");
|
|
186
231
|
return {
|
|
187
232
|
content: content,
|
package/lib/users.js
CHANGED
|
@@ -6,6 +6,7 @@ var { CONFIG_DIR } = require("./config");
|
|
|
6
6
|
var { attachAuth } = require("./users-auth");
|
|
7
7
|
var { DEFAULT_PERMISSIONS, ALL_PERMISSIONS, attachPermissions } = require("./users-permissions");
|
|
8
8
|
var { attachPreferences } = require("./users-preferences");
|
|
9
|
+
var store = require("./store");
|
|
9
10
|
|
|
10
11
|
var USERS_FILE = path.join(CONFIG_DIR, "users.json");
|
|
11
12
|
|
|
@@ -24,6 +25,10 @@ function defaultData() {
|
|
|
24
25
|
// --- Load / Save ---
|
|
25
26
|
|
|
26
27
|
function loadUsers() {
|
|
28
|
+
// Synchronous shim: read from disk directly so existing sync callers keep working.
|
|
29
|
+
// store.js is async-first; we fall back to synchronous fs here because the
|
|
30
|
+
// entire users.js call graph is synchronous and converting all ~79 call sites
|
|
31
|
+
// is a follow-up task (TODO(lr-b372): convert users.js callers to async).
|
|
27
32
|
try {
|
|
28
33
|
var raw = fs.readFileSync(USERS_FILE, "utf8");
|
|
29
34
|
var data = JSON.parse(raw);
|
|
@@ -40,10 +45,12 @@ function loadUsers() {
|
|
|
40
45
|
}
|
|
41
46
|
|
|
42
47
|
function saveUsers(data) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
48
|
+
// Fire-and-forget async write through store.js (atomic, queued, 0o600).
|
|
49
|
+
// Callers within this module are synchronous; converting them all to async
|
|
50
|
+
// is deferred (TODO(lr-b372): convert users.js callers to async).
|
|
51
|
+
store.writeJson("users.json", data).catch(function (err) {
|
|
52
|
+
process.stderr.write("[users] saveUsers failed: " + (err && err.message ? err.message : err) + "\n");
|
|
53
|
+
});
|
|
47
54
|
}
|
|
48
55
|
|
|
49
56
|
// --- User CRUD ---
|
|
@@ -106,13 +106,12 @@ var buffer = "";
|
|
|
106
106
|
// --- Message queue (same implementation as sdk-bridge.js) ---
|
|
107
107
|
function createMessageQueue() {
|
|
108
108
|
var queue = [];
|
|
109
|
-
var
|
|
109
|
+
var waitingResolvers = [];
|
|
110
110
|
var ended = false;
|
|
111
111
|
return {
|
|
112
112
|
push: function(msg) {
|
|
113
|
-
if (
|
|
114
|
-
var resolve =
|
|
115
|
-
waiting = null;
|
|
113
|
+
if (waitingResolvers.length > 0) {
|
|
114
|
+
var resolve = waitingResolvers.shift();
|
|
116
115
|
resolve({ value: msg, done: false });
|
|
117
116
|
} else {
|
|
118
117
|
queue.push(msg);
|
|
@@ -120,9 +119,8 @@ function createMessageQueue() {
|
|
|
120
119
|
},
|
|
121
120
|
end: function() {
|
|
122
121
|
ended = true;
|
|
123
|
-
|
|
124
|
-
var resolve =
|
|
125
|
-
waiting = null;
|
|
122
|
+
while (waitingResolvers.length > 0) {
|
|
123
|
+
var resolve = waitingResolvers.shift();
|
|
126
124
|
resolve({ value: undefined, done: true });
|
|
127
125
|
}
|
|
128
126
|
},
|
|
@@ -136,7 +134,7 @@ function createMessageQueue() {
|
|
|
136
134
|
return Promise.resolve({ value: undefined, done: true });
|
|
137
135
|
}
|
|
138
136
|
return new Promise(function(resolve) {
|
|
139
|
-
|
|
137
|
+
waitingResolvers.push(resolve);
|
|
140
138
|
});
|
|
141
139
|
},
|
|
142
140
|
};
|
|
@@ -309,11 +307,23 @@ function canUseTool(toolName, input, opts) {
|
|
|
309
307
|
decisionReason: opts.decisionReason || "",
|
|
310
308
|
});
|
|
311
309
|
return new Promise(function(resolve) {
|
|
312
|
-
|
|
310
|
+
var timeoutId = setTimeout(function() {
|
|
311
|
+
if (pendingPermissions[requestId]) {
|
|
312
|
+
delete pendingPermissions[requestId];
|
|
313
|
+
resolve({ behavior: "deny", message: "Permission request timed out after 30s" });
|
|
314
|
+
}
|
|
315
|
+
}, 30000);
|
|
316
|
+
pendingPermissions[requestId] = function(result) {
|
|
317
|
+
clearTimeout(timeoutId);
|
|
318
|
+
resolve(result);
|
|
319
|
+
};
|
|
313
320
|
if (opts.signal) {
|
|
314
321
|
opts.signal.addEventListener("abort", function() {
|
|
315
|
-
|
|
316
|
-
|
|
322
|
+
if (pendingPermissions[requestId]) {
|
|
323
|
+
clearTimeout(timeoutId);
|
|
324
|
+
delete pendingPermissions[requestId];
|
|
325
|
+
resolve({ behavior: "deny", message: "Cancelled" });
|
|
326
|
+
}
|
|
317
327
|
});
|
|
318
328
|
}
|
|
319
329
|
});
|
|
@@ -557,12 +567,25 @@ async function handleQueryStart(msg) {
|
|
|
557
567
|
stderr: err.stderr || null,
|
|
558
568
|
});
|
|
559
569
|
} finally {
|
|
570
|
+
for (var k in pendingPermissions) {
|
|
571
|
+
try { pendingPermissions[k]({ behavior: "deny", message: "Worker shutting down" }); } catch(e) {}
|
|
572
|
+
}
|
|
573
|
+
for (var k in pendingMcpToolCalls) {
|
|
574
|
+
try { pendingMcpToolCalls[k].reject(new Error("Worker shutting down")); } catch(e) {}
|
|
575
|
+
}
|
|
576
|
+
for (var k in pendingAskUser) {
|
|
577
|
+
try { pendingAskUser[k](new Error("Worker shutting down")); } catch(e) {}
|
|
578
|
+
}
|
|
579
|
+
for (var k in pendingElicitations) {
|
|
580
|
+
try { pendingElicitations[k](new Error("Worker shutting down")); } catch(e) {}
|
|
581
|
+
}
|
|
560
582
|
queryInstance = null;
|
|
561
583
|
messageQueue = null;
|
|
562
584
|
abortController = null;
|
|
563
585
|
pendingPermissions = {};
|
|
564
586
|
pendingAskUser = {};
|
|
565
587
|
pendingElicitations = {};
|
|
588
|
+
pendingMcpToolCalls = {};
|
|
566
589
|
}
|
|
567
590
|
}
|
|
568
591
|
|
package/package.json
CHANGED