zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! `zc init` — device-code browser authentication.
//!
//! Flow:
//!   1. POST /api/auth/cli/start  → get device_code, user_code, verification_uri, interval
//!   2. Open the browser at verification_uri
//!   3. Poll POST /api/auth/cli/poll with {device_code} every `interval` seconds
//!   4. On 200 + api_key  → save credentials, exit 0
//!      On 428            → keep polling (pending)
//!      On anything else  → print error, exit 1

use std::time::{Duration, Instant};

/// Outcome of a single poll response.
pub enum Decision {
    Pending,
    Approved(String),
    Failed(String),
}

/// Truncate a raw hostname to at most 128 *characters* (never bytes — slicing
/// a multi-byte string at a raw byte offset can land mid-codepoint and
/// panic), defaulting an empty or whitespace-only name to `"zc CLI"`.
pub(crate) fn clamp_device_name(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return "zc CLI".to_string();
    }
    trimmed.chars().take(128).collect()
}

/// This Mac's name for its hub device key (spec §5.1: `device_name`, ≤128 chars).
pub(crate) fn device_name() -> String {
    let name = hostname::get()
        .map(|h| h.to_string_lossy().into_owned())
        .unwrap_or_default();
    clamp_device_name(&name)
}

/// Body of `POST /api/auth/cli/start`. An older hub ignores it.
pub(crate) fn start_body(device_name: &str) -> String {
    serde_json::json!({ "device_name": device_name }).to_string()
}

/// What `zc login` prints once approved: whether the hub minted a revocable
/// device key (`token_type: "device"`) or an older session token.
pub(crate) fn approved_message(poll_body: &str) -> &'static str {
    let kind = serde_json::from_str::<serde_json::Value>(poll_body)
        .ok()
        .and_then(|v| v["token_type"].as_str().map(str::to_string));
    match kind.as_deref() {
        Some("device") => {
            "✓ Signed in. Device key saved to ~/.zakuro/credentials (revoke it on the hub under Signed-in devices)."
        }
        _ => "✓ Signed in. Key saved to ~/.zakuro/credentials.",
    }
}

/// Pure decision function — maps an HTTP status + body to a `Decision`.
/// No network I/O; suitable for unit tests.
pub fn decide(http_status: u16, body: &str) -> Decision {
    match http_status {
        428 => Decision::Pending,
        200 => {
            match serde_json::from_str::<serde_json::Value>(body)
                .ok()
                .and_then(|v| v["api_key"].as_str().map(|s| s.to_string()))
            {
                Some(k) => Decision::Approved(k),
                None => Decision::Failed("approved but no api_key in response".into()),
            }
        }
        410 => Decision::Failed("code expired — run `zc init` again".into()),
        403 => Decision::Failed("authorization was denied".into()),
        404 => Decision::Failed("session not found".into()),
        s => Decision::Failed(format!("unexpected status {s}")),
    }
}

/// Print how to connect by setting an API key, listing the known dashboards.
/// Shown when browser device-code sign-in isn't available on the target.
pub fn print_connect_guidance() {
    eprintln!();
    eprintln!("To connect, grab your API key from the dashboard (Profile → API Keys), then:");
    eprintln!();
    eprintln!("  # pick your environment");
    eprintln!(
        "  export ZAKURO_API_URL={}   # production",
        crate::credentials::PROD_API_URL
    );
    eprintln!(
        "  export ZAKURO_API_URL={}   # staging",
        crate::credentials::STAGING_API_URL
    );
    eprintln!();
    eprintln!("  export ZAKURO_API_KEY=<your key>");
    eprintln!("  zc connect            # join the mesh (add --docker to use Docker)");
}

/// What `zc login` should do, given the credential state and flags. Split out
/// from `run` so the routing is unit-testable without a network or a browser.
#[derive(Debug, PartialEq)]
pub(crate) enum Plan {
    /// Signed in already: bring up the mesh instead of printing another command.
    ConnectMesh,
    /// Signed in already, but the caller asked us not to touch the network.
    ReportOnly,
    /// No usable key, or `--force`: run the device-code sign-in.
    SignIn,
}

pub(crate) fn plan(has_key: bool, force: bool, no_connect: bool) -> Plan {
    if !has_key || force {
        return Plan::SignIn;
    }
    if no_connect {
        return Plan::ReportOnly;
    }
    Plan::ConnectMesh
}

/// What to do right after credentials are saved by a fresh or forced sign-in.
/// Split out from `run` so `--no-connect` is unit-testable without a network.
#[derive(Debug, PartialEq)]
pub(crate) enum PostSignIn {
    /// Bring up the mesh and report whether it's reachable.
    ConnectMesh,
    /// The caller asked us not to touch the network.
    SkipMesh,
}

