summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/tests/test_packaging_win.py
blob: 6f7573bcd8b4c74e6a2d33e69ffcdd28ca8dbc75 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
"""
The Windows installer (W4): a single per-user NSIS package carrying the Electron
client and the frozen node daemon.

Like test_packaging_units.py this reads the config rather than building anything
— there is no electron-builder or PyInstaller run here. Weak evidence, and the
right kind for the defects it guards against: a per-machine flag that would make
the installer demand admin, a build step wired to the wrong file, the 150 MB
node-runtime artifact slipping into git, the autostart seam between the NSIS
uninstaller and meshbay_node.platform drifting apart.
"""

import json
import re
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[3]
CLIENT = ROOT / "packages" / "meshbay-client"
PKG_JSON = CLIENT / "package.json"
WIN = ROOT / "packaging" / "win"
NSH = CLIENT / "build" / "installer.nsh"
MAIN_JS = CLIENT / "src" / "main.js"
PRELOAD_JS = CLIENT / "src" / "preload.js"

# The "Light" target: Electron client + UI, no bundled node. See
# C:\Users\admin\devel\light-client.md for the evaluation this implements.
LIGHT_NSH = CLIENT / "build" / "installer-light.nsh"
LIGHT_YML = WIN / "electron-builder.light.yml"
BUILD_WIN_LIGHT = WIN / "build-win-light.ps1"
BUILD_WIN_COMMON = WIN / "build-win-common.ps1"

# The "MSIX" target: same feature set as Full, packaged for Microsoft Store
# submission instead of NSIS. See C:\Users\admin\devel\msix-installer.md for
# the plan this implements.
MSIX_YML = WIN / "electron-builder.msix.yml"
BUILD_WIN_MSIX = WIN / "build-win-msix.ps1"
MSIX_EXTENSIONS_XML = CLIENT / "build" / "appx-extensions.xml"

# sync-ui.js copies this into CLIENT/ui/ verbatim -- read the source of
# truth, same as every other cross-package check in this file already does
# for meshbay-client's own src/.
HUB_STATIC = ROOT / "packages" / "meshbay-hub" / "src" / "meshbay_hub" / "static"

pytestmark = pytest.mark.skipif(
    not PKG_JSON.exists() or not WIN.exists(),
    reason="Windows packaging not present")


def _pkg() -> dict:
    return json.loads(PKG_JSON.read_text(encoding="utf-8"))


# ── electron-builder: Windows target ────────────────────────────────────────

def test_the_windows_target_is_nsis_with_the_committed_icon():
    win = _pkg()["build"]["win"]
    assert win["target"] == "nsis"
    icon = CLIENT / win["icon"]
    assert icon.suffix == ".ico" and icon.exists(), f"{icon} is missing"


def test_the_installer_is_per_user_and_never_asks_for_admin():
    """
    A logon-triggered scheduled task needs elevation (that is why W3 uses the
    Startup folder), and the whole desktop design is no-admin. perMachine or
    allowElevation here would undo that at install time.
    """
    nsis = _pkg()["build"]["nsis"]
    assert nsis["oneClick"] is False
    assert nsis["perMachine"] is False
    assert nsis["allowElevation"] is False
    assert nsis["allowToChangeInstallationDirectory"] is True


def test_the_node_runtime_is_carried_as_an_extraresource():
    """
    PyInstaller output lands in packages/meshbay-client/node-runtime/ and rides
    into the package under resources/node-runtime/. src/main.js:findNodeBinary
    resolves exactly that path (process.resourcesPath / node-runtime /
    meshbay-node.exe), so the two names must agree.
    """
    extra = _pkg()["build"]["win"]["extraResources"]
    entry = next((e for e in extra if e.get("to") == "node-runtime"), None)
    assert entry, "no extraResources entry mapping to node-runtime"
    assert entry["from"] == "node-runtime"

    main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
    assert "'node-runtime', 'meshbay-node.exe'" in main_js, (
        "findNodeBinary no longer looks for the bundled daemon where "
        "extraResources puts it")


def test_find_node_binary_strips_stray_cr_from_multiline_where_output():
    """
    where.exe/which can list more than one match on PATH, and each line
    keeps its own trailing \\r on Windows. `stdout.trim().split('\\n')[0]`
    only strips the ends of the *whole* string, so with 2+ matches a stray
    \\r stayed glued to the end of the first line -- which then landed
    inside the quoted path written into the Startup .vbs and broke
    VBScript's parser with "Unterminated string constant" the next time
    Windows ran it at sign-in. Reproduced live 2026-09-05 (this user's own
    machine has both a dev venv and an installed build on PATH) and fixed
    by splitting on \\r?\\n and trimming each candidate line individually.
    """
    main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
    assert "stdout.split(/\\r?\\n/)" in main_js, (
        "findNodeBinary must split where.exe/which output on \\r?\\n and "
        "trim each line, not a single stdout.trim() over the whole blob")
    assert "stdout.trim().split('\\n')[0]" not in main_js


def test_firewall_helper_is_carried_as_an_extraresource():
    """packaging/win/firewall.ps1 must ride into resources/, at the fixed
    path installer.nsh invokes it from ($INSTDIR\\resources\\firewall.ps1)."""
    extra = _pkg()["build"]["win"]["extraResources"]
    entry = next((e for e in extra if e.get("to") == "firewall.ps1"), None)
    assert entry, "no extraResources entry mapping to firewall.ps1"
    assert entry["from"].endswith("packaging/win/firewall.ps1")
    assert (ROOT / "packaging" / "win" / "firewall.ps1").exists()


def test_dist_win_delegates_to_the_build_script():
    """`dist` (Linux) delegates to build-client.sh; `dist:win` is its
    counterpart and must not be a second inline electron-builder invocation."""
    scripts = _pkg()["scripts"]
    assert "dist:win" in scripts
    assert "build-win.ps1" in scripts["dist:win"]
    # `dist` stays Linux-only and unchanged (test_desktop_shell.py guards it too).
    assert "win" not in scripts["dist"].lower()


# ── the build scripts exist and point at real files ────────────────────────

@pytest.mark.parametrize("name", [
    "build-win.ps1",
    "build-node-runtime.ps1",
    "meshbay-node.spec",
    "node-entry.py",
    "README.md",
])
def test_packaging_win_ships_its_scripts(name):
    assert (WIN / name).exists(), f"packaging/win/{name} is missing"


def test_the_pyinstaller_entry_point_is_the_daemon_main():
    src = (WIN / "node-entry.py").read_text(encoding="utf-8")
    assert "from meshbay_node.daemon import main" in src
    assert "main()" in src


def test_the_spec_pulls_in_the_awkward_dependencies_whole():
    """
    The C/Rust-extension and dynamic-import packages are the ones PyInstaller's
    static pass drops. If someone trims collect_all to shrink the build, the
    frozen daemon fails at runtime, not at build time.
    """
    spec = (WIN / "meshbay-node.spec").read_text(encoding="utf-8")
    for pkg in ("aiortc", "av", "aioquic", "pydantic_core", "uvicorn",
                "watchdog", "guessit", "blake3", "meshbay_node", "meshbay_common"):
        assert re.search(rf'["\']{re.escape(pkg)}["\']', spec), (
            f"{pkg} dropped from the PyInstaller spec's collect list")


