@scrypted/server 0.147.0 → 0.148.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.
Files changed (47) hide show
  1. package/dist/cluster/cluster-setup.js +16 -17
  2. package/dist/cluster/cluster-setup.js.map +1 -1
  3. package/dist/http-interfaces.js +16 -2
  4. package/dist/http-interfaces.js.map +1 -1
  5. package/dist/plugin/media.d.ts +5 -39
  6. package/dist/plugin/media.js +73 -109
  7. package/dist/plugin/media.js.map +1 -1
  8. package/dist/plugin/plugin-console.d.ts +2 -0
  9. package/dist/plugin/plugin-console.js +10 -0
  10. package/dist/plugin/plugin-console.js.map +1 -1
  11. package/dist/plugin/plugin-host.js +7 -3
  12. package/dist/plugin/plugin-host.js.map +1 -1
  13. package/dist/plugin/plugin-remote-worker.js.map +1 -1
  14. package/dist/plugin/plugin-remote.d.ts +15 -0
  15. package/dist/plugin/plugin-remote.js +36 -39
  16. package/dist/plugin/plugin-remote.js.map +1 -1
  17. package/dist/rpc-serializer.js +4 -0
  18. package/dist/rpc-serializer.js.map +1 -1
  19. package/dist/rpc.d.ts +2 -0
  20. package/dist/rpc.js +29 -1
  21. package/dist/rpc.js.map +1 -1
  22. package/dist/scrypted-cluster-main.js +20 -0
  23. package/dist/scrypted-cluster-main.js.map +1 -1
  24. package/dist/scrypted-server-main.js +31 -15
  25. package/dist/scrypted-server-main.js.map +1 -1
  26. package/dist/services/cluster-fork.js +3 -3
  27. package/dist/services/cluster-fork.js.map +1 -1
  28. package/dist/services/plugin.d.ts +1 -0
  29. package/dist/services/plugin.js +5 -0
  30. package/dist/services/plugin.js.map +1 -1
  31. package/package.json +1 -1
  32. package/python/cluster_setup.py +20 -20
  33. package/python/plugin_remote.py +0 -1
  34. package/python/rpc_reader.py +28 -8
  35. package/src/cluster/cluster-setup.ts +16 -17
  36. package/src/http-interfaces.ts +16 -2
  37. package/src/plugin/media.ts +95 -120
  38. package/src/plugin/plugin-console.ts +11 -0
  39. package/src/plugin/plugin-host.ts +14 -4
  40. package/src/plugin/plugin-remote-worker.ts +1 -1
  41. package/src/plugin/plugin-remote.ts +43 -41
  42. package/src/rpc-serializer.ts +4 -0
  43. package/src/rpc.ts +31 -1
  44. package/src/scrypted-cluster-main.ts +24 -0
  45. package/src/scrypted-server-main.ts +34 -16
  46. package/src/services/cluster-fork.ts +3 -3
  47. package/src/services/plugin.ts +6 -0
@@ -2,13 +2,48 @@ import { EventDetails, MediaManager, ScryptedInterface, ScryptedInterfacePropert
2
2
  import { RpcPeer, RPCResultError } from '../rpc';
3
3
  import { BufferSerializer } from '../rpc-buffer-serializer';
4
4
  import { AccessControls } from './acl';
5
+ import { ClusterManagerImpl } from './cluster';
5
6
  import { DeviceManagerImpl, StorageImpl } from './device';
6
7
  import { EndpointManagerImpl } from './endpoint';
7
8
  import { PluginAPI, PluginHostInfo, PluginRemote, PluginRemoteLoadZipOptions, PluginZipAPI } from './plugin-api';
8
9
  import { createWebSocketClass, WebSocketConnectCallbacks, WebSocketConnection, WebSocketMethods, WebSocketSerializer } from './plugin-remote-websocket';
9
10
  import { SystemManagerImpl } from './system';
10
- import { ClusterManagerImpl } from './cluster';
11
11
 
12
+ function getAccessControlDeviceState(accessControls: AccessControls | undefined, getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } }, id: string, state?: { [property: string]: SystemDeviceState }) {
13
+ state = state || getSystemState()[id];
14
+ if (accessControls && state) {
15
+ state = Object.assign({}, state);
16
+ for (const property of Object.keys(state)) {
17
+ if (accessControls.shouldRejectProperty(id, property))
18
+ delete state[property];
19
+ }
20
+ let interfaces: ScryptedInterface[] = state.interfaces?.value;
21
+ if (interfaces) {
22
+ interfaces = interfaces.filter(scryptedInterface => !accessControls.shouldRejectInterface(id, scryptedInterface));
23
+ state.interfaces = {
24
+ value: interfaces,
25
+ }
26
+ }
27
+ }
28
+ return state;
29
+ }
30
+
31
+
32
+ export function getAccessControlSystemState(accessControls: AccessControls | undefined, getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } }) {
33
+ let state = getSystemState();
34
+ if (accessControls) {
35
+ state = Object.assign({}, state);
36
+ for (const id of Object.keys(state)) {
37
+ if (accessControls.shouldRejectDevice(id)) {
38
+ delete state[id];
39
+ continue;
40
+ }
41
+ state[id] = getAccessControlDeviceState(accessControls, getSystemState, id, state[id]!)!;
42
+ }
43
+ }
44
+
45
+ return state;
46
+ }
12
47
 
