tauri-plugin-hdiff-update 0.4.2

Tauri v2 plugin for signed, transactional HDiffPatch directory updates.
Documentation
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
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
use std::{
    collections::HashMap,
    ffi::OsStr,
    fs,
    io::Read,
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use base64::Engine;
use fs2::FileExt;
use hdiff_update_core::{
    default_platform, download_to_file, sha256_file, write_json_file_atomic, DownloadEvent,
    HttpHeader,
};
use minisign_verify::{PublicKey, Signature};
use semver::Version;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tauri::{ipc::Channel, AppHandle, Manager, Runtime, State};
use url::Url;

use crate::file_update::{FileUpdateCommandError, FileUpdateHelperConfig};

#[cfg(windows)]
use std::{
    ffi::{c_void, OsString},
    os::windows::{ffi::OsStrExt, process::CommandExt},
    process::{Child, Command},
    thread,
    time::Duration,
};
#[cfg(windows)]
use windows_sys::Win32::{
    Foundation::{
        CloseHandle, LocalFree, ERROR_ALREADY_EXISTS, ERROR_CANCELLED, ERROR_ELEVATION_REQUIRED,
        HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT,
    },
    Security::{
        Authorization::{ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1},
        SetFileSecurityW, DACL_SECURITY_INFORMATION, GROUP_SECURITY_INFORMATION,
        OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
        SECURITY_ATTRIBUTES,
    },
    Storage::FileSystem::{CreateDirectoryW, SYNCHRONIZE},
    System::Threading::{
        GetExitCodeProcess, GetProcessId, OpenProcess, WaitForSingleObject,
        PROCESS_QUERY_LIMITED_INFORMATION,
    },
    UI::{
        Shell::{ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW},
        WindowsAndMessaging::SW_SHOWNORMAL,
    },
};

const FULL_UPDATE_ROOT: &str = "full-updates";
const TRANSACTION_SCHEMA_VERSION: u32 = 2;
const PROTECTED_PLAN_SCHEMA_VERSION: u32 = 1;
const MAX_INSTALLER_BYTES: u64 = 1024 * 1024 * 1024;
const MAX_AUTOMATIC_LAUNCH_ATTEMPTS: u32 = 2;
const ACTIVE_LAUNCH_GRACE_MS: u64 = 15_000;
const PROTECTED_PREPARED_GRACE_MS: u64 = 2 * 60 * 1000;
const PROTECTED_INSTALLING_GRACE_MS: u64 = 32 * 60 * 1000;

#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
#[cfg(windows)]
const FULL_SUPERVISOR_ARGUMENT: &str = "--hdiff-full-update-supervisor";
#[cfg(windows)]
const FULL_ELEVATED_BOOTSTRAP_ARGUMENT: &str = "--hdiff-full-update-elevated-bootstrap";
#[cfg(windows)]
const FULL_ELEVATED_WORKER_ARGUMENT: &str = "--hdiff-full-update-elevated-worker";
#[cfg(windows)]
const FULL_CLEANUP_ARGUMENT: &str = "--hdiff-full-update-cleanup";
#[cfg(windows)]
const CLEANUP_FULL: &str = "full";
#[cfg(windows)]
const CLEANUP_HELPER: &str = "helper";
#[cfg(windows)]
const PROTECTED_PLAN_FILE: &str = "plan.json";
#[cfg(windows)]
const PROTECTED_RESULT_FILE: &str = "result.json";
#[cfg(windows)]
const PROTECTED_INSTALLER_FILE: &str = "installer.exe";
#[cfg(windows)]
const PROTECTED_HELPER_FILE: &str = "update-worker.exe";
#[cfg(windows)]
const PARENT_EXIT_TIMEOUT: Duration = Duration::from_secs(5 * 60);
#[cfg(windows)]
const BOOTSTRAP_TIMEOUT: Duration = Duration::from_secs(2 * 60);
#[cfg(windows)]
const INSTALLER_TIMEOUT: Duration = Duration::from_secs(30 * 60);
#[cfg(windows)]
const PROTECTED_RESULT_TIMEOUT: Duration = Duration::from_secs(31 * 60);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FullUpdateState {
    Preparing,
    Ready,
    SupervisorStarted,
    Elevating,
    Installing,
    Completed,
    Failed,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FullUpdateTransaction {
    pub schema_version: u32,
    pub transaction_id: String,
    pub application_id: String,
    pub current_version: String,
    pub target_version: String,
    pub download_url: String,
    pub install_root: PathBuf,
    pub installer_path: PathBuf,
    pub installer_sha256: String,
    pub installer_size: u64,
    pub updater_signature: String,
    pub source_executable_sha256: String,
    pub state: FullUpdateState,
    pub launch_attempts: u32,
    pub automatic_launch_blocked: bool,
    pub last_launch_automatic: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supervisor_pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bootstrap_pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker_pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub installer_pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launched_at_ms: Option<u64>,
    pub created_at_ms: u64,
    pub updated_at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure_reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FullPreparedPointer {
    transaction_path: PathBuf,
    target_version: String,
    installer_sha256: String,
    download_url: String,
    updater_signature: String,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PreparedFullUpdateKind {
    Prepared,
    AlreadyPrepared,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreparedFullUpdate {
    pub kind: PreparedFullUpdateKind,
    pub transaction: FullUpdateTransaction,
    pub transaction_path: PathBuf,
    pub installer_path: PathBuf,
    pub bytes_downloaded: u64,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PrepareFullUpdateOptions {
    pub current_version: String,
    pub expected_version: String,
    pub raw_json: serde_json::Value,
    #[serde(default)]
    pub headers: Vec<HttpHeader>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_secs: Option<u64>,
}

#[derive(Debug, Clone, Deserialize)]
struct TauriUpdateArtifact {
    url: String,
    signature: String,
}

#[derive(Debug, Clone, Deserialize)]
struct TauriUpdateManifest {
    #[serde(alias = "name")]
    version: String,
    #[serde(default)]
    platforms: Option<HashMap<String, TauriUpdateArtifact>>,
    #[serde(default)]
    url: Option<String>,
    #[serde(default)]
    signature: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LaunchFullUpdateOptions {
    pub transaction_path: PathBuf,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LaunchFullUpdateResult {
    pub pid: u32,
}

#[cfg(windows)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProtectedFullUpdatePlan {
    schema_version: u32,
    transaction_id: String,
    application_id: String,
    current_version: String,
    target_version: String,
    install_root: PathBuf,
    installed_executable_path: PathBuf,
    protected_installer_path: PathBuf,
    protected_helper_path: PathBuf,
    installer_sha256: String,
    installer_size: u64,
    updater_signature: String,
    source_executable_sha256: String,
    bootstrap_pid: u32,
    created_at_ms: u64,
}

#[cfg(windows)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum ProtectedResultState {
    Prepared,
    Installing,
    Completed,
    Failed,
}

#[cfg(windows)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProtectedFullUpdateResult {
    state: ProtectedResultState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    worker_pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    installer_pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    installer_exit_code: Option<i32>,
    updated_at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    message: Option<String>,
}

#[cfg(windows)]
#[derive(Debug, Clone, PartialEq, Eq)]
enum FullHelperInvocation {
    Supervisor {
        transaction_path: PathBuf,
        parent_pid: u32,
    },
    ElevatedBootstrap {
        transaction_path: PathBuf,
    },
    ElevatedWorker {
        plan_path: PathBuf,
    },
    Cleanup {
        transaction_path: PathBuf,
        supervisor_pid: u32,
        full: bool,
    },
}

#[tauri::command]
pub async fn prepare_full_update<R: Runtime>(
    app: AppHandle<R>,
    config: State<'_, FileUpdateHelperConfig>,
    options: PrepareFullUpdateOptions,
    on_event: Channel<DownloadEvent>,
) -> Result<PreparedFullUpdate, FileUpdateCommandError> {
    if config.updater_public_key.trim().is_empty() {
        return Err(FileUpdateCommandError::from(
            "full updater public key is not compiled into the application",
        ));
    }
    if app.config().identifier != config.application_id {
        return Err(FileUpdateCommandError::from(
            "full update plugin application id does not match the Tauri identifier",
        ));
    }
    validate_application_id(config.application_id)?;
    validate_version_upgrade(&options.current_version, &options.expected_version)?;
    if !same_version(&options.current_version, config.current_version)
        || !same_version(
            &app.package_info().version.to_string(),
            config.current_version,
        )
    {
        return Err(FileUpdateCommandError::from(format!(
            "full update source version mismatch: updater={}, application={}, configured={}",
            options.current_version,
            app.package_info().version,
            config.current_version
        )));
    }

    let manifest: TauriUpdateManifest = serde_json::from_value(options.raw_json)?;
    if !same_version(&manifest.version, &options.expected_version) {
        return Err(FileUpdateCommandError::from(format!(
            "full update manifest version mismatch: expected {}, got {}",
            options.expected_version, manifest.version
        )));
    }
    let artifact = resolve_tauri_update_artifact(manifest)?;
    let download_url = Url::parse(&artifact.url)?;
    if download_url.scheme() != "https" {
        return Err(FileUpdateCommandError::from(
            "full update installer must use HTTPS",
        ));
    }

    let cache_root = full_update_cache_root(&app)?;
    fs::create_dir_all(&cache_root)?;
    let lock = open_lock(&cache_root)?;
    lock.lock_exclusive()?;

    if let Some(prepared) = load_reusable_update(
        &cache_root,
        &config,
        &options.expected_version,
        download_url.as_str(),
        &artifact.signature,
    )? {
        return Ok(prepared);
    }
    reset_full_update_cache(&cache_root, &config)?;

    let transaction_id = full_transaction_id(
        config.application_id,
        &options.current_version,
        &options.expected_version,
        download_url.as_str(),
        &artifact.signature,
    );
    let transaction_root = cache_root.join("transactions").join(&transaction_id);
    fs::create_dir_all(&transaction_root)?;
    ensure_plain_directory(&transaction_root)?;
    let transaction_path = transaction_root.join("transaction.json");
    let installer_path = transaction_root.join("installer.exe");
    let current_executable = std::env::current_exe()?.canonicalize()?;
    let install_root = current_executable
        .parent()
        .ok_or_else(|| FileUpdateCommandError::from("current executable has no parent"))?
        .to_path_buf();
    validate_installed_executable(&config, &install_root, &current_executable)?;
    let source_executable_sha256 = sha256_file(&current_executable)?.sha256;
    let now = now_millis();
    let mut transaction = FullUpdateTransaction {
        schema_version: TRANSACTION_SCHEMA_VERSION,
        transaction_id,
        application_id: config.application_id.to_string(),
        current_version: options.current_version.clone(),
        target_version: options.expected_version.clone(),
        download_url: download_url.as_str().to_string(),
        install_root,
        installer_path: installer_path.clone(),
        installer_sha256: String::new(),
        installer_size: 0,
        updater_signature: artifact.signature.clone(),
        source_executable_sha256,
        state: FullUpdateState::Preparing,
        launch_attempts: 0,
        automatic_launch_blocked: false,
        last_launch_automatic: false,
        supervisor_pid: None,
        bootstrap_pid: None,
        worker_pid: None,
        installer_pid: None,
        launched_at_ms: None,
        created_at_ms: now,
        updated_at_ms: now,
        failure_reason: None,
    };
    write_json_file_atomic(&transaction_path, &transaction)?;

    let preparation: Result<_, FileUpdateCommandError> = async {
        let stats = download_to_file(
            download_url.as_str(),
            &installer_path,
            &options.headers,
            options.timeout_secs,
            Some(MAX_INSTALLER_BYTES),
            |event| {
                let _ = on_event.send(event);
            },
        )
        .await?;
        ensure_plain_file(&installer_path)?;
        ensure_windows_installer(&installer_path)?;
        verify_updater_signature(
            &installer_path,
            config.updater_public_key,
            &artifact.signature,
        )?;
        let digest = sha256_file(&installer_path)?;
        Ok((stats, digest))
    }
    .await;
    let (stats, digest) = match preparation {
        Ok(prepared) => prepared,
        Err(error) => {
            transaction.state = FullUpdateState::Failed;
            transaction.updated_at_ms = now_millis();
            transaction.failure_reason = Some(error.message.clone());
            let _ = write_json_file_atomic(&transaction_path, &transaction);
            let _ = cleanup_transaction_if_inactive(
                &config,
                &cache_root,
                &transaction_path,
                &transaction,
            );
            return Err(error);
        }
    };

    transaction.installer_sha256 = digest.sha256.clone();
    transaction.installer_size = digest.size;
    transaction.state = FullUpdateState::Ready;
    transaction.updated_at_ms = now_millis();
    if let Err(error) = write_json_file_atomic(&transaction_path, &transaction) {
        let _ =
            cleanup_transaction_if_inactive(&config, &cache_root, &transaction_path, &transaction);
        return Err(FileUpdateCommandError::from(error));
    }
    if let Err(error) = write_json_file_atomic(
        cache_root.join("prepared.json"),
        &pointer_for(&transaction_path, &transaction),
    ) {
        let _ =
            cleanup_transaction_if_inactive(&config, &cache_root, &transaction_path, &transaction);
        return Err(FileUpdateCommandError::from(error));
    }

    Ok(PreparedFullUpdate {
        kind: PreparedFullUpdateKind::Prepared,
        transaction,
        transaction_path,
        installer_path,
        bytes_downloaded: stats.bytes_written,
    })
}

#[tauri::command]
pub async fn launch_full_update<R: Runtime>(
    app: AppHandle<R>,
    config: State<'_, FileUpdateHelperConfig>,
    options: LaunchFullUpdateOptions,
) -> Result<LaunchFullUpdateResult, FileUpdateCommandError> {
    let cache_root = full_update_cache_root(&app)?;
    let lock = open_lock(&cache_root)?;
    lock.lock_exclusive()?;
    let transaction_path = validate_transaction_path(&cache_root, &options.transaction_path)?;
    let pid = launch_full_update_inner(&config, &cache_root, &transaction_path, false)?;
    Ok(LaunchFullUpdateResult { pid })
}

fn resolve_tauri_update_artifact(
    manifest: TauriUpdateManifest,
) -> Result<TauriUpdateArtifact, FileUpdateCommandError> {
    if let Some(platforms) = manifest.platforms {
        let platform = default_platform();
        return platforms.get(&platform).cloned().ok_or_else(|| {
            FileUpdateCommandError::from(format!(
                "full update manifest has no artifact for {platform}"
            ))
        });
    }
    match (manifest.url, manifest.signature) {
        (Some(url), Some(signature)) => Ok(TauriUpdateArtifact { url, signature }),
        _ => Err(FileUpdateCommandError::from(
            "full update manifest does not contain an installer URL and signature",
        )),
    }
}

pub(crate) fn maybe_apply_prepared_full_update(
    config: &FileUpdateHelperConfig,
) -> Result<bool, FileUpdateCommandError> {
    let cache_root = helper_cache_root(config)?;
    let pointer_path = cache_root.join("prepared.json");
    if !pointer_path.is_file() {
        return Ok(false);
    }
    let lock = open_lock(&cache_root)?;
    lock.lock_exclusive()?;

    let pointer = match read_json::<FullPreparedPointer>(&pointer_path) {
        Ok(pointer) => pointer,
        Err(error) => {
            log::warn!(
                "discarding unreadable full update pointer: {}",
                error.message
            );
            let _ = fs::remove_file(pointer_path);
            return Ok(false);
        }
    };
    let transaction_path = match validate_transaction_path(&cache_root, &pointer.transaction_path) {
        Ok(path) => path,
        Err(error) => {
            log::warn!("discarding invalid full update pointer: {}", error.message);
            let _ = fs::remove_file(pointer_path);
            return Ok(false);
        }
    };
    let mut transaction = match read_transaction(&transaction_path) {
        Ok(transaction) => transaction,
        Err(error) => {
            log::warn!(
                "discarding invalid full update transaction: {}",
                error.message
            );
            let _ = remove_transaction_and_pointer(&cache_root, &transaction_path);
            return Ok(false);
        }
    };

    if same_version(config.current_version, &transaction.target_version) {
        let _ =
            cleanup_transaction_if_inactive(config, &cache_root, &transaction_path, &transaction);
        return Ok(false);
    }
    if let Err(error) = validate_transaction_identity(
        config,
        &cache_root,
        &transaction_path,
        &pointer,
        &transaction,
    ) {
        transaction.state = FullUpdateState::Failed;
        transaction.updated_at_ms = now_millis();
        transaction.failure_reason = Some(error.message.clone());
        let _ = write_json_file_atomic(&transaction_path, &transaction);
        let _ =
            cleanup_transaction_if_inactive(config, &cache_root, &transaction_path, &transaction);
        return Ok(false);
    }

    #[cfg(windows)]
    {
        if let Some(result) = read_protected_result(config, &transaction.transaction_id) {
            if result.state == ProtectedResultState::Failed {
                restore_ready_after_launch_failure(
                    &transaction_path,
                    &mut transaction,
                    result
                        .message
                        .as_deref()
                        .unwrap_or("protected full update worker failed"),
                )?;
                cleanup_protected_transaction_root(config, &transaction.transaction_id);
                return Ok(false);
            }
            if result.state == ProtectedResultState::Completed {
                restore_ready_after_launch_failure(
                    &transaction_path,
                    &mut transaction,
                    "full update installer completed without replacing the running version",
                )?;
                cleanup_protected_transaction_root(config, &transaction.transaction_id);
                return Ok(false);
            }
        }
    }

    match transaction.state {
        FullUpdateState::Ready => {
            if transaction.automatic_launch_blocked {
                return Ok(false);
            }
        }
        FullUpdateState::SupervisorStarted
        | FullUpdateState::Elevating
        | FullUpdateState::Installing => {
            if transaction_or_protected_has_running_process(config, &transaction)
                || transaction.launched_at_ms.is_some_and(|started| {
                    now_millis().saturating_sub(started) <= ACTIVE_LAUNCH_GRACE_MS
                })
            {
                return Ok(true);
            }
            if transaction.launch_attempts >= MAX_AUTOMATIC_LAUNCH_ATTEMPTS {
                restore_ready_after_launch_failure(
                    &transaction_path,
                    &mut transaction,
                    "full update helper stopped before installation completed",
                )?;
                return Ok(false);
            }
            transaction.state = FullUpdateState::Ready;
            transaction.supervisor_pid = None;
            transaction.bootstrap_pid = None;
            transaction.worker_pid = None;
            transaction.installer_pid = None;
            transaction.updated_at_ms = now_millis();
            write_json_file_atomic(&transaction_path, &transaction)?;
        }
        FullUpdateState::Completed | FullUpdateState::Failed => {
            let _ = cleanup_transaction_if_inactive(
                config,
                &cache_root,
                &transaction_path,
                &transaction,
            );
            return Ok(false);
        }
        FullUpdateState::Preparing => {
            transaction.state = FullUpdateState::Failed;
            transaction.updated_at_ms = now_millis();
            transaction.failure_reason =
                Some("full update preparation was interrupted".to_string());
            write_json_file_atomic(&transaction_path, &transaction)?;
            let _ = cleanup_transaction_if_inactive(
                config,
                &cache_root,
                &transaction_path,
                &transaction,
            );
            return Ok(false);
        }
    }

    match launch_full_update_inner(config, &cache_root, &transaction_path, true) {
        Ok(_) => Ok(true),
        Err(error) => {
            let mut transaction = read_transaction(&transaction_path).unwrap_or(transaction);
            restore_ready_after_launch_failure(
                &transaction_path,
                &mut transaction,
                &error.message,
            )?;
            Ok(false)
        }
    }
}

#[cfg(windows)]
pub(crate) fn maybe_run_full_update_helper(
    config: &FileUpdateHelperConfig,
    args: &[OsString],
) -> Result<bool, FileUpdateCommandError> {
    let Some(invocation) = parse_full_helper_invocation(args)? else {
        return Ok(false);
    };
    match invocation {
        FullHelperInvocation::Supervisor {
            transaction_path,
            parent_pid,
        } => run_full_supervisor(config, &transaction_path, parent_pid)?,
        FullHelperInvocation::ElevatedBootstrap { transaction_path } => {
            run_full_elevated_bootstrap(config, &transaction_path)?
        }
        FullHelperInvocation::ElevatedWorker { plan_path } => {
            run_full_elevated_worker(config, &plan_path)?
        }
        FullHelperInvocation::Cleanup {
            transaction_path,
            supervisor_pid,
            full,
        } => run_full_cleanup(config, &transaction_path, supervisor_pid, full)?,
    }
    Ok(true)
}

#[cfg(not(windows))]
pub(crate) fn maybe_run_full_update_helper(
    _config: &FileUpdateHelperConfig,
    _args: &[std::ffi::OsString],
) -> Result<bool, FileUpdateCommandError> {
    Ok(false)
}

fn launch_full_update_inner(
    config: &FileUpdateHelperConfig,
    cache_root: &Path,
    transaction_path: &Path,
    automatic: bool,
) -> Result<u32, FileUpdateCommandError> {
    let pointer = read_json::<FullPreparedPointer>(&cache_root.join("prepared.json"))?;
    let mut transaction =
        validate_ready_transaction(config, cache_root, transaction_path, &pointer)?;
    if transaction.state != FullUpdateState::Ready {
        return Err(FileUpdateCommandError::from(format!(
            "full update transaction is not ready: {:?}",
            transaction.state
        )));
    }
    validate_current_executable(config, &transaction)?;

    #[cfg(windows)]
    {
        let helper_path = copy_supervisor_helper(&transaction)?;
        transaction.state = FullUpdateState::SupervisorStarted;
        transaction.launch_attempts = transaction.launch_attempts.saturating_add(1);
        transaction.automatic_launch_blocked = false;
        transaction.last_launch_automatic = automatic;
        transaction.supervisor_pid = None;
        transaction.bootstrap_pid = None;
        transaction.worker_pid = None;
        transaction.installer_pid = None;
        transaction.launched_at_ms = Some(now_millis());
        transaction.updated_at_ms = now_millis();
        transaction.failure_reason = None;
        if let Err(error) = write_json_file_atomic(transaction_path, &transaction) {
            if let Some(helper_root) = helper_path.parent() {
                let _ = fs::remove_dir_all(helper_root);
            }
            return Err(FileUpdateCommandError::from(error));
        }

        let mut command = Command::new(&helper_path);
        command
            .arg(FULL_SUPERVISOR_ARGUMENT)
            .arg(transaction_path)
            .arg(std::process::id().to_string())
            .current_dir(
                helper_path.parent().ok_or_else(|| {
                    FileUpdateCommandError::from("full update helper has no parent")
                })?,
            )
            .creation_flags(CREATE_NO_WINDOW);
        let mut child = match command.spawn() {
            Ok(child) => child,
            Err(error) => {
                if let Some(helper_root) = helper_path.parent() {
                    let _ = fs::remove_dir_all(helper_root);
                }
                restore_ready_after_launch_failure(
                    transaction_path,
                    &mut transaction,
                    &format!(
                        "failed to start full update supervisor {}: {error}",
                        helper_path.display()
                    ),
                )?;
                return Err(FileUpdateCommandError::from(format!(
                    "failed to start full update supervisor {}: {error}",
                    helper_path.display()
                )));
            }
        };
        let pid = child.id();
        transaction.supervisor_pid = Some(pid);
        transaction.updated_at_ms = now_millis();
        if let Err(error) = write_json_file_atomic(transaction_path, &transaction) {
            let _ = child.kill();
            let _ = child.wait();
            if let Some(helper_root) = helper_path.parent() {
                let _ = fs::remove_dir_all(helper_root);
            }
            restore_ready_after_launch_failure(
                transaction_path,
                &mut transaction,
                "failed to persist full update supervisor process id",
            )?;
            return Err(FileUpdateCommandError::from(error));
        }
        Ok(pid)
    }

    #[cfg(not(windows))]
    {
        let _ = (automatic, transaction);
        Err(FileUpdateCommandError::from(
            "persistent full updates are only implemented on Windows",
        ))
    }
}

fn load_reusable_update(
    cache_root: &Path,
    config: &FileUpdateHelperConfig,
    target_version: &str,
    download_url: &str,
    updater_signature: &str,
) -> Result<Option<PreparedFullUpdate>, FileUpdateCommandError> {
    let pointer_path = cache_root.join("prepared.json");
    if !pointer_path.is_file() {
        return Ok(None);
    }
    let pointer = match read_json::<FullPreparedPointer>(&pointer_path) {
        Ok(pointer) => pointer,
        Err(_) => return Ok(None),
    };
    if !release_identity_matches(
        &pointer.target_version,
        &pointer.download_url,
        &pointer.updater_signature,
        target_version,
        download_url,
        updater_signature,
    ) {
        return Ok(None);
    }
    let transaction_path = match validate_transaction_path(cache_root, &pointer.transaction_path) {
        Ok(path) => path,
        Err(_) => return Ok(None),
    };
    let transaction =
        match validate_ready_transaction(config, cache_root, &transaction_path, &pointer) {
            Ok(transaction) => transaction,
            Err(_) => return Ok(None),
        };
    if transaction.state != FullUpdateState::Ready
        || !release_identity_matches(
            &transaction.target_version,
            &transaction.download_url,
            &transaction.updater_signature,
            target_version,
            download_url,
            updater_signature,
        )
    {
        return Ok(None);
    }
    validate_current_executable(config, &transaction)?;
    Ok(Some(PreparedFullUpdate {
        kind: PreparedFullUpdateKind::AlreadyPrepared,
        installer_path: transaction.installer_path.clone(),
        transaction,
        transaction_path,
        bytes_downloaded: 0,
    }))
}

fn validate_ready_transaction(
    config: &FileUpdateHelperConfig,
    cache_root: &Path,
    transaction_path: &Path,
    pointer: &FullPreparedPointer,
) -> Result<FullUpdateTransaction, FileUpdateCommandError> {
    let transaction_path = validate_transaction_path(cache_root, transaction_path)?;
    let mut transaction = read_transaction(&transaction_path)?;
    validate_transaction_identity(config, cache_root, &transaction_path, pointer, &transaction)?;
    let transaction_root = transaction_path
        .parent()
        .ok_or_else(|| FileUpdateCommandError::from("full update transaction has no parent"))?;
    let installer_path = transaction.installer_path.canonicalize()?;
    if !installer_path.starts_with(transaction_root)
        || installer_path.file_name() != Some(OsStr::new("installer.exe"))
    {
        return Err(FileUpdateCommandError::from(
            "full update installer is outside its transaction",
        ));
    }
    ensure_plain_file(&installer_path)?;
    let digest = sha256_file(&installer_path)?;
    if digest.size != transaction.installer_size || digest.sha256 != transaction.installer_sha256 {
        return Err(FileUpdateCommandError::from(
            "full update installer hash or size does not match its transaction",
        ));
    }
    ensure_windows_installer(&installer_path)?;
    verify_updater_signature(
        &installer_path,
        config.updater_public_key,
        &transaction.updater_signature,
    )?;
    transaction.installer_path = installer_path;
    Ok(transaction)
}

fn validate_transaction_identity(
    config: &FileUpdateHelperConfig,
    cache_root: &Path,
    transaction_path: &Path,
    pointer: &FullPreparedPointer,
    transaction: &FullUpdateTransaction,
) -> Result<(), FileUpdateCommandError> {
    validate_application_id(config.application_id)?;
    if transaction.application_id != config.application_id {
        return Err(FileUpdateCommandError::from(
            "full update transaction belongs to another application",
        ));
    }
    if !same_version(&transaction.current_version, config.current_version) {
        return Err(FileUpdateCommandError::from(
            "full update transaction source version does not match the application",
        ));
    }
    validate_version_upgrade(&transaction.current_version, &transaction.target_version)?;
    let canonical_transaction = validate_transaction_path(cache_root, transaction_path)?;
    if pointer.transaction_path.canonicalize()? != canonical_transaction
        || pointer.target_version != transaction.target_version
        || pointer.installer_sha256 != transaction.installer_sha256
        || pointer.download_url != transaction.download_url
        || pointer.updater_signature != transaction.updater_signature
    {
        return Err(FileUpdateCommandError::from(
            "full update prepared pointer does not match its transaction",
        ));
    }
    let expected_id = full_transaction_id(
        &transaction.application_id,
        &transaction.current_version,
        &transaction.target_version,
        &transaction.download_url,
        &transaction.updater_signature,
    );
    if transaction.transaction_id != expected_id {
        return Err(FileUpdateCommandError::from(
            "full update transaction identity is invalid",
        ));
    }
    let transaction_root = canonical_transaction
        .parent()
        .ok_or_else(|| FileUpdateCommandError::from("full update transaction has no parent"))?;
    if transaction_root.file_name() != Some(OsStr::new(&transaction.transaction_id)) {
        return Err(FileUpdateCommandError::from(
            "full update transaction directory does not match its identity",
        ));
    }
    let install_root = transaction.install_root.canonicalize()?;
    if install_root != transaction.install_root {
        return Err(FileUpdateCommandError::from(
            "full update installation root is not canonical",
        ));
    }
    let installed_executable = install_root.join(config.main_executable).canonicalize()?;
    validate_installed_executable(config, &install_root, &installed_executable)?;
    Ok(())
}

fn validate_current_executable(
    config: &FileUpdateHelperConfig,
    transaction: &FullUpdateTransaction,
) -> Result<(), FileUpdateCommandError> {
    let current_executable = std::env::current_exe()?.canonicalize()?;
    let expected_executable = transaction
        .install_root
        .join(config.main_executable)
        .canonicalize()?;
    if current_executable != expected_executable {
        return Err(FileUpdateCommandError::from(
            "full update launch must originate from the installed application executable",
        ));
    }
    let digest = sha256_file(&current_executable)?;
    if digest.sha256 != transaction.source_executable_sha256 {
        return Err(FileUpdateCommandError::from(
            "running executable does not match the prepared full update source",
        ));
    }
    Ok(())
}

fn validate_installed_executable(
    config: &FileUpdateHelperConfig,
    install_root: &Path,
    executable: &Path,
) -> Result<(), FileUpdateCommandError> {
    ensure_plain_directory(install_root)?;
    validate_machine_install_root(install_root)?;
    ensure_plain_file(executable)?;
    if executable.parent() != Some(install_root)
        || !windows_file_name_eq(executable, config.main_executable)
    {
        return Err(FileUpdateCommandError::from(
            "full update executable is outside the configured installation root",
        ));
    }
    Ok(())
}

#[cfg(windows)]
fn validate_machine_install_root(install_root: &Path) -> Result<(), FileUpdateCommandError> {
    let inside_program_files = ["PROGRAMFILES", "PROGRAMFILES(X86)"]
        .into_iter()
        .filter_map(std::env::var_os)
        .filter_map(|path| PathBuf::from(path).canonicalize().ok())
        .any(|root| install_root.starts_with(root));
    if !inside_program_files {
        return Err(FileUpdateCommandError::from(
            "persistent full updates require a per-machine Program Files installation",
        ));
    }
    Ok(())
}

#[cfg(not(windows))]
fn validate_machine_install_root(_install_root: &Path) -> Result<(), FileUpdateCommandError> {
    Ok(())
}

fn read_transaction(path: &Path) -> Result<FullUpdateTransaction, FileUpdateCommandError> {
    let transaction = read_json::<FullUpdateTransaction>(path)?;
    if transaction.schema_version != TRANSACTION_SCHEMA_VERSION {
        return Err(FileUpdateCommandError::from(format!(
            "unsupported full update transaction schema version: {}",
            transaction.schema_version
        )));
    }
    Ok(transaction)
}

fn reset_full_update_cache(
    cache_root: &Path,
    config: &FileUpdateHelperConfig,
) -> Result<(), FileUpdateCommandError> {
    let transactions_root = cache_root.join("transactions");
    if transactions_root.exists() {
        ensure_plain_directory(&transactions_root)?;
        for entry in fs::read_dir(&transactions_root)? {
            let entry = entry?;
            let entry_path = entry.path();
            ensure_plain_directory(&entry_path)?;
            let transaction_path = entry_path.join("transaction.json");
            if let Ok(transaction) = read_transaction(&transaction_path) {
                if transaction_or_protected_has_running_process(config, &transaction)
                    || (matches!(
                        transaction.state,
                        FullUpdateState::SupervisorStarted
                            | FullUpdateState::Elevating
                            | FullUpdateState::Installing
                    ) && transaction.launched_at_ms.is_some_and(|started| {
                        now_millis().saturating_sub(started) <= ACTIVE_LAUNCH_GRACE_MS
                    }))
                {
                    return Err(FileUpdateCommandError::from(
                        "a full update installation is already running",
                    ));
                }
            }
            fs::remove_dir_all(entry_path)?;
        }
    } else {
        fs::create_dir_all(&transactions_root)?;
    }
    let pointer_path = cache_root.join("prepared.json");
    if pointer_path.is_file() {
        fs::remove_file(pointer_path)?;
    }
    Ok(())
}

fn restore_ready_after_launch_failure(
    transaction_path: &Path,
    transaction: &mut FullUpdateTransaction,
    reason: &str,
) -> Result<(), FileUpdateCommandError> {
    transaction.state = FullUpdateState::Ready;
    transaction.automatic_launch_blocked = true;
    transaction.bootstrap_pid = None;
    transaction.worker_pid = None;
    transaction.installer_pid = None;
    transaction.updated_at_ms = now_millis();
    transaction.failure_reason = Some(reason.to_string());
    write_json_file_atomic(transaction_path, transaction)?;
    Ok(())
}

pub(crate) fn cleanup_full_update_cache(
    config: &FileUpdateHelperConfig,
) -> Result<(), FileUpdateCommandError> {
    let cache_root = helper_cache_root(config)?;
    if cache_root.exists() {
        ensure_plain_directory(&cache_root)?;
        let lock = open_lock(&cache_root)?;
        lock.lock_exclusive()?;
        let transactions_root = cache_root.join("transactions");
        if transactions_root.is_dir() {
            ensure_plain_directory(&transactions_root)?;
            for entry in fs::read_dir(&transactions_root)? {
                let entry = entry?;
                let entry_path = entry.path();
                ensure_plain_directory(&entry_path)?;
                let transaction_path = entry_path.join("transaction.json");
                let Ok(transaction) = read_transaction(&transaction_path) else {
                    continue;
                };
                if is_locally_collectable(transaction.state)
                    && !transaction_or_protected_has_running_process(config, &transaction)
                {
                    let _ = remove_transaction_and_pointer(&cache_root, &transaction_path);
                }
            }
        }
    }
    cleanup_protected_terminal_roots(config);
    Ok(())
}

fn cleanup_transaction_if_inactive(
    config: &FileUpdateHelperConfig,
    cache_root: &Path,
    transaction_path: &Path,
    transaction: &FullUpdateTransaction,
) -> Result<bool, FileUpdateCommandError> {
    if transaction_or_protected_has_running_process(config, transaction) {
        return Ok(false);
    }
    remove_transaction_and_pointer(cache_root, transaction_path)?;
    Ok(true)
}

fn remove_transaction_and_pointer(
    cache_root: &Path,
    transaction_path: &Path,
) -> Result<(), FileUpdateCommandError> {
    let transaction_path = validate_transaction_path(cache_root, transaction_path)?;
    let transaction_root = transaction_path
        .parent()
        .ok_or_else(|| FileUpdateCommandError::from("full update transaction has no parent"))?;
    let pointer_path = cache_root.join("prepared.json");
    let pointer_matches = read_json::<FullPreparedPointer>(&pointer_path)
        .ok()
        .and_then(|pointer| pointer.transaction_path.canonicalize().ok())
        .is_some_and(|path| path == transaction_path);
    ensure_plain_directory(transaction_root)?;
    fs::remove_dir_all(transaction_root)?;
    if pointer_matches && pointer_path.is_file() {
        fs::remove_file(pointer_path)?;
    }
    Ok(())
}

fn full_update_cache_root<R: Runtime>(
    app: &AppHandle<R>,
) -> Result<PathBuf, FileUpdateCommandError> {
    Ok(app
        .path()
        .app_local_data_dir()?
        .join("hdiff-update")
        .join(FULL_UPDATE_ROOT))
}

fn helper_cache_root(config: &FileUpdateHelperConfig) -> Result<PathBuf, FileUpdateCommandError> {
    let local_app_data = std::env::var_os("LOCALAPPDATA")
        .ok_or_else(|| FileUpdateCommandError::from("LOCALAPPDATA is not available"))?;
    Ok(PathBuf::from(local_app_data)
        .join(config.application_id)
        .join("hdiff-update")
        .join(FULL_UPDATE_ROOT))
}

fn open_lock(cache_root: &Path) -> Result<fs::File, FileUpdateCommandError> {
    fs::create_dir_all(cache_root)?;
    Ok(fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(cache_root.join("lock"))?)
}

fn validate_transaction_path(
    cache_root: &Path,
    transaction_path: &Path,
) -> Result<PathBuf, FileUpdateCommandError> {
    let expected_root = cache_root.join("transactions").canonicalize()?;
    let transaction_path = transaction_path.canonicalize()?;
    if !transaction_path.starts_with(expected_root)
        || transaction_path.file_name() != Some(OsStr::new("transaction.json"))
    {
        return Err(FileUpdateCommandError::from(format!(
            "full update transaction is outside the managed cache: {}",
            transaction_path.display()
        )));
    }
    Ok(transaction_path)
}

fn pointer_for(
    transaction_path: &Path,
    transaction: &FullUpdateTransaction,
) -> FullPreparedPointer {
    FullPreparedPointer {
        transaction_path: transaction_path.to_path_buf(),
        target_version: transaction.target_version.clone(),
        installer_sha256: transaction.installer_sha256.clone(),
        download_url: transaction.download_url.clone(),
        updater_signature: transaction.updater_signature.clone(),
    }
}

fn verify_updater_signature(
    installer_path: &Path,
    encoded_public_key: &str,
    encoded_signature: &str,
) -> Result<(), FileUpdateCommandError> {
    let public_key_text = decode_base64_utf8(encoded_public_key, "updater public key")?;
    let signature_text = decode_base64_utf8(encoded_signature, "updater signature")?;
    let public_key = PublicKey::decode(&public_key_text)?;
    let signature = Signature::decode(&signature_text)?;
    let mut verifier = public_key.verify_stream(&signature)?;
    let mut installer = fs::File::open(installer_path)?;
    let mut buffer = vec![0_u8; 1024 * 1024];
    loop {
        let read = installer.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        verifier.update(&buffer[..read]);
    }
    verifier.finalize()?;
    Ok(())
}

fn decode_base64_utf8(value: &str, label: &str) -> Result<String, FileUpdateCommandError> {
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(value.trim())
        .map_err(|error| FileUpdateCommandError::from(format!("invalid {label}: {error}")))?;
    String::from_utf8(decoded)
        .map_err(|error| FileUpdateCommandError::from(format!("invalid {label}: {error}")))
}

fn ensure_windows_installer(path: &Path) -> Result<(), FileUpdateCommandError> {
    let mut file = fs::File::open(path)?;
    let mut magic = [0_u8; 2];
    file.read_exact(&mut magic)?;
    if magic != *b"MZ" {
        return Err(FileUpdateCommandError::from(
            "full update artifact is not a Windows executable",
        ));
    }
    Ok(())
}

fn ensure_plain_directory(path: &Path) -> Result<(), FileUpdateCommandError> {
    let metadata = fs::symlink_metadata(path)?;
    if !metadata.is_dir() || metadata.file_type().is_symlink() || is_reparse_point(&metadata) {
        return Err(FileUpdateCommandError::from(format!(
            "directory is missing or is a reparse point: {}",
            path.display()
        )));
    }
    Ok(())
}

fn ensure_plain_file(path: &Path) -> Result<(), FileUpdateCommandError> {
    let metadata = fs::symlink_metadata(path)?;
    if !metadata.is_file() || metadata.file_type().is_symlink() || is_reparse_point(&metadata) {
        return Err(FileUpdateCommandError::from(format!(
            "file is missing or is a reparse point: {}",
            path.display()
        )));
    }
    Ok(())
}

#[cfg(windows)]
fn is_reparse_point(metadata: &fs::Metadata) -> bool {
    use std::os::windows::fs::MetadataExt;
    metadata.file_attributes() & 0x0000_0400 != 0
}

#[cfg(not(windows))]
fn is_reparse_point(_metadata: &fs::Metadata) -> bool {
    false
}

fn validate_application_id(application_id: &str) -> Result<(), FileUpdateCommandError> {
    if application_id.is_empty()
        || !application_id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
    {
        return Err(FileUpdateCommandError::from(
            "full update application id contains unsupported path characters",
        ));
    }
    Ok(())
}

fn validate_version_upgrade(current: &str, target: &str) -> Result<(), FileUpdateCommandError> {
    let current = parse_version(current)?;
    let target = parse_version(target)?;
    if target <= current {
        return Err(FileUpdateCommandError::from(
            "full update target version is not newer than the current version",
        ));
    }
    Ok(())
}

fn same_version(left: &str, right: &str) -> bool {
    match (parse_version(left), parse_version(right)) {
        (Ok(left), Ok(right)) => left == right,
        _ => left.trim() == right.trim(),
    }
}

fn release_identity_matches(
    stored_version: &str,
    stored_url: &str,
    stored_signature: &str,
    requested_version: &str,
    requested_url: &str,
    requested_signature: &str,
) -> bool {
    same_version(stored_version, requested_version)
        && stored_url == requested_url
        && stored_signature == requested_signature
}

fn is_locally_collectable(state: FullUpdateState) -> bool {
    matches!(
        state,
        FullUpdateState::Preparing | FullUpdateState::Completed | FullUpdateState::Failed
    )
}

fn parse_version(value: &str) -> Result<Version, FileUpdateCommandError> {
    Version::parse(value.trim().trim_start_matches('v')).map_err(FileUpdateCommandError::from)
}

fn full_transaction_id(
    application_id: &str,
    current_version: &str,
    target_version: &str,
    download_url: &str,
    updater_signature: &str,
) -> String {
    let mut hasher = Sha256::new();
    for value in [
        application_id,
        current_version,
        target_version,
        download_url,
        updater_signature,
    ] {
        hasher.update(value.as_bytes());
        hasher.update([0]);
    }
    hex::encode(hasher.finalize())
}

fn read_json<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T, FileUpdateCommandError> {
    Ok(serde_json::from_slice(&fs::read(path)?)?)
}

fn now_millis() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .min(u64::MAX as u128) as u64
}

fn windows_file_name_eq(path: &Path, expected: &str) -> bool {
    path.file_name()
        .and_then(OsStr::to_str)
        .is_some_and(|name| name.eq_ignore_ascii_case(expected))
}

fn transaction_has_running_process(transaction: &FullUpdateTransaction) -> bool {
    [
        transaction.supervisor_pid,
        transaction.bootstrap_pid,
        transaction.worker_pid,
        transaction.installer_pid,
    ]
    .into_iter()
    .flatten()
    .any(process_is_running)
}

fn transaction_or_protected_has_running_process(
    config: &FileUpdateHelperConfig,
    transaction: &FullUpdateTransaction,
) -> bool {
    transaction_has_running_process(transaction)
        || protected_transaction_has_running_process(config, &transaction.transaction_id)
}

#[cfg(windows)]
fn protected_transaction_has_running_process(
    config: &FileUpdateHelperConfig,
    transaction_id: &str,
) -> bool {
    let Some(result) = read_protected_result(config, transaction_id) else {
        return false;
    };
    (result.state == ProtectedResultState::Prepared
        && now_millis().saturating_sub(result.updated_at_ms) <= PROTECTED_PREPARED_GRACE_MS)
        || (result.state == ProtectedResultState::Installing
            && now_millis().saturating_sub(result.updated_at_ms) <= PROTECTED_INSTALLING_GRACE_MS)
        || result.worker_pid.is_some_and(process_is_running)
        || result.installer_pid.is_some_and(process_is_running)
}

#[cfg(windows)]
fn read_protected_result(
    config: &FileUpdateHelperConfig,
    transaction_id: &str,
) -> Option<ProtectedFullUpdateResult> {
    let root = protected_transaction_root(config, transaction_id).ok()?;
    read_json::<ProtectedFullUpdateResult>(&root.join(PROTECTED_RESULT_FILE)).ok()
}

#[cfg(not(windows))]
fn protected_transaction_has_running_process(
    _config: &FileUpdateHelperConfig,
    _transaction_id: &str,
) -> bool {
    false
}

#[cfg(windows)]
fn parse_full_helper_invocation(
    args: &[OsString],
) -> Result<Option<FullHelperInvocation>, FileUpdateCommandError> {
    let Some(mode) = args.get(1).and_then(|value| value.to_str()) else {
        return Ok(None);
    };
    let invocation = match mode {
        FULL_SUPERVISOR_ARGUMENT => FullHelperInvocation::Supervisor {
            transaction_path: required_path_argument(args, 2, "transaction path")?,
            parent_pid: required_pid_argument(args, 3, "parent process id")?,
        },
        FULL_ELEVATED_BOOTSTRAP_ARGUMENT => FullHelperInvocation::ElevatedBootstrap {
            transaction_path: required_path_argument(args, 2, "transaction path")?,
        },
        FULL_ELEVATED_WORKER_ARGUMENT => FullHelperInvocation::ElevatedWorker {
            plan_path: required_path_argument(args, 2, "protected update plan path")?,
        },
        FULL_CLEANUP_ARGUMENT => {
            let kind = args
                .get(4)
                .and_then(|value| value.to_str())
                .ok_or_else(|| FileUpdateCommandError::from("missing cleanup kind"))?;
            let full = match kind {
                CLEANUP_FULL => true,
                CLEANUP_HELPER => false,
                _ => {
                    return Err(FileUpdateCommandError::from(
                        "unsupported full update cleanup kind",
                    ))
                }
            };
            FullHelperInvocation::Cleanup {
                transaction_path: required_path_argument(args, 2, "transaction path")?,
                supervisor_pid: required_pid_argument(args, 3, "supervisor process id")?,
                full,
            }
        }
        _ => return Ok(None),
    };
    Ok(Some(invocation))
}

#[cfg(windows)]
fn required_path_argument(
    args: &[OsString],
    index: usize,
    label: &str,
) -> Result<PathBuf, FileUpdateCommandError> {
    args.get(index)
        .map(PathBuf::from)
        .ok_or_else(|| FileUpdateCommandError::from(format!("missing {label}")))
}

#[cfg(windows)]
fn required_pid_argument(
    args: &[OsString],
    index: usize,
    label: &str,
) -> Result<u32, FileUpdateCommandError> {
    args.get(index)
        .and_then(|value| value.to_str())
        .ok_or_else(|| FileUpdateCommandError::from(format!("missing {label}")))?
        .parse::<u32>()
        .map_err(FileUpdateCommandError::from)
}

#[cfg(windows)]
fn copy_supervisor_helper(
    transaction: &FullUpdateTransaction,
) -> Result<PathBuf, FileUpdateCommandError> {
    let current_executable = std::env::current_exe()?.canonicalize()?;
    let installer_path = transaction.installer_path.canonicalize()?;
    let transaction_root = installer_path
        .parent()
        .ok_or_else(|| FileUpdateCommandError::from("full update transaction has no parent"))?;
    let helper_root = transaction_root.join("helper");
    if helper_root.exists() {
        ensure_plain_directory(&helper_root)?;
        fs::remove_dir_all(&helper_root)?;
    }
    fs::create_dir_all(&helper_root)?;
    ensure_plain_directory(&helper_root)?;
    let helper_path = helper_root.join(
        current_executable
            .file_name()
            .unwrap_or_else(|| OsStr::new("update-supervisor.exe")),
    );
    copy_file_synced(&current_executable, &helper_path)?;
    let helper_digest = sha256_file(&helper_path)?;
    if helper_digest.sha256 != transaction.source_executable_sha256 {
        return Err(FileUpdateCommandError::from(
            "copied full update supervisor failed SHA-256 verification",
        ));
    }
    Ok(helper_path)
}

#[cfg(windows)]
fn run_full_supervisor(
    config: &FileUpdateHelperConfig,
    transaction_path: &Path,
    parent_pid: u32,
) -> Result<(), FileUpdateCommandError> {
    let cache_root = helper_cache_root(config)?;
    let transaction_path = validate_transaction_path(&cache_root, transaction_path)?;
    let pointer = read_json::<FullPreparedPointer>(&cache_root.join("prepared.json"))?;
    let transaction =
        validate_ready_or_active_transaction(config, &cache_root, &transaction_path, &pointer)?;
    let own_digest = sha256_file(std::env::current_exe()?)?;
    if own_digest.sha256 != transaction.source_executable_sha256 {
        return Err(FileUpdateCommandError::from(
            "full update supervisor executable hash does not match the transaction",
        ));
    }
    wait_for_process_exit(parent_pid, PARENT_EXIT_TIMEOUT)?;

    let mut transaction =
        validate_ready_or_active_transaction(config, &cache_root, &transaction_path, &pointer)?;
    let installed_executable = transaction
        .install_root
        .join(config.main_executable)
        .canonicalize()?;
    let installed_digest = sha256_file(&installed_executable)?;
    if installed_digest.sha256 != transaction.source_executable_sha256 {
        return recover_supervisor_failure(
            config,
            &transaction_path,
            &mut transaction,
            "installed executable changed after full update preparation",
        );
    }

    transaction.state = FullUpdateState::Elevating;
    transaction.updated_at_ms = now_millis();
    write_json_file_atomic(&transaction_path, &transaction)?;
    let parameters = windows_command_line(&[
        FULL_ELEVATED_BOOTSTRAP_ARGUMENT.to_string(),
        transaction_path.to_string_lossy().into_owned(),
    ]);
    let elevated = match shell_execute_elevated(&installed_executable, &parameters) {
        Ok(process) => process,
        Err(error) => {
            return recover_supervisor_failure(
                config,
                &transaction_path,
                &mut transaction,
                &error.message,
            )
        }
    };
    transaction.bootstrap_pid = Some(elevated.pid);
    transaction.updated_at_ms = now_millis();
    write_json_file_atomic(&transaction_path, &transaction)?;

    let bootstrap_exit = wait_process_handle(elevated.handle, BOOTSTRAP_TIMEOUT)?;
    if bootstrap_exit != 0 {
        return recover_supervisor_failure(
            config,
            &transaction_path,
            &mut transaction,
            &format!("elevated full update bootstrap exited with code {bootstrap_exit}"),
        );
    }

    match wait_for_protected_result(
        config,
        &transaction.transaction_id,
        PROTECTED_RESULT_TIMEOUT,
    ) {
        Ok(result) if result.state == ProtectedResultState::Completed => {
            if let Ok(mut latest) = read_transaction(&transaction_path) {
                latest.state = FullUpdateState::Completed;
                latest.updated_at_ms = now_millis();
                latest.failure_reason = None;
                let _ = write_json_file_atomic(&transaction_path, &latest);
            }
            if let Err(error) = spawn_cleanup_helper(
                config,
                &transaction.install_root,
                &transaction_path,
                std::process::id(),
                true,
            ) {
                log::warn!(
                    "full update completed but deferred cache cleanup could not start: {}",
                    error.message
                );
            }
            Ok(())
        }
        Ok(result) => recover_supervisor_failure(
            config,
            &transaction_path,
            &mut transaction,
            result
                .message
                .as_deref()
                .unwrap_or("full update installer failed"),
        ),
        Err(error) => {
            recover_supervisor_failure(config, &transaction_path, &mut transaction, &error.message)
        }
    }
}

#[cfg(windows)]
fn validate_ready_or_active_transaction(
    config: &FileUpdateHelperConfig,
    cache_root: &Path,
    transaction_path: &Path,
    pointer: &FullPreparedPointer,
) -> Result<FullUpdateTransaction, FileUpdateCommandError> {
    let transaction = validate_ready_transaction(config, cache_root, transaction_path, pointer)?;
    if !matches!(
        transaction.state,
        FullUpdateState::Ready
            | FullUpdateState::SupervisorStarted
            | FullUpdateState::Elevating
            | FullUpdateState::Installing
    ) {
        return Err(FileUpdateCommandError::from(format!(
            "full update transaction is not launchable: {:?}",
            transaction.state
        )));
    }
    Ok(transaction)
}

#[cfg(windows)]
fn recover_supervisor_failure(
    config: &FileUpdateHelperConfig,
    transaction_path: &Path,
    transaction: &mut FullUpdateTransaction,
    reason: &str,
) -> Result<(), FileUpdateCommandError> {
    if protected_transaction_has_running_process(config, &transaction.transaction_id) {
        return Err(FileUpdateCommandError::from(format!(
            "{reason}; protected full update process is still running"
        )));
    }
    let latest = read_transaction(transaction_path).unwrap_or_else(|_| transaction.clone());
    *transaction = latest;
    restore_ready_after_launch_failure(transaction_path, transaction, reason)?;
    cleanup_protected_transaction_root(config, &transaction.transaction_id);
    if let Err(error) = spawn_cleanup_helper(
        config,
        &transaction.install_root,
        transaction_path,
        std::process::id(),
        false,
    ) {
        log::warn!(
            "failed to start deferred full update helper cleanup: {}",
            error.message
        );
    }
    launch_installed_application(config, &transaction.install_root)?;
    Ok(())
}

#[cfg(windows)]
fn run_full_elevated_bootstrap(
    config: &FileUpdateHelperConfig,
    transaction_path: &Path,
) -> Result<(), FileUpdateCommandError> {
    let cache_root = helper_cache_root(config)?;
    let transaction_path = validate_transaction_path(&cache_root, transaction_path)?;
    let pointer = read_json::<FullPreparedPointer>(&cache_root.join("prepared.json"))?;
    let transaction =
        validate_ready_or_active_transaction(config, &cache_root, &transaction_path, &pointer)?;
    validate_current_executable(config, &transaction)?;

    let protected_root = prepare_protected_transaction_root(config, &transaction.transaction_id)?;
    let mut cleanup_guard = ProtectedRootCleanupGuard::new(protected_root.clone());
    let protected_installer = protected_root.join(PROTECTED_INSTALLER_FILE);
    let protected_helper = protected_root.join(PROTECTED_HELPER_FILE);
    copy_file_synced(&transaction.installer_path, &protected_installer)?;
    copy_file_synced(&std::env::current_exe()?, &protected_helper)?;
    verify_protected_copy(
        &protected_installer,
        transaction.installer_size,
        &transaction.installer_sha256,
        config.updater_public_key,
        &transaction.updater_signature,
    )?;
    let helper_digest = sha256_file(&protected_helper)?;
    if helper_digest.sha256 != transaction.source_executable_sha256 {
        return Err(FileUpdateCommandError::from(
            "protected full update worker failed SHA-256 verification",
        ));
    }

    let installed_executable = transaction
        .install_root
        .join(config.main_executable)
        .canonicalize()?;
    let plan = ProtectedFullUpdatePlan {
        schema_version: PROTECTED_PLAN_SCHEMA_VERSION,
        transaction_id: transaction.transaction_id.clone(),
        application_id: transaction.application_id.clone(),
        current_version: transaction.current_version.clone(),
        target_version: transaction.target_version.clone(),
        install_root: transaction.install_root.clone(),
        installed_executable_path: installed_executable,
        protected_installer_path: protected_installer,
        protected_helper_path: protected_helper.clone(),
        installer_sha256: transaction.installer_sha256.clone(),
        installer_size: transaction.installer_size,
        updater_signature: transaction.updater_signature.clone(),
        source_executable_sha256: transaction.source_executable_sha256.clone(),
        bootstrap_pid: std::process::id(),
        created_at_ms: now_millis(),
    };
    let plan_path = protected_root.join(PROTECTED_PLAN_FILE);
    write_json_file_atomic(&plan_path, &plan)?;
    let result_path = protected_root.join(PROTECTED_RESULT_FILE);
    write_protected_result(
        &result_path,
        ProtectedResultState::Prepared,
        None,
        None,
        None,
        None,
    )?;

    let mut command = Command::new(&protected_helper);
    command
        .arg(FULL_ELEVATED_WORKER_ARGUMENT)
        .arg(&plan_path)
        .current_dir(&protected_root)
        .creation_flags(CREATE_NO_WINDOW);
    let mut child = command.spawn().map_err(|error| {
        FileUpdateCommandError::from(format!(
            "failed to start protected full update worker {}: {error}",
            protected_helper.display()
        ))
    })?;
    let worker_pid = child.id();
    if let Err(error) = write_protected_result(
        &result_path,
        ProtectedResultState::Prepared,
        Some(worker_pid),
        None,
        None,
        None,
    ) {
        let _ = child.kill();
        let _ = child.wait();
        return Err(error);
    }
    drop(child);
    cleanup_guard.disarm();
    Ok(())
}

#[cfg(windows)]
fn run_full_elevated_worker(
    config: &FileUpdateHelperConfig,
    plan_path: &Path,
) -> Result<(), FileUpdateCommandError> {
    let plan = validate_protected_plan(config, plan_path)?;
    let protected_root = plan_path
        .parent()
        .ok_or_else(|| FileUpdateCommandError::from("protected update plan has no parent"))?;
    let result_path = protected_root.join(PROTECTED_RESULT_FILE);

    let result = run_full_elevated_worker_inner(config, &plan, protected_root, &result_path);
    if let Err(error) = &result {
        record_protected_failure(&plan, &result_path, &error.message);
    }
    result
}

#[cfg(windows)]
fn run_full_elevated_worker_inner(
    config: &FileUpdateHelperConfig,
    plan: &ProtectedFullUpdatePlan,
    protected_root: &Path,
    result_path: &Path,
) -> Result<(), FileUpdateCommandError> {
    wait_for_process_exit(plan.bootstrap_pid, BOOTSTRAP_TIMEOUT)?;
    let own_digest = sha256_file(std::env::current_exe()?)?;
    if own_digest.sha256 != plan.source_executable_sha256 {
        return Err(FileUpdateCommandError::from(
            "protected full update worker hash does not match the source application",
        ));
    }
    verify_protected_copy(
        &plan.protected_installer_path,
        plan.installer_size,
        &plan.installer_sha256,
        config.updater_public_key,
        &plan.updater_signature,
    )?;
    let installed_digest = sha256_file(&plan.installed_executable_path)?;
    if installed_digest.sha256 != plan.source_executable_sha256 {
        return Err(FileUpdateCommandError::from(
            "installed executable changed before the full installer started",
        ));
    }

    write_protected_result(
        result_path,
        ProtectedResultState::Installing,
        Some(std::process::id()),
        None,
        None,
        None,
    )?;

    let mut installer = Command::new(&plan.protected_installer_path);
    installer
        .args(["/P", "/R", "/UPDATE", "/ARGS"])
        .current_dir(protected_root)
        .creation_flags(CREATE_NO_WINDOW);
    let mut installer = installer.spawn().map_err(|error| {
        FileUpdateCommandError::from(format!(
            "failed to start protected full update installer {}: {error}",
            plan.protected_installer_path.display()
        ))
    })?;
    let installer_pid = installer.id();
    write_protected_result(
        result_path,
        ProtectedResultState::Installing,
        Some(std::process::id()),
        Some(installer_pid),
        None,
        None,
    )?;

    let status = match wait_child_timeout(&mut installer, INSTALLER_TIMEOUT) {
        Ok(status) => status,
        Err(error) => {
            let _ = installer.kill();
            let _ = installer.wait();
            return Err(error);
        }
    };
    if !status.success() {
        return Err(FileUpdateCommandError::from(format!(
            "full update installer exited with code {}",
            status.code().unwrap_or(-1)
        )));
    }

    write_protected_result(
        result_path,
        ProtectedResultState::Completed,
        Some(std::process::id()),
        Some(installer_pid),
        status.code(),
        None,
    )?;
    let _ = fs::remove_file(&plan.protected_installer_path);
    make_protected_root_user_cleanable(protected_root)?;
    Ok(())
}

#[cfg(windows)]
fn record_protected_failure(plan: &ProtectedFullUpdatePlan, result_path: &Path, reason: &str) {
    let _ = write_protected_result(
        result_path,
        ProtectedResultState::Failed,
        Some(std::process::id()),
        None,
        None,
        Some(reason.to_string()),
    );
    let _ = fs::remove_file(&plan.protected_installer_path);
    if let Some(root) = result_path.parent() {
        let _ = make_protected_root_user_cleanable(root);
    }
}

#[cfg(windows)]
fn run_full_cleanup(
    config: &FileUpdateHelperConfig,
    transaction_path: &Path,
    supervisor_pid: u32,
    full: bool,
) -> Result<(), FileUpdateCommandError> {
    wait_for_process_exit(supervisor_pid, BOOTSTRAP_TIMEOUT)?;
    let cache_root = helper_cache_root(config)?;
    let lock = open_lock(&cache_root)?;
    lock.lock_exclusive()?;
    let transaction_path = validate_transaction_path(&cache_root, transaction_path)?;
    let transaction = read_transaction(&transaction_path)?;
    if transaction.application_id != config.application_id {
        return Err(FileUpdateCommandError::from(
            "full update cleanup transaction belongs to another application",
        ));
    }
    if full {
        if !same_version(config.current_version, &transaction.target_version)
            || transaction.state != FullUpdateState::Completed
        {
            return Err(FileUpdateCommandError::from(
                "full update cleanup requires the installed target version",
            ));
        }
        cleanup_protected_transaction_root(config, &transaction.transaction_id);
        remove_transaction_and_pointer(&cache_root, &transaction_path)?;
    } else {
        let helper_root = transaction_path
            .parent()
            .ok_or_else(|| FileUpdateCommandError::from("full update transaction has no parent"))?
            .join("helper");
        if helper_root.exists() {
            ensure_plain_directory(&helper_root)?;
            fs::remove_dir_all(helper_root)?;
        }
        cleanup_protected_transaction_root(config, &transaction.transaction_id);
    }
    Ok(())
}

#[cfg(windows)]
fn validate_protected_plan(
    config: &FileUpdateHelperConfig,
    plan_path: &Path,
) -> Result<ProtectedFullUpdatePlan, FileUpdateCommandError> {
    ensure_plain_file(plan_path)?;
    let plan = read_json::<ProtectedFullUpdatePlan>(plan_path)?;
    if plan.schema_version != PROTECTED_PLAN_SCHEMA_VERSION
        || plan.application_id != config.application_id
    {
        return Err(FileUpdateCommandError::from(
            "protected full update plan identity is invalid",
        ));
    }
    validate_version_upgrade(&plan.current_version, &plan.target_version)?;
    let expected_root = protected_transaction_root(config, &plan.transaction_id)?;
    let canonical_root = expected_root.canonicalize()?;
    let canonical_plan = plan_path.canonicalize()?;
    if canonical_plan.parent() != Some(canonical_root.as_path())
        || canonical_plan.file_name() != Some(OsStr::new(PROTECTED_PLAN_FILE))
    {
        return Err(FileUpdateCommandError::from(
            "protected full update plan is outside the administrator cache",
        ));
    }
    let protected_installer = plan.protected_installer_path.canonicalize()?;
    let protected_helper = plan.protected_helper_path.canonicalize()?;
    if protected_installer.parent() != Some(canonical_root.as_path())
        || protected_installer.file_name() != Some(OsStr::new(PROTECTED_INSTALLER_FILE))
        || protected_helper.parent() != Some(canonical_root.as_path())
        || protected_helper.file_name() != Some(OsStr::new(PROTECTED_HELPER_FILE))
    {
        return Err(FileUpdateCommandError::from(
            "protected full update payload is outside the administrator cache",
        ));
    }
    if std::env::current_exe()?.canonicalize()? != protected_helper {
        return Err(FileUpdateCommandError::from(
            "protected full update worker mode must run from the administrator cache",
        ));
    }
    let install_root = plan.install_root.canonicalize()?;
    let installed_executable = plan.installed_executable_path.canonicalize()?;
    validate_installed_executable(config, &install_root, &installed_executable)?;
    Ok(plan)
}

#[cfg(windows)]
fn verify_protected_copy(
    installer_path: &Path,
    expected_size: u64,
    expected_sha256: &str,
    updater_public_key: &str,
    updater_signature: &str,
) -> Result<(), FileUpdateCommandError> {
    ensure_plain_file(installer_path)?;
    ensure_windows_installer(installer_path)?;
    let digest = sha256_file(installer_path)?;
    if digest.size != expected_size || digest.sha256 != expected_sha256 {
        return Err(FileUpdateCommandError::from(
            "protected full update installer hash or size verification failed",
        ));
    }
    verify_updater_signature(installer_path, updater_public_key, updater_signature)?;
    Ok(())
}

#[cfg(windows)]
fn write_protected_result(
    result_path: &Path,
    state: ProtectedResultState,
    worker_pid: Option<u32>,
    installer_pid: Option<u32>,
    installer_exit_code: Option<i32>,
    message: Option<String>,
) -> Result<(), FileUpdateCommandError> {
    write_json_file_atomic(
        result_path,
        &ProtectedFullUpdateResult {
            state,
            worker_pid,
            installer_pid,
            installer_exit_code,
            updated_at_ms: now_millis(),
            message,
        },
    )?;
    Ok(())
}

#[cfg(windows)]
fn wait_for_protected_result(
    config: &FileUpdateHelperConfig,
    transaction_id: &str,
    timeout: Duration,
) -> Result<ProtectedFullUpdateResult, FileUpdateCommandError> {
    let result_path =
        protected_transaction_root(config, transaction_id)?.join(PROTECTED_RESULT_FILE);
    let deadline = std::time::Instant::now() + timeout;
    loop {
        if let Ok(result) = read_json::<ProtectedFullUpdateResult>(&result_path) {
            if matches!(
                result.state,
                ProtectedResultState::Completed | ProtectedResultState::Failed
            ) {
                wait_for_terminal_protected_processes(&result, BOOTSTRAP_TIMEOUT)?;
                return Ok(result);
            }
        }
        if std::time::Instant::now() >= deadline {
            return Err(FileUpdateCommandError::from(
                "timed out waiting for the full update installer",
            ));
        }
        thread::sleep(Duration::from_millis(250));
    }
}

#[cfg(windows)]
fn wait_for_terminal_protected_processes(
    result: &ProtectedFullUpdateResult,
    timeout: Duration,
) -> Result<(), FileUpdateCommandError> {
    let deadline = std::time::Instant::now() + timeout;
    for pid in [result.installer_pid, result.worker_pid]
        .into_iter()
        .flatten()
    {
        if !process_is_running(pid) {
            continue;
        }
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            return Err(FileUpdateCommandError::from(
                "timed out waiting for terminal full update processes",
            ));
        }
        wait_for_process_exit(pid, remaining)?;
    }
    Ok(())
}

#[cfg(windows)]
fn protected_transaction_root(
    config: &FileUpdateHelperConfig,
    transaction_id: &str,
) -> Result<PathBuf, FileUpdateCommandError> {
    validate_application_id(config.application_id)?;
    if transaction_id.len() != 64 || !transaction_id.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(FileUpdateCommandError::from(
            "full update transaction id is not a SHA-256 digest",
        ));
    }
    let program_data = std::env::var_os("PROGRAMDATA")
        .ok_or_else(|| FileUpdateCommandError::from("PROGRAMDATA is not available"))?;
    Ok(PathBuf::from(program_data)
        .join(config.application_id)
        .join("hdiff-update")
        .join(FULL_UPDATE_ROOT)
        .join("transactions")
        .join(transaction_id))
}

#[cfg(windows)]
fn prepare_protected_transaction_root(
    config: &FileUpdateHelperConfig,
    transaction_id: &str,
) -> Result<PathBuf, FileUpdateCommandError> {
    let transaction_root = protected_transaction_root(config, transaction_id)?;
    let program_data = PathBuf::from(
        std::env::var_os("PROGRAMDATA")
            .ok_or_else(|| FileUpdateCommandError::from("PROGRAMDATA is not available"))?,
    );
    let descriptor = SecurityDescriptor::from_sddl(
        "O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;GRGX;;;BU)",
    )?;
    let relative = transaction_root.strip_prefix(&program_data).map_err(|_| {
        FileUpdateCommandError::from("protected full update root is outside PROGRAMDATA")
    })?;
    let mut current = program_data;
    let component_count = relative.components().count();
    for (index, component) in relative.components().enumerate() {
        current.push(component.as_os_str());
        if index + 1 == component_count && current.exists() {
            remove_path_without_following(&current)?;
        }
        create_or_secure_directory(&current, &descriptor)?;
    }
    Ok(transaction_root)
}

#[cfg(windows)]
fn cleanup_protected_terminal_roots(config: &FileUpdateHelperConfig) {
    let Ok(program_data) = std::env::var("PROGRAMDATA") else {
        return;
    };
    let transactions_root = PathBuf::from(program_data)
        .join(config.application_id)
        .join("hdiff-update")
        .join(FULL_UPDATE_ROOT)
        .join("transactions");
    let Ok(entries) = fs::read_dir(&transactions_root) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let Ok(metadata) = fs::symlink_metadata(&path) else {
            continue;
        };
        if !metadata.is_dir() || metadata.file_type().is_symlink() || is_reparse_point(&metadata) {
            continue;
        }
        let result = read_json::<ProtectedFullUpdateResult>(&path.join(PROTECTED_RESULT_FILE));
        let Ok(result) = result else {
            continue;
        };
        if !matches!(
            result.state,
            ProtectedResultState::Completed | ProtectedResultState::Failed
        ) || result.worker_pid.is_some_and(process_is_running)
            || result.installer_pid.is_some_and(process_is_running)
        {
            continue;
        }
        let _ = fs::remove_dir_all(path);
    }
}

#[cfg(not(windows))]
fn cleanup_protected_terminal_roots(_config: &FileUpdateHelperConfig) {}

#[cfg(windows)]
fn cleanup_protected_transaction_root(config: &FileUpdateHelperConfig, transaction_id: &str) {
    let Ok(root) = protected_transaction_root(config, transaction_id) else {
        return;
    };
    if let Ok(result) = read_json::<ProtectedFullUpdateResult>(&root.join(PROTECTED_RESULT_FILE)) {
        if result.worker_pid.is_some_and(process_is_running)
            || result.installer_pid.is_some_and(process_is_running)
        {
            return;
        }
    }
    let _ = fs::remove_dir_all(root);
}

#[cfg(windows)]
fn make_protected_root_user_cleanable(root: &Path) -> Result<(), FileUpdateCommandError> {
    let descriptor = SecurityDescriptor::from_sddl(
        "O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;BU)",
    )?;
    apply_security_descriptor(root, &descriptor)
}

#[cfg(windows)]
struct ProtectedRootCleanupGuard {
    path: PathBuf,
    armed: bool,
}

#[cfg(windows)]
impl ProtectedRootCleanupGuard {
    fn new(path: PathBuf) -> Self {
        Self { path, armed: true }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

#[cfg(windows)]
impl Drop for ProtectedRootCleanupGuard {
    fn drop(&mut self) {
        if self.armed && self.path.exists() {
            let _ = remove_path_without_following(&self.path);
        }
    }
}

#[cfg(windows)]
struct SecurityDescriptor(PSECURITY_DESCRIPTOR);

#[cfg(windows)]
impl SecurityDescriptor {
    fn from_sddl(sddl: &str) -> Result<Self, FileUpdateCommandError> {
        let sddl = wide_null(OsStr::new(sddl))?;
        let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
        if unsafe {
            ConvertStringSecurityDescriptorToSecurityDescriptorW(
                sddl.as_ptr(),
                SDDL_REVISION_1,
                &mut descriptor,
                std::ptr::null_mut(),
            )
        } == 0
        {
            return Err(FileUpdateCommandError::from(format!(
                "failed to create protected directory security descriptor: {}",
                std::io::Error::last_os_error()
            )));
        }
        Ok(Self(descriptor))
    }
}

#[cfg(windows)]
impl Drop for SecurityDescriptor {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                LocalFree(self.0.cast::<c_void>());
            }
        }
    }
}