def test_the_frozen_exe_carries_a_version_resource():
    """
    Without it the Windows Firewall prompt, Task Manager and Properties show a
    bare "meshbay-node". The version is read from the installed package so it
    tracks pyproject rather than being a second copy to update.
    """
    spec = (WIN / "meshbay-node.spec").read_text(encoding="utf-8")
    assert "VSVersionInfo" in spec
    assert "version=_version_info" in spec, "EXE() is not given the version resource"
    assert 'StringStruct("ProductName", "MeshBay Node")' in spec
    assert '_pkg_version("meshbay-node")' in spec, "version is hardcoded, not read from the package"


# ── the artifact never gets committed ──────────────────────────────────────

def test_the_node_runtime_output_is_gitignored():
    """It is ~150 MB of frozen Python. The `ui/` fork guard in
    test_desktop_shell.py exists for the same reason."""
    gitignore = (ROOT / ".gitignore").read_text(encoding="utf-8")
    assert "packages/meshbay-client/node-runtime/" in gitignore


# ── the NSIS ↔ platform.py autostart seam ─────────────────────────────────

def test_the_uninstaller_clears_the_autostart_launcher():
    """
    W3's `meshbay-node autostart install` drops a .vbs in the Startup folder
    (meshbay_node.platform._startup_vbs). After an uninstall it would point
    wscript at a deleted binary every sign-in, so customUnInstall must delete
    it — and at the path platform.py actually uses.
    """
    from meshbay_node import platform as plat

    nsh = NSH.read_text(encoding="utf-8")
    assert "!macro customUnInstall" in nsh
    assert "taskkill /IM meshbay-node.exe /F" in nsh

    # The tail platform.py builds, made NSIS-relative ($APPDATA == %APPDATA%).
    tail = plat._startup_vbs()
    parts = tail.parts
    i = parts.index("Microsoft")
    rel = "\\".join(parts[i:])                       # Microsoft\...\Startup\MeshBay Node.vbs
    assert rel in nsh, (
        f"customUnInstall does not delete {rel!r} — the W3 autostart path "
        "changed and installer.nsh was not updated")


def test_customInstall_stops_a_running_daemon_before_overwriting_it():
    nsh = NSH.read_text(encoding="utf-8")
    body = _macro_body(nsh, "customInstall")
    assert "taskkill /IM meshbay-node.exe /F" in body


# ── the autostart choice + the one-time elevated firewall step ──────────────

def _macro_body(nsh: str, name: str) -> str:
    # \b after the name so "customInstall" does not also match the start of
    # "customInstallMode" (which is defined just above it in the file).
    return re.split(rf"!macro {re.escape(name)}\b", nsh, maxsplit=1)[1] \
        .split("!macroend", 1)[0]


def test_the_all_users_install_mode_page_is_suppressed():
    """
    MeshBay is per-user only — the keystore and the DPAPI-protected secrets are
    bound to the signed-in account (MESHBAY_DESIGN.md §11.2 / §7.5), and
    build.nsis forbids elevation — so electron-builder's "anyone who uses this
    computer / only me" page only ever showed its first option disabled.
    customInstallMode forcing $isForceCurrentInstall skips the page and pins
    per-user (multiUserUi.nsh: `${if} $isForceCurrentInstall == "1"` → abort).
    """
    nsh = NSH.read_text(encoding="utf-8")
    mode = _macro_body(nsh, "customInstallMode")
    assert 'StrCpy $isForceCurrentInstall "1"' in mode


def test_the_autostart_choice_is_a_radio_page_defaulting_to_service():
    """
    The old two nested Yes/No MessageBoxes are one nsDialogs page now, with the
    same three-way meaning: only-while-open / at-sign-in / background service.
    Background service is the default selection (MB_AutoMode "2"), set in
    customInit so a silent install — where the page never runs — still has a
    definite value.
    """
    nsh = NSH.read_text(encoding="utf-8")
    page = _macro_body(nsh, "customPageAfterChangeDir")

    assert "Page custom mbAutostartPageCreate mbAutostartPageLeave" in page
    assert page.count("${NSD_CreateRadioButton}") == 3, (
        "expected exactly three autostart options")
    assert "${NSD_Check} $MB_RbService" in page, (
        "the background-service option must be the one checked by default")
    assert 'StrCpy $MB_AutoMode "2"' in _macro_body(nsh, "customInit"), (
        "customInit must default MB_AutoMode to service mode for silent installs")
    # The MessageBox-driven flow is gone from customInstall entirely.
    assert "MessageBox MB_YESNO" not in _macro_body(nsh, "customInstall")


def test_the_firewall_rules_are_set_up_in_every_autostart_mode():
    """
    A node that silently accepts no connections is the failure mode
    MESHBAY_DESIGN.md §7.5 calls out. So the rules go in whatever the autostart
    choice: folded into the service elevation for mode "2" (service-mode.ps1
    does task + firewall in one UAC), their own single elevation for
    modes "0"/"1". Still ${Silent}-guarded — an unattended /S install cannot
    raise a UAC prompt, and falls back to Windows' own first-connection dialogs.
    """
    nsh = NSH.read_text(encoding="utf-8")
    install = _macro_body(nsh, "customInstall")

    assert "${IfNot} ${Silent}" in install
    assert 'ExecShellWait "runas"' in install

    i_fw_check = install.index('firewall.ps1" check')
    i_svc_if = install.index('${If} $MB_AutoMode == "2"')
    i_svc_install = install.index('service-mode.ps1" -Action install')
    i_fw_add = install.index('firewall.ps1" add')
    # firewall check (unelevated) → service branch → firewall-only branch.
    assert i_fw_check < i_svc_if < i_svc_install < i_fw_add
    # The service branch's single elevation is service-mode.ps1; it does not
    # ALSO call firewall.ps1 add (service-mode.ps1 already covers that).
    assert 'firewall.ps1" add' not in install[i_svc_if:i_fw_add]


def test_the_signin_mode_installs_the_per_user_startup_launcher():
    """Mode "1" ("at sign-in") drops the Startup-folder .vbs via the frozen
    daemon's own `autostart install` verb — no admin, idempotent. The nearest
    enclosing choice must be `$MB_AutoMode == "1"`, so modes "0"/"2" skip it."""
    nsh = NSH.read_text(encoding="utf-8")
    install = _macro_body(nsh, "customInstall")

    i_call = install.index('meshbay-node.exe" autostart install')
    last_if = install.rindex("${If} $MB_AutoMode ==", 0, i_call)
    assert install[last_if:i_call].startswith('${If} $MB_AutoMode == "1"'), (
        "the Startup launcher must be gated on the at-sign-in choice")


def test_reinstalling_with_everything_already_in_place_asks_nothing():
    """
    Get-NetFirewallRule needs no admin, only New/Remove do — so customInstall
    checks the firewall rules first, unelevated, and only elevates when
    something is actually missing. Without this, a repair or an upgrade that
    changes nothing would still re-trigger UAC. In service mode the task's
    presence is checked the same unelevated way (service.ps1 status), and both
    must be satisfied to skip.
    """
    nsh = NSH.read_text(encoding="utf-8")
    install = _macro_body(nsh, "customInstall")

    check_line = 'firewall.ps1" check'
    assert check_line in install
    # The check runs before any elevation.
    assert install.index(check_line) < install.index('ExecShellWait "runas"')
    assert 'service.ps1" status' in install
    assert "Goto mb_auto_done" in install