pub(crate) fn post_sign_in(no_connect: bool) -> PostSignIn {
    if no_connect {
        PostSignIn::SkipMesh
    } else {
        PostSignIn::ConnectMesh
    }
}

/// Flags accepted by `zc login` / `zc init`, parsed from an injected argument
/// list so the routing is unit-testable without touching `std::env::args()`.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct LoginArgs {
    pub help: bool,
    pub staging: bool,
    pub force: bool,
    pub no_connect: bool,
    pub no_browser: bool,
    /// One JSON object per line on stdout (`code`, `signed_in`, `error`),
    /// for the desktop app's first-run screen, which runs this through its
    /// bundled zc and shows the code itself.
    pub json: bool,
    /// Sign in with an email and password read from stdin as one JSON line
    /// (`{"email":…,"password":…}`), no browser: the desktop app's own login
    /// form. zc approves its own device code with the session it gets.
    pub password: bool,
}

impl LoginArgs {
    pub(crate) fn parse(args: &[String]) -> LoginArgs {
        let mut parsed = LoginArgs::default();
        for arg in args {
            match arg.as_str() {
                "--help" | "-h" => parsed.help = true,
                "--staging" => parsed.staging = true,
                "--force" => parsed.force = true,
                "--no-connect" => parsed.no_connect = true,
                "--no-browser" => parsed.no_browser = true,
                "--json" => parsed.json = true,
                "--password" => parsed.password = true,
                _ => {}
            }
        }
        parsed
    }
}

/// `zc login --help` / `-h` usage text, printed to stdout before any
/// credential read, network call, or mesh setup.
const LOGIN_HELP: &str = "\
Usage: zc login [--staging] [--force] [--no-connect] [--no-browser] [--json] [--password]

Sign in to Zakuro in the browser, then connect to the mesh. The browser opens
on the hub's sign-in page with this device's code already filled in: approve
it there and zc finishes on its own. `zc login` is an alias of `zc init`.

Options:
      --staging      Use the staging dashboard (same as ZAKURO_ENV=staging).
      --force        Re-authenticate even if already signed in.
      --no-connect   Skip connecting to the mesh after signing in.
      --no-browser   Don't open a browser: print the URL and the code, to open
                     on another machine (the default over SSH or without a
                     display).
      --json         Print one JSON object per line (code, signed_in, error)
                     instead of text, for the desktop app (implies
                     --no-connect).
      --password     Sign in with an email and password instead of the
                     browser: one JSON line on stdin with email and
                     password (never on the command line).
  -h, --help         Print this help and exit.

URL precedence: ZAKURO_API_URL > ZAKURO_ENV (lab|staging|prod) > production.
";

/// The sign-in page with the code already filled in. The hub's own
/// `verification_uri_complete` (RFC 8628 §3.3.1) wins when it sends one;
/// otherwise `?code=` is appended to `verification_uri`, which the hub's
/// `/activate` page reads to prefill the field.
pub(crate) fn prefilled_url(
    verification_uri: &str,
    user_code: &str,
    complete: Option<&str>,
) -> String {
    if let Some(c) = complete.filter(|c| !c.trim().is_empty()) {
        return c.to_string();
    }
    if verification_uri.is_empty() || user_code.is_empty() {
        return verification_uri.to_string();
    }
    // The hub's codes are `[A-Z2-9]{4}-[A-Z2-9]{4}`: nothing to escape, but
    // anything else is percent-encoded rather than trusted.
    let code: String = user_code
        .bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => (b as char).to_string(),
            _ => format!("%{b:02X}"),
        })
        .collect();
    let sep = if verification_uri.contains('?') {
        '&'
    } else {
        '?'
    };
    format!("{verification_uri}{sep}code={code}")
}

/// Whether `zc login` should try to open a browser here. Not with
/// `--no-browser`; not in an SSH session (the browser would open on the
/// remote machine, or nowhere); and on Linux not without a display.
pub(crate) fn should_open_browser(no_browser: bool, env: impl Fn(&str) -> Option<String>) -> bool {
    if no_browser {
        return false;
    }
    let set = |k: &str| env(k).is_some_and(|v| !v.is_empty());
    if set("SSH_CONNECTION") || set("SSH_TTY") {
        return false;
    }
    if cfg!(target_os = "linux") && !set("DISPLAY") && !set("WAYLAND_DISPLAY") {
        return false;
    }
    true
}

pub(crate) fn print_help() {
    print!("{LOGIN_HELP}");
}

