@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/LICENSE +21 -0
- package/README.md +72 -2
- package/client.js +392 -0
- package/cordis.patch.yml +7 -0
- package/icon.svg +14 -0
- package/index.js +132 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +74 -4
- package/src/config.js +27 -0
- package/src/control.js +133 -0
- package/src/filter.js +56 -0
- package/src/http.js +161 -0
- package/src/keepalive.js +47 -0
- package/src/media.js +126 -0
- package/src/notify.js +103 -0
- package/src/proto.js +158 -0
- package/src/spacesd.js +122 -0
- package/src/status.js +178 -0
- package/src/tickets.js +120 -0
- package/src/viewer.js +246 -0
- package/viewer/page.css +20 -0
- package/viewer/page.html +26 -0
- package/viewer/page.js +117 -0
- package/viewer/session.js +197 -0
- package/viewer/shim.js +11 -0
package/src/notify.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tell the agent of the DSH session a view was opened from when the owner
|
|
3
|
+
* takes or gives back control of the desktop, so it neither fights the owner
|
|
4
|
+
* nor waits forever for a CAPTCHA that is already solved, without starting
|
|
5
|
+
* turns nobody needs.
|
|
6
|
+
*
|
|
7
|
+
* - Taking control never starts a turn: the note is queued for the agent's
|
|
8
|
+
* next step (`agent.inject`), so a busy agent sees it before it touches the
|
|
9
|
+
* desktop again, and an idle one has nothing to stop.
|
|
10
|
+
* - Giving control back (any way: button, idle timeout, closed view) is sent
|
|
11
|
+
* as steering (`agent.steer`) only when the agent has to carry on: it is
|
|
12
|
+
* running, or the view was opened from a help link the agent sent
|
|
13
|
+
* (`?help=1`), so it is waiting for the owner. Otherwise the note is queued
|
|
14
|
+
* quietly like the first one. With `quiet` nothing ever wakes the agent.
|
|
15
|
+
*
|
|
16
|
+
* The messages carry this plugin's own source kind, which DSH's message
|
|
17
|
+
* source union allows producers to add; the Web UI half shows them as a
|
|
18
|
+
* "Desktop control" row (client.js).
|
|
19
|
+
*/
|
|
20
|
+
import { randomUUID } from 'node:crypto'
|
|
21
|
+
|
|
22
|
+
export const NOTIFY_MODES = Object.freeze(['wake', 'quiet', 'off'])
|
|
23
|
+
export const SOURCE_KIND = 'desktop-view'
|
|
24
|
+
|
|
25
|
+
/** Short wording of why control ended, for the agent. */
|
|
26
|
+
const RELEASE_WORDING = Object.freeze({
|
|
27
|
+
released: 'gave the desktop back',
|
|
28
|
+
idle: 'stopped using the desktop (idle timeout)',
|
|
29
|
+
disconnected: 'closed the desktop view',
|
|
30
|
+
stopped: 'lost control (the desktop view stopped)',
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
/** The model-facing text for one control change. Kept short: it lands in the agent's context. */
|
|
34
|
+
export function noticeText(change, stateFile) {
|
|
35
|
+
if (change.kind === 'taken') {
|
|
36
|
+
return `The owner took control of the desktop. Leave the mouse, keyboard and browser alone until it is given back (state: ${stateFile}).`
|
|
37
|
+
}
|
|
38
|
+
return `The owner ${RELEASE_WORDING[change.reason] ?? RELEASE_WORDING.released}. You may use the desktop again; take a screenshot first.`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The one-line summary the chat row shows. */
|
|
42
|
+
export function noticeSummary(change) {
|
|
43
|
+
return change.kind === 'taken' ? 'Owner took control' : 'Owner gave control back'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether a control change should wake the agent.
|
|
48
|
+
* @param {{ kind: string, help?: boolean }} change
|
|
49
|
+
* @param {'wake' | 'quiet' | 'off'} mode
|
|
50
|
+
* @param {{ status?: string } | undefined} agent - The live agent, when there is one.
|
|
51
|
+
*/
|
|
52
|
+
export function shouldWake(change, mode, agent) {
|
|
53
|
+
if (mode !== 'wake' || change.kind !== 'released') return false
|
|
54
|
+
return change.help === true || (agent?.status !== undefined && agent.status !== 'idle')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param {object} options
|
|
59
|
+
* @param {{ get: (name: string) => any }} options.ctx - Plugin context, for `agents` and `sessionController`.
|
|
60
|
+
* @param {'wake' | 'quiet' | 'off'} options.mode
|
|
61
|
+
* @param {string} options.stateFile
|
|
62
|
+
* @param {{ warn: Function }} options.logger
|
|
63
|
+
* @returns {(state: object, change: { kind: string, reason?: string, sessionId: string | null, help?: boolean }) => Promise<void>}
|
|
64
|
+
*/
|
|
65
|
+
export function createNotifier({ ctx, mode, stateFile, logger }) {
|
|
66
|
+
return async (_state, change) => {
|
|
67
|
+
if (mode === 'off' || change.sessionId === null) return
|
|
68
|
+
// Another view taking over is not a hand-back to the agent.
|
|
69
|
+
if (change.kind === 'released' && change.reason === 'replaced') return
|
|
70
|
+
const message = {
|
|
71
|
+
id: randomUUID(),
|
|
72
|
+
role: 'user',
|
|
73
|
+
content: [{ type: 'text', text: noticeText(change, stateFile) }],
|
|
74
|
+
source: { kind: SOURCE_KIND, form: 'notice', summary: noticeSummary(change), change: change.kind },
|
|
75
|
+
}
|
|
76
|
+
const deliver = async () => {
|
|
77
|
+
const live = ctx.get('agents')?.get(change.sessionId)
|
|
78
|
+
const wake = shouldWake(change, mode, live)
|
|
79
|
+
// A session the owner asked for help from is resumed if needed; any
|
|
80
|
+
// other note waits for a live agent's next step.
|
|
81
|
+
const agent = live ?? (wake ? await resolve(ctx, change.sessionId) : undefined)
|
|
82
|
+
if (agent === undefined) return
|
|
83
|
+
if (wake) agent.steer(message)
|
|
84
|
+
else agent.inject(message)
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
// A socket callback has no initiating agent; say so explicitly, as DSH's schedule does.
|
|
88
|
+
const agents = ctx.get('agents')
|
|
89
|
+
await (agents === undefined ? deliver() : agents.withoutInitiator(deliver))
|
|
90
|
+
} catch (error) {
|
|
91
|
+
logger.warn('could not tell session %s about the desktop: %s', change.sessionId, error instanceof Error ? error.message : String(error))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Resume a session's agent, the way DSH's own schedule does. */
|
|
97
|
+
async function resolve(ctx, sessionId) {
|
|
98
|
+
const controller = ctx.get('sessionController')
|
|
99
|
+
if (controller === undefined) return undefined
|
|
100
|
+
const resolved = await controller.resolveAgent(sessionId)
|
|
101
|
+
if ('error' in resolved) throw resolved.error
|
|
102
|
+
return resolved.agent
|
|
103
|
+
}
|
package/src/proto.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The few protobuf and gRPC-Web pieces the relay needs to call
|
|
3
|
+
* `cua.env.v1.StreamService` on cua-spacesd. The daemon answers gRPC-Web
|
|
4
|
+
* only in its binary form, and the relay sends three small messages, so a
|
|
5
|
+
* hand-written encoder for varints, strings and nested messages is smaller
|
|
6
|
+
* and easier to audit than a generated client.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const WIRE_VARINT = 0
|
|
10
|
+
const WIRE_LENGTH = 2
|
|
11
|
+
|
|
12
|
+
/** Encode an unsigned integer (up to 2^53) as a protobuf varint. */
|
|
13
|
+
function varint(value) {
|
|
14
|
+
const bytes = []
|
|
15
|
+
let rest = value
|
|
16
|
+
while (rest >= 0x80) {
|
|
17
|
+
bytes.push((rest % 0x80) | 0x80)
|
|
18
|
+
rest = Math.floor(rest / 0x80)
|
|
19
|
+
}
|
|
20
|
+
bytes.push(rest)
|
|
21
|
+
return Buffer.from(bytes)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function tag(field, wire) {
|
|
25
|
+
return varint(field * 8 + wire)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Encode one message from a list of fields. Zero numbers, empty strings and
|
|
30
|
+
* undefined values are left out, as proto3 does for defaults.
|
|
31
|
+
* @param {Array<[number, 'varint' | 'string' | 'message', number | string | Buffer | undefined]>} fields
|
|
32
|
+
* @returns {Buffer}
|
|
33
|
+
*/
|
|
34
|
+
export function encodeMessage(fields) {
|
|
35
|
+
const parts = []
|
|
36
|
+
for (const [field, kind, value] of fields) {
|
|
37
|
+
if (value === undefined || value === 0 || value === '') continue
|
|
38
|
+
if (kind === 'varint') {
|
|
39
|
+
parts.push(tag(field, WIRE_VARINT), varint(value))
|
|
40
|
+
} else {
|
|
41
|
+
const bytes = kind === 'string' ? Buffer.from(value, 'utf8') : value
|
|
42
|
+
parts.push(tag(field, WIRE_LENGTH), varint(bytes.length), bytes)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return Buffer.concat(parts)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Decode one message into a map from field number to its values, in order.
|
|
50
|
+
* Varints become numbers, length-delimited fields stay Buffers (decode them
|
|
51
|
+
* again or read them as text). Fixed-width fields are skipped.
|
|
52
|
+
* @param {Buffer} bytes
|
|
53
|
+
* @returns {Map<number, Array<number | Buffer>>}
|
|
54
|
+
*/
|
|
55
|
+
export function decodeMessage(bytes) {
|
|
56
|
+
const fields = new Map()
|
|
57
|
+
let offset = 0
|
|
58
|
+
const readVarint = () => {
|
|
59
|
+
let value = 0
|
|
60
|
+
let scale = 1
|
|
61
|
+
for (;;) {
|
|
62
|
+
if (offset >= bytes.length) throw new Error('truncated protobuf varint')
|
|
63
|
+
const byte = bytes[offset++]
|
|
64
|
+
value += (byte & 0x7f) * scale
|
|
65
|
+
if (byte < 0x80) return value
|
|
66
|
+
scale *= 0x80
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
while (offset < bytes.length) {
|
|
70
|
+
const key = readVarint()
|
|
71
|
+
const field = Math.floor(key / 8)
|
|
72
|
+
const wire = key % 8
|
|
73
|
+
let value
|
|
74
|
+
if (wire === WIRE_VARINT) {
|
|
75
|
+
value = readVarint()
|
|
76
|
+
} else if (wire === WIRE_LENGTH) {
|
|
77
|
+
const length = readVarint()
|
|
78
|
+
if (offset + length > bytes.length) throw new Error('truncated protobuf field')
|
|
79
|
+
value = bytes.subarray(offset, offset + length)
|
|
80
|
+
offset += length
|
|
81
|
+
} else if (wire === 1) {
|
|
82
|
+
offset += 8
|
|
83
|
+
continue
|
|
84
|
+
} else if (wire === 5) {
|
|
85
|
+
offset += 4
|
|
86
|
+
continue
|
|
87
|
+
} else {
|
|
88
|
+
throw new Error(`unsupported protobuf wire type ${wire}`)
|
|
89
|
+
}
|
|
90
|
+
if (!fields.has(field)) fields.set(field, [])
|
|
91
|
+
fields.get(field).push(value)
|
|
92
|
+
}
|
|
93
|
+
return fields
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** First value of a field read as UTF-8 text, or ''. */
|
|
97
|
+
export function text(fields, field) {
|
|
98
|
+
const value = fields.get(field)?.[0]
|
|
99
|
+
return Buffer.isBuffer(value) ? value.toString('utf8') : ''
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** First value of a varint field, or 0. */
|
|
103
|
+
export function number(fields, field) {
|
|
104
|
+
const value = fields.get(field)?.[0]
|
|
105
|
+
return typeof value === 'number' ? value : 0
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** First value of a nested message field, decoded, or an empty map. */
|
|
109
|
+
export function message(fields, field) {
|
|
110
|
+
const value = fields.get(field)?.[0]
|
|
111
|
+
return Buffer.isBuffer(value) ? decodeMessage(value) : new Map()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Wrap one message in a gRPC-Web data frame. */
|
|
115
|
+
export function grpcWebFrame(body) {
|
|
116
|
+
const header = Buffer.alloc(5)
|
|
117
|
+
header.writeUInt32BE(body.length, 1)
|
|
118
|
+
return Buffer.concat([header, body])
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Split a gRPC-Web response body into its message and status. The status
|
|
123
|
+
* comes from the trailer frame, or from the HTTP headers when the server
|
|
124
|
+
* sent a trailers-only response.
|
|
125
|
+
* @param {Buffer} body
|
|
126
|
+
* @param {Headers} headers
|
|
127
|
+
* @returns {{ message: Buffer | undefined, status: number, statusMessage: string }}
|
|
128
|
+
*/
|
|
129
|
+
export function parseGrpcWebResponse(body, headers) {
|
|
130
|
+
let message
|
|
131
|
+
let trailers = ''
|
|
132
|
+
let offset = 0
|
|
133
|
+
while (offset + 5 <= body.length) {
|
|
134
|
+
const flags = body[offset]
|
|
135
|
+
const length = body.readUInt32BE(offset + 1)
|
|
136
|
+
const frame = body.subarray(offset + 5, offset + 5 + length)
|
|
137
|
+
offset += 5 + length
|
|
138
|
+
if (flags & 0x80) trailers += frame.toString('utf8')
|
|
139
|
+
else if (message === undefined) message = frame
|
|
140
|
+
}
|
|
141
|
+
const values = new Map()
|
|
142
|
+
for (const line of trailers.split('\r\n')) {
|
|
143
|
+
const colon = line.indexOf(':')
|
|
144
|
+
if (colon > 0) values.set(line.slice(0, colon).trim().toLowerCase(), line.slice(colon + 1).trim())
|
|
145
|
+
}
|
|
146
|
+
const status = values.get('grpc-status') ?? headers.get('grpc-status') ?? (message === undefined ? '2' : '0')
|
|
147
|
+
const statusMessage = values.get('grpc-message') ?? headers.get('grpc-message') ?? ''
|
|
148
|
+
return { message, status: Number(status), statusMessage: percentDecode(statusMessage) }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** gRPC percent-encodes its status message; keep the raw text when it is malformed. */
|
|
152
|
+
function percentDecode(value) {
|
|
153
|
+
try {
|
|
154
|
+
return decodeURIComponent(value)
|
|
155
|
+
} catch {
|
|
156
|
+
return value
|
|
157
|
+
}
|
|
158
|
+
}
|
package/src/spacesd.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The relay's own calls to cua-spacesd: minting viewer tickets. The env
|
|
3
|
+
* token is read from its file for every call, so a rotated token is picked
|
|
4
|
+
* up, and it only ever travels in a request header to the daemon; it is
|
|
5
|
+
* never logged, put in a URL or sent to a browser.
|
|
6
|
+
*
|
|
7
|
+
* A viewer ticket is the daemon's scoped credential for its web viewer
|
|
8
|
+
* (`SystemService.CreateViewerTicket`): a session-policy ceiling (a
|
|
9
|
+
* view-only ticket cannot open an input-capable stream), clipboard access,
|
|
10
|
+
* a file root, microphone uplink, and a lifetime. The daemon enforces the
|
|
11
|
+
* scope itself; the relay keeps the tickets server-side too.
|
|
12
|
+
*/
|
|
13
|
+
import { readFile } from 'node:fs/promises'
|
|
14
|
+
import { decodeMessage, encodeMessage, grpcWebFrame, message, number, parseGrpcWebResponse, text } from './proto.js'
|
|
15
|
+
|
|
16
|
+
/** `SessionPolicy` values of stream.proto. */
|
|
17
|
+
export const POLICY = Object.freeze({ view_only: 1, allow_activation: 3 })
|
|
18
|
+
|
|
19
|
+
/** How long one call to the daemon may take. */
|
|
20
|
+
const CALL_TIMEOUT_MS = 10_000
|
|
21
|
+
|
|
22
|
+
/** gRPC status the daemon answers when a bearer is missing or no longer valid. */
|
|
23
|
+
export const UNAUTHENTICATED = 16
|
|
24
|
+
|
|
25
|
+
/** A daemon call failed; `status` is the gRPC status code when there was one. */
|
|
26
|
+
export class SpacesdError extends Error {
|
|
27
|
+
constructor(message, status) {
|
|
28
|
+
super(message)
|
|
29
|
+
this.name = 'SpacesdError'
|
|
30
|
+
this.status = status
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {object} options
|
|
36
|
+
* @param {string} options.endpoint - Base URL of cua-spacesd, such as http://127.0.0.1:3211.
|
|
37
|
+
* @param {string} options.tokenFile - File holding the env token.
|
|
38
|
+
* @param {typeof fetch} [options.fetch]
|
|
39
|
+
* @param {(path: string) => Promise<string>} [options.readToken] - Test seam.
|
|
40
|
+
*/
|
|
41
|
+
export function createSpacesd({ endpoint, tokenFile, fetch = globalThis.fetch, readToken }) {
|
|
42
|
+
const base = endpoint.replace(/\/+$/, '')
|
|
43
|
+
const token = readToken ?? (async path => (await readFile(path, 'utf8')).trim())
|
|
44
|
+
|
|
45
|
+
async function call(service, method, body) {
|
|
46
|
+
const secret = await token(tokenFile).catch((error) => {
|
|
47
|
+
throw new SpacesdError(`cannot read the cua-spacesd token file (${error.code ?? 'error'})`)
|
|
48
|
+
})
|
|
49
|
+
if (secret === '') throw new SpacesdError('the cua-spacesd token file is empty')
|
|
50
|
+
let response
|
|
51
|
+
try {
|
|
52
|
+
response = await fetch(`${base}/cua.env.v1.${service}/${method}`, {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
headers: {
|
|
55
|
+
'content-type': 'application/grpc-web+proto',
|
|
56
|
+
'x-grpc-web': '1',
|
|
57
|
+
'x-cua-env-authorization': `Bearer ${secret}`,
|
|
58
|
+
},
|
|
59
|
+
body: grpcWebFrame(body),
|
|
60
|
+
signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
|
|
61
|
+
})
|
|
62
|
+
} catch (error) {
|
|
63
|
+
throw new SpacesdError(`cua-spacesd is not reachable at ${base} (${error.cause?.code ?? error.name})`)
|
|
64
|
+
}
|
|
65
|
+
if (!response.ok) throw new SpacesdError(`cua-spacesd answered HTTP ${response.status} to ${method}`)
|
|
66
|
+
const parsed = parseGrpcWebResponse(Buffer.from(await response.arrayBuffer()), response.headers)
|
|
67
|
+
if (parsed.status !== 0) {
|
|
68
|
+
throw new SpacesdError(`cua-spacesd ${method} failed (status ${parsed.status}): ${parsed.statusMessage}`, parsed.status)
|
|
69
|
+
}
|
|
70
|
+
return decodeMessage(parsed.message ?? Buffer.alloc(0))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
/** Base URL of the daemon, without a trailing slash. */
|
|
75
|
+
base,
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Mint a viewer ticket.
|
|
79
|
+
* @param {{ policy: keyof typeof POLICY, clipboard: boolean, filesRoot: string, audioUplink: boolean, ttlSeconds: number, name: string }} options
|
|
80
|
+
* @returns {Promise<{ ticket: string, expiresAt: number, hints: string }>} `hints` is the viewer fragment without the ticket.
|
|
81
|
+
*/
|
|
82
|
+
async createViewerTicket(options) {
|
|
83
|
+
return decodeViewerTicket(await call('SystemService', 'CreateViewerTicket', encodeViewerTicket(options)))
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The `CreateViewerTicketRequest` bytes. */
|
|
89
|
+
export function encodeViewerTicket({ policy, clipboard, filesRoot, audioUplink, ttlSeconds, name }) {
|
|
90
|
+
const policyValue = POLICY[policy]
|
|
91
|
+
if (policyValue === undefined) throw new Error(`unknown viewer policy ${JSON.stringify(policy)}`)
|
|
92
|
+
return encodeMessage([
|
|
93
|
+
[1, 'message', encodeMessage([[1, 'varint', ttlSeconds]])],
|
|
94
|
+
[2, 'varint', policyValue],
|
|
95
|
+
[3, 'varint', clipboard ? 1 : 0],
|
|
96
|
+
[4, 'string', filesRoot],
|
|
97
|
+
[5, 'varint', audioUplink ? 1 : 0],
|
|
98
|
+
// PrincipalKind 1 is a human; the daemon prefixes the id with `viewer:`.
|
|
99
|
+
[6, 'message', encodeMessage([[1, 'string', 'dsh-owner'], [2, 'string', name], [4, 'varint', 1]])],
|
|
100
|
+
])
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The fields of a `CreateViewerTicketResponse` the relay uses. */
|
|
104
|
+
export function decodeViewerTicket(fields) {
|
|
105
|
+
const ticket = text(fields, 1)
|
|
106
|
+
if (ticket === '') throw new SpacesdError('cua-spacesd returned no viewer ticket')
|
|
107
|
+
const expires = message(fields, 2)
|
|
108
|
+
const fragment = new URLSearchParams(text(fields, 3).split('#')[1] ?? '')
|
|
109
|
+
fragment.delete('ticket')
|
|
110
|
+
return { ticket, expiresAt: number(expires, 1) * 1000, hints: fragment.toString() }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The media session id and ticket from an `OpenMediaResponse`, so the relay
|
|
115
|
+
* can tell which viewer opened a media socket.
|
|
116
|
+
* @returns {{ sessionId: string, ticket: string } | undefined}
|
|
117
|
+
*/
|
|
118
|
+
export function decodeOpenMedia(fields) {
|
|
119
|
+
const sessionId = text(fields, 1)
|
|
120
|
+
const ticket = text(fields, 2)
|
|
121
|
+
return sessionId === '' || ticket === '' ? undefined : { sessionId, ticket }
|
|
122
|
+
}
|
package/src/status.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The open views of the desktop (sidebar tabs, full-screen pages) and their
|
|
3
|
+
* status sockets. A view carries the approved flow: it starts watching,
|
|
4
|
+
* "Take control" and "Give back" are messages on its socket, and the server
|
|
5
|
+
* answers with the relay ticket the view's viewer should load.
|
|
6
|
+
*
|
|
7
|
+
* Server to browser:
|
|
8
|
+
* { type: 'hello', resume } once per view: the token to resume it with
|
|
9
|
+
* { type: 'state', controller, since, mine } on connect and on every control change
|
|
10
|
+
* { type: 'view', mode, ticket, hints } load the viewer in this mode with this relay ticket
|
|
11
|
+
* { type: 'ended', reason } control ended without the view asking
|
|
12
|
+
* { type: 'error', message } the desktop could not be reached
|
|
13
|
+
* { type: 'heartbeat' } keeps proxies from closing a quiet socket
|
|
14
|
+
*
|
|
15
|
+
* Browser to server:
|
|
16
|
+
* { type: 'take' } | { type: 'give' }
|
|
17
|
+
*
|
|
18
|
+
* Control and tickets belong to the view, not to one socket. A socket that
|
|
19
|
+
* drops without closing on purpose (a proxy cut it, the network changed)
|
|
20
|
+
* leaves the view waiting for `graceMs`: a socket that comes back with the
|
|
21
|
+
* view's resume token picks it up unchanged, with its tickets, its stream
|
|
22
|
+
* and its control. A view closed on purpose (code 1000) or not resumed in
|
|
23
|
+
* time ends: control is given back and its tickets are revoked, which
|
|
24
|
+
* closes its media sockets.
|
|
25
|
+
*/
|
|
26
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
27
|
+
import { keepAlive } from './keepalive.js'
|
|
28
|
+
|
|
29
|
+
/** Close code for a socket the browser should not reconnect as control. */
|
|
30
|
+
export const CLOSE_STOPPED = 1001
|
|
31
|
+
|
|
32
|
+
/** How long a dropped view waits for its socket to come back. */
|
|
33
|
+
export const RESUME_GRACE_MS = 30_000
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {object} options
|
|
37
|
+
* @param {ReturnType<typeof import('./control.js').createControl>} options.control
|
|
38
|
+
* @param {ReturnType<typeof import('./tickets.js').createTicketBook>} options.tickets
|
|
39
|
+
* @param {{ maxFps: number }} options.viewer - Viewer options added to its fragment.
|
|
40
|
+
* @param {{ warn: Function, debug: Function }} options.logger
|
|
41
|
+
* @param {number} [options.graceMs]
|
|
42
|
+
* @param {object} [options.keepalive] - Options for {@link keepAlive} (tests).
|
|
43
|
+
*/
|
|
44
|
+
export function createViews({ control, tickets, viewer, logger, graceMs = RESUME_GRACE_MS, keepalive = {} }) {
|
|
45
|
+
/** @type {Map<string, ReturnType<typeof createView>>} by resume token */
|
|
46
|
+
const views = new Map()
|
|
47
|
+
|
|
48
|
+
function createView(sessionId, help) {
|
|
49
|
+
const holderId = randomUUID()
|
|
50
|
+
const resume = randomBytes(24).toString('base64url')
|
|
51
|
+
let socket
|
|
52
|
+
let ended = false
|
|
53
|
+
let graceTimer
|
|
54
|
+
/** The grant the viewer should show now, re-sent on resume. */
|
|
55
|
+
let current
|
|
56
|
+
|
|
57
|
+
const send = (message) => {
|
|
58
|
+
if (socket !== undefined && socket.readyState === socket.OPEN) socket.send(JSON.stringify(message))
|
|
59
|
+
}
|
|
60
|
+
const sendState = state => send({ type: 'state', controller: state.controller, since: state.since, mine: control.holds(holderId) })
|
|
61
|
+
|
|
62
|
+
/** Issue a relay ticket for a mode and tell the view to load it. */
|
|
63
|
+
const grant = async (mode) => {
|
|
64
|
+
try {
|
|
65
|
+
const { hints } = await tickets.viewerTicket(mode)
|
|
66
|
+
// Control may have ended (or the view closed) while the ticket was minted.
|
|
67
|
+
if (ended || (mode === 'control' && !control.holds(holderId))) return
|
|
68
|
+
// Only one ticket per mode and view is live at a time.
|
|
69
|
+
tickets.revokeHolder(holderId, mode)
|
|
70
|
+
const ticket = tickets.issue({ mode, holderId, sessionId })
|
|
71
|
+
const fragment = new URLSearchParams(hints)
|
|
72
|
+
fragment.set('fps', String(viewer.maxFps))
|
|
73
|
+
if (mode === 'watch') fragment.set('view_only', '1')
|
|
74
|
+
current = { type: 'view', mode, ticket, hints: fragment.toString() }
|
|
75
|
+
send(current)
|
|
76
|
+
} catch (error) {
|
|
77
|
+
logger.warn('could not open the desktop viewer: %s', error.message)
|
|
78
|
+
send({ type: 'error', message: 'desktop unavailable' })
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const onMessage = (data, binary) => {
|
|
83
|
+
if (binary) return
|
|
84
|
+
let message
|
|
85
|
+
try {
|
|
86
|
+
message = JSON.parse(String(data))
|
|
87
|
+
} catch {
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
if (message?.type === 'take') {
|
|
91
|
+
if (control.holds(holderId)) return
|
|
92
|
+
control.take({
|
|
93
|
+
id: holderId,
|
|
94
|
+
sessionId,
|
|
95
|
+
help,
|
|
96
|
+
end: (reason) => {
|
|
97
|
+
tickets.revokeHolder(holderId, 'control')
|
|
98
|
+
// Asked for by this view ('released'), or the view is gone: no notice needed.
|
|
99
|
+
if (reason !== 'released' && reason !== 'disconnected') send({ type: 'ended', reason })
|
|
100
|
+
if (!ended) grant('watch')
|
|
101
|
+
},
|
|
102
|
+
})
|
|
103
|
+
grant('control')
|
|
104
|
+
} else if (message?.type === 'give') {
|
|
105
|
+
control.release(holderId, 'released')
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const end = (reason) => {
|
|
110
|
+
if (ended) return
|
|
111
|
+
ended = true
|
|
112
|
+
clearTimeout(graceTimer)
|
|
113
|
+
views.delete(resume)
|
|
114
|
+
unsubscribe()
|
|
115
|
+
control.release(holderId, reason)
|
|
116
|
+
tickets.revokeHolder(holderId)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const unsubscribe = control.subscribe(sendState)
|
|
120
|
+
|
|
121
|
+
const view = {
|
|
122
|
+
holderId,
|
|
123
|
+
resume,
|
|
124
|
+
/** Bind a (new) socket to this view. */
|
|
125
|
+
attach(next) {
|
|
126
|
+
clearTimeout(graceTimer)
|
|
127
|
+
if (socket !== undefined && socket !== next) socket.terminate()
|
|
128
|
+
socket = next
|
|
129
|
+
next.on('message', onMessage)
|
|
130
|
+
keepAlive(next, { ...keepalive, beat: () => send({ type: 'heartbeat' }) })
|
|
131
|
+
next.on('close', (code) => {
|
|
132
|
+
if (socket !== next || ended) return
|
|
133
|
+
socket = undefined
|
|
134
|
+
// On purpose: the page closed the view. Otherwise wait for it to come back.
|
|
135
|
+
if (code === 1000) end('disconnected')
|
|
136
|
+
else graceTimer = setTimeout(() => end('disconnected'), graceMs)
|
|
137
|
+
})
|
|
138
|
+
send({ type: 'hello', resume })
|
|
139
|
+
sendState(control.state())
|
|
140
|
+
if (current !== undefined) send(current)
|
|
141
|
+
},
|
|
142
|
+
/** Close the view from the server side (plugin stopping). */
|
|
143
|
+
close() {
|
|
144
|
+
end('stopped')
|
|
145
|
+
if (socket !== undefined && socket.readyState === socket.OPEN) socket.close(CLOSE_STOPPED, 'stopped')
|
|
146
|
+
},
|
|
147
|
+
start() {
|
|
148
|
+
grant('watch')
|
|
149
|
+
},
|
|
150
|
+
}
|
|
151
|
+
return view
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
/**
|
|
156
|
+
* Serve one status socket: resume its view or open a new one.
|
|
157
|
+
* @param {import('ws').WebSocket} socket
|
|
158
|
+
* @param {{ sessionId: string | null, resume: string | null, help?: boolean }} request - `help`: opened from the agent's help link.
|
|
159
|
+
*/
|
|
160
|
+
attach(socket, { sessionId, resume, help = false }) {
|
|
161
|
+
const resumed = resume === null ? undefined : views.get(resume)
|
|
162
|
+
if (resumed !== undefined) {
|
|
163
|
+
resumed.attach(socket)
|
|
164
|
+
return resumed
|
|
165
|
+
}
|
|
166
|
+
const view = createView(sessionId, help)
|
|
167
|
+
views.set(view.resume, view)
|
|
168
|
+
view.attach(socket)
|
|
169
|
+
view.start()
|
|
170
|
+
return view
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
/** Close every view (plugin stopping). */
|
|
174
|
+
closeAll() {
|
|
175
|
+
for (const view of [...views.values()]) view.close()
|
|
176
|
+
},
|
|
177
|
+
}
|
|
178
|
+
}
|
package/src/tickets.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The credentials of the relayed viewer, in three layers:
|
|
3
|
+
*
|
|
4
|
+
* - Viewer tickets: the daemon's own scoped tickets, one per mode, minted
|
|
5
|
+
* by the relay and kept server-side. They never reach the browser.
|
|
6
|
+
* - Relay tickets: random tokens the browser's viewer sends instead
|
|
7
|
+
* (`x-cua-env-authorization: Bearer <relay ticket>`). Each names a mode
|
|
8
|
+
* (`watch` or `control`), the status socket it belongs to, and the DSH
|
|
9
|
+
* session the view was opened from. The relay swaps it for the viewer
|
|
10
|
+
* ticket of its mode. A control relay ticket lives only while its status
|
|
11
|
+
* socket holds control; a watch one, while its status socket is open.
|
|
12
|
+
* - Media tickets: minted by the daemon for each media session the viewer
|
|
13
|
+
* opens. The relay notes which relay ticket opened each one, so a media
|
|
14
|
+
* socket is judged by the mode that opened it.
|
|
15
|
+
*/
|
|
16
|
+
import { randomBytes } from 'node:crypto'
|
|
17
|
+
|
|
18
|
+
/** Modes and the daemon scope each one's viewer ticket gets. */
|
|
19
|
+
export const MODES = Object.freeze(['watch', 'control'])
|
|
20
|
+
|
|
21
|
+
/** Refresh a viewer ticket when it has less than this long left. */
|
|
22
|
+
const REFRESH_MARGIN_MS = 10 * 60 * 1000
|
|
23
|
+
/** Lifetime asked for each viewer ticket. */
|
|
24
|
+
const VIEWER_TICKET_SECONDS = 60 * 60
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {object} options
|
|
28
|
+
* @param {{ createViewerTicket: Function }} options.spacesd
|
|
29
|
+
* @param {{ clipboard: boolean, filesRoot: string, microphone: boolean }} options.features - What control mode may use.
|
|
30
|
+
* @param {() => number} [options.now]
|
|
31
|
+
*/
|
|
32
|
+
export function createTicketBook({ spacesd, features, now = Date.now }) {
|
|
33
|
+
const viewer = new Map()
|
|
34
|
+
const relay = new Map()
|
|
35
|
+
const media = new Map()
|
|
36
|
+
const revokeListeners = new Set()
|
|
37
|
+
|
|
38
|
+
/** The daemon scope of each mode: watching gets the stream and nothing else. */
|
|
39
|
+
const scope = mode => mode === 'control'
|
|
40
|
+
? { policy: 'allow_activation', clipboard: features.clipboard, filesRoot: features.filesRoot, audioUplink: features.microphone }
|
|
41
|
+
: { policy: 'view_only', clipboard: false, filesRoot: '', audioUplink: false }
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
/**
|
|
45
|
+
* The daemon's viewer ticket for a mode, minted or refreshed as needed.
|
|
46
|
+
* @param {'watch' | 'control'} mode
|
|
47
|
+
* @returns {Promise<{ ticket: string, expiresAt: number, hints: string }>}
|
|
48
|
+
*/
|
|
49
|
+
async viewerTicket(mode) {
|
|
50
|
+
const cached = viewer.get(mode)
|
|
51
|
+
if (cached !== undefined) {
|
|
52
|
+
const current = await cached
|
|
53
|
+
if (current.expiresAt - now() > REFRESH_MARGIN_MS) return current
|
|
54
|
+
if (viewer.get(mode) === cached) viewer.delete(mode)
|
|
55
|
+
}
|
|
56
|
+
if (!viewer.has(mode)) {
|
|
57
|
+
const minting = spacesd.createViewerTicket({ ...scope(mode), ttlSeconds: VIEWER_TICKET_SECONDS, name: 'Owner' })
|
|
58
|
+
viewer.set(mode, minting)
|
|
59
|
+
minting.catch(() => { if (viewer.get(mode) === minting) viewer.delete(mode) })
|
|
60
|
+
}
|
|
61
|
+
return viewer.get(mode)
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
/** Forget a mode's viewer ticket (the daemon said it is no longer valid). */
|
|
65
|
+
invalidate(mode) {
|
|
66
|
+
viewer.delete(mode)
|
|
67
|
+
},
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Issue a relay ticket.
|
|
71
|
+
* @param {{ mode: 'watch' | 'control', holderId: string, sessionId: string | null }} grant
|
|
72
|
+
* @returns {string}
|
|
73
|
+
*/
|
|
74
|
+
issue(grant) {
|
|
75
|
+
const token = randomBytes(32).toString('base64url')
|
|
76
|
+
relay.set(token, { ...grant })
|
|
77
|
+
return token
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
/** The grant of a relay ticket, or undefined when unknown or revoked. */
|
|
81
|
+
lookup(token) {
|
|
82
|
+
return typeof token === 'string' ? relay.get(token) : undefined
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
/** Revoke one relay ticket and every media socket it opened. */
|
|
86
|
+
revoke(token) {
|
|
87
|
+
if (!relay.delete(token)) return
|
|
88
|
+
for (const [ticket, binding] of media) if (binding.relayToken === token) media.delete(ticket)
|
|
89
|
+
for (const listener of revokeListeners) listener(token)
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
/** Revoke every relay ticket of one status socket, or only those of one mode. */
|
|
93
|
+
revokeHolder(holderId, mode) {
|
|
94
|
+
for (const [token, grant] of [...relay]) {
|
|
95
|
+
if (grant.holderId === holderId && (mode === undefined || grant.mode === mode)) this.revoke(token)
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
/** Note that a relay ticket opened a media session. */
|
|
100
|
+
bindMedia(mediaTicket, relayToken, sessionId) {
|
|
101
|
+
if (relay.has(relayToken)) media.set(mediaTicket, { relayToken, sessionId })
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Which relay ticket opened a media ticket's session, with its grant.
|
|
106
|
+
* @returns {{ relayToken: string, sessionId: string, grant: object } | undefined}
|
|
107
|
+
*/
|
|
108
|
+
media(mediaTicket) {
|
|
109
|
+
const binding = media.get(mediaTicket)
|
|
110
|
+
const grant = binding === undefined ? undefined : relay.get(binding.relayToken)
|
|
111
|
+
return grant === undefined ? undefined : { ...binding, grant }
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
/** Follow revocations (to close the media sockets of a revoked ticket). */
|
|
115
|
+
onRevoke(listener) {
|
|
116
|
+
revokeListeners.add(listener)
|
|
117
|
+
return () => revokeListeners.delete(listener)
|
|
118
|
+
},
|
|
119
|
+
}
|
|
120
|
+
}
|