stratum-node-cli 0.1.0-alpha.4

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
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
//! `stratum`: the client for a Stratum node, for its administrator on the
//! loopback API and for tenants through the gate.
//!
//! This file only parses the command line; the commands live in the
//! `stratum_node_cli` library.

use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

use clap::{Args, Parser, Subcommand};
use stratum_node_cli::{
    exit, parse_duration, ApplicationAction, ApplyOptions, CanonicalOrigin, CliError, Confirmation,
    ConnectAddress, ExportOptions, GateTarget, InstallOptions, InviteOptions, JoinOptions,
    LoopbackUrl, Output, OutputFormat, ProfileInitOptions, PutOptions, RemoveOptions, Session,
    SetupOptions, SuspendOptions, WriteCondition, DEFAULT_ENFORCEMENT_WAIT, DEFAULT_URL,
};
use stratum_node_core::{ApplicationId, DidNostr, InstallationId, InvitationId, WorkspaceMode};

/// The exit-code table shown at the end of `--help`.
const EXIT_CODES: &str = "\
Exit codes:
   0  success; for `status`, the node is ready
   1  local failure (key, token or resume file, clock, output)
   2  the node could not be reached
   3  status: the node is unconfigured
   4  status: the node is degraded
   5  the node's response does not follow the API contract
   6  previewed but not applied: no confirmation (pass --yes)
   7  a local check refused the node's answer (claim body, backup manifest,
      admission notice, join probe, a profile card that does not name you,
      an offered grant the manifest does not render), or an ACL that would
      give an application acl:Control
   8  a bounded wait ran out: join (pod not provisioned within --wait-secs;
      rerun to continue) or member suspend --wait (not yet enforced)
   9  export: written, but entries changed, vanished or were skipped
  10  bad_request            11  unauthorized          12  forbidden
  13  not_found              14  conflict              15  payload_too_large
  16  unsupported_media_type 17  invalid (also an invalid preview)
  18  too_many_challenges    19  backup_refused        20  internal
  21  unknown server error code                    22  request_timeout
  23  capacity_exhausted     24  invitation_refused    25  invitations_disabled
  26  gate_unavailable       27  too_many_requests     28  misdirected_request
  29  method_not_allowed     30  insufficient_storage  31  precondition_failed
  32  bad_gateway            33  gateway_timeout       34  suspended
  35  archive_required       36  pod_data_present      38  pod_unavailable
  39  workspace_unavailable  40  application_unavailable
  41  image_absent or image_has_volumes
  42  app install: an ACL did not read back as written, or consent was refused
      (what was written is removed)
  43  app withdraw/cleanup: the ACL cleanup is still pending
  44  an ACL holds a statement the client does not evaluate (nothing written)
  45  runner_unavailable     46  signer_unavailable
  64  invalid command line

Server errors are printed as `code: message`.";

/// The client for a Stratum node.
///
/// Administrator commands talk to the node's loopback API (--url) over plain
/// HTTP and sign requests with the operator's Nostr key. Tenant commands
/// (join, pod, export, profile, app) reach the node's gate (--origin,
/// --connect) and sign with the tenant's own key. `profile show` needs no key at all.
/// PRE-RELEASE (0.1.0-alpha): commands and output may change.
#[derive(Debug, Parser)]
#[command(name = "stratum", version, after_help = EXIT_CODES)]
struct Cli {
    /// Node API URL; the host must be an address in 127.0.0.0/8 (such as
    /// 127.0.0.1), `[::1]` or localhost, which is dialled as 127.0.0.1
    /// without a name lookup (no TLS in Step 1). For sign-challenge: the
    /// claim URL.
    #[arg(long, global = true, env = "STRATUM_URL", default_value = DEFAULT_URL)]
    url: LoopbackUrl,

    /// Key file (one nsec line, mode 0600): the operator's for administrator
    /// commands, the tenant's own for join, pod, export and profile init.
    #[arg(long, global = true, env = "STRATUM_KEY_FILE", value_name = "FILE")]
    key_file: Option<PathBuf>,

