@xopcai/xopcbot 0.1.1 → 0.1.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.
Files changed (72) hide show
  1. package/dist/agent/service.js +121 -35
  2. package/dist/agent/service.js.map +1 -1
  3. package/dist/channels/telegram/command-handler.d.ts +3 -0
  4. package/dist/channels/telegram/command-handler.js +69 -0
  5. package/dist/channels/telegram/command-handler.js.map +1 -1
  6. package/dist/channels/telegram/plugin.d.ts +1 -0
  7. package/dist/channels/telegram/plugin.js +97 -1
  8. package/dist/channels/telegram/plugin.js.map +1 -1
  9. package/dist/cli/commands/config.js +59 -0
  10. package/dist/cli/commands/config.js.map +1 -1
  11. package/dist/cli/commands/gateway-daemon.d.ts +1 -0
  12. package/dist/cli/commands/gateway-daemon.js +141 -0
  13. package/dist/cli/commands/gateway-daemon.js.map +1 -0
  14. package/dist/cli/commands/gateway.js +387 -45
  15. package/dist/cli/commands/gateway.js.map +1 -1
  16. package/dist/cli/commands/onboard.js +198 -0
  17. package/dist/cli/commands/onboard.js.map +1 -1
  18. package/dist/cli/index.js +17 -5
  19. package/dist/cli/index.js.map +1 -1
  20. package/dist/config/paths.js +13 -8
  21. package/dist/config/paths.js.map +1 -1
  22. package/dist/config/schema.d.ts +22 -0
  23. package/dist/config/schema.js +16 -0
  24. package/dist/config/schema.js.map +1 -1
  25. package/dist/daemon/background-start.d.ts +33 -0
  26. package/dist/daemon/background-start.js +89 -0
  27. package/dist/daemon/background-start.js.map +1 -0
  28. package/dist/daemon/gateway-manager.d.ts +87 -0
  29. package/dist/daemon/gateway-manager.js +324 -0
  30. package/dist/daemon/gateway-manager.js.map +1 -0
  31. package/dist/daemon/index.d.ts +5 -0
  32. package/dist/daemon/index.js +6 -0
  33. package/dist/daemon/index.js.map +1 -0
  34. package/dist/gateway/__tests__/auth.test.d.ts +1 -0
  35. package/dist/gateway/__tests__/auth.test.js +128 -0
  36. package/dist/gateway/__tests__/auth.test.js.map +1 -0
  37. package/dist/gateway/__tests__/process-manager.test.d.ts +4 -0
  38. package/dist/gateway/__tests__/process-manager.test.js +140 -0
  39. package/dist/gateway/__tests__/process-manager.test.js.map +1 -0
  40. package/dist/gateway/auth.d.ts +33 -0
  41. package/dist/gateway/auth.js +94 -0
  42. package/dist/gateway/auth.js.map +1 -0
  43. package/dist/gateway/hono/app.js +54 -15
  44. package/dist/gateway/hono/app.js.map +1 -1
  45. package/dist/gateway/index.d.ts +3 -0
  46. package/dist/gateway/index.js +3 -0
  47. package/dist/gateway/index.js.map +1 -1
  48. package/dist/gateway/pid-file.d.ts +35 -0
  49. package/dist/gateway/pid-file.js +111 -0
  50. package/dist/gateway/pid-file.js.map +1 -0
  51. package/dist/gateway/port-checker.d.ts +24 -0
  52. package/dist/gateway/port-checker.js +132 -0
  53. package/dist/gateway/port-checker.js.map +1 -0
  54. package/dist/gateway/process-manager.d.ts +62 -0
  55. package/dist/gateway/process-manager.js +370 -0
  56. package/dist/gateway/process-manager.js.map +1 -0
  57. package/dist/gateway/process-manager.types.d.ts +64 -0
  58. package/dist/gateway/process-manager.types.js +5 -0
  59. package/dist/gateway/process-manager.types.js.map +1 -0
  60. package/dist/gateway/server.js +3 -1
  61. package/dist/gateway/server.js.map +1 -1
  62. package/dist/gateway/service.d.ts +20 -0
  63. package/dist/gateway/service.js +67 -0
  64. package/dist/gateway/service.js.map +1 -1
  65. package/dist/gateway/static/root/assets/{main-CfIxL-cL.js → main-DevbZW9K.js} +373 -251
  66. package/dist/gateway/static/root/assets/main-DevbZW9K.js.map +1 -0
  67. package/dist/gateway/static/root/assets/{main-DndcTCgX.css → main-DxZg1Nmz.css} +1 -1
  68. package/dist/gateway/static/root/index.html +2 -2
  69. package/dist/session/store.js +11 -2
  70. package/dist/session/store.js.map +1 -1
  71. package/package.json +2 -2
  72. package/dist/gateway/static/root/assets/main-CfIxL-cL.js.map +0 -1
