-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
3782 lines (3437 loc) · 162 KB
/
main.js
File metadata and controls
3782 lines (3437 loc) · 162 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
const { app, BrowserWindow, ipcMain, dialog, shell, Tray, Menu, nativeImage } = require('electron'); // safeStorage intentionally excluded — causes fatal BAD_DECRYPT crash on Electron 40+ Windows
// Set app identity at the very top — must be before app is ready for correct Windows taskbar icon
if (process.platform === 'win32') app.setAppUserModelId('com.craftdock.launcher');
app.setName('CraftDock');
const path = require('path');
const fs = require('fs');
const https = require('https');
const zlib = require('zlib');
// All data lives in craftdock-data/ next to the launcher so users can find it easily
const isDev = !app.isPackaged;
const appRoot = isDev ? __dirname : path.dirname(app.getPath('exe'));
const dataRoot = path.join(appRoot, 'craftdock-data');
const skinsDir = path.join(dataRoot, 'skins');
const dataDir = path.join(dataRoot, 'data');
const serversBase = path.join(dataRoot, 'servers');
const instancesBase = path.join(dataRoot, 'instances');
const sharedWorldsDir = path.join(dataRoot, 'shared-worlds');
const sharedServersDir = path.join(dataRoot, 'shared-servers');
const sharedResourcesDir = path.join(dataRoot, 'shared-resources');
[skinsDir, dataDir, serversBase, instancesBase, sharedWorldsDir, sharedServersDir].forEach(d => {
if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
});
// ── Slug map: id → folder name ─────────────────────────────
// Keeps id stable (used in all JSON references) while folder = human-readable slug
const slugMapFile = path.join(dataDir, 'slug-map.json');
let slugMap = {}; // { 'inst_1234': 'My_Instance', 'srv_5678': 'My_Server' }
try { slugMap = JSON.parse(fs.readFileSync(slugMapFile, 'utf8')); } catch {}
function saveSlugMap() {
try { fs.writeFileSync(slugMapFile, JSON.stringify(slugMap, null, 2)); } catch {}
}
function slugify(name) {
// Turn "My Cool Server 1.21!" → "My_Cool_Server_1.21"
return (name || 'unnamed')
.replace(/[<>:"/\\|?*\x00-\x1f]/g, '') // remove illegal chars
.replace(/\s+/g, '_') // spaces → underscores
.replace(/[^\w.\-]/g, '') // keep only word chars, dots, dashes
.replace(/^\.+|\.+$/g, '') // no leading/trailing dots
.slice(0, 64) // max 64 chars
|| 'unnamed';
}
function registerSlug(id, name, base) {
// Pick a unique folder name for this id
const desired = slugify(name);
// If this id already has a mapping, keep it (don't rename on every save)
if (slugMap[id]) return slugMap[id];
// Ensure uniqueness: if folder exists for another id, append suffix
let candidate = desired;
let suffix = 2;
const usedFolders = new Set(Object.values(slugMap));
while (usedFolders.has(candidate) || (fs.existsSync(path.join(base, candidate)) && !slugMap[id])) {
candidate = desired + '_' + suffix++;
}
slugMap[id] = candidate;
saveSlugMap();
return candidate;
}
// ── Module-scope dir helpers (also redefined inside registerIpcHandlers for use there) ──
const INST_SUBDIRS = ['mods','saves','config','resourcepacks','screenshots','shaderpacks','logs'];
function instDir(id) { return path.join(instancesBase, slugMap[id] || id); }
function srvDir(id) { return path.join(serversBase, slugMap[id] || id); }
// ── Minimal NBT parser (for servers.dat) ───────────────────
function parseNBT(buffer) {
let pos = 0;
const readByte = () => buffer[pos++];
const readShort = () => { const v = buffer.readInt16BE(pos); pos += 2; return v; };
const readInt = () => { const v = buffer.readInt32BE(pos); pos += 4; return v; };
const readLong = () => { pos += 8; return 0; };
const readFloat = () => { pos += 4; return 0; };
const readDouble = () => { pos += 8; return 0; };
const readString = () => {
const len = buffer.readUInt16BE(pos); pos += 2;
const s = buffer.slice(pos, pos + len).toString('utf8');
pos += len; return s;
};
const readByteArray = () => { const n = readInt(); const buf = buffer.slice(pos, pos+n); pos += n; return buf; };
const readIntArray = () => { const n = readInt(); pos += n*4; return []; };
const readLongArray = () => { const n = readInt(); pos += n*8; return []; };
function readPayload(type) {
switch(type) {
case 1: return readByte(); case 2: return readShort(); case 3: return readInt();
case 4: return readLong(); case 5: return readFloat(); case 6: return readDouble();
case 7: return readByteArray(); case 8: return readString();
case 9: return readList(); case 10: return readCompound();
case 11: return readIntArray(); case 12: return readLongArray();
default: throw new Error('Unknown NBT type: ' + type);
}
}
function readList() {
const itemType = readByte(); const count = readInt(); const arr = [];
for (let i = 0; i < count; i++) arr.push(readPayload(itemType));
return arr;
}
function readCompound() {
const obj = {};
while (true) { const type = readByte(); if (type === 0) break; const name = readString(); obj[name] = readPayload(type); }
return obj;
}
const rootType = readByte(); readString(); // skip root name
return readPayload(rootType);
}
async function readServersDat(gameDir) {
const datFile = path.join(gameDir, 'servers.dat');
if (!fs.existsSync(datFile)) return [];
try {
const raw = fs.readFileSync(datFile);
// Minecraft Java Edition stores servers.dat as uncompressed NBT.
// Some older versions or tools may gzip it — try raw first, fall back to gunzip.
let buf;
const isGzip = raw[0] === 0x1f && raw[1] === 0x8b;
if (isGzip) {
buf = await new Promise((res, rej) => zlib.gunzip(raw, (e, d) => e ? rej(e) : res(d)));
} else {
buf = raw;
}
const root = parseNBT(buf);
const servers = root.servers || [];
return servers.map(s => ({
name: s.name || 'Minecraft Server',
ip: s.ip || '',
icon: s.icon ? ('data:image/png;base64,' + (Buffer.isBuffer(s.icon) ? s.icon.toString('base64') : s.icon)) : null,
hidden: s.hiddenAddress === 1,
}));
} catch(e) {
console.warn('[CraftDock] servers.dat parse error:', e.message);
return [];
}
}
// Uses AES-256-GCM with a per-install random key stored next to the data.
// This is far more portable than safeStorage/DPAPI which breaks if the app
// is moved, renamed, or updated (causes BAD_DECRYPT on Windows/BoringSSL).
const crypto = require('crypto');
let _tokenKey = null; // 32-byte Buffer, loaded/created lazily
function getTokenKey() {
if (_tokenKey && _tokenKey.length === 32) return _tokenKey;
_tokenKey = null;
const keyFile = path.join(dataDir, '.craftdock_key');
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
if (fs.existsSync(keyFile)) {
try {
const hex = fs.readFileSync(keyFile, 'utf8').trim();
if (/^[0-9a-fA-F]{64}$/.test(hex)) {
const candidate = Buffer.from(hex, 'hex');
if (candidate.length === 32) { _tokenKey = candidate; return _tokenKey; }
}
console.warn('[CraftDock] Key file corrupt, regenerating...');
fs.unlinkSync(keyFile);
} catch {}
}
_tokenKey = crypto.randomBytes(32);
try { fs.writeFileSync(keyFile, _tokenKey.toString('hex'), { mode: 0o600 }); } catch {}
return _tokenKey;
}
function encryptToken(token) {
if (!token) return '';
try {
const key = getTokenKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const enc = Buffer.concat([cipher.update(token, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
// Format: aes:<iv_hex>:<tag_hex>:<ciphertext_hex>
return 'aes:' + iv.toString('hex') + ':' + tag.toString('hex') + ':' + enc.toString('hex');
} catch(e) {
console.warn('[CraftDock] encryptToken failed, using base64 fallback:', e.message);
return 'b64:' + Buffer.from(token).toString('base64');
}
}
function decryptToken(stored) {
if (!stored) return '';
try {
if (stored.startsWith('aes:')) {
const parts = stored.slice(4).split(':');
if (parts.length !== 3) { console.warn('[CraftDock] malformed aes token'); return ''; }
const [ivHex, tagHex, encHex] = parts;
const isHex = s => /^[0-9a-fA-F]+$/.test(s);
if (!isHex(ivHex) || ivHex.length !== 24) { console.warn('[CraftDock] bad IV in token'); return ''; }
if (!isHex(tagHex) || tagHex.length !== 32) { console.warn('[CraftDock] bad tag in token'); return ''; }
if (!isHex(encHex)) { console.warn('[CraftDock] bad ct in token'); return ''; }
const key = getTokenKey();
if (!key || key.length !== 32) { console.warn('[CraftDock] bad key length'); return ''; }
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex,'hex'));
decipher.setAuthTag(Buffer.from(tagHex,'hex'));
return decipher.update(Buffer.from(encHex,'hex')) + decipher.final('utf8');
}
if (stored.startsWith('safe:')) {
// safeStorage/DPAPI tokens are unrecoverable if the app path changed.
// On Electron 40+ Windows, calling safeStorage.decryptString with a
// bad key throws a FATAL native BoringSSL exception that bypasses JS
// try/catch and crashes the process. So we NEVER call it — just return
// empty so the user is prompted to re-login.
console.warn('[CraftDock] Legacy safeStorage token detected — skipping (unrecoverable, user must re-login)');
return '';
}
if (stored.startsWith('b64:')) {
return Buffer.from(stored.slice(4), 'base64').toString('utf8');
}
// Legacy plaintext or unknown format — return as-is
return stored;
} catch(e) {
console.warn('[CraftDock] decryptToken failed:', e.message);
return ''; // empty string so auth re-prompts rather than crashing
}
}
// Microsoft OAuth - loaded from .env (falls back to public Minecraft client ID)
// Xbox/Minecraft auth client ID options (in order of reliability):
// '00000000402b5328' — original Xbox client (being deprecated by MS)
// 'XboxLive.signin' scope requires a client registered for consumers tenant
// Prism Launcher's registered client ID — works for device code flow with personal MS accounts
const MS_CLIENT_ID = process.env.MS_CLIENT_ID || 'c36a9fb6-4f2a-41ff-90bd-ae7cc92031eb';
const MS_SCOPE = 'XboxLive.signin offline_access';
let mainWindow;
let tray = null;
// ── HTTPS helpers ──────────────────────────────────────────
function httpsRequest(method, hostname, path, headers, body) {
return new Promise((resolve, reject) => {
const data = body ? (typeof body === 'string' ? body : JSON.stringify(body)) : null;
const opts = { hostname, path, method, headers: { ...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}), ...headers } };
const req = https.request(opts, res => {
let raw = '';
res.on('data', d => raw += d);
res.on('end', () => {
try { resolve({ status: res.statusCode, body: JSON.parse(raw) }); }
catch(e) { resolve({ status: res.statusCode, body: raw }); }
});
});
req.on('error', reject);
if (data) req.write(data);
req.end();
});
}
const post = (h,p,hdrs,b) => httpsRequest('POST',h,p,hdrs,b);
const get = (h,p,hdrs) => httpsRequest('GET', h,p,hdrs);
// ── Microsoft auth chain ───────────────────────────────────
async function doRequestDeviceCode() {
const body = `client_id=${MS_CLIENT_ID}&scope=${encodeURIComponent(MS_SCOPE)}`;
const r = await post('login.microsoftonline.com', '/consumers/oauth2/v2.0/devicecode',
{ 'Content-Type': 'application/x-www-form-urlencoded' }, body);
if (r.status !== 200) throw new Error(`Device code failed ${r.status}: ${JSON.stringify(r.body)}`);
return r.body; // { user_code, device_code, verification_uri, interval, expires_in }
}
async function doPollToken(deviceCode) {
const body = `client_id=${MS_CLIENT_ID}&device_code=${encodeURIComponent(deviceCode)}&grant_type=urn:ietf:params:oauth:grant-type:device_code`;
const r = await post('login.microsoftonline.com', '/consumers/oauth2/v2.0/token',
{ 'Content-Type': 'application/x-www-form-urlencoded' }, body);
return { status: r.status, data: r.body };
}
// Silently refresh the MC access token using the stored MS refresh token
async function refreshMcToken(msRefreshToken) {
// Step 1: Exchange MS refresh token for new MS access token
const body = `client_id=${MS_CLIENT_ID}&refresh_token=${encodeURIComponent(msRefreshToken)}&grant_type=refresh_token&scope=${encodeURIComponent(MS_SCOPE)}`;
const r = await post('login.microsoftonline.com', '/consumers/oauth2/v2.0/token',
{ 'Content-Type': 'application/x-www-form-urlencoded' }, body);
if (r.status !== 200) throw new Error(`MS refresh failed: ${r.status} — ${JSON.stringify(r.body)}`);
const newMsToken = r.body.access_token;
const newRefreshToken = r.body.refresh_token || msRefreshToken; // Live may rotate it
// Step 2: Full MC auth chain with fresh MS token
const result = await doCompleteLogin(newMsToken);
return { ...result, newMsToken, newRefreshToken };
}
// ── Background token refresh — runs every 23h, keeps tokens perpetually fresh ──
let _bgRefreshTimer = null;
async function backgroundRefreshAllAccounts() {
const accountsFile = path.join(dataDir, 'craftdock_accounts.json');
if (!fs.existsSync(accountsFile)) return;
let accounts;
try { accounts = JSON.parse(fs.readFileSync(accountsFile, 'utf8')); }
catch(e) { return; }
if (!Array.isArray(accounts) || !accounts.length) return;
let anyChanged = false;
for (let i = 0; i < accounts.length; i++) {
const acct = accounts[i];
const encRefresh = acct._msRefreshToken;
if (!encRefresh) continue; // nothing we can do without a refresh token
const msRefresh = decryptToken(encRefresh);
if (!msRefresh) continue; // undecryptable (safe: legacy) — skip
// Refresh if expired or expiring within the next 2 hours
const expiry = acct.mcTokenExpiry || 0;
const twoHours = 2 * 60 * 60 * 1000;
const needsRefresh = Date.now() >= (expiry - twoHours);
if (!needsRefresh) continue;
try {
console.log(`[CraftDock] Background-refreshing token for ${acct.minecraftUsername || acct.name || 'account ' + i}…`);
const refreshed = await refreshMcToken(msRefresh);
accounts[i] = {
...acct,
_minecraftToken: encryptToken(refreshed.mcToken),
_msRefreshToken: encryptToken(refreshed.newRefreshToken),
mcTokenExpiry: refreshed.mcTokenExpiry,
minecraftUsername: refreshed.profile?.name || acct.minecraftUsername,
minecraftUuid: refreshed.profile?.id || acct.minecraftUuid,
_tokensBroken: false,
_lastRefreshFailure: undefined,
};
delete accounts[i].minecraftToken;
delete accounts[i].msRefreshToken;
delete accounts[i]._lastRefreshFailure;
anyChanged = true;
console.log(`[CraftDock] Token refreshed successfully for ${accounts[i].minecraftUsername || 'account ' + i}`);
} catch(e) {
console.warn(`[CraftDock] Background token refresh failed for account ${i}: ${e.message}`);
// Don't mark broken here — it may be a transient network error.
// We'll retry next cycle.
}
}
if (anyChanged) {
try { fs.writeFileSync(accountsFile, JSON.stringify(accounts, null, 2)); }
catch(e) { console.warn('[CraftDock] Failed to save refreshed tokens:', e.message); }
}
}
function startBackgroundTokenRefresh() {
// Run immediately on startup, then every 30 minutes (checks expiry internally)
backgroundRefreshAllAccounts().catch(e => console.warn('[CraftDock] Initial token refresh error:', e.message));
_bgRefreshTimer = setInterval(() => {
backgroundRefreshAllAccounts().catch(e => console.warn('[CraftDock] BG token refresh error:', e.message));
}, 30 * 60 * 1000); // 30 minutes
}
async function doCompleteLogin(msAccessToken) {
// XBL
// With XboxLive.signin scope, RpsTicket must be prefixed with 'd='
const rpsTicket = msAccessToken.startsWith('d=') ? msAccessToken : `d=${msAccessToken}`;
const xblR = await post('user.auth.xboxlive.com', '/user/authenticate',
{ 'Content-Type': 'application/json', 'Accept': 'application/json' },
{ Properties: { AuthMethod: 'RPS', SiteName: 'user.auth.xboxlive.com', RpsTicket: rpsTicket },
RelyingParty: 'http://auth.xboxlive.com', TokenType: 'JWT' });
if (xblR.status !== 200) throw new Error(`Xbox auth failed: ${xblR.status}`);
const xblToken = xblR.body.Token;
const uhs = xblR.body.DisplayClaims.xui[0].uhs;
// XSTS
const xstsR = await post('xsts.auth.xboxlive.com', '/xsts/authorize',
{ 'Content-Type': 'application/json', 'Accept': 'application/json' },
{ Properties: { SandboxId: 'RETAIL', UserTokens: [xblToken] },
RelyingParty: 'rp://api.minecraftservices.com/', TokenType: 'JWT' });
if (xstsR.status !== 200) {
const code = xstsR.body?.XErr;
if (code === 2148916233) throw new Error('No Xbox account. Visit xbox.com to create one.');
if (code === 2148916238) throw new Error('Child account — parental approval required.');
throw new Error(`XSTS failed: ${xstsR.status} XErr=${code}`);
}
const xstsToken = xstsR.body.Token;
// Minecraft token
const mcR = await post('api.minecraftservices.com', '/authentication/login_with_xbox',
{ 'Content-Type': 'application/json' },
{ identityToken: `XBL3.0 x=${uhs};${xstsToken}` });
if (mcR.status !== 200) throw new Error(`Minecraft auth failed: ${mcR.status}`);
const mcToken = mcR.body.access_token;
// Profile
const profR = await get('api.minecraftservices.com', '/minecraft/profile',
{ Authorization: `Bearer ${mcToken}` });
if (profR.status === 404) throw new Error('This account does not own Minecraft Java Edition.');
if (profR.status !== 200) throw new Error(`Profile failed: ${profR.status}`);
const mcTokenExpiry = Date.now() + 23 * 60 * 60 * 1000; // MC tokens valid ~24h; refresh 1h early
return { profile: profR.body, mcToken, mcTokenExpiry }; // profile = { id, name, skins, capes }
}
// ── Window ─────────────────────────────────────────────────
function createWindow() {
// app.setName + setAppUserModelId already called at top of file
// Load our actual icon via nativeImage so Windows taskbar shows it correctly
const icoPath = path.join(__dirname, 'assets', 'icon.ico');
const pngPath = path.join(__dirname, 'assets', 'icon.png');
const winIcon = nativeImage.createFromPath(
process.platform === 'win32' ? icoPath : pngPath
);
mainWindow = new BrowserWindow({
width: 1280, height: 800, minWidth: 1000, minHeight: 640,
frame: false, titleBarStyle: 'hidden', backgroundColor: '#080c14',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true, nodeIntegration: false,
},
icon: winIcon,
title: 'CraftDock',
});
// Explicitly set icon after creation — ensures Windows taskbar picks it up
if (!winIcon.isEmpty()) mainWindow.setIcon(winIcon);
mainWindow.loadFile(path.join(__dirname, 'src', 'index.html'));
// ── System tray icon ─────────────────────────────────────
// Use the .ico on Windows (best multi-res support), .png elsewhere
const trayIconPath = process.platform === 'win32'
? path.join(__dirname, 'assets', 'icon.ico')
: path.join(__dirname, 'assets', 'icon.png');
tray = new Tray(trayIconPath);
tray.setToolTip('CraftDock');
tray.setContextMenu(Menu.buildFromTemplate([
{ label: 'Show CraftDock', click: () => { mainWindow?.show(); mainWindow?.focus(); } },
{ type: 'separator' },
{ label: 'Quit', role: 'quit' },
]));
tray.on('double-click', () => { mainWindow?.show(); mainWindow?.focus(); });
// When main window closes, destroy tray and quit
mainWindow.on('closed', () => {
tray?.destroy();
tray = null;
app.quit();
});
// mainWindow.webContents.openDevTools();
}
// Register all IPC handlers first, BEFORE creating the window
// Bump this whenever new IPC handlers are added — renderer checks on startup
const MAIN_JS_VERSION = '0.6.3';
// ── Simple ZIP writer (no external deps) ────────────────────
function writeZipToFile(destPath, entries) {
// entries = [{ name: string, data: Buffer }]
const parts = [];
const centralDir = [];
let offset = 0;
function crc32(buf) {
let crc = 0xFFFFFFFF;
for (const b of buf) {
crc ^= b;
for (let i = 0; i < 8; i++) crc = (crc & 1) ? (crc >>> 1) ^ 0xEDB88320 : crc >>> 1;
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
for (const { name, data } of entries) {
const nameB = Buffer.from(name, 'utf8');
const crc = crc32(data);
const lh = Buffer.alloc(30 + nameB.length);
lh.writeUInt32LE(0x04034b50, 0);
lh.writeUInt16LE(20, 4); // version needed
lh.writeUInt16LE(0, 6); // flags
lh.writeUInt16LE(0, 8); // compression: store
lh.writeUInt16LE(0, 10); // mod time
lh.writeUInt16LE(0, 12); // mod date
lh.writeUInt32LE(crc, 14);
lh.writeUInt32LE(data.length, 18);
lh.writeUInt32LE(data.length, 22);
lh.writeUInt16LE(nameB.length, 26);
lh.writeUInt16LE(0, 28);
nameB.copy(lh, 30);
const cdh = Buffer.alloc(46 + nameB.length);
cdh.writeUInt32LE(0x02014b50, 0);
cdh.writeUInt16LE(20, 4); cdh.writeUInt16LE(20, 6);
cdh.writeUInt16LE(0, 8); cdh.writeUInt16LE(0, 10);
cdh.writeUInt16LE(0, 12); cdh.writeUInt16LE(0, 14);
cdh.writeUInt32LE(crc, 16);
cdh.writeUInt32LE(data.length, 20);
cdh.writeUInt32LE(data.length, 24);
cdh.writeUInt16LE(nameB.length, 28);
cdh.writeUInt16LE(0, 30); cdh.writeUInt16LE(0, 32);
cdh.writeUInt16LE(0, 34); cdh.writeUInt16LE(0, 36);
cdh.writeUInt32LE(0, 38); cdh.writeUInt32LE(offset, 42);
nameB.copy(cdh, 46);
parts.push(lh, data);
centralDir.push(cdh);
offset += lh.length + data.length;
}
const cdSize = centralDir.reduce((s, b) => s + b.length, 0);
const eocd = Buffer.alloc(22);
eocd.writeUInt32LE(0x06054b50, 0);
eocd.writeUInt16LE(0, 4); eocd.writeUInt16LE(0, 6);
eocd.writeUInt16LE(entries.length, 8);
eocd.writeUInt16LE(entries.length, 10);
eocd.writeUInt32LE(cdSize, 12);
eocd.writeUInt32LE(offset, 16);
eocd.writeUInt16LE(0, 20);
fs.writeFileSync(destPath, Buffer.concat([...parts, ...centralDir, eocd]));
}
function registerIpcHandlers() {
// ── IPC: Version ping ──────────────────────────────────────
ipcMain.handle('get-main-version', () => MAIN_JS_VERSION);
// ── IPC: Electron version (for Settings > About) ───────────
ipcMain.handle('get-electron-version', () => process.versions.electron || '—');
// ── IPC: Window controls ───────────────────────────────────
ipcMain.on('window-minimize', () => mainWindow?.minimize());
ipcMain.on('window-maximize', () => mainWindow?.isMaximized() ? mainWindow.unmaximize() : mainWindow?.maximize());
ipcMain.on('window-close', () => mainWindow?.close());
// ── IPC: Auth ──────────────────────────────────────────────
ipcMain.handle('auth-request-device-code', async () => {
try { return { success: true, data: await doRequestDeviceCode() }; }
catch(e) { return { success: false, error: e.message }; }
});
ipcMain.handle('auth-poll-token', async (_, deviceCode) => {
try { const r = await doPollToken(deviceCode); return { success: true, ...r }; }
catch(e) { return { success: false, error: e.message }; }
});
ipcMain.handle('auth-complete-login', async (_, msAccessToken) => {
try { return { success: true, ...(await doCompleteLogin(msAccessToken)) }; }
catch(e) { return { success: false, error: e.message }; }
});
// ── IPC: Persistent key-value store ───────────────────────
ipcMain.handle('store-get', (_, key) => {
const file = path.join(dataDir, key.replace(/[^a-z0-9_-]/gi, '_') + '.json');
if (!fs.existsSync(file)) return null;
try {
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
if (key === 'craftdock:accounts' && Array.isArray(raw)) {
const TOKEN_FIELDS = ['minecraftToken', 'mcToken', 'msAccessToken', 'msRefreshToken'];
const accounts = raw.map(acct => {
const out = { ...acct };
let anyBad = false;
for (const field of TOKEN_FIELDS) {
const enc = '_' + field;
if (out[enc]) {
const decrypted = decryptToken(out[enc]);
if (!decrypted && out[enc]) {
// Decryption returned empty — token is unrecoverable (e.g. old DPAPI key)
anyBad = true;
}
out[field] = decrypted;
delete out[enc];
}
}
// Flag bad accounts so the renderer can prompt re-login
if (anyBad) out._tokensBroken = true;
return out;
});
return accounts;
}
return raw;
} catch(e) { return null; }
});
ipcMain.handle('store-set', (_, key, value) => {
let toWrite = value;
// Encrypt ALL sensitive token fields in accounts before writing to disk
if (key === 'craftdock:accounts' && Array.isArray(value)) {
toWrite = value.map(acct => {
const out = { ...acct };
// Encrypt every token field; store encrypted under _<field> and delete plaintext
for (const field of ['minecraftToken', 'mcToken', 'msAccessToken', 'msRefreshToken']) {
if (out[field]) {
out['_' + field] = encryptToken(out[field]);
delete out[field];
}
}
return out;
});
}
fs.writeFileSync(
path.join(dataDir, key.replace(/[^a-z0-9_-]/gi, '_') + '.json'),
JSON.stringify(toWrite, null, 2)
);
return { success: true };
});
ipcMain.handle('store-delete', (_, key) => {
const file = path.join(dataDir, key.replace(/[^a-z0-9_-]/gi, '_') + '.json');
if (fs.existsSync(file)) fs.unlinkSync(file);
return { success: true };
});
// ── IPC: Skins ─────────────────────────────────────────────
ipcMain.handle('skins-get-all', () => {
const metaFile = path.join(skinsDir, 'skins.json');
if (!fs.existsSync(metaFile)) return [];
const skins = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
return skins.map(s => {
if (s.filePath && fs.existsSync(s.filePath))
s.dataUrl = 'data:image/png;base64,' + fs.readFileSync(s.filePath).toString('base64');
return s;
});
});
ipcMain.handle('skins-save', (_, skin) => {
const metaFile = path.join(skinsDir, 'skins.json');
let skins = fs.existsSync(metaFile) ? JSON.parse(fs.readFileSync(metaFile, 'utf8')) : [];
if (skin.dataUrl?.startsWith('data:image')) {
const imgPath = path.join(skinsDir, skin.id + '.png');
fs.writeFileSync(imgPath, Buffer.from(skin.dataUrl.replace(/^data:image\/png;base64,/, ''), 'base64'));
skin.filePath = imgPath; delete skin.dataUrl;
}
const idx = skins.findIndex(s => s.id === skin.id);
if (idx >= 0) skins[idx] = skin; else skins.push(skin);
fs.writeFileSync(metaFile, JSON.stringify(skins, null, 2));
return { success: true };
});
ipcMain.handle('skins-delete', (_, id) => {
const metaFile = path.join(skinsDir, 'skins.json');
if (!fs.existsSync(metaFile)) return;
fs.writeFileSync(metaFile, JSON.stringify(JSON.parse(fs.readFileSync(metaFile,'utf8')).filter(s=>s.id!==id), null, 2));
const imgPath = path.join(skinsDir, id + '.png');
if (fs.existsSync(imgPath)) fs.unlinkSync(imgPath);
return { success: true };
});
ipcMain.handle('dialog-open-skin', async () => {
const r = await dialog.showOpenDialog(mainWindow, {
title: 'Select Skin PNG', filters: [{ name: 'PNG Image', extensions: ['png'] }], properties: ['openFile']
});
if (r.canceled || !r.filePaths.length) return null;
return 'data:image/png;base64,' + fs.readFileSync(r.filePaths[0]).toString('base64');
});
// ── IPC: CurseForge API ────────────────────────────────────
// Key is baked in — users never need to supply their own.
// process.env.CF_API_KEY from .env overrides it in dev if needed.
const CF_API_KEY = process.env.CF_API_KEY || '$2a$10$bL4bIL5pUWqfcO7KwxOSAOWBiNKEFGPHDTACGArQcHClc8W6cFx8K';
const CF_BASE_URL = "https://api.curseforge.com/v1";
ipcMain.handle('cf-get-mc-versions', async () => {
try {
const res = await fetch('https://api.curseforge.com/v1/minecraft/version', {
method: 'GET',
headers: {
'Accept': 'application/json',
'x-api-key': CF_API_KEY
}
});
if (!res.ok) {
throw new Error(`CurseForge API error: ${res.status}`);
}
const data = await res.json();
return { success: true, data: data.data || [] };
} catch (e) {
return { success: false, error: e.message };
}
});
async function cfSearch(gameId, classId, query = '', gameVersion = '', modLoaderType = '', pageSize = 20, sortField = 2) {
// Per CF API docs: GET https://api.curseforge.com/v1/mods/search
// Required: gameId. Auth: x-api-key header. Accept: application/json.
// sortField: 1=Featured,2=Popularity,3=LastUpdated,4=Name,5=Author,
// 6=TotalDownloads,8=GameVersion,11=ReleasedDate,12=Rating
// modLoaderType: 0=Any,1=Forge,2=Cauldron,3=LiteLoader,4=Fabric,5=Quilt,6=NeoForge
const params = new URLSearchParams({
gameId,
classId,
searchFilter: query || '',
pageSize,
sortField: sortField || (query ? 1 : 2), // 1=Relevance when searching, 2=Popularity for browse
sortOrder: 'desc'
});
if (gameVersion) params.append('gameVersion', gameVersion);
// Only send modLoaderType if non-empty — omitting it means "Any" per CF docs
if (modLoaderType !== '' && modLoaderType !== null && modLoaderType !== undefined) {
params.append('modLoaderType', Number(modLoaderType));
}
const res = await fetch(`${CF_BASE_URL}/mods/search?${params}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'x-api-key': CF_API_KEY
}
});
if (!res.ok) throw new Error(`CurseForge API ${res.status}: ${await res.text().catch(()=>'')}`);
return await res.json();
}
ipcMain.handle('curseforge-search', async (_, query = '', gameVersion = '', modLoaderType = '', classId = 4471, sortField = 2) => {
try {
// Pass all params including sortField — cfSearch now accepts it as 7th argument
const data = await cfSearch(432, classId, query, gameVersion, modLoaderType, 40, sortField);
return { success: true, data: data.data || [] };
} catch (e) {
return { success: false, error: e.message };
}
});
// CF_API_KEY loaded (debug logging removed)
console.log('[CraftDock] Registering IPC handlers...');
// ═══════════════════════════════════════════════════════════
// SERVER MANAGER IPC
// ═══════════════════════════════════════════════════════════
const { spawn } = require('child_process');
const runningServers = new Map();
// ── Open folder ────────────────────────────────────────────
ipcMain.handle('open-folder', (_, p) => shell.openPath(p));
ipcMain.handle('get-data-root', () => dataRoot);
ipcMain.handle('get-server-path', (_, id) => srvDir(id));
// ── Resolve Paper build URL ────────────────────────────────
async function resolvePaperUrl(version, build) {
return new Promise((resolve, reject) => {
const path_ = build
? `/v2/projects/paper/versions/${version}/builds/${build}`
: `/v2/projects/paper/versions/${version}`;
const req = require('https').get(
{ hostname:'api.papermc.io', path: path_,
headers:{'User-Agent':'CraftDock/0.6.3 (contact@craftdock.app)'} }, res => {
if ([301,302,307,308].includes(res.statusCode)) {
res.resume();
return resolvePaperUrl(version, build).then(resolve).catch(reject);
}
if (res.statusCode !== 200) { res.resume(); return reject(new Error('PaperMC API HTTP ' + res.statusCode)); }
let raw=''; res.on('data',d=>raw+=d);
res.on('end',()=>{
try {
const d=JSON.parse(raw);
const b = build || d.builds[d.builds.length-1];
resolve(`https://api.papermc.io/v2/projects/paper/versions/${version}/builds/${b}/downloads/paper-${version}-${b}.jar`);
} catch(e) { reject(new Error('PaperMC API parse error: '+e.message)); }
});
});
req.setTimeout(20000, () => req.destroy(new Error('PaperMC API timeout')));
req.on('error', reject);
});
}
async function resolvePurpurUrl(version) {
// Purpur API returns a direct download redirect
return `https://api.purpurmc.org/v2/purpur/${version}/latest/download`;
}
async function resolveVanillaUrl(version) {
// Fetch the version manifest with a timeout + User-Agent to avoid Windows SSL issues
const fetchJson = (url) => new Promise((resolve, reject) => {
const req = require('https').get(url, {
headers: { 'User-Agent': 'CraftDock/0.6.3 (contact@craftdock.app)' }
}, res => {
// Follow redirects
if ([301,302,307,308].includes(res.statusCode)) {
res.resume();
return fetchJson(res.headers.location).then(resolve).catch(reject);
}
if (res.statusCode !== 200) { res.resume(); return reject(new Error('HTTP ' + res.statusCode + ' for ' + url)); }
let raw = '';
res.on('data', d => raw += d);
res.on('end', () => { try { resolve(JSON.parse(raw)); } catch(e) { reject(new Error('Bad JSON from ' + url)); } });
res.on('error', reject);
});
req.setTimeout(30000, () => req.destroy(new Error('Timeout fetching ' + url)));
req.on('error', reject);
});
const manifest = await fetchJson('https://launchermeta.mojang.com/mc/game/version_manifest_v2.json');
const entry = manifest.versions.find(x => x.id === version);
if (!entry) throw new Error('Minecraft version ' + version + ' not found in manifest');
const versionMeta = await fetchJson(entry.url);
const serverUrl = versionMeta?.downloads?.server?.url;
if (!serverUrl) throw new Error('No server download for MC ' + version);
return serverUrl;
}
// ── Minimal ZIP reader (Node built-ins only, no adm-zip needed) ────
function readZipEntries(zipPath) {
// Returns Map<name, Buffer> for all entries in the zip
const buf = fs.readFileSync(zipPath);
const entries = new Map();
// Find End of Central Directory (EOCD) — search from end
let eocdOffset = -1;
for (let i = buf.length - 22; i >= 0; i--) {
if (buf.readUInt32LE(i) === 0x06054b50) { eocdOffset = i; break; }
}
if (eocdOffset < 0) throw new Error('Invalid ZIP: EOCD not found');
const cdOffset = buf.readUInt32LE(eocdOffset + 16);
const cdSize = buf.readUInt32LE(eocdOffset + 12);
const cdCount = buf.readUInt16LE(eocdOffset + 10);
let pos = cdOffset;
for (let i = 0; i < cdCount; i++) {
if (buf.readUInt32LE(pos) !== 0x02014b50) break;
const compression = buf.readUInt16LE(pos + 10);
const compressedSz = buf.readUInt32LE(pos + 20);
const fileNameLen = buf.readUInt16LE(pos + 28);
const extraLen = buf.readUInt16LE(pos + 30);
const commentLen = buf.readUInt16LE(pos + 32);
const localOffset = buf.readUInt32LE(pos + 42);
const name = buf.slice(pos + 46, pos + 46 + fileNameLen).toString('utf8');
pos += 46 + fileNameLen + extraLen + commentLen;
// Read local file header to get actual data offset
const localExtraLen = buf.readUInt16LE(localOffset + 28);
const dataOffset = localOffset + 30 + fileNameLen + localExtraLen;
const compData = buf.slice(dataOffset, dataOffset + compressedSz);
if (compression === 0) {
// Stored (no compression)
entries.set(name, compData);
} else if (compression === 8) {
// Deflate
entries.set(name, require('zlib').inflateRawSync(compData));
}
// Other methods ignored
}
return entries;
}
// ── Verify a JAR/ZIP file has a valid ZIP end-of-central-directory ──
function verifyZip(filePath) {
try {
const fd = require('fs').openSync(filePath, 'r');
const stat = require('fs').fstatSync(fd);
if (stat.size < 22) { require('fs').closeSync(fd); return false; }
// Read last 22 bytes — the minimum EOCD record
const buf = Buffer.alloc(22);
require('fs').readSync(fd, buf, 0, 22, stat.size - 22);
require('fs').closeSync(fd);
// EOCD signature: PK
return buf[0]===0x50 && buf[1]===0x4b && buf[2]===0x05 && buf[3]===0x06;
} catch { return false; }
}
async function downloadServerJar(destPath, url, onProgress, send, label) {
const MAX_TRIES = 3;
for (let attempt = 1; attempt <= MAX_TRIES; attempt++) {
if (attempt > 1) {
send && send(0, `Retry ${attempt}/${MAX_TRIES} — re-downloading server.jar...`);
try { fs.unlinkSync(destPath); } catch {}
}
await downloadFile(url, destPath, onProgress, 180000);
if (verifyZip(destPath)) return; // good
// File is corrupt/truncated
if (attempt === MAX_TRIES) {
throw new Error(
`server.jar failed ZIP integrity check after ${MAX_TRIES} attempts.\n` +
`File size: ${fs.existsSync(destPath) ? fs.statSync(destPath).size : 0} bytes.\n` +
`URL: ${url}`
);
}
send && send(0, `server.jar appears truncated (attempt ${attempt}) — retrying...`);
}
}
// ── Download with progress + redirect + timeout ────────────
function downloadFile(url, dest, onProgress, timeoutMs = 120000) {
return new Promise((resolve, reject) => {
let settled = false;
const done = (fn, val) => { if (!settled) { settled = true; fn(val); } };
const go = (u, redirects = 0) => {
if (redirects > 10) { done(reject, new Error('Too many redirects: ' + u)); return; }
const isHttps = u.startsWith('https');
const proto = isHttps ? require('https') : require('http');
// Use a fresh agent per request to avoid BoringSSL session-resumption BAD_DECRYPT errors
const agent = new proto.Agent({ keepAlive: false });
const req = proto.get(u, {
agent,
headers: { 'User-Agent': 'CraftDock/0.6.3 (contact@craftdock.app)' }
}, res => {
if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) {
res.resume(); // drain response
go(res.headers.location, redirects + 1);
return;
}
if (res.statusCode !== 200) {
res.resume();
done(reject, new Error(`HTTP ${res.statusCode} for ${u}`));
return;
}
const total = parseInt(res.headers['content-length'] || '0', 10);
let recv = 0;
const out = require('fs').createWriteStream(dest);
let _lastPct = -1;
res.on('data', chunk => {
recv += chunk.length;
if (total && onProgress) {
const pct = Math.round(recv / total * 100);
if (pct !== _lastPct) { _lastPct = pct; onProgress(pct); }
}
});
res.pipe(out);
out.on('finish', () => done(resolve));
out.on('error', e => done(reject, e));
res.on('error', e => done(reject, e));
});
req.on('error', e => done(reject, e));
req.setTimeout(timeoutMs, () => {
req.destroy(new Error(`Download timed out after ${timeoutMs/1000}s: ${u}`));
});
};
go(url);
});
}
// ═══════════════════════════════════════════════════════════
// INSTANCE MANAGEMENT
// Each instance = craftdock-data/instances/<id>/
// Structure mirrors a real .minecraft profile folder:
// mods/ saves/ config/ resourcepacks/ screenshots/
// shaderpacks/ logs/ instance.json (meta)
// ═══════════════════════════════════════════════════════════
function ensureInstance(id) {
const base = instDir(id);
if (!fs.existsSync(base)) fs.mkdirSync(base, { recursive: true });
for (const sub of INST_SUBDIRS) {
const p = path.join(base, sub);
if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
}
return base;
}
function readInstMeta(id) {
try {
const p = path.join(instDir(id), 'instance.json');
if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf8'));
} catch {}
return null;
}
function writeInstMeta(id, meta) {
const dir = instDir(id);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'instance.json'), JSON.stringify(meta, null, 2));
}
// Set up or remove shared worlds symlink/junction for an instance
function sharedWorldsDirForTag(tag) {
// Each tag gets its own subfolder under shared-worlds/
const safeName = tag.replace(/[^a-z0-9_-]/gi, '_').toLowerCase();
return path.join(sharedWorldsDir, safeName);
}
function applySharedWorlds(id, tag) {
// tag = string (non-empty) → link saves/ to shared-worlds/<tag>/
// tag = null/'' → unlink saves/ back to a real dir
const savesPath = path.join(instDir(id), 'saves');
const isWin = process.platform === 'win32';
// Read current state
let currentlyLinked = false;
try {
const stat = fs.lstatSync(savesPath);
currentlyLinked = stat.isSymbolicLink() || (isWin && stat.isDirectory() && (() => {
try { const { execSync } = require('child_process'); return execSync(`fsutil reparsepoint query "${savesPath}" 2>nul`).toString().includes('Tag value'); } catch { return false; }
})());
} catch {}
if (!tag) {
// Disable: turn symlink back into real folder
if (currentlyLinked) {
try {
if (isWin) { const { execSync } = require('child_process'); execSync(`rmdir "${savesPath}"`, { windowsHide: true }); }
else fs.unlinkSync(savesPath);
} catch {}
}
if (!fs.existsSync(savesPath)) fs.mkdirSync(savesPath, { recursive: true });
return;
}
const tagDir = sharedWorldsDirForTag(tag);
if (!fs.existsSync(tagDir)) fs.mkdirSync(tagDir, { recursive: true });
// Remove existing saves (symlink or empty dir)
if (currentlyLinked) {
try {
if (isWin) { const { execSync } = require('child_process'); execSync(`rmdir "${savesPath}"`, { windowsHide: true }); }
else fs.unlinkSync(savesPath);
} catch {}
} else if (fs.existsSync(savesPath)) {
// Move any existing worlds into the tag folder
try {
const entries = fs.readdirSync(savesPath);
for (const e of entries) {
const src = path.join(savesPath, e);
const dst = path.join(tagDir, e);
if (!fs.existsSync(dst)) fs.renameSync(src, dst);
}
fs.rmdirSync(savesPath);
} catch {}
}
// Create symlink/junction to tag dir