#[cfg(windows)]
fn create_or_secure_directory(
    path: &Path,
    descriptor: &SecurityDescriptor,
) -> Result<(), FileUpdateCommandError> {
    if path.exists() {
        let metadata = fs::symlink_metadata(path)?;
        if metadata.file_type().is_symlink() || is_reparse_point(&metadata) {
            remove_path_without_following(path)?;
        } else if !metadata.is_dir() {
            return Err(FileUpdateCommandError::from(format!(
                "protected update path is not a directory: {}",
                path.display()
            )));
        }
    }
    if !path.exists() {
        let wide_path = wide_null(path.as_os_str())?;
        let attributes = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: descriptor.0,
            bInheritHandle: 0,
        };
        if unsafe { CreateDirectoryW(wide_path.as_ptr(), &attributes) } == 0 {
            let error = std::io::Error::last_os_error();
            if error.raw_os_error() != Some(ERROR_ALREADY_EXISTS as i32) {
                return Err(FileUpdateCommandError::from(format!(
                    "failed to create protected update directory {}: {error}",
                    path.display()
                )));
            }
        }
    }
    ensure_plain_directory(path)?;
    apply_security_descriptor(path, descriptor)
}

#[cfg(windows)]
fn apply_security_descriptor(
    path: &Path,
    descriptor: &SecurityDescriptor,
) -> Result<(), FileUpdateCommandError> {
    let path = wide_null(path.as_os_str())?;
    let information = OWNER_SECURITY_INFORMATION
        | GROUP_SECURITY_INFORMATION
        | DACL_SECURITY_INFORMATION
        | PROTECTED_DACL_SECURITY_INFORMATION;
    if unsafe { SetFileSecurityW(path.as_ptr(), information, descriptor.0) } == 0 {
        return Err(FileUpdateCommandError::from(format!(
            "failed to secure protected update directory: {}",
            std::io::Error::last_os_error()
        )));
    }
    Ok(())
}