def test_the_uninstaller_offers_to_remove_everything_privileged_default_no():
    """
    Opt-in on the way out too, and defaulting to No: a stale allow-rule or
    Scheduled Task is inert, so this should not nag. One elevation removes
    both, unconditionally — service-mode.ps1's own remove actions are each
    no-ops when there is nothing to remove, so this is safe to run whether or
    not service mode was ever chosen.
    """
    nsh = NSH.read_text(encoding="utf-8")
    uninstall = _macro_body(nsh, "customUnInstall")

    assert "${IfNot} ${Silent}" in uninstall
    assert "/SD IDNO" in uninstall, "the uninstall prompt should default to No"
    assert 'service-mode.ps1" -Action remove' in uninstall
    assert 'ExecShellWait "runas"' in uninstall


# ── service mode itself (packaging/win/service.ps1, service-mode.ps1) ──────

def test_service_ps1_and_service_mode_ps1_are_extraresources():
    for name in ("service.ps1", "service-mode.ps1"):
        entry = next(
            (e for e in _pkg()["build"]["win"]["extraResources"] if e.get("to") == name),
            None)
        assert entry, f"no extraResources entry mapping to {name}"
        assert entry["from"].endswith(f"packaging/win/{name}")
        assert (WIN / name).exists()


def test_service_install_uses_s4u_not_a_stored_password():
    """
    Register-ScheduledTask -LogonType S4U: no password stored anywhere, and
    — unlike LocalSystem/NetworkService — it loads this account's own
    profile, so %LOCALAPPDATA%\\meshbay\\ needs no relocation.

    Not `schtasks /create`: schtasks only *infers* the logon type from
    whether /rp is present, and both readings broke live on a blank-password
    account (common on a personal PC, 2026-09-05) -- `/rp ""` fails
    credential validation ("the user name or password is incorrect", even
    though nothing is wrong), and omitting /rp registers "Interactive only"
    instead of S4U, which never runs at boot and does not launch anything
    even run on demand while signed in. -LogonType S4U is explicit, so losing
    it (e.g. "simplifying" back to schtasks, or dropping -ErrorAction Stop so
    a permission failure silently falls through to "installed") would
    reintroduce one of those two live-reproduced failures.
    """
    src = (WIN / "service.ps1").read_text(encoding="utf-8")
    # Isolate the actual "install" case from the docstring above it (which
    # names these same cmdlets in prose) -- checks below must see only code.
    lines = src.splitlines()
    install_start = next(i for i, line in enumerate(lines) if '"install" {' in line)
    remove_start = next(i for i, line in enumerate(lines) if '"remove" {' in line)
    install_block = "\n".join(lines[install_start:remove_start])

    assert "New-ScheduledTaskTrigger -AtStartup" in install_block, (
        "must trigger at boot, not at sign-in")
    assert "-LogonType S4U" in install_block, (
        "must request S4U explicitly, not infer it from /rp")
    assert "Register-ScheduledTask" in install_block
    assert "-ErrorAction Stop" in install_block, (
        "a permission failure must throw, not fall through as if it installed")
    assert "Get-Credential" not in src, "no password should ever be prompted for"
    assert "schtasks" not in install_block, (
        "the install branch must not fall back to schtasks /create")

    # The install branch must not assign to `$action` (any case): that name is
    # this script's own [ValidateSet(...)][string]$Action parameter, and
    # `$action = New-ScheduledTaskAction ...` coerces the CimInstance to the
    # string "MSFT_TaskExecAction", which Register-ScheduledTask -Action then
    # refuses -- reproduced live 2026-09-05, the install path never created the
    # task at all until this was renamed.
    assert not re.search(r"(?im)^\s*\$action\s*=", install_block), (
        "do not assign to $action in service.ps1 -- it shadows the [string]"
        "$Action parameter and Register-ScheduledTask -Action then gets a string")


def test_service_task_name_is_the_same_everywhere():
    """One name, three places: meshbay_node.platform.TASK_NAME (the CLI),
    service.ps1 (the installer), and main.js's WIN_SERVICE_TASK (the client
    driving Start/Stop/Restart). A mismatch means the client manages a task
    that does not exist, or vice versa."""
    from meshbay_node import platform as plat

    service_ps1 = (WIN / "service.ps1").read_text(encoding="utf-8")
    main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")

    assert f'$TASK_NAME = "{plat.TASK_NAME}"' in service_ps1
    assert f"WIN_SERVICE_TASK = '{plat.TASK_NAME}'" in main_js


def test_service_status_reports_state_without_admin():
    """status/run/end must not need elevation once the task exists (only
    install/remove do) — that is what lets the Node page drive it with no
    further UAC prompts. Nothing in those branches should invoke as an
    elevated call; only the two macros in installer.nsh use "runas"."""
    src = (WIN / "service.ps1").read_text(encoding="utf-8")
    assert "runas" not in src.lower(), (
        "service.ps1 itself must never self-elevate — installer.nsh already "
        "runs the whole script elevated for install/remove, and the client "
        "calls status/run/end directly, unelevated")


HUB_STATIC = ROOT / "packages" / "meshbay-hub" / "src" / "meshbay_hub" / "static"


def test_service_mode_toggle_elevates_the_same_script_the_installer_runs():
    """
    The installer's own mode question is effectively one-shot (it skips
    itself the moment the firewall rules exist for any reason, and per-user
    mode sets those up on its own with no Scheduled Task involved) -- so
    declining once, or the rules existing for any other reason, is a dead
    end through setup alone. The Node page's toggle is the other door in
    (and out), and it must drive service-mode.ps1 -- the exact script
    installer.nsh runs -- so the two paths can never disagree about what
    "service mode" means. One elevation (-Verb RunAs), no stored password.
    """
    main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
    assert "winElevateServiceMode" in main_js
    fn = main_js.split("function winElevateServiceMode", 1)[1]
    fn = fn[:fn.index("\n  }\n")]
    assert "service-mode.ps1" in fn
    assert "-Verb RunAs" in fn or "'-Verb', 'RunAs'" in fn or "-Verb', 'RunAs'" in fn
    assert "Get-Credential" not in fn

    handler = main_js.split("ipcMain.handle('node:service-mode'", 1)[1]
    handler = handler[:handler.index("ipcMain.handle(")]
    assert "winElevateServiceMode" in handler
    assert "'install'" in handler or '"install"' in handler
    assert "'remove'" in handler or '"remove"' in handler


def test_node_page_service_mode_toggle_is_wired_end_to_end():
    """preload.js -> platform.js -> node-page.js, the same three-layer shape
    the existing autostart toggle uses. A break anywhere in this chain means
    the checkbox renders but does nothing, or never renders at all."""
    preload = (CLIENT / "src" / "preload.js").read_text(encoding="utf-8")
    assert "serviceMode:" in preload
    assert "'node:service-mode'" in preload

    platform_js = (HUB_STATIC / "platform.js").read_text(encoding="utf-8")
    assert "serviceMode:" in platform_js
    assert "bridge.node.serviceMode('install')" in platform_js
    assert "bridge.node.serviceMode('remove')" in platform_js

    node_page = (HUB_STATIC / "node-page.js").read_text(encoding="utf-8")
    assert "platform.node.serviceMode.available" in node_page
    assert "platform.node.serviceMode.install()" in node_page
    assert "platform.node.serviceMode.remove()" in node_page
    # Checked state must reflect the CURRENT mode, not a separate flag --
    # otherwise the toggle and the status panel above it could disagree.
    assert "info.mode === 'service'" in node_page


