-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathapi.ts
More file actions
288 lines (248 loc) · 9.65 KB
/
Copy pathapi.ts
File metadata and controls
288 lines (248 loc) · 9.65 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
import { Hono } from 'hono';
import type { AppEnv } from '../types';
import { createAccessMiddleware } from '../auth';
import { ensureGateway, findExistingGatewayProcess, killGateway, waitForProcess } from '../gateway';
import { createSnapshot, getLastSync, signalRestoreNeeded } from '../persistence';
import type { StorageStatusResponse, SyncResponse } from '../client/api';
// CLI commands can take 10-15 seconds to complete due to WebSocket connection overhead
const CLI_TIMEOUT_MS = 20000;
/**
* API routes
* - /api/admin/* - Protected admin API routes (Cloudflare Access required)
*
* Note: /api/status is now handled by publicRoutes (no auth required)
*/
const api = new Hono<AppEnv>();
/**
* Admin API routes - all protected by Cloudflare Access
*/
const adminApi = new Hono<AppEnv>();
// Middleware: Verify Cloudflare Access JWT for all admin routes
adminApi.use('*', createAccessMiddleware({ type: 'json' }));
// GET /api/admin/devices - List pending and paired devices
adminApi.get('/devices', async (c) => {
const sandbox = c.get('sandbox');
try {
// Ensure gateway is running first
await ensureGateway(sandbox, c.env);
// Run OpenClaw CLI to list devices
// Must specify --url and --token (OpenClaw v2026.2.3 requires explicit credentials with --url)
const token = c.env.MOLTBOT_GATEWAY_TOKEN;
const tokenArg = token ? ` --token ${token}` : '';
const proc = await sandbox.startProcess(
`openclaw devices list --json --url ws://localhost:18789${tokenArg}`,
);
await waitForProcess(proc, CLI_TIMEOUT_MS);
const logs = await proc.getLogs();
const stdout = logs.stdout || '';
const stderr = logs.stderr || '';
// Try to parse JSON output
try {
// Find JSON in output (may have other log lines)
const jsonMatch = stdout.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const data = JSON.parse(jsonMatch[0]);
return c.json(data);
}
// If no JSON found, return raw output for debugging
return c.json({
pending: [],
paired: [],
raw: stdout,
stderr,
});
} catch {
return c.json({
pending: [],
paired: [],
raw: stdout,
stderr,
parseError: 'Failed to parse CLI output',
});
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return c.json({ error: errorMessage }, 500);
}
});
// POST /api/admin/devices/:requestId/approve - Approve a pending device
adminApi.post('/devices/:requestId/approve', async (c) => {
const sandbox = c.get('sandbox');
const requestId = c.req.param('requestId');
if (!requestId) {
return c.json({ error: 'requestId is required' }, 400);
}
try {
// Ensure gateway is running first
await ensureGateway(sandbox, c.env);
// Run OpenClaw CLI to approve the device
const token = c.env.MOLTBOT_GATEWAY_TOKEN;
const tokenArg = token ? ` --token ${token}` : '';
const proc = await sandbox.startProcess(
`openclaw devices approve ${requestId} --url ws://localhost:18789${tokenArg}`,
);
await waitForProcess(proc, CLI_TIMEOUT_MS);
const logs = await proc.getLogs();
const stdout = logs.stdout || '';
const stderr = logs.stderr || '';
// Check for success indicators (case-insensitive, CLI outputs "Approved ...")
const success = stdout.toLowerCase().includes('approved') || proc.exitCode === 0;
return c.json({
success,
requestId,
message: success ? 'Device approved' : 'Approval may have failed',
stdout,
stderr,
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return c.json({ error: errorMessage }, 500);
}
});
// POST /api/admin/devices/approve-all - Approve all pending devices
adminApi.post('/devices/approve-all', async (c) => {
const sandbox = c.get('sandbox');
try {
// Ensure gateway is running first
await ensureGateway(sandbox, c.env);
// First, get the list of pending devices
const token = c.env.MOLTBOT_GATEWAY_TOKEN;
const tokenArg = token ? ` --token ${token}` : '';
const listProc = await sandbox.startProcess(
`openclaw devices list --json --url ws://localhost:18789${tokenArg}`,
);
await waitForProcess(listProc, CLI_TIMEOUT_MS);
const listLogs = await listProc.getLogs();
const stdout = listLogs.stdout || '';
// Parse pending devices
let pending: Array<{ requestId: string }> = [];
try {
const jsonMatch = stdout.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const data = JSON.parse(jsonMatch[0]);
pending = data.pending || [];
}
} catch {
return c.json({ error: 'Failed to parse device list', raw: stdout }, 500);
}
if (pending.length === 0) {
return c.json({ approved: [], message: 'No pending devices to approve' });
}
// Approve each pending device
const results: Array<{ requestId: string; success: boolean; error?: string }> = [];
for (const device of pending) {
try {
// eslint-disable-next-line no-await-in-loop -- sequential device approval required
const approveProc = await sandbox.startProcess(
`openclaw devices approve ${device.requestId} --url ws://localhost:18789${tokenArg}`,
);
// eslint-disable-next-line no-await-in-loop
await waitForProcess(approveProc, CLI_TIMEOUT_MS);
// eslint-disable-next-line no-await-in-loop
const approveLogs = await approveProc.getLogs();
const success =
approveLogs.stdout?.toLowerCase().includes('approved') || approveProc.exitCode === 0;
results.push({ requestId: device.requestId, success });
} catch (err) {
results.push({
requestId: device.requestId,
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
});
}
}
const approvedCount = results.filter((r) => r.success).length;
return c.json({
approved: results.filter((r) => r.success).map((r) => r.requestId),
failed: results.filter((r) => !r.success),
message: `Approved ${approvedCount} of ${pending.length} device(s)`,
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return c.json({ error: errorMessage }, 500);
}
});
// GET /api/admin/storage - Get backup/restore status
adminApi.get('/storage', async (c) => {
const hasCredentials = !!(
c.env.R2_ACCESS_KEY_ID &&
c.env.R2_SECRET_ACCESS_KEY &&
c.env.CLOUDFLARE_ACCOUNT_ID
);
const missing: string[] = [];
if (!c.env.R2_ACCESS_KEY_ID) missing.push('R2_ACCESS_KEY_ID');
if (!c.env.R2_SECRET_ACCESS_KEY) missing.push('R2_SECRET_ACCESS_KEY');
if (!c.env.CLOUDFLARE_ACCOUNT_ID) missing.push('CLOUDFLARE_ACCOUNT_ID');
const lastSync = hasCredentials ? await getLastSync(c.env.BACKUP_BUCKET) : null;
return c.json({
configured: hasCredentials,
missing: missing.length > 0 ? missing : undefined,
lastSync,
message: hasCredentials
? 'R2 storage is configured. Your data will persist across container restarts via SDK snapshots.'
: 'R2 storage is not configured. Paired devices and conversations will be lost when the container restarts.',
} satisfies StorageStatusResponse);
});
// POST /api/admin/storage/sync - Create a new snapshot
adminApi.post('/storage/sync', async (c) => {
const sandbox = c.get('sandbox');
try {
// Log mount state before backup for diagnostics
let mountState = 'unknown';
let dirContents = 'unknown';
try {
const mnt = await sandbox.exec('mount | grep openclaw || echo "NO_OVERLAY"');
mountState = mnt.stdout?.trim() ?? 'empty';
const ls = await sandbox.exec('ls /home/openclaw/clawd/ 2>&1 || echo "(empty)"');
dirContents = ls.stdout?.trim() ?? 'empty';
} catch {
// non-fatal
}
const handle = await createSnapshot(sandbox, c.env.BACKUP_BUCKET);
return c.json({
success: true,
message: 'Snapshot created successfully',
lastSync: new Date().toISOString(),
debug: { mountState, dirContents, handle },
} satisfies SyncResponse);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
const status =
errorMessage.includes('not configured') || errorMessage.includes('Missing') ? 400 : 500;
return c.json(
{
success: false,
error: errorMessage,
},
status,
);
}
});
// POST /api/admin/gateway/restart - Kill the current gateway and start a new one
adminApi.post('/gateway/restart', async (c) => {
const sandbox = c.get('sandbox');
try {
// Kill the gateway process (shared logic with crash retry)
const existingProcess = await findExistingGatewayProcess(sandbox);
console.log('[Restart] Killing gateway, existing process:', existingProcess?.id ?? 'none');
await killGateway(sandbox);
// Signal that all Worker isolates need to re-restore from R2.
// This writes a marker to R2 that restoreIfNeeded checks, ensuring
// the FUSE overlay is mounted even if a different isolate handles
// the next request (e.g. browser WebSocket reconnect).
await signalRestoreNeeded(c.env.BACKUP_BUCKET);
return c.json({
success: true,
message: existingProcess
? 'Gateway process killed, will restart on next request'
: 'No existing process found, will start on next request',
previousProcessId: existingProcess?.id,
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return c.json({ error: errorMessage }, 500);
}
});
// Mount admin API routes under /admin
api.route('/admin', adminApi);
export { api };