@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/src/viewer.js ADDED
@@ -0,0 +1,246 @@
1
+ /**
2
+ * HTTP side of the relayed Cua viewer, under one fixed base (`/desktop-view/d/`):
3
+ *
4
+ * GET d/viewer/[asset] the daemon's viewer page and assets
5
+ * POST d/cua.env.v1.<Service>/<Rpc> gRPC-Web calls the viewer makes
6
+ *
7
+ * The page is the daemon's own (`/viewer/` on cua-spacesd), passed through
8
+ * with two changes: a same-origin script runs first so the viewer's fetches
9
+ * carry cookies (it sends them with `credentials: "omit"`, which DSH's
10
+ * login and the OIDC proxy in front of it would refuse), and the page may be
11
+ * framed by its own origin, for the sidebar tab.
12
+ *
13
+ * A gRPC-Web call carries a relay ticket where the viewer would send a
14
+ * viewer ticket. The relay looks it up, checks the method against its mode's
15
+ * allow-list, swaps in the daemon's viewer ticket for that mode, and streams
16
+ * the call through. OpenMedia answers are read on the way back, so the
17
+ * media socket can later be tied to the relay ticket that opened it.
18
+ */
19
+ import http from 'node:http'
20
+ import https from 'node:https'
21
+ import { Buffer } from 'node:buffer'
22
+ import { decodeMessage, parseGrpcWebResponse } from './proto.js'
23
+ import { UNAUTHENTICATED, decodeOpenMedia } from './spacesd.js'
24
+
25
+ /** The viewer's base path under the plugin prefix. */
26
+ export const VIEWER_BASE = 'd/'
27
+
28
+ /** Script the relay serves, which the viewer page loads first. */
29
+ export const SHIM_PATH = 'shim.js'
30
+
31
+ const WATCH_METHODS = Object.freeze([
32
+ 'SystemService/GetCapabilities',
33
+ 'StreamService/ListTargets',
34
+ 'StreamService/OpenMedia',
35
+ 'StreamService/SetPreferences',
36
+ 'StreamService/RequestKeyframe',
37
+ 'StreamService/CloseMedia',
38
+ 'PresenceService/Join',
39
+ 'PresenceService/UpdateCursor',
40
+ 'PresenceService/Leave',
41
+ ])
42
+
43
+ /** gRPC methods per mode: exactly what the viewer calls, nothing else. */
44
+ export const METHODS = Object.freeze({
45
+ watch: WATCH_METHODS,
46
+ control: Object.freeze([
47
+ ...WATCH_METHODS,
48
+ 'ComputerService/GetClipboard',
49
+ 'ComputerService/SetClipboard',
50
+ 'FilesystemService/Stat',
51
+ 'FilesystemService/ListDir',
52
+ 'FilesystemService/MakeDir',
53
+ 'FilesystemService/Move',
54
+ 'FilesystemService/Remove',
55
+ 'FilesystemService/ReadFile',
56
+ 'FilesystemService/BeginUpload',
57
+ 'FilesystemService/UploadChunk',
58
+ 'FilesystemService/CommitUpload',
59
+ 'FilesystemService/AbortUpload',
60
+ 'FilesystemService/CreateWatcher',
61
+ 'FilesystemService/GetWatcherEvents',
62
+ 'FilesystemService/RemoveWatcher',
63
+ ]),
64
+ })
65
+
66
+ /**
67
+ * Calls that mean the person in control did something, which keeps control
68
+ * from going idle. Polling the viewer does on its own (clipboard sync,
69
+ * folder watching) does not count.
70
+ */
71
+ export const ACTIVITY_METHODS = Object.freeze([
72
+ 'ComputerService/SetClipboard',
73
+ 'FilesystemService/MakeDir',
74
+ 'FilesystemService/Move',
75
+ 'FilesystemService/Remove',
76
+ 'FilesystemService/ReadFile',
77
+ 'FilesystemService/BeginUpload',
78
+ 'FilesystemService/UploadChunk',
79
+ 'FilesystemService/CommitUpload',
80
+ ])
81
+
82
+ /** Request headers passed to the daemon on a gRPC-Web call. */
83
+ const FORWARD_REQUEST = Object.freeze(['content-type', 'x-grpc-web', 'x-user-agent', 'grpc-timeout', 'accept', 'content-length'])
84
+ /** Response headers passed back to the viewer. */
85
+ const FORWARD_RESPONSE = Object.freeze(['content-type', 'grpc-status', 'grpc-message', 'grpc-status-details-bin', 'cache-control', 'content-length', 'etag', 'last-modified'])
86
+
87
+ const ASSET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/
88
+ const RPC_PATH = /^cua\.env\.v1\.([A-Za-z]+)\/([A-Za-z]+)$/
89
+
90
+ /**
91
+ * Where a path under the viewer base goes.
92
+ * @param {string} rest - The path after `/desktop-view/d/`.
93
+ * @returns {{ kind: 'asset', name: string } | { kind: 'rpc', method: string } | undefined}
94
+ */
95
+ export function classifyViewerPath(rest) {
96
+ if (rest === 'viewer/' || rest === 'viewer') return { kind: 'asset', name: '' }
97
+ if (rest.startsWith('viewer/')) {
98
+ const name = rest.slice('viewer/'.length)
99
+ return ASSET_NAME.test(name) ? { kind: 'asset', name } : undefined
100
+ }
101
+ const rpc = RPC_PATH.exec(rest)
102
+ return rpc === null ? undefined : { kind: 'rpc', method: `${rpc[1]}/${rpc[2]}` }
103
+ }
104
+
105
+ /** The relay ticket a viewer request carries. */
106
+ export function bearerOf(headers) {
107
+ const value = headers['x-cua-env-authorization'] ?? headers.authorization
108
+ const match = typeof value === 'string' ? /^Bearer\s+(\S+)$/i.exec(value) : null
109
+ return match?.[1]
110
+ }
111
+
112
+ /**
113
+ * Make the daemon's viewer page fit the relay: load the shim before
114
+ * anything else and allow same-origin framing.
115
+ * @param {string} html
116
+ * @param {string} shimUrl - Relative URL of the shim from the page.
117
+ * @returns {string | undefined} undefined when the page has no `<head>` to put it in
118
+ */
119
+ export function adaptViewerPage(html, shimUrl) {
120
+ const head = /<head[^>]*>/i.exec(html)
121
+ if (head === null) return undefined
122
+ const at = head.index + head[0].length
123
+ return `${html.slice(0, at)}\n <script src="${shimUrl}"></script>${html.slice(at)}`
124
+ }
125
+
126
+ /** The daemon page's CSP with framing allowed for this origin only. */
127
+ export function adaptCsp(value) {
128
+ if (typeof value !== 'string') return value
129
+ return value.replace(/frame-ancestors\s+[^;]*/i, "frame-ancestors 'self'")
130
+ }
131
+
132
+ /**
133
+ * @param {object} options
134
+ * @param {string} options.endpoint - cua-spacesd base URL.
135
+ * @param {ReturnType<typeof import('./tickets.js').createTicketBook>} options.tickets
136
+ * @param {(holderId: string) => void} options.touch - Records activity of a control holder.
137
+ * @param {{ warn: Function, debug: Function }} options.logger
138
+ * @param {typeof http.request} [options.request] - Test seam.
139
+ */
140
+ export function createViewerProxy({ endpoint, tickets, touch, logger, request }) {
141
+ const upstreamBase = new URL(endpoint.replace(/\/*$/, '/'))
142
+ const send = request ?? (upstreamBase.protocol === 'https:' ? https.request : http.request)
143
+
144
+ const fail = (res, status, text) => {
145
+ if (res.headersSent) return res.destroy()
146
+ res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }).end(`${text}\n`)
147
+ }
148
+
149
+ /** Copy the allowed headers of a daemon response. */
150
+ const responseHeaders = (upstream, pick = FORWARD_RESPONSE) => {
151
+ const headers = {}
152
+ for (const name of pick) if (upstream.headers[name] !== undefined) headers[name] = upstream.headers[name]
153
+ return headers
154
+ }
155
+
156
+ async function asset(req, res, name) {
157
+ if (req.method !== 'GET' && req.method !== 'HEAD') return fail(res, 405, 'Method not allowed.')
158
+ const upstream = await forward({ method: 'GET', path: `/viewer/${name}`, headers: {} })
159
+ const headers = {
160
+ ...responseHeaders(upstream, ['content-type', 'cache-control', 'etag', 'last-modified', 'permissions-policy', 'cross-origin-opener-policy']),
161
+ 'x-content-type-options': 'nosniff',
162
+ 'referrer-policy': 'no-referrer',
163
+ }
164
+ const csp = adaptCsp(upstream.headers['content-security-policy'])
165
+ if (csp !== undefined) headers['content-security-policy'] = csp
166
+ const isPage = String(upstream.headers['content-type'] ?? '').startsWith('text/html')
167
+ if (!isPage) {
168
+ res.writeHead(upstream.statusCode ?? 502, headers)
169
+ if (req.method === 'HEAD') {
170
+ upstream.resume()
171
+ res.end()
172
+ return
173
+ }
174
+ upstream.pipe(res)
175
+ return
176
+ }
177
+ const html = (await readAll(upstream)).toString('utf8')
178
+ const page = upstream.statusCode === 200 ? adaptViewerPage(html, `../../${SHIM_PATH}`) : html
179
+ if (page === undefined) return fail(res, 502, 'The desktop viewer page changed shape; update dsh-desktop-view.')
180
+ const body = Buffer.from(page)
181
+ res.writeHead(upstream.statusCode ?? 502, { ...headers, 'cache-control': 'no-store', 'content-length': body.length })
182
+ res.end(req.method === 'HEAD' ? undefined : body)
183
+ }
184
+
185
+ async function rpc(req, res, method) {
186
+ if (req.method !== 'POST') return fail(res, 405, 'Method not allowed.')
187
+ const token = bearerOf(req.headers)
188
+ const grant = tickets.lookup(token)
189
+ if (grant === undefined) return fail(res, 401, 'This desktop view has expired; reload it.')
190
+ if (!METHODS[grant.mode]?.includes(method)) return fail(res, 403, `${method} is not available in ${grant.mode} mode.`)
191
+ if (grant.mode === 'control' && ACTIVITY_METHODS.includes(method)) touch(grant.holderId)
192
+ const viewer = await tickets.viewerTicket(grant.mode)
193
+ const headers = { 'x-cua-env-authorization': `Bearer ${viewer.ticket}` }
194
+ for (const name of FORWARD_REQUEST) if (req.headers[name] !== undefined) headers[name] = req.headers[name]
195
+ const upstream = await forward({ method: 'POST', path: `/cua.env.v1.${method}`, headers, body: req })
196
+ if (Number(upstream.headers['grpc-status']) === UNAUTHENTICATED) tickets.invalidate(grant.mode)
197
+ res.writeHead(upstream.statusCode ?? 502, responseHeaders(upstream))
198
+ if (method !== 'StreamService/OpenMedia') {
199
+ upstream.pipe(res)
200
+ return
201
+ }
202
+ const body = await readAll(upstream)
203
+ try {
204
+ const parsed = parseGrpcWebResponse(body, new Headers())
205
+ const opened = parsed.status === 0 && parsed.message !== undefined ? decodeOpenMedia(decodeMessage(parsed.message)) : undefined
206
+ if (opened !== undefined) tickets.bindMedia(opened.ticket, token, opened.sessionId)
207
+ } catch (error) {
208
+ logger.debug('could not read an OpenMedia answer: %s', error.message)
209
+ }
210
+ res.end(body)
211
+ }
212
+
213
+ /** One request to the daemon; resolves with its response. */
214
+ function forward({ method, path, headers, body }) {
215
+ return new Promise((resolve, reject) => {
216
+ const outgoing = send(new URL(path.replace(/^\//, ''), upstreamBase), { method, headers }, resolve)
217
+ outgoing.on('error', reject)
218
+ if (body === undefined) outgoing.end()
219
+ else body.pipe(outgoing)
220
+ })
221
+ }
222
+
223
+ /**
224
+ * Handle a request under the viewer base.
225
+ * @param {import('node:http').IncomingMessage} req
226
+ * @param {import('node:http').ServerResponse} res
227
+ * @param {string} rest - Path after the viewer base.
228
+ */
229
+ return async (req, res, rest) => {
230
+ const target = classifyViewerPath(rest)
231
+ try {
232
+ if (target?.kind === 'asset') await asset(req, res, target.name)
233
+ else if (target?.kind === 'rpc') await rpc(req, res, target.method)
234
+ else fail(res, 404, 'Not found.')
235
+ } catch (error) {
236
+ logger.warn('desktop viewer request failed: %s', error.message)
237
+ fail(res, 502, 'The desktop is not reachable right now.')
238
+ }
239
+ }
240
+ }
241
+
242
+ async function readAll(stream) {
243
+ const chunks = []
244
+ for await (const chunk of stream) chunks.push(chunk)
245
+ return Buffer.concat(chunks)
246
+ }
@@ -0,0 +1,20 @@
1
+ * { box-sizing: border-box; }
2
+ html, body { margin: 0; height: 100%; background: #0b0b0c; color: #e8e8ea; font: 14px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; }
3
+ body { display: flex; flex-direction: column; height: 100dvh; overflow: hidden; }
4
+ .bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 8px max(12px, env(safe-area-inset-right)) 8px max(12px, env(safe-area-inset-left)); padding-top: max(8px, env(safe-area-inset-top)); background: #161618; border-bottom: 1px solid #2a2a2e; }
5
+ .status { display: inline-flex; align-items: center; gap: 8px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #b4b4ba; }
6
+ .status::before { content: ""; flex: none; width: 8px; height: 8px; border-radius: 50%; background: #6b6b72; }
7
+ .status[data-tone="live"]::before { background: #3fb950; }
8
+ .status[data-tone="control"] { color: #ffd479; }
9
+ .status[data-tone="control"]::before { background: #f0a020; }
10
+ .status[data-tone="error"]::before { background: #f85149; }
11
+ .actions { display: inline-flex; gap: 8px; flex: none; }
12
+ button { font: inherit; color: inherit; background: #26262a; border: 1px solid #3a3a40; border-radius: 8px; padding: 6px 12px; min-height: 36px; cursor: pointer; }
13
+ button.primary { background: #2f6feb; border-color: #2f6feb; color: #fff; }
14
+ button.primary[data-control="true"] { background: #26262a; border-color: #f0a020; color: #ffd479; }
15
+ .stage { position: relative; flex: 1; min-height: 0; display: flex; padding-bottom: env(safe-area-inset-bottom); }
16
+ .stage[data-control="true"] { box-shadow: inset 0 0 0 2px #f0a020; }
17
+ iframe { flex: 1; width: 100%; height: 100%; border: 0; display: block; background: #000; }
18
+ .stage[data-control="true"] iframe { margin: 2px; width: calc(100% - 4px); height: calc(100% - 4px); }
19
+ .message { position: absolute; left: 12px; right: 12px; bottom: max(12px, env(safe-area-inset-bottom)); margin: 0; padding: 8px 12px; border-radius: 10px; background: #26262a; color: #c8c8cc; text-align: center; }
20
+ @media (pointer: coarse) { button { min-height: 44px; } }
@@ -0,0 +1,26 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <meta name="referrer" content="no-referrer">
7
+ <meta name="color-scheme" content="dark">
8
+ <title>Desktop</title>
9
+ <link rel="icon" href="icon.svg" type="image/svg+xml">
10
+ <link rel="stylesheet" href="page.css">
11
+ <script type="module" src="page.js"></script>
12
+ </head>
13
+ <body>
14
+ <header class="bar">
15
+ <span class="status" id="status" role="status" aria-live="polite"></span>
16
+ <span class="actions">
17
+ <button type="button" id="retry" hidden></button>
18
+ <button type="button" id="toggle" class="primary"></button>
19
+ </span>
20
+ </header>
21
+ <main class="stage" id="stage">
22
+ <iframe id="viewer" title="Desktop"></iframe>
23
+ <p class="message" id="message" role="status" hidden></p>
24
+ </main>
25
+ </body>
26
+ </html>
package/viewer/page.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The full-screen page: the same status bar as the sidebar tab (status,
3
+ * Take control / Give back) over the relayed desktop viewer. It fits any
4
+ * screen and can be linked directly. `?control=1` opens it straight in
5
+ * control mode (the agent sends the owner such a link when it needs a
6
+ * hand); `?session=<id>` names the DSH session to tell when control changes;
7
+ * `?help=1` says the agent sent the link because it is waiting for the owner,
8
+ * so giving control back wakes it. `control` is dropped from the address
9
+ * after loading (a reload does not take control again); `help` stays.
10
+ *
11
+ * Text is in English or Chinese, following the browser's language. The
12
+ * sidebar tab in the DSH Web UI has its own dictionary in client.js,
13
+ * registered with DSH's locale service.
14
+ */
15
+ import { createDesktopSession } from './session.js'
16
+
17
+ const TEXT = {
18
+ en: {
19
+ title: 'Desktop',
20
+ connecting: 'Connecting…',
21
+ watching: 'Watching',
22
+ watchingOther: 'Watching · controlled in another view',
23
+ control: 'You are in control',
24
+ error: 'The desktop is unavailable. Retrying…',
25
+ take: 'Take control',
26
+ give: 'Give back',
27
+ retry: 'Retry',
28
+ 'ended.idle': 'Control returned to watching after a while without input.',
29
+ 'ended.replaced': 'Control moved to another view.',
30
+ 'ended.stopped': 'The desktop view stopped.',
31
+ },
32
+ zh: {
33
+ title: '桌面',
34
+ connecting: '正在连接…',
35
+ watching: '观看中',
36
+ watchingOther: '观看中 · 另一个窗口正在控制',
37
+ control: '你正在控制',
38
+ error: '桌面暂时不可用,正在重试…',
39
+ take: '接管控制',
40
+ give: '交还控制',
41
+ retry: '重试',
42
+ 'ended.idle': '一段时间没有操作,已回到观看模式。',
43
+ 'ended.replaced': '控制已转到另一个窗口。',
44
+ 'ended.stopped': '桌面查看器已停止。',
45
+ },
46
+ }
47
+
48
+ const lang = navigator.language.toLowerCase().startsWith('zh') ? 'zh' : 'en'
49
+ const t = key => TEXT[lang][key] ?? TEXT.en[key] ?? key
50
+ document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'
51
+ document.title = t('title')
52
+
53
+ const params = new URLSearchParams(location.search)
54
+ const statusEl = document.getElementById('status')
55
+ const toggle = document.getElementById('toggle')
56
+ const retry = document.getElementById('retry')
57
+ const stage = document.getElementById('stage')
58
+ const message = document.getElementById('message')
59
+
60
+ // Drop the one-off parameters so a reload does not take control again.
61
+ if (params.has('control') || params.has('bounced')) {
62
+ const clean = new URLSearchParams(params)
63
+ clean.delete('control')
64
+ clean.delete('bounced')
65
+ history.replaceState(null, '', `${location.pathname}${clean.size > 0 ? `?${clean}` : ''}`)
66
+ }
67
+
68
+ /** How long a note about control ending stays on screen. */
69
+ const NOTE_MS = 6000
70
+ let current = 'watch'
71
+ let shownEnded = null
72
+ let noteTimer
73
+
74
+ const render = (status) => {
75
+ current = status.mode
76
+ const inControl = status.mode === 'control' && status.mine
77
+ let label = t('connecting')
78
+ let tone = 'idle'
79
+ if (status.phase === 'error') {
80
+ label = t('error')
81
+ tone = 'error'
82
+ } else if (status.phase === 'live') {
83
+ label = inControl ? t('control') : status.controller !== null ? t('watchingOther') : t('watching')
84
+ tone = inControl ? 'control' : 'live'
85
+ }
86
+ statusEl.textContent = label
87
+ statusEl.dataset.tone = tone
88
+ toggle.textContent = status.mode === 'control' ? t('give') : t('take')
89
+ toggle.dataset.control = String(status.mode === 'control')
90
+ retry.hidden = status.phase !== 'error'
91
+ stage.dataset.control = String(inControl)
92
+ if (status.ended !== shownEnded) {
93
+ shownEnded = status.ended
94
+ const note = status.ended === null ? undefined : TEXT[lang][`ended.${status.ended}`]
95
+ if (note !== undefined) {
96
+ clearTimeout(noteTimer)
97
+ message.textContent = note
98
+ message.hidden = false
99
+ noteTimer = setTimeout(() => { message.hidden = true }, NOTE_MS)
100
+ }
101
+ }
102
+ }
103
+
104
+ retry.textContent = t('retry')
105
+ const session = createDesktopSession({
106
+ frame: document.getElementById('viewer'),
107
+ base: new URL('./', location.href),
108
+ sessionId: params.get('session'),
109
+ mode: params.get('control') === '1' ? 'control' : 'watch',
110
+ help: params.get('help') === '1',
111
+ onStatus: render,
112
+ })
113
+ toggle.addEventListener('click', () => session.setMode(current === 'control' ? 'watch' : 'control'))
114
+ retry.addEventListener('click', () => session.retry())
115
+ addEventListener('pagehide', () => session.destroy())
116
+ // A page restored from the back-forward cache has a closed session.
117
+ addEventListener('pageshow', (event) => { if (event.persisted) location.reload() })
@@ -0,0 +1,197 @@
1
+ /**
2
+ * One open view of the desktop, shared by the sidebar tab and the
3
+ * full-screen page: the status socket that carries Take control / Give
4
+ * back, and the frame that shows the relayed Cua viewer in the mode the
5
+ * server granted. It owns no UI text; callers render the status it reports.
6
+ *
7
+ * Status: { phase: 'connecting' | 'live' | 'error', mode: 'watch' | 'control',
8
+ * controller: 'user' | null, mine: boolean, ended: string | null }
9
+ */
10
+
11
+ const RETRY_MS = [1000, 2000, 5000, 10000]
12
+
13
+ /** Permissions the viewer frame may use (the page itself also allows them). */
14
+ export const FRAME_ALLOW = 'autoplay; clipboard-read; clipboard-write; microphone; fullscreen; keyboard-map'
15
+
16
+ /**
17
+ * The viewer URL for one grant. A fresh query makes the frame load anew;
18
+ * the fragment (ticket and options) never reaches a server.
19
+ * @param {URL} base - The plugin prefix URL, ending in '/'.
20
+ */
21
+ export function viewerUrl(base, { ticket, hints }, serial) {
22
+ const fragment = new URLSearchParams(hints)
23
+ fragment.set('ticket', ticket)
24
+ return new URL(`d/viewer/?v=${serial}#${fragment}`, base).href
25
+ }
26
+
27
+ /**
28
+ * @param {object} options
29
+ * @param {HTMLIFrameElement} options.frame
30
+ * @param {URL | string} options.base - URL of the plugin's prefix, ending in '/'.
31
+ * @param {string | null} [options.sessionId] - DSH session the view belongs to.
32
+ * @param {'watch' | 'control'} [options.mode] - Mode to ask for once connected.
33
+ * @param {boolean} [options.help] - Opened from the agent's help link: giving control back wakes the agent.
34
+ * @param {(status: object) => void} options.onStatus
35
+ */
36
+ export function createDesktopSession({ frame, base, sessionId = null, mode = 'watch', help = false, onStatus }) {
37
+ const root = new URL(base)
38
+ let socket
39
+ let failures = 0
40
+ let retryTimer
41
+ let destroyed = false
42
+ let serial = 0
43
+ let wanted = mode
44
+ /** Token to pick this view up again after a dropped socket. */
45
+ let resume = null
46
+ /** The relay ticket the frame shows now. */
47
+ let shown = null
48
+ /** The grant the server gave last; shown again after a pause. */
49
+ let latest = null
50
+ /** While paused the frame is unloaded, but the view and its control stay. */
51
+ let paused = false
52
+ let status = { phase: 'connecting', mode: 'watch', controller: null, mine: false, ended: null }
53
+
54
+ const report = (patch) => {
55
+ status = { ...status, ...patch }
56
+ onStatus(status)
57
+ }
58
+ const send = (message) => {
59
+ if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message))
60
+ }
61
+
62
+ frame.allow = FRAME_ALLOW
63
+ const onLoad = () => {
64
+ if (!paused && shown !== null && status.phase === 'connecting') report({ phase: 'live' })
65
+ }
66
+ frame.addEventListener('load', onLoad)
67
+
68
+ const show = (grant) => {
69
+ latest = grant
70
+ if (paused) {
71
+ report({ mode: grant.mode })
72
+ return
73
+ }
74
+ // A resumed view gets its current grant again; the frame keeps running.
75
+ if (grant.ticket === shown) {
76
+ report({ phase: frame.src === '' ? 'connecting' : 'live', mode: grant.mode })
77
+ return
78
+ }
79
+ shown = grant.ticket
80
+ serial += 1
81
+ report({ phase: 'connecting', mode: grant.mode })
82
+ frame.src = viewerUrl(root, grant, serial)
83
+ }
84
+
85
+ const onMessage = (event) => {
86
+ let message
87
+ try {
88
+ message = JSON.parse(event.data)
89
+ } catch {
90
+ return
91
+ }
92
+ switch (message?.type) {
93
+ case 'hello':
94
+ resume = message.resume
95
+ break
96
+ case 'state':
97
+ report({ controller: message.controller, mine: message.mine === true })
98
+ break
99
+ case 'view':
100
+ if (message.mode === 'watch' && wanted === 'control' && !status.mine) {
101
+ // First grant after connecting: the page asked to start in control.
102
+ wanted = 'watch'
103
+ send({ type: 'take' })
104
+ }
105
+ show(message)
106
+ break
107
+ case 'ended':
108
+ wanted = 'watch'
109
+ report({ ended: message.reason })
110
+ break
111
+ case 'error':
112
+ report({ phase: 'error' })
113
+ break
114
+ default:
115
+ break
116
+ }
117
+ }
118
+
119
+ const connect = () => {
120
+ clearTimeout(retryTimer)
121
+ if (destroyed) return
122
+ const query = new URLSearchParams()
123
+ if (sessionId) query.set('session', sessionId)
124
+ if (resume) query.set('resume', resume)
125
+ if (help) query.set('help', '1')
126
+ const url = new URL(`status${query.size > 0 ? `?${query}` : ''}`, root)
127
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
128
+ const current = new WebSocket(url)
129
+ socket = current
130
+ current.onmessage = onMessage
131
+ current.onopen = () => { failures = 0 }
132
+ current.onclose = () => {
133
+ if (socket !== current || destroyed) return
134
+ socket = undefined
135
+ failures += 1
136
+ // The server keeps the view (and its control) for a short grace
137
+ // period; reconnecting with the resume token picks it up unchanged.
138
+ // If that is too late, the server starts a new watching view, and
139
+ // control is only ever taken again on request.
140
+ wanted = 'watch'
141
+ report({ phase: failures > 2 ? 'error' : 'connecting' })
142
+ retryTimer = setTimeout(connect, RETRY_MS[Math.min(failures - 1, RETRY_MS.length - 1)])
143
+ }
144
+ }
145
+
146
+ onStatus(status)
147
+ connect()
148
+
149
+ return {
150
+ /** Ask to take control, or give it back. */
151
+ setMode(next) {
152
+ if (next === 'control') {
153
+ report({ ended: null })
154
+ send({ type: 'take' })
155
+ } else {
156
+ send({ type: 'give' })
157
+ }
158
+ },
159
+ /**
160
+ * Stop showing the desktop but keep the view: the frame is unloaded (no
161
+ * stream, no decoding), while the status socket, the grant and control
162
+ * stay. Used while the sidebar tab is hidden.
163
+ */
164
+ pause() {
165
+ if (paused) return
166
+ paused = true
167
+ shown = null
168
+ frame.src = 'about:blank'
169
+ },
170
+ /** Show the desktop again after {@link pause}, with the current grant. */
171
+ resume() {
172
+ if (!paused) return
173
+ paused = false
174
+ if (latest !== null) show(latest)
175
+ },
176
+ /** Reconnect after an error. */
177
+ retry() {
178
+ failures = 0
179
+ if (socket !== undefined) {
180
+ socket.onclose = null
181
+ socket.close(1000)
182
+ socket = undefined
183
+ }
184
+ connect()
185
+ },
186
+ destroy() {
187
+ destroyed = true
188
+ clearTimeout(retryTimer)
189
+ frame.removeEventListener('load', onLoad)
190
+ if (socket !== undefined) {
191
+ socket.onclose = null
192
+ socket.close(1000)
193
+ }
194
+ frame.src = 'about:blank'
195
+ },
196
+ }
197
+ }
package/viewer/shim.js ADDED
@@ -0,0 +1,11 @@
1
+ /*
2
+ * Loaded by the relayed Cua viewer page before its own code. The viewer
3
+ * sends its gRPC-Web calls with `credentials: "omit"`; behind DSH, every
4
+ * request must carry the login cookies (DSH's own and the sign-in proxy's),
5
+ * so its fetches here keep same-origin credentials instead. Nothing else in
6
+ * the page changes.
7
+ */
8
+ (() => {
9
+ const original = window.fetch.bind(window)
10
+ window.fetch = (input, init) => original(input, { ...init, credentials: 'same-origin' })
11
+ })()