def test_the_help_smoke_test_joins_multiline_output_before_matching():
    """
    `& exe --help 2>&1` is an ARRAY once the output wraps past one line, which
    it now does with `autostart`/`service` in the verb list. `$array -notmatch
    X` is a FILTER, not a boolean test -- it returns the *non-matching*
    elements, and any non-empty array is truthy in `if()` regardless of what
    is in it. Almost every help line lacks the literal string "meshbay-node",
    so an unjoined check throws unconditionally the moment --help exceeds one
    line: found when this specific verb list finally grew past that point,
    which is exactly the kind of one-off silent breakage a passing build
    yesterday gives no warning of today.
    """
    src = (WIN / "build-node-runtime.ps1").read_text(encoding="utf-8")
    body = src.split("smoke test: meshbay-node --help", 1)[1]
    body = body[:800]
    assert '-join "`n"' in body, (
        "the captured --help output must be joined to a single string before "
        "any -match/-notmatch check, or a multi-line result silently always "
        "fails the smoke test")
    # And the join has to happen at capture time, not on some other variable.
    assert '(& $exe --help 2>&1) -join' in body


def test_main_js_drives_the_service_task_for_all_three_actions():
    """The hard requirement: Start/Stop/Restart from the Node page must
    control the Scheduled Task when service mode is active, not just spawn a
    detached process that has nothing to do with it."""
    main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
    for handler in ("node:service-stop", "node:service-restart", "node:start"):
        body = main_js.split(f"ipcMain.handle('{handler}'", 1)[1]
        body = body[:body.index("ipcMain.handle(")]
        assert "winServiceTaskStatus" in body, f"{handler} never checks for the service task"


def test_node_start_provisions_before_it_ever_touches_the_service_task():
    """
    On a fresh install with service mode chosen, the Scheduled Task exists
    before anything is provisioned (node.toml is written by the wizard, not
    by the installer). node:start must call provisionNode() first and only
    then ask about the service task / spawn -- reversed, the very first
    "start" from the wizard would run (or query) an unconfigured daemon
    instead of the one it just told the caller to expect.

    A bare unprovisioned run is independently proven harmless
    (test_a_bare_invocation_with_no_config_yet_exits_cleanly in
    test_cli_dispatch.py), so this is about correctness of *this* call
    actually starting the daemon the wizard just configured, not about
    safety if the order were reversed.
    """
    main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
    body = main_js.split("ipcMain.handle('node:start'", 1)[1]
    body = body[:body.index("ipcMain.handle(")]

    provision_at = body.index("provisionNode(")
    service_check_at = body.index("winServiceTaskStatus")
    assert provision_at < service_check_at, (
        "node:start checks the service task before provisioning — a fresh "
        "install's first Start would run/query the daemon before node.toml "
        "exists for it to read")


def test_node_start_links_the_node_key_on_windows_not_only_linux():
    """
    The daemon comes up at 'waiting_for_account' until its Ed25519 key is
    linked to the hub account it runs as. The Linux branch of node:start does
    that link inline (`PUT /v1/users/me/node_key`); the win32 branch used to
    just return the first reachable status, so the Create Group wizard span on
    "Detecting local node…" for ever and the only way through was linking the
    key by hand on the Profile page.

    Pin that the win32 branch now performs the same link before it reports the
    node started.
    """
    main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
    body = main_js.split("ipcMain.handle('node:start'", 1)[1]
    body = body[:body.index("ipcMain.handle(")]
    win_branch = body.split("process.platform === 'win32'", 1)[1]
    win_branch = win_branch[:win_branch.index("process.platform !== 'linux'")]
    assert "linkNodeKeyAndAwaitRunning" in win_branch, (
        "node:start's win32 branch never links the node key — the daemon will "
        "sit at waiting_for_account and the wizard will hang")

    helper = main_js.split("async function linkNodeKeyAndAwaitRunning", 1)[1]
    helper = helper[:2000]
    assert "/v1/users/me/node_key" in helper
    assert "waiting_for_account" in helper and "waiting_for_node_key" in helper


def test_firewall_ps1_targets_both_executables_and_is_idempotent():
    """One script, both rules — so installer.nsh only ever has to name it
    once on the way in and once on the way out."""
    src = (ROOT / "packaging" / "win" / "firewall.ps1").read_text(encoding="utf-8")
    assert "MeshBay.exe" in src
    assert "node-runtime" in src and "meshbay-node.exe" in src
    # Remove-then-add: a re-run (reinstall, or install after a manual add)
    # must not leave duplicate rules.
    assert src.index("Remove-NetFirewallRule") < src.index("New-NetFirewallRule")


def test_firewall_ps1_also_covers_lan_casting():
    """
    The WebRTC rules only reach MeshBay.exe / meshbay-node.exe; the cast HTTP
    relay (src/cast-relay.js, fixed TCP 19550-19553) and mDNS device discovery
    (src/cast-chromecast.js, bonjour-service, UDP 5353) are a separate surface
    on the client alone, and need their own ports and protocols. Ports here
    must agree with cast-relay.js's own constants and with the Linux
    definitions in packaging/firewall/*/meshbay-cast.xml — three descriptions
    of one port range that must not drift apart.
    """
    src = (ROOT / "packaging" / "win" / "firewall.ps1").read_text(encoding="utf-8")
    assert "19550-19553" in src, "cast TCP range missing or does not match cast-relay.js"
    assert '"5353"' in src, "mDNS discovery port (UDP 5353) missing"

    relay = (CLIENT / "src" / "cast-relay.js").read_text(encoding="utf-8")
    assert "PORT_BASE = 19550" in relay and "PORT_COUNT = 4" in relay, (
        "cast-relay.js's port range changed — update firewall.ps1 to match")

    firewalld = (ROOT / "packaging" / "firewall" / "firewalld" / "meshbay-cast.xml").read_text(
        encoding="utf-8")
    assert "19550-19553" in firewalld and "5353" in firewalld, (
        "the Linux and Windows cast firewall definitions have drifted apart")


def test_the_bundled_daemon_goes_on_the_user_path_and_comes_back_off():
    """
    The installer has no console entry point of its own; without this the
    operator has to `cd` into resources\\node-runtime\\ to run `meshbay-node`.
    The add uses stock WordFunc (no EnVar plugin — electron-builder's NSIS does
    not bundle it) and the same $INSTDIR-relative string on the way out.
    """
    nsh = NSH.read_text(encoding="utf-8")
    assert "!insertmacro WordAdd" in nsh and "!insertmacro un.WordAdd" in nsh

    install = _macro_body(nsh, "customInstall")
    uninstall = _macro_body(nsh, "customUnInstall")
    assert 'HKCU "Environment" "Path"' in install
    assert "${WordAdd}" in install and '"+${MB_NODE_BIN}"' in install
    assert "${un.WordAdd}" in uninstall and '"-${MB_NODE_BIN}"' in uninstall
    # New shells need the broadcast to notice.
    assert "WM_WININICHANGE" in install and "WM_WININICHANGE" in uninstall
    # PATH points at the real .exe dir, so `where meshbay-node` resolves to the
    # binary the client and the W3 launcher use too — not a shim.
    assert 'MB_NODE_BIN "$INSTDIR\\resources\\node-runtime"' in nsh


# ── ffmpeg: bundled by default (fetch-ffmpeg.ps1) ───────────────────────────