/// What `zc login` does about this device's node key before it joins the mesh
/// (ruling L1). Without the key, the WireGuard profile request carries no
/// fingerprint, and the device stays on the account's shared mesh identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NodeKeyStep {
    /// The key is already there: nothing to do.
    Present,
    /// No key yet: create it (0600).
    Create,
    /// No key yet, but running as root: a root-owned key in the user's home
    /// would break later non-root zc runs (R13), so leave it and warn.
    SkipAsRoot,
}

/// The [`NodeKeyStep`] decision as a pure function, so it is tested without a
/// real home directory.
pub(crate) fn node_key_step(is_root: bool, key_present: bool) -> NodeKeyStep {
    match (key_present, is_root) {
        (true, _) => NodeKeyStep::Present,
        (false, false) => NodeKeyStep::Create,
        (false, true) => NodeKeyStep::SkipAsRoot,
    }
}

/// Carry out [`node_key_step`] against `<dir>/node_key` and return the step.
/// Only [`NodeKeyStep::Create`] writes, through `NodeKey::load_or_create_in`,
/// and a key that loads is never rewritten.
pub(crate) fn ensure_node_key_in(dir: Option<std::path::PathBuf>, is_root: bool) -> NodeKeyStep {
    use crate::broker::node_identity::NodeKey;
    let step = node_key_step(is_root, NodeKey::load_in(dir.clone()).is_some());
    if step == NodeKeyStep::Create {
        NodeKey::load_or_create_in(dir);
    }
    step
}

/// [`ensure_node_key_in`] against the real state dir, the one
/// `NodeKey::load_or_create` uses, with a one-line warning for root.
fn ensure_node_key() {
    if ensure_node_key_in(crate::credentials::dir(), crate::vpn::native::is_root())
        == NodeKeyStep::SkipAsRoot
    {
        eprintln!(
            "⚠ running as root: not creating ~/.zakuro/node_key; run zc login as your user so this device gets its own mesh identity"
        );
    }
}

/// Bring up mesh access and report it. Shared by both sign-in paths so a fresh
/// sign-in and an already-signed-in re-run print the same thing. `--no-connect`
/// never gets here, so it skips the node key along with the mesh.
///
/// Returns true when the mesh is reachable. Safe to call when already connected:
/// `vpn::connect` returns the live connection instead of rebuilding the tunnel.
fn connect_mesh() -> bool {
    // Before the profile request (ruling L1): with a node key, it carries this
    // device's fingerprint, and the hub can give the device its own mesh
    // identity.
    ensure_node_key();
    match crate::vpn::ensure(crate::vpn::connector::Preference::Auto) {
        Ok(crate::vpn::MeshAccess::Host) => {
            println!("✓ Mesh reachable from this host. Try `zc me`.");
            true
        }
        Ok(crate::vpn::MeshAccess::Proxy(p)) => {
            println!("✓ Mesh reachable via VPN container proxy ({p}). Try `zc me`.");
            true
        }
        Err(e) => {
            eprintln!("✗ VPN setup failed: {e}");
            eprintln!("  Retry with `zc connect`.");
            false
        }
    }
}

/// One `--json` event line.
pub(crate) fn json_event(event: &str, fields: serde_json::Value) -> String {
    let mut v = serde_json::json!({ "event": event });
    if let (Some(o), serde_json::Value::Object(f)) = (v.as_object_mut(), fields) {
        o.extend(f);
    }
    v.to_string()
}

/// Run the `zc init` device-code flow. Returns an exit code (0 = success).
pub fn run() -> i32 {
    // Parse flags first: `--help`/`-h` must return before any credential read,
    // network call, or mesh setup.
    let args = LoginArgs::parse(&std::env::args().skip(1).collect::<Vec<_>>());
    if args.help {
        print_help();
        return 0;
    }
    run_with(args)
}

