@scrypted/server 0.0.116 → 0.0.121

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.

Potentially problematic release.


This version of @scrypted/server might be problematic. Click here for more details.

Files changed (56) hide show
  1. package/.vscode/launch.json +1 -0
  2. package/dist/http-interfaces.js +11 -4
  3. package/dist/http-interfaces.js.map +1 -1
  4. package/dist/level.js.map +1 -1
  5. package/dist/plugin/media.js +4 -4
  6. package/dist/plugin/media.js.map +1 -1
  7. package/dist/plugin/plugin-console.js.map +1 -1
  8. package/dist/plugin/plugin-device.js +13 -3
  9. package/dist/plugin/plugin-device.js.map +1 -1
  10. package/dist/plugin/plugin-host-api.js +2 -2
  11. package/dist/plugin/plugin-host-api.js.map +1 -1
  12. package/dist/plugin/plugin-host.js +110 -235
  13. package/dist/plugin/plugin-host.js.map +1 -1
  14. package/dist/plugin/plugin-http.js +1 -0
  15. package/dist/plugin/plugin-http.js.map +1 -1
  16. package/dist/plugin/plugin-lazy-remote.js.map +1 -1
  17. package/dist/plugin/plugin-remote-worker.js +252 -0
  18. package/dist/plugin/plugin-remote-worker.js.map +1 -0
  19. package/dist/plugin/plugin-remote.js +38 -14
  20. package/dist/plugin/plugin-remote.js.map +1 -1
  21. package/dist/plugin/plugin-repl.js.map +1 -1
  22. package/dist/plugin/system.js +7 -5
  23. package/dist/plugin/system.js.map +1 -1
  24. package/dist/rpc.js +13 -3
  25. package/dist/rpc.js.map +1 -1
  26. package/dist/runtime.js +18 -7
  27. package/dist/runtime.js.map +1 -1
  28. package/dist/scrypted-main.js +4 -437
  29. package/dist/scrypted-main.js.map +1 -1
  30. package/dist/scrypted-plugin-main.js +8 -0
  31. package/dist/scrypted-plugin-main.js.map +1 -0
  32. package/dist/scrypted-server-main.js +429 -0
  33. package/dist/scrypted-server-main.js.map +1 -0
  34. package/package.json +7 -6
  35. package/python/media.py +1 -12
  36. package/python/plugin-remote.py +22 -7
  37. package/python/rpc.py +5 -4
  38. package/src/http-interfaces.ts +12 -5
  39. package/src/level.ts +0 -2
  40. package/src/plugin/media.ts +4 -4
  41. package/src/plugin/plugin-api.ts +9 -1
  42. package/src/plugin/plugin-console.ts +0 -1
  43. package/src/plugin/plugin-device.ts +10 -3
  44. package/src/plugin/plugin-host-api.ts +2 -2
  45. package/src/plugin/plugin-host.ts +121 -264
  46. package/src/plugin/plugin-http.ts +3 -2
  47. package/src/plugin/plugin-lazy-remote.ts +1 -1
  48. package/src/plugin/plugin-remote-worker.ts +271 -0
  49. package/src/plugin/plugin-remote.ts +45 -16
  50. package/src/plugin/plugin-repl.ts +0 -1
  51. package/src/plugin/system.ts +8 -6
  52. package/src/rpc.ts +13 -2
  53. package/src/runtime.ts +18 -7
  54. package/src/scrypted-main.ts +5 -508
  55. package/src/scrypted-plugin-main.ts +6 -0
  56. package/src/scrypted-server-main.ts +498 -0