def test_fetch_ffmpeg_and_its_license_notice_exist():
    assert (WIN / "fetch-ffmpeg.ps1").exists()
    notice = WIN / "LICENSE-ffmpeg.txt"
    assert notice.exists()
    text = notice.read_text(encoding="utf-8")
    assert "GPL" in text
    assert "ffmpeg.org" in text or "FFmpeg/FFmpeg" in text, (
        "the notice must point at where the corresponding source actually is")


def test_ffmpeg_is_pinned_to_a_dated_release_not_the_moving_latest_alias():
    """
    BtbN repoints the "latest" release on every auto-build (their asset
    filenames even embed a fresh git-describe each time), so a URL built from
    that alias silently changes what a build fetches. The dated tag
    (autobuild-YYYY-MM-DD-HH-MM) is immutable once published -- that is what
    makes the pinned checksum mean anything.
    """
    src = (WIN / "fetch-ffmpeg.ps1").read_text(encoding="utf-8")
    tag_match = re.search(r'\$FFMPEG_TAG\s*=\s*"([^"]+)"', src)
    assert tag_match, "no $FFMPEG_TAG pin found"
    assert re.match(r"autobuild-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}$", tag_match.group(1)), (
        f"{tag_match.group(1)!r} is not a dated release tag")
    assert "/releases/latest/" not in src and "/releases/download/latest/" not in src

    sha_match = re.search(r'\$FFMPEG_SHA256\s*=\s*"([0-9a-f]+)"', src)
    assert sha_match, "no $FFMPEG_SHA256 pin found"
    assert len(sha_match.group(1)) == 64, "not a full sha256 hex digest"

    assert '$FFMPEG_URL' in src and '$FFMPEG_TAG' in src.split("$FFMPEG_URL", 1)[1][:200], (
        "the download URL must be built from the pinned tag")


def test_ffplay_is_excluded_from_the_bundle():
    """The vendor zip carries an SDL2 player MeshBay never invokes (~17 MB);
    bundling it would be the collect_all-everything instinct applied where a
    fixed allowlist is right instead."""
    src = (WIN / "fetch-ffmpeg.ps1").read_text(encoding="utf-8")
    keep_block = src.split("$KEEP_FILES", 1)[1].split(")", 1)[0]
    assert "ffplay" not in keep_block
    assert "ffmpeg.exe" in keep_block and "ffprobe.exe" in keep_block


def test_ffmpeg_bundling_is_the_default_not_opt_in():
    """
    Video streaming needs a real H.264 encoder (libx264, GPL -- no LGPL-only
    ffmpeg build has one), and asking an end user to separately run
    `winget install ffmpeg` is not viable for a non-technical install (needs
    network + winget present at that moment, fails silently). So bundling
    must be the default, with an explicit opt-out for local iteration --
    the reverse of the old -FfmpegDir opt-in this replaced.
    """
    runtime_src = (WIN / "build-node-runtime.ps1").read_text(encoding="utf-8")
    assert "SkipFfmpeg" in runtime_src
    assert "FfmpegDir" not in runtime_src, "the old opt-in mechanism should be gone, not parallel"
    assert "fetch-ffmpeg.ps1" in runtime_src

    win_src = (WIN / "build-win.ps1").read_text(encoding="utf-8")
    assert "SkipFfmpeg" in win_src
    assert "FfmpegDir" not in win_src


# ------------------------------------------------------------------------
# The "Light" target: Electron client + UI, no bundled node. See
# C:\Users\admin\devel\light-client.md for the evaluation. Weak, text-
# reading evidence throughout, same reasoning as the rest of this file:
# there is no electron-builder/PowerShell/NSIS runner here, and it is the
# right kind of evidence for what these guard against -- a config drifting
# back to carrying the node-runtime it must not, or the two orchestrators'
# shared steps diverging silently.
# ------------------------------------------------------------------------

def test_light_config_is_standalone_and_ships_no_node():
    """
    electron-builder.light.yml is passed via --config, which (per
    app-builder-lib/out/util/config/load.js's getConfig) makes electron-
    builder read ONLY that file -- package.json's own build field, and
    therefore its node-runtime/service*.ps1 extraResources, is never even
    loaded. Pins the config's own content regardless: it must name neither
    the node runtime nor the two service scripts, and must still carry
    firewall.ps1 (the one thing Light still needs -- packaging/win/
    firewall.ps1's header explains why the client needs an inbound rule too,
    not only a node).
    """
    assert LIGHT_YML.exists(), f"{LIGHT_YML} is missing"
    yml = LIGHT_YML.read_text(encoding="utf-8")

    assert "appId: org.meshbay.client.light" in yml
    assert "productName: MeshBay Light" in yml
    assert "output: dist-light" in yml

    assert "node-runtime" not in yml
    assert "service.ps1" not in yml
    assert "service-mode.ps1" not in yml
    assert "firewall.ps1" in yml

    assert "include: installer-light.nsh" in yml, (
        "nsis.include must point at the Light NSIS customisation, not the "
        "default build/installer.nsh (Full's)")


def test_light_config_keeps_the_same_no_admin_nsis_policy():
    """Per-user, no elevation at install time -- identical policy to Full's
    package.json build.nsis, for the same reason (MESHBAY_DESIGN.md
    11.2/7.5: the DPAPI-protected hub device key is account-bound)."""
    yml = LIGHT_YML.read_text(encoding="utf-8")
    assert "oneClick: false" in yml
    assert "perMachine: false" in yml
    assert "allowElevation: false" in yml


def test_dist_win_light_delegates_to_the_light_orchestrator():
    pkg = _pkg()
    scripts = pkg["scripts"]
    assert "dist:win:light" in scripts
    assert "build-win-light.ps1" in scripts["dist:win:light"]
    assert "dist:win" in scripts
    assert "build-win.ps1" in scripts["dist:win"]
    assert "build-win-light.ps1" not in scripts["dist:win"]


def test_build_win_light_skips_the_node_runtime_step():
    """The entire point of Light: no PyInstaller freeze, no ffmpeg fetch."""
    assert BUILD_WIN_LIGHT.exists(), f"{BUILD_WIN_LIGHT} is missing"
    src = BUILD_WIN_LIGHT.read_text(encoding="utf-8")
    assert "build-node-runtime.ps1" not in src
    assert "electron-builder.light.yml" in src
    assert "--config" in src


def test_build_orchestrators_share_the_common_steps_not_a_copy():
    """
    Node check / npm ci / Electron bump / sync-ui must live in exactly one
    place (build-win-common.ps1), dot-sourced by all three orchestrators --
    a copy would let them drift the way the installer flow itself once did
    (the W3 one-shot dialog bug). Every orchestrator must call the shared
    functions, none may inline its own npm ci / Electron-bump logic.
    """
    assert BUILD_WIN_COMMON.exists(), f"{BUILD_WIN_COMMON} is missing"
    common = BUILD_WIN_COMMON.read_text(encoding="utf-8")
    for fn in ("Assert-NodeVersion", "Invoke-NpmCi", "Invoke-ElectronBump", "Invoke-SyncUi"):
        assert f"function {fn}" in common, f"{fn} is not defined in build-win-common.ps1"

    full = (WIN / "build-win.ps1").read_text(encoding="utf-8")
    light = BUILD_WIN_LIGHT.read_text(encoding="utf-8")
    msix = BUILD_WIN_MSIX.read_text(encoding="utf-8")
    for src, name in ((full, "build-win.ps1"), (light, "build-win-light.ps1"),
                       (msix, "build-win-msix.ps1")):
        assert '. (Join-Path $WinDir "build-win-common.ps1")' in src, (
            f"{name} does not dot-source build-win-common.ps1")
        for fn in ("Assert-NodeVersion", "Invoke-NpmCi", "Invoke-ElectronBump", "Invoke-SyncUi"):
            assert fn in src, f"{name} does not call {fn}"
        assert "npm ci --ignore-scripts" not in src, (
            f"{name} must not re-implement npm ci inline")


