@radnine/claude-session-daemon 0.8.3 → 0.9.3

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.
@@ -1,266 +0,0 @@
1
- 'use strict';
2
-
3
- const http = require('node:http');
4
- const { randomUUID } = require('node:crypto');
5
- const { EventEmitter } = require('node:events');
6
-
7
- /**
8
- * Local HTTP server that receives permission requests from Claude CLI hooks
9
- * and blocks until a decision is received from FlightDeck.
10
- *
11
- * The PreToolUse hook script POSTs to this server, which holds the connection
12
- * open until the permission is approved/denied/timed out.
13
- *
14
- * Emits:
15
- * 'permission_request' — { requestId, sessionId, toolName, toolInput, filePath, description, riskLevel }
16
- *
17
- * @example
18
- * const server = new PermissionServer({ port: 0, timeout: 60 }, logger);
19
- * server.on('permission_request', (req) => forwardToRails(req));
20
- * server.start();
21
- * // Later, when user responds:
22
- * server.resolve('perm_abc123', 'approve');
23
- */
24
- class PermissionServer extends EventEmitter {
25
- /**
26
- * @param {object} config
27
- * @param {number} [config.port=0] - Port to listen on (0 = random)
28
- * @param {number} [config.timeout=60] - Default timeout in seconds
29
- * @param {object} logger
30
- */
31
- constructor(config = {}, logger) {
32
- super();
33
- this._port = config.port || 0;
34
- this._defaultTimeout = config.timeout || 60;
35
- this._logger = logger;
36
- this._server = null;
37
-
38
- // Map of requestId -> { resolve, timer, sessionId }
39
- this._pending = new Map();
40
- }
41
-
42
- /** Actual port the server is listening on. */
43
- get port() {
44
- const addr = this._server?.address();
45
- return addr ? addr.port : this._port;
46
- }
47
-
48
- /**
49
- * Start the HTTP server.
50
- * @returns {Promise<number>} The port the server is listening on.
51
- */
52
- start() {
53
- return new Promise((resolve) => {
54
- this._server = http.createServer((req, res) => this._handleRequest(req, res));
55
-
56
- this._server.listen(this._port, '127.0.0.1', () => {
57
- const addr = this._server.address();
58
- this._logger.info(`Permission server listening on 127.0.0.1:${addr.port}`);
59
- resolve(addr.port);
60
- });
61
- });
62
- }
63
-
64
- /**
65
- * Stop the server and deny all pending requests.
66
- * @returns {Promise<void>}
67
- */
68
- async stop() {
69
- // Deny all pending requests
70
- for (const [requestId] of this._pending) {
71
- this.resolve(requestId, 'deny', 'Daemon shutting down');
72
- }
73
-
74
- return new Promise((resolve) => {
75
- if (this._server) {
76
- this._server.close(() => resolve());
77
- } else {
78
- resolve();
79
- }
80
- });
81
- }
82
-
83
- /**
84
- * Resolve a pending permission request.
85
- * @param {string} requestId
86
- * @param {string} decision - 'approve' or 'deny'
87
- * @param {string} [reason] - Optional reason for denial
88
- */
89
- resolve(requestId, decision, reason) {
90
- const pending = this._pending.get(requestId);
91
- if (!pending) {
92
- this._logger.warn('Permission response for unknown request', { requestId });
93
- return;
94
- }
95
-
96
- clearTimeout(pending.timer);
97
- this._pending.delete(requestId);
98
-
99
- this._logger.info('Permission resolved', { requestId, decision });
100
- pending.resolve({ decision, reason });
101
- }
102
-
103
- /**
104
- * Deny all pending requests for a session (e.g., on disconnect).
105
- * @param {string} sessionId
106
- */
107
- denyAllForSession(sessionId) {
108
- for (const [requestId, pending] of this._pending) {
109
- if (pending.sessionId === sessionId) {
110
- this.resolve(requestId, 'deny', 'Session disconnected');
111
- }
112
- }
113
- }
114
-
115
- /** Number of pending requests. */
116
- get pendingCount() {
117
- return this._pending.size;
118
- }
119
-
120
- // ---------------------------------------------------------------------------
121
- // Internal
122
- // ---------------------------------------------------------------------------
123
-
124
- /**
125
- * Handle incoming HTTP request from the hook script.
126
- */
127
- _handleRequest(req, res) {
128
- if (req.method !== 'POST' || !req.url.startsWith('/permissions/request')) {
129
- res.writeHead(404, { 'Content-Type': 'application/json' });
130
- res.end(JSON.stringify({ error: 'Not found' }));
131
- return;
132
- }
133
-
134
- let body = '';
135
- req.on('data', (chunk) => { body += chunk; });
136
- req.on('end', () => {
137
- try {
138
- const data = JSON.parse(body);
139
- this._handlePermissionRequest(data, res);
140
- } catch (err) {
141
- this._logger.error('Failed to parse permission request', { error: err.message });
142
- res.writeHead(400, { 'Content-Type': 'application/json' });
143
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
144
- }
145
- });
146
- }
147
-
148
- /**
149
- * Process a permission request and hold the connection open.
150
- */
151
- _handlePermissionRequest(data, res) {
152
- const requestId = `perm_${randomUUID().slice(0, 12)}`;
153
- const sessionId = data.session_id || 'unknown';
154
- const toolName = data.tool_name || 'unknown';
155
- const toolInput = data.tool_input || {};
156
- const filePath = this._extractFilePath(toolName, toolInput);
157
- const description = this._buildDescription(toolName, toolInput);
158
- const riskLevel = this._classifyRisk(toolName, toolInput);
159
- const timeoutSeconds = this._defaultTimeout;
160
-
161
- this._logger.info('Permission request received', { requestId, sessionId, toolName, riskLevel });
162
-
163
- // Create a promise that will be resolved when the user responds
164
- const resultPromise = new Promise((resolve) => {
165
- const timer = setTimeout(() => {
166
- this._logger.warn('Permission request timed out', { requestId });
167
- this._pending.delete(requestId);
168
- resolve({ decision: 'deny', reason: 'Timed out waiting for approval' });
169
- this.emit('permission_timeout', { requestId, sessionId });
170
- }, timeoutSeconds * 1000);
171
-
172
- this._pending.set(requestId, { resolve, timer, sessionId });
173
- });
174
-
175
- // Emit the request for the connection layer to forward to Rails
176
- this.emit('permission_request', {
177
- requestId,
178
- sessionId,
179
- toolName,
180
- toolInput,
181
- filePath,
182
- description,
183
- riskLevel,
184
- timeoutSeconds,
185
- });
186
-
187
- // Hold the HTTP connection open until resolved
188
- resultPromise.then(({ decision, reason }) => {
189
- const hookResponse = this._buildHookResponse(decision, reason);
190
- res.writeHead(200, { 'Content-Type': 'application/json' });
191
- res.end(JSON.stringify(hookResponse));
192
- });
193
- }
194
-
195
- /**
196
- * Extract the file path from tool input if applicable.
197
- */
198
- _extractFilePath(toolName, toolInput) {
199
- switch (toolName) {
200
- case 'Write':
201
- case 'Read':
202
- case 'Edit':
203
- return toolInput.file_path || toolInput.path || null;
204
- case 'Bash':
205
- return null;
206
- default:
207
- return toolInput.file_path || toolInput.path || null;
208
- }
209
- }
210
-
211
- /**
212
- * Build a human-readable description of the tool action.
213
- */
214
- _buildDescription(toolName, toolInput) {
215
- switch (toolName) {
216
- case 'Bash':
217
- return `Execute: ${(toolInput.command || '').slice(0, 200)}`;
218
- case 'Write':
219
- return `Write file: ${toolInput.file_path || 'unknown'}`;
220
- case 'Edit':
221
- return `Edit file: ${toolInput.file_path || 'unknown'}`;
222
- case 'Read':
223
- return `Read file: ${toolInput.file_path || 'unknown'}`;
224
- default:
225
- return `${toolName}: ${JSON.stringify(toolInput).slice(0, 200)}`;
226
- }
227
- }
228
-
229
- /**
230
- * Classify risk level based on tool type and input.
231
- */
232
- _classifyRisk(toolName, toolInput) {
233
- if (toolName === 'Bash') return 'high';
234
- if (toolName === 'Write') {
235
- // Overwriting existing files is higher risk
236
- return 'medium';
237
- }
238
- if (toolName === 'Edit') return 'medium';
239
- if (toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep') return 'low';
240
- return 'medium';
241
- }
242
-
243
- /**
244
- * Build the hook response JSON that the hook script returns to Claude CLI.
245
- */
246
- _buildHookResponse(decision, reason) {
247
- if (decision === 'approve') {
248
- return {
249
- hookSpecificOutput: {
250
- hookEventName: 'PreToolUse',
251
- permissionDecision: 'allow',
252
- },
253
- };
254
- }
255
-
256
- return {
257
- hookSpecificOutput: {
258
- hookEventName: 'PreToolUse',
259
- permissionDecision: 'deny',
260
- permissionDecisionReason: reason || 'Denied by user via FlightDeck',
261
- },
262
- };
263
- }
264
- }
265
-
266
- module.exports = { PermissionServer };