dkp 0.4.3

dkp — Domain Knowledge Pack management CLI
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
use anyhow::{Context, Result, bail};
use base64::Engine;
use clap::Args;
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use sha2::{Digest, Sha256};
use std::{collections::HashMap, io::Cursor, path::PathBuf};
use xz2::read::XzDecoder;

use crate::cli::CmdCtx;
use crate::cmd::registry::account::{load_credentials_from_ctx, resolve_registry_url};
use dkp_core::registry::types::{LockFile, LockedPack};

#[derive(Args, Debug)]
pub struct InstallArgs {
    /// Pack name, e.g. @example/nutrition-for-men or @example/pack@1.2.0.
    /// Omit to install all packs from dkp.lock.
    pub name: Option<String>,

    /// Install directly from a URL without involving the registry.
    /// Pass --checksums and/or --sig to verify integrity.
    #[arg(long, value_name = "URL")]
    pub url: Option<String>,

    /// Path to a checksums.json for verifying a --url install
    #[arg(long, value_name = "PATH", requires = "url")]
    pub checksums: Option<PathBuf>,

    /// Path to a bundle.sig for verifying a --url install
    #[arg(long, value_name = "PATH", requires = "url")]
    pub sig: Option<PathBuf>,

    /// Publisher Ed25519 public key for verifying a --url install (hex, base64, or raw 32-byte file)
    #[arg(long, value_name = "PATH", requires = "sig")]
    pub pubkey: Option<PathBuf>,

    /// Install to global store (~/.dkp/packs/)
    #[arg(long, short = 'g')]
    pub global: bool,

    /// Install to a custom directory
    #[arg(long, value_name = "DIR")]
    pub out: Option<PathBuf>,

    /// Registry API token
    #[arg(long, value_name = "KEY", env = "DKP_TOKEN")]
    pub token: Option<String>,

    /// Skip signature verification for registry installs (NOT RECOMMENDED)
    #[arg(long)]
    pub no_verify: bool,

    /// Accept a publisher's signing key even if it differs from the
    /// previously pinned key (lockfile and/or ~/.dkp/trusted_keys.json).
    /// Only pass this after verifying the key rotation out-of-band.
    #[arg(long)]
    pub accept_new_key: bool,
}

pub async fn run(args: InstallArgs, cli: &CmdCtx) -> Result<()> {
    // --- Direct URL install (no registry) ---
    if let Some(ref url) = args.url {
        return install_from_url(url, &args, cli).await;
    }

    let base = resolve_registry_url(&cli.config.registry.url);
    let token = args.token.clone().or_else(|| {
        load_credentials_from_ctx(&cli.config.registry.url)
            .ok()?
            .map(|(_, t)| t)
    });
    let client = dkp_core::registry::RegistryClient::new(base.clone(), token);

    match &args.name {
        Some(name) => install_one(name, &args, cli, &client, &base).await,
        None => install_from_lock(&args, cli, &client, &base).await,
    }
}