13
48
  export async function setupPluginRemote(peer: RpcPeer, api: PluginAPI, pluginId: string, hostInfo: PluginHostInfo, getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } }): Promise<PluginRemote> {
14
49
  try {
@@ -23,42 +58,8 @@ export async function setupPluginRemote(peer: RpcPeer, api: PluginAPI, pluginId:
23
58
 
24
59
  const accessControls: AccessControls = peer.tags.acl;
25
60
 
26
- const getAccessControlDeviceState = (id: string, state?: { [property: string]: SystemDeviceState }) => {
27
- state = state || getSystemState()[id];
28
- if (accessControls && state) {
29
- state = Object.assign({}, state);
30
- for (const property of Object.keys(state)) {
31
- if (accessControls.shouldRejectProperty(id, property))
32
- delete state[property];
33
- }
34
- let interfaces: ScryptedInterface[] = state.interfaces?.value;
35
- if (interfaces) {
36
- interfaces = interfaces.filter(scryptedInterface => !accessControls.shouldRejectInterface(id, scryptedInterface));
37
- state.interfaces = {
38
- value: interfaces,
39
- }
40
- }
41
- }
42
- return state;
43
- }
44
61
 
45
- const getAccessControlSystemState = () => {
46
- let state = getSystemState();
47
- if (accessControls) {
48
- state = Object.assign({}, state);
49
- for (const id of Object.keys(state)) {
50
- if (accessControls.shouldRejectDevice(id)) {
51
- delete state[id];
52
- continue;
53
- }
54
- state[id] = getAccessControlDeviceState(id, state[id]!)!;
55
- }
56
- }
57
-
58
- return state;
59
- }
60
-
61
- await remote.setSystemState(getAccessControlSystemState());
62
+ await remote.setSystemState(getAccessControlSystemState(accessControls, getSystemState));
62
63
  api.listen((id, eventDetails, eventData) => {
63
64
  if (accessControls?.shouldRejectEvent(eventDetails.property === ScryptedInterfaceProperty.id ? eventData : id, eventDetails))
64
65
  return;
@@ -71,7 +72,7 @@ export async function setupPluginRemote(peer: RpcPeer, api: PluginAPI, pluginId:
71
72
  }
72
73
  else {
73
74
  // a change on anything else is a descriptor update
74
- remote.updateDeviceState(id, getAccessControlDeviceState(id)!);
75
+ remote.updateDeviceState(id, getAccessControlDeviceState(accessControls, getSystemState, id)!);
75
76
  }
76
77
  return;
77
78
  }
@@ -97,6 +98,11 @@ export interface WebSocketCustomHandler {
97
98
  }
98
99
 
99
100
  export interface PluginRemoteAttachOptions {
101
+ /**
102
+ * Injected by the host/plugin worker to create the media manager implementation.
103
+ * This keeps the media manager and its Node-only dependencies out of the web
104
+ * client bundle, where attachPluginRemote is also used.
105
+ */
100
106
  createMediaManager?: (systemManager: SystemManager, deviceManager: DeviceManagerImpl) => Promise<MediaManager>;
101
107
  getServicePort?: (name: string, ...args: any[]) => Promise<[number, string]>;
102
108
  getDeviceConsole?: (nativeId?: ScryptedNativeId) => Console;
@@ -144,11 +150,7 @@ export function attachPluginRemote(peer: RpcPeer, options?: PluginRemoteAttachOp
144
150
  const endpointManager = new EndpointManagerImpl();
145
151
  const clusterManager = new ClusterManagerImpl(undefined, api, undefined!);
146
152
  const hostMediaManager = await api.getMediaManager();
147
- if (!hostMediaManager) {
148
- peer.params['createMediaManager'] = async () => createMediaManager!(systemManager, deviceManager);
149
- }
150
153
  const mediaManager = hostMediaManager || await createMediaManager!(systemManager, deviceManager);
151
- peer.params['mediaManager'] = mediaManager;
152
154
 
153
155
  systemManager.api = api;
154
156
  deviceManager.api = api;
@@ -19,6 +19,10 @@ export function createDuplexRpcPeer(selfName: string, peerName: string, readable
19
19
  readable.on('data', data => serializer.onData(data));
20
20
  readable.on('close', serializer.onDisconnected);
21
21
  readable.on('error', serializer.onDisconnected);
22
+ rpcPeer.killedSafe.finally(() => {
23
+ readable.destroy();
24
+ writable.destroy();
25
+ });
22
26
  return rpcPeer;
23
27
  }
24
28
 
package/src/rpc.ts CHANGED
@@ -398,6 +398,22 @@ export class RpcPeer {
398
398
  RpcPeer.PROPERTY_PROXY_PROPERTIES,
399
399
  RpcPeer.PROPERTY_JSON_COPY_SERIALIZE_CHILDREN,
400
400
  ]);
401
+ static readonly FORBIDDEN_RPC_METHODS = new Set<string>([
402
+ 'constructor',
403
+ 'prototype',
404
+ '__proto__',
405
+ '__defineGetter__',
406
+ '__defineSetter__',
407
+ '__lookupGetter__',
408
+ '__lookupSetter__',
409
+ 'apply',
410
+ 'bind',
411
+ 'call',
412
+ 'caller',
413
+ 'arguments',
414
+ 'eval',
415
+ 'Function',
416
+ ]);
401
417
 
402
418
  constructor(public selfName: string, public peerName: string, public send: (message: RpcMessage, reject?: (e: Error) => void, serializationContext?: any) => void) {
403
419
  this.killed = new Promise<string>((resolve, reject) => {
@@ -414,6 +430,17 @@ export class RpcPeer {
414
430
  && this.getDefaultTransportSafeArgumentTypes().has(value.constructor?.name);
415
431
  }
416
432
 
433
+ static validateRpcMethod(method: any) {
434
+ if (typeof method !== 'string' || !method)
435
+ throw new Error('invalid rpc method');
436
+ // Reject constructors, native getters/setters, and other inherited
437
+ // builtins that would allow a peer to escape the proxied object.
438
+ if (RpcPeer.FORBIDDEN_RPC_METHODS.has(method)
439
+ || method in Object.prototype
440
+ || method in Function.prototype)
441
+ throw new Error(`rpc method ${method} is not allowed`);
442
+ }
443
+
417
444
  isTransportSafe(value: any) {
418
445
  if (!value)
419
446
  return true;
@@ -755,6 +782,9 @@ export class RpcPeer {
755
782
  if (!target)
756
783
  throw new Error(`proxy id ${rpcApply.proxyId} not found`);
757
784
 
785
+ if (rpcApply.method)
786
+ RpcPeer.validateRpcMethod(rpcApply.method);
787
+
758
788
  const args = [];
759
789
  for (const arg of (rpcApply.args || [])) {
760
790
  args.push(this.deserialize(arg, deserializationContext));
@@ -763,7 +793,7 @@ export class RpcPeer {
763
793
  let value: any;
764
794
  if (rpcApply.method) {
765
795
  const method = target[rpcApply.method];
766
- if (!method)
796
+ if (typeof method !== 'function')
767
797
  throw new Error(`target ${target?.constructor?.name} does not have method ${rpcApply.method}`);
768
798
 
769
799
  const isIteratorNext = RpcPeer.getIteratorNext(target) === rpcApply.method;
@@ -404,6 +404,30 @@ export function createClusterServer(mainFilename: string, scryptedRuntime: Scryp
404
404
  }
405
405
  }
406
406
  peer.params['connectForkWorker'] = connectForkWorker;
407
+
408
+ let lastCheck = Date.now();
409
+ let killed = false;
410
+
411
+ const healthInterval = setInterval(() => {
412
+ if (Date.now() - lastCheck > 60000)
413
+ peer.kill('Cluster liveness timeout.');
414
+ }, 15000);
415
+
416
+ peer.killedSafe.finally(() => {
417
+ killed = true;
418
+ clearInterval(healthInterval);
419
+ });
420
+
421
+ (async () => {
422
+ while (!killed) {
423
+ await sleep(15000);
424
+ if (killed)
425
+ return;
426
+ const info = await peer.getParam('info').catch(() => { });
427
+ if (info)
428
+ lastCheck = Date.now();
429
+ }
430
+ })();
407
431
  });
408
432
 
409
433
  return server;
@@ -46,6 +46,18 @@ if (SCRYPTED_SERVER_LISTEN_HOSTNAMES) {
46
46
  }
47
47
  }
48
48
 
49
+ // constant time comparison for password hashes and tokens so the string comparison
50
+ // does not leak how many leading characters matched.
51
+ function timingSafeStringEqual(a: string | undefined, b: string | undefined) {
52
+ if (typeof a !== 'string' || typeof b !== 'string')
53
+ return false;
54
+ const ab = Buffer.from(a);
55
+ const bb = Buffer.from(b);
56
+ if (ab.length !== bb.length)
57
+ return false;
58
+ return crypto.timingSafeEqual(ab, bb);
59
+ }
60
+
49
61
  async function listenServerPort(env: string, port: number, server: http.Server | https.Server | net.Server) {
50
62
  server.listen(port);
51
63
  try {
@@ -187,7 +199,7 @@ async function start(mainFilename: string, options?: {
187
199
  hash.update(salted);
188
200
  const sha = hash.digest().toString('hex');
189
201
 
190
- callback(sha === user.passwordHash || password === user.token);
202
+ callback(timingSafeStringEqual(sha, user.passwordHash) || timingSafeStringEqual(password, user.token));
191
203
  });
192
204
 
193
205
  // the default http-auth will returns a WWW-Authenticate header if login fails.
@@ -273,7 +285,7 @@ async function start(mainFilename: string, options?: {
273
285
  // lack of login from cookie auth.
274
286
 
275
287
  const checkToken = (token: string) => {
276
- if (process.env.SCRYPTED_ADMIN_TOKEN === token) {
288
+ if (process.env.SCRYPTED_ADMIN_TOKEN && timingSafeStringEqual(process.env.SCRYPTED_ADMIN_TOKEN, token)) {
277
289
  let username = process.env.SCRYPTED_ADMIN_USERNAME;
278
290
  if (!username) {
279
291
  const firstAdmin = [...scrypted.usersService.users.values()].find(u => !u.aclId);
@@ -287,7 +299,7 @@ async function start(mainFilename: string, options?: {
287
299
  }
288
300
 
289
301
  for (const user of scrypted.usersService.users.values()) {
290
- if (user.token === token) {
302
+ if (timingSafeStringEqual(user.token, token)) {
291
303
  res.locals.username = user._id;
292
304
  res.locals.aclId = user.aclId;
293
305
  break;
@@ -302,7 +314,7 @@ async function start(mainFilename: string, options?: {
302
314
  hash.update(salted);
303
315
  const sha = hash.digest().toString('hex');
304
316
 
305
- if (checkHash === sha) {
317
+ if (timingSafeStringEqual(checkHash, sha)) {
306
318
  const userToken = checkValidUserToken(tokenPart);
307
319
  if (userToken) {
308
320
  res.locals.username = userToken.username;
@@ -551,8 +563,10 @@ async function start(mainFilename: string, options?: {
551
563
  return undefined;
552
564
  try {
553
565
  const userToken = UserToken.validateToken(token);
554
- if (scrypted.usersService.users.has(userToken.username))
555
- return userToken;
566
+ const user = scrypted.usersService.users.get(userToken.username);
567
+ if (!user || userToken.timestamp < user.passwordDate || userToken.aclId !== user.aclId)
568
+ return undefined;
569
+ return userToken;
556
570
  }
557
571
  catch (e) {
558
572
  // console.warn('invalid token', e.message);
@@ -594,9 +608,13 @@ async function start(mainFilename: string, options?: {
594
608
  };
595
609
  }
596
610
 
611
+ async function updateUser(user: ScryptedUser) {
612
+ await db.upsert(user);
613
+ scrypted.usersService.users.set(user._id, user);
614
+ }
615
+
597
616
  app.post('/login', async (req, res) => {
598
617
  const { username, password, change_password, maxAge: maxAgeRequested } = req.body;
599
- const timestamp = Date.now();
600
618
  const maxAge = parseInt(maxAgeRequested) || ONE_DAY_MILLISECONDS;
601
619
  const alternateAddresses = await getAlternateAddresses();
602
620
 
@@ -614,7 +632,7 @@ async function start(mainFilename: string, options?: {
614
632
  const hash = crypto.createHash('sha256');
615
633
  hash.update(salted);
616
634
  const sha = hash.digest().toString('hex');
617
- if (user.passwordHash !== sha && user.token !== password) {
635
+ if (!timingSafeStringEqual(user.passwordHash, sha) && !timingSafeStringEqual(user.token, password)) {
618
636
  res.send({
619
637
  error: 'Incorrect password.',
620
638
  hasLogin,
@@ -622,7 +640,12 @@ async function start(mainFilename: string, options?: {
622
640
  return;
623
641
  }
624
642
 
625
- const userToken = new UserToken(username, user.aclId, timestamp, maxAge);
643
+ if (change_password) {
644
+ setScryptedUserPassword(user, change_password, Date.now());
645
+ await updateUser(user);
646
+ }
647
+
648
+ const userToken = new UserToken(username, user.aclId, Date.now(), maxAge);
626
649
  const login_user_token = userToken.toString();
627
650
  res.cookie(getLoginUserToken(req), login_user_token, {
628
651
  maxAge,
@@ -631,11 +654,6 @@ async function start(mainFilename: string, options?: {
631
654
  httpOnly: true,
632
655
  });
633
656
 
634
- if (change_password) {
635
- setScryptedUserPassword(user, change_password, timestamp);
636
- await db.upsert(user);
637
- }
638
-
639
657
  res.send({
640
658
  ...createTokens(userToken),
641
659
  username,
@@ -657,7 +675,7 @@ async function start(mainFilename: string, options?: {
657
675
  const user = await scrypted.usersService.addUserInternal(username, password, undefined);
658
676
  hasLogin = true;
659
677
 
660
- const userToken = new UserToken(username, user.aclId, timestamp);
678
+ const userToken = new UserToken(username, user.aclId, Date.now());
661
679
  const login_user_token = userToken.toString();
662
680
  res.cookie(getLoginUserToken(req), login_user_token, {
663
681
  maxAge,
@@ -725,7 +743,7 @@ async function start(mainFilename: string, options?: {
725
743
  const user = await db.tryGet(ScryptedUser, username) as ScryptedUser;
726
744
  if (!user.token) {
727
745
  user.token = crypto.randomBytes(16).toString('hex');
728
- await db.upsert(user);
746
+ await updateUser(user);
729
747
  }
730
748
 
731
749
  const userToken = new UserToken(user._id, user.aclId, Date.now());
@@ -92,9 +92,9 @@ export class ClusterForkService {
92
92
  });
93
93
  forkResultPromise.then(forkResult => {
94
94
  forkResult.clusterWorkerId = worker.id;
95
- forkResult.waitKilled().catch(() => { }).finally(() => {
96
- worker.forks.delete(options);
97
- });
95
+ return forkResult.waitKilled().catch(() => { });
96
+ }).catch(() => { }).finally(() => {
97
+ worker.forks.delete(options);
98
98
  });
99
99
 
100
100
  const ret: ClusterForkResultInterface = new WrappedForkResult(worker.id, forkResultPromise);
@@ -172,6 +172,12 @@ export class PluginComponent {
172
172
  consoleServer.clear(pluginDevice.nativeId);
173
173
  }
174
174
 
175
+ async readConsole(id: string) {
176
+ const pluginDevice = this.scrypted.findPluginDeviceById(id)!;
177
+ const consoleServer = await this.scrypted.plugins[pluginDevice.pluginId]!.consoleServer;
178
+ return consoleServer.read(pluginDevice.nativeId).toString();
179
+ }
180
+
175
181
  async getRemoteServicePort(pluginId: string, name: string, ...args: any[]): Promise<[number, string]> {
176
182
  if (name === 'console') {
177
183
  const consoleServer = await this.scrypted.plugins[pluginId]!.consoleServer;