def test_firewall_ps1_skips_the_node_rule_when_the_exe_is_missing():
    """
    The one behaviour Light structurally depends on: firewall.ps1 is
    shipped unforked (test_light_config_is_standalone_and_ships_no_node
    above), relying on `add` already skipping any rule whose target .exe
    does not exist -- true for "MeshBay Node" in a Light install, where
    node-runtime\\meshbay-node.exe is never there. If this guard were ever
    removed, New-NetFirewallRule would be pointed at a path that does not
    exist and Light's one firewall elevation would start failing.
    """
    src = (WIN / "firewall.ps1").read_text(encoding="utf-8")
    add_block = src.split('if ($Action -eq "add")', 1)[1]
    assert "if (-not (Test-Path $r.Path))" in add_block
    skip_stanza = add_block.split("if (-not (Test-Path $r.Path))", 1)[1].split("}", 1)[0]
    assert "continue" in skip_stanza


def test_light_installer_forces_per_user_and_elevates_firewall_once():
    assert LIGHT_NSH.exists(), f"{LIGHT_NSH} is missing"
    nsh = LIGHT_NSH.read_text(encoding="utf-8")
    install = _macro_body(nsh, "customInstall")
    mode = _macro_body(nsh, "customInstallMode")

    assert 'StrCpy $isForceCurrentInstall "1"' in mode

    assert "${IfNot} ${Silent}" in install
    i_check = install.index('firewall.ps1" check')
    i_runas = install.index('ExecShellWait "runas"')
    assert i_check < i_runas, "the unelevated check must run before any elevation"
    assert 'firewall.ps1" add' in install

    assert "MB_AutoMode" not in nsh, "there is no autostart choice for Light"
    assert "Page custom" not in nsh
    assert "MessageBox MB_YESNO" not in install, (
        "customInstall itself must ask nothing -- only customUnInstall's "
        "opt-in firewall-removal prompt uses MessageBox")


def test_light_installer_never_touches_a_co_installed_full_clients_node():
    """
    Full and Light can be installed side by side (distinct appId/
    productName/install dir -- test_light_config_is_standalone_and_ships_
    no_node above). Light's installer/uninstaller must be a complete no-op
    with respect to anything a co-installed Full client owns: its node
    process, its Startup .vbs, its Scheduled Task, its own firewall rule.
    The easy mistake here is copy-pasting installer.nsh and trimming it,
    leaving one of these in by accident.
    """
    nsh = LIGHT_NSH.read_text(encoding="utf-8")
    for forbidden in ("taskkill", 'HKCU "Environment"', "service.ps1",
                       "service-mode.ps1", ".vbs", "MeshBay Node.vbs"):
        assert forbidden not in nsh, (
            f"installer-light.nsh must not reference {forbidden!r} -- that "
            "belongs to a co-installed Full client, not to Light")


def test_light_uninstaller_offers_to_remove_the_firewall_rules_default_no():
    nsh = LIGHT_NSH.read_text(encoding="utf-8")
    uninstall = _macro_body(nsh, "customUnInstall")
    assert "${IfNot} ${Silent}" in uninstall
    assert "/SD IDNO" in uninstall
    assert 'firewall.ps1" remove' in uninstall
    assert 'ExecShellWait "runas"' in uninstall


# ── the app-side gaps a bundle-less build would otherwise hit ──────────────

def test_has_bundled_node_is_windows_only_and_packaged_only():
    """
    Off win32, or unpackaged (dev), this must stay true unconditionally --
    only a packaged Windows build can even be Light, so nothing here may
    change today's behaviour for Linux, macOS or `npm start`.
    """
    src = MAIN_JS.read_text(encoding="utf-8")
    assert "function hasBundledNode()" in src
    body = src.split("function hasBundledNode()", 1)[1].split("\n  }", 1)[0]
    assert "process.platform === 'win32'" in body
    assert "app.isPackaged" in body
    assert "return true" in body, (
        "must fall back to true (today's behaviour) off win32 / unpackaged")


def test_node_bundled_ipc_channel_exists_end_to_end():
    """main.js handles it, preload.js exposes it, platform.js wraps it --
    the same three-layer shape every other node.* capability already has."""
    main = MAIN_JS.read_text(encoding="utf-8")
    assert "ipcMain.handle('node:bundled'" in main
    assert "hasBundledNode()" in main

    preload = PRELOAD_JS.read_text(encoding="utf-8")
    assert "ipcRenderer.invoke('node:bundled')" in preload

    platform_js = (HUB_STATIC / "platform.js").read_text(encoding="utf-8")
    assert "bridge.node.bundled()" in platform_js


def test_can_elevate_checks_service_mode_ps1_actually_exists():
    """
    app.isPackaged alone used to gate canElevate -- true for Light too,
    where service-mode.ps1 is never shipped, so the Node page would offer
    "background service" and only fail when clicked. Both nodeServiceStatus
    branches (service installed, and the per-user Startup branch) must go
    through the same helper rather than reimplementing the check.
    """
    src = MAIN_JS.read_text(encoding="utf-8")
    assert "function winCanElevateServiceMode()" in src
    helper = src.split("function winCanElevateServiceMode()", 1)[1].split("\n  }", 1)[0]
    assert "app.isPackaged" in helper
    assert "'service-mode.ps1'" in helper
    assert src.count("canElevate: winCanElevateServiceMode()") == 2, (
        "both nodeServiceStatus branches must use the helper, not a bare "
        "app.isPackaged")
    assert "canElevate: app.isPackaged," not in src


def test_startup_mode_is_null_not_a_lie_when_no_node_is_found():
    """
    The per-user Startup branch used to report mode: 'startup' unconditionally,
    so a Light install with no node anywhere (bundled or on PATH) showed a
    working-looking autostart dropdown for a node that did not exist --
    node-page.js's showStartupRow is gated on typeof info.mode === 'string'.
    """
    src = MAIN_JS.read_text(encoding="utf-8")
    assert "mode: bin ? 'startup' : null," in src
    assert "mode: 'startup'," not in src


def test_create_group_page_falls_back_when_no_node_is_bundled():
    """
    The wizard's node-linking step is exactly the known "Detecting local
    node..." hang when nothing ever answers. Gating it on `bundled` (not
    just `available`, which is true for Light too -- both are Electron)
    routes a Light install to CreateGroupFormSimple: not a lesser feature,
    but the same node-free form a plain browser member already uses.
    """
    src = (HUB_STATIC / "create-group-page.js").read_text(encoding="utf-8")
    body = src.split("export function CreateGroupPage(props) {", 1)[1] \
        .split("\nfunction CreateGroupFormSimple", 1)[0]
    assert "platform.node.bundled()" in body
    assert "platform.node.available && bundled" in body
    assert "CreateGroupWizard" in body and "CreateGroupFormSimple" in body