#[cfg(windows)]
fn remove_path_without_following(path: &Path) -> Result<(), FileUpdateCommandError> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || is_reparse_point(&metadata) {
        if metadata.is_dir() {
            fs::remove_dir(path)?;
        } else {
            fs::remove_file(path)?;
        }
        return Ok(());
    }
    if metadata.is_dir() {
        ensure_plain_tree(path)?;
        fs::remove_dir_all(path)?;
    } else if metadata.is_file() {
        fs::remove_file(path)?;
    } else {
        return Err(FileUpdateCommandError::from(format!(
            "unsupported protected update path type: {}",
            path.display()
        )));
    }
    Ok(())
}

#[cfg(windows)]
fn ensure_plain_tree(root: &Path) -> Result<(), FileUpdateCommandError> {
    ensure_plain_directory(root)?;
    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path)?;
        if metadata.file_type().is_symlink() || is_reparse_point(&metadata) {
            return Err(FileUpdateCommandError::from(format!(
                "protected update tree contains a reparse point: {}",
                path.display()
            )));
        }
        if metadata.is_dir() {
            ensure_plain_tree(&path)?;
        } else if !metadata.is_file() {
            return Err(FileUpdateCommandError::from(format!(
                "protected update tree contains an unsupported entry: {}",
                path.display()
            )));
        }
    }
    Ok(())
}

