@mmmbuto/nexuscli 0.5.0

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 (148) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +172 -0
  3. package/bin/nexuscli.js +117 -0
  4. package/frontend/dist/apple-touch-icon.png +0 -0
  5. package/frontend/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  6. package/frontend/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  7. package/frontend/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  8. package/frontend/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  9. package/frontend/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  10. package/frontend/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  11. package/frontend/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  12. package/frontend/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  13. package/frontend/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  14. package/frontend/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  15. package/frontend/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  16. package/frontend/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  17. package/frontend/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  18. package/frontend/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  19. package/frontend/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  20. package/frontend/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  21. package/frontend/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  22. package/frontend/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  23. package/frontend/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  24. package/frontend/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  25. package/frontend/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  26. package/frontend/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  27. package/frontend/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  28. package/frontend/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  29. package/frontend/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  30. package/frontend/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  31. package/frontend/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  32. package/frontend/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  33. package/frontend/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  34. package/frontend/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  35. package/frontend/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  36. package/frontend/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  37. package/frontend/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  38. package/frontend/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  39. package/frontend/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  40. package/frontend/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  41. package/frontend/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  42. package/frontend/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  43. package/frontend/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  44. package/frontend/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  45. package/frontend/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  46. package/frontend/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  47. package/frontend/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  48. package/frontend/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  49. package/frontend/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  50. package/frontend/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  51. package/frontend/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  52. package/frontend/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  53. package/frontend/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  54. package/frontend/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  55. package/frontend/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  56. package/frontend/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  57. package/frontend/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  58. package/frontend/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  59. package/frontend/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  60. package/frontend/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  61. package/frontend/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  62. package/frontend/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  63. package/frontend/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  64. package/frontend/dist/assets/index-Bn_l1e6e.css +1 -0
  65. package/frontend/dist/assets/index-CikJbUR5.js +8617 -0
  66. package/frontend/dist/browserconfig.xml +12 -0
  67. package/frontend/dist/favicon-16x16.png +0 -0
  68. package/frontend/dist/favicon-32x32.png +0 -0
  69. package/frontend/dist/favicon-48x48.png +0 -0
  70. package/frontend/dist/favicon.ico +0 -0
  71. package/frontend/dist/icon-192.png +0 -0
  72. package/frontend/dist/icon-512.png +0 -0
  73. package/frontend/dist/icon-maskable-192.png +0 -0
  74. package/frontend/dist/icon-maskable-512.png +0 -0
  75. package/frontend/dist/index.html +79 -0
  76. package/frontend/dist/manifest.json +75 -0
  77. package/frontend/dist/sw.js +122 -0
  78. package/frontend/package.json +28 -0
  79. package/lib/cli/api.js +156 -0
  80. package/lib/cli/boot.js +172 -0
  81. package/lib/cli/config.js +185 -0
  82. package/lib/cli/engines.js +257 -0
  83. package/lib/cli/init.js +660 -0
  84. package/lib/cli/logs.js +72 -0
  85. package/lib/cli/start.js +220 -0
  86. package/lib/cli/status.js +187 -0
  87. package/lib/cli/stop.js +64 -0
  88. package/lib/cli/uninstall.js +194 -0
  89. package/lib/cli/users.js +295 -0
  90. package/lib/cli/workspaces.js +337 -0
  91. package/lib/config/manager.js +233 -0
  92. package/lib/server/.env.example +20 -0
  93. package/lib/server/db/adapter.js +314 -0
  94. package/lib/server/db/drivers/better-sqlite3.js +38 -0
  95. package/lib/server/db/drivers/sql-js.js +75 -0
  96. package/lib/server/db/migrate.js +174 -0
  97. package/lib/server/db/migrations/001_ultra_light_schema.sql +96 -0
  98. package/lib/server/db/migrations/002_session_conversation_mapping.sql +19 -0
  99. package/lib/server/db/migrations/003_message_engine_tracking.sql +18 -0
  100. package/lib/server/db/migrations/004_performance_indexes.sql +16 -0
  101. package/lib/server/db.js +2 -0
  102. package/lib/server/lib/cli-wrapper.js +164 -0
  103. package/lib/server/lib/output-parser.js +132 -0
  104. package/lib/server/lib/pty-adapter.js +57 -0
  105. package/lib/server/middleware/auth.js +103 -0
  106. package/lib/server/models/Conversation.js +259 -0
  107. package/lib/server/models/Message.js +228 -0
  108. package/lib/server/models/User.js +115 -0
  109. package/lib/server/package-lock.json +5895 -0
  110. package/lib/server/routes/auth.js +168 -0
  111. package/lib/server/routes/chat.js +206 -0
  112. package/lib/server/routes/codex.js +205 -0
  113. package/lib/server/routes/conversations.js +224 -0
  114. package/lib/server/routes/gemini.js +228 -0
  115. package/lib/server/routes/jobs.js +317 -0
  116. package/lib/server/routes/messages.js +60 -0
  117. package/lib/server/routes/models.js +198 -0
  118. package/lib/server/routes/sessions.js +285 -0
  119. package/lib/server/routes/upload.js +134 -0
  120. package/lib/server/routes/wake-lock.js +95 -0
  121. package/lib/server/routes/workspace.js +80 -0
  122. package/lib/server/routes/workspaces.js +142 -0
  123. package/lib/server/scripts/cleanup-ghost-sessions.js +71 -0
  124. package/lib/server/scripts/seed-users.js +37 -0
  125. package/lib/server/scripts/test-history-access.js +50 -0
  126. package/lib/server/server.js +227 -0
  127. package/lib/server/services/cache.js +85 -0
  128. package/lib/server/services/claude-wrapper.js +312 -0
  129. package/lib/server/services/cli-loader.js +384 -0
  130. package/lib/server/services/codex-output-parser.js +277 -0
  131. package/lib/server/services/codex-wrapper.js +224 -0
  132. package/lib/server/services/context-bridge.js +289 -0
  133. package/lib/server/services/gemini-output-parser.js +398 -0
  134. package/lib/server/services/gemini-wrapper.js +249 -0
  135. package/lib/server/services/history-sync.js +407 -0
  136. package/lib/server/services/output-parser.js +415 -0
  137. package/lib/server/services/session-manager.js +465 -0
  138. package/lib/server/services/summary-generator.js +259 -0
  139. package/lib/server/services/workspace-manager.js +516 -0
  140. package/lib/server/tests/history-sync.test.js +90 -0
  141. package/lib/server/tests/integration-session-sync.test.js +151 -0
  142. package/lib/server/tests/integration.test.js +76 -0
  143. package/lib/server/tests/performance.test.js +118 -0
  144. package/lib/server/tests/services.test.js +160 -0
  145. package/lib/setup/postinstall.js +216 -0
  146. package/lib/utils/paths.js +107 -0
  147. package/lib/utils/termux.js +145 -0
  148. package/package.json +82 -0