/// [`run`] with the flags already parsed: `zc setup` signs in through here.
pub(crate) fn run_with(args: LoginArgs) -> i32 {
    let json = args.json;
    let emit_error = |m: &str| {
        if json {
            println!(
                "{}",
                json_event("error", serde_json::json!({ "message": m }))
            );
        } else {
            eprintln!("{m}");
        }
    };

    crate::credentials::load_into_env();

    // `--staging` (or `ZAKURO_ENV=staging`) points init at the staging dashboard.
    // An explicit `ZAKURO_API_URL` still wins over both.
    let api_url = if args.staging && std::env::var("ZAKURO_API_URL").is_err() {
        crate::credentials::STAGING_API_URL.to_string()
    } else {
        crate::credentials::default_api_url()
    };

    let has_key = std::env::var("ZAKURO_API_KEY")
        .map(|k| !k.trim().is_empty())
        .unwrap_or(false);
    let force = args.force;
    // `--json` never connects the mesh: its output is not JSON, and the app
    // brings sharing up through the agent once signed in.
    let no_connect = args.no_connect || json;
    if json && has_key && !force {
        println!(
            "{}",
            json_event(
                "signed_in",
                serde_json::json!({ "already": true, "api_url": api_url })
            )
        );
        if no_connect {
            return 0;
        }
    }
    match plan(has_key, force, no_connect) {
        Plan::ReportOnly if json => return 0,
        Plan::ReportOnly => {
            eprintln!("Already signed in (→ {api_url}).");
            eprintln!("  Connect with:   zc connect");
            eprintln!("  Re-auth with:   zc login --force");
            return 0;
        }
        Plan::ConnectMesh => {
            // Already authenticated: go straight to the mesh rather than printing
            // a second command to run. `zc login` then means "get this machine
            // ready" whatever state it starts in, matching a fresh sign-in.
            eprintln!("Already signed in (→ {api_url}).");
            eprintln!("  Connecting to the zakuro mesh…");
            // Exit 0 even when the mesh is unreachable: this command's contract
            // is "am I authenticated", it has always returned 0 here, and a
            // flaky network should not start failing scripts that re-run it.
            connect_mesh();
            return 0;
        }
        Plan::SignIn => {}
    }

    if args.password {
        return password_sign_in(&api_url, no_connect, json, &emit_error);
    }

    // ── start ──────────────────────────────────────────────────────────
    // Browser device-code sign-in. Not every dashboard exposes it yet; when the
    // endpoint is missing (404) or unreachable we fall back to explicit guidance
    // rather than dumping a raw error — the user can always set ZAKURO_API_KEY.
    let start_url = format!("{}/api/auth/cli/start", api_url.trim_end_matches('/'));
    let start_send = ureq::post(&start_url)
        .config()
        .http_status_as_error(false)
        .build()
        .header("Content-Type", "application/json")
        .send(start_body(&device_name()).as_str());
    let start_resp = match start_send {
        Ok(r) if r.status().as_u16() == 200 => r,
        Ok(r) if r.status().as_u16() == 404 => {
            emit_error(&format!(
                "Browser sign-in isn't available on {api_url} (device-code endpoint not found)."
            ));
            if !json {
                print_connect_guidance();
            }
            // With a working key already set, this isn't a real failure.
            return if has_key { 0 } else { 1 };
        }
        Ok(r) => {
            emit_error(&format!(
                "Sign-in could not start on {api_url}: HTTP {}",
                r.status().as_u16()
            ));
            if !json {
                print_connect_guidance();
            }
            return 1;
        }
        Err(e) => {
            emit_error(&format!("Could not reach {api_url}: {e}"));
            if !json {
                print_connect_guidance();
            }
            return 1;
        }
    };
    let start_body = match start_resp.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            emit_error(&format!("Failed to read start response: {e}"));
            return 1;
        }
    };
    let start: serde_json::Value = match serde_json::from_str(&start_body) {
        Ok(v) => v,
        Err(e) => {
            emit_error(&format!("Failed to parse start response: {e}"));
            return 1;
        }
    };

    let device_code = start["device_code"].as_str().unwrap_or("").to_string();
    let user_code = start["user_code"].as_str().unwrap_or("");
    let verification_uri = start["verification_uri"].as_str().unwrap_or("");
    let interval = start["interval"].as_u64().unwrap_or(5);
    let expires_in = start["expires_in"].as_u64().unwrap_or(300);
    let url = prefilled_url(
        verification_uri,
        user_code,
        start["verification_uri_complete"].as_str(),
    );

    // Device-code polling below is the one completion path: the hub has no
    // localhost-callback redirect for `zc login` yet, so even when the
    // browser opens here zc learns of the approval by polling.
    let opened = should_open_browser(args.no_browser, |k| std::env::var(k).ok())
        && open_browser(&url).is_ok();
    if json {
        println!(
            "{}",
            json_event(
                "code",
                serde_json::json!({
                    "user_code": user_code,
                    "url": url,
                    "expires_in": expires_in,
                    "browser_opened": opened,
                    "api_url": api_url,
                })
            )
        );
    } else if opened {
        println!("\n  Opened your browser to sign in. If it didn't open, go to:");
        println!("    {url}");
        println!("  and check that it shows the code:  {user_code}\n");
    } else {
        println!("\n  To sign in, open this URL on any device:");
        println!("    {url}");
        println!("  and check that it shows the code:  {user_code}\n");
    }

    // ── poll ───────────────────────────────────────────────────────────
    let poll_url = format!("{}/api/auth/cli/poll", api_url.trim_end_matches('/'));
    let poll_start = Instant::now();
    loop {
        std::thread::sleep(Duration::from_secs(interval));

        if poll_start.elapsed().as_secs() >= expires_in {
            emit_error("Code expired — run `zc login` again");
            return 1;
        }

        let payload = serde_json::to_string(&serde_json::json!({"device_code": &device_code}))
            .unwrap_or_default();

        let (status, resp_body) = match ureq::post(&poll_url)
            .config()
            .http_status_as_error(false)
            .build()
            .header("Content-Type", "application/json")
            .send(payload.as_str())
        {
            Ok(r) => {
                let s = r.status().as_u16();
                let b = r.into_body().read_to_string().unwrap_or_default();
                (s, b)
            }
            Err(_) => continue, // transient network error — keep polling
        };

        match decide(status, &resp_body) {
            Decision::Pending if json => {}
            Decision::Pending => {
                print!(".");
                use std::io::Write;
                let _ = std::io::stdout().flush();
            }
            Decision::Approved(key) => {
                if let Err(e) = crate::credentials::save(&key, Some(&api_url)) {
                    emit_error(&format!("signed in but could not write credentials: {e}"));
                    return 1;
                }
                // Export into THIS process so the mesh step below sees the key it
                // just minted — otherwise `vpn::ensure` (which reads the env) fails
                // with "p2p requires ZAKURO_API_KEY" immediately after a successful
                // sign-in.
                std::env::set_var("ZAKURO_API_KEY", &key);
                std::env::set_var("ZAKURO_API_URL", &api_url);
                if json {
                    println!(
                        "{}",
                        json_event(
                            "signed_in",
                            serde_json::json!({ "already": false, "api_url": api_url })
                        )
                    );
                } else {
                    println!("\n{}", approved_message(&resp_body));
                }
                match post_sign_in(no_connect) {
                    PostSignIn::SkipMesh => {
                        println!(
                            "  Signed in. Skipping the mesh (--no-connect); connect later with zc connect."
                        );
                        return 0;
                    }
                    PostSignIn::ConnectMesh => {
                        println!("  Connecting to the zakuro mesh…");
                        // Unlike the already-signed-in path, a fresh sign-in reports a
                        // mesh failure as a failure: the user asked to get set up now
                        // and did not, so exiting 0 would misreport a half-finished
                        // setup.
                        return if connect_mesh() { 0 } else { 1 };
                    }
                }
            }
            Decision::Failed(msg) => {
                emit_error(&msg);
                return 1;
            }
        }
    }
}

