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();
write_man(&out_dir, &cmd, "yb");
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);
}
}
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 requires the PIN for
encrypted blobs. \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 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 atomically.
.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
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."#,
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. Unverified blobs (older
yb0/yb1 format without a signature trailer) are listed normally."#,
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.
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>
PIN ok (3/3 tries left)
PUK ok (3/3 tries left)
Management key 3DES, kept on the YubiKey, unlocked by the PIN
Slot 0x82 EC P-256, generated on card, certificate CN=YBLOB ECCP256
Key/certificate not checked (use \-\-check\-key)
Store: <n> objects, slot 0x<xx>, age <n>
Blobs: <n> stored, <n> objects free (~<n> bytes used by store)
blob-name-1 VERIFIED
blob-name-2 UNVERIFIED
old-blob CORRUPTED
Integrity: <n> verified, <n> unverified, <n> corrupted
.fi
.RE
.PP
Possible per-blob verdicts:
.TP
\fBVERIFIED\fR
ECDSA signature is present and cryptographically valid.
.TP
\fBUNVERIFIED\fR
No signature trailer (older yb0/yb1 format) or certificate unreadable.
.TP
\fBCORRUPTED\fR
Signature present but verification failed, or payload is truncated.
.PP
With \fB\-\-nvm\fR, an additional NVM breakdown line is printed after the
integrity summary, showing bytes attributed to the yb store, to 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 NVM breakdown:
.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");
let (desc_extra, extra) = extra_sections(page_name);
if !desc_extra.is_empty() || !extra.is_empty() {
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());
}
fn patch_description(src: &str, extra: &str) -> String {
let marker = ".SH DESCRIPTION\n";
if let Some(desc_start) = src.find(marker) {
let body_start = desc_start + marker.len();
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; (&src[..body_start], &src[abs..])
} else {
(&src[..body_start], "")
};
format!("{before_body}{extra}\n{after_body}")
} else {
src.to_owned()
}
}