    /// Write machine-readable JSON to standard output.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Create or inspect an operator key file.
    Key {
        #[command(subcommand)]
        command: KeyCommand,
    },
    /// Show the node's readiness (exit 0 ready, 3 unconfigured, 4 degraded,
    /// 2 unreachable).
    Status,
    /// Read, preview and apply configuration.
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Claim an unconfigured node with the bootstrap token and this key.
    Setup(SetupArgs),
    /// Sign a claim body offline and print the Authorization header value.
    ///
    /// Refuses a body that names another claimant, another node than
    /// --expect-node, or has expired. The configuration hash in the body
    /// cannot be checked offline and is signed as issued; `stratum setup`
    /// checks it. Uses --url as the claim URL: a bare origin gets
    /// /api/v1/bootstrap/claim appended, and a URL with a path must end in
    /// exactly that path. It must equal the `url` in the challenge
    /// response. No network access.
    SignChallenge {
        /// File holding the claim body bytes exactly as the node issued them.
        #[arg(long, value_name = "FILE")]
        claim_body_file: PathBuf,

        /// The node DID the claim must name, as stratumd printed it at start
        /// (never taken from the claim file).
        #[arg(long, value_name = "DID")]
        expect_node: DidNostr,
    },
    /// Audit log operations.
    Audit {
        #[command(subcommand)]
        command: AuditCommand,
    },
    /// Ask the node for a backup and verify its signed manifest.
    Backup {
        /// Operation ID to reuse when retrying; random when omitted.
        #[arg(long, value_name = "ID")]
        operation_id: Option<String>,

        /// Refuse unless /readyz reports this node DID.
        #[arg(long, value_name = "DID")]
        expect_node: Option<DidNostr>,
    },
    /// Issue, list and revoke invitations (administrator).
    Invite {
        #[command(subcommand)]
        command: InviteCommand,
    },
    /// List, show, repair, cancel, suspend, resume, archive and remove
    /// members (administrator).
    Member {
        #[command(subcommand)]
        command: MemberCommand,
    },
    /// Redeem an invitation with this key and activate the pod (tenant).
    ///
    /// Shows the node's admission notice and checks it is the one this
    /// client knows and that the node is the one the invitation names, asks
    /// for confirmation, redeems, waits for the pod, writes and reads a
    /// probe, and confirms. Safe to rerun after a partial run.
    Join(JoinArgs),
    /// Read and write resources in a pod (tenant).
    ///
    /// PATH is relative to your own pod root, or absolute `/pods/<pk>/…` for
    /// another member's pod (which needs their grant). Names may use only
    /// A-Z a-z 0-9 - . _ ~ (no spaces, no percent-encoding).
    Pod {
        #[command(subcommand)]
        command: PodCommand,
    },
    /// Export your own pod to a .tar.zst archive and a manifest (tenant).
    Export(ExportArgs),
    /// Write your public profile document, or read anyone's.
    ///
    /// The profile is `/pods/<pk>/profile/card`: a short Turtle document
    /// saying which key owns the pod, readable by anyone without a
    /// signature, even while the owner is suspended.
    Profile {
        #[command(subcommand)]
        command: ProfileCommand,
    },
    /// Install, inspect, run and withdraw applications in your pod (tenant).
    ///
    /// Every `app` command also shows any withdrawn installation whose ACL
    /// cleanup has not been reported yet.
    App {
        #[command(subcommand)]
        command: AppCommand,
    },
    /// Approve, list, withdraw and disable applications (administrator).
    Application {
        #[command(subcommand)]
        command: ApplicationCommand,
    },
    /// List every installation on the node: owner, application, state, key
    /// reasons, job counts and grant state (administrator).
    Installations,
}

