-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplugin.js
More file actions
3175 lines (3012 loc) · 102 KB
/
Copy pathplugin.js
File metadata and controls
3175 lines (3012 loc) · 102 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
/**
* Hermes Tailscale. Roster of the machines on this device's tailnet.
*
* One uncompiled plugin.js. Reads the installed Tailscale CLI through
* shell.exec (same door Resetwatch uses). LocalAPI is a named pipe / unix
* socket, so the renderer cannot call it. Cloud API tokens are not used.
*
* AUTHORING RULES (this file is loaded UNCOMPILED):
* - Single file. Relative specifiers do not resolve from a blob URL.
* - Do not write the word import followed by a quoted string in a comment.
* - No JSX. Use jsx() / jsxs() from react/jsx-runtime.
* - Only three specifiers resolve: the plugin SDK, react, and jsx-runtime.
* - Colors go through var(--ui-*). Never a hex.
*/
import * as sdk from '@hermes/plugin-sdk'
import { Fragment, useEffect, useMemo, useRef, useState } from 'react'
import { jsx, jsxs } from 'react/jsx-runtime'
const PLUGIN_ID = 'hermes-tailscale'
const PLUGIN_NAME = 'Tailscale'
const VERSION = '0.0.3'
const ROUTE = '/tailscale'
const PAGE_POLL_MS = 8 * 1000
const BAR_POLL_MS = 60 * 1000
const DOWNLOAD_URL = 'https://tailscale.com/download'
const QUAD100_URL = 'http://100.100.100.100'
const CACHE_FILE = 'status-cache.json'
const HERMES_PORT = 9119
const TAILDROP_AVAILABLE = 1
const XTERM_VERSION = '5.5.0'
const XTERM_FILE = 'xterm.js'
// SHA-384 of lib/xterm.js inside the @xterm/xterm@5.5.0 npm tarball. jsDelivr
// and unpkg serve that file byte for byte, so one pin covers both mirrors and
// a local copy. Never point this at a /+esm or .min.js URL: those are built
// per CDN and their bytes are not stable. Bump XTERM_VERSION and this hash
// together.
const XTERM_SHA384 = 'sha384-M169f14mRZOXm3hD/v2Ti0ThIT/RnAQagXA9nlE15yHAtrW19gdePJh/HaTzUOe/'
const XTERM_URLS = [
`https://cdn.jsdelivr.net/npm/@xterm/xterm@${XTERM_VERSION}/lib/${XTERM_FILE}`,
`https://unpkg.com/@xterm/xterm@${XTERM_VERSION}/lib/${XTERM_FILE}`
]
const host = sdk.host
const {
atom,
useValue,
ROUTES_AREA,
SIDEBAR_NAV_AREA,
PALETTE_AREA,
STATUSBAR_AREAS,
Tip,
haptic
} = sdk
const text = {
primary: 'var(--ui-text-primary)',
secondary: 'var(--ui-text-secondary)',
tertiary: 'var(--ui-text-tertiary)',
quaternary: 'var(--ui-text-quaternary)',
red: 'var(--ui-red)',
yellow: 'var(--ui-yellow)',
green: 'var(--ui-green)',
accent: 'var(--ui-accent)'
}
let storage = null
let os = null
let pollTimer = null
let inFlight = false
let pageMounted = 0
let cachedBin = null
let cachedRoot = ''
let cachedOutPath = null
let sshStop = null
let noticeTimer = null
let xtermCssInjected = false
let TerminalCtor = null
let xtermLoad = null
let sshReplay = { id: '', chunks: [], onChunk: null }
let sendStop = null
let sendClearTimer = null
const $snap = atom({ kind: 'idle' })
const $showShared = atom(false)
const $showOwner = atom(false)
const $dialog = atom(null)
const $ping = atom({})
const $ssh = atom(null)
const $sshAsk = atom(null)
const $publishAsk = atom(null)
const $notice = atom('')
const $send = atom(null)
const TAILDROP = {
0: '',
1: 'Can receive files',
2: 'No netmap yet',
3: 'Tailscale is not running',
4: 'Missing file-sharing capability',
5: 'Offline',
6: 'No peer info',
7: 'OS does not support Taildrop',
8: 'No PeerAPI',
9: 'Owned by another user'
}
// --- helpers (tested by tests/*.test.mjs, which slice this block out) ---
function errorMessage(error, fallback) {
if (typeof error === 'string' && error && error !== '[object Object]') return error
if (error && typeof error.message === 'string' && error.message && error.message !== '[object Object]') {
return error.message
}
return fallback
}
function platformKind(nav) {
const source = nav || (typeof navigator !== 'undefined' ? navigator : {})
const platform = String(source.platform || source.userAgentData && source.userAgentData.platform || '')
const ua = String(source.userAgent || '')
if (/Win/i.test(platform) || /Windows/i.test(ua)) return 'windows'
if (/Mac/i.test(platform) || /Mac OS/i.test(ua) || /iPhone|iPad|iPod/i.test(ua)) return 'darwin'
return 'linux'
}
function quoteShell(value, kind) {
const s = String(value)
if (kind === 'windows') return `"${s.replace(/"/g, '\\"')}"`
return `'${s.replace(/'/g, `'\\''`)}'`
}
function joinPath(root, parts, kind) {
const sep = kind === 'windows' ? '\\' : '/'
const clean = String(root || '').replace(/[\\/]+$/, '')
return [clean, ...parts].join(sep)
}
// Where to look for xterm, in order: a copy next to plugin.js, then each
// pinned CDN URL. Every candidate is checked against the same hash.
function xtermSources(root, kind, pluginId, fileName, urls) {
const out = []
if (root) out.push({ kind: 'file', path: joinPath(root, [pluginId, fileName], kind) })
for (const url of urls || []) out.push({ kind: 'url', url })
return out
}
function integrityMatches(expected, digestBase64) {
const want = String(expected || '').replace(/^sha384-/, '')
const got = String(digestBase64 || '')
return want.length === 64 && want === got
}
// Shadows the CommonJS and AMD globals so xterm's UMD header falls through
// to `root.Terminal = ...` with root = globalThis, then exports that.
function wrapXtermModule(text) {
return `let exports, module, define;\n${text}\nexport default globalThis.Terminal\n`
}
function bytesToBase64(bytes) {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
const table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
let out = ''
for (let i = 0; i < view.length; i += 3) {
const a = view[i]
const b = i + 1 < view.length ? view[i + 1] : 0
const c = i + 2 < view.length ? view[i + 2] : 0
const n = (a << 16) | (b << 8) | c
out += table[(n >> 18) & 63] + table[(n >> 12) & 63]
out += i + 1 < view.length ? table[(n >> 6) & 63] : '='
out += i + 2 < view.length ? table[n & 63] : '='
}
return out
}
function binaryCandidates(kind) {
if (kind === 'windows') {
return [
{ path: 'tailscale' },
{ path: 'tailscale.exe' },
{ path: 'C:\\Program Files\\Tailscale\\tailscale.exe' },
{ path: 'C:\\Program Files (x86)\\Tailscale\\tailscale.exe' }
]
}
if (kind === 'darwin') {
return [
{ path: 'tailscale' },
{ path: '/usr/local/bin/tailscale' },
{ path: '/opt/homebrew/bin/tailscale' },
{ path: '/Applications/Tailscale.app/Contents/MacOS/Tailscale', envPrefix: 'TAILSCALE_BE_CLI=1' }
]
}
return [
{ path: 'tailscale' },
{ path: '/usr/bin/tailscale' },
{ path: '/usr/local/bin/tailscale' },
{ path: '/snap/bin/tailscale' }
]
}
function binCommand(bin, args, kind) {
const exe = bin.envPrefix
? `${bin.envPrefix} ${quoteShell(bin.path, kind)}`
: quoteShell(bin.path, kind)
return `${exe} ${args}`
}
// Writes `tailscale status --json` to the cache file. On POSIX the file is
// created 0600 (umask) and an older, wider copy is tightened (chmod). On
// Windows the profile directory is already user-only, so plain redirect.
function statusRedirectCommand(bin, outPath, kind) {
const target = quoteShell(outPath, kind)
const write = `${binCommand(bin, 'status --json', kind)} > ${target}`
if (kind === 'windows') return write
return `umask 077 && ${write} && chmod 600 ${target}`
}
// Works from both cmd.exe and PowerShell on Windows, and any POSIX sh.
function removeCacheCommand(outPath, kind) {
if (kind === 'windows') return `cmd /c del /q ${quoteShell(outPath, kind)}`
return `rm -f ${quoteShell(outPath, kind)}`
}
function classifyCliError(result) {
const err = `${(result && result.stderr) || ''} ${(result && result.stdout) || ''}`
const code = result && result.code
if (code === 127 || code === 9009) return 'missing'
if (/not recognized|No such file or directory|cannot find the path|command not found/i.test(err)) {
return 'missing'
}
if (
/failed to connect to local tailscaled|cannot find the file specified|no such file or directory.*(?:sock|tailscaled)/i.test(
err
)
) {
return 'daemon'
}
if (/access denied|permission denied/i.test(err)) return 'denied'
return 'failed'
}
function isZeroTime(value) {
if (!value) return true
const t = Date.parse(value)
if (!Number.isFinite(t)) return true
return t < Date.parse('1971-01-01T00:00:00Z')
}
function dnsLabel(dnsName, suffix) {
let name = String(dnsName || '').replace(/\.$/, '')
const extra = String(suffix || '').replace(/^\.+|\.+$/g, '')
if (extra && name.toLowerCase().endsWith('.' + extra.toLowerCase())) {
name = name.slice(0, -(extra.length + 1))
}
return name
}
function ownerLabel(user) {
const login = user && (user.LoginName || user.DisplayName)
if (!login) return ''
const at = String(login).indexOf('@')
return at > 0 ? String(login).slice(0, at + 1) : String(login)
}
function osLabel(value) {
const x = String(value || '')
if (!x) return '—'
const lower = x.toLowerCase()
if (lower === 'macos' || lower === 'darwin') return 'macOS'
if (lower === 'windows') return 'Windows'
if (lower === 'linux') return 'Linux'
if (lower === 'ios') return 'iOS'
if (lower === 'android') return 'Android'
if (lower === 'tvos') return 'tvOS'
return x
}
function pathLabel(peer) {
if (!peer) return '—'
if (peer.CurAddr) return 'direct'
if (peer.Relay) return `relay ${peer.Relay}`
if (peer.Active) return 'active'
if (peer.Online) return 'idle'
return '—'
}
function formatLastSeen(value, nowMs) {
if (isZeroTime(value)) return ''
const then = Date.parse(value)
const now = nowMs || Date.now()
const delta = Math.max(0, now - then)
const minutes = Math.round(delta / 60000)
if (minutes < 1) return 'just now'
if (minutes < 60) return `${minutes}m ago`
const hours = Math.floor(minutes / 60)
if (hours < 48) return `${hours}h ago`
const days = Math.floor(hours / 24)
return `${days}d ago`
}
function formatKeyExpiry(value) {
if (!value) return ''
const t = Date.parse(value)
if (!Number.isFinite(t)) return String(value)
return new Date(t).toLocaleString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric'
})
}
function rowStatus(row) {
if (!row) return 'offline'
if (row.online) {
if (row.isSelf) return row.path && row.path !== 'this device' ? row.path : 'online'
if (row.path && row.path !== 'idle' && row.path !== 'active') return row.path
return 'online'
}
return row.lastSeen || 'offline'
}
function rowGrid(showOwner) {
return showOwner
? '14px minmax(140px, 1.8fr) 76px minmax(88px, 0.9fr) 132px minmax(92px, 0.9fr)'
: '14px minmax(160px, 2fr) 76px 132px minmax(100px, 1fr)'
}
function formatBytes(n) {
const x = Number(n)
if (!Number.isFinite(x) || x <= 0) return '0 B'
if (x < 1024) return `${Math.round(x)} B`
if (x < 1024 * 1024) return `${(x / 1024).toFixed(1).replace(/\.0$/, '')} KB`
if (x < 1024 * 1024 * 1024) return `${(x / (1024 * 1024)).toFixed(1).replace(/\.0$/, '')} MB`
return `${(x / (1024 * 1024 * 1024)).toFixed(1).replace(/\.0$/, '')} GB`
}
function ipv4Of(ips) {
if (!Array.isArray(ips)) return ''
const found = ips.find(ip => /^\d+\.\d+\.\d+\.\d+$/.test(String(ip)))
return found ? String(found) : ''
}
function ipv6Of(ips) {
if (!Array.isArray(ips)) return ''
const found = ips.find(ip => String(ip).includes(':'))
return found ? String(found) : ''
}
function tagList(tags) {
if (!tags) return []
if (Array.isArray(tags)) return tags.map(String)
if (Array.isArray(tags.Items)) return tags.Items.map(String)
return []
}
function taildropLabel(code) {
const n = Number(code)
if (!Number.isFinite(n) || n === 0) return ''
return TAILDROP[n] || `Taildrop ${n}`
}
function sshLine(row) {
const hostName = row && (row.label || row.hostName)
if (!hostName) return ''
return `tailscale ssh ${hostName}`
}
function onlineCount(rows) {
return (rows || []).filter(row => row.online).length
}
function parseStatus(raw, nowMs) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
const backend = String(raw.BackendState || '')
if (!backend) return null
const suffix = (raw.CurrentTailnet && raw.CurrentTailnet.MagicDNSSuffix) || raw.MagicDNSSuffix || ''
const users = raw.User && typeof raw.User === 'object' ? raw.User : {}
const selfPeer = raw.Self && typeof raw.Self === 'object' ? raw.Self : null
const peerMap = raw.Peer && typeof raw.Peer === 'object' ? raw.Peer : {}
function toRow(peer, isSelf) {
if (!peer || typeof peer !== 'object') return null
const ips = Array.isArray(peer.TailscaleIPs) ? peer.TailscaleIPs.map(String) : []
const user = users[peer.UserID] || users[String(peer.UserID)] || null
const label = dnsLabel(peer.DNSName, suffix) || peer.HostName || ipv4Of(ips) || 'unknown'
const dns = String(peer.DNSName || '').replace(/\.$/, '')
return {
id: String(peer.ID || peer.PublicKey || label),
isSelf: !!isSelf,
sharee: !!peer.ShareeNode,
label,
hostName: peer.HostName || '',
dns,
os: osLabel(peer.OS),
osRaw: peer.OS || '',
owner: ownerLabel(user),
ownerFull: (user && (user.LoginName || user.DisplayName)) || '',
ipv4: ipv4Of(ips),
ipv6: ipv6Of(ips),
ips,
online: !!peer.Online,
active: !!peer.Active,
path: isSelf ? (peer.Relay ? `home ${peer.Relay}` : 'this device') : pathLabel(peer),
lastSeen: formatLastSeen(peer.LastSeen, nowMs),
lastSeenRaw: peer.LastSeen || '',
rx: formatBytes(peer.RxBytes),
tx: formatBytes(peer.TxBytes),
tags: tagList(peer.Tags),
expired: !!peer.Expired,
keyExpiry: isZeroTime(peer.KeyExpiry) ? '' : formatKeyExpiry(peer.KeyExpiry),
taildrop: taildropLabel(peer.TaildropTarget),
taildropCode: Number(peer.TaildropTarget) || 0,
ssh: Array.isArray(peer.sshHostKeys) && peer.sshHostKeys.length > 0,
exitNode: !!peer.ExitNode,
exitNodeOption: !!peer.ExitNodeOption
}
}
const rows = []
const selfRow = toRow(selfPeer, true)
if (selfRow) rows.push(selfRow)
for (const key of Object.keys(peerMap)) {
const row = toRow(peerMap[key], false)
if (row) rows.push(row)
}
rows.sort((a, b) => {
if (a.isSelf !== b.isSelf) return a.isSelf ? -1 : 1
if (a.online !== b.online) return a.online ? -1 : 1
if (a.active !== b.active) return a.active ? -1 : 1
return a.label.localeCompare(b.label)
})
const exit = raw.ExitNodeStatus
return {
backend,
version: raw.Version || '',
tun: !!raw.TUN,
health: Array.isArray(raw.Health) ? raw.Health.map(String) : [],
suffix: String(suffix || ''),
tailnet: (raw.CurrentTailnet && raw.CurrentTailnet.Name) || '',
magicDns: !!(raw.CurrentTailnet && raw.CurrentTailnet.MagicDNSEnabled),
authUrl: raw.AuthURL || '',
selfIps: Array.isArray(raw.TailscaleIPs) ? raw.TailscaleIPs.map(String) : selfRow ? selfRow.ips : [],
exitNode: exit && exit.ID ? { id: String(exit.ID), online: !!exit.Online } : null,
rows
}
}
function visibleRows(status, showShared) {
const rows = (status && status.rows) || []
if (showShared) return rows
return rows.filter(row => row.isSelf || !row.sharee)
}
function emptyKind(status) {
if (!status) return 'failed'
if (status.backend === 'NeedsLogin' || status.backend === 'NeedsMachineAuth') return 'login'
if (status.backend === 'Stopped' || status.backend === 'NoState') return 'stopped'
if (status.backend === 'Starting') return 'starting'
return ''
}
function barLabel(snap) {
if (!snap || snap.kind === 'idle' || snap.kind === 'loading') return 'ts'
if (snap.kind === 'missing') return 'ts off'
if (snap.kind === 'daemon') return 'ts down'
if (snap.kind === 'denied') return 'ts denied'
if (snap.kind === 'gateway') return 'ts'
if (snap.kind === 'error') return 'ts'
if (snap.kind === 'ready') {
const kind = emptyKind(snap.status)
if (kind === 'login') return 'ts login'
if (kind === 'stopped') return 'ts stopped'
if (kind === 'starting') return 'ts …'
const n = onlineCount(visibleRows(snap.status, false))
return `ts ${n}`
}
return 'ts'
}
function barOk(snap) {
return snap && snap.kind === 'ready' && snap.status && snap.status.backend === 'Running'
}
function isSafeHost(value) {
const s = String(value || '')
if (!s || s.length > 253) return false
return /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(s)
}
function isSafeUser(value) {
const s = String(value || '').trim()
if (!s || s.length > 32) return false
return /^[A-Za-z_][A-Za-z0-9._-]*$/.test(s)
}
// A TCP port typed by the user. 0 means "not a port".
function parsePort(value) {
const s = String(value == null ? '' : value).trim()
if (!/^\d{1,5}$/.test(s)) return 0
const n = Number(s)
return n >= 1 && n <= 65535 ? n : 0
}
function serveArgs(port) {
return `serve --bg --yes ${parsePort(port)}`
}
// curl is on Windows 10+, macOS, and nearly every Linux. It only has to tell
// us whether something answers on the loopback port; the body is discarded.
// On Windows the .exe suffix skips PowerShell's curl alias (Invoke-WebRequest).
function portProbeCommand(port, kind) {
if (kind === 'windows') return `curl.exe -s -o NUL -m 3 http://127.0.0.1:${parsePort(port)}/`
return `curl -s -o /dev/null -m 3 http://127.0.0.1:${parsePort(port)}/`
}
// 'open' when something answered (any HTTP status), 'closed' when the
// connection was refused, 'unknown' when curl is missing or gave up.
function classifyPortProbe(result) {
if (!result) return 'unknown'
const code = Number(result.code)
if (code === 0 || code === 22) return 'open'
if (code === 7) return 'closed'
return 'unknown'
}
function sshSpec(user, dest) {
const u = String(user || '').trim()
const d = String(dest || '').trim()
if (!isSafeUser(u) || !isSafeHost(d)) return ''
return `${u}@${d}`
}
function parsePingOutput(text) {
const lines = String(text || '').split(/\r?\n/)
const pongs = []
for (const line of lines) {
const match = line.match(/^pong from (\S+) \(([^)]+)\) via (.+) in (\d+)\s*ms/i)
if (!match) continue
const via = match[3]
let path = 'direct'
if (/^DERP\(/i.test(via)) path = 'derp'
else if (/^peer-relay\(/i.test(via)) path = 'peer-relay'
pongs.push({ host: match[1], ip: match[2], via, ms: Number(match[4]), path })
}
const last = pongs.length ? pongs[pongs.length - 1] : null
return {
ok: pongs.length > 0,
last,
pongs,
directFailed: /direct connection not established/i.test(String(text || ''))
}
}
function pingSummary(parsed) {
if (!parsed || !parsed.last) return parsed && parsed.directFailed ? 'no path' : 'no reply'
const last = parsed.last
const path = last.path === 'derp' ? last.via : last.path === 'peer-relay' ? 'peer-relay' : 'direct'
return `${last.ms}ms ${path}`
}
function parseServeStatus(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return { empty: true, url: '', proxy: '', hostPort: '' }
}
const web = raw.Web
if (!web || typeof web !== 'object') return { empty: true, url: '', proxy: '', hostPort: '' }
const hostPort = Object.keys(web)[0] || ''
if (!hostPort) return { empty: true, url: '', proxy: '', hostPort: '' }
const handlers = web[hostPort] && web[hostPort].Handlers
let proxy = ''
if (handlers && typeof handlers === 'object') {
const keys = Object.keys(handlers)
const root = handlers['/'] || (keys.length ? handlers[keys[0]] : null)
proxy = (root && (root.Proxy || root.Path || '')) || ''
}
const url = /:\/\//.test(hostPort) ? hostPort : `https://${hostPort}`
return { empty: false, url, proxy: String(proxy), hostPort }
}
function parseSwitchList(raw) {
const list = Array.isArray(raw) ? raw : []
return list
.filter(row => row && (row.id || row.account))
.map(row => ({
id: String(row.id || ''),
nickname: String(row.nickname || row.account || ''),
tailnet: String(row.tailnet || ''),
account: String(row.account || ''),
selected: !!row.selected
}))
}
function canReceiveFiles(row) {
return !!(row && !row.isSelf && row.taildropCode === TAILDROP_AVAILABLE)
}
function exitNodeChoices(rows) {
return (rows || []).filter(row => !row.isSelf && (row.exitNodeOption || row.exitNode))
}
function shellLine(bin, args, kind) {
const rest = String(args || '').trim()
if (!bin || !bin.path) return rest
const pathName = String(bin.path)
if (kind === 'windows') {
if (!/[\\/]/.test(pathName)) return `tailscale ${rest}`
return `& ${quoteShell(pathName, 'windows')} ${rest}`
}
if (bin.envPrefix) return `${bin.envPrefix} ${quoteShell(pathName, kind)} ${rest}`
if (!pathName.includes('/')) return `tailscale ${rest}`
return `${quoteShell(pathName, kind)} ${rest}`
}
function ptyChunk(payload) {
if (payload == null) return ''
if (typeof payload === 'string') return payload
if (typeof payload === 'object' && typeof payload.data === 'string') return payload.data
return String(payload)
}
function stripPty(text) {
return String(text || '')
.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, '')
.replace(/\u001b\[(?:[0-9]*B|[0-9]*E)/g, '\n')
.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '')
.replace(/\u001b[PX^_].*?\u001b\\/g, '')
.replace(/[\u0000-\u0007\u000b\u000c\u000e-\u001a\u001c-\u001f]/g, '')
}
function applyPtyText(existing, incoming) {
let chunk = String(incoming || '')
.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, '')
.replace(/\u001b[PX^_].*?\u001b\\/g, '')
let out = String(existing || '')
if (out.endsWith('\r')) {
out = out.slice(0, -1)
chunk = `\r${chunk}`
}
const clearLine = () => {
const lastNl = out.lastIndexOf('\n')
out = lastNl >= 0 ? out.slice(0, lastNl + 1) : ''
}
let i = 0
while (i < chunk.length) {
const ch = chunk[i]
if (ch === '\u001b') {
if (chunk[i + 1] === '[') {
const match = chunk.slice(i).match(/^\u001b\[([0-9;?]*)([@-~])/)
if (match) {
const cmd = match[2]
const n = parseInt(match[1], 10)
i += match[0].length
if (cmd === 'G' && (!n || n <= 1)) clearLine()
else if (cmd === 'K' && (n === 1 || n === 2)) clearLine()
else if (cmd === 'A' || cmd === 'F') {
const count = Number.isFinite(n) && n > 0 ? n : 1
for (let k = 0; k < count; k += 1) {
if (out.endsWith('\n')) out = out.slice(0, -1)
clearLine()
}
} else if (cmd === 'B' || cmd === 'E') {
const count = Number.isFinite(n) && n > 0 ? n : 1
out += '\n'.repeat(count)
}
continue
}
}
i += 1
continue
}
if (ch === '\r') {
if (i === chunk.length - 1) {
out += '\r'
break
}
if (chunk[i + 1] === '\n') {
out += '\n'
i += 2
continue
}
clearLine()
i += 1
continue
}
if (ch === '\n') {
out += '\n'
i += 1
continue
}
if (ch === '\b') {
if (out.length && out[out.length - 1] !== '\n') out = out.slice(0, -1)
i += 1
continue
}
if (ch < ' ' && ch !== '\t') {
i += 1
continue
}
out += ch
i += 1
}
return out.slice(-24000)
}
function pathBase(filePath) {
const s = String(filePath || '').replace(/\\/g, '/')
const trimmed = s.replace(/\/+$/, '')
const i = trimmed.lastIndexOf('/')
return (i >= 0 ? trimmed.slice(i + 1) : trimmed) || String(filePath || '')
}
function isSafeFilePath(filePath) {
const s = String(filePath || '')
return !!s && !/[\r\n\0"]/.test(s)
}
function quoteCmdArg(value) {
return `"${String(value).replace(/"/g, '')}"`
}
function fileCpCommand(bin, kind, filePath, dest) {
if (kind === 'windows') {
const exe = bin && bin.path && /[\\/]/.test(String(bin.path)) ? String(bin.path) : 'tailscale'
return `echo HERMES_SEND_START\rcmd --% /c call ${quoteCmdArg(exe)} file cp ${quoteCmdArg(filePath)} ${quoteCmdArg(dest)}\rif ($null -ne $LASTEXITCODE) { exit $LASTEXITCODE }\rexit 0\r`
}
const args = `file cp ${quoteShell(filePath, kind)} ${quoteShell(dest, kind)}`
const line = shellLine(bin, args, kind)
return `echo HERMES_SEND_START; ${line}; echo HERMES_SEND_DONE:$?; exit $?\r`
}
function parseFileCpProgress(existingLog, incoming) {
const log = applyPtyText(existingLog, incoming)
const lines = log.replace(/\r/g, '\n').split('\n')
let percent = null
let rate = ''
let eta = ''
let size = ''
let warning = ''
const extra = []
for (let i = 0; i < lines.length; i += 1) {
const line = String(lines[i] || '').replace(/\s+/g, ' ').trim()
if (!line) continue
if (/^# warning:/i.test(line)) {
warning = line.replace(/^#\s*warning:\s*/i, '')
continue
}
const pct = line.match(/(\d+(?:\.\d+)?)%/)
const rateMatch = line.match(/(\d+(?:\.\d+)?(?:Ki|Mi|Gi|Ti)?B\/s)/i)
const etaMatch = line.match(/ETA\s+(\d{2}:\d{2}:\d{2}|-)/i)
const sizeMatch = line.match(/(\d+(?:\.\d+)?(?:Ki|Mi|Gi|Ti)?B)(?!\/)/i)
if (pct) {
percent = Math.max(0, Math.min(100, Number(pct[1])))
if (rateMatch) rate = rateMatch[1]
if (etaMatch && etaMatch[1] !== '-') eta = etaMatch[1]
if (sizeMatch) size = sizeMatch[1]
continue
}
if (/^PS /i.test(line) || /HERMES_SEND_/.test(line)) continue
if (/^cmd --%/i.test(line) || /^echo HERMES_/i.test(line)) continue
extra.push(line)
}
const detail = extra.length ? extra[extra.length - 1].slice(0, 180) : ''
return {
log: log.slice(-12000),
percent,
rate,
eta,
size,
warning,
extra,
detail,
started: /HERMES_SEND_START/.test(log)
}
}
function sendStatusText(job) {
if (!job) return ''
if (job.state === 'ok') return `Sent ${job.name} to ${job.label}`
if (job.state === 'err') return job.text || `Could not send ${job.name}`
const bits = [`Sending ${job.name}`]
if (job.percent != null && Number.isFinite(job.percent)) {
const n = job.percent
bits.push(`${Number.isInteger(n) ? n : n.toFixed(1).replace(/\.0$/, '')}%`)
}
if (job.size) bits.push(job.size)
if (job.rate) bits.push(job.rate)
if (job.eta) bits.push(`ETA ${job.eta}`)
else if (job.detail && job.percent == null) bits.push(job.detail)
return bits.join(' · ')
}
// --- runtime ---
function tap() {
if (typeof haptic === 'function') haptic('tap')
}
function stored(key, fallback) {
return storage ? storage.get(key, fallback) : fallback
}
function remember(key, value) {
if (storage) storage.set(key, value)
}
function go(route) {
if (typeof host.navigate === 'function') host.navigate(route)
}
function desktop() {
return typeof window !== 'undefined' ? window.hermesDesktop : null
}
async function runShell(command) {
return host.request('shell.exec', { command })
}
async function resolvePluginsRoot() {
if (cachedRoot) return cachedRoot
const bridge = desktop()
if (bridge && typeof bridge.desktopPluginsRoot === 'function') {
try {
const root = await bridge.desktopPluginsRoot()
if (root) {
cachedRoot = String(root)
return cachedRoot
}
} catch {
/* older shell */
}
}
return ''
}
async function resolveOutPath(kind) {
if (cachedOutPath) return cachedOutPath
const root = await resolvePluginsRoot()
if (!root) return ''
cachedOutPath = joinPath(root, [PLUGIN_ID, CACHE_FILE], kind)
return cachedOutPath
}
// Best effort. The gateway may already be gone when the plugin unloads.
function removeCacheFile() {
const path = cachedOutPath
if (!path) return
try {
runShell(removeCacheCommand(path, platformKind())).catch(() => {})
} catch {
/* gateway closed first */
}
}
async function readCacheFile(path) {
const bridge = desktop()
if (!bridge || typeof bridge.readFileText !== 'function' || !path) return ''
const result = await bridge.readFileText(path)
if (!result || result.truncated) return ''
return String(result.text || '')
}
function looksCompleteJson(text) {
const s = String(text || '').trim()
return s.startsWith('{') && s.endsWith('}')
}
async function probeBinary(kind) {
if (cachedBin) return { bin: cachedBin, error: null, kind: 'ok' }
const failures = []
for (const bin of binaryCandidates(kind)) {
try {
const result = await runShell(binCommand(bin, 'version --json', kind))
if (!result || result.code) {
const why = classifyCliError(result)
failures.push(why)
if (why === 'daemon' || why === 'denied') return { bin: null, error: result, kind: why }
continue
}
cachedBin = bin
return { bin, error: null, kind: 'ok' }
} catch (error) {
const message = errorMessage(error, '')
if (/gateway unavailable/i.test(message)) return { bin: null, error: { message }, kind: 'gateway' }
failures.push('failed')
}
}
const kindOut = failures.includes('daemon') ? 'daemon' : failures.includes('denied') ? 'denied' : 'missing'
return { bin: null, error: null, kind: kindOut }
}
async function loadSnapshot() {
const gateway = host.state && host.state.gateway ? host.state.gateway.get() : ''
if (gateway && gateway !== 'open') {
return { kind: 'gateway', message: 'Hermes is not connected, so the Tailscale CLI cannot run.' }
}
const kind = platformKind()
const probed = await probeBinary(kind)
if (probed.kind === 'gateway') {
return { kind: 'gateway', message: 'Hermes is not connected, so the Tailscale CLI cannot run.' }
}
if (probed.kind === 'missing') {
return { kind: 'missing', message: 'Tailscale is not installed on this machine.' }
}
if (probed.kind === 'daemon') {
return { kind: 'daemon', message: 'Tailscale is installed, but the daemon is not running.' }
}
if (probed.kind === 'denied') {
return { kind: 'denied', message: 'This user cannot talk to the local Tailscale daemon.' }
}
if (!probed.bin) {
return { kind: 'error', message: 'Could not run the Tailscale CLI.' }
}
const outPath = await resolveOutPath(kind)
let rawText = ''
try {
if (outPath) {
const redirected = await runShell(statusRedirectCommand(probed.bin, outPath, kind))
if (redirected && redirected.code) {
const why = classifyCliError(redirected)
if (why === 'daemon') {
return { kind: 'daemon', message: 'Tailscale is installed, but the daemon is not running.' }
}
// A missing cache directory looks like "cannot find the path" on
// Windows. The version probe already proved the binary exists, so
// fall through to the inline status read.
} else {
rawText = await readCacheFile(outPath)
}
}
if (!looksCompleteJson(rawText)) {
const inline = await runShell(binCommand(probed.bin, 'status --json', kind))
if (inline && inline.code) {
const why = classifyCliError(inline)
if (why === 'missing') {
cachedBin = null
return { kind: 'missing', message: 'Tailscale is not installed on this machine.' }
}
if (why === 'daemon') {
return { kind: 'daemon', message: 'Tailscale is installed, but the daemon is not running.' }
}
const err = String((inline && inline.stderr) || '').trim()
return { kind: 'error', message: err || 'tailscale status failed' }
}
rawText = String((inline && inline.stdout) || '')
}
} catch (error) {
const message = errorMessage(error, 'Could not run tailscale status')
if (/gateway unavailable/i.test(message)) {
return { kind: 'gateway', message: 'Hermes is not connected, so the Tailscale CLI cannot run.' }
}
return { kind: 'error', message }
}
const trimmed = rawText.trim()
if (!looksCompleteJson(trimmed)) {
return {
kind: 'error',
message: 'Tailscale status was truncated. Hermes only returns the last 4k of a shell command, and the cache file could not be read.'
}
}
let parsed
try {
parsed = JSON.parse(trimmed)
} catch {
return { kind: 'error', message: 'Tailscale status was not valid JSON.' }
}
const status = parseStatus(parsed, Date.now())
if (!status) return { kind: 'error', message: 'Tailscale status JSON was missing BackendState.' }
let serve = { empty: true, url: '', proxy: '', hostPort: '' }
let accounts = []
try {
const serveRun = await runShell(binCommand(probed.bin, 'serve status --json', kind))
if (serveRun && !serveRun.code) {
const textOut = String((serveRun.stdout || '')).trim() || '{}'
serve = parseServeStatus(JSON.parse(textOut))
}
} catch {
/* serve status is optional */
}
try {
const switchRun = await runShell(binCommand(probed.bin, 'switch --list --json', kind))
if (switchRun && !switchRun.code) {
const textOut = String((switchRun.stdout || '')).trim() || '[]'
accounts = parseSwitchList(JSON.parse(textOut))
}
} catch {
/* switch list is optional */
}
return { kind: 'ready', status, serve, accounts, at: Date.now() }
}
async function refresh() {
if (inFlight) return
inFlight = true
if ($snap.get().kind === 'idle') $snap.set({ kind: 'loading' })
try {