/// `{"email","password"}` from the first stdin line. Never from argv, where
/// `ps` would show the password.
pub(crate) fn read_password_creds(line: &str) -> Result<(String, String), String> {
    let v: serde_json::Value = serde_json::from_str(line.trim())
        .map_err(|_| "expected {\"email\":…,\"password\":…} on stdin".to_string())?;
    let email = v["email"].as_str().unwrap_or("").trim().to_string();
    let password = v["password"].as_str().unwrap_or("").to_string();
    if email.is_empty() || password.is_empty() {
        return Err("Enter your email and password.".into());
    }
    Ok((email, password))
}

/// What the hub's `POST /api/auth/login` answer means for the user.
pub(crate) fn login_error(status: u16, body: &str) -> String {
    let detail = serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|v| v["detail"].as_str().map(str::to_string));
    match status {
        401 => "Wrong email or password.".into(),
        403 => detail.unwrap_or_else(|| "This account is disabled.".into()),
        429 => "Too many attempts. Wait a minute and try again.".into(),
        422 => "Enter a valid email and password.".into(),
        s => detail.unwrap_or_else(|| format!("The hub answered HTTP {s}.")),
    }
}

fn post_json(
    url: &str,
    body: &serde_json::Value,
    bearer: Option<&str>,
) -> Result<(u16, String), String> {
    let mut req = ureq::post(url)
        .config()
        .http_status_as_error(false)
        .timeout_global(Some(Duration::from_secs(30)))
        .build()
        .header("Content-Type", "application/json");
    if let Some(t) = bearer {
        req = req.header("Authorization", &format!("Bearer {t}"));
    }
    let r = req
        .send(body.to_string().as_str())
        .map_err(|e| e.to_string())?;
    let s = r.status().as_u16();
    Ok((s, r.into_body().read_to_string().unwrap_or_default()))
}

