-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol.ts
More file actions
637 lines (578 loc) · 19.2 KB
/
Copy pathprotocol.ts
File metadata and controls
637 lines (578 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
export const PROTOCOL_VERSION = 1;
export const MAX_TEXT_LENGTH = 2_000;
export const MAX_POINTER_DELTA = 500;
export const MAX_SCROLL_DELTA = 50;
export const MAX_SHORTCUT_KEYS = 6;
export const MAX_ERROR_MESSAGE_LENGTH = 300;
export type ProtocolErrorCode =
| 'invalid_json'
| 'invalid_message'
| 'invalid_version'
| 'invalid_type'
| 'invalid_payload'
| 'invalid_auth'
| 'command_failed';
export type MouseButton = 'left' | 'right' | 'middle';
export type KeyboardKey =
| 'Backspace'
| 'Delete'
| 'Enter'
| 'Escape'
| 'Space'
| 'Tab'
| 'ArrowUp'
| 'ArrowDown'
| 'ArrowLeft'
| 'ArrowRight'
| 'Home'
| 'End'
| 'PageUp'
| 'PageDown'
| 'F1'
| 'F2'
| 'F3'
| 'F4'
| 'F5'
| 'F6'
| 'F7'
| 'F8'
| 'F9'
| 'F10'
| 'F11'
| 'F12';
export type ShortcutKey =
| KeyboardKey
| 'Ctrl'
| 'Alt'
| 'Shift'
| 'Meta'
| 'A'
| 'C'
| 'V'
| 'X'
| 'Z'
| 'Y';
export type MediaAction = 'playPause' | 'nextTrack' | 'previousTrack' | 'volumeUp' | 'volumeDown' | 'mute';
export type WindowControlAction =
| 'switchNext'
| 'switchPrevious'
| 'taskView'
| 'showDesktop'
| 'closeFocused'
| 'minimizeFocused'
| 'maximizeFocused';
export type CommandResponseMode = 'ack' | 'none';
export const NO_ACK_CONTROL_COMMAND_TYPES = [
'mouse.move',
'mouse.click',
'mouse.doubleClick',
'mouse.rightClick',
'mouse.scroll',
'mouse.dragStart',
'mouse.dragEnd',
'keyboard.key',
'keyboard.shortcut',
'keyboard.typeText',
'media.control',
'window.control'
] as const;
export type NoAckControlCommandType = (typeof NO_ACK_CONTROL_COMMAND_TYPES)[number];
export type PointerMovementProfile = {
displayId: string;
scaleFactor: number;
bounds: {
x: number;
y: number;
width: number;
height: number;
};
maxDelta: number;
recommendedDeltas: {
small: number;
medium: number;
large: number;
};
capabilities: {
noAckMouseMove: boolean;
noAckCommands: NoAckControlCommandType[];
};
};
export interface BaseRequestEnvelope<TType extends string, TPayload> {
version: typeof PROTOCOL_VERSION;
id: string;
deviceId: string;
timestamp: number;
type: TType;
payload: TPayload;
auth: string;
responseMode?: CommandResponseMode;
}
export type PairingApprovalRequest = {
version: typeof PROTOCOL_VERSION;
id: string;
type: 'pairing.request';
payload: {
deviceId: string;
deviceName: string;
desktopId: string;
requestNonce: string;
};
};
export type PairingRequest = PairingApprovalRequest;
export type MouseMoveCommand = BaseRequestEnvelope<'mouse.move', { dx: number; dy: number }>;
export type MouseClickCommand = BaseRequestEnvelope<'mouse.click', { button: MouseButton }>;
export type MouseDoubleClickCommand = BaseRequestEnvelope<'mouse.doubleClick', { button: MouseButton }>;
export type MouseRightClickCommand = BaseRequestEnvelope<'mouse.rightClick', Record<string, never>>;
export type MouseScrollCommand = BaseRequestEnvelope<'mouse.scroll', { dx: number; dy: number }>;
export type MouseDragStartCommand = BaseRequestEnvelope<'mouse.dragStart', { button: MouseButton }>;
export type MouseDragEndCommand = BaseRequestEnvelope<'mouse.dragEnd', { button: MouseButton }>;
export type KeyboardKeyCommand = BaseRequestEnvelope<'keyboard.key', { key: KeyboardKey }>;
export type KeyboardShortcutCommand = BaseRequestEnvelope<'keyboard.shortcut', { keys: ShortcutKey[] }>;
export type KeyboardTypeTextCommand = BaseRequestEnvelope<'keyboard.typeText', { text: string }>;
export type MediaControlCommand = BaseRequestEnvelope<'media.control', { action: MediaAction }>;
export type WindowControlCommand = BaseRequestEnvelope<'window.control', { action: WindowControlAction }>;
export type PingCommand = BaseRequestEnvelope<'connection.ping', Record<string, never>>;
export type DisconnectingCommand = BaseRequestEnvelope<'connection.disconnecting', Record<string, never>>;
export type PointerProfileCommand = BaseRequestEnvelope<'pointer.profile', Record<string, never>>;
export type CommandRequest =
| MouseMoveCommand
| MouseClickCommand
| MouseDoubleClickCommand
| MouseRightClickCommand
| MouseScrollCommand
| MouseDragStartCommand
| MouseDragEndCommand
| KeyboardKeyCommand
| KeyboardShortcutCommand
| KeyboardTypeTextCommand
| MediaControlCommand
| WindowControlCommand
| PointerProfileCommand
| DisconnectingCommand
| PingCommand;
export type ProtocolRequest = CommandRequest | PairingRequest;
export type AckResponse = {
version: typeof PROTOCOL_VERSION;
id: string;
type: 'ack';
ok: true;
error: null;
};
export type ErrorResponse = {
version: typeof PROTOCOL_VERSION;
id: string | null;
type: 'error';
ok: false;
error: {
code: ProtocolErrorCode;
message: string;
detail?: string;
};
};
export type PairingCompleteResponse = {
version: typeof PROTOCOL_VERSION;
id: string;
type: 'pairing.complete';
ok: true;
payload: {
desktopId: string;
deviceId: string;
token: string;
};
error: null;
};
export type PointerProfileResponse = {
version: typeof PROTOCOL_VERSION;
id: string;
type: 'pointer.profile';
ok: true;
payload: PointerMovementProfile;
error: null;
};
export type ProtocolResponse = AckResponse | ErrorResponse | PairingCompleteResponse | PointerProfileResponse;
export type ValidationResult<T> =
| { ok: true; value: T }
| { ok: false; error: ProtocolErrorCode; message: string };
const commandTypes = new Set<CommandRequest['type']>([
'mouse.move',
'mouse.click',
'mouse.doubleClick',
'mouse.rightClick',
'mouse.scroll',
'mouse.dragStart',
'mouse.dragEnd',
'keyboard.key',
'keyboard.shortcut',
'keyboard.typeText',
'media.control',
'window.control',
'pointer.profile',
'connection.ping',
'connection.disconnecting'
]);
const pairingTypes = new Set<PairingRequest['type']>(['pairing.request']);
const commandResponseModes = new Set<CommandResponseMode>(['ack', 'none']);
const noAckControlCommandTypes = new Set<CommandRequest['type']>(NO_ACK_CONTROL_COMMAND_TYPES);
const mouseButtons = new Set<MouseButton>(['left', 'right', 'middle']);
const keyboardKeys = new Set<KeyboardKey>([
'Backspace',
'Delete',
'Enter',
'Escape',
'Space',
'Tab',
'ArrowUp',
'ArrowDown',
'ArrowLeft',
'ArrowRight',
'Home',
'End',
'PageUp',
'PageDown',
'F1',
'F2',
'F3',
'F4',
'F5',
'F6',
'F7',
'F8',
'F9',
'F10',
'F11',
'F12'
]);
const shortcutKeys = new Set<ShortcutKey>([
...keyboardKeys,
'Ctrl',
'Alt',
'Shift',
'Meta',
'A',
'C',
'V',
'X',
'Z',
'Y'
]);
const mediaActions = new Set<MediaAction>([
'playPause',
'nextTrack',
'previousTrack',
'volumeUp',
'volumeDown',
'mute'
]);
const windowControlActions = new Set<WindowControlAction>([
'switchNext',
'switchPrevious',
'taskView',
'showDesktop',
'closeFocused',
'minimizeFocused',
'maximizeFocused'
]);
export function parseProtocolRequest(raw: string): ValidationResult<ProtocolRequest> {
try {
return validateProtocolRequest(JSON.parse(raw));
} catch {
return invalid('invalid_json', 'Message must be valid JSON.');
}
}
export function validateProtocolRequest(value: unknown): ValidationResult<ProtocolRequest> {
if (!isRecord(value)) return invalid('invalid_message', 'Message must be an object.');
if (value.version !== PROTOCOL_VERSION) return invalid('invalid_version', 'Unsupported protocol version.');
if (!isNonEmptyString(value.id)) return invalid('invalid_message', 'Message id is required.');
if (!isNonEmptyString(value.type)) return invalid('invalid_type', 'Message type is required.');
if (!('payload' in value) || !isRecord(value.payload)) {
return invalid('invalid_payload', 'Payload must be an object.');
}
if (commandTypes.has(value.type as CommandRequest['type'])) {
return validateCommandRequest(value);
}
if (pairingTypes.has(value.type as PairingRequest['type'])) {
return validatePairingRequest(value);
}
return invalid('invalid_type', 'Unsupported message type.');
}
export function validateProtocolResponse(value: unknown): ValidationResult<ProtocolResponse> {
if (!isRecord(value)) return invalid('invalid_message', 'Response must be an object.');
if (value.version !== PROTOCOL_VERSION) return invalid('invalid_version', 'Unsupported protocol version.');
if (value.type === 'ack') {
if (!isNonEmptyString(value.id)) return invalid('invalid_message', 'Ack id is required.');
if (value.ok !== true || value.error !== null) return invalid('invalid_message', 'Ack response is malformed.');
return { ok: true, value: value as AckResponse };
}
if (value.type === 'error') {
if (!(value.id === null || isNonEmptyString(value.id))) {
return invalid('invalid_message', 'Error response id must be a string or null.');
}
if (value.ok !== false || !isRecord(value.error)) {
return invalid('invalid_message', 'Error response is malformed.');
}
if (!isNonEmptyString(value.error.code) || !isNonEmptyString(value.error.message)) {
return invalid('invalid_message', 'Error code and message are required.');
}
if (value.error.message.length > MAX_ERROR_MESSAGE_LENGTH) {
return invalid('invalid_message', 'Error message is too long.');
}
return { ok: true, value: value as ErrorResponse };
}
if (value.type === 'pairing.complete') {
if (!isNonEmptyString(value.id)) return invalid('invalid_message', 'Pairing response id is required.');
if (value.ok !== true || value.error !== null || !isRecord(value.payload)) {
return invalid('invalid_message', 'Pairing response is malformed.');
}
if (
!isNonEmptyString(value.payload.desktopId) ||
!isNonEmptyString(value.payload.deviceId) ||
!isNonEmptyString(value.payload.token)
) {
return invalid('invalid_payload', 'Pairing response payload is invalid.');
}
return { ok: true, value: value as PairingCompleteResponse };
}
if (value.type === 'pointer.profile') {
if (!isNonEmptyString(value.id)) return invalid('invalid_message', 'Pointer profile response id is required.');
if (value.ok !== true || value.error !== null || !isRecord(value.payload)) {
return invalid('invalid_message', 'Pointer profile response is malformed.');
}
return validatePointerProfilePayload(value.payload).ok
? { ok: true, value: value as PointerProfileResponse }
: invalid('invalid_payload', 'Pointer profile payload is invalid.');
}
return invalid('invalid_type', 'Unsupported response type.');
}
export function createAckResponse(id: string): AckResponse {
return {
version: PROTOCOL_VERSION,
id,
type: 'ack',
ok: true,
error: null
};
}
export function createErrorResponse(
id: string | null,
code: ProtocolErrorCode,
message: string,
detail?: string
): ErrorResponse {
return {
version: PROTOCOL_VERSION,
id,
type: 'error',
ok: false,
error: {
code,
message: message.slice(0, MAX_ERROR_MESSAGE_LENGTH),
...(detail ? { detail } : {})
}
};
}
export function createPairingCompleteResponse(
id: string,
payload: PairingCompleteResponse['payload']
): PairingCompleteResponse {
return {
version: PROTOCOL_VERSION,
id,
type: 'pairing.complete',
ok: true,
payload,
error: null
};
}
export function createPointerProfileResponse(id: string, payload: PointerMovementProfile): PointerProfileResponse {
return {
version: PROTOCOL_VERSION,
id,
type: 'pointer.profile',
ok: true,
payload,
error: null
};
}
function validateCommandRequest(value: Record<string, unknown>): ValidationResult<CommandRequest> {
if (!isNonEmptyString(value.deviceId)) return invalid('invalid_message', 'Device id is required.');
if (!isFiniteNumber(value.timestamp)) return invalid('invalid_message', 'Timestamp is required.');
if (!isNonEmptyString(value.auth)) return invalid('invalid_auth', 'Auth proof is required.');
if (!isValidResponseMode(value.type as CommandRequest['type'], value.responseMode)) {
return invalid('invalid_payload', 'Response mode is invalid.');
}
const payload = value.payload as Record<string, unknown>;
const payloadOk = validateCommandPayload(value.type as CommandRequest['type'], payload);
if (!payloadOk.ok) return payloadOk;
return { ok: true, value: value as unknown as CommandRequest };
}
function validatePairingRequest(value: Record<string, unknown>): ValidationResult<PairingRequest> {
const payload = value.payload as Record<string, unknown>;
if (!isNonEmptyString(payload.deviceId)) return invalid('invalid_payload', 'Pairing device id is required.');
if (!isNonEmptyString(payload.deviceName)) return invalid('invalid_payload', 'Pairing device name is required.');
if (!isNonEmptyString(payload.desktopId)) return invalid('invalid_payload', 'Desktop id is required.');
if (!isNonEmptyString(payload.requestNonce)) return invalid('invalid_payload', 'Pairing request nonce is required.');
return { ok: true, value: value as PairingApprovalRequest };
}
function validateCommandPayload(
type: CommandRequest['type'],
payload: Record<string, unknown>
): ValidationResult<unknown> {
switch (type) {
case 'mouse.move':
return validateBoundedNumbers(payload, ['dx', 'dy'], MAX_POINTER_DELTA);
case 'mouse.scroll':
return validateBoundedNumbers(payload, ['dx', 'dy'], MAX_SCROLL_DELTA);
case 'mouse.click':
case 'mouse.doubleClick':
case 'mouse.dragStart':
case 'mouse.dragEnd':
return mouseButtons.has(payload.button as MouseButton)
? valid()
: invalid('invalid_payload', 'Mouse button is invalid.');
case 'mouse.rightClick':
case 'connection.ping':
case 'connection.disconnecting':
return Object.keys(payload).length === 0
? valid()
: invalid('invalid_payload', 'Payload must be empty.');
case 'keyboard.key':
return keyboardKeys.has(payload.key as KeyboardKey)
? valid()
: invalid('invalid_payload', 'Keyboard key is invalid.');
case 'keyboard.shortcut':
return validateShortcutPayload(payload);
case 'keyboard.typeText':
return isSafeTextPayload(payload.text)
? valid()
: invalid('invalid_payload', 'Text payload is invalid.');
case 'media.control':
return mediaActions.has(payload.action as MediaAction)
? valid()
: invalid('invalid_payload', 'Media action is invalid.');
case 'window.control':
return windowControlActions.has(payload.action as WindowControlAction)
? valid()
: invalid('invalid_payload', 'Window control action is invalid.');
case 'pointer.profile':
return Object.keys(payload).length === 0
? valid()
: invalid('invalid_payload', 'Payload must be empty.');
}
}
function validatePointerProfilePayload(payload: Record<string, unknown>): ValidationResult<unknown> {
if (!isNonEmptyString(payload.displayId)) return invalid('invalid_payload', 'Display id is required.');
if (!isPositiveFiniteNumber(payload.scaleFactor)) return invalid('invalid_payload', 'Scale factor is invalid.');
if (!isRecord(payload.bounds) || !isFiniteBounds(payload.bounds)) {
return invalid('invalid_payload', 'Bounds are invalid.');
}
if (!isPositiveFiniteNumber(payload.maxDelta) || payload.maxDelta > MAX_POINTER_DELTA) {
return invalid('invalid_payload', 'Max delta is invalid.');
}
if (!isRecord(payload.recommendedDeltas)) {
return invalid('invalid_payload', 'Recommended deltas are required.');
}
for (const key of ['small', 'medium', 'large']) {
const value = payload.recommendedDeltas[key];
if (!isPositiveFiniteNumber(value) || value > MAX_POINTER_DELTA) {
return invalid('invalid_payload', 'Recommended delta is invalid.');
}
}
if ('capabilities' in payload) {
if (!isRecord(payload.capabilities)) {
return invalid('invalid_payload', 'Pointer capabilities are invalid.');
}
if (
'noAckMouseMove' in payload.capabilities &&
typeof payload.capabilities.noAckMouseMove !== 'boolean'
) {
return invalid('invalid_payload', 'No-ack mouse move capability is invalid.');
}
if ('noAckCommands' in payload.capabilities) {
if (!Array.isArray(payload.capabilities.noAckCommands)) {
return invalid('invalid_payload', 'No-ack commands capability is invalid.');
}
if (
!payload.capabilities.noAckCommands.every(
(commandType) => typeof commandType === 'string' && noAckControlCommandTypes.has(commandType as CommandRequest['type'])
)
) {
return invalid('invalid_payload', 'No-ack commands capability is invalid.');
}
}
}
return valid();
}
function isValidResponseMode(type: CommandRequest['type'], responseMode: unknown): boolean {
if (responseMode === undefined) return true;
if (!commandResponseModes.has(responseMode as CommandResponseMode)) return false;
return responseMode !== 'none' || noAckControlCommandTypes.has(type);
}
function isFiniteBounds(value: Record<string, unknown>): boolean {
return (
isFiniteNumber(value.x) &&
isFiniteNumber(value.y) &&
isPositiveFiniteNumber(value.width) &&
isPositiveFiniteNumber(value.height)
);
}
function validateShortcutPayload(payload: Record<string, unknown>): ValidationResult<unknown> {
if (!Array.isArray(payload.keys)) {
return invalid('invalid_payload', 'Shortcut keys must be an array.');
}
if (payload.keys.length === 0 || payload.keys.length > MAX_SHORTCUT_KEYS) {
return invalid('invalid_payload', 'Shortcut key count is invalid.');
}
if (!payload.keys.every((key) => shortcutKeys.has(key as ShortcutKey))) {
return invalid('invalid_payload', 'Shortcut contains an invalid key.');
}
return valid();
}
function validateBoundedNumbers(
payload: Record<string, unknown>,
keys: string[],
maxAbsValue: number
): ValidationResult<unknown> {
for (const key of keys) {
const value = payload[key];
if (!isFiniteNumber(value) || Math.abs(value) > maxAbsValue) {
return invalid('invalid_payload', `${key} is invalid.`);
}
}
return valid();
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function isSafeTextPayload(value: unknown): value is string {
return isString(value) && value.length <= MAX_TEXT_LENGTH && !containsDisallowedControlCharacter(value);
}
function containsDisallowedControlCharacter(value: string): boolean {
for (let index = 0; index < value.length; index += 1) {
const code = value.charCodeAt(index);
if (code >= 0x00 && code <= 0x1f && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
return true;
}
if (code >= 0x7f && code <= 0x9f) {
return true;
}
}
return false;
}
function isNonEmptyString(value: unknown): value is string {
return isString(value) && value.length > 0;
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function isPositiveFiniteNumber(value: unknown): value is number {
return isFiniteNumber(value) && value > 0;
}
function valid(): ValidationResult<unknown> {
return { ok: true, value: undefined };
}
function invalid(error: ProtocolErrorCode, message: string): ValidationResult<never> {
return { ok: false, error, message };
}