#[cfg(windows)]
fn copy_file_synced(source: &Path, destination: &Path) -> Result<(), FileUpdateCommandError> {
    ensure_plain_file(source)?;
    if destination.exists() {
        ensure_plain_file(destination)?;
        fs::remove_file(destination)?;
    }
    fs::copy(source, destination)?;
    fs::OpenOptions::new()
        .write(true)
        .open(destination)?
        .sync_all()?;
    ensure_plain_file(destination)?;
    Ok(())
}

#[cfg(windows)]
struct ElevatedProcess {
    handle: HANDLE,
    pid: u32,
}

#[cfg(windows)]
fn shell_execute_elevated(
    executable: &Path,
    parameters: &str,
) -> Result<ElevatedProcess, FileUpdateCommandError> {
    let verb = wide_null(OsStr::new("runas"))?;
    let executable_wide = wide_null(executable.as_os_str())?;
    let parameters = wide_null(OsStr::new(parameters))?;
    let directory = executable
        .parent()
        .map(|path| wide_null(path.as_os_str()))
        .transpose()?;
    let mut execute_info = SHELLEXECUTEINFOW {
        cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
        fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC,
        lpVerb: verb.as_ptr(),
        lpFile: executable_wide.as_ptr(),
        lpParameters: parameters.as_ptr(),
        lpDirectory: directory
            .as_ref()
            .map_or(std::ptr::null(), |value| value.as_ptr()),
        nShow: SW_SHOWNORMAL,
        ..Default::default()
    };
    if unsafe { ShellExecuteExW(&mut execute_info) } == 0 {
        let error = std::io::Error::last_os_error();
        if error.raw_os_error() == Some(ERROR_CANCELLED as i32) {
            return Err(FileUpdateCommandError::from(
                "administrator permission was declined",
            ));
        }
        if error.raw_os_error() == Some(ERROR_ELEVATION_REQUIRED as i32) {
            return Err(FileUpdateCommandError::from(
                "administrator permission is required",
            ));
        }
        return Err(FileUpdateCommandError::from(format!(
            "failed to start elevated full update bootstrap: {error}"
        )));
    }
    if execute_info.hProcess.is_null() {
        return Err(FileUpdateCommandError::from(
            "elevated full update bootstrap started without a process handle",
        ));
    }
    let pid = unsafe { GetProcessId(execute_info.hProcess) };
    if pid == 0 {
        unsafe {
            CloseHandle(execute_info.hProcess);
        }
        return Err(FileUpdateCommandError::from(
            "elevated full update bootstrap started without a process id",
        ));
    }
    Ok(ElevatedProcess {
        handle: execute_info.hProcess,
        pid,
    })
}