/// `zc login --password`: the device-code handshake with zc approving its own
/// code, so the machine still gets a revocable per-device key (listed under
/// Signed-in devices) and the password is never stored. Uses only the hub's
/// existing routes: `cli/start`, `/api/auth/login`, `cli/approve`, `cli/poll`.
fn password_sign_in(api_url: &str, no_connect: bool, json: bool, emit_error: &dyn Fn(&str)) -> i32 {
    let mut line = String::new();
    let _ = std::io::stdin().read_line(&mut line);
    let (email, password) = match read_password_creds(&line) {
        Ok(c) => c,
        Err(m) => {
            emit_error(&m);
            return 1;
        }
    };
    let base = api_url.trim_end_matches('/');
    let unreachable = |e: String| format!("Could not reach {api_url}: {e}");

    let start: serde_json::Value = match post_json(
        &format!("{base}/api/auth/cli/start"),
        &serde_json::json!({ "device_name": device_name() }),
        None,
    ) {
        Ok((200, b)) => serde_json::from_str(&b).unwrap_or_default(),
        Ok((s, _)) => {
            emit_error(&format!("Sign-in could not start on {api_url}: HTTP {s}"));
            return 1;
        }
        Err(e) => {
            emit_error(&unreachable(e));
            return 1;
        }
    };
    let device_code = start["device_code"].as_str().unwrap_or("").to_string();
    let user_code = start["user_code"].as_str().unwrap_or("").to_string();

    let session = match post_json(
        &format!("{base}/api/auth/login"),
        &serde_json::json!({ "email": email, "password": password }),
        None,
    ) {
        Ok((200, b)) => serde_json::from_str::<serde_json::Value>(&b)
            .ok()
            .and_then(|v| v["access_token"].as_str().map(str::to_string)),
        Ok((s, b)) => {
            emit_error(&login_error(s, &b));
            return 1;
        }
        Err(e) => {
            emit_error(&unreachable(e));
            return 1;
        }
    };
    let Some(session) = session else {
        emit_error("The hub signed you in but sent no session.");
        return 1;
    };

    match post_json(
        &format!("{base}/api/auth/cli/approve"),
        &serde_json::json!({ "user_code": user_code }),
        Some(&session),
    ) {
        Ok((200, _)) => {}
        Ok((s, b)) => {
            emit_error(&format!(
                "Could not approve this device: {}",
                login_error(s, &b)
            ));
            return 1;
        }
        Err(e) => {
            emit_error(&unreachable(e));
            return 1;
        }
    }

    // Approved: the first poll mints the key. A few retries cover a replica lag.
    for _ in 0..5 {
        if let Ok((s, b)) = post_json(
            &format!("{base}/api/auth/cli/poll"),
            &serde_json::json!({ "device_code": device_code }),
            None,
        ) {
            match decide(s, &b) {
                Decision::Approved(key) => {
                    if let Err(e) = crate::credentials::save(&key, Some(api_url)) {
                        emit_error(&format!("signed in but could not write credentials: {e}"));
                        return 1;
                    }
                    std::env::set_var("ZAKURO_API_KEY", &key);
                    std::env::set_var("ZAKURO_API_URL", api_url);
                    if json {
                        println!(
                            "{}",
                            json_event(
                                "signed_in",
                                serde_json::json!({ "already": false, "api_url": api_url, "email": email })
                            )
                        );
                    } else {
                        println!("{}", approved_message(&b));
                    }
                    return if no_connect || connect_mesh() { 0 } else { 1 };
                }
                Decision::Pending => {}
                Decision::Failed(m) => {
                    emit_error(&m);
                    return 1;
                }
            }
        }
        std::thread::sleep(Duration::from_secs(1));
    }
    emit_error("The hub approved this device but has not issued its key yet. Try again.");
    1
}

pub fn open_browser(url: &str) -> std::io::Result<()> {
    let cmd = if cfg!(target_os = "macos") {
        "open"
    } else {
        "xdg-open"
    };
    std::process::Command::new(cmd)
        .arg(url)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map(|_| ())
}

#[cfg(test)]
mod tests {
    #[test]
    fn password_creds_come_from_one_json_line() {
        let ok =
            super::read_password_creds("{\"email\":\" a@b.c \",\"password\":\" p w \"}\n").unwrap();
        assert_eq!(
            ok,
            ("a@b.c".to_string(), " p w ".to_string()),
            "email trimmed, password verbatim"
        );
        assert!(super::read_password_creds("").is_err());
        assert!(super::read_password_creds("{\"email\":\"a@b.c\"}").is_err());
        assert!(super::LoginArgs::parse(&["--json".into(), "--password".into()]).password);
    }

    #[test]
    fn login_errors_read_like_a_form() {
        assert_eq!(super::login_error(401, "{}"), "Wrong email or password.");
        assert!(super::login_error(429, "").contains("Too many"));
        assert_eq!(
            super::login_error(403, "{\"detail\":\"Account is disabled\"}"),
            "Account is disabled"
        );
        assert_eq!(super::login_error(500, ""), "The hub answered HTTP 500.");
    }

    #[test]
    fn decision_maps_statuses() {
        assert!(matches!(super::decide(428, ""), super::Decision::Pending));
        assert!(matches!(
            super::decide(200, "{\"api_key\":\"zk_1_x\"}"),
            super::Decision::Approved(ref k) if k == "zk_1_x"
        ));
        assert!(matches!(super::decide(410, ""), super::Decision::Failed(_)));
    }

