-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1221 lines (1081 loc) · 54.2 KB
/
Copy pathserver.js
File metadata and controls
1221 lines (1081 loc) · 54.2 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 express = require('express');
const rateLimit = require('express-rate-limit');
const axios = require('axios');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const fs = require('fs');
const yaml = require('js-yaml');
const path = require('path');
const { execSync } = require('child_process');
const app = express();
app.set('trust proxy', 1); // Trust Traefik reverse proxy
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change-in-prod';
const HEADSCALE_URL = process.env.HEADSCALE_URL || 'http://headscale:8080';
// ── Auto-create users-mapping.json if it doesn't exist ──────────────────
const USERS_MAPPING_PATH = '/etc/headscale/users-mapping.json';
const defaultUsersMapping = {
users: {
"admin": {
email: "admin@yourdomain.com",
role: "super_admin",
manageable_domains: ["*"]
}
},
api_key_labels: {}
};
if (!fs.existsSync(USERS_MAPPING_PATH)) {
try {
fs.mkdirSync('/etc/headscale', { recursive: true });
fs.writeFileSync(USERS_MAPPING_PATH, JSON.stringify(defaultUsersMapping, null, 2));
console.log('[INIT] Created default users-mapping.json at', USERS_MAPPING_PATH);
console.log('[INIT] Default admin user created - update email and username to match your Headscale user');
} catch (err) {
console.error('[INIT] Could not create users-mapping.json:', err.message);
}
} else {
console.log('[INIT] users-mapping.json found at', USERS_MAPPING_PATH);
}
app.use(express.json());
// Rate limit login to 20 attempts per 15 minutes per IP
const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 20, message: { message: 'Too many login attempts, try again later' } });
app.use(cors());
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
next();
});
const userTokenMap = new Map();
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(401).json({ message: 'No token provided' });
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(403).json({ message: 'Invalid token' });
}
};
const getUserRoleFromACL = (email, aclPolicy) => {
if (!aclPolicy || !aclPolicy.groups) return 'viewer';
const adminGroups = aclPolicy.tagOwners?.['tag:admin'] || [];
for (const groupName in aclPolicy.groups) {
const members = aclPolicy.groups[groupName];
if (members.includes(email) && adminGroups.includes(groupName)) {
return 'admin';
}
}
return 'viewer';
};
app.post('/api/auth/login', loginLimiter, async (req, res) => {
const { username, apiKey } = req.body;
const headscaleUrl = HEADSCALE_URL;
if (!username || !apiKey) return res.status(400).json({ message: 'Missing fields: username, apiKey' });
try {
console.log(`\n[LOGIN] ${username}`);
await axios.get(`${headscaleUrl}/api/v1/user`, { headers: { Authorization: `Bearer ${apiKey}` }, timeout: 5000 });
console.log('✓ API key validated');
console.log('[LOGIN] Fetching policy...');
const policyResponse = await axios.get(`${headscaleUrl}/api/v1/policy`, { headers: { Authorization: `Bearer ${apiKey}` }, timeout: 5000 });
let aclPolicy = policyResponse.data;
if (typeof aclPolicy.policy === 'string') {
aclPolicy = JSON.parse(aclPolicy.policy);
}
console.log('[LOGIN] ACL Policy users:', Object.keys(aclPolicy.users || {}));
let usersMapping;
try {
usersMapping = JSON.parse(fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8'));
console.log('[LOGIN] Users mapping loaded:', Object.keys(usersMapping.users || {}));
} catch (err) {
console.error('[LOGIN] Failed to load users mapping:', err.message);
return res.status(500).json({ message: 'Failed to load users mapping' });
}
const userRecord = usersMapping.users?.[username];
const email = userRecord?.email;
console.log(`[LOGIN] Looking up email for username: ${username}`);
if (!email) return res.status(400).json({ message: `Username "${username}" not found in ACL users mapping` });
// Get role from users-mapping.json (not from ACL policy)
const currentUser = Object.values(usersMapping.users || {}).find((u) => u.email === email);
const role = currentUser?.role || 'user';
userTokenMap.set(email, { apiKey, headscaleUrl, validatedAt: Date.now() });
const manageable_domains = currentUser?.manageable_domains || [];
const sessionToken = jwt.sign({ email, username, role, id: email, manageable_domains }, JWT_SECRET, { expiresIn: '24h' });
console.log(`[LOGIN SUCCESS] ${username} (${email}) role: ${role}`);
logAudit(username, 'login', `${username} logged in`, `role: ${role}`);
res.json({ sessionToken, user: { email, username, role, id: email, manageable_domains } });
} catch (error) {
console.error('Login error:', error.message);
res.status(401).json({ message: 'Invalid API key' });
}
});
app.post('/api/auth/logout', authenticateToken, (req, res) => {
if (req.user?.email) userTokenMap.delete(req.user.email);
res.json({ message: 'Logged out' });
});
app.get('/api/auth/me', authenticateToken, (req, res) => {
try {
const usersMapping = JSON.parse(fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8'));
// Try username first, fall back to email lookup for old tokens
let username = req.user?.username;
let userRecord = usersMapping.users?.[username];
if (!userRecord && req.user?.email) {
const entry = Object.entries(usersMapping.users || {}).find(([_, u]) => u.email === req.user.email);
if (entry) { username = entry[0]; userRecord = entry[1]; }
}
userRecord = userRecord || {};
const role = userRecord.role || req.user?.role || 'user';
const manageable_domains = userRecord.manageable_domains || req.user?.manageable_domains || [];
res.json({ user: { email: req.user?.email, username, role, id: req.user?.email, manageable_domains } });
} catch (err) {
res.json({ user: { email: req.user?.email, role: req.user?.role, id: req.user?.email, manageable_domains: req.user?.manageable_domains || [] } });
}
});
app.post('/api/headscale/approve-route', authenticateToken, async (req, res) => {
const userEmail = req.user?.email;
if (!userEmail) return res.status(401).json({ message: 'Unauthorized' });
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const { nodeId, route } = req.body;
if (!nodeId || !route) return res.status(400).json({ message: 'Missing nodeId or route' });
try {
console.log(`[APPROVE] Route: ${route}, NodeId: ${nodeId}`);
const nodeResponse = await axios.get(
`${tokenData.headscaleUrl}/api/v1/node/${nodeId}`,
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
const node = nodeResponse.data.node;
const newApproved = [...new Set([...(node.approvedRoutes || []), route])];
console.log(`[APPROVE] Calling API with routes: ${newApproved.join(', ')}`);
const updateResponse = await axios.post(
`${tokenData.headscaleUrl}/api/v1/node/${nodeId}/approve_routes`,
{ routes: newApproved },
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
console.log(`[APPROVE] Success`);
res.json({ message: 'Route approved', node: updateResponse.data.node });
} catch (error) {
console.error(`[APPROVE] Error:`, error.message);
res.status(500).json({ message: error.message });
}
});
app.post('/api/headscale/disapprove-route', authenticateToken, async (req, res) => {
const userEmail = req.user?.email;
if (!userEmail) return res.status(401).json({ message: 'Unauthorized' });
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const { nodeId, route } = req.body;
if (!nodeId || !route) return res.status(400).json({ message: 'Missing nodeId or route' });
try {
console.log(`[DISAPPROVE] Route: ${route}, NodeId: ${nodeId}`);
const nodeResponse = await axios.get(
`${tokenData.headscaleUrl}/api/v1/node/${nodeId}`,
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
const node = nodeResponse.data.node;
const newApproved = (node.approvedRoutes || []).filter(r => r !== route);
console.log(`[DISAPPROVE] Calling API with routes: ${newApproved.join(', ')}`);
const updateResponse = await axios.post(
`${tokenData.headscaleUrl}/api/v1/node/${nodeId}/approve_routes`,
{ routes: newApproved },
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
console.log(`[DISAPPROVE] Success`);
res.json({ message: 'Route disapproved', node: updateResponse.data.node });
} catch (error) {
console.error(`[DISAPPROVE] Error:`, error.message);
res.status(500).json({ message: error.message });
}
});
app.post('/api/headscale/user/create', authenticateToken, async (req, res) => {
const userEmail = req.user?.email;
if (!userEmail) return res.status(401).json({ message: 'Unauthorized' });
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const { username, email } = req.body;
if (!username) return res.status(400).json({ message: 'Username required' });
try {
console.log(`\n[CREATE-USER] Creating user: ${username}`);
const userResponse = await axios.post(
`${tokenData.headscaleUrl}/api/v1/user`,
{ name: username },
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
console.log(`[CREATE-USER] User created successfully`);
// If email provided, set it via CLI
if (email && email.trim()) {
try {
console.log(`[CREATE-USER] Setting email via CLI: ${email}`);
const cmd = `docker exec headscale /ko-app/headscale users rename --name '${username}' --new-name '${username}'`;
execSync(cmd, { encoding: 'utf-8' });
console.log(`[CREATE-USER] User renamed (preparing for email)`);
} catch (cliError) {
console.error(`[CREATE-USER] Warning: Could not set email via CLI`, cliError.message);
}
}
res.json({ message: 'User created successfully', username, email });
} catch (error) {
console.error('Failed to create user:', error.message);
res.status(500).json({ message: error.message });
}
});
// DNS Configuration Endpoints
const HEADSCALE_CONFIG_PATH = '/etc/headscale/config.yaml';
const execHeadscaleCommand = (cmd) => execSync(`docker exec headscale ${cmd}`, { encoding: 'utf-8' });
// DNS Configuration Endpoints
app.get('/api/config/dns', authenticateToken, async (req, res) => {
try {
const configContent = fs.readFileSync('/etc/headscale/config.yaml', 'utf8');
const yaml = require('js-yaml');
const config = yaml.load(configContent);
const dnsConfig = {
tailnetName: config.dns?.base_domain || 'tailnet.local',
magicDns: config.dns?.magic_dns ?? true,
overrideLocalDns: config.dns?.override_local_dns ?? true,
nameservers: config.dns?.nameservers?.global || [],
searchDomains: config.dns?.search_domains || [],
splitDns: config.dns?.nameservers?.split || {},
extraRecords: config.dns?.extra_records || []
};
res.json(dnsConfig);
} catch (error) {
console.error('Failed to read DNS config:', error.message);
res.status(500).json({ message: `Failed to read DNS config: ${error.message}` });
}
});
app.post('/api/config/dns', authenticateToken, async (req, res) => {
try {
const yaml = require('js-yaml');
const { tailnetName, magicDns, overrideLocalDns, nameservers, searchDomains, splitDns, extraRecords } = req.body;
const configContent = fs.readFileSync('/etc/headscale/config.yaml', 'utf8');
const config = yaml.load(configContent);
config.dns = {
base_domain: tailnetName || 'tailnet.local',
magic_dns: magicDns !== undefined ? magicDns : true,
override_local_dns: overrideLocalDns !== undefined ? overrideLocalDns : true,
nameservers: {
global: nameservers || [],
split: splitDns || {}
},
search_domains: searchDomains || [],
extra_records: extraRecords || []
};
const updatedConfig = yaml.dump(config);
fs.writeFileSync('/etc/headscale/config.yaml', updatedConfig, 'utf8');
console.log('[DNS-CONFIG] Updated DNS configuration');
res.json({ message: 'DNS configuration updated', config: config.dns });
} catch (error) {
console.error('Failed to update DNS config:', error.message);
res.status(500).json({ message: `Failed to update DNS config: ${error.message}` });
}
});
// Nodes Management Endpoints
app.post('/api/headscale/node/rename', authenticateToken, async (req, res) => {
const { nodeId, newName } = req.body;
if (!nodeId || !newName) return res.status(400).json({ message: 'nodeId and newName required' });
if (!/^[0-9]+$/.test(String(nodeId))) return res.status(400).json({ message: 'Invalid nodeId' });
// Headscale requires lowercase DNS-safe names. Validate explicitly so we can return a useful error.
const sanitized = String(newName).trim().toLowerCase();
if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(sanitized)) {
return res.status(400).json({ message: 'Invalid name. Use lowercase letters, digits, and hyphens (max 63 chars, no leading hyphen).' });
}
try {
const userEmail = req.user.email;
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
// Headscale's REST API takes the new name as a URL path segment, not a JSON body.
const response = await axios.post(
`${tokenData.headscaleUrl}/api/v1/node/${nodeId}/rename/${encodeURIComponent(sanitized)}`,
null,
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
console.log(`[NODE-RENAME] ${nodeId} \u2192 ${sanitized}`);
res.json({ message: 'Node renamed', nodeId, newName: sanitized, node: response.data.node });
} catch (error) {
// Surface Headscale's underlying error message instead of swallowing it.
const upstream = error.response?.data?.message || error.response?.data || error.message;
console.error('Failed to rename node:', upstream);
res.status(error.response?.status || 500).json({ message: typeof upstream === 'string' ? upstream : JSON.stringify(upstream) });
}
});
app.post('/api/headscale/node/delete', authenticateToken, async (req, res) => {
const { nodeId } = req.body;
if (!nodeId) return res.status(400).json({ message: 'nodeId required' });
if (!/^[0-9]+$/.test(String(nodeId))) return res.status(400).json({ message: 'Invalid nodeId' });
try {
const cmd = `docker exec headscale /ko-app/headscale nodes delete --identifier '${nodeId}' --force`;
execSync(cmd, { encoding: 'utf-8' });
console.log(`[NODE-DELETE] ${nodeId}`);
res.json({ message: 'Node deleted', nodeId });
} catch (error) {
console.error('Failed to delete node:', error.message);
res.status(500).json({ message: error.message });
}
});
app.post('/api/headscale/node/expire', authenticateToken, async (req, res) => {
const { nodeId } = req.body;
if (!nodeId) return res.status(400).json({ message: 'nodeId required' });
if (!/^[0-9]+$/.test(String(nodeId))) return res.status(400).json({ message: 'Invalid nodeId' });
try {
const cmd = `docker exec headscale /ko-app/headscale nodes update --identifier '${nodeId}' --expiration now`;
execSync(cmd, { encoding: 'utf-8' });
console.log(`[NODE-EXPIRE] ${nodeId}`);
res.json({ message: 'Node expired', nodeId });
} catch (error) {
console.error('Failed to expire node:', error.message);
res.status(500).json({ message: error.message });
}
});
app.get('/api/headscale/user-mapping', authenticateToken, async (req, res) => {
const userEmail = req.user.email;
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
try {
const policyResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/policy`, { headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 });
let policy = policyResp.data;
if (typeof policy.policy === 'string') policy = JSON.parse(policy.policy);
const usersResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/user`, { headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 });
const map = {};
const groups = policy.groups || {};
Object.values(groups).forEach(emails => {
emails.forEach(email => {
const user = usersResp.data.users.find(u => u.email === email);
if (user) map[user.name] = email;
});
});
usersResp.data.users.forEach(user => {
if (user.email && !map[user.name]) map[user.name] = user.email;
});
// Fallback: fill in emails from users-mapping.json for users with no headscale email
try {
const usersMapping = JSON.parse(fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8'));
Object.entries(usersMapping.users || {}).forEach(([username, record]) => {
if (record.email && !map[username]) map[username] = record.email;
});
} catch (e) { /* mapping file optional */ }
console.log('[USER-MAPPING] Generated:', Object.keys(map).length, 'users');
res.json(map);
} catch (e) {
console.error('[USER-MAPPING]', e.message);
res.status(500).json({ message: e.message });
}
});
// Move node to different user - proper Headscale workflow
// This deletes the node and returns instructions for re-registration under new user
app.post('/api/headscale/node/move-user', authenticateToken, async (req, res) => {
const { nodeId, newUser } = req.body;
if (!nodeId || !newUser) return res.status(400).json({ message: 'nodeId and newUser required' });
try {
const userEmail = req.user.email;
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const usersResp = await axios.get(tokenData.headscaleUrl + '/api/v1/user', { headers: { Authorization: 'Bearer ' + tokenData.apiKey }, timeout: 10000 });
const targetUser = usersResp.data.users.find(u => u.name === newUser);
if (!targetUser) return res.status(400).json({ message: `User '${newUser}' not found` });
const nodesResp = await axios.get(tokenData.headscaleUrl + '/api/v1/node', { headers: { Authorization: 'Bearer ' + tokenData.apiKey }, timeout: 10000 });
const node = nodesResp.data.nodes.find(n => n.id.toString() === nodeId.toString());
if (!node) return res.status(400).json({ message: `Node ${nodeId} not found` });
// 1) Create the new pre-auth key FIRST so we can guarantee a key to return
// even if anything later fails. Avoids the previous "deleted then crashed
// before key returned" failure mode.
const preauthResp = await axios.post(
tokenData.headscaleUrl + '/api/v1/preauthkey',
{ user: parseInt(targetUser.id, 10), ephemeral: false, expiration: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString() },
{ headers: { Authorization: 'Bearer ' + tokenData.apiKey }, timeout: 10000 }
);
// Headscale returns the key under `preAuthKey` (camelCase) in this API version.
// The fallback covers older snake_case payloads.
const newKey = preauthResp.data?.preAuthKey?.key || preauthResp.data?.pre_auth_key?.key;
if (!newKey) {
console.error('[NODE-MOVE-USER] Headscale returned no key:', JSON.stringify(preauthResp.data));
return res.status(500).json({ message: 'Headscale did not return a pre-auth key. Node has NOT been deleted.' });
}
// 2) Now delete the existing node
await axios.delete(
tokenData.headscaleUrl + '/api/v1/node/' + nodeId,
{ headers: { Authorization: 'Bearer ' + tokenData.apiKey }, timeout: 10000 }
);
console.log('[NODE-MOVE-USER] Node ' + nodeId + ' (' + (node.givenName || node.hostname) + ') deleted. New pre-auth key created for user ' + newUser);
logAudit(req.user.username, 'move-node-user', `node:${nodeId}`, `to user ${newUser}`);
res.json({
message: 'Node deleted and new pre-auth key created',
nodeId,
hostname: node.givenName || node.hostname,
newUser,
newKey,
instructions: 'Device must reconnect with: tailscale login --auth-key=' + newKey,
});
} catch (error) {
const upstream = error.response?.data?.message || error.response?.data || error.message;
console.error('Failed to move node to user:', upstream);
res.status(error.response?.status || 500).json({ message: typeof upstream === 'string' ? upstream : JSON.stringify(upstream) });
}
});
// ACL Management Endpoints
app.get('/api/headscale/acl', authenticateToken, async (req, res) => {
try {
const userEmail = req.user.email;
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const policyResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/policy`, { headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 });
let policy = policyResp.data.policy;
if (typeof policy === 'string') policy = JSON.parse(policy);
// Strip fields Headscale includes in GET but rejects on PUT (e.g. 'users')
const { groups, tagOwners, hosts, acls, ssh } = policy;
res.json({ groups: groups || {}, tagOwners: tagOwners || {}, hosts: hosts || {}, acls: acls || [], ssh: ssh || [] });
} catch (error) {
console.error('Failed to get ACL:', error.message);
res.status(500).json({ message: error.message });
}
});
app.post('/api/headscale/acl', authenticateToken, async (req, res) => {
const { groups, tagOwners, hosts, acls, ssh } = req.body;
try {
const userEmail = req.user.email;
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
// Keep #ha-meta fields (Headscale accepts them) — only filter rules missing required fields
const cleanAcls = (acls || [])
.filter(rule => rule.action && rule.src && rule.dst); // must have required fields
// Only send fields Headscale accepts — strip 'users' and any other extra fields
const policy = { groups: groups || {}, tagOwners: tagOwners || {}, hosts: hosts || {}, acls: cleanAcls, ssh: ssh || [] };
console.log('[ACL] Sending policy - groups:', Object.keys(groups||{}).length, 'hosts:', Object.keys(hosts||{}).length, 'acls:', cleanAcls.length);
// Safety: never save a completely empty/broken policy
const hasContent = Object.keys(groups||{}).length > 0 || Object.keys(hosts||{}).length > 0 || cleanAcls.length > 0;
if (!hasContent) {
console.error('[ACL] Refusing to save empty policy — this would wipe all rules');
return res.status(400).json({ message: 'Cannot save empty policy — all groups, hosts and rules are empty. Check your ACL editor.' });
}
const policyStr = JSON.stringify(policy);
const updateResp = await axios.put(`${tokenData.headscaleUrl}/api/v1/policy`, { policy: policyStr }, { headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 });
console.log('[ACL] Policy updated successfully - groups:', Object.keys(groups||{}).length, 'hosts:', Object.keys(hosts||{}).length, 'acls:', cleanAcls.length);
// Save to history
try {
ensureAclHistoryDir();
const now = new Date();
const ts = now.toISOString().replace(/[:.]/g, '-').slice(0, 19);
const uname = (req.user?.username || req.user?.email || 'unknown').replace(/[^a-zA-Z0-9]/g, '_').slice(0, 30);
fs.writeFileSync(`${ACL_HISTORY_DIR}/${ts}_${uname}.json`, JSON.stringify(policy, null, 2));
const allFiles = fs.readdirSync(ACL_HISTORY_DIR).filter(f => f.endsWith('.json')).sort();
if (allFiles.length > 20) allFiles.slice(0, allFiles.length - 20).forEach(f => { try { fs.unlinkSync(`${ACL_HISTORY_DIR}/${f}`); } catch {} });
} catch (he) { console.error('[ACL-HISTORY] Save failed:', he.message); }
res.json({ message: 'ACL updated', policy });
} catch (error) {
const errMsg = error.response?.data?.message || error.response?.data || error.message;
console.error('[ACL] Failed to update - Status:', error.response?.status, 'Error:', JSON.stringify(errMsg));
res.status(500).json({ message: typeof errMsg === 'string' ? errMsg : JSON.stringify(errMsg) });
}
});
app.get('/api/headscale/user-emails', authenticateToken, async (req, res) => {
try {
const data = fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8');
res.json(JSON.parse(data));
} catch (err) {
res.status(500).json({ message: 'Failed to read users' });
}
});
// GET api key labels from mapping file
app.get('/api/headscale/apikey/labels', authenticateToken, (req, res) => {
try {
const mapping = JSON.parse(fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8'));
res.json({ labels: mapping.api_key_labels || {}, owners: mapping.api_key_owners || {} });
} catch (e) {
res.json({ labels: {}, owners: {} });
}
});
// POST update a label for an api key prefix
app.post('/api/headscale/apikey/label', authenticateToken, (req, res) => {
const { prefix, label } = req.body;
if (!prefix) return res.status(400).json({ message: 'prefix required' });
try {
const mapping = JSON.parse(fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8'));
if (!mapping.api_key_labels) mapping.api_key_labels = {};
if (label === null || label === '') {
delete mapping.api_key_labels[prefix];
} else {
mapping.api_key_labels[prefix] = label;
}
fs.writeFileSync('/etc/headscale/users-mapping.json', JSON.stringify(mapping, null, 2));
res.json({ success: true, labels: mapping.api_key_labels });
} catch (e) {
res.status(500).json({ message: e.message });
}
});
// Group admin creates an API key for a user in their domain
app.post('/api/headscale/apikey/create-for-user', authenticateToken, async (req, res) => {
const { targetUsername, label, expiryDays } = req.body;
const adminEmail = req.user?.email;
const adminUsername = req.user?.username;
if (!targetUsername) return res.status(400).json({ message: 'targetUsername required' });
try {
const mapping = JSON.parse(fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8'));
const adminRecord = mapping.users?.[adminUsername] || {};
const targetRecord = mapping.users?.[targetUsername] || {};
// Check admin has permission for this user's domain
const adminDomains = adminRecord.manageable_domains || [];
const targetEmail = targetRecord.email || '';
const canManage = adminDomains.includes('*') || adminDomains.some(d => targetEmail.endsWith(d.replace('@','')));
if (!canManage) return res.status(403).json({ message: 'Not authorized to manage this user' });
// Get the admin's API key to create the new key
const tokenData = userTokenMap.get(adminEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
// Create the API key via headscale
const days = expiryDays || 90;
const expDate = new Date();
expDate.setDate(expDate.getDate() + days);
// Get user ID for the target user
const allUsersResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/user`, { headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 });
const targetUserObj = allUsersResp.data.users?.find((u) => u.name === targetUsername);
if (!targetUserObj) return res.status(400).json({ message: `User ${targetUsername} not found` });
const createResp = await axios.post(
`${tokenData.headscaleUrl}/api/v1/apikey`,
{ expiration: expDate.toISOString() },
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
const newKey = createResp.data.apiKey;
// Auto-label with target username
const autoLabel = label || `${targetUsername} - Login Key`;
// Get prefix from key list
const keysResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/apikey`, { headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 });
const keys = keysResp.data.apiKeys || [];
// Find the newest key (just created)
const newestKey = keys.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))[0];
if (newestKey) {
if (!mapping.api_key_labels) mapping.api_key_labels = {};
mapping.api_key_labels[newestKey.prefix] = autoLabel;
fs.writeFileSync('/etc/headscale/users-mapping.json', JSON.stringify(mapping, null, 2));
}
res.json({ apiKey: newKey, label: autoLabel, prefix: newestKey?.prefix });
} catch (e) {
console.error('[CREATE-FOR-USER]', e.message);
res.status(500).json({ message: e.message });
}
});
// ── Update checker ──────────────────────────────────────────────────────────
app.get('/api/headscale/check-update', authenticateToken, async (req, res) => {
try {
const currentVersion = require('./build/static/js/main.*.js') || '';
// Fetch latest commit from GitHub API
const ghResp = await axios.get(
'https://api.github.com/repos/HybridRCG/headscale-admin-react/commits/main',
{ headers: { 'User-Agent': 'hs-react-update-check' }, timeout: 5000 }
);
// Get version from latest commit message
const commitMsg = ghResp.data.commit?.message || '';
const match = commitMsg.match(/v(\d+\.\d+\.\d+)/);
const latestVersion = match ? match[1] : null;
res.json({ latestVersion, currentVersion: process.env.APP_VERSION || null });
} catch (e) {
res.json({ latestVersion: null, error: e.message });
}
});
// ── Registration / Licensing ────────────────────────────────────────────────
const HS_LICENSE_SECRET = process.env.HS_LICENSE_SECRET || 'CHANGE-THIS-TO-YOUR-PRIVATE-SECRET-MIN-32-CHARS';
const REGISTRATION_FILE = '/etc/headscale/registration.json';
function readRegistration() {
try { return JSON.parse(fs.readFileSync(REGISTRATION_FILE, 'utf8')); }
catch { return { registered: false }; }
}
function validateLicenseKey(key) {
try {
// Format: HSR-{CLIENTNAME}-{YEAR}-{12char HMAC}
const parts = key.trim().split('-');
if (parts.length < 4 || parts[0] !== 'HSR') return null;
const hmacPart = parts[parts.length - 1];
const payload = parts.slice(1, parts.length - 1).join('-');
const expected = require('crypto')
.createHmac('sha256', HS_LICENSE_SECRET)
.update(payload)
.digest('hex')
.substring(0, 12)
.toUpperCase();
if (hmacPart !== expected) return null;
return { valid: true, payload };
} catch { return null; }
}
app.post('/api/headscale/register', authenticateToken, (req, res) => {
const { key } = req.body;
if (!key) return res.status(400).json({ message: 'License key required' });
const result = validateLicenseKey(key);
if (!result) return res.status(400).json({ message: 'Invalid license key' });
try {
const reg = { registered: true, key: key.trim(), payload: result.payload, registeredAt: new Date().toISOString() };
fs.writeFileSync(REGISTRATION_FILE, JSON.stringify(reg, null, 2));
// Log to instances file for tracking
const instances = readInstances();
const existingIdx = instances.findIndex(i => i.payload === result.payload);
const instanceEntry = { payload: result.payload, registeredAt: new Date().toISOString(), domain: req.headers.host || 'unknown' };
if (existingIdx >= 0) instances[existingIdx] = instanceEntry;
else instances.push(instanceEntry);
try { fs.writeFileSync(INSTANCES_FILE, JSON.stringify(instances, null, 2)); } catch(e) {}
logAudit(req.user.username, 'register', 'instance registration', result.payload);
console.log('[REGISTER] Instance registered:', result.payload);
res.json({ success: true, payload: result.payload });
} catch (e) {
res.status(500).json({ message: 'Failed to save registration: ' + e.message });
}
});
app.get('/api/headscale/registration', authenticateToken, (req, res) => {
const reg = readRegistration();
res.json(reg);
});
app.post('/api/headscale/unregister', authenticateToken, (req, res) => {
try {
fs.writeFileSync(REGISTRATION_FILE, JSON.stringify({ registered: false }, null, 2));
logAudit(req.user.username, 'unregister', 'instance unregistered', '');
console.log('[UNREGISTER] Instance unregistered');
res.json({ success: true });
} catch (e) {
res.status(500).json({ message: 'Failed to unregister: ' + e.message });
}
});
// ── Registered Instances Log ────────────────────────────────────────────────
const INSTANCES_FILE = '/etc/headscale/registered-instances.json';
function readInstances() {
try { return JSON.parse(fs.readFileSync(INSTANCES_FILE, 'utf8')); }
catch { return []; }
}
app.get('/api/headscale/instances', authenticateToken, (req, res) => {
if (req.user?.role !== 'super_admin') return res.status(403).json({ message: 'Forbidden' });
res.json(readInstances());
});
// ── Audit Log ──────────────────────────────────────────────────────────────
const AUDIT_LOG_PATH = '/etc/headscale/audit-log.json';
const ACL_HISTORY_DIR = '/etc/headscale/acl-history';
function ensureAclHistoryDir() {
try { fs.mkdirSync(ACL_HISTORY_DIR, { recursive: true }); } catch {}
}
function readAuditLog() {
try {
return JSON.parse(fs.readFileSync(AUDIT_LOG_PATH, 'utf8'));
} catch { return []; }
}
function writeAuditLog(entries) {
// Keep last 1000 entries
const trimmed = entries.slice(-1000);
fs.writeFileSync(AUDIT_LOG_PATH, JSON.stringify(trimmed, null, 2));
}
function logAudit(actor, action, target, details) {
const entries = readAuditLog();
entries.push({
id: Date.now().toString() + Math.random().toString(36).substr(2,5),
timestamp: new Date().toISOString(),
actor: actor || 'unknown',
action,
target,
details: details || ''
});
writeAuditLog(entries);
}
app.delete('/api/headscale/audit-log', authenticateToken, (req, res) => {
if (req.user?.role !== 'super_admin') return res.status(403).json({ message: 'Forbidden' });
try {
fs.writeFileSync(AUDIT_LOG_PATH, JSON.stringify([], null, 2));
logAudit(req.user.username, 'clear', 'audit log', 'all entries cleared');
res.json({ success: true });
} catch (e) {
res.status(500).json({ message: e.message });
}
});
app.get('/api/headscale/audit-log/export', authenticateToken, (req, res) => {
if (req.user?.role !== 'super_admin') return res.status(403).json({ message: 'Forbidden' });
try {
const logs = readAuditLog();
const csv = [
'Timestamp,Actor,Action,Target,Details',
...logs.map(l => [
l.timestamp, l.actor, l.action,
`"${(l.target||'').replace(/"/g,'""')}"`,
`"${(l.details||'').replace(/"/g,'""')}"`
].join(','))
].join('\n');
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', `attachment; filename="audit-log-${new Date().toISOString().split('T')[0]}.csv"`);
res.send(csv);
} catch (e) {
res.status(500).json({ message: e.message });
}
});
app.get('/api/headscale/audit-log', authenticateToken, (req, res) => {
const entries = readAuditLog();
// Filter by manageable_domains for non-super_admins
res.json(entries.reverse()); // newest first
});
// Create pre-auth key - properly handles user lookup
app.post('/api/headscale/preauthkey/create', authenticateToken, async (req, res) => {
const { userId, reusable, ephemeral, expiration, tags } = req.body;
if (!userId) return res.status(400).json({ message: 'userId required' });
try {
const userEmail = req.user.email;
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
// Find user by id or name
const usersResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/user`, { headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 });
const allUsers = usersResp.data.users || [];
const targetUser = allUsers.find(u => String(u.id) === String(userId) || u.name === userId);
if (!targetUser) return res.status(400).json({ message: `User not found: ${userId}` });
// headscale v0.28 requires numeric user ID as string for the user field
// headscale v0.28 REST API requires user as uint64 (numeric ID)
const expDate = expiration ? new Date(expiration) : new Date(Date.now() + 90 * 24 * 60 * 60 * 1000);
if (expDate <= new Date()) expDate.setDate(expDate.getDate() + 90);
const payload = {
user: parseInt(targetUser.id, 10),
reusable: !!reusable,
ephemeral: !!ephemeral,
expiration: expDate.toISOString(),
};
if (tags && tags.length > 0) payload.aclTags = tags;
console.log('[PREAUTHKEY-CREATE] user id:', targetUser.id, 'expiry:', expDate.toISOString());
const resp = await axios.post(
`${tokenData.headscaleUrl}/api/v1/preauthkey`,
payload,
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
const key = resp.data.preAuthKey?.key || resp.data.pre_auth_key?.key || '';
logAudit(req.user.username, 'create-preauthkey', `user: ${targetUser.name}`, `reusable:${reusable} ephemeral:${ephemeral}`);
res.json({ key, user: targetUser.name });
} catch (e) {
console.error('[PREAUTHKEY-CREATE]', e.response?.data || e.message);
res.status(500).json({ message: e.response?.data?.message || e.message });
}
});
// Expire a pre-auth key - uses key ID via headscale CLI
app.post('/api/headscale/preauthkey/expire', authenticateToken, async (req, res) => {
const { user, key, id } = req.body;
if (!id && !key) return res.status(400).json({ message: 'id or key required' });
try {
const userEmail = req.user.email;
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
// If we have an ID use it, otherwise find it via the API
let keyId = id;
if (!keyId && user && key) {
const keysResp = await axios.get(
`${tokenData.headscaleUrl}/api/v1/preauthkey?user=${encodeURIComponent(user)}`,
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
const found = (keysResp.data.preAuthKeys || []).find(k => k.key === key);
if (!found) return res.status(404).json({ message: 'Key not found' });
keyId = found.id;
}
// Use headscale CLI to expire by ID
if (!/^[0-9]+$/.test(String(keyId))) return res.status(400).json({ message: 'Invalid key id' });
execSync(`docker exec headscale /ko-app/headscale preauthkeys expire --id ${keyId}`, { timeout: 10000 });
logAudit(req.user.username, 'expire-preauthkey', `user: ${user}`, `id: ${keyId}`);
res.json({ success: true });
} catch (e) {
console.error('[PREAUTHKEY-EXPIRE]', e.response?.data || e.message);
res.status(500).json({ message: e.response?.data?.message || e.message });
}
});
app.post('/api/headscale/user-emails', authenticateToken, async (req, res) => {
const userEmail = req.user?.email;
if (!userEmail) return res.status(401).json({ message: 'Unauthorized' });
try {
const currentData = JSON.parse(fs.readFileSync('/etc/headscale/users-mapping.json', 'utf8'));
const currentUser = Object.values(currentData.users).find(u => u.email === userEmail);
if (!currentUser || currentUser.role !== 'super_admin') {
return res.status(403).json({ message: 'Only super admins can modify users' });
}
const newData = req.body;
fs.writeFileSync('/etc/headscale/users-mapping.json', JSON.stringify(newData, null, 2));
res.json({ message: 'Users updated successfully' });
} catch (err) {
res.status(500).json({ message: 'Failed to update users: ' + err.message });
}
});
// ── Delete user — intercept before proxy to also clean up users-mapping.json ──
app.delete('/api/headscale/api/v1/user/:id', authenticateToken, async (req, res) => {
const userEmail = req.user?.email;
if (!userEmail) return res.status(401).json({ message: 'Unauthorized' });
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const userId = req.params.id;
try {
// Step 1: Get username from Headscale before deleting (so we know what to remove from mapping)
let username = null;
try {
const usersResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/user`, {
headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000
});
const user = (usersResp.data.users || []).find(u => String(u.id) === String(userId));
if (user) username = user.name;
} catch (e) {
console.error('[DELETE-USER] Failed to fetch users list:', e.message);
}
// Step 2: Delete from Headscale
const deleteResp = await axios.delete(`${tokenData.headscaleUrl}/api/v1/user/${userId}`, {
headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000
});
// Step 3: Remove from users-mapping.json
if (username) {
try {
const mapping = JSON.parse(fs.readFileSync(USERS_MAPPING_PATH, 'utf8'));
if (mapping.users && mapping.users[username]) {
delete mapping.users[username];
fs.writeFileSync(USERS_MAPPING_PATH, JSON.stringify(mapping, null, 2));
console.log(`[DELETE-USER] Removed ${username} from users-mapping.json`);
logAudit(req.user.username || userEmail, 'delete', `user:${username}`, `removed from Headscale and users-mapping.json`);
} else {
console.log(`[DELETE-USER] ${username} not found in users-mapping.json — skipping`);
}
} catch (e) {
console.error('[DELETE-USER] Failed to update users-mapping.json:', e.message);
// Don't fail the request — user was deleted from Headscale successfully
}
}
res.status(deleteResp.status).json(deleteResp.data);
} catch (error) {
console.error('[DELETE-USER] Error:', error.message);
if (error.response) res.status(error.response.status || 500).json({ message: error.response.data?.message || error.message });
else res.status(500).json({ message: error.message });
}
});
// ── Rename user — intercept to also update key in users-mapping.json ──────────
app.post('/api/headscale/api/v1/user/:id/rename/:newName', authenticateToken, async (req, res) => {
const userEmail = req.user?.email;
if (!userEmail) return res.status(401).json({ message: 'Unauthorized' });
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const { id: userId, newName } = req.params;
try {
// Step 1: Get old username before renaming
let oldName = null;
try {
const usersResp = await axios.get(`${tokenData.headscaleUrl}/api/v1/user`, {
headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000
});
const user = (usersResp.data.users || []).find(u => String(u.id) === String(userId));
if (user) oldName = user.name;
} catch (e) { console.error('[RENAME-USER] Failed to fetch users:', e.message); }
// Step 2: Rename in Headscale
const renameResp = await axios.post(`${tokenData.headscaleUrl}/api/v1/user/${userId}/rename/${newName}`, {}, {
headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000
});
// Step 3: Update key in users-mapping.json
if (oldName && oldName !== newName) {
try {
const mapping = JSON.parse(fs.readFileSync(USERS_MAPPING_PATH, 'utf8'));
if (mapping.users && mapping.users[oldName]) {
mapping.users[newName] = mapping.users[oldName];
delete mapping.users[oldName];
fs.writeFileSync(USERS_MAPPING_PATH, JSON.stringify(mapping, null, 2));
console.log(`[RENAME-USER] Renamed ${oldName} → ${newName} in users-mapping.json`);
logAudit(req.user.username || userEmail, 'rename', `user:${oldName}`, `renamed to ${newName} in Headscale and users-mapping.json`);
}
} catch (e) { console.error('[RENAME-USER] Failed to update mapping:', e.message); }
}
res.status(renameResp.status).json(renameResp.data);
} catch (error) {
if (error.response) res.status(error.response.status || 500).json({ message: error.response.data?.message || error.message });
else res.status(500).json({ message: error.message });
}
});
// ── Node Tags — set tags and preserve original owner ─────────────────────────
app.post('/api/headscale/node/tags', authenticateToken, async (req, res) => {
const userEmail = req.user?.email;
if (!userEmail) return res.status(401).json({ message: 'Unauthorized' });
const tokenData = userTokenMap.get(userEmail);
if (!tokenData) return res.status(401).json({ message: 'Session expired' });
const { nodeId, tags, originalOwner } = req.body;
if (!nodeId) return res.status(400).json({ message: 'nodeId required' });
try {
// Step 1: Set tags via Headscale API
const tagResp = await axios.post(
`${tokenData.headscaleUrl}/api/v1/node/${nodeId}/tags`,
{ tags: tags || [] },
{ headers: { Authorization: `Bearer ${tokenData.apiKey}` }, timeout: 10000 }
);
// Step 2: Preserve or clear owner in users-mapping.json node_owners
try {
const mapping = JSON.parse(fs.readFileSync(USERS_MAPPING_PATH, 'utf8'));
if (!mapping.node_owners) mapping.node_owners = {};
if (tags && tags.length > 0) {
// Save original owner before tagging overwrites it
if (originalOwner) {
mapping.node_owners[String(nodeId)] = originalOwner;
}
} else {