#[cfg(windows)]
fn wait_process_handle(handle: HANDLE, timeout: Duration) -> Result<u32, FileUpdateCommandError> {
    let timeout_ms = timeout.as_millis().min(u32::MAX as u128) as u32;
    let wait = unsafe { WaitForSingleObject(handle, timeout_ms) };
    if wait != WAIT_OBJECT_0 {
        unsafe {
            CloseHandle(handle);
        }
        if wait == WAIT_TIMEOUT {
            return Err(FileUpdateCommandError::from(
                "timed out waiting for elevated full update bootstrap",
            ));
        }
        return Err(FileUpdateCommandError::from(format!(
            "waiting for elevated full update bootstrap failed with code {wait}"
        )));
    }
    let mut exit_code = 0_u32;
    if unsafe { GetExitCodeProcess(handle, &mut exit_code) } == 0 {
        let error = std::io::Error::last_os_error();
        unsafe {
            CloseHandle(handle);
        }
        return Err(FileUpdateCommandError::from(format!(
            "failed to read elevated full update bootstrap exit code: {error}"
        )));
    }
    unsafe {
        CloseHandle(handle);
    }
    Ok(exit_code)
}

#[cfg(windows)]
fn wait_for_process_exit(pid: u32, timeout: Duration) -> Result<(), FileUpdateCommandError> {
    let process = unsafe { OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
    if process.is_null() {
        return Ok(());
    }
    let timeout_ms = timeout.as_millis().min(u32::MAX as u128) as u32;
    let result = unsafe { WaitForSingleObject(process, timeout_ms) };
    unsafe {
        CloseHandle(process);
    }
    if result == WAIT_OBJECT_0 {
        Ok(())
    } else if result == WAIT_TIMEOUT {
        Err(FileUpdateCommandError::from(format!(
            "process {pid} did not exit within {} seconds",
            timeout.as_secs()
        )))
    } else {
        Err(FileUpdateCommandError::from(format!(
            "waiting for process {pid} failed with code {result}"
        )))
    }
}

#[cfg(windows)]
fn wait_child_timeout(
    child: &mut Child,
    timeout: Duration,
) -> Result<std::process::ExitStatus, FileUpdateCommandError> {
    let deadline = std::time::Instant::now() + timeout;
    loop {
        if let Some(status) = child.try_wait()? {
            return Ok(status);
        }
        if std::time::Instant::now() >= deadline {
            return Err(FileUpdateCommandError::from(
                "full update installer did not exit before the timeout",
            ));
        }
        thread::sleep(Duration::from_millis(250));
    }
}

#[cfg(windows)]
fn launch_installed_application(
    config: &FileUpdateHelperConfig,
    install_root: &Path,
) -> Result<Child, FileUpdateCommandError> {
    let executable = install_root.join(config.main_executable);
    let mut command = Command::new(&executable);
    command
        .current_dir(install_root)
        .creation_flags(CREATE_NO_WINDOW);
    command.spawn().map_err(|error| {
        FileUpdateCommandError::from(format!(
            "failed to restart installed application {}: {error}",
            executable.display()
        ))
    })
}

#[cfg(windows)]
fn spawn_cleanup_helper(
    config: &FileUpdateHelperConfig,
    install_root: &Path,
    transaction_path: &Path,
    supervisor_pid: u32,
    full: bool,
) -> Result<u32, FileUpdateCommandError> {
    let executable = install_root.join(config.main_executable);
    let mut command = Command::new(&executable);
    command
        .arg(FULL_CLEANUP_ARGUMENT)
        .arg(transaction_path)
        .arg(supervisor_pid.to_string())
        .arg(if full { CLEANUP_FULL } else { CLEANUP_HELPER })
        .current_dir(install_root)
        .creation_flags(CREATE_NO_WINDOW);
    let child = command.spawn().map_err(|error| {
        FileUpdateCommandError::from(format!(
            "failed to start full update cleanup helper {}: {error}",
            executable.display()
        ))
    })?;
    let pid = child.id();
    drop(child);
    Ok(pid)
}

#[cfg(windows)]
fn process_is_running(pid: u32) -> bool {
    let process = unsafe { OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
    if process.is_null() {
        return false;
    }
    let wait = unsafe { WaitForSingleObject(process, 0) };
    unsafe {
        CloseHandle(process);
    }
    wait == WAIT_TIMEOUT
}

#[cfg(not(windows))]
fn process_is_running(_pid: u32) -> bool {
    false
}

#[cfg(windows)]
fn wide_null(value: &OsStr) -> std::io::Result<Vec<u16>> {
    let mut wide = Vec::new();
    for unit in value.encode_wide() {
        if unit == 0 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "value contains an embedded null character",
            ));
        }
        wide.push(unit);
    }
    wide.push(0);
    Ok(wide)
}