    // `zc login` used to stop at "Already signed in" and print `zc vpn connect`
    // for the user to run themselves, so getting a machine ready took two
    // commands on every run after the first. It now connects the mesh itself.
    #[test]
    fn already_signed_in_connects_the_mesh() {
        assert_eq!(super::plan(true, false, false), super::Plan::ConnectMesh);
    }

    #[test]
    fn no_key_signs_in() {
        assert_eq!(super::plan(false, false, false), super::Plan::SignIn);
    }

    // --force re-auths even with a key present, and outranks --no-connect.
    #[test]
    fn force_signs_in_again() {
        assert_eq!(super::plan(true, true, false), super::Plan::SignIn);
        assert_eq!(super::plan(true, true, true), super::Plan::SignIn);
    }

    // Escape hatch for callers relying on this path having no side effects.
    #[test]
    fn no_connect_keeps_the_old_report_only_behaviour() {
        assert_eq!(super::plan(true, false, true), super::Plan::ReportOnly);
    }

    // An empty/whitespace key is not a key: `run` treats it as absent, so a
    // blank ZAKURO_API_KEY must still route to sign-in rather than the mesh.
    #[test]
    fn blank_key_is_not_signed_in() {
        assert_eq!(super::plan(false, false, true), super::Plan::SignIn);
    }

    #[test]
    fn start_sends_this_macs_device_name() {
        let body: serde_json::Value =
            serde_json::from_str(&super::start_body("jeans-mbp")).unwrap();
        assert_eq!(body, serde_json::json!({ "device_name": "jeans-mbp" }));
        let name = super::device_name();
        assert!(!name.is_empty() && name.chars().count() <= 128, "{name}");
    }

