-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
344 lines (290 loc) · 10.2 KB
/
Copy pathserver.js
File metadata and controls
344 lines (290 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import { exec } from 'child_process';
import os from 'os';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });
const PORT = process.env.PORT || 3456;
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Guest Mode State
let isGuestLockdownActive = false;
let blockedApps = ['Terminal', 'System Settings', 'Keychain Access', 'Safari'];
let lockdownInterval = null;
function runCmd(cmd) {
return new Promise((resolve) => {
exec(cmd, { maxBuffer: 1024 * 1024 * 10 }, (error, stdout, stderr) => {
if (error) {
resolve({ success: false, error: error.message, stderr });
} else {
resolve({ success: true, output: stdout.trim() });
}
});
});
}
function runOsa(script) {
const escaped = script.replace(/"/g, '\\"');
return runCmd(`osascript -e "${escaped}"`);
}
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return 'localhost';
}
// Guest Lockdown Watchdog
function startLockdownWatchdog() {
if (lockdownInterval) clearInterval(lockdownInterval);
lockdownInterval = setInterval(async () => {
if (!isGuestLockdownActive) return;
for (const appName of blockedApps) {
await runCmd(`killall "${appName}" 2>/dev/null || true`);
}
}, 1500);
}
startLockdownWatchdog();
// --- API ENDPOINTS ---
// 1. System Info & Health
app.get('/api/system-info', async (req, res) => {
try {
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
let batteryStr = '100% (AC)';
try {
const pmRes = await runCmd("pmset -g batt | grep -o '[0-9]*%'");
if (pmRes.success && pmRes.output) batteryStr = pmRes.output;
} catch (e) {}
let diskStr = 'Available';
try {
const dfRes = await runCmd("df -h / | tail -1 | awk '{print $4}'");
if (dfRes.success && dfRes.output) diskStr = dfRes.output + ' free';
} catch (e) {}
let volume = 50;
try {
const volRes = await runOsa("output volume of (get volume settings)");
if (volRes.success) volume = parseInt(volRes.output, 10) || 50;
} catch (e) {}
res.json({
hostname: os.hostname(),
platform: 'macOS ' + os.release(),
memoryTotal: (totalMem / (1024 * 1024 * 1024)).toFixed(1) + ' GB',
memoryUsedPct: Math.round((usedMem / totalMem) * 100),
battery: batteryStr,
diskFree: diskStr,
uptime: Math.round(os.uptime() / 60) + ' mins',
volume,
isGuestLockdownActive,
blockedApps,
ipAddress: getLocalIP(),
port: PORT
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// 2. Control System Actions (Power, Restart, Shutdown, Lock, Sleep)
app.post('/api/control', async (req, res) => {
const { action, value } = req.body;
let result;
switch (action) {
case 'set-volume':
const vol = Math.min(100, Math.max(0, parseInt(value, 10) || 0));
result = await runOsa(`set volume output volume ${vol}`);
break;
case 'mute-toggle':
result = await runOsa(`set volume output muted (not (output muted of (get volume settings)))`);
break;
case 'lock-screen':
result = await runCmd(`pmset displaysleepnow`);
break;
case 'sleep-mac':
result = await runOsa(`tell application "System Events" to sleep`);
break;
case 'restart-mac':
result = await runOsa(`tell application "System Events" to restart`);
break;
case 'shutdown-mac':
result = await runOsa(`tell application "System Events" to shut down`);
break;
case 'empty-trash':
result = await runCmd(`rm -rf ~/.Trash/*`);
break;
case 'spotlight':
result = await runOsa(`tell application "System Events" to key code 49 using command down`);
break;
case 'mission-control':
result = await runCmd(`open -a "Mission Control"`);
break;
default:
return res.status(400).json({ error: 'Unknown action' });
}
res.json(result);
});
// 3. Guest Mode & Restriction Guard
app.post('/api/restrictions/toggle', (req, res) => {
const { enabled, apps } = req.body;
isGuestLockdownActive = !!enabled;
if (Array.isArray(apps)) blockedApps = apps;
res.json({
success: true,
isGuestLockdownActive,
blockedApps
});
});
// 4. App Manager (Launch, Force Quit, Install, Delete/Uninstall)
app.get('/api/apps', async (req, res) => {
const osaScript = `
tell application "System Events"
set processList to name of every process whose background only is false
return processList
end tell
`;
const result = await runOsa(osaScript);
let running = [];
if (result.success && result.output) {
running = result.output.split(', ').map(s => s.trim());
}
res.json({
running,
blocked: blockedApps,
isGuestLockdownActive
});
});
app.post('/api/apps/launch', async (req, res) => {
const { appName } = req.body;
if (!appName) return res.status(400).json({ error: 'appName required' });
if (isGuestLockdownActive && blockedApps.includes(appName)) {
return res.status(403).json({ error: `App '${appName}' is BLOCKED by Guest Mode Restriction!` });
}
const result = await runCmd(`open -a "${appName.replace(/"/g, '')}"`);
res.json(result);
});
app.post('/api/apps/force-quit', async (req, res) => {
const { appName } = req.body;
if (!appName) return res.status(400).json({ error: 'appName required' });
const result = await runCmd(`killall "${appName.replace(/"/g, '')}"`);
res.json(result);
});
app.post('/api/apps/install', async (req, res) => {
const { packageName, tool } = req.body; // tool: 'brew' | 'cask' | 'npm'
if (!packageName) return res.status(400).json({ error: 'packageName required' });
let cmd = `brew install --cask "${packageName}"`;
if (tool === 'brew') cmd = `brew install "${packageName}"`;
if (tool === 'npm') cmd = `npm install -g "${packageName}"`;
const result = await runCmd(cmd);
res.json(result);
});
app.post('/api/apps/uninstall', async (req, res) => {
const { packageName, tool } = req.body;
if (!packageName) return res.status(400).json({ error: 'packageName required' });
let cmd = `brew uninstall --cask "${packageName}"`;
if (tool === 'brew') cmd = `brew uninstall "${packageName}"`;
if (tool === 'npm') cmd = `npm uninstall -g "${packageName}"`;
const result = await runCmd(cmd);
res.json(result);
});
// 5. Mac File Explorer & File Operations
app.post('/api/files/list', async (req, res) => {
const targetPath = req.body.path || os.homedir();
try {
const items = await fs.promises.readdir(targetPath, { withFileTypes: true });
const fileList = [];
for (const item of items) {
if (item.name.startsWith('.')) continue;
const fullPath = path.join(targetPath, item.name);
let stat = { size: 0, isDirectory: item.isDirectory() };
try {
const s = await fs.promises.stat(fullPath);
stat.size = s.size;
} catch (e) {}
fileList.push({
name: item.name,
path: fullPath,
isDirectory: item.isDirectory(),
size: (stat.size / (1024 * 1024)).toFixed(2) + ' MB'
});
}
res.json({ currentPath: targetPath, items: fileList });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/files/delete', async (req, res) => {
const { filePath } = req.body;
if (!filePath) return res.status(400).json({ error: 'filePath required' });
try {
await fs.promises.rm(filePath, { recursive: true, force: true });
res.json({ success: true, message: `Deleted ${filePath}` });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// 6. Live Screen Snapshot
const tmpScreenshotPath = path.join(os.tmpdir(), 'macdeck_screencap.jpg');
app.get('/api/screen/snapshot', async (req, res) => {
try {
await runCmd(`screencapture -x -t jpg -C ${tmpScreenshotPath}`);
if (fs.existsSync(tmpScreenshotPath)) {
res.setHeader('Content-Type', 'image/jpeg');
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, private');
fs.createReadStream(tmpScreenshotPath).pipe(res);
} else {
res.status(500).json({ error: 'Screenshot failed' });
}
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// 7. Keyboard & Key Input
app.post('/api/input/keyboard', async (req, res) => {
const { text, key, modifiers } = req.body;
if (text) {
const escapedText = text.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
const result = await runOsa(`tell application "System Events" to keystroke "${escapedText}"`);
return res.json(result);
}
if (key) {
let modClause = '';
if (modifiers && modifiers.length > 0) {
const formattedMods = modifiers.map(m => `${m} down`).join(', ');
modClause = ` using {${formattedMods}}`;
}
const result = await runOsa(`tell application "System Events" to keystroke "${key}"${modClause}`);
return res.json(result);
}
res.status(400).json({ error: 'Invalid input' });
});
// 8. Terminal Shell
app.post('/api/terminal/exec', async (req, res) => {
const { command } = req.body;
if (!command) return res.status(400).json({ error: 'Command required' });
const result = await runCmd(command);
res.json(result);
});
// WebSocket Server
wss.on('connection', (ws) => {
console.log('iPhone connected to MacDeck WebSocket server');
});
// Start Server
server.listen(PORT, () => {
const ip = getLocalIP();
console.log(`\n==================================================`);
console.log(` 🖥️ MacDeck Full Remote Bridge Server`);
console.log(`==================================================`);
console.log(` Local URL: http://localhost:${PORT}`);
console.log(` iPhone URL: http://${ip}:${PORT}`);
console.log(`==================================================\n`);
});