#[cfg(windows)]
fn windows_command_line(args: &[String]) -> String {
    args.iter()
        .map(|argument| quote_windows_argument(argument))
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(windows)]
fn quote_windows_argument(argument: &str) -> String {
    if !argument.is_empty()
        && !argument
            .chars()
            .any(|character| matches!(character, ' ' | '\t' | '"'))
    {
        return argument.to_owned();
    }
    let mut quoted = String::with_capacity(argument.len() + 2);
    quoted.push('"');
    let mut backslashes = 0usize;
    for character in argument.chars() {
        match character {
            '\\' => backslashes += 1,
            '"' => {
                quoted.extend(std::iter::repeat('\\').take(backslashes * 2 + 1));
                quoted.push('"');
                backslashes = 0;
            }
            _ => {
                quoted.extend(std::iter::repeat('\\').take(backslashes));
                quoted.push(character);
                backslashes = 0;
            }
        }
    }
    quoted.extend(std::iter::repeat('\\').take(backslashes * 2));
    quoted.push('"');
    quoted
}

#[cfg(test)]
mod tests {
    use std::fs;

    use base64::Engine;

    use super::{
        full_transaction_id, is_locally_collectable, release_identity_matches,
        resolve_tauri_update_artifact, same_version, validate_application_id,
        validate_version_upgrade, verify_updater_signature, FullUpdateState, TauriUpdateManifest,
    };