    #[test]
    fn approval_says_when_the_hub_minted_a_device_key() {
        assert!(
            super::approved_message(r#"{"api_key":"zk_1_x","token_type":"device"}"#)
                .contains("Device key")
        );
        assert_eq!(
            super::approved_message(r#"{"api_key":"x","token_type":"session","expires_in":43200}"#),
            "✓ Signed in. Key saved to ~/.zakuro/credentials."
        );
        assert_eq!(
            super::approved_message("not json"),
            "✓ Signed in. Key saved to ~/.zakuro/credentials."
        );
    }

    // A device name is truncated by characters, never bytes: slicing a
    // multi-byte string at a raw byte offset can land mid-codepoint and panic.
    #[test]
    fn device_name_clamp_truncates_multibyte_chars_not_bytes() {
        let long_multibyte: String = "é".repeat(200);
        let clamped = super::clamp_device_name(&long_multibyte);
        assert_eq!(clamped.chars().count(), 128);
    }

    #[test]
    fn device_name_clamp_defaults_empty_or_blank_to_zc_cli() {
        assert_eq!(super::clamp_device_name(""), "zc CLI");
        assert_eq!(super::clamp_device_name("   "), "zc CLI");
    }

    #[test]
    fn device_name_clamp_passes_short_names_through() {
        assert_eq!(super::clamp_device_name("jeans-mbp"), "jeans-mbp");
    }

    fn args(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn login_args_help_long_flag() {
        let a = super::LoginArgs::parse(&args(&["--help"]));
        assert!(a.help);
    }

    #[test]
    fn login_args_help_short_flag() {
        let a = super::LoginArgs::parse(&args(&["-h"]));
        assert!(a.help);
    }

    #[test]
    fn login_args_json_and_events() {
        assert!(super::LoginArgs::parse(&args(&["--json"])).json);
        let line = super::json_event("code", serde_json::json!({"user_code": "KQ7F-2MZD"}));
        let v: serde_json::Value = serde_json::from_str(&line).unwrap();
        assert_eq!(
            (v["event"].as_str(), v["user_code"].as_str()),
            (Some("code"), Some("KQ7F-2MZD"))
        );
    }

    #[test]
    fn login_args_no_browser() {
        assert!(super::LoginArgs::parse(&args(&["--no-browser"])).no_browser);
        assert!(!super::LoginArgs::parse(&args(&[])).no_browser);
    }

    #[test]
    fn the_sign_in_url_carries_the_code() {
        assert_eq!(
            super::prefilled_url("https://hub.example/activate", "WXYZ-2345", None),
            "https://hub.example/activate?code=WXYZ-2345"
        );
        assert_eq!(
            super::prefilled_url("https://hub.example/activate?x=1", "AB CD", None),
            "https://hub.example/activate?x=1&code=AB%20CD"
        );
        assert_eq!(
            super::prefilled_url(
                "https://hub.example/activate",
                "WXYZ-2345",
                Some("https://hub.example/device?code=WXYZ-2345")
            ),
            "https://hub.example/device?code=WXYZ-2345",
            "the hub's own complete URI wins"
        );
        assert_eq!(
            super::prefilled_url("https://hub.example/activate", "", None),
            "https://hub.example/activate"
        );
    }

    #[test]
    fn no_browser_over_ssh_or_when_asked() {
        let env = |pairs: &'static [(&'static str, &'static str)]| {
            move |k: &str| {
                pairs
                    .iter()
                    .find(|(n, _)| *n == k)
                    .map(|(_, v)| v.to_string())
            }
        };
        assert!(!super::should_open_browser(true, env(&[("DISPLAY", ":0")])));
        assert!(!super::should_open_browser(
            false,
            env(&[
                ("SSH_CONNECTION", "1.2.3.4 5 6.7.8.9 22"),
                ("DISPLAY", ":0")
            ])
        ));
        assert!(!super::should_open_browser(
            false,
            env(&[("SSH_TTY", "/dev/pts/0"), ("DISPLAY", ":0")])
        ));
        assert!(super::should_open_browser(false, env(&[("DISPLAY", ":0")])));
        assert_eq!(
            super::should_open_browser(false, env(&[])),
            !cfg!(target_os = "linux"),
            "Linux needs a display; macOS always has one"
        );
    }

    #[test]
    fn login_args_force_and_no_connect() {
        let a = super::LoginArgs::parse(&args(&["--force", "--no-connect"]));
        assert!(a.force);
        assert!(a.no_connect);
        assert!(!a.help);
        assert!(!a.staging);
    }

    #[test]
    fn login_args_plain_sign_in_has_no_flags() {
        let a = super::LoginArgs::parse(&args(&[]));
        assert!(!a.help && !a.force && !a.no_connect && !a.staging);
    }

    #[test]
    fn login_args_staging_flag() {
        let a = super::LoginArgs::parse(&args(&["--staging"]));
        assert!(a.staging);
    }

    // After a fresh or forced sign-in, --no-connect must skip the mesh instead
    // of only affecting the already-signed-in `plan()` path.
    #[test]
    fn post_sign_in_no_connect_skips_the_mesh() {
        assert_eq!(super::post_sign_in(true), super::PostSignIn::SkipMesh);
    }

    #[test]
    fn post_sign_in_default_connects_the_mesh() {
        assert_eq!(super::post_sign_in(false), super::PostSignIn::ConnectMesh);
    }

    // Ruling L1: `zc login` gives a keyless device its own node key before it
    // joins the mesh; as root it leaves the user's home alone (R13).
    #[test]
    fn node_key_step_matrix() {
        use super::{node_key_step, NodeKeyStep};
        assert_eq!(node_key_step(false, true), NodeKeyStep::Present);
        assert_eq!(node_key_step(true, true), NodeKeyStep::Present);
        assert_eq!(node_key_step(false, false), NodeKeyStep::Create);
        assert_eq!(node_key_step(true, false), NodeKeyStep::SkipAsRoot);
    }

    /// A fresh temp dir per test, never the real `~/.zakuro`.
    fn key_dir(tag: &str) -> std::path::PathBuf {
        let d = std::env::temp_dir().join(format!("zc-init-node-key-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn login_creates_the_node_key_when_not_root() {
        let dir = key_dir("create");
        assert_eq!(
            super::ensure_node_key_in(Some(dir.clone()), false),
            super::NodeKeyStep::Create
        );
        let path = dir.join("node_key");
        assert!(path.exists(), "node_key created");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600, "{mode:o}");
        }
        let fp = crate::vpn::profile::device_fingerprint_in(Some(dir.clone()))
            .expect("the profile request can now send this device's fingerprint");
        assert_eq!(fp.len(), 16, "{fp}");
        assert!(
            fp.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f')),
            "{fp}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn login_leaves_an_existing_node_key_alone() {
        let dir = key_dir("present");
        crate::broker::node_identity::NodeKey::load_or_create_in(Some(dir.clone()));
        let before = std::fs::read(dir.join("node_key")).unwrap();
        for is_root in [false, true] {
            assert_eq!(
                super::ensure_node_key_in(Some(dir.clone()), is_root),
                super::NodeKeyStep::Present
            );
            assert_eq!(std::fs::read(dir.join("node_key")).unwrap(), before);
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn login_as_root_creates_no_node_key() {
        let dir = key_dir("root");
        assert_eq!(
            super::ensure_node_key_in(Some(dir.clone()), true),
            super::NodeKeyStep::SkipAsRoot
        );
        assert!(!dir.join("node_key").exists());
        let _ = std::fs::remove_dir_all(&dir);
    }
}