async fn install_one(
    arg: &str,
    args: &InstallArgs,
    cli: &CmdCtx,
    client: &dkp_core::registry::RegistryClient,
    registry_url: &str,
) -> Result<()> {
    let (pack_name, version) = parse_pack_arg(arg);

    println!("Resolving {pack_name}@{version} ...");
    let meta = client.resolve(&pack_name, &version).await?;

    if meta.yanked {
        eprintln!(
            "Warning: {}@{} is yanked: {}",
            meta.name,
            meta.version,
            meta.yank_reason.as_deref().unwrap_or("no reason given")
        );
    }

    if meta.deprecated {
        eprintln!(
            "Warning: {}@{} is deprecated: {}",
            meta.name,
            meta.version,
            meta.deprecation_message
                .as_deref()
                .unwrap_or("no message provided")
        );
    }

    let install_dir = resolve_install_dir(args, cli, &meta.name, &meta.version)?;
    if install_dir.exists() {
        println!("Already installed at {}", install_dir.display());
        return Ok(());
    }

    // Fetch the CDN download URL from the registry
    let dl = client.get_download_url(&meta.name, &meta.version).await?;

    println!("Downloading from {} ...", dl.url);
    let http = reqwest::Client::new();
    let resp = http
        .get(&dl.url)
        .send()
        .await
        .context("failed to download pack archive")?;
    if !resp.status().is_success() {
        bail!("download failed: {}", resp.status());
    }
    let archive_bytes = resp.bytes().await.context("failed to read archive body")?;

    if !args.no_verify {
        check_key_pin(&meta.name, &meta.publisher_public_key, registry_url, args)?;

        let expected: HashMap<String, String> =
            serde_json::from_value(meta.checksums.clone()).context("invalid checksums")?;
        let actual = hash_archive(&archive_bytes, &meta.archive_format)?;
        for (path, expected_hash) in &expected {
            let actual_hash = actual
                .get(path)
                .with_context(|| format!("'{path}' in checksums not found in archive"))?;
            if actual_hash != expected_hash {
                bail!(
                    "checksum mismatch for '{path}': expected {expected_hash}, got {actual_hash}"
                );
            }
        }

        let sig_bytes = base64::engine::general_purpose::STANDARD
            .decode(&meta.bundle_sig)
            .context("invalid bundle_sig base64")?;
        let key_bytes = base64::engine::general_purpose::STANDARD
            .decode(&meta.publisher_public_key)
            .context("invalid publisher_public_key base64")?;
        verify_signature(&sig_bytes, &key_bytes, &expected)?;

        println!("Checksums and signature verified.");
    } else {
        eprintln!("Warning: skipping verification (--no-verify)");
    }

    let tmp = tempfile::tempdir().context("failed to create temp dir")?;
    extract_archive(&archive_bytes, &meta.archive_format, tmp.path())?;
    let extracted_root = find_pack_root(tmp.path());

    std::fs::create_dir_all(&install_dir)
        .with_context(|| format!("creating install dir {}", install_dir.display()))?;
    for entry in std::fs::read_dir(&extracted_root)? {
        let entry = entry?;
        std::fs::rename(entry.path(), install_dir.join(entry.file_name()))?;
    }

    println!("Installed to {}", install_dir.display());

    let integrity = format!(
        "sha256-{}",
        hex::encode(Sha256::digest(meta.checksums.to_string().as_bytes()))
    );
    update_lock_file(
        &meta.name,
        &meta.version,
        &meta.archive_format,
        &integrity,
        Some(&meta.publisher_public_key),
    )?;

    Ok(())
}

async fn install_from_lock(
    args: &InstallArgs,
    cli: &CmdCtx,
    client: &dkp_core::registry::RegistryClient,
    registry_url: &str,
) -> Result<()> {
    let lock_path = std::env::current_dir()?.join("dkp.lock");
    if !lock_path.exists() {
        println!("No dkp.lock found. Specify a pack name to install.");
        return Ok(());
    }
    let lock: LockFile = serde_json::from_str(&std::fs::read_to_string(&lock_path)?)?;
    for (name, locked) in &lock.resolved {
        let install_dir = resolve_install_dir(args, cli, name, &locked.version)?;
        if install_dir.exists() {
            println!("{name}@{} already installed", locked.version);
            continue;
        }
        // Re-use install_one logic
        install_one(
            &format!("{name}@{}", locked.version),
            args,
            cli,
            client,
            registry_url,
        )
        .await?;
    }
    Ok(())
}

