@soffits/dsh-desktop-view 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.
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@soffits/dsh-desktop-view",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Live view of the agent machine's desktop in the DeepSeek Harness Web UI, relayed from cua-spacesd behind DSH's own login with Cua's viewer: watch with sound, take control when the agent needs a hand (CAPTCHAs, QR logins), with clipboard and file transfer, also from a phone.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./locale/*.json": "./locale/*.json",
11
+ "./icon": "./icon.svg",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "client.js",
17
+ "src/*.js",
18
+ "viewer/*",
19
+ "cordis.patch.yml",
20
+ "locale/*.json",
21
+ "icon.svg",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "dsh": {
26
+ "bundle": {
27
+ "patch": "./cordis.patch.yml"
28
+ },
29
+ "client": {
30
+ "platform": "web",
31
+ "immediately": true,
32
+ "inject": [
33
+ "@deepseek-ai/dsh-client-locale",
34
+ "@deepseek-ai/dsh-client-ui-sidebar-right",
35
+ "@deepseek-ai/dsh-client-ui-conversation"
36
+ ]
37
+ }
38
+ },
39
+ "engines": {
40
+ "node": ">=22",
41
+ "dsh": ">=0.2.2-rc.1 <0.3.0-0"
42
+ },
43
+ "scripts": {
44
+ "test": "node --test \"test/*.test.js\"",
45
+ "check": "for f in index.js client.js src/*.js viewer/*.js test/*.js; do node --check \"$f\" || exit 1; done"
46
+ },
47
+ "dependencies": {
48
+ "ws": "^8.22.2"
49
+ },
50
+ "devDependencies": {
51
+ "@deepseek-ai/cordis": "4.1.0",
52
+ "@deepseek-ai/dsh-client-connection": "0.2.2-rc.1",
53
+ "@deepseek-ai/schemastery": "^3.19.0"
54
+ },
55
+ "keywords": [
56
+ "dsh-plugin",
57
+ "deepseek-harness",
58
+ "dsh",
59
+ "cua",
60
+ "remote-desktop",
61
+ "desktop-stream"
62
+ ],
63
+ "author": "Sakina",
64
+ "license": "MIT",
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "git+https://github.com/soffits/dsh-desktop-view.git"
68
+ },
69
+ "homepage": "https://github.com/soffits/dsh-desktop-view#readme",
70
+ "bugs": {
71
+ "url": "https://github.com/soffits/dsh-desktop-view/issues"
72
+ },
73
+ "peerDependencies": {
74
+ "@deepseek-ai/schemastery": "^3.18.5"
75
+ }
76
+ }
package/src/config.js ADDED
@@ -0,0 +1,27 @@
1
+ import { tmpdir } from 'node:os'
2
+ import { join } from 'node:path'
3
+ import z from '@deepseek-ai/schemastery'
4
+ import { NOTIFY_MODES } from './notify.js'
5
+
6
+ export const DEFAULT_STATE_FILE = join(tmpdir(), 'dsh-desktop-view', 'control.json')
7
+
8
+ export const Config = z.object({
9
+ endpoint: z.string().default('http://127.0.0.1:3211')
10
+ .description('Address of cua-spacesd on this machine. Keep it on loopback: the relay sends the env token to it.'),
11
+ tokenFile: z.string().default('/run/cua/env-token')
12
+ .description('File holding the cua-spacesd env token. It stays on the server and is never logged.'),
13
+ maxFps: z.natural().min(1).max(60).default(30)
14
+ .description('Highest frame rate the viewer asks for. Lower it to save CPU and bandwidth.'),
15
+ clipboard: z.boolean().default(true)
16
+ .description('While in control, sync the clipboard between your device and the desktop.'),
17
+ filesRoot: z.string().default('~')
18
+ .description('While in control, the desktop folder you may browse, upload to and download from ("~" is the desktop user\'s home). Empty turns file transfer off.'),
19
+ microphone: z.boolean().default(true)
20
+ .description('While in control, allow sending your microphone to the desktop (when the desktop supports it).'),
21
+ idleSeconds: z.natural().min(10).default(120)
22
+ .description('Control returns to watching after this many seconds without input.'),
23
+ stateFile: z.string().default(DEFAULT_STATE_FILE)
24
+ .description('JSON file showing who controls the desktop ("controller": "user" or null), for the agent\'s scripts to check before acting.'),
25
+ notifyAgent: z.union(NOTIFY_MODES.map(mode => z.const(mode))).default('wake')
26
+ .description('Tell the session the view was opened from when control changes. wake: giving control back wakes the agent when it is running or sent the help link (?help=1), otherwise the note waits; quiet: notes always wait for its next step; off: no notes.'),
27
+ })
package/src/control.js ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Who controls the desktop. At most one control socket holds control at a
3
+ * time; a newer one replaces it. Control ends when the holder gives it back,
4
+ * when its socket closes, or after `idleMs` without input, and the desktop
5
+ * then returns to watching for everyone.
6
+ *
7
+ * Every change is written to a small JSON file so the agent's own scripts
8
+ * can check it before acting on the desktop:
9
+ *
10
+ * { "controller": "user", "since": "...", "sessionId": "...", "updatedAt": "..." }
11
+ * { "controller": null, "since": null, "sessionId": null, "updatedAt": "...", "lastReason": "idle" }
12
+ */
13
+ import { mkdir, rename, writeFile } from 'node:fs/promises'
14
+ import { dirname } from 'node:path'
15
+
16
+ /** Why control ended; also the WebSocket close reason the browser sees. */
17
+ export const RELEASE_REASONS = Object.freeze(['released', 'idle', 'disconnected', 'replaced', 'stopped'])
18
+
19
+ /**
20
+ * @param {object} options
21
+ * @param {number} options.idleMs - Return to watching after this long without input.
22
+ * @param {(state: object) => Promise<void>} options.persist - Writes the state file.
23
+ * @param {() => number} [options.now]
24
+ * @param {(callback: () => void, ms: number) => unknown} [options.setTimer]
25
+ * @param {(timer: unknown) => void} [options.clearTimer]
26
+ */
27
+ export function createControl({ idleMs, persist, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
28
+ /** @type {{ id: string, sessionId: string | null, help: boolean, since: number, lastInput: number, end: (reason: string) => void } | null} */
29
+ let holder = null
30
+ let timer
31
+ let lastReason = null
32
+ const listeners = new Set()
33
+ let writing = Promise.resolve()
34
+
35
+ const snapshot = () => ({
36
+ controller: holder === null ? null : 'user',
37
+ since: holder === null ? null : new Date(holder.since).toISOString(),
38
+ sessionId: holder?.sessionId ?? null,
39
+ updatedAt: new Date(now()).toISOString(),
40
+ ...(holder === null && lastReason !== null ? { lastReason } : {}),
41
+ })
42
+
43
+ const publish = (change) => {
44
+ const state = snapshot()
45
+ writing = writing.then(() => persist(state)).catch(() => {})
46
+ for (const listener of listeners) listener(state, change)
47
+ }
48
+
49
+ const arm = () => {
50
+ if (timer !== undefined) clearTimer(timer)
51
+ timer = undefined
52
+ if (holder === null) return
53
+ const due = holder.lastInput + idleMs - now()
54
+ timer = setTimer(() => {
55
+ timer = undefined
56
+ if (holder === null) return
57
+ if (now() - holder.lastInput >= idleMs) end(holder.id, 'idle')
58
+ else arm()
59
+ }, Math.max(due, 0))
60
+ timer?.unref?.()
61
+ }
62
+
63
+ function end(id, reason) {
64
+ if (holder === null || holder.id !== id) return false
65
+ const previous = holder
66
+ holder = null
67
+ lastReason = reason
68
+ arm()
69
+ previous.end(reason)
70
+ publish({ kind: 'released', reason, sessionId: previous.sessionId, help: previous.help, heldMs: now() - previous.since })
71
+ return true
72
+ }
73
+
74
+ return {
75
+ /** The current state, as written to the file. */
76
+ state: snapshot,
77
+
78
+ /** Whether this socket holds control now. */
79
+ holds: id => holder?.id === id,
80
+
81
+ /**
82
+ * Give control to one socket, ending any other holder's control.
83
+ * @param {{ id: string, sessionId: string | null, help?: boolean, end: (reason: string) => void }} claim - `help`: the view was opened from the agent's help link.
84
+ */
85
+ take(claim) {
86
+ if (holder !== null) end(holder.id, 'replaced')
87
+ const at = now()
88
+ holder = { help: false, ...claim, since: at, lastInput: at }
89
+ arm()
90
+ publish({ kind: 'taken', sessionId: claim.sessionId, help: holder.help })
91
+ },
92
+
93
+ /** Record input from the holder, which keeps control from going idle. */
94
+ touch(id) {
95
+ if (holder?.id === id) holder.lastInput = now()
96
+ },
97
+
98
+ /**
99
+ * End control if this socket holds it.
100
+ * @param {string} id
101
+ * @param {typeof RELEASE_REASONS[number]} reason
102
+ * @returns {boolean} whether it held control
103
+ */
104
+ release: end,
105
+
106
+ /** Follow every change; returns the unsubscribe function. */
107
+ subscribe(listener) {
108
+ listeners.add(listener)
109
+ return () => listeners.delete(listener)
110
+ },
111
+
112
+ /** Write the current state (startup), and wait for queued writes. */
113
+ async flush() {
114
+ const state = snapshot()
115
+ writing = writing.then(() => persist(state)).catch(() => {})
116
+ await writing
117
+ },
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Write the state file atomically (temp file, then rename), creating its
123
+ * directory, readable by the agent's user only.
124
+ * @param {string} path
125
+ */
126
+ export function fileWriter(path) {
127
+ return async (state) => {
128
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
129
+ const temp = `${path}.${process.pid}.tmp`
130
+ await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
131
+ await rename(temp, path)
132
+ }
133
+ }
package/src/filter.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * What a browser may send up the media socket. The relay forwards only the
3
+ * message types the viewer uses, so a modified page cannot reach anything
4
+ * else the media plane offers (such as semantic actions). Input, window
5
+ * geometry and the microphone (binary audio uplink) are forwarded only on a
6
+ * socket opened in control mode; a watch socket's media session is also
7
+ * `view_only` (its viewer ticket caps the policy), so cua-spacesd refuses
8
+ * input there even if this filter were bypassed.
9
+ */
10
+
11
+ /** Largest text message a browser may send (an input batch is small). */
12
+ export const MAX_CLIENT_MESSAGE_BYTES = 64 * 1024
13
+
14
+ const WATCH_TYPES = Object.freeze(['request_keyframe', 'get_stats', 'frame_ack', 'ping'])
15
+ const CONTROL_TYPES = Object.freeze([...WATCH_TYPES, 'interactive_input', 'set_window_geometry', 'audio_uplink_state'])
16
+
17
+ /** Message types allowed per socket mode. */
18
+ export const ALLOWED_TYPES = Object.freeze({ watch: WATCH_TYPES, control: CONTROL_TYPES })
19
+
20
+ /**
21
+ * Check one message from the browser.
22
+ * @param {Buffer | string} data - The WebSocket message.
23
+ * @param {boolean} binary - Whether it arrived as a binary frame.
24
+ * @param {'watch' | 'control'} mode
25
+ * @param {string} sessionId - The media session this socket is attached to.
26
+ * @returns {{ ok: true, type: string, data: Buffer | string, binary: boolean } | { ok: false, reason: string }}
27
+ */
28
+ export function checkClientMessage(data, binary, mode, sessionId) {
29
+ if (binary) {
30
+ // Binary from the browser is only ever microphone audio (RAU2 packets).
31
+ if (mode !== 'control') return { ok: false, reason: 'binary messages are not accepted on a watch socket' }
32
+ return { ok: true, type: 'audio', data, binary: true }
33
+ }
34
+ const text = typeof data === 'string' ? data : data.toString('utf8')
35
+ if (Buffer.byteLength(text) > MAX_CLIENT_MESSAGE_BYTES) return { ok: false, reason: 'message too large' }
36
+ let value
37
+ try {
38
+ value = JSON.parse(text)
39
+ } catch {
40
+ return { ok: false, reason: 'not JSON' }
41
+ }
42
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return { ok: false, reason: 'not an object' }
43
+ const { type, payload } = value
44
+ if (typeof type !== 'string' || !ALLOWED_TYPES[mode]?.includes(type)) {
45
+ return { ok: false, reason: `type ${JSON.stringify(type)} is not allowed on a ${mode} socket` }
46
+ }
47
+ if (payload !== undefined && (payload === null || typeof payload !== 'object' || Array.isArray(payload))) {
48
+ return { ok: false, reason: 'payload is not an object' }
49
+ }
50
+ if (payload?.session_id !== undefined && payload.session_id !== sessionId) {
51
+ return { ok: false, reason: 'message names another media session' }
52
+ }
53
+ // Only the two documented envelope fields go up, so nothing the filter did
54
+ // not look at rides along.
55
+ return { ok: true, type, data: JSON.stringify(payload === undefined ? { type } : { type, payload }), binary: false }
56
+ }
package/src/http.js ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The plugin's routes on DSH's own web server, all under one prefix:
3
+ *
4
+ * GET /desktop-view/ full-screen page (phones, direct links): status bar + viewer
5
+ * GET /desktop-view/<asset> its script, styles, the shared session module and the viewer shim
6
+ * * /desktop-view/d/... the relayed Cua viewer and its gRPC-Web calls (src/viewer.js)
7
+ * WS /desktop-view/status one open view's status, Take control / Give back (src/status.js)
8
+ * WS /desktop-view/d/media the viewer's media socket (src/media.js)
9
+ *
10
+ * Every request goes through `connection.admit`, the same check DSH applies
11
+ * to its own API: the Host/Origin fence against cross-site and rebinding
12
+ * requests, then the signed browser cookie. Only the owner gets through.
13
+ * (DSH's reverse proxy with its OIDC gate sits in front of all of this too.)
14
+ */
15
+ import { readFile } from 'node:fs/promises'
16
+ import { fileURLToPath } from 'node:url'
17
+ import { VIEWER_BASE } from './viewer.js'
18
+
19
+ export const PREFIX = '/desktop-view'
20
+ export const STATUS_PATH = `${PREFIX}/status`
21
+ export const MEDIA_PATH = `${PREFIX}/${VIEWER_BASE}media`
22
+
23
+ /** The plugin's own static files, by the path segment they are served under. */
24
+ export const ASSETS = Object.freeze({
25
+ '': { file: 'page.html', type: 'text/html; charset=utf-8' },
26
+ 'page.js': { file: 'page.js', type: 'text/javascript; charset=utf-8' },
27
+ 'page.css': { file: 'page.css', type: 'text/css; charset=utf-8' },
28
+ 'session.js': { file: 'session.js', type: 'text/javascript; charset=utf-8' },
29
+ 'shim.js': { file: 'shim.js', type: 'text/javascript; charset=utf-8' },
30
+ 'icon.svg': { file: '../icon.svg', type: 'image/svg+xml' },
31
+ })
32
+
33
+ const VIEWER_DIR = fileURLToPath(new URL('../viewer/', import.meta.url))
34
+
35
+ /** Headers on the plugin's own pages: never cached, not framed by others, no referrer. */
36
+ export const SECURITY_HEADERS = Object.freeze({
37
+ 'cache-control': 'no-store',
38
+ 'referrer-policy': 'no-referrer',
39
+ 'x-content-type-options': 'nosniff',
40
+ 'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'",
41
+ })
42
+
43
+ /** Session ids are opaque but short and URL-safe; anything else is ignored. */
44
+ const SESSION_ID = /^[A-Za-z0-9_.:-]{1,200}$/
45
+
46
+ /**
47
+ * Admit one request as the owner.
48
+ * @param {{ admit: (request: { headers: object }) => ({ peer: { principal: { kind: string } } } | { rejection: 401 | 403 }) }} connection
49
+ * @param {{ headers: object }} request
50
+ * @returns {{ ok: true } | { ok: false, status: 401 | 403 }}
51
+ */
52
+ export function admitOwner(connection, request) {
53
+ const admission = connection.admit(request)
54
+ if ('rejection' in admission) return { ok: false, status: admission.rejection }
55
+ if (admission.peer?.principal?.kind !== 'owner') return { ok: false, status: 403 }
56
+ return { ok: true }
57
+ }
58
+
59
+ /** Resume tokens are random base64url. */
60
+ const RESUME = /^[A-Za-z0-9_-]{16,64}$/
61
+
62
+ /**
63
+ * What a status socket names: the DSH session the view was opened from,
64
+ * and the view it resumes after a dropped connection. Malformed values are
65
+ * ignored.
66
+ * @param {string | undefined} url - The request target.
67
+ * `help=1` marks a view opened from a help link the agent sent, so giving
68
+ * control back wakes the agent to carry on.
69
+ * @returns {{ sessionId: string | null, resume: string | null, help: boolean }}
70
+ */
71
+ export function statusQuery(url) {
72
+ const params = new URL(url ?? '/', 'http://relay.invalid').searchParams
73
+ const session = params.get('session')
74
+ const resume = params.get('resume')
75
+ return {
76
+ sessionId: session !== null && SESSION_ID.test(session) ? session : null,
77
+ resume: resume !== null && RESUME.test(resume) ? resume : null,
78
+ help: params.get('help') === '1',
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Whether a refused request is a cross-site page navigation (a link opened
84
+ * from a chat app or mail). DSH's cookie is SameSite=Strict, so such a
85
+ * navigation arrives without it; a page that reloads itself from this origin
86
+ * then carries the cookie.
87
+ */
88
+ export function isCrossSiteNavigation(headers) {
89
+ return headers['sec-fetch-mode'] === 'navigate' && headers['sec-fetch-site'] === 'cross-site'
90
+ }
91
+
92
+ /** Query flag on the reload, so a reload that still fails is not repeated. */
93
+ const BOUNCED = 'bounced'
94
+
95
+ /**
96
+ * A page that only reloads the same URL from this origin; it holds nothing.
97
+ * @param {URLSearchParams} params - The request's query.
98
+ */
99
+ function bouncePage(params) {
100
+ const next = new URLSearchParams(params)
101
+ next.set(BOUNCED, '1')
102
+ const target = `?${next.toString()}`.replace(/&/g, '&amp;').replace(/"/g, '&quot;')
103
+ return `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${target}"><title>Desktop</title>`
104
+ }
105
+
106
+ /**
107
+ * The HTTP handler for everything under the prefix.
108
+ * @param {object} options
109
+ * @param {object} options.connection - DSH `ctx.connection`.
110
+ * @param {(req: object, res: object, rest: string) => Promise<void>} options.viewer - Handles `d/...`.
111
+ * @param {(file: string) => Promise<Buffer>} [options.read]
112
+ */
113
+ export function createPageHandler({ connection, viewer, read = file => readFile(VIEWER_DIR + file) }) {
114
+ return async (req, res) => {
115
+ const url = new URL(req.url ?? '/', 'http://relay.invalid')
116
+ const admitted = admitOwner(connection, req)
117
+ if (!admitted.ok) {
118
+ if (req.method === 'GET' && isCrossSiteNavigation(req.headers) && !url.searchParams.has(BOUNCED)) {
119
+ res.writeHead(200, { ...SECURITY_HEADERS, 'content-type': 'text/html; charset=utf-8' }).end(bouncePage(url.searchParams))
120
+ return
121
+ }
122
+ res.writeHead(admitted.status, { ...SECURITY_HEADERS, 'content-type': 'text/plain; charset=utf-8' })
123
+ .end(admitted.status === 401 ? 'Sign in to DSH first.\n' : 'Forbidden.\n')
124
+ return
125
+ }
126
+ const rest = url.pathname.slice(PREFIX.length + 1)
127
+ if (url.pathname.startsWith(`${PREFIX}/${VIEWER_BASE}`)) {
128
+ await viewer(req, res, rest.slice(VIEWER_BASE.length))
129
+ return
130
+ }
131
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
132
+ res.writeHead(405, { ...SECURITY_HEADERS, allow: 'GET, HEAD' }).end()
133
+ return
134
+ }
135
+ if (url.pathname === PREFIX) {
136
+ // Relative assets need the trailing slash; keep the query (control, session).
137
+ res.writeHead(308, { ...SECURITY_HEADERS, location: `${PREFIX.slice(PREFIX.lastIndexOf('/') + 1)}/${url.search}` }).end()
138
+ return
139
+ }
140
+ const asset = ASSETS[rest]
141
+ if (asset === undefined) {
142
+ res.writeHead(404, { ...SECURITY_HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end('Not found.\n')
143
+ return
144
+ }
145
+ let body
146
+ try {
147
+ body = await read(asset.file)
148
+ } catch {
149
+ res.writeHead(500, { ...SECURITY_HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end('The viewer files are missing.\n')
150
+ return
151
+ }
152
+ res.writeHead(200, { ...SECURITY_HEADERS, 'content-type': asset.type, 'content-length': body.length })
153
+ res.end(req.method === 'HEAD' ? undefined : body)
154
+ }
155
+ }
156
+
157
+ /** Refuse an upgrade before any WebSocket handshake. */
158
+ export function refuseUpgrade(socket, status) {
159
+ const text = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden' }[status] ?? 'Error'
160
+ socket.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
161
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Keep a browser-facing WebSocket alive through the proxies in front of
3
+ * DSH, and notice when it is dead.
4
+ *
5
+ * The public path to DSH runs through proxies (a Cloudflare tunnel closes a
6
+ * WebSocket after about 100 s without traffic). A view's status socket is
7
+ * silent between control changes, and a media socket is silent while the
8
+ * desktop does not change, so both were cut. The relay therefore pings every
9
+ * browser socket on a fixed interval (browsers answer pings by themselves,
10
+ * also in background tabs) and drops a socket that missed a whole interval's
11
+ * pong, so a dead link is noticed in seconds rather than at the next send.
12
+ */
13
+
14
+ /** Ping interval: well below the ~100 s idle limit of common proxies. */
15
+ export const PING_INTERVAL_MS = 25_000
16
+
17
+ /**
18
+ * @param {import('ws').WebSocket} socket
19
+ * @param {object} [options]
20
+ * @param {number} [options.intervalMs]
21
+ * @param {() => void} [options.beat] - Extra traffic sent with each ping (an app-level heartbeat).
22
+ * @param {(callback: () => void, ms: number) => unknown} [options.setTimer]
23
+ * @param {(timer: unknown) => void} [options.clearTimer]
24
+ * @returns {() => void} stop
25
+ */
26
+ export function keepAlive(socket, { intervalMs = PING_INTERVAL_MS, beat, setTimer = setInterval, clearTimer = clearInterval } = {}) {
27
+ let answered = true
28
+ const onPong = () => { answered = true }
29
+ socket.on('pong', onPong)
30
+ const timer = setTimer(() => {
31
+ if (socket.readyState !== socket.OPEN) return
32
+ if (!answered) {
33
+ socket.terminate()
34
+ return
35
+ }
36
+ answered = false
37
+ socket.ping()
38
+ beat?.()
39
+ }, intervalMs)
40
+ timer?.unref?.()
41
+ const stop = () => {
42
+ clearTimer(timer)
43
+ socket.off('pong', onPong)
44
+ }
45
+ socket.once('close', stop)
46
+ return stop
47
+ }
package/src/media.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The media socket of the relayed viewer: one browser socket piped to one
3
+ * cua-spacesd `/media` socket. The browser presents the media ticket the
4
+ * daemon gave its viewer; the relay accepts it only when one of its own
5
+ * relay tickets opened that media session, and judges the socket by that
6
+ * ticket's mode. Everything the daemon sends goes down unchanged; only what
7
+ * {@link checkClientMessage} allows for the mode goes up.
8
+ *
9
+ * A slow browser (a phone on a weak link) must not make the server buffer
10
+ * video without limit: past `MAX_BUFFERED_BYTES` the relay drops frames and
11
+ * asks the daemon for a keyframe, then forwards again from that keyframe.
12
+ */
13
+ import WebSocket from 'ws'
14
+ import { checkClientMessage } from './filter.js'
15
+
16
+ /** Browser send buffer above which video frames are dropped. */
17
+ export const MAX_BUFFERED_BYTES = 4 * 1024 * 1024
18
+
19
+ /** Close codes the relay sends the browser (4000-4999 are application codes). */
20
+ export const CLOSE = Object.freeze({
21
+ CONTROL_ENDED: 4100,
22
+ UPSTREAM_FAILED: 4502,
23
+ })
24
+
25
+ /**
26
+ * Read whether one binary media packet is a video keyframe.
27
+ * @param {Buffer} data - `u32 header_len, u32 payload_len, JSON header, payload`.
28
+ * @returns {boolean | undefined} undefined when it is not a video packet
29
+ */
30
+ export function videoKeyframe(data) {
31
+ if (data.length < 8 || data[0] !== 0) return undefined
32
+ const length = data.readUInt32BE(0)
33
+ if (8 + length > data.length) return undefined
34
+ try {
35
+ const header = JSON.parse(data.subarray(8, 8 + length).toString('utf8'))
36
+ return header?.direction === 'video' ? header.message?.keyframe === true : undefined
37
+ } catch {
38
+ return undefined
39
+ }
40
+ }
41
+
42
+ /**
43
+ * The media ticket a browser presents: the `ticket` query parameter, or the
44
+ * `cua.ticket.<ticket>` subprotocol.
45
+ * @param {string | undefined} url
46
+ * @param {string | undefined} protocols - The Sec-WebSocket-Protocol header.
47
+ */
48
+ export function mediaTicketOf(url, protocols) {
49
+ const query = new URL(url ?? '/', 'http://relay.invalid').searchParams.get('ticket')
50
+ if (query) return query
51
+ for (const offered of (protocols ?? '').split(',')) {
52
+ const name = offered.trim()
53
+ if (name.startsWith('cua.ticket.')) return name.slice('cua.ticket.'.length)
54
+ }
55
+ return undefined
56
+ }
57
+
58
+ /**
59
+ * Pipe one accepted browser socket to the daemon.
60
+ * @param {object} options
61
+ * @param {import('ws').WebSocket} options.browser
62
+ * @param {'watch' | 'control'} options.mode
63
+ * @param {string} options.sessionId - The media session the ticket belongs to.
64
+ * @param {() => void} [options.onInput] - Called for each forwarded input batch.
65
+ * @param {() => WebSocket} options.connect - Opens the daemon socket.
66
+ * @param {{ warn: Function, debug: Function }} options.logger
67
+ * @returns {{ close: (code?: number, reason?: string) => void }}
68
+ */
69
+ export function pipeMedia({ browser, mode, sessionId, onInput = () => {}, connect, logger }) {
70
+ let closed = false
71
+ let skipping = false
72
+ const pending = []
73
+ const upstream = connect()
74
+
75
+ const close = (code = 1000, reason = '') => {
76
+ if (closed) return
77
+ closed = true
78
+ if (browser.readyState === browser.OPEN || browser.readyState === browser.CONNECTING) browser.close(code, reason)
79
+ upstream.terminate()
80
+ }
81
+
82
+ browser.on('close', () => close())
83
+ browser.on('error', () => close(1011))
84
+ browser.on('message', (data, binary) => {
85
+ const checked = checkClientMessage(data, binary, mode, sessionId)
86
+ if (!checked.ok) {
87
+ logger.debug('dropped a browser media message: %s', checked.reason)
88
+ return
89
+ }
90
+ if (checked.type === 'interactive_input') onInput()
91
+ if (upstream.readyState === WebSocket.OPEN) upstream.send(checked.data, { binary: checked.binary })
92
+ else if (upstream.readyState === WebSocket.CONNECTING) pending.push(checked)
93
+ })
94
+
95
+ upstream.on('open', () => {
96
+ for (const message of pending.splice(0)) upstream.send(message.data, { binary: message.binary })
97
+ })
98
+ upstream.on('message', (data, binary) => {
99
+ if (browser.readyState !== browser.OPEN) return
100
+ if (!binary) {
101
+ browser.send(data, { binary: false })
102
+ return
103
+ }
104
+ const keyframe = videoKeyframe(data)
105
+ if (keyframe !== undefined) {
106
+ if (skipping && !keyframe) return
107
+ if (!skipping && !keyframe && browser.bufferedAmount > MAX_BUFFERED_BYTES) {
108
+ skipping = true
109
+ upstream.send(JSON.stringify({ type: 'request_keyframe', payload: { session_id: sessionId } }))
110
+ return
111
+ }
112
+ skipping = false
113
+ }
114
+ browser.send(data, { binary: true })
115
+ })
116
+ upstream.on('close', (code, reason) => {
117
+ // Pass the daemon's own application codes through (MEDIA.md §10).
118
+ close(code >= 4000 && code < 5000 ? code : CLOSE.UPSTREAM_FAILED, String(reason).slice(0, 120))
119
+ })
120
+ upstream.on('error', (error) => {
121
+ logger.warn('media socket error: %s', error.message)
122
+ close(CLOSE.UPSTREAM_FAILED, 'desktop stream unavailable')
123
+ })
124
+
125
+ return { close }
126
+ }