@tianacloud/dsh-remote 0.0.0-stage → 0.2.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.
@@ -0,0 +1,433 @@
1
+ import { normalizeStun } from '../web-src/peer-path.js';
2
+ import { formatPairingKey } from './state.js';
3
+
4
+ const MAX_ADMIN_BODY_BYTES = 64 * 1024;
5
+
6
+ function jsonResponse(status, body) {
7
+ return Response.json(body, {
8
+ status,
9
+ headers: {
10
+ 'content-type': 'application/json; charset=utf-8',
11
+ 'cache-control': 'no-store',
12
+ 'x-content-type-options': 'nosniff',
13
+ },
14
+ });
15
+ }
16
+
17
+ export function isLoopbackAddress(addr) {
18
+ if (!addr || typeof addr !== 'string') return false;
19
+ const bare = addr.trim().replace(/^\[|\]$/gu, '').toLowerCase();
20
+ return bare === '127.0.0.1' || bare === '::1' || bare === '::ffff:127.0.0.1';
21
+ }
22
+
23
+ export function isLoopbackHostHeader(hostHeader) {
24
+ if (!hostHeader || typeof hostHeader !== 'string') return false;
25
+ const trimmed = hostHeader.trim();
26
+ if (!trimmed || /[\s/@?#\\]/u.test(trimmed)) return false;
27
+ try {
28
+ const parsed = new URL(`http://${trimmed}`);
29
+ const host = parsed.hostname.toLowerCase();
30
+ return host === '127.0.0.1' || host === '::1' || host === '[::1]' || host === 'localhost';
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ async function readJsonBody(request) {
37
+ const text = await request.text();
38
+ if (Buffer.byteLength(text, 'utf8') > MAX_ADMIN_BODY_BYTES) {
39
+ throw Object.assign(new Error('Request body too large'), { status: 413 });
40
+ }
41
+ if (!text.trim()) return {};
42
+ try {
43
+ const parsed = JSON.parse(text);
44
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
45
+ } catch {
46
+ throw Object.assign(new Error('Invalid JSON request body'), { status: 400 });
47
+ }
48
+ }
49
+
50
+ function normalizeRejectionResponse(rejection, { mapAuthToForbidden = false } = {}) {
51
+ if (rejection === undefined || rejection === null || rejection === false || rejection === 0) {
52
+ return null;
53
+ }
54
+ if (typeof rejection === 'number') {
55
+ const status = mapAuthToForbidden && (rejection === 401 || rejection === 403) ? 403 : rejection;
56
+ return jsonResponse(status, {
57
+ ok: false,
58
+ error: status === 403 ? 'Local DSH owner session required' : 'Request rejected',
59
+ });
60
+ }
61
+ if (rejection instanceof Response || (typeof rejection === 'object' && typeof rejection.status === 'number')) {
62
+ if (mapAuthToForbidden && (rejection.status === 401 || rejection.status === 403)) {
63
+ return jsonResponse(403, { ok: false, error: 'Local DSH owner session required' });
64
+ }
65
+ return rejection instanceof Response
66
+ ? rejection
67
+ : jsonResponse(rejection.status, { ok: false, error: 'Request rejected' });
68
+ }
69
+ return jsonResponse(403, { ok: false, error: 'Request rejected' });
70
+ }
71
+
72
+ /**
73
+ * Triple-guard check for all local-only `/api/tiana-remote/admin/*` endpoints:
74
+ * 1. Verified loopback TCP socket address (`isLoopbackAddress(remoteAddress) === true`, fail-closed when missing)
75
+ * AND verified loopback `Host` header (`isLoopbackHostHeader(hostHeader) === true`, fail-closed when missing/non-loopback)
76
+ * 2. Strict absence of `X-DSH-Remote-Tunnel` header (checked via presence, rejecting even empty-string values)
77
+ * 3. Valid local DSH owner session via `connection.requestRejection` (supports numeric status code & Response return forms)
78
+ */
79
+ export async function guardAdminRequest(request, connection, meta = {}) {
80
+ const { remoteAddress, hostHeader, hasTunnelHeader, nodeReq } = meta;
81
+
82
+ // Guard 2: reject any request carrying X-DSH-Remote-Tunnel (even empty string)
83
+ const tunnelHeaderPresent = Boolean(hasTunnelHeader) ||
84
+ (nodeReq && 'x-dsh-remote-tunnel' in (nodeReq.headers || {})) ||
85
+ request.headers.has('x-dsh-remote-tunnel');
86
+ if (tunnelHeaderPresent) {
87
+ return jsonResponse(403, { ok: false, error: 'Admin endpoints are forbidden over remote tunnel' });
88
+ }
89
+
90
+ // Guard 1a: require verified TCP loopback peer address (fail-closed when absent)
91
+ if (!isLoopbackAddress(remoteAddress)) {
92
+ return jsonResponse(403, { ok: false, error: 'Admin endpoints require local loopback access' });
93
+ }
94
+
95
+ // Guard 1b: require verified loopback Host header (fail-closed when missing or non-loopback)
96
+ let effectiveHost;
97
+ if (nodeReq) {
98
+ effectiveHost = nodeReq.headers?.host;
99
+ } else if (hostHeader !== undefined) {
100
+ effectiveHost = hostHeader;
101
+ } else if (request.headers.has('host')) {
102
+ effectiveHost = request.headers.get('host');
103
+ } else {
104
+ try {
105
+ effectiveHost = new URL(request.url).host;
106
+ } catch {
107
+ effectiveHost = '';
108
+ }
109
+ }
110
+ if (!isLoopbackHostHeader(effectiveHost)) {
111
+ return jsonResponse(403, { ok: false, error: 'Admin endpoints require a loopback Host header' });
112
+ }
113
+
114
+ // Guard 3: verify local DSH owner session
115
+ if (typeof connection?.requestRejection === 'function') {
116
+ const authTarget = nodeReq ?? request;
117
+ const rejection = await connection.requestRejection(authTarget, { allowAuthorizationHeader: false });
118
+ const mapped = normalizeRejectionResponse(rejection, { mapAuthToForbidden: true });
119
+ if (mapped) return mapped;
120
+ }
121
+
122
+ return null;
123
+ }
124
+
125
+ export async function guardPublicRequest(request, connection, meta = {}) {
126
+ if (typeof connection?.requestRejection === 'function') {
127
+ const authTarget = meta.nodeReq ?? request;
128
+ const rejection = await connection.requestRejection(authTarget, { allowAuthorizationHeader: false });
129
+ const mapped = normalizeRejectionResponse(rejection, { mapAuthToForbidden: false });
130
+ if (mapped) return mapped;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ /**
136
+ * Build a unified Fetch router for `/api/tiana-remote/*` endpoints.
137
+ * Used by `registerWebServerRoutes` (preferred, with real TCP socket remoteAddress),
138
+ * `registerRemoteRoutes` (Fetch fallback where admin routes fail closed), and tests.
139
+ */
140
+ export function createRemoteApiHandler(controller, connection = null) {
141
+ return async function handleRemoteApiRequest(request, meta = {}) {
142
+ const url = new URL(request.url, 'http://127.0.0.1');
143
+ const path = url.pathname;
144
+ const method = request.method.toUpperCase();
145
+
146
+ // 1. Public redacted status (safe for both local & remote sidebar; strictly 8 spec fields)
147
+ if (path === '/api/tiana-remote/status' || path === '/api/tiana-remote/public-status') {
148
+ if (method !== 'GET' && method !== 'HEAD') {
149
+ return jsonResponse(405, { ok: false, error: 'Method not allowed' });
150
+ }
151
+ const pubReject = await guardPublicRequest(request, connection, meta);
152
+ if (pubReject) return pubReject;
153
+ const pub = await controller.getPublicStatus();
154
+ return method === 'HEAD'
155
+ ? new Response(null, { status: 200, headers: { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' } })
156
+ : jsonResponse(200, pub);
157
+ }
158
+
159
+ // 2. Local-only Admin endpoints (triple-guarded)
160
+ if (path === '/api/tiana-remote/admin' || path.startsWith('/api/tiana-remote/admin/')) {
161
+ const adminReject = await guardAdminRequest(request, connection, meta);
162
+ if (adminReject) return adminReject;
163
+
164
+ try {
165
+ if ((path === '/api/tiana-remote/admin/overview' || path === '/api/tiana-remote/admin/status') &&
166
+ (method === 'GET' || method === 'HEAD')) {
167
+ const overview = await controller.getAdminOverview();
168
+ return method === 'HEAD' ? new Response(null, { status: 200 }) : jsonResponse(200, overview);
169
+ }
170
+
171
+ if (path === '/api/tiana-remote/admin/toggle' && method === 'POST') {
172
+ const body = await readJsonBody(request);
173
+ if (typeof body.enabled !== 'boolean') {
174
+ return jsonResponse(400, { ok: false, error: '`enabled` boolean is required' });
175
+ }
176
+ const result = await controller.setEnabled(body.enabled);
177
+ return jsonResponse(200, { ok: true, ...result });
178
+ }
179
+
180
+ if ((path === '/api/tiana-remote/admin/pairing-key/reveal' || path === '/api/tiana-remote/admin/key/reveal') &&
181
+ method === 'POST') {
182
+ const revealed = await controller.revealPairingKey();
183
+ return jsonResponse(200, {
184
+ ok: true,
185
+ pairingKey: formatPairingKey(revealed.secret),
186
+ secret: revealed.secret,
187
+ fingerprint: revealed.fingerprint,
188
+ });
189
+ }
190
+
191
+ if ((path === '/api/tiana-remote/admin/pairing-key/rotate' || path === '/api/tiana-remote/admin/key/rotate') &&
192
+ method === 'POST') {
193
+ const body = await readJsonBody(request);
194
+ if (body.confirm !== true) {
195
+ return jsonResponse(400, { ok: false, error: 'Explicit confirmation `{ confirm: true }` is required' });
196
+ }
197
+ const rotated = await controller.rotatePairingKey();
198
+ return jsonResponse(200, {
199
+ ok: true,
200
+ pairingKey: formatPairingKey(rotated.secret),
201
+ secret: rotated.secret,
202
+ fingerprint: rotated.fingerprint,
203
+ createdAt: rotated.createdAt,
204
+ kickedSessions: rotated.kickedSessions ?? 0,
205
+ });
206
+ }
207
+
208
+ if ((path === '/api/tiana-remote/admin/sessions/disconnect' || path === '/api/tiana-remote/admin/sessions/disconnect-all') &&
209
+ method === 'POST') {
210
+ const body = await readJsonBody(request);
211
+ if (path.endsWith('/disconnect-all') || body.all === true || !body.sessionId) {
212
+ const count = await controller.disconnectAllSessions();
213
+ return jsonResponse(200, { ok: true, disconnected: count });
214
+ }
215
+ const removed = await controller.disconnectSession(String(body.sessionId));
216
+ return jsonResponse(200, { ok: true, disconnected: removed ? 1 : 0 });
217
+ }
218
+
219
+ if (path === '/api/tiana-remote/admin/settings' && method === 'POST') {
220
+ const body = await readJsonBody(request);
221
+ const patch = {};
222
+ if (body.hostName !== undefined) {
223
+ const name = String(body.hostName).trim();
224
+ if (!name || name.length > 128) {
225
+ return jsonResponse(400, { ok: false, error: 'Invalid hostName (1..128 chars)' });
226
+ }
227
+ patch.hostName = name;
228
+ }
229
+ if (body.p2pEnabled !== undefined) {
230
+ patch.p2pEnabled = Boolean(body.p2pEnabled);
231
+ }
232
+ if (body.stunUrls !== undefined) {
233
+ try {
234
+ patch.stunUrls = normalizeStun(body.stunUrls);
235
+ } catch (err) {
236
+ return jsonResponse(400, { ok: false, error: err.message });
237
+ }
238
+ }
239
+ if (body.allowedWebPlugins !== undefined) {
240
+ if (!Array.isArray(body.allowedWebPlugins)) {
241
+ return jsonResponse(400, { ok: false, error: 'allowedWebPlugins must be an array' });
242
+ }
243
+ patch.allowedWebPlugins = body.allowedWebPlugins.map((p) => String(p).trim()).filter(Boolean);
244
+ }
245
+ const updated = await controller.updateSettings(patch);
246
+ return jsonResponse(200, { ok: true, ...updated });
247
+ }
248
+
249
+ if (path === '/api/tiana-remote/admin/repair' && method === 'POST') {
250
+ const result = await controller.repairStaticShell();
251
+ return jsonResponse(200, { ok: true, ...result });
252
+ }
253
+
254
+ if (path === '/api/tiana-remote/admin/token/renew' && method === 'POST') {
255
+ const result = await controller.renewHostToken();
256
+ return jsonResponse(200, { ok: true, ...result });
257
+ }
258
+
259
+ if (path === '/api/tiana-remote/admin/provision' && method === 'POST') {
260
+ const body = await readJsonBody(request);
261
+ const started = controller.startProvision(body);
262
+ if (!started.started) {
263
+ return jsonResponse(409, { ok: false, error: 'A provision task is already running' });
264
+ }
265
+ return jsonResponse(202, { ok: true, ...started });
266
+ }
267
+
268
+ if (path === '/api/tiana-remote/admin/provision-status' && (method === 'GET' || method === 'HEAD')) {
269
+ return jsonResponse(200, { ok: true, ...controller.getProvisionStatus() });
270
+ }
271
+
272
+ return jsonResponse(404, { ok: false, error: 'Unknown admin route' });
273
+ } catch (err) {
274
+ const status = Number.isInteger(err?.status) ? err.status : 500;
275
+ return jsonResponse(status, {
276
+ ok: false,
277
+ error: err instanceof Error ? err.message : String(err),
278
+ });
279
+ }
280
+ }
281
+
282
+ return null;
283
+ };
284
+ }
285
+
286
+ async function readBoundedNodeBody(req, maxBytes = MAX_ADMIN_BODY_BYTES) {
287
+ const chunks = [];
288
+ let total = 0;
289
+ for await (const chunk of req) {
290
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
291
+ total += buf.byteLength;
292
+ if (total > maxBytes) {
293
+ req.resume();
294
+ return null;
295
+ }
296
+ chunks.push(buf);
297
+ }
298
+ return chunks.length ? Buffer.concat(chunks, total) : Buffer.alloc(0);
299
+ }
300
+
301
+ function sendNodeJson(res, status, payload) {
302
+ res.statusCode = status;
303
+ res.setHeader('content-type', 'application/json; charset=utf-8');
304
+ res.setHeader('cache-control', 'no-store');
305
+ res.setHeader('x-content-type-options', 'nosniff');
306
+ res.end(JSON.stringify(payload));
307
+ }
308
+
309
+ async function writeFetchResponseToNode(res, response) {
310
+ res.statusCode = response.status;
311
+ response.headers.forEach((value, key) => {
312
+ res.setHeader(key, value);
313
+ });
314
+ if (!response.body) {
315
+ res.end();
316
+ return;
317
+ }
318
+ const buf = Buffer.from(await response.arrayBuffer());
319
+ res.end(buf);
320
+ }
321
+
322
+ /**
323
+ * Preferred DSH rc.5 native Node `(req, res)` registration via `webServer.register`.
324
+ * Captures the real TCP `req.socket?.remoteAddress`, raw `req.headers.host`, exact
325
+ * `'x-dsh-remote-tunnel' in req.headers`, and passes `req` directly to `connection.requestRejection(req)`.
326
+ */
327
+ export function registerWebServerRoutes(webServer, connection, controller) {
328
+ if (typeof webServer?.register !== 'function') {
329
+ return () => {};
330
+ }
331
+ const handler = createRemoteApiHandler(controller, connection);
332
+
333
+ const handleNode = async (req, res) => {
334
+ try {
335
+ const method = (req.method || 'GET').toUpperCase();
336
+ let bodyBuf;
337
+ if (method !== 'GET' && method !== 'HEAD') {
338
+ bodyBuf = await readBoundedNodeBody(req, MAX_ADMIN_BODY_BYTES);
339
+ if (bodyBuf === null) {
340
+ sendNodeJson(res, 413, { ok: false, error: 'Request body too large' });
341
+ return;
342
+ }
343
+ }
344
+ const headers = new Headers();
345
+ for (const [k, v] of Object.entries(req.headers || {})) {
346
+ if (v === undefined) continue;
347
+ if (Array.isArray(v)) {
348
+ for (const item of v) headers.append(k, String(item));
349
+ } else {
350
+ headers.set(k, String(v));
351
+ }
352
+ }
353
+ const fetchReq = new Request(new URL(String(req.url || '/'), 'http://127.0.0.1').href, {
354
+ method,
355
+ headers,
356
+ body: method === 'GET' || method === 'HEAD' ? undefined : bodyBuf,
357
+ });
358
+ const response = await handler(fetchReq, {
359
+ remoteAddress: req.socket?.remoteAddress,
360
+ hostHeader: req.headers?.host,
361
+ hasTunnelHeader: 'x-dsh-remote-tunnel' in (req.headers || {}),
362
+ nodeReq: req,
363
+ });
364
+ if (!response) {
365
+ sendNodeJson(res, 404, { ok: false, error: 'Not found' });
366
+ return;
367
+ }
368
+ await writeFetchResponseToNode(res, response);
369
+ } catch (err) {
370
+ if (!res.headersSent) {
371
+ sendNodeJson(res, 500, { ok: false, error: err instanceof Error ? err.message : String(err) });
372
+ } else {
373
+ res.end();
374
+ }
375
+ }
376
+ };
377
+
378
+ const disposers = [
379
+ webServer.register({ kind: 'exact', path: '/api/tiana-remote/public-status', handler: handleNode }),
380
+ webServer.register({ kind: 'exact', path: '/api/tiana-remote/status', handler: handleNode }),
381
+ webServer.register({ kind: 'prefix', path: '/api/tiana-remote/admin', handler: handleNode }),
382
+ ];
383
+
384
+ return () => {
385
+ for (const dispose of disposers) {
386
+ try { dispose?.(); } catch { /* ignore */ }
387
+ }
388
+ };
389
+ }
390
+
391
+ /**
392
+ * Fallback route mounting onto `connection.fetch.register` when `webServer.register` is unavailable.
393
+ * Because Fetch requests lack a verifiable TCP `remoteAddress`, all `/api/tiana-remote/admin/*`
394
+ * routes fail closed with 403 while public status remains available.
395
+ */
396
+ export function registerRemoteRoutes(connection, controller) {
397
+ const registry = connection?.fetch;
398
+ if (typeof registry?.register !== 'function') {
399
+ return () => {};
400
+ }
401
+ const handler = createRemoteApiHandler(controller, connection);
402
+ const routes = [
403
+ { path: '/api/tiana-remote/status', methods: ['GET', 'HEAD'] },
404
+ { path: '/api/tiana-remote/public-status', methods: ['GET', 'HEAD'] },
405
+ { path: '/api/tiana-remote/admin/overview', methods: ['GET', 'HEAD'] },
406
+ { path: '/api/tiana-remote/admin/status', methods: ['GET', 'HEAD'] },
407
+ { path: '/api/tiana-remote/admin/toggle', methods: ['POST'] },
408
+ { path: '/api/tiana-remote/admin/pairing-key/reveal', methods: ['POST'] },
409
+ { path: '/api/tiana-remote/admin/key/reveal', methods: ['POST'] },
410
+ { path: '/api/tiana-remote/admin/pairing-key/rotate', methods: ['POST'] },
411
+ { path: '/api/tiana-remote/admin/key/rotate', methods: ['POST'] },
412
+ { path: '/api/tiana-remote/admin/sessions/disconnect', methods: ['POST'] },
413
+ { path: '/api/tiana-remote/admin/sessions/disconnect-all', methods: ['POST'] },
414
+ { path: '/api/tiana-remote/admin/settings', methods: ['POST'] },
415
+ { path: '/api/tiana-remote/admin/repair', methods: ['POST'] },
416
+ { path: '/api/tiana-remote/admin/token/renew', methods: ['POST'] },
417
+ { path: '/api/tiana-remote/admin/provision', methods: ['POST'] },
418
+ { path: '/api/tiana-remote/admin/provision-status', methods: ['GET', 'HEAD'] },
419
+ ];
420
+
421
+ const disposers = routes.map(({ path, methods }) => registry.register({
422
+ path,
423
+ methods,
424
+ requestBody: 'buffered',
425
+ fetch: async (request) => (await handler(request)) ?? jsonResponse(404, { ok: false, error: 'Not found' }),
426
+ }));
427
+
428
+ return () => {
429
+ for (const dispose of disposers) {
430
+ try { dispose?.(); } catch { /* ignore */ }
431
+ }
432
+ };
433
+ }