    #[test]
    fn full_transaction_id_binds_url_and_signature() {
        let first = full_transaction_id(
            "app",
            "1.0.0",
            "1.1.0",
            "https://example/app.exe",
            "signature-a",
        );
        let same = full_transaction_id(
            "app",
            "1.0.0",
            "1.1.0",
            "https://example/app.exe",
            "signature-a",
        );
        let different_url = full_transaction_id(
            "app",
            "1.0.0",
            "1.1.0",
            "https://example/republished.exe",
            "signature-a",
        );
        let different_signature = full_transaction_id(
            "app",
            "1.0.0",
            "1.1.0",
            "https://example/app.exe",
            "signature-b",
        );
        assert_eq!(first, same);
        assert_ne!(first, different_url);
        assert_ne!(first, different_signature);
        assert_eq!(first.len(), 64);
    }

    #[test]
    fn reusable_full_update_requires_exact_version_url_and_signature() {
        assert!(release_identity_matches(
            "v1.1.0",
            "https://example.test/app.exe",
            "signature-a",
            "1.1.0",
            "https://example.test/app.exe",
            "signature-a",
        ));
        assert!(!release_identity_matches(
            "1.1.0",
            "https://example.test/app.exe",
            "signature-a",
            "1.1.0",
            "https://example.test/app.exe?republished=1",
            "signature-a",
        ));
        assert!(!release_identity_matches(
            "1.1.0",
            "https://example.test/app.exe",
            "signature-a",
            "1.1.0",
            "https://example.test/app.exe",
            "signature-b",
        ));
    }