@@ -0,0 +1,18 @@
1
+ -- ============================================================
2
+ -- MIGRATION 003: Add engine tracking to messages
3
+ -- Enables context bridging between Claude/Codex engines
4
+ -- ============================================================
5
+
6
+ -- Add engine column to messages table
7
+ ALTER TABLE messages ADD COLUMN engine TEXT DEFAULT 'claude';
8
+
9
+ -- Index for filtering by engine
10
+ CREATE INDEX IF NOT EXISTS idx_messages_engine ON messages(engine);
11
+
12
+ -- Composite index for conversation + engine queries
13
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_engine ON messages(conversation_id, engine);
14
+
15
+ -- ============================================================
16
+ -- BACKFILL: Set engine based on metadata or default to claude
17
+ -- ============================================================
18
+ UPDATE messages SET engine = 'claude' WHERE engine IS NULL;
@@ -0,0 +1,16 @@
1
+ -- Migration 004: Performance indexes for chat list optimization
2
+ -- Created: 2025-11-22
3
+ --
4
+ -- Adds indexes to improve:
5
+ -- - Workspace filtering (sessions.workspace_path)
6
+ -- - Conversation listing (conversations.updated_at)
7
+ -- - Session-conversation joins
8
+
9
+ -- Index for workspace filtering
10
+ CREATE INDEX IF NOT EXISTS idx_sessions_workspace_path ON sessions(workspace_path);
11
+
12
+ -- Index for conversation sorting (updated_at DESC)
13
+ CREATE INDEX IF NOT EXISTS idx_conversations_updated_at ON conversations(updated_at DESC);
14
+
15
+ -- Composite index for session-conversation joins
16
+ CREATE INDEX IF NOT EXISTS idx_sessions_id_workspace ON sessions(id, workspace_path);
@@ -0,0 +1,2 @@
1
+ // Re-export adapter as main db module
2
+ module.exports = require('./db/adapter');
@@ -0,0 +1,164 @@
1
+ const pty = require('./pty-adapter');
2
+ const OutputParser = require('./output-parser');
3
+
4
+ /**
5
+ * CLI Wrapper - Generic CLI tool execution (adapted from NexusChat claude-wrapper)
6
+ * Spawns PTY processes for any CLI tool (bash, git, docker, python, etc.)
7
+ * Streams output via SSE
8
+ */
9
+ class CliWrapper {
10
+ constructor(options = {}) {
11
+ this.workspaceDir = options.workspaceDir || process.cwd();
12
+ this.activeJobs = new Map();
13
+ }
14
+
15
+ /**
16
+ * Execute command via PTY
17
+ * @param {Object} params - { jobId, tool, command, workingDir, timeout, onStatus }
18
+ * @returns {Promise<Object>} - { exitCode, stdout, stderr, duration }
19
+ */
20
+ async execute({ jobId, tool = 'bash', command, workingDir, timeout = 30000, onStatus }) {
21
+ return new Promise((resolve, reject) => {
22
+ const parser = new OutputParser();
23
+ const startTime = Date.now();
24
+
25
+ // Determine shell command
26
+ let shellCmd = '/bin/bash';
27
+ let args = ['-c', command];
28
+
29
+ // Tool-specific handling
30
+ if (tool === 'bash') {
31
+ shellCmd = '/bin/bash';
32
+ args = ['-c', command];
33
+ } else if (tool === 'python') {
34
+ shellCmd = '/usr/bin/python3';
35
+ args = ['-c', command];
36
+ } else if (tool === 'node') {
37
+ shellCmd = '/usr/bin/node';
38
+ args = ['-e', command];
39
+ } else {
40
+ // Generic: assume tool is in PATH
41
+ shellCmd = tool;
42
+ args = command.split(' ');
43
+ }
44
+
45
+ console.log(`[CliWrapper] Executing: ${tool} - ${command.substring(0, 50)}...`);
46
+ console.log(`[CliWrapper] Working dir: ${workingDir || this.workspaceDir}`);
47
+
48
+ // Spawn PTY process
49
+ let ptyProcess;
50
+ try {
51
+ ptyProcess = pty.spawn(shellCmd, args, {
52
+ name: 'xterm-color',
53
+ cols: 80,
54
+ rows: 30,
55
+ cwd: workingDir || this.workspaceDir,
56
+ env: process.env,
57
+ });
58
+ } catch (err) {
59
+ return reject(err);
60
+ }
61
+
62
+ this.activeJobs.set(jobId, ptyProcess);
63
+
64
+ let stdout = '';
65
+ let stderr = '';
66
+
67
+ // Handle timeout
68
+ const timer = setTimeout(() => {
69
+ console.log(`[CliWrapper] Job ${jobId} timeout`);
70
+ ptyProcess.kill('SIGTERM');
71
+
72
+ if (onStatus) {
73
+ onStatus({
74
+ type: 'error',
75
+ error: 'Command timeout exceeded',
76
+ timeout
77
+ });
78
+ }
79
+ }, timeout);
80
+
81
+ // Handle process errors
82
+ if (typeof ptyProcess.on === 'function') {
83
+ ptyProcess.on('error', (err) => {
84
+ console.error('[CliWrapper] Spawn error:', err);
85
+ reject(err);
86
+ });
87
+ } else if (typeof ptyProcess.onError === 'function') {
88
+ ptyProcess.onError((err) => {
89
+ console.error('[CliWrapper] Spawn error:', err);
90
+ reject(err);
91
+ });
92
+ }
93
+
94
+ // Handle output
95
+ ptyProcess.onData((data) => {
96
+ stdout += data;
97
+
98
+ // Parse output and emit status events
99
+ if (onStatus) {
100
+ try {
101
+ const events = parser.parse(data);
102
+ events.forEach(event => {
103
+ onStatus(event);
104
+ });
105
+ } catch (parseError) {
106
+ console.error('[CliWrapper] Parser error:', parseError);
107
+ }
108
+ }
109
+ });
110
+
111
+ // Handle exit
112
+ ptyProcess.onExit(({ exitCode }) => {
113
+ clearTimeout(timer);
114
+ this.activeJobs.delete(jobId);
115
+
116
+ const duration = Date.now() - startTime;
117
+
118
+ // Clean ANSI escape codes
119
+ const cleanStdout = stdout
120
+ .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // ANSI codes
121
+ .replace(/\x1B\[\?[0-9;]*[a-zA-Z]/g, '') // Private modes
122
+ .trim();
123
+
124
+ console.log(`[CliWrapper] Job ${jobId} exit: ${exitCode} (${duration}ms)`);
125
+
126
+ if (exitCode !== 0) {
127
+ // Extract stderr (if any)
128
+ stderr = cleanStdout; // In PTY mode, stderr is mixed with stdout
129
+ }
130
+
131
+ resolve({
132
+ exitCode,
133
+ stdout: cleanStdout,
134
+ stderr,
135
+ duration
136
+ });
137
+ });
138
+ });
139
+ }
140
+
141
+ /**
142
+ * Kill running job
143
+ * @param {string} jobId - Job ID
144
+ */
145
+ kill(jobId) {
146
+ const ptyProcess = this.activeJobs.get(jobId);
147
+ if (ptyProcess) {
148
+ ptyProcess.kill('SIGTERM');
149
+ this.activeJobs.delete(jobId);
150
+ console.log(`[CliWrapper] Killed job ${jobId}`);
151
+ return true;
152
+ }
153
+ return false;
154
+ }
155
+
156
+ /**
157
+ * Get active job count
158
+ */
159
+ getActiveJobCount() {
160
+ return this.activeJobs.size;
161
+ }
162
+ }
163
+
164
+ module.exports = CliWrapper;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * OutputParser - Parse CLI stdout/stderr into structured events
3
+ * Adapted from NexusChat output-parser.js
4
+ */
5
+ class OutputParser {
6
+ constructor() {
7
+ this.state = 'idle';
8
+ this.buffer = '';
9
+ this.lineBuffer = '';
10
+ }
11
+
12
+ /**
13
+ * Regex patterns for detecting CLI output markers
14
+ */
15
+ static PATTERNS = {
16
+ // Tool execution patterns (generic)
17
+ toolExecution: /(?:Running|Executing)\s+(\w+)(?:\s+(?:command|tool))?:\s*(.+)/i,
18
+
19
+ // Common CLI patterns
20
+ errorPattern: /(?:Error|ERROR|Failed|FAILED|Exception):\s*(.+)/i,
21
+ warningPattern: /(?:Warning|WARNING|warn):\s*(.+)/i,
22
+
23
+ // ANSI escape codes
24
+ ansiCodes: /\x1B\[[0-9;]*[a-zA-Z]/g,
25
+ ansiPrivate: /\x1B\[\?[0-9;]*[a-zA-Z]/g,
26
+ };
27
+
28
+ /**
29
+ * Parse chunk of stdout and return array of events
30
+ * @param {string} chunk - Raw stdout chunk from PTY
31
+ * @returns {Array} Array of event objects
32
+ */
33
+ parse(chunk) {
34
+ const events = [];
35
+
36
+ // Add to buffer
37
+ this.buffer += chunk;
38
+ this.lineBuffer += chunk;
39
+
40
+ // Process line by line
41
+ const lines = this.lineBuffer.split('\n');
42
+ this.lineBuffer = lines.pop(); // Keep incomplete line
43
+
44
+ for (const line of lines) {
45
+ const lineEvents = this.parseLine(line);
46
+ events.push(...lineEvents);
47
+ }
48
+
49
+ // Also emit raw output chunks
50
+ const cleanChunk = this.cleanAnsi(chunk);
51
+ if (cleanChunk && cleanChunk.trim()) {
52
+ events.push({
53
+ type: 'output_chunk',
54
+ stream: 'stdout',
55
+ text: cleanChunk,
56
+ isIncremental: true,
57
+ });
58
+ }
59
+
60
+ return events;
61
+ }
62
+
63
+ /**
64
+ * Parse single line
65
+ * @param {string} line - Single line of output
66
+ * @returns {Array} Events from this line
67
+ */
68
+ parseLine(line) {
69
+ const events = [];
70
+ const cleanLine = this.cleanAnsi(line);
71
+
72
+ // Check for tool execution
73
+ const toolMatch = cleanLine.match(OutputParser.PATTERNS.toolExecution);
74
+ if (toolMatch) {
75
+ const [, tool, command] = toolMatch;
76
+ events.push({
77
+ type: 'status',
78
+ category: 'tool',
79
+ tool,
80
+ message: `${tool}: ${command.substring(0, 60)}${command.length > 60 ? '...' : ''}`,
81
+ icon: '🔧',
82
+ timestamp: new Date().toISOString(),
83
+ });
84
+ }
85
+
86
+ // Check for errors
87
+ if (OutputParser.PATTERNS.errorPattern.test(cleanLine)) {
88
+ const [, errorMsg] = cleanLine.match(OutputParser.PATTERNS.errorPattern);
89
+ events.push({
90
+ type: 'status',
91
+ category: 'warning',
92
+ message: `Error: ${errorMsg}`,
93
+ icon: '⚠️',
94
+ timestamp: new Date().toISOString(),
95
+ });
96
+ }
97
+
98
+ // Check for warnings
99
+ if (OutputParser.PATTERNS.warningPattern.test(cleanLine)) {
100
+ const [, warnMsg] = cleanLine.match(OutputParser.PATTERNS.warningPattern);
101
+ events.push({
102
+ type: 'status',
103
+ category: 'warning',
104
+ message: `Warning: ${warnMsg}`,
105
+ icon: '⚠️',
106
+ timestamp: new Date().toISOString(),
107
+ });
108
+ }
109
+
110
+ return events;
111
+ }
112
+
113
+ /**
114
+ * Clean ANSI escape codes from text
115
+ */
116
+ cleanAnsi(text) {
117
+ return text
118
+ .replace(OutputParser.PATTERNS.ansiCodes, '')
119
+ .replace(OutputParser.PATTERNS.ansiPrivate, '');
120
+ }
121
+
122
+ /**
123
+ * Reset parser state
124
+ */
125
+ reset() {
126
+ this.state = 'idle';
127
+ this.buffer = '';
128
+ this.lineBuffer = '';
129
+ }
130
+ }
131
+
132
+ module.exports = OutputParser;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * PTY Adapter for NexusCLI (Termux)
3
+ * Provides node-pty-like interface using child_process.spawn
4
+ * Termux-only: no native node-pty compilation needed
5
+ */
6
+
7
+ const { spawn: cpSpawn } = require('child_process');
8
+
9
+ /**
10
+ * Spawn a process with node-pty-like interface
11
+ * @param {string} command - Command to spawn
12
+ * @param {string[]} args - Arguments
13
+ * @param {Object} options - Spawn options (cwd, env)
14
+ * @returns {Object} PTY-like interface with onData, onExit, kill
15
+ */
16
+ function spawn(command, args, options = {}) {
17
+ const proc = cpSpawn(command, args, {
18
+ cwd: options.cwd,
19
+ env: options.env,
20
+ shell: false,
21
+ stdio: ['ignore', 'pipe', 'pipe'],
22
+ });
23
+
24
+ const dataHandlers = [];
25
+ const exitHandlers = [];
26
+ const errorHandlers = [];
27
+
28
+ proc.stdout.on('data', (buf) => {
29
+ const data = buf.toString();
30
+ dataHandlers.forEach((fn) => fn(data));
31
+ });
32
+
33
+ proc.stderr.on('data', (buf) => {
34
+ const data = buf.toString();
35
+ dataHandlers.forEach((fn) => fn(data));
36
+ });
37
+
38
+ proc.on('close', (code) => {
39
+ exitHandlers.forEach((fn) => fn({ exitCode: code ?? 0 }));
40
+ });
41
+
42
+ proc.on('error', (err) => {
43
+ console.error('[PTY-Adapter] Error:', err.message);
44
+ errorHandlers.forEach((fn) => fn(err));
45
+ });
46
+
47
+ return {
48
+ onData: (fn) => dataHandlers.push(fn),
49
+ onExit: (fn) => exitHandlers.push(fn),
50
+ onError: (fn) => errorHandlers.push(fn),
51
+ write: (data) => proc.stdin?.writable && proc.stdin.write(data),
52
+ kill: (signal = 'SIGTERM') => proc.kill(signal),
53
+ pid: proc.pid,
54
+ };
55
+ }
56
+
57
+ module.exports = { spawn };
@@ -0,0 +1,103 @@
1
+ const jwt = require('jsonwebtoken');
2
+ const User = require('../models/User');
3
+ const { getConfig } = require('../../config/manager');
4
+
5
+ const JWT_SECRET = process.env.JWT_SECRET || 'nexuscli-secret-change-in-production';
6
+
7
+ /**
8
+ * Get config user (admin from init) by id
9
+ */
10
+ function findConfigUserById(id) {
11
+ if (id !== 'config-admin') return null;
12
+
13
+ const config = getConfig();
14
+ if (config.auth && config.auth.user) {
15
+ return {
16
+ id: 'config-admin',
17
+ username: config.auth.user,
18
+ role: 'admin',
19
+ is_locked: false,
20
+ created_at: Date.now()
21
+ };
22
+ }
23
+ return null;
24
+ }
25
+ const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';
26
+
27
+ function generateToken(user) {
28
+ return jwt.sign(
29
+ {
30
+ id: user.id,
31
+ username: user.username,
32
+ role: user.role
33
+ },
34
+ JWT_SECRET,
35
+ { expiresIn: JWT_EXPIRES_IN }
36
+ );
37
+ }
38
+
39
+ function verifyToken(token) {
40
+ try {
41
+ return jwt.verify(token, JWT_SECRET);
42
+ } catch (err) {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ function authMiddleware(req, res, next) {
48
+ const authHeader = req.headers.authorization;
49
+
50
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
51
+ return res.status(401).json({ error: 'No token provided' });
52
+ }
53
+
54
+ const token = authHeader.substring(7);
55
+ const decoded = verifyToken(token);
56
+
57
+ if (!decoded) {
58
+ return res.status(401).json({ error: 'Invalid or expired token' });
59
+ }
60
+
61
+ // Verify user still exists - check config user first, then database
62
+ let user = findConfigUserById(decoded.id);
63
+ let isConfigUser = !!user;
64
+
65
+ if (!user) {
66
+ user = User.findById(decoded.id);
67
+ }
68
+
69
+ if (!user) {
70
+ return res.status(401).json({ error: 'User not found' });
71
+ }
72
+
73
+ // Check if account is locked (only for DB users)
74
+ if (!isConfigUser && User.isAccountLocked(user)) {
75
+ return res.status(403).json({
76
+ error: 'Account locked',
77
+ locked_until: user.locked_until
78
+ });
79
+ }
80
+
81
+ req.user = {
82
+ id: user.id,
83
+ username: user.username,
84
+ role: user.role
85
+ };
86
+
87
+ next();
88
+ }
89
+
90
+ function adminOnly(req, res, next) {
91
+ if (req.user.role !== 'admin') {
92
+ return res.status(403).json({ error: 'Admin access required' });
93
+ }
94
+ next();
95
+ }
96
+
97
+ module.exports = {
98
+ generateToken,
99
+ verifyToken,
100
+ authMiddleware,
101
+ adminOnly,
102
+ JWT_SECRET
103
+ };