/// Compare the registry-returned publisher key against any previously pinned
/// value (project lockfile + global ~/.dkp/trusted_keys.json), hard-failing on
/// mismatch unless `--accept-new-key` was passed.
fn check_key_pin(
    pack_name: &str,
    fetched_key: &str,
    registry_url: &str,
    args: &InstallArgs,
) -> Result<()> {
    let scope = pack_name;

    // Project-local lockfile pin, if one exists for this exact package.
    let lock_path = std::env::current_dir()?.join("dkp.lock");
    if lock_path.exists()
        && let Ok(lock) = serde_json::from_str::<LockFile>(&std::fs::read_to_string(&lock_path)?)
        && let Some(locked) = lock.resolved.get(pack_name)
        && let Some(pinned) = &locked.publisher_public_key
        && pinned != fetched_key
        && !args.accept_new_key
    {
        bail!(
            "publisher key for '{pack_name}' changed since it was last installed \
                             in this project.\n  pinned:  {pinned}\n  fetched: {fetched_key}\n\
                             This could mean the publisher legitimately rotated their key, or \
                             that the registry response has been tampered with. If you've \
                             verified the rotation out-of-band, re-run with --accept-new-key."
        );
    }

    // Global cross-project pin.
    match dkp_core::trust::check_and_pin(scope, fetched_key, registry_url)? {
        dkp_core::trust::PinCheck::FirstContact => {
            println!(
                "Pinning publisher key for '{scope}' (first time seen on this machine) — \
                 verify out-of-band if this matters."
            );
        }
        dkp_core::trust::PinCheck::Match => {}
        dkp_core::trust::PinCheck::Mismatch { pinned_key } => {
            if !args.accept_new_key {
                bail!(
                    "publisher key for '{scope}' differs from the key pinned on this machine.\n  \
                     pinned:  {pinned_key}\n  fetched: {fetched_key}\n\
                     This could mean the publisher legitimately rotated their key, or that the \
                     registry response has been tampered with. If you've verified the rotation \
                     out-of-band, re-run with --accept-new-key."
                );
            }
            eprintln!("Warning: accepting new publisher key for '{scope}' (--accept-new-key).");
            dkp_core::trust::accept_new_key(scope, fetched_key, registry_url)?;
        }
    }

    Ok(())
}

// --- Direct URL install ---

async fn install_from_url(url: &str, args: &InstallArgs, cli: &CmdCtx) -> Result<()> {
    println!("Downloading from {url} ...");
    let http = reqwest::Client::new();
    let resp = http
        .get(url)
        .send()
        .await
        .context("failed to download archive")?;
    if !resp.status().is_success() {
        bail!("download failed: {}", resp.status());
    }
    let archive_bytes = resp.bytes().await.context("failed to read archive body")?;

    // Detect format from bytes
    let archive_format = detect_format_from_bytes(&archive_bytes)?;

    // Optional checksums verification
    let mut verified_checksums = false;
    if let Some(ref checksums_path) = args.checksums {
        let expected: HashMap<String, String> =
            serde_json::from_str(&std::fs::read_to_string(checksums_path)?)
                .context("failed to parse checksums file")?;
        let actual = hash_archive(&archive_bytes, &archive_format)?;
        for (path, expected_hash) in &expected {
            let actual_hash = actual
                .get(path)
                .with_context(|| format!("'{path}' in checksums not found in archive"))?;
            if actual_hash != expected_hash {
                bail!(
                    "checksum mismatch for '{path}': expected {expected_hash}, got {actual_hash}"
                );
            }
        }
        verified_checksums = true;
        println!("Checksums verified.");

        // Optional signature verification (requires --sig and --pubkey)
        if let (Some(sig_path), Some(pubkey_path)) = (&args.sig, &args.pubkey) {
            let sig_bytes = std::fs::read(sig_path).context("failed to read .sig file")?;
            let key_bytes = load_public_key(pubkey_path)?;
            verify_signature(&sig_bytes, &key_bytes, &expected)?;
            println!("Signature verified.");
        } else if args.sig.is_some() {
            eprintln!("Warning: --sig provided without --pubkey; skipping signature verification.");
        }
    } else {
        eprintln!(
            "Warning: installing without integrity verification. \
             Pass --checksums <path> to verify this archive."
        );
    }

    // Determine pack name and version from archive filename or prompt
    let filename = url.rsplit('/').next().unwrap_or("unknown.tar.gz");
    let (pack_name, version) = parse_dkp_filename(filename);

    let install_dir = resolve_install_dir(args, cli, &pack_name, &version)?;

    let tmp = tempfile::tempdir().context("failed to create temp dir")?;
    extract_archive(&archive_bytes, &archive_format, tmp.path())?;
    let extracted_root = find_pack_root(tmp.path());

    std::fs::create_dir_all(&install_dir)
        .with_context(|| format!("creating install dir {}", install_dir.display()))?;
    for entry in std::fs::read_dir(&extracted_root)? {
        let entry = entry?;
        std::fs::rename(entry.path(), install_dir.join(entry.file_name()))?;
    }

    println!("Installed to {}", install_dir.display());

    if verified_checksums {
        // We don't have a registry checksums JSON value; use a placeholder integrity
        let integrity = format!("sha256-{}", hex::encode(Sha256::digest(&archive_bytes)));
        update_lock_file(&pack_name, &version, &archive_format, &integrity, None)?;
    }

    Ok(())
}