@@ -0,0 +1,498 @@
1
+ import path from 'path';
2
+ import process from 'process';
3
+ import http from 'http';
4
+ import https from 'https';
5
+ import express from 'express';
6
+ import bodyParser from 'body-parser';
7
+ import net from 'net';
8
+ import { ScryptedRuntime } from './runtime';
9
+ import level from './level';
10
+ import { Plugin, ScryptedUser, Settings } from './db-types';
11
+ import { SCRYPTED_DEBUG_PORT, SCRYPTED_INSECURE_PORT, SCRYPTED_SECURE_PORT } from './server-settings';
12
+ import crypto from 'crypto';
13
+ import cookieParser from 'cookie-parser';
14
+ import axios from 'axios';
15
+ import qs from 'query-string';
16
+ import { RPCResultError } from './rpc';
17
+ import fs from 'fs';
18
+ import mkdirp from 'mkdirp';
19
+ import { install as installSourceMapSupport } from 'source-map-support';
20
+ import httpAuth from 'http-auth';
21
+ import semver from 'semver';
22
+ import { Info } from './services/info';
23
+ import { getAddresses } from './addresses';
24
+ import { sleep } from './sleep';
25
+ import { createSelfSignedCertificate, CURRENT_SELF_SIGNED_CERTIFICATE_VERSION } from './cert';
26
+ import { PluginError } from './plugin/plugin-error';
27
+ import { getScryptedVolume } from './plugin/plugin-volume';
28
+
29
+ if (!semver.gte(process.version, '16.0.0')) {
30
+ throw new Error('"node" version out of date. Please update node to v16 or higher.')
31
+ }
32
+
33
+ process.on('unhandledRejection', error => {
34
+ if (error?.constructor !== RPCResultError && error?.constructor !== PluginError) {
35
+ throw error;
36
+ }
37
+ console.warn('unhandled rejection of RPC Result', error);
38
+ });
39
+
40
+ function listenServerPort(env: string, port: number, server: any) {
41
+ server.listen(port,);
42
+ server.on('error', (e: Error) => {
43
+ console.error(`Failed to listen on port ${port}. It may be in use.`);
44
+ console.error(`Use the environment variable ${env} to change the port.`);
45
+ throw e;
46
+ })
47
+ }
48
+
49
+ installSourceMapSupport({
50
+ environment: 'node',
51
+ });
52
+
53
+ let workerInspectPort: number = undefined;
54
+
55
+ async function doconnect(): Promise<net.Socket> {
56
+ return new Promise((resolve, reject) => {
57
+ const target = net.connect(workerInspectPort);
58
+ target.once('error', reject)
59
+ target.once('connect', () => resolve(target))
60
+ })
61
+ }
62
+
63
+ const debugServer = net.createServer(async (socket) => {
64
+ if (!workerInspectPort) {
65
+ socket.destroy();
66
+ return;
67
+ }
68
+
69
+ for (let i = 0; i < 10; i++) {
70
+ try {
71
+ const target = await doconnect();
72
+ socket.pipe(target).pipe(socket);
73
+ const destroy = () => {
74
+ socket.destroy();
75
+ target.destroy();
76
+ }
77
+ socket.on('error', destroy);
78
+ target.on('error', destroy);
79
+ socket.on('close', destroy);
80
+ target.on('close', destroy);
81
+ return;
82
+ }
83
+ catch (e) {
84
+ await sleep(500);
85
+ }
86
+ }
87
+ console.warn('debugger connect timed out');
88
+ socket.destroy();
89
+ })
90
+ listenServerPort('SCRYPTED_DEBUG_PORT', SCRYPTED_DEBUG_PORT, debugServer);
91
+
92
+ const app = express();
93
+
94
+ // parse application/x-www-form-urlencoded
95
+ app.use(bodyParser.urlencoded({ extended: false }) as any)
96
+
97
+ // parse application/json
98
+ app.use(bodyParser.json())
99
+
100
+ // parse some custom thing into a Buffer
101
+ app.use(bodyParser.raw({ type: 'application/zip', limit: 100000000 }) as any)
102
+
103
+ async function start() {
104
+ const volumeDir = getScryptedVolume();
105
+ mkdirp.sync(volumeDir);
106
+ const dbPath = path.join(volumeDir, 'scrypted.db');
107
+ const db = level(dbPath);
108
+ await db.open();
109
+
110
+ if (process.env.SCRYPTED_RESET_ALL_USERS === 'true') {
111
+ await db.removeAll(ScryptedUser);
112
+ }
113
+
114
+ let certSetting = await db.tryGet(Settings, 'certificate') as Settings;
115
+
116
+ if (certSetting?.value?.version !== CURRENT_SELF_SIGNED_CERTIFICATE_VERSION) {
117
+ const cert = createSelfSignedCertificate();
118
+
119
+ certSetting = new Settings();
120
+ certSetting._id = 'certificate';
121
+ certSetting.value = cert;
122
+ certSetting = await db.upsert(certSetting);
123
+ }
124
+
125
+
126
+ const basicAuth = httpAuth.basic({
127
+ realm: 'Scrypted',
128
+ }, async (username, password, callback) => {
129
+ const user = await db.tryGet(ScryptedUser, username);
130
+ if (!user) {
131
+ callback(false);
132
+ return;
133
+ }
134
+
135
+ const salted = user.salt + password;
136
+ const hash = crypto.createHash('sha256');
137
+ hash.update(salted);
138
+ const sha = hash.digest().toString('hex');
139
+
140
+ callback(sha === user.passwordHash || password === user.token);
141
+ });
142
+
143
+ const keys = certSetting.value;
144
+
145
+ const httpsServerOptions = process.env.SCRYPTED_HTTPS_OPTIONS_FILE
146
+ ? JSON.parse(fs.readFileSync(process.env.SCRYPTED_HTTPS_OPTIONS_FILE).toString())
147
+ : {};
148
+
149
+ const mergedHttpsServerOptions = Object.assign({
150
+ key: keys.serviceKey,
151
+ cert: keys.certificate
152
+ }, httpsServerOptions);
153
+ const secure = https.createServer(mergedHttpsServerOptions, app);
154
+ const insecure = http.createServer(app);
155
+
156
+ // use a hash of the private key as the cookie secret.
157
+ app.use(cookieParser(crypto.createHash('sha256').update(certSetting.value.serviceKey).digest().toString('hex')));
158
+
159
+ app.all('*', async (req, res, next) => {
160
+ // this is a trap for all auth.
161
+ // only basic auth will fail with 401. it is up to the endpoints to manage
162
+ // lack of login from cookie auth.
163
+
164
+ const { login_user_token } = req.signedCookies;
165
+ if (login_user_token) {
166
+ const userTokenParts = login_user_token.split('#');
167
+ const username = userTokenParts[0];
168
+ const timestamp = parseInt(userTokenParts[1]);
169
+ if (timestamp + 86400000 < Date.now()) {
170
+ console.warn('login expired');
171
+ return next();
172
+ }
173
+
174
+ const user = await db.tryGet(ScryptedUser, username);
175
+ if (!user) {
176
+ console.warn('login not found');
177
+ return next();
178
+ }
179
+
180
+ res.locals.username = username;
181
+ }
182
+ next();
183
+ });
184
+
185
+ // allow basic auth to deploy plugins
186
+ app.all('/web/component/*', (req, res, next) => {
187
+ if (req.protocol === 'https' && req.headers.authorization && req.headers.authorization.toLowerCase()?.indexOf('basic') !== -1) {
188
+ const basicChecker = basicAuth.check((req) => {
189
+ res.locals.username = req.user;
190
+ next();
191
+ });
192
+
193
+ // this automatically handles unauthorized.
194
+ basicChecker(req, res);
195
+ return;
196
+ }
197
+ next();
198
+ })
199
+
200
+ // verify all plugin related requests have some sort of auth
201
+ app.all('/web/component/*', (req, res, next) => {
202
+ if (!res.locals.username) {
203
+ res.status(401);
204
+ res.send('Not Authorized');
205
+ return;
206
+ }
207
+ next();
208
+ });
209
+
210
+ const scrypted = new ScryptedRuntime(db, insecure, secure, app);
211
+ await scrypted.start();
212
+
213
+ listenServerPort('SCRYPTED_SECURE_PORT', SCRYPTED_SECURE_PORT, secure);
214
+ listenServerPort('SCRYPTED_INSECURE_PORT', SCRYPTED_INSECURE_PORT, insecure);
215
+
216
+ console.log('#######################################################');
217
+ console.log(`Scrypted Server (Local) : https://localhost:${SCRYPTED_SECURE_PORT}/`);
218
+ for (const address of getAddresses()) {
219
+ console.log(`Scrypted Server (Remote) : https://${address}:${SCRYPTED_SECURE_PORT}/`);
220
+ }
221
+ console.log(`Version: : ${await new Info().getVersion()}`);
222
+ console.log('#######################################################');
223
+ console.log('Chrome Users: You may need to type "thisisunsafe" into')
224
+ console.log(' the window to bypass the warning. There')
225
+ console.log(' may be no button to continue, type the')
226
+ console.log(' letters "thisisunsafe" and it will proceed.')
227
+ console.log('#######################################################');
228
+ console.log('Scrypted insecure http service port:', SCRYPTED_INSECURE_PORT);
229
+ console.log('Ports can be changed with environment variables.')
230
+ console.log('https: $SCRYPTED_SECURE_PORT')
231
+ console.log('http : $SCRYPTED_INSECURE_PORT')
232
+ console.log('Certificate can be modified via tls.createSecureContext options in')
233
+ console.log('JSON file located at SCRYPTED_HTTPS_OPTIONS_FILE environment variable:');
234
+ console.log('export SCRYPTED_HTTPS_OPTIONS_FILE=/path/to/options.json');
235
+ console.log('https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions')
236
+ console.log('#######################################################');
237
+
238
+ app.get(['/web/component/script/npm/:pkg', '/web/component/script/npm/@:owner/:pkg'], async (req, res) => {
239
+ const { owner, pkg } = req.params;
240
+ let endpoint = pkg;
241
+ if (owner)
242
+ endpoint = `@${owner}/${endpoint}`;
243
+ try {
244
+ const response = await axios(`https://registry.npmjs.org/${endpoint}`);
245
+ res.send(response.data);
246
+ }
247
+ catch (e) {
248
+ res.status(500);
249
+ res.end();
250
+ }
251
+ });
252
+
253
+ app.post(['/web/component/script/install/:pkg', '/web/component/script/install/@:owner/:pkg', '/web/component/script/install/@:owner/:pkg/:tag'], async (req, res) => {
254
+ const { owner, pkg, tag } = req.params;
255
+ let endpoint = pkg;
256
+ if (owner)
257
+ endpoint = `@${owner}/${endpoint}`;
258
+ try {
259
+ const plugin = await scrypted.installNpm(endpoint, tag);
260
+ res.send({
261
+ id: scrypted.findPluginDevice(plugin.pluginId)._id,
262
+ });
263
+ }
264
+ catch (e) {
265
+ res.status(500);
266
+ res.end();
267
+ }
268
+ });
269
+
270
+ app.get('/web/component/script/search', async (req, res) => {
271
+ try {
272
+ const query = qs.stringify({
273
+ text: req.query.text,
274
+ })
275
+ const response = await axios(`https://registry.npmjs.org/-/v1/search?${query}`);
276
+ res.send(response.data);
277
+ }
278
+ catch (e) {
279
+ res.status(500);
280
+ res.end();
281
+ }
282
+ });
283
+
284
+ app.post('/web/component/script/setup', async (req, res) => {
285
+ const npmPackage = req.query.npmPackage as string;
286
+ const plugin = await db.tryGet(Plugin, npmPackage) || new Plugin();
287
+
288
+ plugin._id = npmPackage;
289
+ plugin.packageJson = req.body;
290
+
291
+ await db.upsert(plugin);
292
+
293
+ res.send('ok');
294
+ });
295
+
296
+ app.post('/web/component/script/deploy', async (req, res) => {
297
+ const npmPackage = req.query.npmPackage as string;
298
+ const plugin = await db.tryGet(Plugin, npmPackage);
299
+
300
+ if (!plugin) {
301
+ res.status(500);
302
+ res.send(`npm package ${npmPackage} not found`);
303
+ return;
304
+ }
305
+
306
+ plugin.zip = req.body.toString('base64');
307
+ await db.upsert(plugin);
308
+
309
+ const noRebind = req.query['no-rebind'] !== undefined;
310
+ if (!noRebind)
311
+ await scrypted.installPlugin(plugin);
312
+
313
+ res.send('ok');
314
+ });
315
+
316
+ app.post('/web/component/script/debug', async (req, res) => {
317
+ const npmPackage = req.query.npmPackage as string;
318
+ const plugin = await db.tryGet(Plugin, npmPackage);
319
+
320
+ if (!plugin) {
321
+ res.status(500);
322
+ res.send(`npm package ${npmPackage} not found`);
323
+ return;
324
+ }
325
+
326
+ const waitDebug = new Promise<void>((resolve, reject) => {
327
+ setTimeout(() => reject(new Error('timed out waiting for debug session')), 30000);
328
+ debugServer.on('connection', resolve);
329
+ });
330
+
331
+ workerInspectPort = Math.round(Math.random() * 10000) + 30000;
332
+ try {
333
+ await scrypted.installPlugin(plugin, {
334
+ waitDebug,
335
+ inspectPort: workerInspectPort,
336
+ });
337
+ }
338
+ catch (e) {
339
+ res.status(500);
340
+ res.send(e.toString());
341
+ return
342
+ }
343
+
344
+ res.send({
345
+ workerInspectPort,
346
+ });
347
+ });
348
+
349
+ app.get('/logout', (req, res) => {
350
+ res.clearCookie('login_user_token');
351
+ res.send({});
352
+ });
353
+
354
+ app.post('/login', async (req, res) => {
355
+ const hasLogin = await db.getCount(ScryptedUser) > 0;
356
+
357
+ const { username, password, change_password } = req.body;
358
+ const timestamp = Date.now();
359
+ const maxAge = 86400000;
360
+
361
+ if (hasLogin) {
362
+
363
+ const user = await db.tryGet(ScryptedUser, username);
364
+ if (!user) {
365
+ res.send({
366
+ error: 'User does not exist.',
367
+ hasLogin,
368
+ })
369
+ return;
370
+ }
371
+
372
+ const salted = user.salt + password;
373
+ const hash = crypto.createHash('sha256');
374
+ hash.update(salted);
375
+ const sha = hash.digest().toString('hex');
376
+ if (user.passwordHash !== sha) {
377
+ res.send({
378
+ error: 'Incorrect password.',
379
+ hasLogin,
380
+ })
381
+ return;
382
+ }
383
+
384
+ const login_user_token = `${username}#${timestamp}`;
385
+ res.cookie('login_user_token', login_user_token, {
386
+ maxAge,
387
+ secure: true,
388
+ signed: true,
389
+ httpOnly: true,
390
+ });
391
+
392
+ if (change_password) {
393
+ user.salt = crypto.randomBytes(64).toString('base64');
394
+ user.passwordHash = crypto.createHash('sha256').update(user.salt + change_password).digest().toString('hex');
395
+ user.passwordDate = timestamp;
396
+ await db.upsert(user);
397
+ }
398
+
399
+ res.send({
400
+ username,
401
+ expiration: maxAge,
402
+ });
403
+
404
+ return;
405
+ }
406
+
407
+ const user = new ScryptedUser();
408
+ user._id = username;
409
+ user.salt = crypto.randomBytes(64).toString('base64');
410
+ user.passwordHash = crypto.createHash('sha256').update(user.salt + password).digest().toString('hex');
411
+ user.passwordDate = timestamp;
412
+ await db.upsert(user);
413
+
414
+ const login_user_token = `${username}#${timestamp}`
415
+ res.cookie('login_user_token', login_user_token, {
416
+ maxAge,
417
+ secure: true,
418
+ signed: true,
419
+ httpOnly: true,
420
+ });
421
+
422
+ res.send({
423
+ username,
424
+ expiration: maxAge,
425
+ });
426
+ });
427
+
428
+ app.get('/login', async (req, res) => {
429
+ if (req.protocol === 'https' && req.headers.authorization) {
430
+ const username = await new Promise(resolve => {
431
+ const basicChecker = basicAuth.check((req) => {
432
+ resolve(req.user);
433
+ });
434
+
435
+ // this automatically handles unauthorized.
436
+ basicChecker(req, res);
437
+ });
438
+
439
+ const user = await db.tryGet(ScryptedUser, username);
440
+ if (!user.token) {
441
+ user.token = crypto.randomBytes(16).toString('hex');
442
+ await db.upsert(user);
443
+ }
444
+ res.send({
445
+ username,
446
+ token: user.token,
447
+ });
448
+ return;
449
+ }
450
+
451
+ const hasLogin = await db.getCount(ScryptedUser) > 0;
452
+ const { login_user_token } = req.signedCookies;
453
+ if (!login_user_token) {
454
+ res.send({
455
+ error: 'Not logged in.',
456
+ hasLogin,
457
+ })
458
+ return;
459
+ }
460
+
461
+ const userTokenParts = login_user_token.split('#');
462
+ const username = userTokenParts[0];
463
+ const timestamp = parseInt(userTokenParts[1]);
464
+ if (timestamp + 86400000 < Date.now()) {
465
+ res.send({
466
+ error: 'Login expired.',
467
+ hasLogin,
468
+ })
469
+ return;
470
+ }
471
+
472
+ const user = await db.tryGet(ScryptedUser, username);
473
+ if (!user) {
474
+ res.send({
475
+ error: 'User not found.',
476
+ hasLogin,
477
+ })
478
+ return;
479
+ }
480
+
481
+ if (timestamp < user.passwordDate) {
482
+ res.send({
483
+ error: 'Login invalid. Password has changed.',
484
+ hasLogin,
485
+ })
486
+ return;
487
+ }
488
+
489
+ res.send({
490
+ expiration: 86400000 - (Date.now() - timestamp),
491
+ username,
492
+ })
493
+ });
494
+
495
+ app.get('/', (_req, res) => res.redirect('/endpoint/@scrypted/core/public/'));
496
+ }
497
+
498
+ start();