-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
2299 lines (2024 loc) · 109 KB
/
index.js
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fetch = require('node-fetch');
const { URL, URLSearchParams } = require('url');
const crypto = require('crypto');
const Semaphore = require('async-mutex').Semaphore;
/**
* Represents a UrBackup Server.
* @class
*/
class UrbackupServer {
#isLoggedIn = false;
#lastLogId = new Map();
#password;
#semaphore = new Semaphore(1);
#sessionId = '';
#url;
#username;
#constants = {
availableClientVersion: '2.5.25',
availableServerVersion: '2.5.33',
adminUserRights: [{ domain: 'all', right: 'all' }],
defaultUserRights: []
};
#messages = {
failedAnonymousLogin: 'Anonymous login failed.',
failedFetch: 'Fetch request failed: response status is not in the range 200-299.',
failedLogin: 'Login failed: invalid username or password.',
failedLoginUnknown: 'Login failed: unknown reason.',
invalidCategory: 'Syntax error: invalid category name.',
missingClientData: 'API response error: missing client data. Make sure the UrBackup user has appropriate rights.',
missingGroupData: 'API response error: missing group data. Make sure the UrBackup user has appropriate rights.',
missingParameters: 'Syntax error: missing or invalid parameters.',
missingServerIdentity: 'API response error: missing server identity. Make sure the UrBackup user has appropriate rights.',
missingUserData: 'API response error: missing user data. Make sure the UrBackup user has appropriate rights.',
missingValues: 'API response error: some values are missing. Make sure the UrBackup user has appropriate rights.',
syntaxClientId: 'Syntax error: clientId must be a number.',
syntaxClientName: 'Syntax error: clientName must be a string.',
syntaxGroupId: 'Syntax error: groupId must be a number.',
syntaxGroupName: 'Syntax error: groupName must be a string.'
};
/**
* This is a constructor.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.url='http://127.0.0.1:55414'] - The URL of the server, must include the protocol, hostname, and port. Defaults to `http://127.0.0.1:55414`.
* @param {string} [params.username=''] - The username used for logging in. If empty, anonymous login method will be used. Defaults to an empty string.
* @param {string} [params.password=''] - The password used to log in. Defaults to an empty string.
* @example <caption>Connect to the built-in server locally without a password</caption>
* const server = new UrbackupServer();
* @example <caption>Connect locally with a specified password</caption>
* const server = new UrbackupServer({ url: 'http://127.0.0.1:55414', username: 'admin', password: 'secretpassword' });
* @example <caption>Connect over the network</caption>
* const server = new UrbackupServer({ url: 'https://192.168.0.2:443', username: 'admin', password: 'secretpassword' });
*/
constructor({ url = 'http://127.0.0.1:55414', username = '', password = '' } = {}) {
this.#url = new URL(url);
this.#url.pathname = 'x';
this.#username = username;
this.#password = password;
}
/**
* Clears the session ID and logged-in flag.
* This method is intended for internal use only and should not be called outside the class.
* @private
* @example
* this.#clearLoginStatus();
*/
#clearLoginStatus() {
this.#sessionId = '';
this.#isLoggedIn = false;
}
/**
* Makes an API call to the server.
* This method is intended for internal use only and should not be called outside the class.
* @param {string} action - The action to perform.
* @param {object} bodyParams - The parameters for the action.
* @returns {Promise<object>} The response body text parsed as JSON.
* @throws {Error} If the fetch request is unsuccessful.
* @private
* @example
* const response = await this.#fetchJson('status');
*/
async #fetchJson(action = '', bodyParams = {}) {
this.#url.searchParams.set('a', action);
if (this.#sessionId.length > 0) {
bodyParams.ses = this.#sessionId;
}
const response = await fetch(this.#url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
},
body: new URLSearchParams(bodyParams)
});
if (response?.ok === true) {
return response.json();
} else {
throw new Error(this.#messages.failedFetch);
}
}
/**
* Hashes the user password.
* This method is intended for internal use only and should not be called outside the class.
* @param {string} salt - PBKDF2 salt value as stored on the server.
* @param {number} rounds - PBKDF2 iterations number.
* @param {string} randomKey - Random key generated by the server for each session.
* @returns {Promise<string>} The hashed password.
* @private
* @example
* const hashedPassword = await this.#hashPassword(saltResponse.salt, saltResponse.pbkdf2_rounds, saltResponse.rnd);
*/
async #hashPassword(salt = '', rounds = 10000, randomKey = '') {
/**
* Async PBKDF2 wrapper.
* @param {Buffer} passwordHash - The hashed password.
* @returns {Promise<Buffer>} The derived key.
* @example
* const hashedPassword = await this.#hashPassword(saltResponse.salt, saltResponse.pbkdf2_rounds, saltResponse.rnd);
*/
function pbkdf2Async(passwordHash) {
return new Promise((resolve, reject) => {
crypto.pbkdf2(passwordHash, salt, rounds, 32, 'sha256', (error, key) => {
return error ? reject(error) : resolve(key);
});
});
}
let passwordHash = crypto.createHash('md5')
.update(salt + this.#password, 'utf8')
.digest();
let derivedKey;
if (rounds > 0) {
derivedKey = await pbkdf2Async(passwordHash);
}
passwordHash = crypto.createHash('md5')
.update(randomKey + (rounds > 0 ? derivedKey.toString('hex') : passwordHash), 'utf8')
.digest('hex');
return passwordHash;
}
/**
* Generates an MD5 hashed password using a salt and a password.
* This method is intended for internal use only and should not be called outside the class.
* @param {string} salt - The salt to use for hashing.
* @param {string} password - The password to hash.
* @returns {string} The MD5 hashed password.
* @private
*/
#hashPasswordMd5(salt, password) {
const hash = crypto.createHash('md5');
hash.update(salt + password);
return hash.digest('hex');
}
/**
* Generates a random string of the specified length using a set of alphanumeric characters.
* This method is intended for internal use only and should not be called outside the class.
* @param {number} length - The desired length of the random string.
* @returns {string} - The generated random alphanumeric string.
* @private
* @example
* const randomStr = this.#generateRandomAlphanumericString(10);
*/
#generateRandomString(length) {
const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const charactersLength = characters.length;
const randomBytes = crypto.randomBytes(length);
let randomString = '';
for (let i = 0; i < length; i++) {
const randomValue = randomBytes[i] % charactersLength;
randomString += characters[randomValue];
}
return randomString;
}
/**
* Encodes user rights into apropriate string format.
* This method is intended for internal use only and should not be called outside the class.
* @param {Array<object>} rights - An array of objects representing user rights.
* @param {string} rights[].domain - The domain of the right.
* @param {string} rights[].right - The specific right.
* @returns {string} The encoded query string representing user rights.
* @private
* @example
* const encodedRights = this.#encodeUserRights([{ domain: 'all', right: 'all' }]);
*/
#encodeUserRights(rights) {
let encodedRights = '';
const indices = [];
let index = 0;
while (index < rights.length) {
const { domain, right } = rights[index];
if (index !== 0) {
encodedRights += '&';
}
encodedRights += `${index}_domain=${domain}&${index}_right=${right}`;
indices.push(index);
index++;
}
encodedRights += `&idx=${indices.join(',')}`;
return encodedRights;
}
/**
* Compares two version strings to determine if the installed version is older than the available version.
* This method is intended for internal use only and should not be called outside the class.
* @param {string} installed - The installed version string in the format 'major.minor.patch'.
* @param {string} available - The available version string in the format 'major.minor.patch'.
* @returns {boolean} Returns true if the installed version is older than the available version, false otherwise.
* @private
*/
#compareVersion(installed, available) {
const parseVersion = (version) => version.split('.').map(Number);
const [installedMajor, installedMinor, installedPatch] = parseVersion(installed);
const [availableMajor, availableMinor, availablePatch] = parseVersion(available);
if (installedMajor !== availableMajor) {
return installedMajor < availableMajor;
}
if (installedMinor !== availableMinor) {
return installedMinor < availableMinor;
}
if (installedPatch !== availablePatch) {
return installedPatch < availablePatch;
}
return false;
}
/**
* Determines whether a given client is considered "blank" (i.e., without any backups).
* This method is intended for internal use only and should not be called outside the class.
* A client is considered "blank" if either file backups or image backups have never been performed and the respective backup type is not disabled.
* @param {Object} params - Options for determining the blank state.
* @param {Object} params.client - The client object to evaluate.
* @param {boolean} params.includeFileBackups - Whether to include file backups in the blank evaluation.
* @param {boolean} params.includeImageBackups - Whether to include image backups in the blank evaluation.
* @returns {boolean} - Returns `true` if the client is considered "blank", otherwise `false`.
* @private
*/
#isBlankClient({ client, includeFileBackups = true, includeImageBackups = true } = {}) {
const isBlankFileBackup = includeFileBackups === true &&
client.lastbackup === 0 && client.file_disabled !== true;
const isBlankImageBackup = includeImageBackups === true &&
client.lastbackup_image === 0 &&
client.image_disabled !== true;
return isBlankFileBackup === true || isBlankImageBackup === true;
}
/**
* Determines whether a given client is considered "failed" based on its backup statuses.
* This method is intended for internal use only and should not be called outside the class.
* @param {Object} params - The options for determining the failure state.
* @param {Object} params.client - The client object to evaluate.
* @param {boolean} params.includeFileBackups - Whether to include file backups in the failure evaluation.
* @param {boolean} params.includeImageBackups - Whether to include image backups in the failure evaluation.
* @param {boolean} params.failOnFileIssues - Whether to fail the client if file backup issues are detected.
* @returns {boolean} - Returns `true` if the client is considered "failed" (either due to file or image backup failure), otherwise `false`.
* @private
*/
#isFailedClient({ client, includeFileBackups, includeImageBackups, failOnFileIssues } = {}) {
const isFailedFileBackup = includeFileBackups === true &&
client.file_disabled !== true &&
(failOnFileIssues === true ? (client.last_filebackup_issues !== 0 || client.file_ok !== true) : client.file_ok !== true) === true;
const isFailedImageBackup = includeImageBackups === true &&
client.image_disabled !== true &&
client.image_ok !== true;
return isFailedFileBackup === true || isFailedImageBackup === true;
}
/**
* Determines whether a given client is considered "stale".
* A client is considered "stale" if the time elapsed since their last file or image backup exceeds the given time threshold,
* and the respective backup type is not disabled.
* This method is intended for internal use only and should not be called outside the class.
* @param {Object} params - Options for determining the stale state.
* @param {Object} params.client - The client object to evaluate.
* @param {boolean} params.includeFileBackups - Whether to include file backups in the stale evaluation.
* @param {boolean} params.includeImageBackups - Whether to include image backups in the stale evaluation.
* @param {number} params.time - The current timestamp (in seconds).
* @param {number} params.timeThreshold - The time threshold (in minutes) used to determine staleness.
* @returns {boolean} - Returns `true` if the client is considered "stale" (either for file or image backups), otherwise `false`.
* @private
*/
#isStaleClient({ client, includeFileBackups, includeImageBackups, time, timeThreshold } = {}) {
const isStaleFileBackup = includeFileBackups === true &&
client.file_disabled !== true &&
Math.round((time - (client.lastbackup ?? 0)) / 60) >= timeThreshold;
const isStaleImageBackup = includeImageBackups === true &&
client.image_disabled !== true &&
Math.round((time - (client.lastbackup_image ?? 0)) / 60) >= timeThreshold;
return isStaleFileBackup === true || isStaleImageBackup === true;
}
/**
* Logs in to the server.
* This method is intended for internal use only and should not be called outside the class.
* If the username is empty, then the anonymous login method is used.
* @returns {Promise<boolean>} Boolean value true if the login was successful or if the user was already logged in. Boolean value false in any other case.
* @throws {Error} If the login fails.
* @private
* @example
* const login = await this.#login();
*/
async #login() {
// NOTE: Use a semaphore to prevent race conditions with the login status, i.e., this.#sessionId
// eslint-disable-next-line no-unused-vars
const [value, release] = await this.#semaphore.acquire();
try {
if (this.#isLoggedIn === true && this.#sessionId.length > 0) {
return true;
}
if (this.#username.length === 0) {
const anonymousLoginResponse = await this.#fetchJson('login');
if (anonymousLoginResponse?.success === true) {
this.#sessionId = anonymousLoginResponse.session;
this.#isLoggedIn = true;
return true;
} else {
this.#clearLoginStatus();
throw new Error(this.#messages.failedAnonymousLogin);
}
} else {
const saltResponse = await this.#fetchJson('salt', { username: this.#username });
if (typeof saltResponse?.salt === 'string') {
this.#sessionId = saltResponse.ses;
const hashedPassword = await this.#hashPassword(saltResponse.salt, saltResponse.pbkdf2_rounds, saltResponse.rnd);
const userLoginResponse = await this.#fetchJson('login', { username: this.#username, password: hashedPassword });
if (userLoginResponse?.success === true) {
this.#isLoggedIn = true;
return true;
} else {
// NOTE: Invalid password
this.#clearLoginStatus();
throw new Error(this.#messages.failedLogin);
}
} else {
// NOTE: Invalid username
this.#clearLoginStatus();
throw new Error(this.#messages.failedLogin);
}
}
} finally {
release();
}
}
/**
* Maps client name to client ID or client ID to client name.
* This method is intended for internal use only and should not be called outside the class.
* @param {string|number} inputIdentifier - The client's name or ID.
* @param {string} outputIdentifierType - The type of output identifier. Must be: 'name' or 'id'.
* @returns {Promise<number|string|null>} The client's ID or name, or null if no matching clients are found.
* @throws {Error} If the `inputIdentifier` is not a string when `outputIdentifierType` is 'name' or not a number when `outputIdentifierType` is 'id'.
* @private
* @example
* const clientId = await this.#getClientIdentifier('dbserver', 'id');
* const clientName = await this.#getClientIdentifier(42, 'name');
*/
async #getClientIdentifier(inputIdentifier, outputIdentifierType) {
if ((outputIdentifierType === 'id' && typeof inputIdentifier !== 'string') || (outputIdentifierType === 'name' && typeof inputIdentifier !== 'number')) {
throw new Error(outputIdentifierType === 'id' ? this.#messages.syntaxClientName : this.#messages.syntaxClientId);
}
const fallbackReturnValue = null;
const clients = await this.getClients({ includeRemoved: true });
let result;
if (outputIdentifierType === 'id') {
result = clients.find((client) => client.name === inputIdentifier)?.id;
} else if (outputIdentifierType === 'name') {
result = clients.find((client) => client.id === inputIdentifier)?.name;
}
return typeof result === 'undefined' ? fallbackReturnValue : result;
}
/**
* Maps group name to group ID or group ID to group name.
* This method is intended for internal use only and should not be called outside the class.
* @param {string|number} inputIdentifier - The group's name or ID.
* @param {string} outputIdentifierType - The type of output identifier Must be: 'name' or 'id'.
* @returns {Promise<number|string|null>} The group's ID or name, or null if no matching group are found.
* @throws {Error} If the `inputIdentifier` is not a string when `outputIdentifierType` is 'name' or not a number when `outputIdentifierType` is 'id'.
* @private
* @example
* const groupId = await this.#getGroupIdentifier('hr', 'id');
* const groupName = await this.#getGroupIdentifier(2, 'name');
*/
async #getGroupIdentifier(inputIdentifier, outputIdentifierType) {
if ((outputIdentifierType === 'id' && typeof inputIdentifier !== 'string') || (outputIdentifierType === 'name' && typeof inputIdentifier !== 'number')) {
throw new Error(outputIdentifierType === 'id' ? this.#messages.syntaxGroupName : this.#messages.syntaxGroupId);
}
const fallbackReturnValue = null;
const groups = await this.getGroups();
let result;
if (outputIdentifierType === 'id') {
result = groups.find((group) => group.name === inputIdentifier)?.id;
} else if (outputIdentifierType === 'name') {
result = groups.find((group) => group.id === inputIdentifier)?.name;
}
return typeof result === 'undefined' ? fallbackReturnValue : result;
}
/**
* Retrieves server identity.
* @returns {Promise<string>} The server identity.
* @throws {Error} If the API response is missing required values or if the login fails.
* @example <caption>Get server identity</caption>
* server.getServerIdentity().then(data => console.log(data));
*/
async getServerIdentity() {
const login = await this.#login();
if (login === true) {
const statusResponse = await this.#fetchJson('status');
if (typeof statusResponse?.server_identity === 'string') {
return statusResponse.server_identity;
} else {
throw new Error(this.#messages.missingServerIdentity);
}
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Retrieves the server version in both number and string representation.
* @returns {Promise<object>} An object containing the server version number and string.
* @throws {Error} If the API response is missing required values or if the login fails.
* @example <caption>Get server version number</caption>
* server.getServerVersion().then(data => console.log(data.number));
* @example <caption>Get server version string</caption>
* server.getServerVersion().then(data => console.log(data.string));
*/
async getServerVersion() {
const login = await this.#login();
if (login === true) {
const serverVersion = { number: 0, string: '' };
const statusResponse = await this.#fetchJson('status');
if (typeof statusResponse?.curr_version_num === 'number') {
serverVersion.number = statusResponse.curr_version_num;
} else {
throw new Error(this.#messages.missingValues);
}
if (typeof statusResponse?.curr_version_str === 'string') {
serverVersion.string = statusResponse.curr_version_str;
} else {
throw new Error(this.#messages.missingValues);
}
return serverVersion;
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Checks if the server version is outdated compared to the available version.
* @returns {Promise<boolean>} A promise that resolves to true if the server version is outdated, false otherwise.
* @throws {Error} If the API response is missing required values or if the login fails.
* @example
* server.isServerOutdated().then(isOutdated => console.log(isOutdated));
*/
async isServerOutdated() {
const login = await this.#login();
if (login === true) {
const serverVersion = await this.getServerVersion();
return this.#compareVersion(serverVersion.string, this.#constants.availableServerVersion);
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Retrieves a list of users.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing users. If no users are found, it returns an empty array.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get all users</caption>
* server.getUsers().then(data => console.log(data));
*/
async getUsers() {
const login = await this.#login();
if (login === true) {
const usersResponse = await this.#fetchJson('settings', { sa: 'listusers' });
if (Array.isArray(usersResponse?.users)) {
return usersResponse.users;
} else {
throw new Error(this.#messages.missingUserData);
}
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Adds a new user with the specified username, password, and rights.
* @param {object} params - An object containing parameters.
* @param {string} params.userName - The username for the new user.
* @param {string} params.password - The password for the new user.
* @param {boolean} [params.isAdmin=false] - Whether the new user should have admin rights (all domains, all rights). Defaults to false.
* @param {Array<object>} [params.rights] - Array of user permissions. Ignored if `isAdmin` is true. Defaults to the default user rights.
* @returns {Promise<boolean>} A promise that resolves to true if the user was added successfully, false otherwise.
* @throws {Error} If required parameters are missing, the login fails, or the API response is missing expected values.
* @example <caption>Add a regular user</caption>
* server.addUser({ userName: 'newUser', password: 'userPassword' }).then(result => console.log(result));
* @example <caption>Add an admin user</caption>
* server.addUser({ userName: 'adminUser', password: 'adminPassword', isAdmin: true }).then(result => console.log(result));
*/
async addUser({ userName, password, isAdmin = false, rights = this.#constants.defaultUserRights } = {}) {
if (typeof userName !== 'string' || userName.length === 0 || typeof password !== 'string' || password.length === 0) {
throw new Error(this.#messages.missingParameters);
}
const login = await this.#login();
if (login === true) {
// NOTE: Server expects an alphanumeric string (no special characters), hence an additional method is needed
const salt = this.#generateRandomString(50);
const response = await this.#fetchJson('settings', {
sa: 'useradd',
name: userName,
pwmd5: this.#hashPasswordMd5(salt, password),
salt: salt,
rights: this.#encodeUserRights(isAdmin ? this.#constants.adminUserRights : rights)
});
if ('add_ok' in response || 'alread_exists' in response) {
return response.add_ok === true;
} else {
throw new Error(this.#messages.missingValues);
}
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Removes a user by their user ID.
* @param {object} params - An object containing parameters.
* @param {number} params.userId - The ID of the user to be removed.
* @returns {Promise<boolean>} A promise that resolves to a boolean indicating whether the user was successfully removed.
* @throws {Error} If the `userId` parameter is missing or invalid, or if the login fails.
* @example <caption>Remove a user by their ID</caption>
* server.removeUser({ userId: 123 }).then(status => console.log(status));
*/
async removeUser({ userId } = {}) {
if (typeof userId !== 'number' || userId <= 0) {
throw new Error(this.#messages.missingParameters);
}
let operationStatus = false;
const login = await this.#login();
if (login === true) {
const users = await this.getUsers();
if (typeof users.find(user => user.id === userId.toString(10)) !== 'undefined') {
const response = await this.#fetchJson('settings', { sa: 'removeuser', userid: userId.toString(10) });
operationStatus = typeof response.users.find(user => user.id === userId.toString(10)) === 'undefined';
}
return operationStatus;
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Retrieves the rights of a specific user.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.userId] - The user's ID. Takes precedence if both `userId` and `userName` are defined. Required if `clientName` is undefined.
* @param {string} [params.userName=this.#username] - The user's name. Ignored if `userId` is defined. Defaults to the username of the current session. Required if `clientId` is undefined.
* @returns {Promise<Array|null>} A promise that resolves to an array of user rights, or null if the user is not found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get user rights of the current session user</caption>
* server.getUserRights().then(data => console.log(data));
* @example <caption>Get user rights by user ID</caption>
* server.getUserRights({ userId: '12345' }).then(data => console.log(data));
* @example <caption>Get user rights by user name</caption>
* server.getUserRights({ userName: 'john_doe' }).then(data => console.log(data));
*/
async getUserRights({ userId, userName = this.#username } = {}) {
const login = await this.#login();
if (login === true) {
const fallbackReturnValue = null;
const allUsers = await this.getUsers();
let userRights;
if (typeof userId === 'string') {
userRights = allUsers.find(user => user.id === userId)?.rights;
} else if (typeof userName === 'string') {
userRights = allUsers.find(user => user.name === userName)?.rights;
} else {
return fallbackReturnValue;
}
return Array.isArray(userRights) ? userRights : fallbackReturnValue;
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Retrieves a list of groups.
* By default, UrBackup clients are added to a group with ID 0 and an empty name (empty string).
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing groups. If no groups are found, it returns an empty array.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get all groups</caption>
* server.getGroups().then(data => console.log(data));
*/
async getGroups() {
const login = await this.#login();
if (login === true) {
const settingsResponse = await this.#fetchJson('settings');
if (Array.isArray(settingsResponse?.navitems?.groups)) {
return settingsResponse.navitems.groups;
} else {
throw new Error(this.#messages.missingGroupData);
}
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Adds a new group.
* @param {object} params - An object containing parameters.
* @param {string} params.groupName - The group name. Must be unique and cannot be an empty string.
* @returns {Promise<boolean>} When successful, returns true. If the group already exists, or adding the group was not successful for any reason, returns false.
* @throws {Error} If the groupName is missing or invalid, or if the API response is missing expected values.
* @example <caption>Add new group</caption>
* server.addGroup({ groupName: 'prod' }).then(data => console.log(data));
*/
async addGroup({ groupName } = {}) {
if (typeof groupName === 'undefined') {
throw new Error(this.#messages.missingParameters);
}
// NOTE: Fail early due to a possible UrBackup bug (server does not allow adding multiple groups with the same name,
// but allows '' (empty string) which is the same as default group name)
if (groupName === '') {
return false;
}
const login = await this.#login();
if (login === true) {
const response = await this.#fetchJson('settings', { sa: 'groupadd', name: groupName });
if ('add_ok' in response || 'already_exists' in response) {
return response?.add_ok === true;
} else {
throw new Error(this.#messages.missingGroupData);
}
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Removes a group.
* All clients in this group will be reassigned to the default group. Does not allow removal of the default group (ID: 0, name: '').
* @param {object} params - An object containing parameters.
* @param {number} [params.groupId] - Group ID. Must be greater than 0. Takes precedence if both `groupId` and `groupName` are defined. Required if `groupName` is undefined.
* @param {string} [params.groupName] - Group name. Must be different than '' (empty string). Ignored if both `groupId` and `groupName` are defined. Required if `groupId` is undefined.
* @returns {Promise<boolean>} When the removal is successful, the method returns true. If the removal is not successful, the method returns false.
* @throws {Error} If both `groupId` and `groupName` are missing or invalid, or if the login fails.
* @example <caption>Remove group</caption>
* server.removeGroup({ groupId: 1 }).then(data => console.log(data));
* server.removeGroup({ groupName: 'prod' }).then(data => console.log(data));
*/
async removeGroup({ groupId, groupName } = {}) {
if (typeof groupId === 'undefined' && typeof groupName === 'undefined') {
throw new Error(this.#messages.missingParameters);
}
if (groupId === 0 || groupName === '') {
return false;
}
const login = await this.#login();
if (login === true) {
let mappedGroupId;
if (typeof groupId === 'undefined') {
mappedGroupId = await this.#getGroupIdentifier(groupName, 'id');
if (mappedGroupId === 0 || mappedGroupId === null) {
return false;
}
} else {
// NOTE: Fail early due to a possible UrBackup bug where the server returns delete_ok:true even when
// attempting to delete a non-existent group ID
const mappedGroupName = await this.#getGroupIdentifier(groupId, 'name');
if (mappedGroupName === null) {
return false;
}
}
const response = await this.#fetchJson('settings', { sa: 'groupremove', id: groupId ?? mappedGroupId });
return response?.delete_ok === true;
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Retrieves a list of clients who are members of a given group.
* This is only a convenience method that wraps the `getClients()` method.
* @param {object} params - An object containing parameters.
* @param {number} [params.groupId] - Group ID. Ignored if both `groupId` and `groupName` are defined. Required if `groupName` is undefined.
* @param {string} [params.groupName] - Group name. Takes precedence if both `groupId` and `groupName` are defined. Required if `groupId` is undefined.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients matching the search criteria. Returns an empty array when no matching clients are found.
* @throws {Error} If both `groupId` and `groupName` are missing or invalid.
* @example <caption>Get members of default group</caption>
* server.getGroupMembers({ groupId: 0 }).then(data => console.log(data));
* @example <caption>Get all clients belonging to a specific group</caption>
* server.getGroupMembers({ groupName: 'office' }).then(data => console.log(data));
*/
async getGroupMembers({ groupId, groupName } = {}) {
if (typeof groupId === 'undefined' && typeof groupName === 'undefined') {
throw new Error(this.#messages.missingParameters);
}
const fallbackReturnValue = [];
let mappedGroupName;
if (typeof groupName === 'undefined') {
mappedGroupName = await this.#getGroupIdentifier(groupId, 'name');
if (mappedGroupName === null) {
return fallbackReturnValue;
}
}
const groupMembers = await this.getClients({ groupName: groupName ?? mappedGroupName });
return groupMembers;
}
/**
* Retrieves a list of clients.
* By default, this method matches all clients, including those marked for removal.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.groupName] - Group name. Defaults to undefined, which matches all groups.
* @param {boolean} [params.includeRemoved=true] - Whether or not clients pending deletion should be included. Defaults to true.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients matching the search criteria. Returns an empty array when no matching clients are found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get all clients</caption>
* server.getClients().then(data => console.log(data));
* @example <caption>Get all clients, but exclude clients marked for removal</caption>
* server.getClients({ includeRemoved: false }).then(data => console.log(data));
* @example <caption>Get all clients belonging to a specific group</caption>
* server.getClients({ groupName: 'office' }).then(data => console.log(data));
*/
async getClients({ groupName, includeRemoved = true } = {}) {
const clients = [];
const login = await this.#login();
if (login === true) {
const statusResponse = await this.#fetchJson('status');
if (Array.isArray(statusResponse?.status)) {
for (const client of statusResponse.status) {
if (typeof groupName === 'string' && groupName !== client.groupname) {
continue;
}
if (includeRemoved === false && client.delete_pending === '1') {
continue;
}
clients.push(client);
}
return clients;
} else {
throw new Error(this.#messages.missingClientData);
}
} else {
throw new Error(this.#messages.failedLoginUnknown);
}
}
/**
* Retrieves a list of clients marked for removal.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.groupName] - Group name. Defaults to undefined, which matches all groups.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients. Returns an empty array when no matching clients are found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get clients marked for removal</caption>
* server.getRemovedClients().then(data => console.log(data));
* @example <caption>Get clients marked for removal in a specific group</caption>
* server.getRemovedClients({ groupName: 'sales' }).then(data => console.log(data));
*/
async getRemovedClients({ groupName } = {}) {
return await this.getClients({ groupName, includeRemoved: true })
.then(removedClients => removedClients.filter(client => client.delete_pending === '1'));
}
/**
* Retrieves a list of online clients.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.groupName] - Group name. Defaults to undefined, which matches all groups.
* @param {boolean} [params.includeRemoved=true] - Whether or not clients pending deletion should be included. Defaults to true.
* @param {boolean} [params.includeBlank=true] - Whether or not blank clients should be taken into account when matching clients. Defaults to true.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients. Returns an empty array when no matching clients are found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get all online clients</caption>
* server.getOnlineClients().then(data => console.log(data));
* @example <caption>Get online clients from a specific group</caption>
* server.getOnlineClients({ groupName: 'servers' }).then(data => console.log(data));
*/
async getOnlineClients({ groupName, includeRemoved = true, includeBlank = true } = {}) {
const clients = await this.getClients({ groupName, includeRemoved });
const onlineClients = [];
clients.forEach(client => {
if (client.online === true) {
if (includeBlank === true) {
onlineClients.push(client);
} else {
if (this.#isBlankClient({ client, includeFileBackups: true, includeImageBackups: true }) === false) {
onlineClients.push(client);
}
}
}
});
return onlineClients;
}
/**
* Retrieves a list of offline clients.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.groupName] - Group name. Defaults to undefined, which matches all groups.
* @param {boolean} [params.includeRemoved=true] - Whether or not clients pending deletion should be included. Defaults to true.
* @param {boolean} [params.includeBlank=true] - Whether or not blank clients should be taken into account when matching clients. Defaults to true.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients. Returns an empty array when no matching clients are found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get all offline clients</caption>
* server.getOfflineClients().then(data => console.log(data));
* @example <caption>Get offline clients, skip clients marked for removal</caption>
* server.getOfflineClients({ includeRemoved: false }).then(data => console.log(data));
* @example <caption>Get offline clients from a specific groups</caption>
* server.getOfflineClients({ groupName: 'servers' }).then(data => console.log(data));
*/
async getOfflineClients({ groupName, includeRemoved = true, includeBlank = true } = {}) {
const clients = await this.getClients({ groupName, includeRemoved });
const offlineClients = [];
clients.forEach(client => {
if (client.online === false) {
if (includeBlank === true) {
offlineClients.push(client);
} else {
if (this.#isBlankClient({ client, includeFileBackups: true, includeImageBackups: true }) === false) {
offlineClients.push(client);
}
}
}
});
return offlineClients;
}
/**
* Retrieves a list of active clients.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.groupName] - Group name. Defaults to undefined, which matches all groups.
* @param {boolean} [params.includeRemoved=true] - Whether or not clients pending deletion should be included. Defaults to true.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients. Returns an empty array when no matching clients are found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get all active clients</caption>
* server.getActiveClients().then(data => console.log(data));
*/
async getActiveClients({ groupName, includeRemoved = true } = {}) {
return await this.getClients({ groupName, includeRemoved })
.then(activeClients => activeClients.filter(client => client.status !== 0));
}
/**
* Retrieves a list of blank clients, i.e., clients without any finished file and/or image backups.
* Matching empty clients considers whether file backups or image backups are enabled.
* By default, it matches clients without both file and image backups.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.groupName] - Group name. Defaults to undefined, which matches all groups.
* @param {boolean} [params.includeRemoved=true] - Whether or not clients pending deletion should be included. Defaults to true.
* @param {boolean} [params.includeFileBackups=true] - Whether or not file backups should be taken into account when matching clients. Defaults to true.
* @param {boolean} [params.includeImageBackups=true] - Whether or not image backups should be taken into account when matching clients. Defaults to true.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients. Returns an empty array when no matching clients are found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get all blank clients, i.e., clients without both file and image backups</caption>
* server.getBlankClients().then(data => console.log(data));
* @example <caption>Get blank clients, skip clients marked for removal</caption>
* server.getBlankClients({ includeRemoved: false }).then(data => console.log(data));
* @example <caption>Get clients without any file backups</caption>
* server.getBlankClients({ includeImageBackups: false }).then(data => console.log(data));
* @example <caption>Get clients without any image backups</caption>
* server.getBlankClients({ includeFileBackups: false }).then(data => console.log(data));
*/
async getBlankClients({ groupName, includeRemoved = true, includeFileBackups = true, includeImageBackups = true } = {}) {
const clients = await this.getClients({ groupName, includeRemoved });
const blankClients = [];
clients.forEach(client => {
if (this.#isBlankClient({ client, includeFileBackups, includeImageBackups }) === true) {
blankClients.push(client);
}
});
return blankClients;
}
/**
* Retrieves a list of failed clients, i.e., clients with failed backup status.
* @param {object} [params] - An optional object containing parameters.
* @param {string} [params.groupName] - Group name. Defaults to undefined, which matches all groups.
* @param {boolean} [params.includeRemoved=true] - Whether or not clients pending deletion should be included. Defaults to true.
* @param {boolean} [params.includeBlank=true] - Whether or not blank clients should be taken into account when matching clients. Defaults to true.
* @param {boolean} [params.includeFileBackups=true] - Whether or not file backups should be taken into account when matching clients. Defaults to true.
* @param {boolean} [params.includeImageBackups=true] - Whether or not image backups should be taken into account when matching clients. Defaults to true.
* @param {boolean} [params.failOnFileIssues=false] - Whether or not to treat file backups finished with issues as being failed. Defaults to false.
* @returns {Promise<Array<object>>} A promise that resolves to an array of objects representing clients. Returns an empty array when no matching clients are found.
* @throws {Error} If the login fails or the API response is missing expected values.
* @example <caption>Get clients with failed file or image backups</caption>
* server.getFailedClients().then(data => console.log(data));
* @example <caption>Get failed clients, skip clients marked for removal</caption>
* server.getFailedClients({ includeRemoved: false }).then(data => console.log(data));
* @example <caption>Get clients with failed file backups</caption>
* server.getFailedClients({ includeImageBackups: false }).then(data => console.log(data));
* @example <caption>Get clients with failed image backups</caption>
* server.getFailedClients({ includeFileBackups: false }).then(data => console.log(data));
*/
async getFailedClients({ groupName, includeRemoved = true, includeBlank = true, includeFileBackups = true, includeImageBackups = true, failOnFileIssues = false } = {}) {
const clients = await this.getClients({ groupName, includeRemoved });
const failedClients = [];
for (const client of clients) {
if (this.#isFailedClient({ client, includeFileBackups, includeImageBackups, failOnFileIssues }) === true) {
if (includeBlank === true) {
failedClients.push(client);
continue;
} else {
if (this.#isBlankClient({ client, includeFileBackups, includeImageBackups }) === false) {
failedClients.push(client);
continue;
}
}
}
}