# ------------------------------------------------------------------------
# The "MSIX" target: same feature set as Full, packaged for Microsoft Store
# submission instead of NSIS. See C:\Users\admin\devel\msix-installer.md for
# the plan. Unlike Light, this target keeps the node runtime and both
# service scripts -- what changes is packaging format, not what ships.
# Weak, text-reading evidence throughout, same reasoning as the rest of
# this file: there is no electron-builder/appx runner here either.
# ------------------------------------------------------------------------

def test_msix_config_is_standalone_and_keeps_the_full_bundle():
    """
    Unlike Light, MSIX ships the same node-runtime/ffmpeg/service scripts as
    Full -- an AppX install never elevating (msix-installer.md 4) is not a
    reason to drop the daemon, only to change how its two elevated
    operations get triggered (see the two tests below). --config still
    means this file is read alone (app-builder-lib's getConfig), so it
    cannot silently inherit Full's package.json build.nsis or any signing
    config meant for NSIS.
    """
    assert MSIX_YML.exists(), f"{MSIX_YML} is missing"
    yml = MSIX_YML.read_text(encoding="utf-8")

    assert "appId: org.meshbay.client" in yml
    assert "target: appx" in yml
    assert "output: dist-msix" in yml

    assert "node-runtime" in yml
    assert "service.ps1" in yml
    assert "service-mode.ps1" in yml
    assert "firewall.ps1" in yml


def test_msix_identity_matches_the_partner_center_reservation():
    """
    identityName/publisher/publisherDisplayName are assigned by Partner
    Center's "App identity" page when the app name is reserved -- they
    cannot be chosen freely, and a mismatch fails Store validation outright
    rather than warning. Pins the exact reservation (done 2026-09-11) so a
    future edit cannot silently drift back to electron-builder's own
    unconfigured-build stand-in ("CN=ms", see windowsSignToolManager.js's
    computePublisherName) without a test noticing.
    publisherDisplayName is "MeshBay" as Partner Center assigned it, NOT
    package.json's author company name ("MeshBay Team") -- AppXOptions.d.ts's
    own default (company name from app metadata) would pick the wrong one if
    this were ever left unset instead of explicit.
    """
    yml = MSIX_YML.read_text(encoding="utf-8")
    assert "identityName: MeshBay.MeshBay" in yml
    assert 'publisher: "CN=CE32BB0D-6B7C-4D3A-AA42-E259B778CAC9"' in yml
    assert "publisherDisplayName: MeshBay" in yml
    assert '"CN=ms"' not in yml, (
        "must not have drifted back to electron-builder's own placeholder "
        "publisher")


def test_msix_declares_no_csc_on_purpose():
    """
    No certificateFile/certificateSubjectName/certificateSha1 anywhere in
    this config -- per app-builder-lib's own windowsSignToolManager.js, an
    AppX target built with no certificate configured is logged as "Windows
    Store only build" and left unsigned; Microsoft signs it at publish time
    (msix-installer.md 3). Configuring a cert here would be wasted work, not
    extra safety, and would risk this target picking up whatever might one
    day be configured for Full's NSIS signing if it were ever added to this
    file instead of package.json's own build.win.
    """
    yml = MSIX_YML.read_text(encoding="utf-8")
    for forbidden in ("certificateFile", "certificateSubjectName", "certificateSha1"):
        assert forbidden not in yml


def test_msix_declares_the_network_capabilities_firewall_ps1_would_add():
    """
    Matches firewall.ps1's own rules, which are `-Profile Any` (private AND
    public network) -- msix-installer.md 8's #1 open item: whether Windows
    actually auto-exempts a full-trust packaged app on the strength of
    these declarations is unverified until sideloaded, but the declaration
    itself must at least match what the elevated NSIS path grants today, or
    an MSIX install would be silently narrower than Full/Light.
    """
    yml = MSIX_YML.read_text(encoding="utf-8")
    caps_block = yml.split("capabilities:", 1)[1].split("customExtensionsPath", 1)[0]
    assert "internetClientServer" in caps_block
    assert "privateNetworkClientServer" in caps_block


def test_msix_startup_task_targets_the_node_not_the_electron_shell():
    """
    addAutoLaunchExtension's built-in windows.startupTask (app-builder-lib's
    AppxTarget.js) always targets the package's own main executable -- the
    Electron shell -- which is not what "starts at sign in" means today
    (main.js's WIN_STARTUP_VBS launches meshbay-node.exe directly, keeping
    the daemon running whether or not the UI is ever opened). This config
    must NOT use addAutoLaunchExtension for that reason, and must instead
    supply its own extension via customExtensionsPath pointing at the node
    binary's in-package path -- app\\resources\\node-runtime\\meshbay-node.exe,
    derived from AppxTarget.js's own `"app\\\\" + appOutDir-relative path`
    mapping (build() in that file), which is not the same prefix
    process.resourcesPath resolves to at runtime and easy to get wrong.
    """
    yml = MSIX_YML.read_text(encoding="utf-8")
    # The comment explaining *why* addAutoLaunchExtension is not used
    # necessarily names it -- check the directive, not the prose (the same
    # "parse directives, not text" mistake CLAUDE.md's engineering lessons
    # already record for a differently-shaped bug).
    lines = [ln.strip() for ln in yml.splitlines()]
    assert not any(ln.startswith("addAutoLaunchExtension:") for ln in lines), (
        "must not set addAutoLaunchExtension -- it always targets the "
        "Electron shell, not the node binary (see this test's docstring)")
    assert "customExtensionsPath: build/appx-extensions.xml" in yml

    assert MSIX_EXTENSIONS_XML.exists(), f"{MSIX_EXTENSIONS_XML} is missing"
    ext = MSIX_EXTENSIONS_XML.read_text(encoding="utf-8")
    assert 'Category="windows.startupTask"' in ext
    assert 'Executable="app\\resources\\node-runtime\\meshbay-node.exe"' in ext
    assert 'EntryPoint="Windows.FullTrustApplication"' in ext


def test_msix_ships_the_four_required_tile_images():
    """
    app-builder-lib's AppxTarget.js requires StoreLogo/Square44x44Logo/
    Square150x150Logo/Wide310x150Logo regardless of showNameOnTiles, falling
    back to its own vendor-bundled samples if build/appx/ does not supply
    them. This repo points ELECTRON_BUILDER_WINDOWS_KITS_PATH at the system
    Windows SDK instead of that vendor bundle (build-win-msix.ps1), which
    has no samples to fall back to -- so a missing one here is a hard
    makeappx failure, not a cosmetic gap. See build/appx/README.md for
    where these came from.
    """
    appx_assets = CLIENT / "build" / "appx"
    for name in ("StoreLogo.png", "Square44x44Logo.png",
                 "Square150x150Logo.png", "Wide310x150Logo.png"):
        assert (appx_assets / name).exists(), f"{name} is missing from {appx_assets}"


def test_build_win_msix_keeps_the_node_runtime_step():
    """The opposite of Light's equivalent test: MSIX is Full's feature set,
    repackaged -- build-node-runtime.ps1 must still run."""
    assert BUILD_WIN_MSIX.exists(), f"{BUILD_WIN_MSIX} is missing"
    src = BUILD_WIN_MSIX.read_text(encoding="utf-8")
    assert "build-node-runtime.ps1" in src
    assert "electron-builder.msix.yml" in src
    assert "--config" in src
    assert "--win appx" in src


def test_dist_win_msix_delegates_to_the_msix_orchestrator():
    pkg = _pkg()
    scripts = pkg["scripts"]
    assert "dist:win:msix" in scripts
    assert "build-win-msix.ps1" in scripts["dist:win:msix"]