    #[test]
    fn cache_collection_keeps_ready_and_active_transactions() {
        assert!(is_locally_collectable(FullUpdateState::Preparing));
        assert!(is_locally_collectable(FullUpdateState::Completed));
        assert!(is_locally_collectable(FullUpdateState::Failed));
        assert!(!is_locally_collectable(FullUpdateState::Ready));
        assert!(!is_locally_collectable(FullUpdateState::SupervisorStarted));
        assert!(!is_locally_collectable(FullUpdateState::Elevating));
        assert!(!is_locally_collectable(FullUpdateState::Installing));
    }

    #[test]
    fn version_comparison_accepts_v_prefix_and_rejects_non_upgrade() {
        assert!(same_version("v1.2.3", "1.2.3"));
        assert!(validate_version_upgrade("1.2.3", "1.2.4").is_ok());
        assert!(validate_version_upgrade("1.2.3", "1.2.3").is_err());
        assert!(validate_version_upgrade("1.2.3", "1.2.2").is_err());
    }

    #[test]
    fn application_id_is_safe_as_a_program_data_component() {
        assert!(validate_application_id("ai.xcodex.citizenl").is_ok());
        assert!(validate_application_id("../other").is_err());
        assert!(validate_application_id("app\\other").is_err());
        assert!(validate_application_id("").is_err());
    }

    #[test]
    fn resolves_dynamic_tauri_update_artifact() {
        let manifest: TauriUpdateManifest = serde_json::from_value(serde_json::json!({
            "version": "1.2.4",
            "url": "https://example.test/app.exe",
            "signature": "signature"
        }))
        .unwrap();
        let artifact = resolve_tauri_update_artifact(manifest).unwrap();
        assert_eq!(artifact.url, "https://example.test/app.exe");
        assert_eq!(artifact.signature, "signature");
    }

    #[test]
    fn verifies_tauri_wrapped_prehashed_minisign_signature_from_disk() {
        let directory = tempfile::tempdir().unwrap();
        let installer = directory.path().join("installer.exe");
        fs::write(&installer, b"test").unwrap();
        let public_key = "untrusted comment: minisign public key E7620F1842B4E81F\nRWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3";
        let signature = "untrusted comment: signature from minisign secret key\nRUQf6LRCGA9i559r3g7V1qNyJDApGip8MfqcadIgT9CuhV3EMhHoN1mGTkUidF/z7SrlQgXdy8ofjb7bNJJylDOocrCo8KLzZwo=\ntrusted comment: timestamp:1556193335\tfile:test\ny/rUw2y8/hOUYjZU71eHp/Wo1KZ40fGy2VJEDl34XMJM+TX48Ss/17u3IvIfbVR1FkZZSNCisQbuQY+bHwhEBg==";
        let public_key = base64::engine::general_purpose::STANDARD.encode(public_key);
        let signature = base64::engine::general_purpose::STANDARD.encode(signature);

        verify_updater_signature(&installer, &public_key, &signature).unwrap();
    }

    #[cfg(windows)]
    #[test]
    fn helper_dispatch_requires_an_explicit_full_update_mode() {
        use std::ffi::OsString;

        use super::{parse_full_helper_invocation, FullHelperInvocation, FULL_SUPERVISOR_ARGUMENT};

        assert!(parse_full_helper_invocation(&[OsString::from("app.exe")])
            .unwrap()
            .is_none());
        assert!(parse_full_helper_invocation(&[
            OsString::from("app.exe"),
            OsString::from("--embedded-terminal-broker"),
        ])
        .unwrap()
        .is_none());
        let invocation = parse_full_helper_invocation(&[
            OsString::from("app.exe"),
            OsString::from(FULL_SUPERVISOR_ARGUMENT),
            OsString::from("C:\\cache\\transaction.json"),
            OsString::from("42"),
        ])
        .unwrap();
        assert_eq!(
            invocation,
            Some(FullHelperInvocation::Supervisor {
                transaction_path: "C:\\cache\\transaction.json".into(),
                parent_pid: 42,
            })
        );
    }

    #[cfg(windows)]
    #[test]
    fn quotes_elevated_bootstrap_arguments() {
        use super::{windows_command_line, FULL_ELEVATED_BOOTSTRAP_ARGUMENT};

        assert_eq!(
            windows_command_line(&[
                FULL_ELEVATED_BOOTSTRAP_ARGUMENT.to_string(),
                "C:\\Program Data\\transaction.json".to_string(),
            ]),
            "--hdiff-full-update-elevated-bootstrap \"C:\\Program Data\\transaction.json\""
        );
    }
}