Repository navigation
Expand file tree
/
Copy pathtm.py
More file actions
2219 lines (1956 loc) · 87.9 KB
/
Copy pathtm.py
File metadata and controls
2219 lines (1956 loc) · 87.9 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
"""Tunnel Management (TM) — multi-server tunnel-chain control plane.
The visual graph is the *source of truth*. It is validated, the role of every
participant is derived from topology, per-hop routes are computed, and the
resulting participant configuration is pushed to every real SpiderPanel server
in the chain over the existing authenticated Node (SPI-key) channel.
Nothing in this module duplicates the Node subsystem: TM reuses the same
``NODES`` storage, the same ``spdr_`` key handling, the same ``_probe_node``
health code, the same VLESS relay/proxy pipeline and the same state file.
TM only owns the parts that did not exist before — the graph overlay
(positions, edges, Set selection), the chain algorithm and the TM inbound.
The module never imports ``main`` at import time: it resolves the already
loaded application module lazily through ``sys.modules["main"]`` (the same
pattern ``main._get_main()`` uses), which keeps the import graph acyclic.
"""
from __future__ import annotations
import asyncio
import json
import math
import secrets
import sys
import time
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Request, WebSocket
from fastapi.responses import JSONResponse
# ── Constants ───────────────────────────────────────────────────────────────
TM_INBOUND_ID = "tm"
TM_INBOUND_NAME = "TM"
TM_MANAGED_KIND = "tm"
TM_PROTOCOL = "tm"
TM_PUBLIC_PORT = 443
# Path templates. ``{uuid}`` is substituted with the user's existing
# ``config_uuid`` — TM never invents a second identifier.
TM_ENTRY_PATH_TEMPLATE = "/ws/TM/{uuid}" # node has no next hop → exits here
TM_FORWARD_PATH_TEMPLATE = "/ws/nextTM/{uuid}" # node has a next hop → forwards
EDGE_STYLE_STRAIGHT = "straight"
EDGE_STYLE_CURVED = "curved"
def _clean_edge(edge: dict) -> dict:
"""Normalize one edge from the browser: known direction, valid style, a
bounded `bend` (how far the operator dragged the bar off its cord, 0 =
straight). Returns None when the input is unusable."""
src, dst = str(edge.get("from") or ""), str(edge.get("to") or "")
if not src or not dst or src == dst:
return None
try:
bend = float(edge.get("bend")) if edge.get("bend") is not None else None
except (TypeError, ValueError):
bend = None
if bend is not None and not (math.isfinite(bend)):
bend = None
if bend is not None:
bend = max(-70.0, min(70.0, bend))
style = str(edge.get("style") or EDGE_STYLE_CURVED).lower()
return {
"id": str(edge.get("id") or f"edge_{secrets.token_hex(4)}"),
"from": src,
"to": dst,
"style": style if style in (EDGE_STYLE_CURVED, EDGE_STYLE_STRAIGHT) else EDGE_STYLE_CURVED,
# Persisted only so a dragged bar keeps its shape after a reload; the
# runtime never reads it.
"bend": bend,
}
# Roles (derived, never configured by hand).
ROLE_INITIAL = "initial"
ROLE_MIDDLE = "middle"
ROLE_FINAL = "final"
def _m():
"""The already-loaded application module (never a second copy)."""
mod = sys.modules.get("main")
if mod is None:
raise RuntimeError("main module is not initialized")
return mod
# ── TM state (persisted inside the panel's own state file) ──────────────────
# TM keeps ONLY what the plain Node records do not have: the graph overlay.
# Server credentials stay in NODES; this structure is safe to hand to the
# browser once ``_safe_servers()`` strips it down.
TM_STATE: dict = {
"enabled": False,
"positions": {}, # node_id -> {"x": float, "y": float}
"edges": [], # [{"id", "from", "to", "style", "bend"}]
"active_server": "", # the "Set" server used for config generation
"applied": None, # last known-good applied topology
"participant": None, # this panel's own role, pushed by the entry panel
"last_apply": "",
"last_error": "",
"last_validate": None,
}
TM_LOCK = asyncio.Lock()
def load_state(data) -> None:
"""Restore TM state from the persisted panel state (called by load_state).
Node records are loaded before TM, so unknown servers (deleted nodes) are
dropped here instead of leaving orphan positions/edges behind.
"""
if not isinstance(data, dict):
return
try:
known = set(_live_servers().keys())
except Exception:
known = set()
positions = data.get("positions")
if isinstance(positions, dict):
cleaned = {}
for nid, pos in positions.items():
if not isinstance(pos, dict):
continue
nid = str(nid)
if known and nid not in known:
continue
try:
cleaned[nid] = {"x": float(pos.get("x") or 0), "y": float(pos.get("y") or 0)}
except (TypeError, ValueError):
continue
TM_STATE["positions"] = cleaned
edges = data.get("edges")
if isinstance(edges, list):
seen = set()
cleaned_edges = []
for edge in edges:
if not isinstance(edge, dict):
continue
src, dst = str(edge.get("from") or ""), str(edge.get("to") or "")
if not src or not dst or src == dst or (src, dst) in seen:
continue
if known and (src not in known or dst not in known):
continue
cleaned = _clean_edge(edge)
if cleaned is None:
continue
seen.add((src, dst))
cleaned_edges.append(cleaned)
TM_STATE["edges"] = cleaned_edges
active = str(data.get("active_server") or "")
TM_STATE["active_server"] = active if (not known or active in known) else ""
TM_STATE["enabled"] = bool(data.get("enabled"))
TM_STATE["last_apply"] = str(data.get("last_apply") or "")
TM_STATE["last_error"] = str(data.get("last_error") or "")
applied = data.get("applied")
if isinstance(applied, dict):
TM_STATE["applied"] = applied
participant = data.get("participant")
if isinstance(participant, dict):
TM_STATE["participant"] = participant
TM_STATE["last_validate"] = data.get("last_validate")
def dump_state() -> dict:
"""The exact TM slice written into the panel state file."""
return {
"enabled": bool(TM_STATE.get("enabled")),
"positions": dict(TM_STATE.get("positions") or {}),
"edges": [dict(e) for e in (TM_STATE.get("edges") or [])],
"active_server": str(TM_STATE.get("active_server") or ""),
"applied": TM_STATE.get("applied"),
"participant": TM_STATE.get("participant"),
"last_apply": str(TM_STATE.get("last_apply") or ""),
"last_error": str(TM_STATE.get("last_error") or ""),
"last_validate": TM_STATE.get("last_validate"),
}
async def _save():
await _m().save_state()
def _now() -> str:
return datetime.now().isoformat()
# ── Server access (reuses the ordinary Node records) ────────────────────────
def _live_servers() -> dict:
"""Every ordinary Node is a TM candidate server; the graph selects which
of them actually participate."""
main = _m()
return dict(main.NODES)
def _normalize_positions(positions: dict, server_ids: list) -> dict:
"""Keep positions JSON-serializable and bounded to real servers."""
known = set(server_ids)
out = {}
for nid, pos in (positions or {}).items():
nid = str(nid)
if nid not in known or not isinstance(pos, dict):
continue
try:
out[nid] = {"x": round(float(pos.get("x") or 0), 1), "y": round(float(pos.get("y") or 0), 1)}
except (TypeError, ValueError):
continue
return out
def _edge_nodes() -> set:
ids = set()
for edge in TM_STATE.get("edges") or []:
ids.add(str(edge.get("from") or ""))
ids.add(str(edge.get("to") or ""))
return {x for x in ids if x}
def _tm_server_ids() -> list:
"""Nodes that are part of the graph (have an edge) — the active members."""
return sorted(_edge_nodes())
def _node_name(node_id: str) -> str:
node = _live_servers().get(node_id) or {}
return str(node.get("name") or node.get("domain") or node_id)
def _default_position(index: int, total: int) -> dict:
"""Deterministic fallback layout so a node added in Server has a place to
live in Configure before the admin drags it."""
if total <= 1:
return {"x": 260.0, "y": 220.0}
cols = max(1, min(4, total))
col = index % cols
row = index // cols
return {"x": 160.0 + col * 220.0, "y": 120.0 + row * 170.0}
def _ensure_position(node_id: str, index: int, total: int) -> dict:
positions = TM_STATE.setdefault("positions", {})
pos = positions.get(node_id)
if not isinstance(pos, dict):
pos = _default_position(index, total)
positions[node_id] = pos
return pos
def _safe_servers() -> list:
"""Browser-safe server metadata: never the API key, never the raw record."""
main = _m()
out = []
live = _live_servers()
member_ids = _edge_nodes()
ordered = sorted(live.keys(), key=lambda nid: str((live.get(nid) or {}).get("created_at") or ""), reverse=True)
for index, nid in enumerate(ordered):
node = live.get(nid) or {}
view = main._node_public_view(nid, node)
pos = _ensure_position(nid, index, max(1, len(ordered)))
out.append({
"node_id": nid,
"name": view.get("name") or nid,
"domain": view.get("domain") or "",
"status": view.get("status") or "offline",
"api_key_masked": view.get("api_key_masked") or "",
"server_latency_ms": view.get("latency_ms"),
"country": view.get("country") or "",
"country_flag": view.get("country_flag") or "🌐",
"public_ip": view.get("public_ip") or "",
"last_seen": view.get("last_seen"),
"last_error": view.get("last_error") or "",
"created_at": view.get("created_at") or "",
"in_graph": nid in member_ids,
"x": pos.get("x", 0.0),
"y": pos.get("y", 0.0),
})
return out
def _server_payload(node_id: str, node: dict) -> dict:
"""The subset of a Node that TM pushes/uses server-side (contains the key —
this value never leaves a server-to-server channel or the state file)."""
return {
"node_id": node_id,
"name": node.get("name") or node_id,
"domain": node.get("domain") or "",
"api_key": node.get("api_key") or "",
"remote_tls_ws": dict(node.get("remote_tls_ws") or {}),
"status": node.get("status") or "",
}
# ── Topology: validation, roles, routes ─────────────────────────────────────
class TopologyError(Exception):
def __init__(self, message: str, errors: list | None = None):
super().__init__(message)
self.message = message
self.errors = errors or [message]
def _cycle_path(edges: list, nodes: list) -> list | None:
"""Return the node-id cycle when the graph is not a DAG (else None)."""
adjacency = {nid: [] for nid in nodes}
for edge in edges:
adjacency.setdefault(edge["from"], []).append(edge["to"])
WHITE, GREY, BLACK = 0, 1, 2
color = {nid: WHITE for nid in nodes}
stack: list = []
def visit(nid: str) -> list | None:
color[nid] = GREY
stack.append(nid)
for nxt in adjacency.get(nid, []):
if color.get(nxt, WHITE) == GREY:
idx = stack.index(nxt) if nxt in stack else 0
return stack[idx:] + [nxt]
if color.get(nxt, WHITE) == WHITE:
found = visit(nxt)
if found:
return found
stack.pop()
color[nid] = BLACK
return None
for nid in nodes:
if color.get(nid, WHITE) == WHITE:
found = visit(nid)
if found:
return found
return None
def _compute_topology(edges: list, server_ids: list, active_server: str) -> dict:
"""Derive roles, per-node routes and the active chain from the graph.
The graph is a layered DAG:
* level 0 → every node is an *Initial* server
* last level → every node is a *Final* server
* anything between → *Middle*
A node with several outgoing edges forms a **balancer group**: the entry
tries its next hops in order and falls through to the next one when a hop is
unreachable, so `A → {B, C, D} → E` uses all three middles automatically.
Fan-in is allowed only when every predecessor belongs to one and the same
parallel group (they share a single upstream), so `E` above is reachable
from `B`, `C` and `D` while an accidental `X → E` merge is still rejected.
Components that do not contain the active server stay idle and are
reported, never silently mixed into the live chain.
"""
next_of: dict = {}
prev_of: dict = {}
for edge in edges:
next_of.setdefault(edge["from"], [])
if edge["to"] not in next_of[edge["from"]]:
next_of[edge["from"]].append(edge["to"])
prev_of.setdefault(edge["to"], [])
if edge["from"] not in prev_of[edge["to"]]:
prev_of[edge["to"]].append(edge["from"])
id_set = set(server_ids)
# Only servers that actually carry an edge participate in the chain
# analysis; servers that have never been connected are idle candidates,
# not opposing chains (that would make any two unconnected servers look
# ambiguous). A single unconnected server is still a valid Initial+Final
# chain on its own.
# `next_of` and `prev_of` are both keyed by the node the edge touches, so
# only the KEYS are participants (taking prev_of's values would name the
# upstream server twice and lose the downstream one).
participating = {nid for nid in next_of if nid in id_set}
participating |= {nid for nid in prev_of if nid in id_set}
heads = [nid for nid in server_ids if nid in participating and not prev_of.get(nid)]
def walk(start: str) -> list:
"""Levels reachable from `start`: [[entry], [parallel middles], …]."""
levels: list = [[start]]
seen = {start}
frontier = [start]
while frontier:
nxt: list = []
for node in frontier:
for child in next_of.get(node, []):
if child not in seen:
seen.add(child)
nxt.append(child)
if not nxt:
break
levels.append(nxt)
frontier = nxt
return levels
chains: list = [] # level lists
flat_chains: list = [] # same, flattened — the shape tests and the UI read
placed: set = set()
for head in heads:
levels = walk(head)
if head in placed:
continue
for level in levels:
for nid in level:
placed.add(nid)
chains.append(levels)
flat_chains.append([nid for level in levels for nid in level])
# Standalone servers (no edges at all): each is its own one-node chain.
standalone = [nid for nid in server_ids if nid not in participating]
for nid in standalone:
chains.append([[nid]])
flat_chains.append([nid])
placed.add(nid)
# A node whose edges point at an unknown id would have been dropped —
# surface it instead of losing it silently.
leftovers = [nid for nid in server_ids if nid not in placed]
roles: dict = {}
for levels, flat in zip(chains, flat_chains):
size = len(flat)
last_index = len(levels) - 1
for level_index, level in enumerate(levels):
has_next = level_index < last_index
for position, nid in enumerate(level):
if level_index == 0 and last_index == 0:
# A single-node chain is both ends: Initial + Final (spec §6).
role = "initial_final"
elif level_index == 0:
role = ROLE_INITIAL
elif level_index == last_index:
role = ROLE_FINAL
else:
role = ROLE_MIDDLE
nexts = list(next_of.get(nid, [])) if has_next else []
prevs = list(prev_of.get(nid, [])) if level_index > 0 else []
flat_pos = sum(len(levels[i]) for i in range(level_index)) + position
roles[nid] = {
"node_id": nid,
"name": _node_name(nid),
"chain_position": flat_pos,
"chain_length": size,
"level": level_index,
"level_size": len(level),
"initial": level_index == 0,
"middle": 0 < level_index < last_index,
"final": level_index == last_index,
"prev_node_id": prevs[0] if prevs else None,
"prev_node_ids": prevs,
# A node with several next hops *is* the balancer.
"next_node_id": nexts[0] if nexts else None,
"next_node_ids": nexts,
"balancer": len(nexts) > 1,
"role": role,
"role_label": ("Initial + Final" if role == "initial_final"
else ROLE_INITIAL.capitalize() if role == ROLE_INITIAL
else ROLE_FINAL.capitalize() if role == ROLE_FINAL
else "Middle"),
"ingress_path": (TM_FORWARD_PATH_TEMPLATE if nexts else TM_ENTRY_PATH_TEMPLATE),
}
active_chain: list = []
active_levels: list = []
if active_server:
for levels, flat in zip(chains, flat_chains):
if active_server in flat:
active_chain = list(flat)
active_levels = levels
break
if not active_chain:
# With no Set, the single chain the operator actually built is the live
# one. Servers that were never connected are idle candidates, not
# competing chains.
edge_ids = set(participating)
built = [(levels, flat) for levels, flat in zip(chains, flat_chains) if flat and flat[0] in edge_ids]
if len(built) == 1:
active_levels, active_chain = built[0][0], list(built[0][1])
elif not built and len(chains) == 1:
# One unconnected server is a valid Initial + Final chain.
active_levels, active_chain = chains[0], list(flat_chains[0])
if not active_chain and active_server and active_server in id_set:
active_levels = [[active_server]]
active_chain = [active_server]
active_set = set(active_chain)
idle = [nid for flat in flat_chains for nid in flat if nid not in active_set]
return {
"chains": flat_chains,
"levels": active_levels,
"roles": roles,
"leftovers": leftovers,
"active_chain": active_chain,
"idle": idle,
}
def validate_graph(edges: list, server_ids: list, active_server: str = "") -> dict:
"""Validate the topology. Raises TopologyError with a human message."""
known = set(server_ids)
seen_pairs = set()
for edge in edges:
src, dst = str(edge.get("from") or ""), str(edge.get("to") or "")
if not src or not dst:
raise TopologyError("Invalid TM topology: an edge is missing a source or destination.")
if src not in known or dst not in known:
missing = src if src not in known else dst
raise TopologyError(f"Invalid TM topology: server {missing} is not a registered server.")
if src == dst:
raise TopologyError(
f"Invalid TM topology: self-loop on {_node_name(src)} — a server cannot route to itself."
)
pair = (src, dst)
if pair in seen_pairs:
raise TopologyError(
f"Invalid TM topology: duplicate connection {_node_name(src)} → {_node_name(dst)}."
)
seen_pairs.add(pair)
# Fan-out from one server is the balancer; fan-in is allowed only when every
# predecessor is itself a balancer branch of the SAME upstream, which is
# exactly `A → {B, C} → D`. Anything else would need routing the chain
# cannot express, so it is rejected with a message that says why.
predecessors: dict = {}
successors: dict = {}
for edge in edges:
successors.setdefault(edge["from"], []).append(edge["to"])
predecessors.setdefault(edge["to"], []).append(edge["from"])
for nid, preds in predecessors.items():
if len(preds) < 2:
continue
roots = set()
for pred in preds:
own = predecessors.get(pred) or []
roots.add(tuple(sorted(own)) if own else ("<head>", pred))
if len(roots) != 1:
raise TopologyError(
f"Invalid TM topology: {_node_name(nid)} is reached from {len(preds)} unrelated servers "
f"({', '.join(_node_name(p) for p in preds)}). Only parallel servers of one balancer may "
"share a next server."
)
for nid, succs in successors.items():
if len(succs) != len(set(succs)):
raise TopologyError(f"Invalid TM topology: duplicate connection from {_node_name(nid)}.")
cycle = _cycle_path(edges, sorted(known))
if cycle:
names = [f"{_node_name(nid)}" for nid in cycle]
raise TopologyError(
"Invalid TM topology: cycle detected between " + " → ".join(names) + "."
)
if active_server and str(active_server) not in known:
raise TopologyError(
f"Invalid TM topology: the selected (Set) server {active_server} is not a registered server."
)
topology = _compute_topology(edges, sorted(known), str(active_server or ""))
if topology.get("leftovers"):
names = ", ".join(_node_name(nid) for nid in topology["leftovers"])
raise TopologyError(
f"Invalid TM topology: routing is ambiguous for {names}. Re-apply the connections."
)
# Multi-component graphs ARE valid, but only chains the operator built with
# edges count as components needing a Set. A node with no edges at all stays
# a candidate, not a competing component.
built_chains = [c for c in topology["chains"] if len(c) > 1]
if len(built_chains) > 1 and not str(active_server or ""):
raise TopologyError(
"Multiple independent chains found: set (Set) a chain before applying. "
"Chains: " + "; ".join(" → ".join(_node_name(n) for n in c) for c in built_chains)
)
# Every member chain must be a real path with a reachable final destination.
for chain in topology["chains"]:
if not chain:
raise TopologyError("Invalid TM topology: an empty chain was produced.")
for nid in chain:
role = topology["roles"].get(nid) or {}
if not role.get("next_node_id") and not role.get("final"):
raise TopologyError(
f"Invalid TM topology: {_node_name(nid)} has no next server and is not a final destination."
)
return topology
def client_path_for(topology: dict, node_id: str) -> str:
"""The TM route a client must use when it enters at ``node_id``."""
role = (topology.get("roles") or {}).get(node_id) or {}
return str(role.get("ingress_path") or TM_ENTRY_PATH_TEMPLATE)
def _topology_summary(topology: dict) -> dict:
chain = topology.get("active_chain") or []
entry = chain[0] if chain else ""
exit_node = chain[-1] if chain else ""
return {
"chains": topology.get("chains") or [],
"levels": [list(level) for level in (topology.get("levels") or [])],
"balancer": any(len(level) > 1 for level in (topology.get("levels") or [])[1:]),
"active_chain": chain,
"idle": topology.get("idle") or [],
"entry": {"node_id": entry, "name": _node_name(entry) if entry else ""} if entry else None,
"exit": {"node_id": exit_node, "name": _node_name(exit_node) if exit_node else ""} if exit_node else None,
"roles": topology.get("roles") or {},
}
def current_topology(strict: bool = False) -> dict:
"""Topology for the live graph; used by config generation and status."""
edges = [dict(e) for e in (TM_STATE.get("edges") or [])]
server_ids = sorted(_live_servers().keys())
try:
return validate_graph(edges, server_ids, str(TM_STATE.get("active_server") or ""))
except TopologyError:
if strict:
raise
return {"chains": [], "roles": {}, "leftovers": [], "active_chain": [], "idle": [],
"entry_node_id": "", "active_server": ""}
def resolve_entry_node_id() -> str:
"""The server whose domain the generated client config dials.
The explicit Set selection wins. When nothing is Set, the entry of the
active chain is used so TM still produces a working config.
"""
servers = _live_servers()
active = str(TM_STATE.get("active_server") or "").strip()
if active and active in servers:
return active
topology = current_topology()
chain = topology.get("active_chain") or []
return chain[0] if chain else ""
def _split_host_port(value: str, default_port: int | None) -> tuple[str, int | None]:
"""Split ``host[:port]`` into its parts.
Node domains are often written as ``example.com:8443`` (or ``[::1]:8443``).
Emitting that verbatim into ``vless://uuid@host:port`` would produce a
double port, so the port is taken out of the host when it is there.
"""
value = str(value or "").strip()
if not value:
return "", default_port
if value.startswith("["):
end = value.find("]")
if end > 0:
rest = value[end + 1:]
if rest.startswith(":") and rest[1:].isdigit():
return value[:end + 1], int(rest[1:])
return value[:end + 1], default_port
return value, default_port
if value.count(":") == 1:
host, _, port_text = value.rpartition(":")
if host and port_text.isdigit():
return host, int(port_text)
return value, default_port
def _entry_target(node_id: str) -> dict | None:
"""Resolve the dial target (host/port/path) for a TM entry server."""
main = _m()
node = _live_servers().get(node_id)
if not node:
return None
view = main._node_public_view(node_id, node)
remote_ib = dict(node.get("remote_tls_ws") or {})
raw_host = str(remote_ib.get("domain") or node.get("remote_host") or view.get("domain") or "").strip()
if not raw_host:
raw_host = str(node.get("domain") or "").strip()
raw_host = raw_host.replace("https://", "").replace("http://", "").strip("/")
if not raw_host:
return None
try:
port = int(remote_ib.get("external_port") or remote_ib.get("port") or 443)
except (TypeError, ValueError):
port = 443
# A port carried inside the host string wins: it is what the URL really is.
host, embedded_port = _split_host_port(raw_host, None)
if embedded_port is not None:
port = embedded_port
if not host:
return None
topology = current_topology()
path_template = client_path_for(topology, node_id)
# The SNI is a hostname, never host:port.
sni, _ = _split_host_port(str(remote_ib.get("sni") or ""), None)
return {
"node_id": node_id,
"host": host,
"port": port,
"path_template": path_template,
"sni": sni or host,
"flag": view.get("country_flag") or "🌐",
"name": view.get("name") or node_id,
}
def tm_config_for_node(user: dict, node_id: str) -> str:
"""One VLESS config for entering the tunnel at ``node_id``."""
from urllib.parse import quote
config_uuid = str(user.get("config_uuid") or "").strip()
if not config_uuid or not node_id:
return ""
target = _entry_target(node_id)
if not target:
return ""
path = target["path_template"].replace("{uuid}", config_uuid)
username = user.get("username") or "user"
role = (current_topology().get("roles") or {}).get(node_id) or {}
# The entry a config dials is always an entry point: the remark says which
# server it goes through, never "relay"/"exit" — those are not places a
# client can start from.
hop_note = " Entry" if role.get("initial") or role.get("initial_final") else ""
remark = f"Spider-{username} TM {target['flag']} {target['name']}{hop_note}".strip()
params = (
"encryption=none&security=tls&type=ws"
f"&host={quote(target['host'], safe='')}"
f"&path={quote(path, safe='')}"
f"&sni={quote(target['sni'], safe='')}"
"&fp=chrome&alpn=http/1.1"
)
return f"vless://{config_uuid}@{target['host']}:{target['port']}?{params}#{quote(remark)}"
def tm_entry_node_ids() -> list:
"""Every server a client may legitimately enter the tunnel through.
Only the first layer of a chain counts as a door — a balancer's parallel
entries therefore each get their own config, which is the whole point of
having several. A middle or exit is never a door, even when the operator
left a stray edge on it; the Set selection is the one exception, because it
is an explicit instruction and always gets its own config.
"""
topology = current_topology()
roles = topology.get("roles") or {}
# A server with no links at all is not part of any chain: it must not
# collect a config merely because it sits alone in its own layer.
linked = set()
for edge in (TM_STATE.get("edges") or []):
linked.add(str(edge.get("from") or ""))
linked.add(str(edge.get("to") or ""))
ids: list = []
for nid, role in roles.items():
if nid not in linked:
continue
# `initial` is layer 0; `initial_final` is a one-server chain.
if role.get("initial") or role.get("initial_final") or role.get("level") == 0:
ids.append(nid)
# Keep the topology's own ordering so the configs read top-down.
ordered = [nid for nid in (topology.get("active_chain") or []) if nid in ids]
for nid in ids:
if nid not in ordered:
ordered.append(nid)
active = str(TM_STATE.get("active_server") or "").strip()
if active and active in _live_servers() and active not in ordered:
ordered.append(active)
return ordered
def tm_client_configs(user: dict) -> list:
"""Every TM config this user should receive.
One per entry server (a balancer with several entries gives several) and
one for the Set server — all carrying the user's own ``config_uuid``.
"""
out, seen = [], set()
for nid in tm_entry_node_ids():
cfg = tm_config_for_node(user, nid)
if cfg and cfg not in seen:
out.append(cfg)
seen.add(cfg)
return out
def tm_client_config(user: dict, node_id: str = "") -> str:
"""The single config for a user over TM — same UUID as every other config.
Used wherever the panel needs exactly one string. The Set selection wins,
then the chain entry; subscriptions use ``tm_client_configs`` for every door.
"""
if node_id:
return tm_config_for_node(user, node_id)
return tm_config_for_node(user, resolve_entry_node_id())
# ── TM inbound (a real inbound, participates in config generation) ──────────
def is_tm_inbound(inbound: dict | None) -> bool:
if not inbound:
return False
return (str(inbound.get("_managed_kind") or "") == TM_MANAGED_KIND
or (str(inbound.get("protocol") or "").lower() == TM_PROTOCOL
and str(inbound.get("name") or "").strip() == TM_INBOUND_NAME))
def find_tm_inbound_id() -> str | None:
main = _m()
for iid, ib in main.INBOUNDS.items():
if str(ib.get("_managed_kind") or "") == TM_MANAGED_KIND:
return iid
for iid, ib in main.INBOUNDS.items():
if is_tm_inbound(ib):
ib.setdefault("_managed_kind", TM_MANAGED_KIND)
return iid
return None
async def ensure_tm_inbound() -> str:
"""Create the dedicated ``TM`` inbound once; adopt it on later boots."""
main = _m()
changed = False
async with main.INBOUNDS_LOCK:
iid = find_tm_inbound_id()
if not iid:
iid = TM_INBOUND_ID if TM_INBOUND_ID not in main.INBOUNDS else main.generate_short_id()
main.INBOUNDS[iid] = {
"name": TM_INBOUND_NAME,
"_managed_kind": TM_MANAGED_KIND,
"protocol": TM_PROTOCOL,
"inbound_type": "transport",
"system": True,
"enabled": True,
# No extra listener: TM rides the panel's own HTTPS/WSS entry.
"port": TM_PUBLIC_PORT,
"internal_port": int(main.CONFIG.get("port") or 8080),
"network": "ws",
"security": "tls",
"domain": main._safe_host(main.SETTINGS.get("domain"), main.get_host()),
"external_domain": "",
"sni": "",
"external_port": "",
"fingerprint": "chrome",
"ws_settings": {"path": TM_ENTRY_PATH_TEMPLATE},
"created_at": _now(),
}
changed = True
else:
ib = main.INBOUNDS[iid]
ib.setdefault("_managed_kind", TM_MANAGED_KIND)
ib.setdefault("system", True)
if not ib.get("advanced_customized"):
ib["name"] = TM_INBOUND_NAME
ib["protocol"] = TM_PROTOCOL
ib["network"] = "ws"
ib["security"] = "tls"
ib["port"] = TM_PUBLIC_PORT
ib.setdefault("ws_settings", {"path": TM_ENTRY_PATH_TEMPLATE})
ib["domain"] = main._safe_host(ib.get("domain"), main.SETTINGS.get("domain"), main.get_host())
if changed:
main.log_activity("inbound", "اینباند TM ساخته شد", "ok")
await _save()
return iid
async def sync_tm_inbound_nodes() -> None:
"""The TM inbound exposes exactly the servers of the live chain."""
main = _m()
iid = find_tm_inbound_id()
if not iid:
return
chain = list((current_topology().get("active_chain") or []))
if not chain:
chain = _tm_server_ids()
async with main.INBOUNDS_LOCK:
ib = main.INBOUNDS.get(iid)
if ib is not None:
ib["enabled_node_ids"] = chain
ib["node_ids"] = chain
# ── Graph API payload ───────────────────────────────────────────────────────
def graph_payload() -> dict:
servers = _safe_servers()
valid_ids = {s["node_id"] for s in servers}
edges = [dict(e) for e in (TM_STATE.get("edges") or []) if e.get("from") in valid_ids and e.get("to") in valid_ids]
active = str(TM_STATE.get("active_server") or "")
if active not in valid_ids:
active = ""
return {
"servers": servers,
"edges": edges,
"active_server": active,
}
def status_payload() -> dict:
servers = _safe_servers()
valid_ids = {s["node_id"] for s in servers}
edges = [dict(e) for e in (TM_STATE.get("edges") or []) if e.get("from") in valid_ids and e.get("to") in valid_ids]
active = str(TM_STATE.get("active_server") or "")
if active not in valid_ids:
active = ""
topology = _compute_topology(edges, sorted(valid_ids), active)
chain = topology.get("active_chain") or []
applied = TM_STATE.get("applied") or {}
participant = TM_STATE.get("participant") or {}
# The graph is "live" once it has been applied AND still matches what was
# applied — an unapplied edit must never be reported as the running chain.
applied_chain = list((applied or {}).get("chain") or [])
applied_edges = (applied or {}).get("edges") or []
dirty = bool(applied) and (
list(chain) != applied_chain
or sorted((e.get("from"), e.get("to")) for e in edges)
!= sorted((e.get("from"), e.get("to")) for e in applied_edges)
)
return {
"enabled": bool(TM_STATE.get("enabled")),
"dirty": dirty,
"applied": bool(applied),
# Edges as they were applied. The browser compares these with the live
# graph to tell "what the chain is doing now" from "what you just drew".
"applied_edges": [dict(e) for e in applied_edges],
"active": bool(chain),
"server_count": len(servers),
"link_count": len(edges),
"active_server": active,
"active_server_name": _node_name(active) if active else "",
"entry": _node_name(chain[0]) if chain else "",
"entry_node_id": chain[0] if chain else "",
"exit": _node_name(chain[-1]) if chain else "",
"exit_node_id": chain[-1] if chain else "",
"chain": [{"node_id": nid, "name": _node_name(nid)} for nid in chain],
"idle": [{"node_id": nid, "name": _node_name(nid)} for nid in (topology.get("idle") or [])],
"levels": [list(level) for level in (topology.get("levels") or [])],
"balancer": any(len(level) > 1 for level in (topology.get("levels") or [])[1:]),
# Per-node role (initial / middle / final), which layer it sits in and
# whether it fans out — the browser never derives these itself.
"roles": topology.get("roles") or {},
"chain_length": len(chain),
"last_apply": TM_STATE.get("last_apply") or "",
"last_error": TM_STATE.get("last_error") or "",
"applied_at": (applied or {}).get("at") or "",
"applied_chain": (applied or {}).get("chain") or [],
"documented_path": (client_path_for(topology, chain[0]) if chain else TM_ENTRY_PATH_TEMPLATE).replace("{uuid}", "<uuid>"),
"participant": {
"node_id": (participant or {}).get("node_id") or main_node_domain(),
"role": ((participant or {}).get("self") or {}).get("role") or "",
"next_node_id": ((participant or {}).get("self") or {}).get("next_node_id") or "",
"prev_node_id": ((participant or {}).get("self") or {}).get("prev_node_id") or "",
"ingress_path": ((participant or {}).get("self") or {}).get("ingress_path") or "",
"applied_at": (participant or {}).get("applied_at") or "",
} if participant else None,
}
def main_node_domain() -> str:
main = _m()
try:
return str(main.SETTINGS.get("domain") or main.get_host() or "")
except Exception:
return ""
# ── Server management (thin layer over the Node records) ────────────────────
async def add_server(name: str, domain: str, api_key: str) -> dict:
"""Verify then persist, exactly like /api/nodes does."""
main = _m()
normalized_domain = main._normalize_node_base_url(domain)
raw_key = str(api_key or "").strip()
if not raw_key:
raise TopologyError("API Key is required.")
if not raw_key.startswith("spdr_"):
raise TopologyError("API Key must start with spdr_")
key = main._normalize_node_key(raw_key)
if not normalized_domain:
raise TopologyError("Server domain is not valid.")
async with main.NODES_LOCK:
duplicate = any(
str(n.get("domain") or "").rstrip("/").lower() == normalized_domain.rstrip("/").lower()
for n in main.NODES.values()
)
if duplicate:
raise TopologyError("This server is already registered in Nodes.")
node_id = "node_" + secrets.token_hex(6)
node = {
"name": str(name or "").strip()[:60],
"domain": normalized_domain,
"url": normalized_domain,
"api_key": key,
"created_at": _now(),
"last_sync": None,
"status": "checking",
"last_status": "checking",
"last_error": "",
}
probe = await main._probe_node(node)
if probe.get("status") != "online":
raise TopologyError(probe.get("last_error") or "Server verification failed.")
node.update(probe)
if not node.get("name"):
node["name"] = f"{node.get('country_flag') or '🌐'} {node.get('country') or node.get('public_ip') or normalized_domain}"
async with main.NODES_LOCK:
main.NODES[node_id] = node
total = len(main.NODES)
async with TM_LOCK:
positions = TM_STATE.setdefault("positions", {})
positions[node_id] = _default_position(total - 1, total)
await _save()
main.log_activity("tm", f"سرور TM «{node['name']}» اضافه شد", "ok")