yb 0.7.1

Secure blob storage on a YubiKey
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
// SPDX-FileCopyrightText: 2025 - 2026 Frederic Ruget <fred@atlant.is> (GitHub: @douzebis)
//
// SPDX-License-Identifier: MIT

//! `yb-gen-man` — generate man pages from the live clap definition.
//!
//! Usage (from workspace root):
//!   cargo run -p yb --bin yb-gen-man [-- <output-dir>]
//!
//! Generates:
//!   <output-dir>/yb.1
//!   <output-dir>/yb-format.1
//!   <output-dir>/yb-store.1
//!   <output-dir>/yb-fetch.1
//!   <output-dir>/yb-list.1
//!   <output-dir>/yb-remove.1
//!   <output-dir>/yb-fsck.1
//!   <output-dir>/yb-rotate-management-key.1
//!   <output-dir>/yb-list-readers.1
//!   <output-dir>/yb-select.1

use std::path::PathBuf;

fn main() {
    let out_dir = PathBuf::from(
        std::env::args()
            .nth(1)
            .unwrap_or_else(|| "man/man1".to_owned()),
    );

    std::fs::create_dir_all(&out_dir).expect("cannot create output directory");

    let cmd = yb::command();

    // Top-level page.
    write_man(&out_dir, &cmd, "yb");

    // One page per subcommand (skip "help" which is auto-injected by clap).
    for sub in cmd.get_subcommands() {
        let name = sub.get_name();
        if name == "help" {
            continue;
        }
        let page_name = format!("yb-{name}");
        write_man(&out_dir, sub, &page_name);
    }
}