def test_build_win_msix_points_electron_builder_at_the_system_sdk():
    """
    electron-builder's own bundled AppX tooling download (winCodeSign-*.7z)
    extracts symlinks for binaries this target never uses and fails without
    SeCreateSymbolicLinkPrivilege -- reproduced on this machine's build
    shell. ELECTRON_BUILDER_WINDOWS_KITS_PATH (app-builder-lib's
    getWindowsKitsBundle) is the documented escape hatch; this must be set
    automatically, not left as a step a future build is expected to
    remember.
    """
    src = BUILD_WIN_MSIX.read_text(encoding="utf-8")
    assert "ELECTRON_BUILDER_WINDOWS_KITS_PATH" in src
    assert "makeappx.exe" in src


# ── main.js needs nothing new for this target ──────────────────────────────
#
# Unlike Light (which needed hasBundledNode/winCanElevateServiceMode/the
# create-group gate because the bundle itself is smaller), MSIX ships
# everything Full does, and the two elevation paths it cannot get from an
# installer already exist independently of installer.nsh:
# firewall.ps1's per-first-use Windows prompt (no admin needed for that
# fallback -- see firewall.ps1's own header) and main.js's
# winElevateServiceMode(), driven from the Node page ("the other door",
# already exercised by test_can_elevate_checks_service_mode_ps1_actually_
# exists above) rather than from setup. There is deliberately no
# MSIX-specific test here pinning main.js: the Light-target tests above
# already pin that winCanElevateServiceMode() checks for service-mode.ps1's
# presence generically, which is exactly what makes it work for a third
# packaged target without being told about it.


# ------------------------------------------------------------------------
# Three gaps a real sideload install found (2026-09-12) that reading the
# manifest and launching the app once had missed: no install-time hook means
# no equivalent of installer.nsh's PATH write either, an immediate daemon
# crash was silently discarded instead of surfacing to the user, and nobody
# told a first-time MSIX user the startup-mode choice existed at all.
# Confirmed live: process.resourcesPath/spawn work correctly under the
# installed AppX path, PATH actually gained the entry on next launch, and a
# real port-18000 collision now rejects in ~2s with the daemon's own stderr
# instead of a 60s generic timeout.
# ------------------------------------------------------------------------

ENSURE_NODE_PATH_PS1 = WIN / "ensure-node-path.ps1"


def test_ensure_node_path_script_is_idempotent_and_unelevated():
    """
    No admin verb, no elevation helper -- a per-user HKCU write never needed
    elevation in the first place (installer.nsh's customInstall already did
    this one unelevated); what MSIX lacks is an install-time hook to run
    anything from, not the right to make this specific change.
    """
    assert ENSURE_NODE_PATH_PS1.exists(), f"{ENSURE_NODE_PATH_PS1} is missing"
    src = ENSURE_NODE_PATH_PS1.read_text(encoding="utf-8")
    assert "HKEY_CURRENT_USER\\Environment" in src
    assert "already present" in src, "must be a no-op when the entry already exists"
    assert "RunAs" not in src and "Verb" not in src
    assert "WM_SETTINGCHANGE" in src or "SendMessageTimeout" in src, (
        "must broadcast the change so already-open shells notice, same as "
        "installer.nsh's own SendMessage")


def test_ensure_node_path_shipped_to_full_and_msix_not_light():
    pkg = _pkg()
    full_yml = json.dumps(pkg["build"])
    assert "ensure-node-path.ps1" in full_yml

    msix_yml = MSIX_YML.read_text(encoding="utf-8")
    assert "ensure-node-path.ps1" in msix_yml

    light_yml = LIGHT_YML.read_text(encoding="utf-8")
    assert "ensure-node-path.ps1" not in light_yml, (
        "Light has no bundled node-runtime to add to PATH")


def test_main_js_calls_ensure_node_path_on_every_launch():
    src = MAIN_JS.read_text(encoding="utf-8")
    assert "function winEnsureNodeOnPath()" in src
    body = src.split("function winEnsureNodeOnPath()", 1)[1].split("\n  }", 1)[0]
    assert "hasBundledNode()" in body, "must not run at all for a Light install"
    assert "ensure-node-path.ps1" in body
    # Actually invoked, not just defined -- registerBridge() calls it once,
    # unconditionally, on every launch (idempotent, so Full's already-set
    # PATH is just a fast no-op query each time).
    assert src.count("winEnsureNodeOnPath()") >= 2, (
        "must be both defined and called")


def test_node_start_surfaces_an_immediate_daemon_crash_instead_of_a_60s_timeout():
    """
    Reproduced live: a daemon that exits within ~1s (a port already bound,
    reproduced with a second instance colliding on 127.0.0.1:18000) used to
    be indistinguishable from one that simply never started -- spawn()'s
    stdio was 'ignore', discarding the exact stderr line that named the real
    problem, and waitForNode()'s 60s generic timeout was the only failure
    path left. spawnNodeDetachedWatched watches for an early exit and
    rejects with the daemon's own tail of stderr instead.
    """
    src = MAIN_JS.read_text(encoding="utf-8")
    assert "function spawnNodeDetachedWatched(" in src
    body = src.split("function spawnNodeDetachedWatched(", 1)[1].split("\n  }", 1)[0]
    assert "stdio: ['ignore', 'pipe', 'pipe']" in body
    assert "exited immediately" in body
    assert "NODE_CRASH_WATCH_MS" in body
    # The tail must be bounded by length, not by a line count -- a real
    # capture had the actual OSError line pushed out by two uvicorn/asyncio
    # tracebacks that followed it, which a short "last N lines" cut before
    # this was fixed to bound by characters instead.
    assert "split(/\\r?\\n/).slice(" not in body, (
        "a line-count tail can cut the one line that names the real error "
        "-- bound by characters instead (reproduced live, see the comment "
        "above this constant)")
    assert "4000" in body

    async_fn = src.split("async function spawnNodeDetached()", 1)[1].split("\n  }", 1)[0]
    assert "spawnNodeDetachedWatched" in async_fn, (
        "spawnNodeDetached must actually use the watched spawn, not the old "
        "fire-and-forget one")


def test_setup_welcome_hints_at_the_node_startup_choice():
    """
    build/installer.nsh's radio page was the only place this choice was ever
    offered, and an AppX/MSIX install has no install-time page at all to
    replace it with -- a first-time user of a build with a bundled node
    otherwise has no reason to ever find the Node page's startup-mode
    control. Shown only while neither mode is configured yet (so it
    disappears on its own once one is, or never appears for Light/non-
    Windows/browser, where platform.node.service.available is false).
    """
    src = (HUB_STATIC / "app.js").read_text(encoding="utf-8")
    fn = src.split("function SetupWelcome(", 1)[1].split("\nfunction ", 1)[0]
    assert "platform.node.bundled()" in fn
    assert "platform.node.service.status()" in fn
    assert "mode === 'service'" in fn and "autostart" in fn
    assert "setup.node_startup_hint" in fn


def test_node_startup_hint_key_exists_in_all_ten_locales():
    for name in ("en", "fr", "es", "pt-BR", "zh-CN", "ja", "de", "it", "nl", "pl"):
        cat = (HUB_STATIC / "locales" / f"{name}.js").read_text(encoding="utf-8")
        assert "'setup.node_startup_hint':" in cat, f"{name}.js is missing the key"