fn parse_dkp_filename(name: &str) -> (String, String) {
    // Expected: "{name}-{version}.tar.gz" or "{name}-{version}.zip"
    let base = name
        .strip_suffix(".tar.gz")
        .or_else(|| name.strip_suffix(".tar.xz"))
        .or_else(|| name.strip_suffix(".dkp"))
        .or_else(|| name.strip_suffix(".zip"))
        .unwrap_or(name);
    if let Some(pos) = base.rfind('-') {
        let maybe_version = &base[pos + 1..];
        if maybe_version
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_digit())
        {
            return (base[..pos].to_owned(), maybe_version.to_owned());
        }
    }
    (base.to_owned(), "unknown".to_owned())
}

// --- Shared helpers ---

fn parse_pack_arg(arg: &str) -> (String, String) {
    if let Some(pos) = arg.rfind('@').filter(|&p| p > 0) {
        (arg[..pos].to_owned(), arg[pos + 1..].to_owned())
    } else {
        (arg.to_owned(), "latest".to_owned())
    }
}

fn resolve_install_dir(
    args: &InstallArgs,
    cli: &CmdCtx,
    pack_name: &str,
    version: &str,
) -> Result<PathBuf> {
    if let Some(out) = &args.out {
        return Ok(out.join(pack_name).join(version));
    }
    if args.global {
        let global = cli
            .config
            .install
            .global_dir
            .as_deref()
            .map(PathBuf::from)
            .or_else(|| dirs::home_dir().map(|h| h.join(".dkp").join("packs")))
            .context("cannot determine global install dir")?;
        return Ok(global.join(pack_name).join(version));
    }
    let local_name = cli.config.install.local_dir.as_deref().unwrap_or("dkps");
    Ok(std::env::current_dir()?
        .join(local_name)
        .join(pack_name)
        .join(version))
}

fn strip_top_component(path: &str) -> String {
    match path.find('/') {
        Some(i) => path[i + 1..].to_string(),
        None => String::new(),
    }
}

fn detect_format_from_bytes(bytes: &[u8]) -> Result<String> {
    if bytes.starts_with(b"PK\x03\x04") {
        return Ok("zip".into());
    }
    if bytes.starts_with(&[0x1f, 0x8b]) {
        return Ok("tar.gz".into());
    }
    if bytes.starts_with(b"\xfd7zXZ\x00") {
        return Ok("tar.xz".into());
    }
    bail!("unrecognized archive format (not zip, tar.gz, or tar.xz)")
}

/// Formats sharing identical tar+xz decode logic, so hashing and extraction
/// can't silently diverge if a new format is added to only one of them.
fn is_xz_tar_format(format: &str) -> bool {
    matches!(format, "tar.xz" | "dkp")
}

fn hash_archive(bytes: &[u8], format: &str) -> Result<HashMap<String, String>> {
    let mut map = HashMap::new();
    match format {
        "zip" => {
            let mut archive = zip::ZipArchive::new(Cursor::new(bytes))?;
            for i in 0..archive.len() {
                let mut file = archive.by_index(i)?;
                if file.is_dir() {
                    continue;
                }
                let name = strip_top_component(file.name());
                if name.is_empty() {
                    continue;
                }
                let mut hasher = Sha256::new();
                std::io::copy(&mut file, &mut hasher)?;
                map.insert(name, hex::encode(hasher.finalize()));
            }
        }
        "tar.gz" => hash_tar(flate2::read::GzDecoder::new(Cursor::new(bytes)), &mut map)?,
        _ if is_xz_tar_format(format) => hash_tar(XzDecoder::new(Cursor::new(bytes)), &mut map)?,
        _ => bail!("unsupported archive format: {format}"),
    }
    Ok(map)
}