/// Extra roff sections appended after the clap-generated content.
/// Returns `(description_override, extra_roff)` where `description_override`
/// replaces the one-liner DESCRIPTION when non-empty.
fn extra_sections(page: &str) -> (&'static str, &'static str) {
    match page {
        "yb" => (
            r#".PP
\fByb\fR stores and retrieves arbitrary binary blobs on a YubiKey's PIV
applet.  Each blob is encrypted with a per-device ECDH key before being
written to the on-card PIV data objects; without the YubiKey the data
cannot be decrypted.
.PP
The store is a flat sequence of PIV objects provisioned by \fByb format\fR.
Each object is written at exactly the size its content requires (9-byte
sentinel when empty, up to 3,063 bytes when occupied).  Large blobs are
automatically split across multiple objects (chunk chaining); the number of
objects can be tuned at format time (\fB\-\-object\-count\fR).
.PP
All write operations (\fBformat\fR, \fBstore\fR, \fBremove\fR) require both the
PIV PIN and the PIV management key.  \fBfetch\fR asks for the PIN only
when a matched blob is encrypted.  \fBlist\fR and \fBfsck\fR never require a PIN (except
\fBfsck \-\-check\-key\fR) — they verify blob integrity using only the
public key from the store's X.509 certificate."#,
            r#".SH ENVIRONMENT
.TP
\fBYB_PIN\fR
PIV PIN.  Takes precedence over the interactive prompt.
Superseded by \fB\-\-pin\-stdin\fR when both are set.
.TP
\fBYB_MANAGEMENT_KEY\fR
PIV management key as a hex string.  Required for write operations when
the factory default has been changed (recommended).
.TP
\fBYB_COMPLETE\fR
Shell name (\fBbash\fR, \fBzsh\fR, \fBfish\fR).  When set, \fByb\fR emits shell
completion code to stdout and exits.
.SH EXAMPLES
.PP
Set up a YubiKey, guided (from a terminal):
.RS
.nf
yb format
.fi
.RE
.PP
The same, from a script, on a YubiKey whose PIN and PUK were changed:
.RS
.nf
yb format \-\-generate \-\-protect
.fi
.RE
.PP
Store an encrypted file:
.RS
.nf
yb store secret.key
.fi
.RE
.PP
Retrieve it to the current directory:
.RS
.nf
yb fetch secret.key
.fi
.RE
.PP
List all blobs with details:
.RS
.nf
yb list \-\-long
.fi
.RE
.SH EXIT STATUS
.TP
\fB0\fR
Success.
.TP
\fB1\fR
An error other than those below.
.TP
\fB2\fR
A blob name or pattern matched nothing (\fBfetch\fR; \fBremove\fR
without \fB\-f\fR).
.TP
\fB3\fR
The store has no room for the blobs (\fBstore\fR); nothing was written.
.SH SECURITY
Blobs are encrypted with AES-256-GCM using a key derived via ECDH with a
P-256 private key that never leaves the YubiKey hardware.
.PP
\fBDo not\fR use the factory-default PIN or management key in production.
\fByb\fR refuses to operate with default credentials unless
\fB\-\-allow\-defaults\fR is passed.
.SH SEE ALSO
\fByb\-format\fR(1),
\fByb\-store\fR(1),
\fByb\-fetch\fR(1),
\fByb\-list\fR(1),
\fByb\-remove\fR(1),
\fByb\-fsck\fR(1),
\fByb\-rotate\-management\-key\fR(1),
\fByb\-list\-readers\fR(1),
\fByb\-select\fR(1),
\fBykman\fR(1)"#,
        ),

        "yb-format" => (
            r#".PP
Prepare a YubiKey for use with \fByb\fR(1).
\fBformat\fR writes a fresh store header and allocates \fICOUNT\fR PIV data
objects.  Any existing \fByb\fR data on the card is erased.
Each object is written at exactly the size its content requires (9-byte
sentinel for empty slots, up to 3,063 bytes for occupied slots).
.PP
Run without format options from a terminal, \fBformat\fR is \fBguided\fR:
it shows the state of the YubiKey (as \fByb fsck\fR does), changes a
factory-default PIN and PUK, keeps or replaces the key in slot 0x82,
always keeps the management key on the YubiKey, unlocked by the PIN (so
that writes need only the PIN), shows the plan, and asks
for confirmation before writing anything.  When the plan destroys blobs or
an existing key, the confirmation is the YubiKey's serial number.  Any
format option, or \fB\-\-yes\fR, selects the flag-driven mode described
below, as does running without a terminal.  \fByb format \-\-yes\fR
formats with the defaults, without prompting.
.PP
By default \fBformat\fR expects an ECDH key to already exist in the chosen
PIV slot, and checks that it matches the slot's X.509 certificate.  Pass
\fB\-\-generate\fR to create a new P-256 key pair and a self-signed
certificate on the card.
.PP
Pass \fB\-\-protect\fR to keep the management key on the YubiKey,
unlocked by the PIN.  If it is not kept there, it is replaced with a random
key stored in the PRINTED PIV object, which only the PIN unlocks; if it
already is, it is kept.  This is a convenience: you no longer need to keep
the management key yourself.  After this,
future write operations only require the PIN — no \fBYB_MANAGEMENT_KEY\fR
or \fB\-\-key\fR needed.  The current management key is taken from
\fBYB_MANAGEMENT_KEY\fR / \fB\-\-key\fR, else from PRINTED if the card is
already protected, else the factory default.
.PP
Pass \fB\-\-plan\fR to run the checks and print the plan without writing
anything.  \fB\-\-plan\fR talks to the YubiKey and verifies the PIN; it
exits with status 1, with the error the real command would give, when a
check fails.
.PP
\fBformat\fR first checks everything it can without writing (PIN,
management key, slot key) and lists the blobs it will destroy.  It then
sets up protection, erases the store, and generates the key last, so that
a failure never leaves blobs behind a replaced key.  If it stops partway,
the message says what was done and what to run next.
.PP
\fBformat\fR must be run once before \fBstore\fR, \fBfetch\fR, or any other
command that accesses the store."#,
            r#".SH EXAMPLES
.PP
First-time setup, guided:
.RS
.nf
yb format
.fi
.RE
.PP
First-time setup from a script \(em generate a key, format, and keep
the management key on the YubiKey:
.RS
.nf
yb format \-\-generate \-\-protect
.fi
.RE
.PP
Show what that would do, without writing anything:
.RS
.nf
yb format \-\-generate \-\-protect \-\-plan
.fi
.RE
.PP
First-time setup, keeping the management key yourself:
.RS
.nf
yb format \-\-generate
.fi
.RE
.PP
Compact store (10 objects) in slot 0x83:
.RS
.nf
yb format \-c 10 \-k 0x83 \-\-generate
.fi
.RE
.PP
Re-format using an existing key in slot 0x9D:
.RS
.nf
yb format \-k 0x9D
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-store\fR(1), \fByb\-fsck\fR(1), \fBykman\fR(1)"#,
        ),

        "yb-store" => (
            r#".PP
Write one or more binary blobs to the YubiKey.
Each blob is identified by a short name (at most 32 bytes).  When a
blob with the same name already exists it is replaced safely: the new
copy is written first, then the old one removed, so an interruption
leaves the old or the new content.  This needs room for both copies.
\fByb store\fR refuses, writing nothing, when the store lacks free
objects (exit status 3); the YubiKey's memory (about 51 KB, shared with
certificates) cannot be checked beforehand, so a store can still run out
of it while writing: the blobs then keep their previous content, and the
next \fByb\fR command frees the space the interrupted write used.
.PP
Blobs are compressed before storage by default.  \fByb\fR tries both
brotli (level 11) and xz (preset 9) and keeps the smaller result;
if neither algorithm reduces the size the blob is stored uncompressed.
Pass \fB\-\-no\-compress\fR to skip compression entirely (useful for
already-compressed data such as JPEG, ZIP, or existing brotli/xz
archives).
.PP
Blobs are encrypted by default using AES-256-GCM with a key derived via
ECDH from the public key stored in the configured PIV slot.  Pass
\fB\-\-unencrypted\fR to skip encryption (use with care)."#,
            r#".SH EXAMPLES
.PP
Store a file (blob name = basename):
.RS
.nf
yb store secret.key
.fi
.RE
.PP
Store with an explicit name:
.RS
.nf
yb store \-n mykey /path/to/key.pem
.fi
.RE
.PP
Store several files at once:
.RS
.nf
yb store a.key b.key c.key
.fi
.RE
.PP
Pipe from stdin:
.RS
.nf
pass show mysite | yb store \-\-name mysite
.fi
.RE
.PP
The PIN and the content on one standard input, with no file (for
programs driving \fByb\fR): the first line is the PIN, the rest is the
blob, byte for byte:
.RS
.nf
{ printf '%s\\n' "$PIN"; cat vault.kdbx; } | yb \-\-pin\-stdin store \-n vault.kdbx
.fi
.RE
.PP
Store unencrypted (plain-text blob):
.RS
.nf
yb store \-\-unencrypted config.toml
.fi
.RE
.PP
Store without compression (e.g. already-compressed binary):
.RS
.nf
yb store \-\-no\-compress archive.tar.xz
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-fetch\fR(1), \fByb\-remove\fR(1), \fByb\-fsck\fR(1)"#,
        ),

        "yb-fetch" => (
            r#".PP
Retrieve one or more blobs from the YubiKey.
Names and glob patterns are accepted; each matched blob is written to a
file in the current directory (or \fIOUTPUT_DIR\fR) using the blob name as
the filename.
.PP
Use \fB\-\-stdout\fR or \fB\-\-output\fR when exactly one blob is selected and
you need direct control over the destination.
.PP
Before anything is written or decrypted, each matched blob's signature is
verified with the public key of the store's certificate (no PIN needed).
If any blob is corrupted or was tampered with, \fByb fetch\fR fails and
fetches nothing.  An unsigned blob (written by a yb version before 0.3)
is fetched with a warning."#,
            r#".SH EXAMPLES
.PP
Fetch a single blob to the current directory:
.RS
.nf
yb fetch secret.key
.fi
.RE
.PP
Fetch to a specific file:
.RS
.nf
yb fetch \-o /tmp/key.pem mykey
.fi
.RE
.PP
Print to stdout (pipe-friendly):
.RS
.nf
yb fetch \-\-stdout mypassword | xclip
.fi
.RE
.PP
Fetch all blobs matching a glob into a directory:
.RS
.nf
yb fetch \-O ./restore '*.key'
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-store\fR(1), \fByb\-list\fR(1)"#,
        ),

        "yb-list" => (
            r#".PP
List the names of all blobs currently stored on the YubiKey.
An optional glob pattern filters the output.
.PP
The default output is one name per line, suitable for scripting.
\fB\-\-long\fR adds an encryption flag, chunk count, modification time,
and plaintext size.
.PP
Every blob's ECDSA signature is verified automatically (no PIN required).
If a blob is CORRUPTED the word \fBCORRUPTED\fR is appended to its output
line and \fByb list\fR exits with status 1.  Unsigned blobs (written by
a yb version before 0.3, without a signature trailer) are marked
\fBUNSIGNED\fR, and blobs encrypted with the legacy, unauthenticated
AES-CBC scheme of older versions \fBLEGACY\fR (store them again)."#,
            r#".SH LONG FORMAT
In long format each line contains:
.TP
Flag
\fB\-\fR for an encrypted blob, \fBP\fR for a plaintext (unencrypted) blob.
.TP
Chunks
Number of PIV objects consumed by this blob.
.TP
Date
Modification time (month, day, time for recent blobs; year for older).
.TP
Size
Plaintext size in bytes.
.TP
Name
Blob name, followed by \fBCORRUPTED\fR if signature verification failed,
or \fBUNSIGNED\fR if the blob has no signature and \fBLEGACY\fR if it
uses the legacy AES-CBC encryption.
Names containing characters outside the portable set
\fBa\-z A\-Z 0\-9 . \- _ + , / :\fR are wrapped in POSIX single quotes
so the marker is never ambiguous.
.SH EXAMPLES
.PP
List all blobs:
.RS
.nf
yb list
.fi
.RE
.PP
Long listing, newest first:
.RS
.nf
yb list \-l \-t
.fi
.RE
.PP
Filter by glob:
.RS
.nf
yb list '*.key'
.fi
.RE
.PP
Alert on corruption (for scripts):
.RS
.nf
yb list || echo "WARNING: store corruption detected" >&2
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-fsck\fR(1), \fByb\-fetch\fR(1), \fByb\-remove\fR(1)"#,
        ),

        "yb-remove" => (
            r#".PP
Delete one or more blobs from the YubiKey.
Blob names and glob patterns are accepted; all matching blobs are
removed in a single write pass.
.PP
The operation is destructive and cannot be undone without the original
plaintext."#,
            r#".SH EXAMPLES
.PP
Remove a single blob:
.RS
.nf
yb remove secret.key
.fi
.RE
.PP
Remove all blobs whose names end in \fB.bak\fR:
.RS
.nf
yb remove '*.bak'
.fi
.RE
.PP
Remove if present, silently do nothing if absent:
.RS
.nf
yb remove \-\-ignore\-missing maybe.key
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-list\fR(1), \fByb\-fsck\fR(1)"#,
        ),

        "yb-fsck" => (
            r#".PP
Report the state of the YubiKey (PIN and PUK, management key, store
slot), then read the store header and all PIV objects without decrypting
any blob, verify every blob's ECDSA signature and print an integrity
summary.  No PIN is required, except with \fB\-\-check\-key\fR, which
checks that the key in the store slot matches its certificate.
.PP
\fBfsck\fR runs on any YubiKey, including a factory-fresh one or one
without a store.  It exits with status 1 when the report shows an error
(blocked PIN, unsupported management key mode, key/certificate mismatch,
a certificate without an EC P-256 key, an unreadable store, a CORRUPTED
blob), and 0 otherwise; warnings (e.g. factory-default credentials) do
not change the exit status.  When the YubiKey does not keep its
management key, a hint says how to have it kept
(\fByb rotate\-management\-key\fR).  It does not repair damage; use
\fByb remove\fR to clean up corrupt blobs."#,
            r#".SH OUTPUT
Default output (no flags):
.PP
.RS
.nf
YubiKey <serial> \(em firmware <version>

PIV application \(em protects this store
  PIN              set, 3/3 tries left
  PUK              set, 3/3 tries left
  Management key   set, 3DES, kept on the YubiKey (PRINTED), unlocked by the PIV PIN
  Store key        slot 0x82: EC P-256, generated on card, certificate CN=YBLOB ECCP256
  Key/certificate  not checked (use \-\-check\-key)

FIDO2 application \(em not used by this store

Store: legacy, <n> objects, age <n>
  Blobs            <n> stored, <n> objects free (~<n> bytes used by the store)

  blob-name-1          VERIFIED
  blob-name-2          UNSIGNED
  old-blob             CORRUPTED

Integrity: <n> verified, <n> unsigned, <n> corrupted
.fi
.RE
.PP
A post\-quantum store shows the PIV application as holding the store's
objects, and the FIDO2 application as protecting it, with the FIDO2
PIN's attempts left (read without using one).  Without \fB\-\-seals\fR,
fsck asks for no PIN and no touch; \fB\-\-seals\fR checks, with the
FIDO2 PIN, the store's credential, the management key and every blob's
seal, under "Checked with the FIDO2 PIN".
.PP
Possible per-blob verdicts:
.TP
\fBVERIFIED\fR
ECDSA signature is present and cryptographically valid.
.TP
\fBUNSIGNED\fR
No signature trailer (written by a yb version before 0.3).
.TP
\fBUNVERIFIABLE\fR
Signature present, but it cannot be checked here: the store's key slot
has no readable certificate, or the signature was made by a newer version
of yb (update yb to check it).
.TP
\fBCORRUPTED\fR
Signature present but verification failed (the blob's bytes or its
metadata were altered), or payload is truncated.
.PP
A verdict may be followed by \fBLEGACY\fR: the blob is encrypted with the
legacy, unauthenticated AES-CBC scheme of older versions; storing it again
encrypts it with AES-GCM.
.PP
\fBfsck\fR also reports, as an error, an object that records another
object count than the store's (it does not belong to the store, and yb
ignores it), and warns when the store's 24-bit age counter nears its end
(stores then fail; reformatting resets it).
.PP
With \fB\-\-nvm\fR, a line on the YubiKey's memory is printed after the
integrity summary: the bytes used by the yb store, by other PIV objects,
and the estimated free space.  This issues approximately
290 read-only APDUs and may take a few seconds on real hardware.
.PP
With \fB\-\-verbose\fR, structural warnings (orphaned continuation chunks,
duplicate blob names) are printed after the integrity summary, followed
by a raw per-object dump showing all metadata fields.
.SH EXAMPLES
.PP
Integrity audit:
.RS
.nf
yb fsck
.fi
.RE
.PP
Audit with the YubiKey's memory:
.RS
.nf
yb fsck \-\-nvm
.fi
.RE
.PP
Full object dump for debugging:
.RS
.nf
yb fsck \-\-verbose
.fi
.RE
.PP
Also check the store key against its certificate (asks for the PIN):
.RS
.nf
yb fsck \-\-check\-key
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-list\fR(1), \fByb\-format\fR(1), \fByb\-remove\fR(1)"#,
        ),

        "yb-rotate-management-key" => (
            r#".PP
Replace the PIV management key with a new random key, kept on the
YubiKey and unlocked by the PIN.  The store and its blobs are not touched:
the management key only authorizes writes.
.PP
Keeping the management key on the YubiKey is a convenience, not extra
security: you never need to keep or type it, since \fByb\fR reads it when
a write needs it.  On a YubiKey that already keeps its key this way, the
command replaces it (rotation); on one that does not, it sets this up,
without erasing the store as \fByb format \-\-protect\fR would.
.PP
The new key has the same algorithm as the current one.  The current key
is taken from \fBYB_MANAGEMENT_KEY\fR, else from the YubiKey, else the
factory default.  The command refuses while the PIN or PUK is still the
factory default (unless \fB\-\-allow\-defaults\fR is given), since the
new key would be kept behind that PIN.
.PP
The new key is written to the YubiKey before the switch, so an
interruption never leaves a key that exists nowhere; the next \fByb\fR
write finishes any leftover cleanup.  The key is never printed."#,
            r#".SH EXAMPLES
.PP
Replace the management key:
.RS
.nf
yb rotate\-management\-key
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-format\fR(1), \fByb\-fsck\fR(1), \fBykman\fR(1)"#,
        ),

        "yb-select" => (
            r#".PP
Interactively select one YubiKey from all connected devices and print
its serial number to stdout.  Intended for use in scripts:
.PP
.RS
.nf
yb \-\-serial "$(yb select)" store myfile
.fi
.RE
.PP
If only one YubiKey is connected the serial is printed immediately
without displaying the picker.  If multiple YubiKeys are connected and
the process is attached to a TTY, a single-line carousel is rendered on
stderr: use \fB\(la\fR/\fB\(ra\fR (or \fBj\fR/\fBk\fR) to cycle through devices
and \fBEnter\fR to confirm.  The currently highlighted device flashes its
LED to help identify it physically.  Press \fBEsc\fR or \fBCtrl\-C\fR to cancel.
.PP
If multiple YubiKeys are connected but stderr is not a TTY, the command
exits with an error."#,
            r#".SH EXAMPLES
.PP
Print the serial number of the selected YubiKey:
.RS
.nf
yb select
.fi
.RE
.PP
Print the PC/SC reader name instead:
.RS
.nf
yb select \-\-reader
.fi
.RE
.PP
Use in a script to target a specific YubiKey:
.RS
.nf
yb \-\-serial "$(yb select)" store secret.key
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fByb\-list\-readers\fR(1)"#,
        ),

        "yb-list-readers" => (
            r#".PP
Print all PC/SC reader names visible to the pcscd daemon, one per line.
This command does not require a YubiKey to be connected and bypasses
\fBContext\fR construction entirely, so it works even when no card is present."#,
            r#".SH EXAMPLES
.PP
List readers:
.RS
.nf
yb list-readers
.fi
.RE
.PP
Use the reader name with another command:
.RS
.nf
yb \-r "Yubico YubiKey OTP+FIDO+CCID 00 00" list
.fi
.RE
.SH SEE ALSO
\fByb\fR(1), \fBpcsc_scan\fR(1)"#,
        ),

        _ => ("", ""),
    }
}

fn write_man(dir: &std::path::Path, cmd: &clap::Command, page_name: &str) {
    let man = clap_mangen::Man::new(cmd.clone())
        .title(page_name.to_uppercase())
        .section("1")
        .date("2026-03")
        .source("yb")
        .manual("User Commands");

    let mut buf = Vec::new();
    man.render(&mut buf).expect("man page rendering failed");

    // Append extra sections if available.
    let (desc_extra, extra) = extra_sections(page_name);
    if !desc_extra.is_empty() || !extra.is_empty() {
        // Insert desc_extra after the .SH DESCRIPTION line (replace the clap one-liner).
        let text = String::from_utf8(buf).expect("man page is not utf-8");
        let patched = if !desc_extra.is_empty() {
            patch_description(&text, desc_extra)
        } else {
            text
        };
        let mut result = patched;
        if !extra.is_empty() {
            result.push('\n');
            result.push_str(extra);
            result.push('\n');
        }
        buf = result.into_bytes();
    }

    let dest = dir.join(format!("{page_name}.1"));
    std::fs::write(&dest, &buf).expect("cannot write man page");
    eprintln!("Written: {}", dest.display());
}

/// Replace the one-liner DESCRIPTION body with `extra`.
/// The clap-generated DESCRIPTION section looks like:
///   .SH DESCRIPTION\n<one line>\n
/// We keep the .SH DESCRIPTION header and replace the body.
fn patch_description(src: &str, extra: &str) -> String {
    // Find .SH DESCRIPTION, then replace everything until the next .SH
    let marker = ".SH DESCRIPTION\n";
    if let Some(desc_start) = src.find(marker) {
        let body_start = desc_start + marker.len();
        // Find the next section header after DESCRIPTION.
        let next_sh = src[body_start..].find("\n.SH ");
        let (before_body, after_body) = if let Some(rel) = next_sh {
            let abs = body_start + rel + 1; // keep the leading \n of next .SH
            (&src[..body_start], &src[abs..])
        } else {
            (&src[..body_start], "")
        };
        format!("{before_body}{extra}\n{after_body}")
    } else {
        src.to_owned()
    }
}