forked from multisynq/synchronizer-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·6340 lines (5464 loc) · 234 KB
/
index.js
File metadata and controls
executable file
·6340 lines (5464 loc) · 234 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
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
#!/usr/bin/env node
const { Command } = require('commander');
const inquirer = require('inquirer');
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const os = require('os');
const { spawn, execSync } = require('child_process');
const express = require('express');
const packageJson = require('./package.json');
const fetch = require('node-fetch'); // Add node-fetch for API validation
const WebSocket = require('ws'); // Add WebSocket for real-time container communication
const program = new Command();
const CONFIG_DIR = path.join(os.homedir(), '.synchronizer-cli');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
const POINTS_FILE = path.join(CONFIG_DIR, 'points.json');
// Cache file for wallet points API responses
const CACHE_FILE = path.join(CONFIG_DIR, 'wallet-points-cache.json');
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds for successful responses
const ERROR_CACHE_DURATION = 30 * 1000; // 30 seconds for error responses
// Global variable to store WebSocket connection and latest data
let containerWebSocket = null;
let latestContainerData = null;
let wsConnectionAttempts = 0;
const MAX_WS_RECONNECT_ATTEMPTS = 5;
let wsInitialized = false; // Flag to ensure we only try to connect once
// Global rate limiting and caching for ALL stats requests
let lastStatsRequestTime = 0;
let lastStatsResult = null;
let statsRequestInProgress = null; // Promise to prevent race conditions
const STATS_REQUEST_COOLDOWN = 60 * 1000; // 60 seconds between ANY stats requests (once a minute as requested)
const STATS_CACHE_DURATION = 60 * 1000; // Cache results for 60 seconds (once a minute as requested)
// Global WebSocket connection management
let wsConnectionInProgress = false;
let lastWebSocketRequestTime = 0;
const WS_REQUEST_COOLDOWN = 10 * 1000; // Only allow WebSocket requests every 10 seconds
// Global caching for all dashboard data to prevent redundant requests
let globalCache = {
performance: { data: null, timestamp: 0 },
points: { data: null, timestamp: 0 },
status: { data: null, timestamp: 0 }
};
const DASHBOARD_CACHE_DURATION = 30 * 1000; // Cache dashboard data for 30 seconds
function loadConfig() {
if (fs.existsSync(CONFIG_FILE)) {
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
}
return {};
}
function saveConfig(config) {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
}
function loadPointsData() {
if (fs.existsSync(POINTS_FILE)) {
try {
return JSON.parse(fs.readFileSync(POINTS_FILE, 'utf8'));
} catch (error) {
console.log('Error loading points data, starting fresh:', error.message);
return createEmptyPointsData();
}
}
return createEmptyPointsData();
}
function savePointsData(pointsData) {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
fs.writeFileSync(POINTS_FILE, JSON.stringify(pointsData, null, 2));
}
function createEmptyPointsData() {
return {
totalLifetimePoints: 0,
sessions: [],
lastUpdated: new Date().toISOString(),
version: '1.0'
};
}
function authenticateRequest(req, res, next) {
const config = loadConfig();
// If no password is set, allow access
if (!config.dashboardPassword) {
return next();
}
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Basic ')) {
res.setHeader('WWW-Authenticate', 'Basic realm="Synchronizer Dashboard"');
res.status(401).send('Authentication required');
return;
}
const credentials = Buffer.from(auth.slice(6), 'base64').toString();
const [username, password] = credentials.split(':');
// Simple authentication - username can be anything, password must match
if (password === config.dashboardPassword) {
req.authenticated = true;
return next();
}
res.setHeader('WWW-Authenticate', 'Basic realm="Synchronizer Dashboard"');
res.status(401).send('Invalid credentials');
}
function generateSyncHash(userName, secret, hostname) {
const input = `${userName || ''}:${hostname}:${secret}`;
const hash = crypto.createHash('sha256').update(input).digest('hex');
return `synq-${hash.slice(0, 12)}`;
}
function detectNpxPath() {
try {
// Try to find npx using 'which' command
const npxPath = execSync('which npx', { encoding: 'utf8', stdio: 'pipe' }).trim();
if (npxPath && fs.existsSync(npxPath)) {
return npxPath;
}
} catch (error) {
// 'which' failed, try other methods
}
try {
// Try to find npm and assume npx is in the same directory
const npmPath = execSync('which npm', { encoding: 'utf8', stdio: 'pipe' }).trim();
if (npmPath) {
const npxPath = npmPath.replace(/npm$/, 'npx');
if (fs.existsSync(npxPath)) {
return npxPath;
}
}
} catch (error) {
// npm not found either
}
// Common fallback locations
const fallbackPaths = [
'/usr/bin/npx',
'/usr/local/bin/npx',
'/opt/homebrew/bin/npx',
path.join(os.homedir(), '.npm-global/bin/npx'),
path.join(os.homedir(), '.nvm/current/bin/npx')
];
for (const fallbackPath of fallbackPaths) {
if (fs.existsSync(fallbackPath)) {
return fallbackPath;
}
}
// Last resort - assume it's in PATH
return 'npx';
}
/**
* Check if a new Docker image is available by comparing local and remote digests
* @param {string} imageName Docker image name with tag
* @returns {Promise<boolean>} True if new image is available or no local image exists
*/
async function isNewDockerImageAvailable(imageName) {
try {
// Check if we have the image locally
try {
const localImageCmd = `docker images ${imageName} --format "{{.ID}}"`;
const localImageId = execSync(localImageCmd, { encoding: 'utf8', stdio: 'pipe' }).trim();
// If there's no local image, we need to pull
if (!localImageId) {
return true;
}
} catch (error) {
// No local image found
return true;
}
// For now, we'll use a simpler approach:
// Always pull with --pull always flag when starting containers
// This lets Docker handle the logic of whether to actually download
// Return false to avoid duplicate pulling attempts
return false;
} catch (error) {
// On any error, assume we should try to pull
return true;
}
}
/**
* Validate synq key format using regex pattern
* Checks if the key is a valid UUID v4 format
* @param {string} key The synq key to validate
* @returns {boolean} True if the key format is valid
*/
function validateSynqKeyFormat(key) {
return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i.test(key);
}
/**
* Check if a synq key is valid by calling the remote API
* @param {string} key The synq key to check
* @param {string} nickname Optional nickname for the synchronizer
* @returns {Promise<{isValid: boolean, message: string}>} Result object with validation status and message
*/
async function validateSynqKeyWithAPI(key, nickname = '') {
const DOMAIN = 'multisynq.io';
const SYNQ_KEY_URL = `https://api.${DOMAIN}/depin/synchronizers/key`;
// If no nickname is provided, use a default one to prevent the "missing synchronizer name" error
const syncNickname = nickname || 'cli-validator';
const url = `${SYNQ_KEY_URL}/${key}/precheck?nickname=${encodeURIComponent(syncNickname)}`;
console.log(chalk.gray(`Validating synq key with remote API...`));
try {
const response = await fetch(url);
const keyStatus = await response.text();
if (keyStatus === 'ok') {
return { isValid: true, message: 'Key is valid and available' };
} else {
return { isValid: false, message: keyStatus };
}
} catch (error) {
return {
isValid: false,
message: `Could not validate key with API: ${error.message}. Will proceed with local validation only.`
};
}
}
async function init() {
const questions = [];
questions.push({
type: 'input',
name: 'userName',
message: 'Optional sync name (for your reference only):',
default: ''
});
// Get the userName first
const userNameAnswer = await inquirer.prompt([questions[0]]);
const userName = userNameAnswer.userName;
// Then use it when validating the key
const keyQuestion = {
type: 'input',
name: 'key',
message: 'Synq key:',
validate: async (input) => {
if (!input) return 'Synq key is required';
// First validate the format locally
if (!validateSynqKeyFormat(input)) {
return 'Invalid synq key format. Must be a valid UUID v4 format (XXXXXXXX-XXXX-4XXX-YXXX-XXXXXXXXXXXX where Y is 8, 9, A, or B)';
}
// If local validation passes, try remote validation with the userName
try {
// Use the userName or a default nickname
const nickname = userName || 'cli-setup';
const validationResult = await validateSynqKeyWithAPI(input, nickname);
if (!validationResult.isValid) {
// If API returns an error specific to the key, show it
if (validationResult.message.includes('Key')) {
return validationResult.message;
}
// For network errors, we'll accept the key if it passed format validation
console.log(chalk.yellow(`⚠️ ${validationResult.message}`));
console.log(chalk.yellow('Continuing with local validation only.'));
} else {
console.log(chalk.green('✅ Key validated successfully with API'));
}
return true;
} catch (error) {
// If API validation fails for any reason, accept the key if it passed format validation
console.log(chalk.yellow(`⚠️ API validation error: ${error.message}`));
console.log(chalk.yellow('Continuing with local validation only.'));
return true;
}
}
};
// Add the key question and wallet question
const remainingQuestions = [
keyQuestion,
{
type: 'input',
name: 'wallet',
message: 'Wallet address:',
validate: input => input ? true : 'Wallet is required',
},
{
type: 'confirm',
name: 'setDashboardPassword',
message: 'Set a password for the web dashboard? (Recommended for security):',
default: true
}
];
// Get answers for the remaining questions
const remainingAnswers = await inquirer.prompt(remainingQuestions);
// Combine all answers
const answers = {
...userNameAnswer,
...remainingAnswers
};
// Ask for password if user wants to set one
if (answers.setDashboardPassword) {
const passwordQuestions = [{
type: 'password',
name: 'dashboardPassword',
message: 'Dashboard password:',
validate: input => input && input.length >= 4 ? true : 'Password must be at least 4 characters',
mask: '*'
}];
const passwordAnswers = await inquirer.prompt(passwordQuestions);
answers.dashboardPassword = passwordAnswers.dashboardPassword;
}
const secret = crypto.randomBytes(8).toString('hex');
const hostname = os.hostname();
const syncHash = generateSyncHash(answers.userName, secret, hostname);
const config = {
...answers,
secret,
hostname,
syncHash,
depin: 'wss://api.multisynq.io/depin',
launcher: 'cli'
};
// Remove the setDashboardPassword flag from config
delete config.setDashboardPassword;
saveConfig(config);
console.log(chalk.green('Configuration saved to'), CONFIG_FILE);
if (config.dashboardPassword) {
console.log(chalk.yellow('🔒 Dashboard password protection enabled'));
console.log(chalk.gray('Use any username with your password to access the web dashboard'));
} else {
console.log(chalk.yellow('⚠️ Dashboard is unprotected - synq key will be visible to anyone'));
}
}
function checkDocker() {
try {
execSync('docker --version', { stdio: 'ignore' });
return true;
} catch (error) {
return false;
}
}
async function installDocker() {
const platform = os.platform();
console.log(chalk.blue('🐳 Docker Installation Helper'));
console.log(chalk.yellow('This will help you install Docker on your system.\n'));
if (platform === 'linux') {
const distro = await detectLinuxDistro();
console.log(chalk.cyan(`Detected Linux distribution: ${distro}`));
const confirm = await inquirer.prompt([{
type: 'confirm',
name: 'install',
message: 'Would you like to install Docker automatically?',
default: true
}]);
if (confirm.install) {
await installDockerLinux(distro);
} else {
showManualInstructions(platform);
}
} else {
console.log(chalk.yellow(`Automatic installation not supported on ${platform}.`));
showManualInstructions(platform);
}
}
async function detectLinuxDistro() {
try {
const release = fs.readFileSync('/etc/os-release', 'utf8');
if (release.includes('ubuntu') || release.includes('Ubuntu')) return 'ubuntu';
if (release.includes('debian') || release.includes('Debian')) return 'debian';
if (release.includes('centos') || release.includes('CentOS')) return 'centos';
if (release.includes('rhel') || release.includes('Red Hat')) return 'rhel';
if (release.includes('fedora') || release.includes('Fedora')) return 'fedora';
return 'unknown';
} catch (error) {
return 'unknown';
}
}
async function installDockerLinux(distro) {
console.log(chalk.blue('Installing Docker...'));
try {
if (distro === 'ubuntu' || distro === 'debian') {
console.log(chalk.cyan('Updating package index...'));
execSync('sudo apt-get update', { stdio: 'inherit' });
console.log(chalk.cyan('Installing prerequisites...'));
execSync('sudo apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release', { stdio: 'inherit' });
console.log(chalk.cyan('Adding Docker GPG key...'));
execSync('curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg', { stdio: 'inherit' });
console.log(chalk.cyan('Adding Docker repository...'));
const arch = execSync('dpkg --print-architecture', { encoding: 'utf8' }).trim();
const codename = execSync('lsb_release -cs', { encoding: 'utf8' }).trim();
execSync(`echo "deb [arch=${arch} signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu ${codename} stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null`, { stdio: 'inherit' });
console.log(chalk.cyan('Installing Docker...'));
execSync('sudo apt-get update', { stdio: 'inherit' });
execSync('sudo apt-get install -y docker-ce docker-ce-cli containerd.io', { stdio: 'inherit' });
} else if (distro === 'centos' || distro === 'rhel' || distro === 'fedora') {
console.log(chalk.cyan('Installing Docker via yum/dnf...'));
const installer = distro === 'fedora' ? 'dnf' : 'yum';
execSync(`sudo ${installer} install -y yum-utils`, { stdio: 'inherit' });
execSync(`sudo ${installer}-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo`, { stdio: 'inherit' });
execSync(`sudo ${installer} install -y docker-ce docker-ce-cli containerd.io`, { stdio: 'inherit' });
}
console.log(chalk.cyan('Starting Docker service...'));
execSync('sudo systemctl start docker', { stdio: 'inherit' });
execSync('sudo systemctl enable docker', { stdio: 'inherit' });
console.log(chalk.cyan('Adding user to docker group...'));
const username = os.userInfo().username;
execSync(`sudo usermod -aG docker ${username}`, { stdio: 'inherit' });
console.log(chalk.green('✅ Docker installed successfully!'));
console.log(chalk.yellow('⚠️ You may need to log out and log back in for group changes to take effect.'));
console.log(chalk.blue('You can test Docker with: docker run hello-world'));
} catch (error) {
console.error(chalk.red('❌ Failed to install Docker automatically.'));
console.error(chalk.red('Error:', error.message));
showManualInstructions('linux');
}
}
function showManualInstructions(platform) {
console.log(chalk.blue('\n📖 Manual Installation Instructions:'));
if (platform === 'linux') {
console.log(chalk.white('For Ubuntu/Debian:'));
console.log(chalk.gray(' curl -fsSL https://get.docker.com -o get-docker.sh'));
console.log(chalk.gray(' sudo sh get-docker.sh'));
console.log(chalk.white('\nFor CentOS/RHEL/Fedora:'));
console.log(chalk.gray(' sudo yum install -y docker-ce'));
console.log(chalk.gray(' sudo systemctl start docker'));
} else if (platform === 'darwin') {
console.log(chalk.white('For macOS:'));
console.log(chalk.gray(' Download Docker Desktop from: https://docs.docker.com/desktop/mac/install/'));
console.log(chalk.gray(' Or install via Homebrew: brew install --cask docker'));
} else if (platform === 'win32') {
console.log(chalk.white('For Windows:'));
console.log(chalk.gray(' Download Docker Desktop from: https://docs.docker.com/desktop/windows/install/'));
}
console.log(chalk.blue('\nFor more details: https://docs.docker.com/get-docker/'));
}
async function start() {
const config = loadConfig();
if (!config.key) {
console.error(chalk.red('Missing synq key. Run `synchronize init` first.'));
process.exit(1);
}
if (config.hostname !== os.hostname()) {
console.error(chalk.red(`This config was created for ${config.hostname}, not ${os.hostname()}.`));
process.exit(1);
}
// Check if Docker is installed
if (!checkDocker()) {
console.error(chalk.red('Docker is not installed or not accessible.'));
const shouldInstall = await inquirer.prompt([{
type: 'confirm',
name: 'install',
message: 'Would you like to install Docker now?',
default: true
}]);
if (shouldInstall.install) {
await installDocker();
// Check again after installation
if (!checkDocker()) {
console.error(chalk.red('Docker installation may have failed or requires a restart.'));
console.error(chalk.yellow('Please try running the command again after restarting your terminal.'));
process.exit(1);
}
} else {
console.error(chalk.yellow('Please install Docker first: https://docs.docker.com/get-docker/'));
process.exit(1);
}
}
const syncName = config.syncHash;
const containerName = 'synchronizer-cli';
// Check if container is already running
try {
const runningContainers = execSync(`docker ps --filter name=${containerName} --format "{{.Names}}"`, {
encoding: 'utf8',
stdio: 'pipe'
});
if (runningContainers.includes(containerName)) {
console.log(chalk.green(`✅ Found existing synchronizer container running`));
console.log(chalk.cyan(`🔗 Connecting to logs... (Ctrl+C will stop the container)`));
// Connect to the existing container's logs
const logProc = spawn('docker', ['logs', '-f', containerName], { stdio: 'inherit' });
// Handle Ctrl+C to stop the container
const cleanup = () => {
console.log(chalk.yellow('\n🛑 Stopping synchronizer container...'));
try {
execSync(`docker stop ${containerName}`, { stdio: 'pipe' });
console.log(chalk.green('✅ Container stopped'));
} catch (error) {
console.log(chalk.red('❌ Error stopping container:', error.message));
}
process.exit(0);
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
logProc.on('exit', (code) => {
process.exit(code);
});
return;
}
} catch (error) {
// No existing container, continue with normal startup
}
// Detect platform architecture
const arch = os.arch();
const platform = os.platform();
let dockerPlatform = 'linux/amd64'; // Default to amd64
if (platform === 'linux') {
if (arch === 'arm64' || arch === 'aarch64') {
dockerPlatform = 'linux/arm64';
} else if (arch === 'x64' || arch === 'x86_64') {
dockerPlatform = 'linux/amd64';
}
} else if (platform === 'darwin') {
dockerPlatform = arch === 'arm64' ? 'linux/arm64' : 'linux/amd64';
}
console.log(chalk.blue(`Detected platform: ${platform}/${arch} -> Using Docker platform: ${dockerPlatform}`));
// Use the main synchronizer image
const imageName = 'cdrakep/synqchronizer:latest';
// Get dynamic version info for launcher
let dockerImageVersion = 'latest';
try {
// Try to get the version from the image we're about to use
const imageInspectOutput = execSync(`docker inspect ${imageName} --format "{{json .Config.Labels}}"`, {
encoding: 'utf8',
stdio: 'pipe'
});
const labels = JSON.parse(imageInspectOutput);
if (labels && labels.version) {
dockerImageVersion = labels.version;
} else {
// Get image creation date as fallback
const createdOutput = execSync(`docker inspect ${imageName} --format "{{.Created}}"`, {
encoding: 'utf8',
stdio: 'pipe'
});
const created = new Date(createdOutput.trim());
dockerImageVersion = `${created.toISOString().split('T')[0]}`;
}
} catch (error) {
// Use latest as fallback
dockerImageVersion = 'latest';
}
// Set launcher with dynamic version
const launcherWithVersion = `cli-${packageJson.version}/docker-${dockerImageVersion}`;
console.log(chalk.cyan(`Using launcher identifier: ${launcherWithVersion}`));
// Check if we need to pull the latest Docker image
const shouldPull = await isNewDockerImageAvailable(imageName);
// Pull the latest image only if necessary
if (shouldPull) {
console.log(chalk.cyan('Pulling latest Docker image...'));
try {
execSync(`docker pull ${imageName}`, {
stdio: ['ignore', 'pipe', 'pipe']
});
console.log(chalk.green('✅ Docker image pulled successfully'));
} catch (error) {
console.log(chalk.yellow('⚠️ Could not pull latest image - will use local cache if available'));
console.log(chalk.gray(error.message));
}
}
// Create Docker command
const dockerCmd = 'docker';
const args = [
'run', '--rm', '--name', containerName,
'--pull', 'always', // Always try to pull the latest image
'--platform', dockerPlatform,
'-p', '3333:3333', // Expose WebSocket CLI port
'-p', '9090:9090', // Expose HTTP metrics port
imageName
];
// Add container arguments correctly - each flag and value as separate items
if (config.depin) {
args.push('--depin');
args.push(config.depin);
} else {
args.push('--depin');
args.push('wss://api.multisynq.io/depin');
}
args.push('--sync-name');
args.push(syncName);
args.push('--launcher');
args.push(launcherWithVersion);
args.push('--key');
args.push(config.key);
if (config.wallet) {
args.push('--wallet');
args.push(config.wallet);
}
if (config.account) {
args.push('--account');
args.push(config.account);
}
console.log(chalk.cyan(`Running synchronizer "${syncName}" with wallet ${config.wallet || '[none]'}`));
// For debugging
console.log(chalk.gray(`Running command: ${dockerCmd} ${args.join(' ')}`));
const proc = spawn(dockerCmd, args, { stdio: 'inherit' });
// Handle Ctrl+C to stop the container
const cleanup = () => {
console.log(chalk.yellow('\n🛑 Stopping synchronizer container...'));
try {
execSync(`docker stop ${containerName}`, { stdio: 'pipe' });
console.log(chalk.green('✅ Container stopped'));
} catch (error) {
console.log(chalk.red('❌ Error stopping container:', error.message));
}
process.exit(0);
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
proc.on('error', (err) => {
if (err.code === 'ENOENT') {
console.error(chalk.red('Docker command not found. Please ensure Docker is installed and in your PATH.'));
} else {
console.error(chalk.red('Error running Docker:'), err.message);
}
process.exit(1);
});
proc.on('exit', code => {
if (code === 126) {
console.error(chalk.red('❌ Docker permission denied.'));
console.error(chalk.yellow('This usually means your user is not in the docker group.'));
console.error(chalk.blue('\n🔧 To fix this:'));
console.error(chalk.white('1. Add your user to the docker group:'));
console.error(chalk.gray(` sudo usermod -aG docker ${os.userInfo().username}`));
console.error(chalk.white('2. Log out and log back in (or restart your terminal)'));
console.error(chalk.white('3. Test with: docker run hello-world'));
console.error(chalk.blue('\n💡 Alternative: Run with sudo (not recommended):'));
console.error(chalk.gray(' sudo synchronize start'));
console.error(chalk.blue('\n🔧 Or use the fix command:'));
console.error(chalk.gray(' synchronize fix-docker'));
} else if (code === 125) {
console.error(chalk.red('❌ Docker container failed to start.'));
console.error(chalk.yellow('This might be due to platform architecture issues.'));
console.error(chalk.blue('\n🔧 Troubleshooting steps:'));
console.error(chalk.gray('1. Test platform compatibility:'));
console.error(chalk.gray(' synchronize test-platform'));
console.error(chalk.gray('2. Check Docker logs:'));
console.error(chalk.gray(' docker logs synchronizer-cli'));
console.error(chalk.gray('3. Try running with different platform:'));
console.error(chalk.gray(' docker run --platform linux/amd64 cdrakep/synqchronizer:latest --help'));
} else if (code !== 0) {
console.error(chalk.red(`Docker process exited with code ${code}`));
}
process.exit(code);
});
}
/**
* Generate systemd service file and environment file for headless operation.
*/
async function installService() {
const config = loadConfig();
if (!config.key) {
console.error(chalk.red('Missing synq key. Run `synchronize init` first.'));
process.exit(1);
}
if (!config.wallet && !config.account) {
console.error(chalk.red('Missing wallet or account. Run `synchronize init` first.'));
process.exit(1);
}
const serviceFile = path.join(CONFIG_DIR, 'synchronizer-cli.service');
const user = os.userInfo().username;
// Detect platform architecture (same logic as start function)
const arch = os.arch();
const platform = os.platform();
let dockerPlatform = 'linux/amd64'; // Default to amd64
if (platform === 'linux') {
if (arch === 'arm64' || arch === 'aarch64') {
dockerPlatform = 'linux/arm64';
} else if (arch === 'x64' || arch === 'x86_64') {
dockerPlatform = 'linux/amd64';
}
} else if (platform === 'darwin') {
dockerPlatform = arch === 'arm64' ? 'linux/arm64' : 'linux/amd64';
}
// Detect Docker path for PATH environment
let dockerPath = '/usr/bin/docker';
try {
const dockerWhich = execSync('which docker', { encoding: 'utf8', stdio: 'pipe' }).trim();
if (dockerWhich && fs.existsSync(dockerWhich)) {
dockerPath = dockerWhich;
}
} catch (error) {
// Use default path
}
const dockerDir = path.dirname(dockerPath);
// Build PATH environment variable including docker directory
const systemPaths = [
'/usr/local/sbin',
'/usr/local/bin',
'/usr/sbin',
'/usr/bin',
'/sbin',
'/bin'
];
// Add docker directory to the beginning of PATH if it's not already a system path
const pathDirs = systemPaths.includes(dockerDir) ? systemPaths : [dockerDir, ...systemPaths];
const pathEnv = pathDirs.join(':');
// Get dynamic version info for service launcher
let dockerImageVersion = 'latest';
try {
// Try to get the version from the main image
const imageName = 'cdrakep/synqchronizer:latest';
const imageInspectOutput = execSync(`docker inspect ${imageName} --format "{{json .Config.Labels}}"`, {
encoding: 'utf8',
stdio: 'pipe'
});
const labels = JSON.parse(imageInspectOutput);
if (labels && labels.version) {
dockerImageVersion = labels.version;
} else {
// Get image creation date as fallback
const createdOutput = execSync(`docker inspect ${imageName} --format "{{.Created}}"`, {
encoding: 'utf8',
stdio: 'pipe'
});
const created = new Date(createdOutput.trim());
dockerImageVersion = `${created.toISOString().split('T')[0]}`;
}
} catch (error) {
// Use latest as fallback
dockerImageVersion = 'latest';
}
// Set launcher with dynamic version
const launcherWithVersion = `cli-${packageJson.version}/docker-${dockerImageVersion}`;
console.log(chalk.cyan(`Using launcher identifier: ${launcherWithVersion}`));
// No need to check for image updates here - the service will use --pull always
// Build the exact same command as the start function
const dockerArgs = [
'run', '--rm', '--name', 'synchronizer-cli',
'--pull', 'always', // Always try to pull the latest image
'--platform', dockerPlatform,
'cdrakep/synqchronizer:latest',
'--depin', config.depin || 'wss://api.multisynq.io/depin',
'--sync-name', config.syncHash,
'--launcher', launcherWithVersion,
'--key', config.key,
...(config.wallet ? ['--wallet', config.wallet] : []),
...(config.account ? ['--account', config.account] : [])
].join(' ');
const unit = `[Unit]
Description=Multisynq Synchronizer headless service
After=docker.service
Requires=docker.service
[Service]
Type=simple
User=${user}
Restart=always
RestartSec=10
ExecStart=${dockerPath} ${dockerArgs}
Environment=PATH=${pathEnv}
[Install]
WantedBy=multi-user.target
`;
fs.writeFileSync(serviceFile, unit);
console.log(chalk.green('Systemd service file written to'), serviceFile);
console.log(chalk.blue(`To install the service, run:
sudo cp ${serviceFile} /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable synchronizer-cli
sudo systemctl start synchronizer-cli`));
console.log(chalk.cyan('\n📋 Service will run with the following configuration:'));
console.log(chalk.gray(`Platform: ${dockerPlatform}`));
console.log(chalk.gray(`Docker Path: ${dockerPath}`));
console.log(chalk.gray(`PATH: ${pathEnv}`));
console.log(chalk.gray(`DePIN: ${config.depin || 'wss://api.multisynq.io/depin'}`));
console.log(chalk.gray(`Sync Name: ${config.syncHash}`));
console.log(chalk.gray(`Wallet: ${config.wallet || '[none]'}`));
console.log(chalk.gray(`Account: ${config.account || '[none]'}`));
}
async function fixDockerPermissions() {
console.log(chalk.blue('🔧 Docker Permissions Fix'));
console.log(chalk.yellow('This will add your user to the docker group.\n'));
const username = os.userInfo().username;
try {
console.log(chalk.cyan(`Adding user "${username}" to docker group...`));
execSync(`sudo usermod -aG docker ${username}`, { stdio: 'inherit' });
console.log(chalk.green('✅ User added to docker group successfully!'));
console.log(chalk.yellow('⚠️ You need to log out and log back in for changes to take effect.'));
console.log(chalk.blue('\n🧪 To test after logging back in:'));
console.log(chalk.gray(' docker run hello-world'));
console.log(chalk.gray(' synchronize start'));
} catch (error) {
console.error(chalk.red('❌ Failed to add user to docker group.'));
console.error(chalk.red('Error:', error.message));
console.error(chalk.blue('\n📖 Manual steps:'));
console.error(chalk.gray(` sudo usermod -aG docker ${username}`));
console.error(chalk.gray(' # Then log out and log back in'));
}
}
async function testPlatform() {
console.log(chalk.blue('🔍 Platform Compatibility Test'));
console.log(chalk.yellow('Testing Docker platform compatibility...\n'));
const arch = os.arch();
const platform = os.platform();
console.log(chalk.cyan(`Host System: ${platform}/${arch}`));
// Test Docker availability
if (!checkDocker()) {
console.error(chalk.red('❌ Docker is not available'));
return;
}
console.log(chalk.green('✅ Docker is available'));
// Test both platforms and fallback
const tests = [
{ name: 'linux/amd64', args: ['--platform', 'linux/amd64'] },
{ name: 'linux/arm64', args: ['--platform', 'linux/arm64'] },
{ name: 'no platform flag', args: [] }
];
let workingPlatforms = [];
for (const test of tests) {
console.log(chalk.blue(`\nTesting ${test.name}...`));
try {
const args = [
'run', '--rm',
...test.args,
'cdrakep/synqchronizer:latest',
'--help'
];
const result = execSync(`docker ${args.join(' ')}`, {
encoding: 'utf8',
timeout: 30000,
stdio: 'pipe'
});
if (result.includes('Usage:') || result.includes('--help')) {
console.log(chalk.green(`✅ ${test.name} works`));
workingPlatforms.push(test.name);
} else {
console.log(chalk.yellow(`⚠️ ${test.name} responded but output unexpected`));
}
} catch (error) {
const errorMsg = error.message.split('\n')[0];
console.log(chalk.red(`❌ ${test.name} failed: ${errorMsg}`));
}
}
// Recommend best platform
let recommendedPlatform = 'linux/amd64';
if (arch === 'arm64' || arch === 'aarch64') {
recommendedPlatform = 'linux/arm64';
}
console.log(chalk.blue(`\n💡 Recommended platform for your system: ${recommendedPlatform}`));
if (workingPlatforms.length === 0) {
console.log(chalk.red('\n❌ No platforms are working!'));
console.log(chalk.yellow('This suggests the Docker image may not support your architecture.'));
console.log(chalk.blue('\n🔧 Troubleshooting steps:'));
console.log(chalk.gray('1. Check what platforms the image supports:'));
console.log(chalk.gray(' docker manifest inspect cdrakep/synqchronizer:latest'));
console.log(chalk.gray('2. Try pulling the image manually:'));
console.log(chalk.gray(' docker pull cdrakep/synqchronizer:latest'));
console.log(chalk.gray('3. Check if there are architecture-specific tags:'));
console.log(chalk.gray(' docker search cdrakep/synqchronizer'));
console.log(chalk.gray('4. Contact the image maintainer for multi-arch support'));
} else {
console.log(chalk.green(`\n✅ Working platforms: ${workingPlatforms.join(', ')}`));
console.log(chalk.gray('synchronize start will try these platforms automatically'));
}
}
async function showStatus() {
console.log(chalk.blue('🔍 synchronizer Service Status'));
console.log(chalk.yellow('Checking systemd service status...\n'));
try {
// Check if service file exists
const serviceExists = fs.existsSync('/etc/systemd/system/synchronizer-cli.service');
if (!serviceExists) {
console.log(chalk.yellow('⚠️ Systemd service not installed'));
console.log(chalk.gray('Run `synchronize service` to generate the service file'));
return;