fn hash_tar<R: std::io::Read>(reader: R, map: &mut HashMap<String, String>) -> Result<()> {
    let mut archive = tar::Archive::new(reader);
    for entry in archive.entries()? {
        let mut entry = entry?;
        if entry.header().entry_type().is_dir() {
            continue;
        }
        let raw = entry.path()?.to_string_lossy().into_owned();
        let name = strip_top_component(&raw);
        if name.is_empty() {
            continue;
        }
        let mut hasher = Sha256::new();
        std::io::copy(&mut entry, &mut hasher)?;
        map.insert(name, hex::encode(hasher.finalize()));
    }
    Ok(())
}

fn verify_signature(
    sig_bytes: &[u8],
    key_bytes: &[u8],
    checksums: &HashMap<String, String>,
) -> Result<()> {
    let key_arr: [u8; 32] = key_bytes
        .try_into()
        .context("Ed25519 key must be 32 bytes")?;
    let key = VerifyingKey::from_bytes(&key_arr).context("invalid Ed25519 public key")?;
    let sig_arr: [u8; 64] = sig_bytes
        .try_into()
        .context("Ed25519 signature must be 64 bytes")?;
    let sig = Signature::from_bytes(&sig_arr);
    let canonical = serde_json::to_string_pretty(
        &checksums
            .iter()
            .collect::<std::collections::BTreeMap<_, _>>(),
    )?;
    let digest = Sha256::digest(canonical.as_bytes());
    key.verify(&digest, &sig)
        .context("signature verification failed — pack may have been tampered with")?;
    Ok(())
}

fn extract_archive(bytes: &[u8], format: &str, dest: &std::path::Path) -> Result<()> {
    match format {
        "zip" => {
            zip::ZipArchive::new(Cursor::new(bytes))?.extract(dest)?;
        }
        "tar.gz" => {
            tar::Archive::new(flate2::read::GzDecoder::new(Cursor::new(bytes))).unpack(dest)?;
        }
        _ if is_xz_tar_format(format) => {
            tar::Archive::new(XzDecoder::new(Cursor::new(bytes))).unpack(dest)?;
        }
        _ => bail!("unsupported format: {format}"),
    }
    Ok(())
}

fn find_pack_root(dir: &std::path::Path) -> PathBuf {
    if let Ok(entries) = std::fs::read_dir(dir) {
        let entries: Vec<_> = entries.flatten().collect();
        if entries.len() == 1 && entries[0].path().is_dir() {
            return entries[0].path();
        }
    }
    dir.to_path_buf()
}

fn load_public_key(path: &PathBuf) -> Result<Vec<u8>> {
    use base64::Engine;
    let bytes =
        std::fs::read(path).with_context(|| format!("reading key from {}", path.display()))?;
    if bytes.len() == 32 {
        return Ok(bytes);
    }
    let text = String::from_utf8(bytes).context("key file is not UTF-8")?;
    let text = text.trim();
    if text.len() == 64 && text.chars().all(|c| c.is_ascii_hexdigit()) {
        return hex::decode(text).context("invalid hex in key file");
    }
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(text)
        .context("key file is not hex, raw bytes, or base64")?;
    if decoded.len() != 32 {
        bail!("Ed25519 public key must be 32 bytes; got {}", decoded.len());
    }
    Ok(decoded)
}

fn update_lock_file(
    name: &str,
    version: &str,
    archive_format: &str,
    integrity: &str,
    publisher_public_key: Option<&str>,
) -> Result<()> {
    let lock_path = std::env::current_dir()?.join("dkp.lock");
    let mut lock: LockFile = if lock_path.exists() {
        serde_json::from_str(&std::fs::read_to_string(&lock_path)?)?
    } else {
        LockFile {
            lockfile_version: 1,
            resolved: HashMap::new(),
        }
    };

    lock.resolved.insert(
        name.to_owned(),
        LockedPack {
            version: version.to_owned(),
            archive_format: archive_format.to_owned(),
            integrity: integrity.to_owned(),
            publisher_public_key: publisher_public_key.map(str::to_owned),
        },
    );

    std::fs::write(&lock_path, serde_json::to_string_pretty(&lock)?)?;
    Ok(())
}