@@ -0,0 +1,370 @@
1
+ /**
2
+ * Gateway Process Manager
3
+ *
4
+ * Manages the lifecycle of the gateway server process.
5
+ * Supports starting, stopping, and restarting the gateway in background mode.
6
+ */
7
+ import { spawn } from 'child_process';
8
+ import { existsSync, appendFileSync, mkdirSync } from 'fs';
9
+ import { dirname, join } from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import { createLogger } from '../utils/logger.js';
12
+ import { writePidFile, readPidFile, removePidFile, processExists, cleanupStalePidFile, } from './pid-file.js';
13
+ import { checkPortAvailable, getProcessUsingPort, formatPortConflictError } from './port-checker.js';
14
+ const log = createLogger('GatewayProcessManager');
15
+ // Get __dirname equivalent in ESM
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = dirname(__filename);
18
+ // Project root (go up from src/gateway to project root)
19
+ const PROJECT_ROOT = join(__dirname, '..', '..');
20
+ // Default log file location
21
+ const DEFAULT_LOG_DIR = join(process.env.HOME || process.env.USERPROFILE || '.', '.xopcbot', 'logs');
22
+ const DEFAULT_LOG_FILE = join(DEFAULT_LOG_DIR, 'gateway.log');
23
+ /**
24
+ * Gateway Process Manager class
25
+ */
26
+ export class GatewayProcessManager {
27
+ childProcess = null;
28
+ config = null;
29
+ startTime = null;
30
+ /**
31
+ * Check if gateway is currently running
32
+ */
33
+ isRunning() {
34
+ // First check PID file
35
+ const pid = readPidFile();
36
+ if (pid === null) {
37
+ // No PID file, check if we have an active child process
38
+ return this.childProcess !== null && !this.childProcess.killed;
39
+ }
40
+ // Check if process exists
41
+ if (!processExists(pid)) {
42
+ // Process doesn't exist, clean up stale PID file
43
+ cleanupStalePidFile();
44
+ return false;
45
+ }
46
+ return true;
47
+ }
48
+ /**
49
+ * Get current gateway status
50
+ */
51
+ getStatus() {
52
+ const pid = readPidFile();
53
+ if (!this.isRunning()) {
54
+ return {
55
+ running: false,
56
+ };
57
+ }
58
+ const uptime = this.startTime ? Date.now() - this.startTime : 0;
59
+ return {
60
+ running: true,
61
+ pid: pid || undefined,
62
+ port: this.config?.port,
63
+ host: this.config?.host,
64
+ uptime,
65
+ health: 'unknown', // Would need health check endpoint to determine
66
+ };
67
+ }
68
+ /**
69
+ * Start gateway process
70
+ */
71
+ async start(config) {
72
+ log.info({ host: config.host, port: config.port, background: config.background }, 'Starting gateway process');
73
+ // Check if already running
74
+ if (this.isRunning()) {
75
+ log.warn('Gateway is already running');
76
+ return {
77
+ success: false,
78
+ alreadyRunning: true,
79
+ error: 'Gateway is already running. Use "xopcbot gateway restart" to restart.',
80
+ };
81
+ }
82
+ // Clean up any stale PID file
83
+ cleanupStalePidFile();
84
+ // Check if port is available
85
+ const portAvailable = await checkPortAvailable(config.port, config.host);
86
+ if (!portAvailable) {
87
+ const pid = await getProcessUsingPort(config.port);
88
+ const errorMessage = formatPortConflictError(config.port, config.host, pid);
89
+ log.error({ port: config.port, host: config.host, pid }, 'Port is in use');
90
+ return {
91
+ success: false,
92
+ portInUse: true,
93
+ error: errorMessage,
94
+ };
95
+ }
96
+ // Build command arguments
97
+ const args = ['gateway'];
98
+ if (config.host && config.host !== '0.0.0.0') {
99
+ args.push('--host', config.host);
100
+ }
101
+ if (config.port) {
102
+ args.push('--port', String(config.port));
103
+ }
104
+ if (config.token) {
105
+ args.push('--token', config.token);
106
+ }
107
+ if (config.configPath) {
108
+ args.push('--config', config.configPath);
109
+ }
110
+ if (config.verbose) {
111
+ args.push('--verbose');
112
+ }
113
+ if (config.enableHotReload === false) {
114
+ args.push('--no-hot-reload');
115
+ }
116
+ try {
117
+ if (config.background) {
118
+ // Background mode: spawn detached process
119
+ await this.startBackground(config, args);
120
+ }
121
+ else {
122
+ // Foreground mode: spawn attached process
123
+ await this.startForeground(config, args);
124
+ }
125
+ this.config = config;
126
+ this.startTime = Date.now();
127
+ log.info({ pid: this.childProcess?.pid }, 'Gateway process started');
128
+ return {
129
+ success: true,
130
+ pid: this.childProcess?.pid,
131
+ };
132
+ }
133
+ catch (err) {
134
+ const error = err instanceof Error ? err.message : String(err);
135
+ log.error({ err }, 'Failed to start gateway process');
136
+ return {
137
+ success: false,
138
+ error,
139
+ };
140
+ }
141
+ }
142
+ /**
143
+ * Start gateway in background mode (detached process)
144
+ */
145
+ async startBackground(config, args) {
146
+ const logFile = config.logFile || DEFAULT_LOG_FILE;
147
+ // Ensure log directory exists
148
+ const logDir = dirname(logFile);
149
+ if (!existsSync(logDir)) {
150
+ mkdirSync(logDir, { recursive: true });
151
+ }
152
+ // Always use compiled JS for background mode to avoid tsx complexity
153
+ // This ensures clean process detachment
154
+ // __dirname is dist/gateway, so we need to go up one level to dist
155
+ const cliPath = join(__dirname, '..', 'cli', 'index.js');
156
+ // Check if compiled code exists
157
+ if (!existsSync(cliPath)) {
158
+ throw new Error('Compiled code not found. Please run "pnpm run build" before using background mode, ' +
159
+ 'or use foreground mode (without --background) for development.');
160
+ }
161
+ // Use node with compiled JS
162
+ this.childProcess = spawn('node', [cliPath, ...args], {
163
+ detached: true,
164
+ stdio: 'ignore',
165
+ env: { ...process.env },
166
+ shell: false,
167
+ });
168
+ // Write PID file after process is spawned
169
+ if (this.childProcess.pid) {
170
+ writePidFile(this.childProcess.pid);
171
+ log.info({ pid: this.childProcess.pid, logFile }, 'Gateway running in background');
172
+ }
173
+ // Don't attach any event listeners - they would prevent unref from working
174
+ // The child process is now fully detached and will run independently
175
+ // Allow parent process to exit immediately
176
+ this.childProcess.unref();
177
+ }
178
+ /**
179
+ * Start gateway in foreground mode (attached process)
180
+ */
181
+ async startForeground(config, args) {
182
+ const cliPath = join(__dirname, 'cli', 'index.js');
183
+ const isDevelopment = !existsSync(cliPath);
184
+ const command = isDevelopment ? 'tsx' : 'node';
185
+ const commandArgs = isDevelopment
186
+ ? [join(PROJECT_ROOT, 'src', 'cli', 'index.ts'), ...args]
187
+ : [cliPath, ...args];
188
+ this.childProcess = spawn(command, commandArgs, {
189
+ stdio: 'inherit', // Inherit stdin/stdout/stderr from parent
190
+ env: { ...process.env },
191
+ shell: false,
192
+ cwd: isDevelopment ? PROJECT_ROOT : undefined,
193
+ });
194
+ // Handle process exit
195
+ this.childProcess.on('exit', (code, signal) => {
196
+ log.info({ code, signal }, 'Gateway process exited');
197
+ this.childProcess = null;
198
+ this.startTime = null;
199
+ removePidFile();
200
+ });
201
+ // Write PID file
202
+ if (this.childProcess.pid) {
203
+ writePidFile(this.childProcess.pid);
204
+ }
205
+ // Don't detach - keep attached to parent process
206
+ }
207
+ /**
208
+ * Append data to log file
209
+ */
210
+ appendToLogFile(logFile, data) {
211
+ try {
212
+ const timestamp = new Date().toISOString();
213
+ const content = `[${timestamp}] ${data.toString()}`;
214
+ appendFileSync(logFile, content, 'utf-8');
215
+ }
216
+ catch (err) {
217
+ log.error({ err }, 'Failed to write to log file');
218
+ }
219
+ }
220
+ /**
221
+ * Stop gateway process gracefully
222
+ */
223
+ async stop(options = {}) {
224
+ const { timeout = 5000, force = false } = options;
225
+ log.info({ timeout, force }, 'Stopping gateway process');
226
+ // Check if running
227
+ const wasRunning = this.isRunning();
228
+ if (!wasRunning) {
229
+ log.info('Gateway is not running');
230
+ return {
231
+ success: true,
232
+ wasRunning: false,
233
+ };
234
+ }
235
+ const pid = readPidFile() || this.childProcess?.pid;
236
+ if (!pid) {
237
+ return {
238
+ success: false,
239
+ error: 'Could not determine gateway PID',
240
+ };
241
+ }
242
+ try {
243
+ if (force) {
244
+ // Force kill immediately
245
+ process.kill(pid, 'SIGKILL');
246
+ log.info({ pid }, 'Gateway process force killed');
247
+ }
248
+ else {
249
+ // Graceful shutdown with timeout
250
+ await this.gracefulShutdown(pid, timeout);
251
+ }
252
+ // Clean up PID file
253
+ removePidFile();
254
+ this.childProcess = null;
255
+ this.startTime = null;
256
+ this.config = null;
257
+ return {
258
+ success: true,
259
+ wasRunning: true,
260
+ };
261
+ }
262
+ catch (err) {
263
+ const error = err instanceof Error ? err.message : String(err);
264
+ log.error({ err, pid }, 'Failed to stop gateway process');
265
+ return {
266
+ success: false,
267
+ error,
268
+ wasRunning: true,
269
+ };
270
+ }
271
+ }
272
+ /**
273
+ * Perform graceful shutdown with timeout
274
+ */
275
+ async gracefulShutdown(pid, timeout) {
276
+ return new Promise((resolve, reject) => {
277
+ let completed = false;
278
+ // Send SIGTERM for graceful shutdown
279
+ try {
280
+ process.kill(pid, 'SIGTERM');
281
+ }
282
+ catch (err) {
283
+ reject(err);
284
+ return;
285
+ }
286
+ // Set timeout for force kill
287
+ const timeoutId = setTimeout(() => {
288
+ if (completed)
289
+ return;
290
+ log.warn({ pid }, 'Graceful shutdown timed out, force killing');
291
+ try {
292
+ process.kill(pid, 'SIGKILL');
293
+ completed = true;
294
+ resolve();
295
+ }
296
+ catch (err) {
297
+ reject(err);
298
+ }
299
+ }, timeout);
300
+ // Poll for process exit
301
+ const checkInterval = setInterval(() => {
302
+ if (!processExists(pid)) {
303
+ clearInterval(checkInterval);
304
+ clearTimeout(timeoutId);
305
+ completed = true;
306
+ log.info({ pid }, 'Gateway process stopped gracefully');
307
+ resolve();
308
+ }
309
+ }, 100);
310
+ });
311
+ }
312
+ /**
313
+ * Restart gateway process
314
+ */
315
+ async restart(config) {
316
+ log.info('Restarting gateway process');
317
+ // Stop current process
318
+ await this.stop({ timeout: 5000 });
319
+ // Wait a bit for port to be released
320
+ await new Promise(resolve => setTimeout(resolve, 500));
321
+ // Start with new or existing config
322
+ const startConfig = config || this.config;
323
+ if (!startConfig) {
324
+ throw new Error('No configuration available for restart');
325
+ }
326
+ const result = await this.start(startConfig);
327
+ if (!result.success) {
328
+ throw new Error(result.error || 'Failed to restart gateway');
329
+ }
330
+ }
331
+ /**
332
+ * Get gateway log file path
333
+ */
334
+ getLogFile() {
335
+ return this.config?.logFile || DEFAULT_LOG_FILE;
336
+ }
337
+ /**
338
+ * Get recent logs (tail)
339
+ */
340
+ async getLogs(options = {}) {
341
+ const { lines = 100 } = options;
342
+ const logFile = this.getLogFile();
343
+ if (!existsSync(logFile)) {
344
+ return '';
345
+ }
346
+ try {
347
+ const { exec } = await import('child_process');
348
+ return new Promise((resolve) => {
349
+ const cmd = process.platform === 'win32'
350
+ ? `powershell -Command "Get-Content '${logFile}' -Tail ${lines}"`
351
+ : `tail -n ${lines} "${logFile}"`;
352
+ exec(cmd, (error, stdout) => {
353
+ if (error) {
354
+ resolve('');
355
+ }
356
+ else {
357
+ resolve(stdout);
358
+ }
359
+ });
360
+ });
361
+ }
362
+ catch (err) {
363
+ log.error({ err }, 'Failed to read logs');
364
+ return '';
365
+ }
366
+ }
367
+ }
368
+ // Export singleton instance for convenience
369
+ export const gatewayProcessManager = new GatewayProcessManager();
370
+ //# sourceMappingURL=process-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-manager.js","sourceRoot":"","sources":["../../src/gateway/process-manager.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,KAAK,EAAqB,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAQlD,OAAO,EACL,YAAY,EACZ,WAAW,EACX,aAAa,EACb,aAAa,EACb,mBAAmB,GACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAErG,MAAM,GAAG,GAAG,YAAY,CAAC,uBAAuB,CAAC,CAAC;AAElD,kCAAkC;AAClC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAEtC,wDAAwD;AACxD,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAEjD,4BAA4B;AAC5B,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO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qCAAqC,OAAO,WAAW,KAAK,GAAG;oBACjE,CAAC,CAAC,WAAW,KAAK,KAAK,OAAO,GAAG,CAAC;gBAEpC,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;oBAC1B,IAAI,KAAK,EAAE,CAAC;wBACV,OAAO,CAAC,EAAE,CAAC,CAAC;oBACd,CAAC;yBAAM,CAAC;wBACN,OAAO,CAAC,MAAM,CAAC,CAAC;oBAClB,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,EAAE,qBAAqB,CAAC,CAAC;YAC1C,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AAED,4CAA4C;AAC5C,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,qBAAqB,EAAE,CAAC"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Gateway Process Manager Types
3
+ */
4
+ /**
5
+ * Gateway process status
6
+ */
7
+ export interface GatewayStatus {
8
+ running: boolean;
9
+ pid?: number;
10
+ port?: number;
11
+ host?: string;
12
+ uptime?: number;
13
+ health?: 'healthy' | 'unhealthy' | 'unknown';
14
+ lastError?: string;
15
+ }
16
+ /**
17
+ * Configuration for starting gateway process
18
+ */
19
+ export interface GatewayProcessConfig {
20
+ /** Host to bind to */
21
+ host: string;
22
+ /** Port to listen on */
23
+ port: number;
24
+ /** Authentication token (optional, will use config if not provided) */
25
+ token?: string;
26
+ /** Config file path */
27
+ configPath?: string;
28
+ /** Enable verbose logging */
29
+ verbose?: boolean;
30
+ /** Run in background (daemon mode) */
31
+ background?: boolean;
32
+ /** Log file path for background mode */
33
+ logFile?: string;
34
+ /** Enable config hot reload */
35
+ enableHotReload?: boolean;
36
+ }
37
+ /**
38
+ * Result of starting gateway process
39
+ */
40
+ export interface StartResult {
41
+ success: boolean;
42
+ pid?: number;
43
+ error?: string;
44
+ portInUse?: boolean;
45
+ alreadyRunning?: boolean;
46
+ }
47
+ /**
48
+ * Result of stopping gateway process
49
+ */
50
+ export interface StopResult {
51
+ success: boolean;
52
+ error?: string;
53
+ timedOut?: boolean;
54
+ wasRunning?: boolean;
55
+ }
56
+ /**
57
+ * Options for stopping gateway process
58
+ */
59
+ export interface StopOptions {
60
+ /** Timeout in milliseconds before force kill */
61
+ timeout?: number;
62
+ /** Force kill immediately */
63
+ force?: boolean;
64
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Gateway Process Manager Types
3
+ */
4
+ export {};
5
+ //# sourceMappingURL=process-manager.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-manager.types.js","sourceRoot":"","sources":["../../src/gateway/process-manager.types.ts"],"names":[],"mappings":"AAAA;;GAEG"}
@@ -19,9 +19,11 @@ export class GatewayServer {
19
19
  // Start the underlying service first
20
20
  await this.service.start();
21
21
  // Create Hono app
22
+ // Priority: CLI token > service auto-generated token
23
+ const effectiveToken = this.config.token || this.serviceInstance.getAuthToken();
22
24
  const app = createHonoApp({
23
25
  service: this.service,
24
- token: this.config.token,
26
+ token: effectiveToken,
25
27
  });
26
28
  // Create Node.js HTTP server (no WebSocket upgrade needed)
27
29
  this.server = serve({
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/gateway/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAmB,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C,MAAM,GAAG,GAAG,YAAY,CAAC,eAAe,CAAC,CAAC;AAW1C,MAAM,OAAO,aAAa;IAChB,MAAM,CAAc;IACpB,MAAM,CAAsB;IAC5B,OAAO,CAAiB;IAEhC,YA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AM,EAAE,CAAC;YAChB,uEAAuE;YACvE,MAAM,UAAU,GAAG,UAAU,CAAC,GAAG,EAAE;gBACjC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;oBACf,IAAI,CAAC,MAAc,CAAC,mBAAmB,EAAE,EAAE,CAAC;gBAC/C,CAAC;YACH,CAAC,EAAE,IAAI,CAAC,CAAC;YAET,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;gBAClC,IAAI,CAAC,MAAO,CAAC,KAAK,CAAC,GAAG,EAAE;oBACtB,YAAY,CAAC,UAAU,CAAC,CAAC;oBACzB,OAAO,EAAE,CAAC;gBACZ,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QAC1B,CAAC;QAED,8BAA8B;QAC9B,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;QAE1B,GAAG,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IACrC,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC;IACnC,CAAC;IAED,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF"}
@@ -27,6 +27,7 @@ export declare class GatewayService {
27
27
  private configReloader;
28
28
  private startTime;
29
29
  private workspacePath;
30
+ private auth;
30
31
  private eventCounter;
31
32
  private subscribers;
32
33
  private eventBuffers;
@@ -261,5 +262,24 @@ export declare class GatewayService {
261
262
  chatId: string;
262
263
  lastActive: string;
263
264
  }>>;
265
+ /**
266
+ * Validate authentication token from request headers.
267
+ * Returns true if auth is disabled (mode: 'none') or token is valid.
268
+ */
269
+ validateAuth(headers?: Record<string, string | string[] | undefined>): boolean;
270
+ /**
271
+ * Get current auth mode.
272
+ */
273
+ getAuthMode(): 'none' | 'token';
274
+ /**
275
+ * Get current auth token (for CLI server integration).
276
+ * Returns undefined if mode is 'none'.
277
+ */
278
+ getAuthToken(): string | undefined;
279
+ /**
280
+ * Refresh (regenerate) the gateway auth token.
281
+ * Returns the new token.
282
+ */
283
+ refreshAuthToken(): Promise<string>;
264
284
  }
265
285
  export {};
@@ -11,6 +11,7 @@ import { PluginLoader, normalizePluginConfig } from '../plugins/index.js';
11
11
  import { HeartbeatService } from '../heartbeat/index.js';
12
12
  import { ConfigHotReloader } from '../config/reload.js';
13
13
  import { SessionManager } from '../session/index.js';
14
+ import { resolveGatewayAuth, assertGatewayAuthConfigured, validateToken, extractToken } from './auth.js';
14
15
  const log = createLogger('GatewayService');
15
16
  const EVENT_BUFFER_SIZE = 200; // ring buffer per subscriber for Last-Event-ID replay
16
17
  export class GatewayService {
@@ -28,6 +29,8 @@ export class GatewayService {
28
29
  configReloader = null;
29
30
  startTime = Date.now();
30
31
  workspacePath;
32
+ // Authentication
33
+ auth;
31
34
  // SSE event system
32
35
  eventCounter = 0;
33
36
  subscribers = new Map();
@@ -37,6 +40,20 @@ export class GatewayService {
37
40
  this.bus = new MessageBus();
38
41
  this.configPath = serviceConfig.configPath || DEFAULT_PATHS.config;
39
42
  this.config = loadConfig(this.configPath);
43
+ // Initialize authentication
44
+ this.auth = resolveGatewayAuth({
45
+ authConfig: this.config.gateway?.auth,
46
+ });
47
+ // Validate auth configuration
48
+ assertGatewayAuthConfigured(this.auth);
49
+ // Log token info (not the token itself)
50
+ if (this.auth.mode === 'token') {
51
+ const tokenPreview = this.auth.token ? `${this.auth.token.slice(0, 8)}...` : 'none';
52
+ log.info({ mode: this.auth.mode, tokenPreview }, 'Gateway authentication configured');
53
+ }
54
+ else {
55
+ log.warn({ mode: this.auth.mode }, 'Gateway authentication disabled (no auth required)');
56
+ }
40
57
  // Initialize channel manager
41
58
  this.channelManager = new ChannelManager(this.config, this.bus);
42
59
  // Initialize plugin loader
@@ -617,5 +634,55 @@ export class GatewayService {
617
634
  }
618
635
  return chatIds;
619
636
  }
637
+ /**
638
+ * Validate authentication token from request headers.
639
+ * Returns true if auth is disabled (mode: 'none') or token is valid.
640
+ */
641
+ validateAuth(headers) {
642
+ const token = extractToken(headers);
643
+ return validateToken(this.auth, token);
644
+ }
645
+ /**
646
+ * Get current auth mode.
647
+ */
648
+ getAuthMode() {
649
+ return this.auth.mode;
650
+ }
651
+ /**
652
+ * Get current auth token (for CLI server integration).
653
+ * Returns undefined if mode is 'none'.
654
+ */
655
+ getAuthToken() {
656
+ return this.auth.mode === 'token' ? this.auth.token : undefined;
657
+ }
658
+ /**
659
+ * Refresh (regenerate) the gateway auth token.
660
+ * Returns the new token.
661
+ */
662
+ async refreshAuthToken() {
663
+ if (this.auth.mode !== 'token') {
664
+ throw new Error('Cannot refresh token: auth mode is not token');
665
+ }
666
+ // Generate new token
667
+ const newToken = crypto.randomBytes(24).toString('hex');
668
+ // Update in-memory auth
669
+ this.auth.token = newToken;
670
+ // Update config
671
+ this.config = {
672
+ ...this.config,
673
+ gateway: {
674
+ ...this.config.gateway,
675
+ auth: {
676
+ ...this.config.gateway?.auth,
677
+ mode: 'token',
678
+ token: newToken,
679
+ },
680
+ },
681
+ };
682
+ // Save to disk
683
+ await saveConfig(this.config, this.configPath);
684
+ log.info({ tokenPreview: `${newToken.slice(0, 8)}...` }, 'Gateway token refreshed');
685
+ return newToken;
686
+ }
620
687
  }
621
688
  //# sourceMappingURL=service.js.map