iroh-ssh 0.2.10

ssh without ip
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
name: Build cross-platform artifacts

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
    types: [opened, synchronize, reopened]

jobs:
  build:
    name: Build ${{ matrix.platform.name }}
    runs-on: ${{ matrix.platform.runs-on }}
    strategy:
      fail-fast: false
      matrix:
        platform:
          - name: Linux x86_64 (musl)
            runs-on: ubuntu-latest
            target: x86_64-unknown-linux-musl
            ext: ""
          - name: Windows x86_64 (MSVC)
            runs-on: windows-latest
            target: x86_64-pc-windows-msvc
            ext: ".exe"
          - name: macOS x86_64
            runs-on: macos-latest
            target: x86_64-apple-darwin
            ext: ""

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Cache Rust build artifacts
        uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.platform.target }}

      - name: Build with cross
        uses: houseabsolute/actions-rust-cross@v1
        with:
          command: build
          target: ${{ matrix.platform.target }}
          args: --locked --release
          strip: true

      - name: Prepare binary
        shell: bash
        run: |
          set -euo pipefail
          BIN_NAME="iroh-ssh"
          TARGET="${{ matrix.platform.target }}"
          EXT="${{ matrix.platform.ext }}"
          
          OUT_EXT="${EXT}"
          if [ -z "${OUT_EXT}" ]; then
            if [[ "${TARGET}" == *"linux"* ]]; then
              OUT_EXT=".linux"
            elif [[ "${TARGET}" == *"apple-darwin"* ]]; then
              OUT_EXT=".macos"
            else
              OUT_EXT=""
            fi
          fi

          SRC="target/${TARGET}/release/${BIN_NAME}${EXT}"
          OUTDIR="dist/${TARGET}"
          mkdir -p "${OUTDIR}"
          if [ ! -f "${SRC}" ]; then
            echo "Built binary not found: ${SRC}"
            exit 1
          fi
          cp "${SRC}" "${OUTDIR}/${BIN_NAME}${OUT_EXT}"
          chmod +x "${OUTDIR}/${BIN_NAME}${OUT_EXT}" || true
          echo "Resulting files:"
          ls -la "${OUTDIR}"

      - name: Upload binary artifact
        uses: actions/upload-artifact@v6
        with:
          name: iroh-ssh-${{ matrix.platform.target }}
          path: dist/${{ matrix.platform.target }}/*
          retention-days: 2

  test:
    name: Test ${{ matrix.platform.name }}
    needs: build
    if: ${{ success() }}
    runs-on: ${{ matrix.platform.runs-on }}
    strategy:
      fail-fast: false
      matrix:
        platform:
          - name: Linux x86_64 (musl)
            runs-on: ubuntu-latest
            target: x86_64-unknown-linux-musl
            ext: ".linux"
          - name: Windows x86_64 (MSVC)
            runs-on: windows-latest
            target: x86_64-pc-windows-msvc
            ext: ".exe"
          - name: macOS x86_64
            runs-on: macos-latest
            target: x86_64-apple-darwin
            ext: ".macos"

    steps:
      - name: Download binary artifact
        uses: actions/download-artifact@v8
        with:
          name: iroh-ssh-${{ matrix.platform.target }}
          path: dist/${{ matrix.platform.target }}

      - name: Setup SSH Server (Linux)
        if: runner.os == 'Linux'
        shell: bash
        run: |
          sudo apt-get update
          sudo apt-get install -y openssh-server
          sudo systemctl start ssh
          sudo systemctl status ssh

      - name: Setup SSH Server (macOS)
        if: runner.os == 'macOS'
        shell: bash
        run: |
          sudo systemsetup -setremotelogin on
          sleep 2

      - name: Setup SSH Server (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
          Start-Service sshd
          Set-Service -Name sshd -StartupType 'Automatic'
          Get-Service sshd

      - name: Set execute permissions (Linux/macOS)
        if: runner.os != 'Windows'
        shell: bash
        run: |
          chmod +x dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}

      - name: Run integration test (Linux/macOS)
        if: runner.os != 'Windows'
        shell: bash
        timeout-minutes: 5
        run: |
          set -euo pipefail
          
          BIN_PATH="dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}"
          
          echo "Starting iroh-ssh server..."
          "$BIN_PATH" server --persist > server_output.txt 2>&1 &
          SERVER_PID=$!
          
          echo "Waiting for server to be ready..."
          for i in {1..30}; do
            if grep -q 'iroh-ssh.*@[a-f0-9]' server_output.txt 2>/dev/null; then
              echo "Server is ready"
              break
            fi
            if ! kill -0 $SERVER_PID 2>/dev/null; then
              echo "ERROR: Server process died"
              cat server_output.txt
              exit 1
            fi
            sleep 1
          done
          
          cat server_output.txt
          
          CONNECTION_STRING=$(grep 'iroh-ssh' server_output.txt | grep -v 'client ->' | awk '{print $2}' | head -1 || true)
          
          if [ -z "$CONNECTION_STRING" ]; then
            echo "ERROR: Could not extract connection string from server output"
            cat server_output.txt
            kill $SERVER_PID || true
            exit 1
          fi
          
          echo "Connection string: $CONNECTION_STRING"
          
          echo "Attempting to connect..."
          set +e
          if command -v timeout > /dev/null; then
            timeout 10s "$BIN_PATH" -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" -o "BatchMode=yes" "$CONNECTION_STRING" echo "test" 2>&1 | tee connect_output.txt
            EXIT_CODE=$?
          else
            (sleep 10; kill $$ 2>/dev/null) &
            TIMEOUT_PID=$!
            "$BIN_PATH" -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" -o "BatchMode=yes" "$CONNECTION_STRING" echo "test" 2>&1 | tee connect_output.txt
            EXIT_CODE=$?
            kill $TIMEOUT_PID 2>/dev/null || true
          fi
          set -e
          
          if grep -q "Permanently added" connect_output.txt; then
            echo "SUCCESS: Connection reached SSH host (host key exchanged)"
            kill $SERVER_PID || true
            exit 0
          else
            echo "FAILURE: Could not establish connection"
            cat connect_output.txt
            kill $SERVER_PID || true
            exit 1
          fi

      - name: Run exit code propagation test (Linux/macOS)
        if: runner.os != 'Windows'
        shell: bash
        timeout-minutes: 10
        run: |
          set -euo pipefail

          BIN_PATH="dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}"
          TEST_KEY_DIR="$(mktemp -d)"
          TEST_KEY="$TEST_KEY_DIR/id_ed25519"

          cleanup() {
            if [ -n "${SERVER_PID:-}" ]; then
              kill "$SERVER_PID" 2>/dev/null || true
              wait "$SERVER_PID" 2>/dev/null || true
            fi
            rm -rf "$TEST_KEY_DIR"
          }

          trap cleanup EXIT

          mkdir -p "$HOME/.ssh"
          chmod 700 "$HOME/.ssh"
          ssh-keygen -q -t ed25519 -N "" -f "$TEST_KEY"
          cat "$TEST_KEY.pub" >> "$HOME/.ssh/authorized_keys"
          chmod 600 "$HOME/.ssh/authorized_keys"

          echo "Starting iroh-ssh server for exit code tests..."
          "$BIN_PATH" server --persist > exit_server_output.txt 2>&1 &
          SERVER_PID=$!

          echo "Waiting for server to be ready..."
          for i in {1..30}; do
            if grep -q 'iroh-ssh.*@[a-f0-9]' exit_server_output.txt 2>/dev/null; then
              echo "Server is ready"
              break
            fi
            if ! kill -0 "$SERVER_PID" 2>/dev/null; then
              echo "ERROR: Server process died"
              cat exit_server_output.txt
              exit 1
            fi
            sleep 1
          done

          cat exit_server_output.txt

          CONNECTION_STRING=$(grep 'iroh-ssh' exit_server_output.txt | grep -v 'client ->' | awk '{print $2}' | head -1 || true)

          if [ -z "$CONNECTION_STRING" ]; then
            echo "ERROR: Could not extract connection string from server output"
            cat exit_server_output.txt
            exit 1
          fi

          CURRENT_USER="$(id -un)"
          ENDPOINT_HOST="${CONNECTION_STRING#*@}"
          SSH_CONFIG_FILE="$HOME/.ssh/config"

          cat >> "$SSH_CONFIG_FILE" <<EOF

          Host iroh-endpoint-config
            HostName $ENDPOINT_HOST

          Host iroh-localhost-config
            HostName localhost
            User $CURRENT_USER
          EOF
          chmod 600 "$SSH_CONFIG_FILE"

          run_success_case() {
            local name="$1"
            local expected_text="$2"
            shift 2

            local output_file="${name}_output.txt"
            local actual_exit

            echo "Running ${name}..."
            set +e
            if command -v timeout > /dev/null; then
              timeout 60s "$@" > "$output_file" 2>&1
              actual_exit=$?
            else
              "$@" > "$output_file" 2>&1 &
              local cmd_pid=$!
              (
                sleep 60
                kill "$cmd_pid" 2>/dev/null || true
              ) &
              local watchdog_pid=$!
              wait "$cmd_pid"
              actual_exit=$?
              kill "$watchdog_pid" 2>/dev/null || true
              wait "$watchdog_pid" 2>/dev/null || true
            fi
            set -e

            cat "$output_file"

            if [ "$actual_exit" -ne 0 ]; then
              echo "ERROR: ${name} expected exit 0, got ${actual_exit}"
              exit 1
            fi

            if ! grep -q "$expected_text" "$output_file"; then
              echo "ERROR: ${name} missing expected output '${expected_text}'"
              exit 1
            fi

            echo "SUCCESS: ${name}"
          }

          run_case() {
            local name="$1"
            local expected_exit="$2"
            shift 2

            local output_file="${name}_output.txt"
            local actual_exit

            echo "Running ${name}..."
            set +e
            if command -v timeout > /dev/null; then
              timeout 60s "$@" > "$output_file" 2>&1
              actual_exit=$?
            else
              "$@" > "$output_file" 2>&1 &
              local cmd_pid=$!
              (
                sleep 60
                kill "$cmd_pid" 2>/dev/null || true
              ) &
              local watchdog_pid=$!
              wait "$cmd_pid"
              actual_exit=$?
              kill "$watchdog_pid" 2>/dev/null || true
              wait "$watchdog_pid" 2>/dev/null || true
            fi
            set -e

            cat "$output_file"

            if [ "$actual_exit" -ne "$expected_exit" ]; then
              echo "ERROR: ${name} expected exit ${expected_exit}, got ${actual_exit}"
              exit 1
            fi

            echo "SUCCESS: ${name} exited with ${actual_exit}"
          }

          COMMON_SSH_ARGS=(
            -i "$TEST_KEY"
            -o "StrictHostKeyChecking=no"
            -o "UserKnownHostsFile=/dev/null"
            -o "BatchMode=yes"
          )

          run_success_case inline-endpoint-id inline-endpoint-id "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$CONNECTION_STRING" "printf inline-endpoint-id"
          run_success_case inline-localhost inline-localhost "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$CURRENT_USER@localhost" "printf inline-localhost"
          run_success_case inline-loopback-ip inline-loopback-ip "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$CURRENT_USER@127.0.0.1" "printf inline-loopback-ip"
          run_success_case config-endpoint-explicit-user config-endpoint-explicit-user "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$CURRENT_USER@iroh-endpoint-config" "printf config-endpoint-explicit-user"
          run_success_case config-localhost-config-user config-localhost-config-user "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "iroh-localhost-config" "printf config-localhost-config-user"

          run_case normal-exit-0 0 "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$CONNECTION_STRING" "sh -c 'exit 0'"
          run_case custom-exit-197 197 "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$CONNECTION_STRING" "sh -c 'exit 197'"

          REMOTE_TERMINATE_COMMAND="sh -c 'kill -TERM \$\$'"
          PROXY_COMMAND="$BIN_PATH proxy %h"
          BASELINE_OUTPUT_FILE="remote-sigterm-baseline-output.txt"

          echo "Running remote-sigterm baseline with stock ssh..."
          set +e
          if command -v timeout > /dev/null; then
            timeout 15s ssh \
              -i "$TEST_KEY" \
              -o "StrictHostKeyChecking=no" \
              -o "UserKnownHostsFile=/dev/null" \
              -o "BatchMode=yes" \
              -o "ProxyCommand=$PROXY_COMMAND" \
              "$CONNECTION_STRING" \
              "$REMOTE_TERMINATE_COMMAND" > "$BASELINE_OUTPUT_FILE" 2>&1
            BASELINE_EXIT=$?
          else
            ssh \
              -i "$TEST_KEY" \
              -o "StrictHostKeyChecking=no" \
              -o "UserKnownHostsFile=/dev/null" \
              -o "BatchMode=yes" \
              -o "ProxyCommand=$PROXY_COMMAND" \
              "$CONNECTION_STRING" \
              "$REMOTE_TERMINATE_COMMAND" > "$BASELINE_OUTPUT_FILE" 2>&1 &
            baseline_pid=$!
            (
              sleep 15
              kill "$baseline_pid" 2>/dev/null || true
            ) &
            watchdog_pid=$!
            wait "$baseline_pid"
            BASELINE_EXIT=$?
            kill "$watchdog_pid" 2>/dev/null || true
            wait "$watchdog_pid" 2>/dev/null || true
          fi
          set -e

          cat "$BASELINE_OUTPUT_FILE"
          echo "Stock ssh baseline exit: $BASELINE_EXIT"

          if [ "$BASELINE_EXIT" -eq 0 ]; then
            echo "ERROR: Stock ssh returned 0 for forced remote termination"
            exit 1
          fi

          run_case remote-sigterm "$BASELINE_EXIT" "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$CONNECTION_STRING" "$REMOTE_TERMINATE_COMMAND"

      - name: Run integration test (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        timeout-minutes: 5
        run: |
          $ErrorActionPreference = "Continue"
          
          $BinPath = "dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}"
          
          Write-Host "Starting iroh-ssh server..."
          $ServerJob = Start-Job -ScriptBlock {
            param($Path)
            & $Path server --persist
          } -ArgumentList (Resolve-Path $BinPath).Path
          
          Start-Sleep -Seconds 5
          
          $ServerOutput = Receive-Job -Job $ServerJob
          Write-Host "Server output:"
          Write-Host $ServerOutput
          
          $ConnectionMatch = ($ServerOutput | Select-String -Pattern 'iroh-ssh ([^@]+@[a-f0-9]{64})').Matches
          if ($ConnectionMatch.Count -eq 0) {
            Write-Host "ERROR: Could not extract connection string"
            Stop-Job -Job $ServerJob
            Remove-Job -Job $ServerJob
            exit 1
          }
          
          $ConnectionString = $ConnectionMatch[0].Groups[1].Value
          Write-Host "Connection string: $ConnectionString"
          
          Write-Host "Attempting to connect..."
          $ConnectOutput = & $BinPath -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=NUL" -o "BatchMode=yes" $ConnectionString "echo test" 2>&1 | Out-String
          $ExitCode = $LASTEXITCODE
          
          Write-Host "Connect output:"
          Write-Host $ConnectOutput
          
          if ($ConnectOutput -match "Permanently added") {
            Write-Host "SUCCESS: Connection reached SSH host (host key exchanged)"
            Stop-Job -Job $ServerJob
            Remove-Job -Job $ServerJob
            exit 0
          }
          else {
            Write-Host "FAILURE: Could not establish connection"
            Stop-Job -Job $ServerJob
            Remove-Job -Job $ServerJob
            exit 1
          }

      - name: Run exit code propagation test (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        timeout-minutes: 10
        run: |
          $ErrorActionPreference = "Stop"

          $BinPath = (Resolve-Path "dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}").Path
          $TestKeyDir = Join-Path $env:TEMP ([System.Guid]::NewGuid().ToString())
          $TestKey = Join-Path $TestKeyDir "id_ed25519"
          $ServerJob = $null

          function Invoke-SuccessCase {
            param(
              [string]$Name,
              [string]$ExpectedText,
              [string]$Target
            )

            Write-Host "Running $Name..."
            $Output = & $BinPath @BaseArgs $Target "cmd /c echo $ExpectedText" 2>&1 | Out-String
            $ActualExit = $LASTEXITCODE
            Write-Host $Output

            if ($ActualExit -ne 0) {
              throw "$Name expected exit 0, got $ActualExit"
            }

            if ($Output -notmatch [regex]::Escape($ExpectedText)) {
              throw "$Name missing expected output $ExpectedText"
            }

            Write-Host "SUCCESS: $Name exited with $ActualExit"
            $global:LASTEXITCODE = 0
          }

          function Invoke-ExitCase {
            param(
              [string]$Name,
              [int]$ExpectedExit,
              [string]$Target,
              [string]$RemoteCommand,
              [string]$Executable = $BinPath
            )

            Write-Host "Running $Name..."
            $Output = & $Executable @BaseArgs $Target $RemoteCommand 2>&1 | Out-String
            $ActualExit = $LASTEXITCODE
            Write-Host $Output

            if ($ActualExit -ne $ExpectedExit) {
              throw "$Name expected exit $ExpectedExit, got $ActualExit"
            }

            Write-Host "SUCCESS: $Name exited with $ActualExit"
            $global:LASTEXITCODE = 0
          }

          try {
            New-Item -ItemType Directory -Force -Path $TestKeyDir | Out-Null
            & ssh-keygen -q -t ed25519 -N "" -f $TestKey

            $PublicKey = (Get-Content "$TestKey.pub" -Raw).Trim()
            $UserSshDir = Join-Path $env:USERPROFILE ".ssh"
            $UserAuthorizedKeys = Join-Path $UserSshDir "authorized_keys"

            New-Item -ItemType Directory -Force -Path $UserSshDir | Out-Null
            Add-Content -Path $UserAuthorizedKeys -Value $PublicKey
            & icacls $UserAuthorizedKeys /inheritance:r /grant:r "${env:USERNAME}:(F)" /grant:r "SYSTEM:(F)" | Out-Null

            $CurrentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
            $CurrentPrincipal = [Security.Principal.WindowsPrincipal]::new($CurrentIdentity)
            if ($CurrentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
              $AdminAuthorizedKeys = Join-Path $env:ProgramData "ssh\administrators_authorized_keys"
              Add-Content -Path $AdminAuthorizedKeys -Value $PublicKey
              & icacls $AdminAuthorizedKeys /inheritance:r /grant:r "Administrators:(F)" /grant:r "SYSTEM:(F)" | Out-Null
            }

            Write-Host "Starting iroh-ssh server for exit code tests..."
            $ServerJob = Start-Job -ScriptBlock {
              param($Path)
              & $Path server --persist
            } -ArgumentList $BinPath

            $ServerOutput = ""
            $ConnectionString = $null
            for ($i = 0; $i -lt 30; $i++) {
              $ServerOutput = (Receive-Job -Job $ServerJob -Keep 2>$null | Out-String)
              if ($ServerOutput -match 'iroh-ssh ([^@]+@[a-f0-9]{64})') {
                $ConnectionString = $Matches[1]
                break
              }
              if ($ServerJob.State -in @('Completed', 'Failed', 'Stopped')) {
                break
              }
              Start-Sleep -Seconds 1
            }

            Write-Host "Server output:"
            Write-Host $ServerOutput

            if (-not $ConnectionString) {
              throw "Could not extract connection string from server output"
            }

            Write-Host "Connection string: $ConnectionString"

            $CurrentUser = $env:USERNAME
            $EndpointHost = $ConnectionString.Split('@')[1]
            $UserSshConfig = Join-Path $UserSshDir "config"

            @(
              '',
              'Host iroh-endpoint-config',
              "  HostName $EndpointHost",
              '',
              'Host iroh-localhost-config',
              '  HostName localhost',
              "  User $CurrentUser"
            ) | Add-Content -Path $UserSshConfig

            $script:BaseArgs = @(
              '-i', $TestKey,
              '-o', 'StrictHostKeyChecking=no',
              '-o', 'UserKnownHostsFile=NUL',
              '-o', 'BatchMode=yes'
            )

            Invoke-SuccessCase -Name 'inline-endpoint-id' -ExpectedText 'inline-endpoint-id' -Target $ConnectionString
            Invoke-SuccessCase -Name 'inline-localhost' -ExpectedText 'inline-localhost' -Target ("{0}@localhost" -f $CurrentUser)
            Invoke-SuccessCase -Name 'inline-loopback-ip' -ExpectedText 'inline-loopback-ip' -Target ("{0}@127.0.0.1" -f $CurrentUser)
            Invoke-SuccessCase -Name 'config-endpoint-explicit-user' -ExpectedText 'config-endpoint-explicit-user' -Target ("{0}@iroh-endpoint-config" -f $CurrentUser)
            Invoke-SuccessCase -Name 'config-localhost-config-user' -ExpectedText 'config-localhost-config-user' -Target 'iroh-localhost-config'

            Invoke-ExitCase -Name 'normal-exit' -ExpectedExit 0 -Target $ConnectionString -RemoteCommand 'cmd /c exit 0'
            Invoke-ExitCase -Name 'custom-exit' -ExpectedExit 197 -Target $ConnectionString -RemoteCommand 'cmd /c exit 197'

            $RemoteTerminateCommand = 'powershell -NoProfile -NonInteractive -Command "Stop-Process -Id $PID -Force"'
            $ProxyCommand = ('"{0}" proxy %h' -f $BinPath)
            $BaselineArgs = $BaseArgs + @(
              '-o', "ProxyCommand=$ProxyCommand",
              $ConnectionString
            )
            $BaselineOutput = & ssh.exe @BaselineArgs $RemoteTerminateCommand 2>&1 | Out-String
            $BaselineExit = $LASTEXITCODE

            Write-Host "Stock ssh baseline output:"
            Write-Host $BaselineOutput
            Write-Host "Stock ssh baseline exit: $BaselineExit"

            if ($BaselineExit -eq 0) {
              throw "Stock ssh returned 0 for forced remote termination, refusing to treat that as a valid signal-style failure"
            }

            $global:LASTEXITCODE = 0

            Invoke-ExitCase -Name 'remote-termination' -ExpectedExit $BaselineExit -Target $ConnectionString -RemoteCommand $RemoteTerminateCommand
          }
          finally {
            if ($ServerJob) {
              Stop-Job -Job $ServerJob -ErrorAction SilentlyContinue
              Remove-Job -Job $ServerJob -Force -ErrorAction SilentlyContinue
            }
            Remove-Item -Path $TestKeyDir -Recurse -Force -ErrorAction SilentlyContinue
          }

      - name: Run key-dir test (Linux/macOS)
        if: runner.os != 'Windows'
        shell: bash
        timeout-minutes: 5
        run: |
          set -euo pipefail

          BIN_PATH="dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}"
          CUSTOM_KEY_DIR="$(mktemp -d)"
          TEST_KEY_DIR="$(mktemp -d)"
          TEST_KEY="$TEST_KEY_DIR/id_ed25519"

          cleanup() {
            kill "$SERVER_DEFAULT_PID" 2>/dev/null || true
            kill "$SERVER_CUSTOM_PID" 2>/dev/null || true
            wait "$SERVER_DEFAULT_PID" 2>/dev/null || true
            wait "$SERVER_CUSTOM_PID" 2>/dev/null || true
            rm -rf "$CUSTOM_KEY_DIR" "$TEST_KEY_DIR"
          }
          trap cleanup EXIT

          mkdir -p "$HOME/.ssh"
          chmod 700 "$HOME/.ssh"
          ssh-keygen -q -t ed25519 -N "" -f "$TEST_KEY"
          cat "$TEST_KEY.pub" >> "$HOME/.ssh/authorized_keys"
          chmod 600 "$HOME/.ssh/authorized_keys"

          # Start server A: default key-dir (~/.ssh)
          echo "Starting server with default key-dir..."
          "$BIN_PATH" server --persist > server_default_output.txt 2>&1 &
          SERVER_DEFAULT_PID=$!

          for i in {1..30}; do
            if grep -q 'iroh-ssh.*@[a-f0-9]' server_default_output.txt 2>/dev/null; then break; fi
            if ! kill -0 "$SERVER_DEFAULT_PID" 2>/dev/null; then
              echo "ERROR: Default server died"; cat server_default_output.txt; exit 1
            fi
            sleep 1
          done

          DEFAULT_CONN=$(grep 'iroh-ssh' server_default_output.txt | grep -v 'client ->' | awk '{print $2}' | head -1)
          DEFAULT_ENDPOINT="${DEFAULT_CONN#*@}"
          echo "Default server endpoint: $DEFAULT_ENDPOINT"

          # Start server B: custom key-dir
          echo "Starting server with --key-dir $CUSTOM_KEY_DIR..."
          "$BIN_PATH" server --persist --key-dir "$CUSTOM_KEY_DIR" > server_custom_output.txt 2>&1 &
          SERVER_CUSTOM_PID=$!

          for i in {1..30}; do
            if grep -q 'iroh-ssh.*@[a-f0-9]' server_custom_output.txt 2>/dev/null; then break; fi
            if ! kill -0 "$SERVER_CUSTOM_PID" 2>/dev/null; then
              echo "ERROR: Custom key-dir server died"; cat server_custom_output.txt; exit 1
            fi
            sleep 1
          done

          CUSTOM_CONN=$(grep 'iroh-ssh' server_custom_output.txt | grep -v 'client ->' | awk '{print $2}' | head -1)
          CUSTOM_ENDPOINT="${CUSTOM_CONN#*@}"
          echo "Custom key-dir server endpoint: $CUSTOM_ENDPOINT"

          # Endpoints must differ
          if [ "$DEFAULT_ENDPOINT" = "$CUSTOM_ENDPOINT" ]; then
            echo "ERROR: Both servers have the same endpoint, key-dir was not respected"
            exit 1
          fi
          echo "SUCCESS: Endpoints differ as expected"

          # Verify key files exist in custom dir
          if [ ! -f "$CUSTOM_KEY_DIR/irohssh_ed25519" ] || [ ! -f "$CUSTOM_KEY_DIR/irohssh_ed25519.pub" ]; then
            echo "ERROR: Key files not found in custom key-dir $CUSTOM_KEY_DIR"
            ls -la "$CUSTOM_KEY_DIR"
            exit 1
          fi
          echo "SUCCESS: Key files present in custom key-dir"

          # Info with default key-dir should show default endpoint
          INFO_DEFAULT=$("$BIN_PATH" info 2>&1 || true)
          echo "Info (default):"
          echo "$INFO_DEFAULT"
          if ! echo "$INFO_DEFAULT" | grep -q "$DEFAULT_ENDPOINT"; then
            echo "ERROR: info output does not contain default endpoint"
            exit 1
          fi
          echo "SUCCESS: info shows default endpoint"

          # Info with custom key-dir should show custom endpoint
          INFO_CUSTOM=$("$BIN_PATH" info --key-dir "$CUSTOM_KEY_DIR" 2>&1 || true)
          echo "Info (custom key-dir):"
          echo "$INFO_CUSTOM"
          if ! echo "$INFO_CUSTOM" | grep -q "$CUSTOM_ENDPOINT"; then
            echo "ERROR: info --key-dir output does not contain custom endpoint"
            exit 1
          fi
          echo "SUCCESS: info --key-dir shows custom endpoint"

          # Connect test: default server
          COMMON_SSH_ARGS=(-i "$TEST_KEY" -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" -o "BatchMode=yes")

          run_connect() {
            local label="$1" target="$2"
            echo "Connecting to ${label}..."
            set +e
            if command -v timeout > /dev/null; then
              CONNECT_OUT=$(timeout 30s "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$target" "echo keydir-${label}-ok" 2>&1)
              CONNECT_EXIT=$?
            else
              "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$target" "echo keydir-${label}-ok" > connect_${label}.txt 2>&1 &
              local cpid=$!
              ( sleep 30; kill "$cpid" 2>/dev/null ) &
              local wpid=$!
              wait "$cpid"
              CONNECT_EXIT=$?
              kill "$wpid" 2>/dev/null || true
              wait "$wpid" 2>/dev/null || true
              CONNECT_OUT=$(cat connect_${label}.txt)
            fi
            set -e
            echo "$CONNECT_OUT"

            if echo "$CONNECT_OUT" | grep -q "keydir-${label}-ok"; then
              echo "SUCCESS: Connected to ${label}"
            elif echo "$CONNECT_OUT" | grep -q "Permanently added"; then
              echo "SUCCESS: Reached SSH host on ${label} (host key exchanged)"
            else
              echo "ERROR: Could not reach ${label}"
              exit 1
            fi
          }

          run_connect "default-server" "$DEFAULT_CONN"
          run_connect "custom-keydir-server" "$CUSTOM_CONN"

      - name: Run key-dir test (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        timeout-minutes: 5
        run: |
          $ErrorActionPreference = "Stop"

          $BinPath = (Resolve-Path "dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}").Path
          $CustomKeyDir = Join-Path $env:TEMP ("iroh-keydir-" + [System.Guid]::NewGuid().ToString())
          $TestKeyDir = Join-Path $env:TEMP ("iroh-testkey-" + [System.Guid]::NewGuid().ToString())
          $TestKey = Join-Path $TestKeyDir "id_ed25519"
          $ServerDefaultJob = $null
          $ServerCustomJob = $null

          try {
            New-Item -ItemType Directory -Force -Path $CustomKeyDir | Out-Null
            New-Item -ItemType Directory -Force -Path $TestKeyDir | Out-Null

            & ssh-keygen -q -t ed25519 -N "" -f $TestKey
            $PublicKey = (Get-Content "$TestKey.pub" -Raw).Trim()
            $UserSshDir = Join-Path $env:USERPROFILE ".ssh"
            New-Item -ItemType Directory -Force -Path $UserSshDir | Out-Null
            $UserAuthorizedKeys = Join-Path $UserSshDir "authorized_keys"
            Add-Content -Path $UserAuthorizedKeys -Value $PublicKey
            & icacls $UserAuthorizedKeys /inheritance:r /grant:r "${env:USERNAME}:(F)" /grant:r "SYSTEM:(F)" | Out-Null

            $CurrentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
            $CurrentPrincipal = [Security.Principal.WindowsPrincipal]::new($CurrentIdentity)
            if ($CurrentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
              $AdminAuthorizedKeys = Join-Path $env:ProgramData "ssh\administrators_authorized_keys"
              Add-Content -Path $AdminAuthorizedKeys -Value $PublicKey
              & icacls $AdminAuthorizedKeys /inheritance:r /grant:r "Administrators:(F)" /grant:r "SYSTEM:(F)" | Out-Null
            }

            # Start server A: default key-dir
            Write-Host "Starting server with default key-dir..."
            $ServerDefaultJob = Start-Job -ScriptBlock {
              param($Path)
              & $Path server --persist
            } -ArgumentList $BinPath

            $DefaultConn = $null
            for ($i = 0; $i -lt 30; $i++) {
              $Out = (Receive-Job -Job $ServerDefaultJob -Keep 2>$null | Out-String)
              if ($Out -match 'iroh-ssh ([^@]+@[a-f0-9]{64})') {
                $DefaultConn = $Matches[1]
                break
              }
              if ($ServerDefaultJob.State -in @('Completed', 'Failed', 'Stopped')) { break }
              Start-Sleep -Seconds 1
            }

            if (-not $DefaultConn) {
              throw "Could not extract default server connection string"
            }

            $DefaultEndpoint = $DefaultConn.Split('@')[1]
            Write-Host "Default server endpoint: $DefaultEndpoint"

            # Start server B: custom key-dir
            Write-Host "Starting server with --key-dir $CustomKeyDir..."
            $ServerCustomJob = Start-Job -ScriptBlock {
              param($Path, $Dir)
              & $Path server --persist --key-dir $Dir
            } -ArgumentList $BinPath, $CustomKeyDir

            $CustomConn = $null
            for ($i = 0; $i -lt 30; $i++) {
              $Out = (Receive-Job -Job $ServerCustomJob -Keep 2>$null | Out-String)
              if ($Out -match 'iroh-ssh ([^@]+@[a-f0-9]{64})') {
                $CustomConn = $Matches[1]
                break
              }
              if ($ServerCustomJob.State -in @('Completed', 'Failed', 'Stopped')) { break }
              Start-Sleep -Seconds 1
            }

            if (-not $CustomConn) {
              throw "Could not extract custom key-dir server connection string"
            }

            $CustomEndpoint = $CustomConn.Split('@')[1]
            Write-Host "Custom key-dir server endpoint: $CustomEndpoint"

            # Endpoints must differ
            if ($DefaultEndpoint -eq $CustomEndpoint) {
              throw "Both servers have the same endpoint, key-dir was not respected"
            }
            Write-Host "SUCCESS: Endpoints differ as expected"

            # Verify key files in custom dir
            if (-not (Test-Path (Join-Path $CustomKeyDir "irohssh_ed25519")) -or
                -not (Test-Path (Join-Path $CustomKeyDir "irohssh_ed25519.pub"))) {
              throw "Key files not found in custom key-dir $CustomKeyDir"
            }
            Write-Host "SUCCESS: Key files present in custom key-dir"

            # Info with default key-dir
            $InfoDefault = & $BinPath info 2>&1 | Out-String
            Write-Host "Info (default):"
            Write-Host $InfoDefault
            if ($InfoDefault -notmatch [regex]::Escape($DefaultEndpoint)) {
              throw "info output does not contain default endpoint"
            }
            Write-Host "SUCCESS: info shows default endpoint"

            # Info with custom key-dir
            $InfoCustom = & $BinPath info --key-dir $CustomKeyDir 2>&1 | Out-String
            Write-Host "Info (custom key-dir):"
            Write-Host $InfoCustom
            if ($InfoCustom -notmatch [regex]::Escape($CustomEndpoint)) {
              throw "info --key-dir output does not contain custom endpoint"
            }
            Write-Host "SUCCESS: info --key-dir shows custom endpoint"

            # Connect test: default server
            $BaseArgs = @('-i', $TestKey, '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=NUL', '-o', 'BatchMode=yes')

            Write-Host "Connecting to default server..."
            $ConnectOut = & $BinPath @BaseArgs $DefaultConn "cmd /c echo keydir-default-ok" 2>&1 | Out-String
            $ConnExit = $LASTEXITCODE
            Write-Host $ConnectOut

            if ($ConnectOut -match "keydir-default-ok") {
              Write-Host "SUCCESS: Connected to default server"
            } elseif ($ConnectOut -match "Permanently added") {
              Write-Host "SUCCESS: Reached SSH host on default server (host key exchanged)"
            } else {
              throw "Could not reach default server"
            }

            # Connect test: custom key-dir server
            Write-Host "Connecting to custom key-dir server..."
            $ConnectOut = & $BinPath @BaseArgs $CustomConn "cmd /c echo keydir-custom-ok" 2>&1 | Out-String
            $ConnExit = $LASTEXITCODE
            Write-Host $ConnectOut

            if ($ConnectOut -match "keydir-custom-ok") {
              Write-Host "SUCCESS: Connected to custom key-dir server"
            } elseif ($ConnectOut -match "Permanently added") {
              Write-Host "SUCCESS: Reached SSH host on custom key-dir server (host key exchanged)"
            } else {
              throw "Could not reach custom key-dir server"
            }

            $global:LASTEXITCODE = 0
          }
          finally {
            if ($ServerDefaultJob) {
              Stop-Job -Job $ServerDefaultJob -ErrorAction SilentlyContinue
              Remove-Job -Job $ServerDefaultJob -Force -ErrorAction SilentlyContinue
            }
            if ($ServerCustomJob) {
              Stop-Job -Job $ServerCustomJob -ErrorAction SilentlyContinue
              Remove-Job -Job $ServerCustomJob -Force -ErrorAction SilentlyContinue
            }
            Remove-Item -Path $CustomKeyDir -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path $TestKeyDir -Recurse -Force -ErrorAction SilentlyContinue
          }

      - name: Run service install test (Linux)
        if: runner.os == 'Linux'
        shell: bash
        timeout-minutes: 5
        run: |
          set -euo pipefail

          BIN_PATH="$(pwd)/dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}"
          CUSTOM_KEY_DIR="svc-test-keys"
          TEST_KEY_DIR="$(mktemp -d)"
          TEST_KEY="$TEST_KEY_DIR/id_ed25519"

          cleanup() {
            sudo "$BIN_PATH" service uninstall 2>/dev/null || true
            sleep 2
            sudo rm -f /etc/systemd/system/iroh-ssh-server.service
            sudo rm -f /usr/local/bin/iroh-ssh
            sudo systemctl daemon-reload 2>/dev/null || true
            rm -rf "$(pwd)/$CUSTOM_KEY_DIR" "$TEST_KEY_DIR"
          }
          trap cleanup EXIT

          # Prepare SSH key for connect tests
          mkdir -p "$HOME/.ssh"
          chmod 700 "$HOME/.ssh"
          ssh-keygen -q -t ed25519 -N "" -f "$TEST_KEY"
          cat "$TEST_KEY.pub" >> "$HOME/.ssh/authorized_keys"
          chmod 600 "$HOME/.ssh/authorized_keys"
          # Service runs as root, so authorize for root too
          sudo mkdir -p /root/.ssh
          sudo chmod 700 /root/.ssh
          cat "$TEST_KEY.pub" | sudo tee -a /root/.ssh/authorized_keys > /dev/null
          sudo chmod 600 /root/.ssh/authorized_keys

          COMMON_SSH_ARGS=(-i "$TEST_KEY" -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" -o "BatchMode=yes")

          try_connect() {
            local label="$1" target="$2"
            echo "Connecting to ${label}..."
            set +e
            CONNECT_OUT=$(timeout 30s "$BIN_PATH" "${COMMON_SSH_ARGS[@]}" "$target" "echo svc-${label}-ok" 2>&1)
            CONNECT_EXIT=$?
            set -e
            echo "$CONNECT_OUT"

            if echo "$CONNECT_OUT" | grep -q "svc-${label}-ok"; then
              echo "SUCCESS: Connected to ${label}"
            elif echo "$CONNECT_OUT" | grep -q "Permanently added"; then
              echo "SUCCESS: Reached SSH host on ${label} (host key exchanged)"
            else
              echo "ERROR: Could not reach ${label}"
              return 1
            fi
          }

          echo "Installing service without --key-dir..."
          sudo "$BIN_PATH" service install --ssh-port 22
          sleep 5

          if ! sudo systemctl is-active --quiet iroh-ssh-server.service; then
            echo "ERROR: Service not running"
            sudo systemctl status iroh-ssh-server.service || true
            sudo journalctl -u iroh-ssh-server.service --no-pager -n 30 || true
            exit 1
          fi
          echo "Service is running"

          # Wait for keys to appear (service creates them on startup)
          for i in {1..15}; do
            if sudo test -f /root/.ssh/irohssh_ed25519.pub; then break; fi
            sleep 1
          done

          # Get endpoint from info (run as root to see /root/.ssh keys)
          INFO_DEFAULT=$(sudo "$BIN_PATH" info 2>&1 || true)
          echo "Info (service, no key-dir):"
          echo "$INFO_DEFAULT"

          SVC_ENDPOINT_DEFAULT=$(echo "$INFO_DEFAULT" | grep -A1 'service iroh-ssh endpoint' | grep -oP '@\K[a-f0-9]{64}' | head -1)
          if [ -z "$SVC_ENDPOINT_DEFAULT" ]; then
            # Fall back to first endpoint if no service-specific one found
            SVC_ENDPOINT_DEFAULT=$(echo "$INFO_DEFAULT" | grep -oP '@\K[a-f0-9]{64}' | head -1)
          fi
          if [ -z "$SVC_ENDPOINT_DEFAULT" ]; then
            echo "ERROR: Could not extract service endpoint from info"
            exit 1
          fi
          echo "Service endpoint (default): $SVC_ENDPOINT_DEFAULT"

          CURRENT_USER="$(id -un)"
          try_connect "service-default" "${CURRENT_USER}@${SVC_ENDPOINT_DEFAULT}"

          echo "Uninstalling service"
          sudo "$BIN_PATH" service uninstall
          sleep 3

          if sudo systemctl is-active --quiet iroh-ssh-server.service 2>/dev/null; then
            echo "ERROR: Service still running after uninstall"
            exit 1
          fi
          echo "Service uninstalled"

          # Clean up default service keys so they don't interfere
          sudo rm -f /root/.ssh/irohssh_ed25519 /root/.ssh/irohssh_ed25519.pub

          echo "Installing service with relative --key-dir $CUSTOM_KEY_DIR..."
          mkdir -p "$CUSTOM_KEY_DIR"
          sudo "$BIN_PATH" service install --ssh-port 22 --key-dir "$CUSTOM_KEY_DIR"
          sleep 5

          if ! sudo systemctl is-active --quiet iroh-ssh-server.service; then
            echo "ERROR: Service not running with --key-dir"
            sudo systemctl status iroh-ssh-server.service || true
            sudo journalctl -u iroh-ssh-server.service --no-pager -n 30 || true
            exit 1
          fi
          echo "Service is running with --key-dir"

          # Wait for keys to appear
          for i in {1..15}; do
            if [ -f "$CUSTOM_KEY_DIR/irohssh_ed25519.pub" ]; then break; fi
            sleep 1
          done

          if [ ! -f "$CUSTOM_KEY_DIR/irohssh_ed25519" ] || [ ! -f "$CUSTOM_KEY_DIR/irohssh_ed25519.pub" ]; then
            echo "ERROR: Key files not found in custom key-dir"
            ls -la "$CUSTOM_KEY_DIR"
            exit 1
          fi
          echo "SUCCESS: Key files present in custom key-dir"

          # Get endpoint from info --key-dir
          INFO_CUSTOM=$("$BIN_PATH" info --key-dir "$CUSTOM_KEY_DIR" 2>&1 || true)
          echo "Info (service, --key-dir):"
          echo "$INFO_CUSTOM"

          SVC_ENDPOINT_CUSTOM=$(echo "$INFO_CUSTOM" | grep -oP '@\K[a-f0-9]{64}' | head -1)
          if [ -z "$SVC_ENDPOINT_CUSTOM" ]; then
            echo "ERROR: Could not extract service endpoint from info --key-dir"
            exit 1
          fi
          echo "Service endpoint (key-dir): $SVC_ENDPOINT_CUSTOM"

          if [ "$SVC_ENDPOINT_DEFAULT" = "$SVC_ENDPOINT_CUSTOM" ]; then
            echo "ERROR: Service endpoints should differ between default and custom key-dir"
            exit 1
          fi
          echo "SUCCESS: Service endpoints differ"

          try_connect "service-keydir" "${CURRENT_USER}@${SVC_ENDPOINT_CUSTOM}"

      - name: Run service install test (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        timeout-minutes: 5
        run: |
          $ErrorActionPreference = "Stop"

          $BinPath = (Resolve-Path "dist/${{ matrix.platform.target }}/iroh-ssh${{ matrix.platform.ext }}").Path
          $CustomKeyDir = "svc-test-keys"
          $TestKeyDir = Join-Path $env:TEMP ("iroh-svctestkey-" + [System.Guid]::NewGuid().ToString())
          $TestKey = Join-Path $TestKeyDir "id_ed25519"

          function Invoke-Cleanup {
            & $BinPath service uninstall 2>$null
            Start-Sleep -Seconds 3
            Remove-Item -Path (Join-Path (Get-Location) $CustomKeyDir) -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path $TestKeyDir -Recurse -Force -ErrorAction SilentlyContinue
          }

          try {
            New-Item -ItemType Directory -Force -Path $CustomKeyDir | Out-Null
            New-Item -ItemType Directory -Force -Path $TestKeyDir | Out-Null

            & ssh-keygen -q -t ed25519 -N "" -f $TestKey
            $PublicKey = (Get-Content "$TestKey.pub" -Raw).Trim()
            $UserSshDir = Join-Path $env:USERPROFILE ".ssh"
            New-Item -ItemType Directory -Force -Path $UserSshDir | Out-Null
            $UserAuthorizedKeys = Join-Path $UserSshDir "authorized_keys"
            Add-Content -Path $UserAuthorizedKeys -Value $PublicKey
            & icacls $UserAuthorizedKeys /inheritance:r /grant:r "${env:USERNAME}:(F)" /grant:r "SYSTEM:(F)" | Out-Null

            $AdminAuthorizedKeys = Join-Path $env:ProgramData "ssh\administrators_authorized_keys"
            if (Test-Path (Split-Path $AdminAuthorizedKeys)) {
              Add-Content -Path $AdminAuthorizedKeys -Value $PublicKey
              & icacls $AdminAuthorizedKeys /inheritance:r /grant:r "Administrators:(F)" /grant:r "SYSTEM:(F)" | Out-Null
            }

            $BaseArgs = @('-i', $TestKey, '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=NUL', '-o', 'BatchMode=yes')

            function Test-ServiceConnect {
              param([string]$Label, [string]$Target)
              Write-Host "Connecting to $Label..."
              $Out = & $BinPath @BaseArgs $Target "cmd /c echo svc-${Label}-ok" 2>&1 | Out-String
              $Exit = $LASTEXITCODE
              Write-Host $Out

              if ($Out -match "svc-${Label}-ok") {
                Write-Host "SUCCESS: Connected to $Label"
              } elseif ($Out -match "Permanently added") {
                Write-Host "SUCCESS: Reached SSH host on $Label (host key exchanged)"
              } else {
                throw "Could not reach $Label"
              }
              $global:LASTEXITCODE = 0
            }

            Write-Host "Installing service without --key-dir"
            & $BinPath service install --ssh-port 22
            Start-Sleep -Seconds 10

            $Svc = Get-Service -Name "iroh-ssh" -ErrorAction SilentlyContinue
            if (-not $Svc -or $Svc.Status -ne 'Running') {
              Write-Host "ERROR: Service not running"
              if ($Svc) { Write-Host "Service status: $($Svc.Status)" }
              throw "Service not running after install"
            }
            Write-Host "Service is running"

            # Wait for keys to appear
            $SvcSshDir = "C:\Windows\ServiceProfiles\iroh-ssh\.ssh"
            for ($i = 0; $i -lt 15; $i++) {
              if (Test-Path (Join-Path $SvcSshDir "irohssh_ed25519.pub")) { break }
              Start-Sleep -Seconds 1
            }

            # Get endpoint from info
            $InfoDefault = & $BinPath info 2>&1 | Out-String
            Write-Host "Info (service, no key-dir):"
            Write-Host $InfoDefault

            $SvcEndpointDefault = $null
            $Lines = $InfoDefault -split "`n"
            for ($i = 0; $i -lt $Lines.Count; $i++) {
              if ($Lines[$i] -match 'service iroh-ssh endpoint' -and ($i + 1) -lt $Lines.Count) {
                if ($Lines[$i + 1] -match '@([a-f0-9]{64})') {
                  $SvcEndpointDefault = $Matches[1]
                  break
                }
              }
            }
            if (-not $SvcEndpointDefault -and $InfoDefault -match '@([a-f0-9]{64})') {
              $SvcEndpointDefault = $Matches[1]
            }
            if (-not $SvcEndpointDefault) {
              throw "Could not extract service endpoint from info"
            }
            Write-Host "Service endpoint (default): $SvcEndpointDefault"

            $CurrentUser = $env:USERNAME
            Test-ServiceConnect -Label "service-default" -Target "${CurrentUser}@${SvcEndpointDefault}"

            Write-Host "Uninstalling service"
            & $BinPath service uninstall
            Start-Sleep -Seconds 5

            $Svc = Get-Service -Name "iroh-ssh" -ErrorAction SilentlyContinue
            if ($Svc -and $Svc.Status -eq 'Running') {
              throw "Service still running after uninstall"
            }
            Write-Host "Service uninstalled"

            # Clean default service keys
            Remove-Item -Path (Join-Path $SvcSshDir "irohssh_ed25519") -Force -ErrorAction SilentlyContinue
            Remove-Item -Path (Join-Path $SvcSshDir "irohssh_ed25519.pub") -Force -ErrorAction SilentlyContinue

            Write-Host "Installing service with relative --key-dir $CustomKeyDir..."
            New-Item -ItemType Directory -Force -Path $CustomKeyDir | Out-Null
            & $BinPath service install --ssh-port 22 --key-dir $CustomKeyDir
            Start-Sleep -Seconds 10

            $Svc = Get-Service -Name "iroh-ssh" -ErrorAction SilentlyContinue
            if (-not $Svc -or $Svc.Status -ne 'Running') {
              Write-Host "ERROR: Service not running with --key-dir"
              if ($Svc) { Write-Host "Service status: $($Svc.Status)" }
              throw "Service not running after install with --key-dir"
            }
            Write-Host "Service is running with --key-dir"

            # Wait for keys to appear
            for ($i = 0; $i -lt 15; $i++) {
              if (Test-Path (Join-Path $CustomKeyDir "irohssh_ed25519.pub")) { break }
              Start-Sleep -Seconds 1
            }

            if (-not (Test-Path (Join-Path $CustomKeyDir "irohssh_ed25519")) -or
                -not (Test-Path (Join-Path $CustomKeyDir "irohssh_ed25519.pub"))) {
              throw "Key files not found in custom key-dir $CustomKeyDir"
            }
            Write-Host "SUCCESS: Key files present in custom key-dir"

            # Get endpoint from info --key-dir
            $InfoCustom = & $BinPath info --key-dir $CustomKeyDir 2>&1 | Out-String
            Write-Host "Info (service, --key-dir):"
            Write-Host $InfoCustom

            if ($InfoCustom -match '@([a-f0-9]{64})') {
              $SvcEndpointCustom = $Matches[1]
            } else {
              throw "Could not extract service endpoint from info --key-dir"
            }
            Write-Host "Service endpoint (key-dir): $SvcEndpointCustom"

            if ($SvcEndpointDefault -eq $SvcEndpointCustom) {
              throw "Service endpoints should differ between default and custom key-dir"
            }
            Write-Host "SUCCESS: Service endpoints differ"

            Test-ServiceConnect -Label "service-keydir" -Target "${CurrentUser}@${SvcEndpointCustom}"

            Write-Host "All service tests passed"
            $global:LASTEXITCODE = 0
          }
          finally {
            Invoke-Cleanup
          }