#[derive(Debug, Subcommand)]
enum AppCommand {
    /// List the applications this node has approved, with their manifests.
    Catalogue {
        #[command(flatten)]
        gate: GateArgs,
    },
    /// Install an application: preview the ACL changes, ask, write each
    /// granted container's ACL conditionally, read it back, then consent.
    ///
    /// Prints the diff of each ACL, the owner, the application, its version
    /// and image ID, and the operator's access (root on the host). The
    /// application is never given acl:Control. An ACL holding a statement
    /// the client does not evaluate is refused (exit 44).
    Install(InstallArgs),
    /// List your installations.
    List {
        #[command(flatten)]
        gate: GateArgs,
    },
    /// Show one installation: state, key, grant, pending cleanup,
    /// enforcement and job counts.
    Show {
        /// The installation (32 hex characters).
        installation: InstallationId,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// List an installation's jobs and their results.
    Jobs {
        /// The installation (32 hex characters).
        installation: InstallationId,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Create the job for one period now, if it has none.
    Run(RunArgs),
    /// Withdraw an installation, then remove its authorisation from each
    /// granted container's ACL and report the cleanup.
    Withdraw(InstallationArgs),
    /// Finish an interrupted ACL cleanup of a withdrawn installation.
    Cleanup(CleanupArgs),
    /// Enable an installation's key again after a restore.
    Resume(InstallationArgs),
}

#[derive(Debug, Args)]
struct InstallArgs {
    /// The application (32 hex characters), as `app catalogue` lists it.
    application: ApplicationId,

    /// Run every SECONDS (300 to 604800); 0, the default, is manual runs
    /// only.
    #[arg(long = "schedule", value_name = "SECONDS", default_value_t = 0)]
    schedule_secs: u64,

    /// The workspace to grant: none (default), read or write; no more than
    /// the manifest allows.
    #[arg(long, value_name = "MODE", default_value = "none")]
    workspace: WorkspaceMode,

    /// Operation ID of the create request, to continue an installation an
    /// earlier run created (repeat its --schedule and --workspace).
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    #[command(flatten)]
    gate: GateArgs,

    /// Write the ACLs and consent without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Args)]
struct RunArgs {
    /// The installation (32 hex characters).
    installation: InstallationId,

    /// The period to run.
    #[arg(long, value_name = "N")]
    period: u64,

    /// Operation ID to reuse when retrying; random when omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    #[command(flatten)]
    gate: GateArgs,

    /// Proceed without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Args)]
struct CleanupArgs {
    /// The installation (32 hex characters).
    installation: InstallationId,

    #[command(flatten)]
    gate: GateArgs,

    /// Proceed without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Args)]
struct InstallationArgs {
    /// The installation (32 hex characters).
    installation: InstallationId,

    /// Operation ID to reuse when retrying; random when omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    #[command(flatten)]
    gate: GateArgs,

    /// Proceed without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Subcommand)]
enum ApplicationCommand {
    /// Approve the application a manifest describes. The node refuses it
    /// unless the image is present on the tenant daemon and declares no
    /// volumes.
    Add(ApplicationAddArgs),
    /// List every application with its state and installation count.
    List,
    /// Stop new installations of an application; existing ones keep running.
    Withdraw(ApplicationArgs),
    /// Make a withdrawn application installable again.
    Approve(ApplicationArgs),
    /// Emergency stop, final: disable every installation's key and stop its
    /// jobs.
    Disable(ApplicationArgs),
}

#[derive(Debug, Args)]
struct ApplicationAddArgs {
    /// The manifest, JSON (at most 256 KiB).
    manifest: PathBuf,

    /// Operation ID to reuse when retrying; random when omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    /// Proceed without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Args)]
struct ApplicationArgs {
    /// The application (32 hex characters).
    application: ApplicationId,

    /// Operation ID to reuse when retrying; random when omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    /// Proceed without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Subcommand)]
enum ProfileCommand {
    /// Write the standard profile card and its public-read ACL into your
    /// own pod (tenant), changing nothing already right.
    ///
    /// A card that names you is left alone and only a missing ACL is
    /// written; an existing ACL is never changed. A card that does not name
    /// you is reported and left alone unless --replace. Running it again
    /// changes nothing. `join` does this for you.
    Init {
        /// Replace an existing card that does not name you with the
        /// standard card (only if it has not changed since it was read).
        #[arg(long)]
        replace: bool,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Print a member's public profile, read without a signature (no key
    /// needed). Exit 13 when there is no public profile.
    Show {
        /// The member's did:nostr.
        did: DidNostr,

        #[command(flatten)]
        gate: GateArgs,
    },
}

#[derive(Debug, Subcommand)]
enum InviteCommand {
    /// Issue an invitation for one identity and print the invitee's
    /// `stratum join` command line.
    Create {
        /// The did:nostr of the person invited.
        did: DidNostr,

        /// Lifetime: seconds, or a number with s, m, h or d (at most 30d);
        /// the node's `membership.invitation_ttl_secs` when omitted.
        #[arg(long, value_name = "DURATION", value_parser = parse_duration)]
        expires_in: Option<Duration>,

        /// The gate address printed in the invitee's command line;
        /// 127.0.0.1:7461 when omitted.
        #[arg(long, value_name = "HOST:PORT")]
        connect: Option<ConnectAddress>,

        /// Operation ID to reuse when retrying; random when omitted.
        #[arg(long, value_name = "ID")]
        operation_id: Option<String>,

        /// Refuse unless /readyz reports this node DID.
        #[arg(long, value_name = "DID")]
        expect_node: Option<DidNostr>,
    },
    /// List invitations and their state.
    List,
    /// Revoke an invitation that is still issued.
    Revoke {
        /// The invitation identifier (32 hex characters).
        invitation: InvitationId,

        /// Operation ID to reuse when retrying; random when omitted.
        #[arg(long, value_name = "ID")]
        operation_id: Option<String>,
    },
}

#[derive(Debug, Subcommand)]
enum MemberCommand {
    /// List members, their state and pod, and the capacity in use.
    List,
    /// Show one member now: state, generation, suspension, enforcement,
    /// quota, last measurement, purge time and archive.
    Show {
        /// The member's did:nostr.
        did: DidNostr,
    },
    /// Run provisioning again for a member (restores a missing root ACL).
    Repair(MemberArgs),
    /// Cancel a reserved member, releasing its slot.
    Cancel(MemberArgs),
    /// Suspend a provisioned or active member: every signed request by
    /// them, or to their pod, is refused. Needs no member key.
    ///
    /// Reports `enforcing` (the gate may still admit new requests) or
    /// `enforced` (it admits none). --wait reads the member until enforced.
    Suspend(SuspendArgs),
    /// Return a suspended member to the state they had.
    Resume(MemberArgs),
    /// Take the node's encrypted archive of a suspended member's pod (the
    /// suspension must be enforced; writes pause while it runs).
    Archive(MemberArgs),
    /// Remove a suspended member: frees the slot, makes the pod
    /// unreachable; the data stays on disk until the operator purges it.
    ///
    /// Requires an archive taken during this suspension unless
    /// --no-archive. Other members' ACLs naming the key are not changed.
    Remove(RemoveArgs),
}

// `--wait`'s default below is written as text; keep it equal to the library's.
const _: () = assert!(
    DEFAULT_ENFORCEMENT_WAIT.as_secs() == 330,
    "--wait's default_missing_value must equal DEFAULT_ENFORCEMENT_WAIT"
);

#[derive(Debug, Args)]
struct SuspendArgs {
    #[command(flatten)]
    member: MemberArgs,

    /// After suspending, wait until the suspension is enforced, for at
    /// most SECONDS (330 when given without a value). Write --wait=SECONDS.
    #[arg(
        long,
        value_name = "SECONDS",
        num_args = 0..=1,
        require_equals = true,
        default_missing_value = "330"
    )]
    wait: Option<u64>,
}

#[derive(Debug, Args)]
struct RemoveArgs {
    #[command(flatten)]
    member: MemberArgs,

    /// Remove without an archive. The waiver is part of the signed request
    /// and the node records who waived it.
    #[arg(long)]
    no_archive: bool,
}

#[derive(Debug, Args)]
struct MemberArgs {
    /// The member's did:nostr.
    did: DidNostr,

    /// Operation ID to reuse when retrying; random when omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    /// Proceed without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

/// Where tenant commands reach the node.
#[derive(Debug, Args)]
struct GateArgs {
    /// The node's canonical origin, such as `https://stratum.visionclaw.pro`;
    /// every request is signed for it and names it in Host.
    #[arg(long, env = "STRATUM_ORIGIN", value_name = "ORIGIN")]
    origin: CanonicalOrigin,

    /// The loopback address of the gate, such as 127.0.0.1:7461; plain HTTP
    /// is sent there. Required for an https:// origin.
    #[arg(long, env = "STRATUM_CONNECT", value_name = "HOST:PORT")]
    connect: Option<ConnectAddress>,
}

impl GateArgs {
    fn target(self) -> Result<GateTarget, CliError> {
        GateTarget::new(self.origin, self.connect)
    }
}

#[derive(Debug, Args)]
struct JoinArgs {
    /// The invitation identifier the administrator gave you.
    #[arg(long, value_name = "ID")]
    invitation: InvitationId,

    /// The node DID the administrator gave you; the node reached must
    /// report it.
    #[arg(long, value_name = "DID")]
    node: DidNostr,

    #[command(flatten)]
    gate: GateArgs,

    /// How long to wait for the pod to be provisioned.
    #[arg(long, value_name = "SECONDS", default_value_t = 120)]
    wait_secs: u64,

    /// Accept the notice without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Subcommand)]
enum PodCommand {
    /// List a container (your pod root when PATH is omitted).
    Ls {
        /// The container.
        #[arg(default_value = "")]
        path: String,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Read a resource to standard output or a new file.
    Get {
        /// The resource.
        path: String,

        /// Write the bytes to this new file (mode 0600) instead.
        #[arg(short = 'o', long = "output", value_name = "FILE")]
        output: Option<PathBuf>,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Write a file to a resource.
    Put(PutArgs),
    /// Delete a resource or an empty container.
    Rm(RmArgs),
    /// Read or write the ACL beside a resource or container.
    Acl {
        #[command(subcommand)]
        command: AclCommand,
    },
}

#[derive(Debug, Args)]
struct RmArgs {
    /// The resource or container.
    path: String,

    #[command(flatten)]
    gate: GateArgs,

    /// Delete without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Subcommand)]
enum AclCommand {
    /// Read the ACL beside PATH (the root ACL `/pods/<pk>.acl` for the pod
    /// root, an empty PATH).
    Get {
        /// The resource or container whose ACL is read.
        #[arg(default_value = "")]
        path: String,

        /// Write the bytes to this new file (mode 0600) instead.
        #[arg(short = 'o', long = "output", value_name = "FILE")]
        output: Option<PathBuf>,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Write FILE as the ACL beside PATH (text/turtle unless
    /// --content-type is given).
    Put(PutArgs),
}

#[derive(Debug, Args)]
struct PutArgs {
    /// The resource (for `acl put`: the resource or container whose ACL is
    /// written; "" for the pod root).
    path: String,

    /// The file whose bytes are written (at most 1 GiB; the node refuses a body over its `limits.max_pod_body_bytes`, 16 MiB by default).
    file: PathBuf,

    /// The content type; guessed from the file name when omitted.
    #[arg(long, value_name = "TYPE")]
    content_type: Option<String>,

    /// Write only if the resource's entity tag is still this one.
    #[arg(long, value_name = "ETAG", conflicts_with = "create_only")]
    if_match: Option<String>,

    /// Write only if nothing is there yet.
    #[arg(long)]
    create_only: bool,

    #[command(flatten)]
    gate: GateArgs,
}

impl PutArgs {
    fn into_parts(self) -> (PutOptions, GateArgs) {
        let condition = match (self.if_match, self.create_only) {
            (Some(etag), _) => WriteCondition::IfMatch(etag),
            (None, true) => WriteCondition::CreateOnly,
            (None, false) => WriteCondition::Always,
        };
        (
            PutOptions {
                path: self.path,
                file: self.file,
                content_type: self.content_type,
                condition,
            },
            self.gate,
        )
    }
}

#[derive(Debug, Args)]
struct ExportArgs {
    /// The archive to write, such as pod.tar.zst; the manifest goes beside
    /// it as ARCHIVE.manifest.json.
    #[arg(short = 'o', long = "output", value_name = "ARCHIVE")]
    output: PathBuf,

    /// Replace an existing archive and manifest.
    #[arg(long)]
    force: bool,

    #[command(flatten)]
    gate: GateArgs,
}

#[derive(Debug, Subcommand)]
enum KeyCommand {
    /// Generate a new operator key into a new 0600 file; prints its DID and
    /// npub only.
    Generate {
        /// The key file to create; an existing file is never overwritten.
        #[arg(long, value_name = "FILE")]
        out: PathBuf,
    },
    /// Print the DID and npub of the key in --key-file.
    Show,
}

#[derive(Debug, Subcommand)]
enum ConfigCommand {
    /// Print the configuration schema.
    Schema,
    /// Print the effective configuration and revisions.
    Show,
    /// Show what a change would do, without applying it.
    Preview(PreviewArgs),
    /// Preview a change, confirm, then apply it.
    Apply(ApplyArgs),
}

#[derive(Debug, Subcommand)]
enum AuditCommand {
    /// Print the audit checkpoint `<seq>:<hex>` and the node DID.
    Checkpoint,
}

/// `--set` and `--base-revision`, shared by preview and apply.
#[derive(Debug, Args)]
struct ChangeArgs {
    /// A change, typed by the schema: booleans `true`/`false`, integers in
    /// decimal, strings as given; lists comma-separated or by repeating
    /// --set for the same path (`path=` is the empty list).
    #[arg(long = "set", value_name = "PATH=VALUE")]
    sets: Vec<String>,

    /// The revision the change is based on; the node's head when omitted.
    #[arg(long, value_name = "N")]
    base_revision: Option<u64>,
}

#[derive(Debug, Args)]
struct PreviewArgs {
    #[command(flatten)]
    changes: ChangeArgs,
}

#[derive(Debug, Args)]
struct ApplyArgs {
    #[command(flatten)]
    changes: ChangeArgs,

    /// Operation ID to reuse when retrying; random (and printed) when
    /// omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    /// Apply without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Args)]
struct SetupArgs {
    /// The node's bootstrap token file, STATE_DIR/bootstrap-token.
    #[arg(long, value_name = "FILE")]
    token_file: PathBuf,

    /// An initial configuration change (as for `config apply`); optional:
    /// with none, the node is claimed with its seed configuration.
    #[arg(long = "set", value_name = "PATH=VALUE")]
    sets: Vec<String>,

    /// The node DID stratumd printed at start. The bootstrap token is sent
    /// only if /readyz reports it. Without it, setup trusts whatever answers
    /// on the loopback port.
    #[arg(long, value_name = "DID")]
    expect_node: Option<DidNostr>,

    /// Also print the full configuration text whose SHA-256 the claim binds.
    #[arg(long)]
    show_text: bool,

    /// Where the signed claim is saved before sending (0600); defaults to
    /// KEY_FILE.setup-resume. If it exists, it is resent unchanged.
    #[arg(long, value_name = "FILE")]
    resume_file: Option<PathBuf>,

    /// Claim without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

/// Maps the `--yes` flag of a command that changes the node.
trait YesFlag {
    /// Returns the flag's value.
    fn yes(&self) -> bool;

    /// Returns [`Confirmation::Assumed`] under `--yes`, else
    /// [`Confirmation::Prompt`].
    fn confirmation(&self) -> Confirmation {
        if self.yes() {
            Confirmation::Assumed
        } else {
            Confirmation::Prompt
        }
    }
}

impl YesFlag for ApplyArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for SetupArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for MemberArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for JoinArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for RmArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for InstallArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for RunArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for InstallationArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for ApplicationArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for CleanupArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for ApplicationAddArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

fn main() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => {
            let code = if err.use_stderr() {
                exit::USAGE
            } else {
                exit::OK
            };
            // Nothing useful can be done if printing the usage message fails.
            let _printed = err.print();
            return ExitCode::from(code);
        }
    };
    let output = Output::new(if cli.json {
        OutputFormat::Json
    } else {
        OutputFormat::Human
    });
    let session = Session::new(cli.url, cli.key_file, output);
    let result = match cli.command {
        Command::Key {
            command: KeyCommand::Generate { out },
        } => session.key_generate(&out),
        Command::Key {
            command: KeyCommand::Show,
        } => session.key_show(),
        Command::Status => session.status(),
        Command::Config { command } => match command {
            ConfigCommand::Schema => session.config_schema(),
            ConfigCommand::Show => session.config_show(),
            ConfigCommand::Preview(args) => {
                session.config_preview(&args.changes.sets, args.changes.base_revision)
            }
            ConfigCommand::Apply(args) => session.config_apply(&ApplyOptions {
                confirmation: args.confirmation(),
                sets: args.changes.sets,
                base_revision: args.changes.base_revision,
                operation_id: args.operation_id,
            }),
        },
        Command::Setup(args) => session.setup(&SetupOptions {
            confirmation: args.confirmation(),
            token_file: args.token_file,
            sets: args.sets,
            resume_file: args.resume_file,
            expect_node: args.expect_node,
            show_text: args.show_text,
        }),
        Command::SignChallenge {
            claim_body_file,
            expect_node,
        } => session.sign_challenge(&claim_body_file, &expect_node),
        Command::Audit {
            command: AuditCommand::Checkpoint,
        } => session.audit_checkpoint(),
        Command::Backup {
            operation_id,
            expect_node,
        } => session.backup(operation_id.as_deref(), expect_node.as_ref()),
        Command::Invite { command } => run_invite(&session, command),
        Command::Member { command } => run_member(&session, command),
        Command::Join(args) => {
            let confirmation = args.confirmation();
            args.gate.target().and_then(|target| {
                session.join(
                    &target,
                    &JoinOptions {
                        invitation: args.invitation,
                        node: args.node,
                        wait: Duration::from_secs(args.wait_secs),
                        confirmation,
                    },
                )
            })
        }
        Command::Pod { command } => run_pod(&session, command),
        Command::Profile { command } => run_profile(&session, command),
        Command::App { command } => run_app(&session, command),
        Command::Application { command } => run_application(&session, command),
        Command::Installations => session.installations(),
        Command::Export(args) => args.gate.target().and_then(|target| {
            session.export(
                &target,
                &ExportOptions {
                    output: args.output,
                    force: args.force,
                },
            )
        }),
    };
    match result {
        Ok(code) => ExitCode::from(code),
        Err(err) => {
            output.error(&err);
            ExitCode::from(err.exit_code())
        }
    }
}

/// Runs an `invite` command.
fn run_invite(session: &Session, command: InviteCommand) -> Result<u8, CliError> {
    match command {
        InviteCommand::Create {
            did,
            expires_in,
            connect,
            operation_id,
            expect_node,
        } => session.invite_create(&InviteOptions {
            subject: did,
            expires_in,
            operation_id,
            expect_node,
            gate: connect,
        }),
        InviteCommand::List => session.invite_list(),
        InviteCommand::Revoke {
            invitation,
            operation_id,
        } => session.invite_revoke(&invitation, operation_id.as_deref()),
    }
}

/// Runs a `member` command.
fn run_member(session: &Session, command: MemberCommand) -> Result<u8, CliError> {
    match command {
        MemberCommand::List => session.member_list(),
        MemberCommand::Show { did } => session.member_show(&did),
        MemberCommand::Suspend(args) => session.member_suspend(&SuspendOptions {
            member: args.member.did,
            confirmation: args.member.confirmation(),
            operation_id: args.member.operation_id,
            wait: args.wait.map(Duration::from_secs),
        }),
        MemberCommand::Resume(args) => {
            session.member_resume(&args.did, args.operation_id.as_deref(), args.confirmation())
        }
        MemberCommand::Archive(args) => {
            session.member_archive(&args.did, args.operation_id.as_deref(), args.confirmation())
        }
        MemberCommand::Remove(args) => session.member_remove(&RemoveOptions {
            member: args.member.did,
            confirmation: args.member.confirmation(),
            operation_id: args.member.operation_id,
            require_archive: !args.no_archive,
        }),
        MemberCommand::Repair(args) => {
            session.member_repair(&args.did, args.operation_id.as_deref(), args.confirmation())
        }
        MemberCommand::Cancel(args) => {
            session.member_cancel(&args.did, args.operation_id.as_deref(), args.confirmation())
        }
    }
}

/// Runs a `profile` command.
fn run_profile(session: &Session, command: ProfileCommand) -> Result<u8, CliError> {
    match command {
        ProfileCommand::Init { replace, gate } => gate
            .target()
            .and_then(|target| session.profile_init(&target, ProfileInitOptions { replace })),
        ProfileCommand::Show { did, gate } => gate
            .target()
            .and_then(|target| session.profile_show(&target, &did)),
    }
}

/// Runs an `app` command.
fn run_app(session: &Session, command: AppCommand) -> Result<u8, CliError> {
    match command {
        AppCommand::Catalogue { gate } => session.app_catalogue(&gate.target()?),
        AppCommand::Install(args) => {
            let confirmation = args.confirmation();
            session.app_install(
                &args.gate.target()?,
                &InstallOptions {
                    application: args.application,
                    schedule_secs: args.schedule_secs,
                    workspace: args.workspace,
                    operation_id: args.operation_id,
                    confirmation,
                },
            )
        }
        AppCommand::List { gate } => session.app_list(&gate.target()?),
        AppCommand::Show { installation, gate } => session.app_show(&gate.target()?, &installation),
        AppCommand::Jobs { installation, gate } => session.app_jobs(&gate.target()?, &installation),
        AppCommand::Run(args) => {
            let confirmation = args.confirmation();
            session.app_run(
                &args.gate.target()?,
                &args.installation,
                args.period,
                args.operation_id.as_deref(),
                confirmation,
            )
        }
        AppCommand::Withdraw(args) => {
            let confirmation = args.confirmation();
            session.app_withdraw(
                &args.gate.target()?,
                &args.installation,
                args.operation_id.as_deref(),
                confirmation,
            )
        }
        AppCommand::Cleanup(args) => {
            let confirmation = args.confirmation();
            session.app_cleanup(&args.gate.target()?, &args.installation, confirmation)
        }
        AppCommand::Resume(args) => {
            let confirmation = args.confirmation();
            session.app_resume(
                &args.gate.target()?,
                &args.installation,
                args.operation_id.as_deref(),
                confirmation,
            )
        }
    }
}

/// Runs an `application` command.
fn run_application(session: &Session, command: ApplicationCommand) -> Result<u8, CliError> {
    let action = |args: ApplicationArgs, action: ApplicationAction| {
        session.application_action(
            &args.application,
            action,
            args.operation_id.as_deref(),
            args.confirmation(),
        )
    };
    match command {
        ApplicationCommand::Add(args) => session.application_add(
            &args.manifest,
            args.operation_id.as_deref(),
            args.confirmation(),
        ),
        ApplicationCommand::List => session.application_list(),
        ApplicationCommand::Withdraw(args) => action(args, ApplicationAction::Withdraw),
        ApplicationCommand::Approve(args) => action(args, ApplicationAction::Approve),
        ApplicationCommand::Disable(args) => action(args, ApplicationAction::Disable),
    }
}

/// Runs a `pod` command.
fn run_pod(session: &Session, command: PodCommand) -> Result<u8, CliError> {
    match command {
        PodCommand::Ls { path, gate } => session.pod_ls(&gate.target()?, &path),
        PodCommand::Get { path, output, gate } => {
            session.pod_get(&gate.target()?, &path, output.as_deref())
        }
        PodCommand::Put(args) => {
            let (options, gate) = args.into_parts();
            session.pod_put(&gate.target()?, &options)
        }
        PodCommand::Rm(args) => {
            let confirmation = args.confirmation();
            session.pod_rm(&args.gate.target()?, &args.path, confirmation)
        }
        PodCommand::Acl {
            command: AclCommand::Get { path, output, gate },
        } => session.pod_acl_get(&gate.target()?, &path, output.as_deref()),
        PodCommand::Acl {
            command: AclCommand::Put(args),
        } => {
            let (options, gate) = args.into_parts();
            session.pod_acl_put(&gate.target()?, &options)
        }
    }
}