n8n-mcp 2.18.10 → 2.19.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/data/nodes.db CHANGED
Binary file
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import express from 'express';
3
3
  import { InstanceContext } from './types/instance-context';
4
+ import { SessionRestoreHook, SessionState, SessionLifecycleEvents } from './types/session-restoration';
4
5
  export declare class SingleSessionHTTPServer {
5
6
  private transports;
6
7
  private servers;
@@ -13,7 +14,19 @@ export declare class SingleSessionHTTPServer {
13
14
  private sessionTimeout;
14
15
  private authToken;
15
16
  private cleanupTimer;
16
- constructor();
17
+ private onSessionNotFound?;
18
+ private sessionRestorationTimeout;
19
+ private sessionEvents?;
20
+ private sessionRestorationRetries;
21
+ private sessionRestorationRetryDelay;
22
+ constructor(options?: {
23
+ sessionTimeout?: number;
24
+ onSessionNotFound?: SessionRestoreHook;
25
+ sessionRestorationTimeout?: number;
26
+ sessionEvents?: SessionLifecycleEvents;
27
+ sessionRestorationRetries?: number;
28
+ sessionRestorationRetryDelay?: number;
29
+ });
17
30
  private startSessionCleanup;
18
31
  private cleanupExpiredSessions;
19
32
  private removeSession;
@@ -24,6 +37,11 @@ export declare class SingleSessionHTTPServer {
24
37
  private updateSessionAccess;
25
38
  private switchSessionContext;
26
39
  private performContextSwitch;
40
+ private timeout;
41
+ private emitEvent;
42
+ private restoreSessionWithRetry;
43
+ private createSession;
44
+ private generateSessionId;
27
45
  private getSessionMetrics;
28
46
  private loadAuthToken;
29
47
  private validateEnvironment;
@@ -44,5 +62,10 @@ export declare class SingleSessionHTTPServer {
44
62
  sessionIds: string[];
45
63
  };
46
64
  };
65
+ getActiveSessions(): string[];
66
+ getSessionState(sessionId: string): SessionState | null;
67
+ getAllSessionStates(): SessionState[];
68
+ manuallyRestoreSession(sessionId: string, instanceContext: InstanceContext): boolean;
69
+ manuallyDeleteSession(sessionId: string): boolean;
47
70
  }
48
71
  //# sourceMappingURL=http-server-single-session.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"http-server-single-session.d.ts","sourceRoot":"","sources":["../src/http-server-single-session.ts"],"names":[],"mappings":";AAMA,OAAO,OAAO,MAAM,SAAS,CAAC;AAoB9B,OAAO,EAAE,eAAe,EAA2B,MAAM,0BAA0B,CAAC;AA+CpF,qBAAa,uBAAuB;IAElC,OAAO,CAAC,UAAU,CAA8D;IAChF,OAAO,CAAC,OAAO,CAA0D;IACzE,OAAO,CAAC,eAAe,CAAsE;IAC7F,OAAO,CAAC,eAAe,CAA4D;IACnF,OAAO,CAAC,kBAAkB,CAAyC;IACnE,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,cAAc,CAAwB;IAC9C,OAAO,CAAC,aAAa,CAAM;IAC3B,OAAO,CAAC,cAAc,CAAkB;IACxC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,YAAY,CAA+B;;IAcnD,OAAO,CAAC,mBAAmB;IAmB3B,OAAO,CAAC,sBAAsB;YAqChB,aAAa;IAsB3B,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,gBAAgB;IAkBxB,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,sBAAsB;IAkC9B,OAAO,CAAC,mBAAmB;YASb,oBAAoB;YAwBpB,oBAAoB;IAwBlC,OAAO,CAAC,iBAAiB;IAsBzB,OAAO,CAAC,aAAa;IA2BrB,OAAO,CAAC,mBAAmB;IAoDrB,aAAa,CACjB,GAAG,EAAE,OAAO,CAAC,OAAO,EACpB,GAAG,EAAE,OAAO,CAAC,QAAQ,EACrB,eAAe,CAAC,EAAE,eAAe,GAChC,OAAO,CAAC,IAAI,CAAC;YAmOF,eAAe;IA8C7B,OAAO,CAAC,SAAS;IAQX,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgnBtB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAkD/B,cAAc,IAAI;QAChB,MAAM,EAAE,OAAO,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,QAAQ,CAAC,EAAE;YACT,KAAK,EAAE,MAAM,CAAC;YACd,MAAM,EAAE,MAAM,CAAC;YACf,OAAO,EAAE,MAAM,CAAC;YAChB,GAAG,EAAE,MAAM,CAAC;YACZ,UAAU,EAAE,MAAM,EAAE,CAAC;SACtB,CAAC;KACH;CA8BF"}
1
+ {"version":3,"file":"http-server-single-session.d.ts","sourceRoot":"","sources":["../src/http-server-single-session.ts"],"names":[],"mappings":";AAMA,OAAO,OAAO,MAAM,SAAS,CAAC;AAoB9B,OAAO,EAAE,eAAe,EAA2B,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AA+CvG,qBAAa,uBAAuB;IAElC,OAAO,CAAC,UAAU,CAA8D;IAChF,OAAO,CAAC,OAAO,CAA0D;IACzE,OAAO,CAAC,eAAe,CAAsE;IAC7F,OAAO,CAAC,eAAe,CAA4D;IACnF,OAAO,CAAC,kBAAkB,CAAyC;IACnE,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,cAAc,CAAwB;IAC9C,OAAO,CAAC,aAAa,CAAM;IAC3B,OAAO,CAAC,cAAc,CAAkB;IACxC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,YAAY,CAA+B;IAGnD,OAAO,CAAC,iBAAiB,CAAC,CAAqB;IAC/C,OAAO,CAAC,yBAAyB,CAAS;IAG1C,OAAO,CAAC,aAAa,CAAC,CAAyB;IAG/C,OAAO,CAAC,yBAAyB,CAAS;IAC1C,OAAO,CAAC,4BAA4B,CAAS;gBAEjC,OAAO,GAAE;QACnB,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,iBAAiB,CAAC,EAAE,kBAAkB,CAAC;QACvC,yBAAyB,CAAC,EAAE,MAAM,CAAC;QACnC,aAAa,CAAC,EAAE,sBAAsB,CAAC;QACvC,yBAAyB,CAAC,EAAE,MAAM,CAAC;QACnC,4BAA4B,CAAC,EAAE,MAAM,CAAC;KAClC;IA6BN,OAAO,CAAC,mBAAmB;IAmB3B,OAAO,CAAC,sBAAsB;YAiEhB,aAAa;IAsB3B,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,gBAAgB;IAwBxB,OAAO,CAAC,gBAAgB;IAwBxB,OAAO,CAAC,sBAAsB;IAkC9B,OAAO,CAAC,mBAAmB;YAmBb,oBAAoB;YAwBpB,oBAAoB;IA6BlC,OAAO,CAAC,OAAO;YAkBD,SAAS;YAkCT,uBAAuB;IAmGrC,OAAO,CAAC,aAAa;IA+IrB,OAAO,CAAC,iBAAiB;IAwBzB,OAAO,CAAC,iBAAiB;IAsBzB,OAAO,CAAC,aAAa;IA2BrB,OAAO,CAAC,mBAAmB;IAoDrB,aAAa,CACjB,GAAG,EAAE,OAAO,CAAC,OAAO,EACpB,GAAG,EAAE,OAAO,CAAC,QAAQ,EACrB,eAAe,CAAC,EAAE,eAAe,GAChC,OAAO,CAAC,IAAI,CAAC;YAqXF,eAAe;IA8C7B,OAAO,CAAC,SAAS;IAQX,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgnBtB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAkD/B,cAAc,IAAI;QAChB,MAAM,EAAE,OAAO,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,QAAQ,CAAC,EAAE;YACT,KAAK,EAAE,MAAM,CAAC;YACd,MAAM,EAAE,MAAM,CAAC;YACf,OAAO,EAAE,MAAM,CAAC;YAChB,GAAG,EAAE,MAAM,CAAC;YACZ,UAAU,EAAE,MAAM,EAAE,CAAC;SACtB,CAAC;KACH;IA4CD,iBAAiB,IAAI,MAAM,EAAE;IAsB7B,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI;IA4CvD,mBAAmB,IAAI,YAAY,EAAE;IAkCrC,sBAAsB,CAAC,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,eAAe,GAAG,OAAO;IAyEpF,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO;CA+ClD"}
@@ -35,7 +35,7 @@ function extractMultiTenantHeaders(req) {
35
35
  };
36
36
  }
37
37
  class SingleSessionHTTPServer {
38
- constructor() {
38
+ constructor(options = {}) {
39
39
  this.transports = {};
40
40
  this.servers = {};
41
41
  this.sessionMetadata = {};
@@ -47,6 +47,14 @@ class SingleSessionHTTPServer {
47
47
  this.authToken = null;
48
48
  this.cleanupTimer = null;
49
49
  this.validateEnvironment();
50
+ this.onSessionNotFound = options.onSessionNotFound;
51
+ this.sessionRestorationTimeout = options.sessionRestorationTimeout || 5000;
52
+ this.sessionEvents = options.sessionEvents;
53
+ this.sessionRestorationRetries = options.sessionRestorationRetries ?? 0;
54
+ this.sessionRestorationRetryDelay = options.sessionRestorationRetryDelay || 100;
55
+ if (options.sessionTimeout) {
56
+ this.sessionTimeout = options.sessionTimeout;
57
+ }
50
58
  this.startSessionCleanup();
51
59
  }
52
60
  startSessionCleanup() {
@@ -79,7 +87,28 @@ class SingleSessionHTTPServer {
79
87
  logger_1.logger.debug('Cleaned orphaned session context', { sessionId });
80
88
  }
81
89
  }
90
+ for (const sessionId in this.transports) {
91
+ if (!this.sessionMetadata[sessionId]) {
92
+ logger_1.logger.warn('Orphaned transport detected, cleaning up', { sessionId });
93
+ this.removeSession(sessionId, 'orphaned_transport').catch(err => {
94
+ logger_1.logger.error('Error cleaning orphaned transport', { sessionId, error: err });
95
+ });
96
+ }
97
+ }
98
+ for (const sessionId in this.servers) {
99
+ if (!this.sessionMetadata[sessionId]) {
100
+ logger_1.logger.warn('Orphaned server detected, cleaning up', { sessionId });
101
+ delete this.servers[sessionId];
102
+ logger_1.logger.debug('Cleaned orphaned server', { sessionId });
103
+ }
104
+ }
82
105
  for (const sessionId of expiredSessions) {
106
+ this.emitEvent('onSessionExpired', sessionId).catch(err => {
107
+ logger_1.logger.error('Failed to emit onSessionExpired event (non-blocking)', {
108
+ sessionId,
109
+ error: err instanceof Error ? err.message : String(err)
110
+ });
111
+ });
83
112
  this.removeSession(sessionId, 'expired');
84
113
  }
85
114
  if (expiredSessions.length > 0) {
@@ -111,7 +140,16 @@ class SingleSessionHTTPServer {
111
140
  return this.getActiveSessionCount() < MAX_SESSIONS;
112
141
  }
113
142
  isValidSessionId(sessionId) {
114
- return Boolean(sessionId && sessionId.length > 0);
143
+ if (!sessionId || typeof sessionId !== 'string') {
144
+ return false;
145
+ }
146
+ if (!/^[a-zA-Z0-9_-]+$/.test(sessionId)) {
147
+ return false;
148
+ }
149
+ if (sessionId.length > 100) {
150
+ return false;
151
+ }
152
+ return true;
115
153
  }
116
154
  sanitizeErrorForClient(error) {
117
155
  const isProduction = process.env.NODE_ENV === 'production';
@@ -138,6 +176,12 @@ class SingleSessionHTTPServer {
138
176
  updateSessionAccess(sessionId) {
139
177
  if (this.sessionMetadata[sessionId]) {
140
178
  this.sessionMetadata[sessionId].lastAccess = new Date();
179
+ this.emitEvent('onSessionAccessed', sessionId).catch(err => {
180
+ logger_1.logger.error('Failed to emit onSessionAccessed event (non-blocking)', {
181
+ sessionId,
182
+ error: err instanceof Error ? err.message : String(err)
183
+ });
184
+ });
141
185
  }
142
186
  }
143
187
  async switchSessionContext(sessionId, newContext) {
@@ -169,6 +213,211 @@ class SingleSessionHTTPServer {
169
213
  }
170
214
  }
171
215
  }
216
+ timeout(ms) {
217
+ return new Promise((_, reject) => {
218
+ setTimeout(() => {
219
+ const error = new Error(`Operation timed out after ${ms}ms`);
220
+ error.name = 'TimeoutError';
221
+ reject(error);
222
+ }, ms);
223
+ });
224
+ }
225
+ async emitEvent(eventName, ...args) {
226
+ const handler = this.sessionEvents?.[eventName];
227
+ if (!handler)
228
+ return;
229
+ try {
230
+ await Promise.resolve(handler(...args));
231
+ }
232
+ catch (error) {
233
+ logger_1.logger.error(`Session event handler failed: ${eventName}`, {
234
+ error: error instanceof Error ? error.message : String(error),
235
+ sessionId: args[0]
236
+ });
237
+ }
238
+ }
239
+ async restoreSessionWithRetry(sessionId) {
240
+ if (!this.onSessionNotFound) {
241
+ throw new Error('onSessionNotFound hook not configured');
242
+ }
243
+ const maxRetries = this.sessionRestorationRetries;
244
+ const retryDelay = this.sessionRestorationRetryDelay;
245
+ const overallTimeout = this.sessionRestorationTimeout;
246
+ const startTime = Date.now();
247
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
248
+ try {
249
+ const remainingTime = overallTimeout - (Date.now() - startTime);
250
+ if (remainingTime <= 0) {
251
+ const error = new Error(`Session restoration timed out after ${overallTimeout}ms`);
252
+ error.name = 'TimeoutError';
253
+ throw error;
254
+ }
255
+ if (attempt > 0) {
256
+ logger_1.logger.debug('Retrying session restoration', {
257
+ sessionId,
258
+ attempt: attempt,
259
+ maxRetries: maxRetries,
260
+ remainingTime: remainingTime + 'ms'
261
+ });
262
+ }
263
+ const context = await Promise.race([
264
+ this.onSessionNotFound(sessionId),
265
+ this.timeout(remainingTime)
266
+ ]);
267
+ if (attempt > 0) {
268
+ logger_1.logger.info('Session restoration succeeded after retry', {
269
+ sessionId,
270
+ attempts: attempt + 1
271
+ });
272
+ }
273
+ return context;
274
+ }
275
+ catch (error) {
276
+ if (error instanceof Error && error.name === 'TimeoutError') {
277
+ logger_1.logger.error('Session restoration timeout (no retry)', {
278
+ sessionId,
279
+ timeout: overallTimeout
280
+ });
281
+ throw error;
282
+ }
283
+ if (attempt === maxRetries) {
284
+ logger_1.logger.error('Session restoration failed after all retries', {
285
+ sessionId,
286
+ attempts: attempt + 1,
287
+ error: error instanceof Error ? error.message : String(error)
288
+ });
289
+ throw error;
290
+ }
291
+ logger_1.logger.warn('Session restoration failed, will retry', {
292
+ sessionId,
293
+ attempt: attempt + 1,
294
+ maxRetries: maxRetries,
295
+ error: error instanceof Error ? error.message : String(error),
296
+ nextRetryIn: retryDelay + 'ms'
297
+ });
298
+ await new Promise(resolve => setTimeout(resolve, retryDelay));
299
+ }
300
+ }
301
+ throw new Error('Unexpected state in restoreSessionWithRetry');
302
+ }
303
+ createSession(instanceContext, sessionId, waitForConnection = false) {
304
+ const id = sessionId || this.generateSessionId(instanceContext);
305
+ if (this.transports[id]) {
306
+ logger_1.logger.debug('Session already exists, skipping creation (idempotent)', {
307
+ sessionId: id
308
+ });
309
+ return waitForConnection ? Promise.resolve(id) : id;
310
+ }
311
+ if (sessionId && !this.isValidSessionId(sessionId)) {
312
+ logger_1.logger.error('Invalid session ID format during creation', { sessionId });
313
+ throw new Error('Invalid session ID format');
314
+ }
315
+ if (!this.sessionMetadata[id]) {
316
+ this.sessionMetadata[id] = {
317
+ lastAccess: new Date(),
318
+ createdAt: new Date()
319
+ };
320
+ this.sessionContexts[id] = instanceContext;
321
+ }
322
+ const server = new server_1.N8NDocumentationMCPServer(instanceContext);
323
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
324
+ sessionIdGenerator: () => id,
325
+ onsessioninitialized: (initializedSessionId) => {
326
+ logger_1.logger.info('Session initialized during explicit creation', {
327
+ sessionId: initializedSessionId
328
+ });
329
+ }
330
+ });
331
+ this.transports[id] = transport;
332
+ this.servers[id] = server;
333
+ transport.onclose = () => {
334
+ if (transport.sessionId) {
335
+ logger_1.logger.info('Transport closed during createSession, cleaning up', {
336
+ sessionId: transport.sessionId
337
+ });
338
+ this.removeSession(transport.sessionId, 'transport_closed').catch(err => {
339
+ logger_1.logger.error('Error during transport close cleanup', {
340
+ sessionId: transport.sessionId,
341
+ error: err instanceof Error ? err.message : String(err)
342
+ });
343
+ });
344
+ }
345
+ };
346
+ transport.onerror = (error) => {
347
+ if (transport.sessionId) {
348
+ logger_1.logger.error('Transport error during createSession', {
349
+ sessionId: transport.sessionId,
350
+ error: error.message
351
+ });
352
+ this.removeSession(transport.sessionId, 'transport_error').catch(err => {
353
+ logger_1.logger.error('Error during transport error cleanup', { error: err });
354
+ });
355
+ }
356
+ };
357
+ const initializeSession = async () => {
358
+ try {
359
+ await server.initialized;
360
+ await server.connect(transport);
361
+ if (waitForConnection) {
362
+ logger_1.logger.info('Session created and connected successfully', {
363
+ sessionId: id,
364
+ hasInstanceContext: !!instanceContext,
365
+ instanceId: instanceContext?.instanceId
366
+ });
367
+ }
368
+ else {
369
+ logger_1.logger.info('Session created successfully (connecting server to transport)', {
370
+ sessionId: id,
371
+ hasInstanceContext: !!instanceContext,
372
+ instanceId: instanceContext?.instanceId
373
+ });
374
+ }
375
+ }
376
+ catch (err) {
377
+ logger_1.logger.error('Failed to connect server to transport in createSession', {
378
+ sessionId: id,
379
+ error: err instanceof Error ? err.message : String(err),
380
+ waitForConnection
381
+ });
382
+ await this.removeSession(id, 'connection_failed').catch(cleanupErr => {
383
+ logger_1.logger.error('Error during connection failure cleanup', { error: cleanupErr });
384
+ });
385
+ throw err;
386
+ }
387
+ this.emitEvent('onSessionCreated', id, instanceContext).catch(eventErr => {
388
+ logger_1.logger.error('Failed to emit onSessionCreated event (non-blocking)', {
389
+ sessionId: id,
390
+ error: eventErr instanceof Error ? eventErr.message : String(eventErr)
391
+ });
392
+ });
393
+ return id;
394
+ };
395
+ if (waitForConnection) {
396
+ return initializeSession();
397
+ }
398
+ initializeSession().catch(error => {
399
+ logger_1.logger.error('Async session creation failed in manual restore flow', {
400
+ sessionId: id,
401
+ error: error instanceof Error ? error.message : String(error)
402
+ });
403
+ });
404
+ return id;
405
+ }
406
+ generateSessionId(instanceContext) {
407
+ const isMultiTenantEnabled = process.env.ENABLE_MULTI_TENANT === 'true';
408
+ const sessionStrategy = process.env.MULTI_TENANT_SESSION_STRATEGY || 'instance';
409
+ if (isMultiTenantEnabled && sessionStrategy === 'instance' && instanceContext?.instanceId) {
410
+ const configHash = (0, crypto_1.createHash)('sha256')
411
+ .update(JSON.stringify({
412
+ url: instanceContext.n8nApiUrl,
413
+ instanceId: instanceContext.instanceId
414
+ }))
415
+ .digest('hex')
416
+ .substring(0, 8);
417
+ return `instance-${instanceContext.instanceId}-${configHash}-${(0, uuid_1.v4)()}`;
418
+ }
419
+ return (0, uuid_1.v4)();
420
+ }
172
421
  getSessionMetrics() {
173
422
  const now = Date.now();
174
423
  let expiredCount = 0;
@@ -326,6 +575,12 @@ class SingleSessionHTTPServer {
326
575
  };
327
576
  logger_1.logger.info('handleRequest: Connecting server to new transport');
328
577
  await server.connect(transport);
578
+ this.emitEvent('onSessionCreated', sessionIdToUse, instanceContext).catch(eventErr => {
579
+ logger_1.logger.error('Failed to emit onSessionCreated event (non-blocking)', {
580
+ sessionId: sessionIdToUse,
581
+ error: eventErr instanceof Error ? eventErr.message : String(eventErr)
582
+ });
583
+ });
329
584
  }
330
585
  else if (sessionId && this.transports[sessionId]) {
331
586
  if (!this.isValidSessionId(sessionId)) {
@@ -350,29 +605,142 @@ class SingleSessionHTTPServer {
350
605
  this.updateSessionAccess(sessionId);
351
606
  }
352
607
  else {
353
- const errorDetails = {
354
- hasSessionId: !!sessionId,
355
- isInitialize: isInitialize,
356
- sessionIdValid: sessionId ? this.isValidSessionId(sessionId) : false,
357
- sessionExists: sessionId ? !!this.transports[sessionId] : false
358
- };
359
- logger_1.logger.warn('handleRequest: Invalid request - no session ID and not initialize', errorDetails);
360
- let errorMessage = 'Bad Request: No valid session ID provided and not an initialize request';
361
- if (sessionId && !this.isValidSessionId(sessionId)) {
362
- errorMessage = 'Bad Request: Invalid session ID format';
608
+ if (sessionId) {
609
+ if (!this.isValidSessionId(sessionId)) {
610
+ logger_1.logger.warn('handleRequest: Invalid session ID format rejected', {
611
+ sessionId: sessionId.substring(0, 20)
612
+ });
613
+ res.status(400).json({
614
+ jsonrpc: '2.0',
615
+ error: {
616
+ code: -32602,
617
+ message: 'Invalid session ID format'
618
+ },
619
+ id: req.body?.id || null
620
+ });
621
+ return;
622
+ }
623
+ if (this.onSessionNotFound) {
624
+ logger_1.logger.info('Attempting session restoration', { sessionId });
625
+ try {
626
+ const restoredContext = await this.restoreSessionWithRetry(sessionId);
627
+ if (restoredContext === null || restoredContext === undefined) {
628
+ logger_1.logger.info('Session restoration declined by hook', {
629
+ sessionId,
630
+ returnValue: restoredContext === null ? 'null' : 'undefined'
631
+ });
632
+ res.status(400).json({
633
+ jsonrpc: '2.0',
634
+ error: {
635
+ code: -32000,
636
+ message: 'Session not found or expired'
637
+ },
638
+ id: req.body?.id || null
639
+ });
640
+ return;
641
+ }
642
+ const validation = (0, instance_context_1.validateInstanceContext)(restoredContext);
643
+ if (!validation.valid) {
644
+ logger_1.logger.error('Invalid context returned from restoration hook', {
645
+ sessionId,
646
+ errors: validation.errors
647
+ });
648
+ res.status(400).json({
649
+ jsonrpc: '2.0',
650
+ error: {
651
+ code: -32000,
652
+ message: 'Invalid session context'
653
+ },
654
+ id: req.body?.id || null
655
+ });
656
+ return;
657
+ }
658
+ logger_1.logger.info('Session restoration successful, creating session', {
659
+ sessionId,
660
+ instanceId: restoredContext.instanceId
661
+ });
662
+ await this.createSession(restoredContext, sessionId, true);
663
+ if (!this.transports[sessionId]) {
664
+ logger_1.logger.error('Session creation failed after restoration', { sessionId });
665
+ res.status(500).json({
666
+ jsonrpc: '2.0',
667
+ error: {
668
+ code: -32603,
669
+ message: 'Session creation failed'
670
+ },
671
+ id: req.body?.id || null
672
+ });
673
+ return;
674
+ }
675
+ this.emitEvent('onSessionRestored', sessionId, restoredContext).catch(err => {
676
+ logger_1.logger.error('Failed to emit onSessionRestored event (non-blocking)', {
677
+ sessionId,
678
+ error: err instanceof Error ? err.message : String(err)
679
+ });
680
+ });
681
+ transport = this.transports[sessionId];
682
+ logger_1.logger.info('Using restored session transport', { sessionId });
683
+ }
684
+ catch (error) {
685
+ if (error instanceof Error && error.name === 'TimeoutError') {
686
+ logger_1.logger.error('Session restoration timeout', {
687
+ sessionId,
688
+ timeout: this.sessionRestorationTimeout
689
+ });
690
+ res.status(408).json({
691
+ jsonrpc: '2.0',
692
+ error: {
693
+ code: -32000,
694
+ message: 'Session restoration timeout'
695
+ },
696
+ id: req.body?.id || null
697
+ });
698
+ return;
699
+ }
700
+ logger_1.logger.error('Session restoration failed', {
701
+ sessionId,
702
+ error: error instanceof Error ? error.message : String(error)
703
+ });
704
+ res.status(500).json({
705
+ jsonrpc: '2.0',
706
+ error: {
707
+ code: -32603,
708
+ message: 'Session restoration failed'
709
+ },
710
+ id: req.body?.id || null
711
+ });
712
+ return;
713
+ }
714
+ }
715
+ else {
716
+ logger_1.logger.warn('Session not found and no restoration hook configured', {
717
+ sessionId
718
+ });
719
+ res.status(400).json({
720
+ jsonrpc: '2.0',
721
+ error: {
722
+ code: -32000,
723
+ message: 'Session not found or expired'
724
+ },
725
+ id: req.body?.id || null
726
+ });
727
+ return;
728
+ }
363
729
  }
364
- else if (sessionId && !this.transports[sessionId]) {
365
- errorMessage = 'Bad Request: Session not found or expired';
730
+ else {
731
+ logger_1.logger.warn('handleRequest: Invalid request - no session ID and not initialize', {
732
+ isInitialize
733
+ });
734
+ res.status(400).json({
735
+ jsonrpc: '2.0',
736
+ error: {
737
+ code: -32000,
738
+ message: 'Bad Request: No valid session ID provided and not an initialize request'
739
+ },
740
+ id: req.body?.id || null
741
+ });
742
+ return;
366
743
  }
367
- res.status(400).json({
368
- jsonrpc: '2.0',
369
- error: {
370
- code: -32000,
371
- message: errorMessage
372
- },
373
- id: req.body?.id || null
374
- });
375
- return;
376
744
  }
377
745
  logger_1.logger.info('handleRequest: Handling request with transport', {
378
746
  sessionId: isInitialize ? 'new' : sessionId,
@@ -1018,6 +1386,117 @@ class SingleSessionHTTPServer {
1018
1386
  }
1019
1387
  };
1020
1388
  }
1389
+ getActiveSessions() {
1390
+ return Object.keys(this.sessionMetadata);
1391
+ }
1392
+ getSessionState(sessionId) {
1393
+ const metadata = this.sessionMetadata[sessionId];
1394
+ if (!metadata) {
1395
+ return null;
1396
+ }
1397
+ const instanceContext = this.sessionContexts[sessionId];
1398
+ const expiresAt = new Date(metadata.lastAccess.getTime() + this.sessionTimeout);
1399
+ return {
1400
+ sessionId,
1401
+ instanceContext: instanceContext || {
1402
+ n8nApiUrl: process.env.N8N_API_URL,
1403
+ n8nApiKey: process.env.N8N_API_KEY,
1404
+ instanceId: process.env.N8N_INSTANCE_ID
1405
+ },
1406
+ createdAt: metadata.createdAt,
1407
+ lastAccess: metadata.lastAccess,
1408
+ expiresAt,
1409
+ metadata: instanceContext?.metadata
1410
+ };
1411
+ }
1412
+ getAllSessionStates() {
1413
+ const sessionIds = this.getActiveSessions();
1414
+ const states = [];
1415
+ for (const sessionId of sessionIds) {
1416
+ const state = this.getSessionState(sessionId);
1417
+ if (state) {
1418
+ states.push(state);
1419
+ }
1420
+ }
1421
+ return states;
1422
+ }
1423
+ manuallyRestoreSession(sessionId, instanceContext) {
1424
+ try {
1425
+ if (!this.isValidSessionId(sessionId)) {
1426
+ logger_1.logger.error('Invalid session ID format in manual restoration', { sessionId });
1427
+ return false;
1428
+ }
1429
+ const validation = (0, instance_context_1.validateInstanceContext)(instanceContext);
1430
+ if (!validation.valid) {
1431
+ logger_1.logger.error('Invalid instance context in manual restoration', {
1432
+ sessionId,
1433
+ errors: validation.errors
1434
+ });
1435
+ return false;
1436
+ }
1437
+ this.sessionMetadata[sessionId] = {
1438
+ lastAccess: new Date(),
1439
+ createdAt: new Date()
1440
+ };
1441
+ this.sessionContexts[sessionId] = instanceContext;
1442
+ const creationResult = this.createSession(instanceContext, sessionId, false);
1443
+ Promise.resolve(creationResult).catch(error => {
1444
+ logger_1.logger.error('Async session creation failed in manual restoration', {
1445
+ sessionId,
1446
+ error: error instanceof Error ? error.message : String(error)
1447
+ });
1448
+ delete this.sessionMetadata[sessionId];
1449
+ delete this.sessionContexts[sessionId];
1450
+ });
1451
+ logger_1.logger.info('Session manually restored', {
1452
+ sessionId,
1453
+ instanceId: instanceContext.instanceId
1454
+ });
1455
+ return true;
1456
+ }
1457
+ catch (error) {
1458
+ logger_1.logger.error('Failed to manually restore session', {
1459
+ sessionId,
1460
+ error: error instanceof Error ? error.message : String(error)
1461
+ });
1462
+ return false;
1463
+ }
1464
+ }
1465
+ manuallyDeleteSession(sessionId) {
1466
+ if (!this.sessionMetadata[sessionId]) {
1467
+ logger_1.logger.debug('Session not found for manual deletion', { sessionId });
1468
+ return false;
1469
+ }
1470
+ try {
1471
+ if (this.transports[sessionId]) {
1472
+ this.transports[sessionId].close().catch(error => {
1473
+ logger_1.logger.warn('Error closing transport during manual deletion', {
1474
+ sessionId,
1475
+ error: error instanceof Error ? error.message : String(error)
1476
+ });
1477
+ });
1478
+ }
1479
+ this.emitEvent('onSessionDeleted', sessionId).catch(err => {
1480
+ logger_1.logger.error('Failed to emit onSessionDeleted event (non-blocking)', {
1481
+ sessionId,
1482
+ error: err instanceof Error ? err.message : String(err)
1483
+ });
1484
+ });
1485
+ delete this.transports[sessionId];
1486
+ delete this.servers[sessionId];
1487
+ delete this.sessionMetadata[sessionId];
1488
+ delete this.sessionContexts[sessionId];
1489
+ logger_1.logger.info('Session manually deleted', { sessionId });
1490
+ return true;
1491
+ }
1492
+ catch (error) {
1493
+ logger_1.logger.error('Error during manual session deletion', {
1494
+ sessionId,
1495
+ error: error instanceof Error ? error.message : String(error)
1496
+ });
1497
+ return false;
1498
+ }
1499
+ }
1021
1500
  }
1022
1501
  exports.SingleSessionHTTPServer = SingleSessionHTTPServer;
1023
1502
  if (require.main === module) {