arcature-cli 2026.2.0

Developer lifecycle CLI for Arcature applications.
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
//! The bundle assembly — copy the app binary + `public/build/` into the
//! `dist/<target>/` bundle and write the manifest, checksums, SBOM, and
//! license inventory (AP2.1-10).
//!
//! The bundle layout (PROGRAM.md AP2.1-10):
//!
//! ```text
//! dist/<app-target>/
//!     app-binary             # the release executable, renamed
//!     public/build/...       # the Vite production assets (real manifest)
//!     manifest.json          # deterministic manifest of bundled files
//!     checksums.sha256       # sha256sum -c compatible checksums
//!     sbom.spdx.json         # SPDX 2.3 SBOM
//!     licenses/              # LICENSE texts
//! ```
//!
//! # Security: no secrets, no `.env`, no dev source
//!
//! The copy step refuses to bundle any file matching the secret/dev-source
//! denylist (`.env*`, `*.pem`, `*.key`, `node_modules/`, `.git/`, source
//! `.rs`/`.ts`/`.tsx`/`.vue`, `target/`, `.arcature/` dev artifacts). This
//! is defense in depth — `arc build` produces only the binary and
//! `public/build/`, so the denylist catches accidental inclusions from a
//! misconfigured Vite `outDir` or a future template change. The bundle is
//! the production artifact; it must never carry secrets or source.

use std::path::{Path, PathBuf};

use super::checksums;
use super::error::PackageError;
use super::licenses::LicenseInventory;
use super::manifest::{Manifest, ManifestFile, relative_path};
use super::sbom::SpdxDocument;

/// The secret/dev-source denylist. A path component or suffix that, if
/// matched, refuses the file. Lowercased for the suffix check.
const FORBIDDEN_SUFFIXES: &[&str] = &[
    ".env", ".pem", ".key", ".p12", ".pfx", ".rs", ".ts", ".tsx", ".vue", ".jsx", ".sql",
];

const FORBIDDEN_COMPONENTS: &[&str] = &[
    "node_modules",
    ".git",
    "target",
    ".arcature",
    "dist",
    ".vscode",
    ".idea",
];

/// Whether a bundle candidate path is forbidden (a secret or dev source).
/// Public so the package tests can assert the denylist behavior.
pub(crate) fn is_forbidden(path: &Path) -> bool {
    for comp in path.components() {
        let name = comp.as_os_str().to_string_lossy().to_lowercase();
        if FORBIDDEN_COMPONENTS.iter().any(|c| name == *c) {
            return true;
        }
    }
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    // `.env`, `.env.local`, `.env.production` etc. all start with `.env`.
    if name.starts_with(".env") {
        return true;
    }
    FORBIDDEN_SUFFIXES
        .iter()
        .any(|suffix| name.ends_with(suffix))
}

/// Recursively copy `src` (a directory) into `dest`, preserving structure.
/// Returns the list of copied file paths (absolute). Refuses forbidden
/// files (a defense-in-depth filter; the caller also filters the candidate
/// list before calling).
fn copy_dir_filtered(
    src: &Path,
    dest: &Path,
    bundle_root: &Path,
) -> Result<Vec<PathBuf>, PackageError> {
    let mut copied = Vec::new();
    let entries = std::fs::read_dir(src).map_err(|source| PackageError::Walk {
        root: src.to_path_buf(),
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| PackageError::Walk {
            root: src.to_path_buf(),
            source,
        })?;
        let path = entry.path();
        let rel = path.strip_prefix(src).unwrap_or(&path);
        let dest_path = dest.join(rel);
        // The bundle-relative path (from the bundle root) is what the
        // denylist checks, so `public/build/.env` is caught.
        let bundle_rel = dest_path.strip_prefix(bundle_root).unwrap_or(&dest_path);
        if is_forbidden(bundle_rel) {
            return Err(PackageError::Forbidden {
                what: "file",
                path: path.clone(),
            });
        }
        if path.is_dir() {
            std::fs::create_dir_all(&dest_path).map_err(|source| PackageError::Write {
                path: dest_path.clone(),
                source,
            })?;
            copied.extend(copy_dir_filtered(&path, &dest_path, bundle_root)?);
        } else {
            std::fs::create_dir_all(dest_path.parent().unwrap_or(dest_path.as_path())).map_err(
                |source| PackageError::Write {
                    path: dest_path.clone(),
                    source,
                },
            )?;
            std::fs::copy(&path, &dest_path).map_err(|err| PackageError::Copy {
                what: "asset",
                from: path.clone(),
                source: err,
            })?;
            copied.push(dest_path);
        }
    }
    Ok(copied)
}

/// The assembled bundle: its root and the bundled file list. The direct
/// Rust dependencies are passed into [`assemble`] for the SPDX SBOM but are
/// not retained on the bundle (the SBOM file is the record; the in-memory
/// list has no consumer after assembly).
#[derive(Debug)]
pub(crate) struct Bundle {
    pub root: PathBuf,
    pub files: Vec<PathBuf>,
}

/// Assemble the production artifact bundle at `dist/<app_target>` under
/// `dist_root`.
///
/// `app_binary` is the path to the release executable (e.g.
/// `target/release/<backend_binary>`). `public_build` is the path to the
/// Vite production output (e.g. `public/build`). `application` is the app
/// name; `framework_version` is `arcature::FRAMEWORK_VERSION`; `target` is
/// the build target triple; `created_at` is the RFC 3339 timestamp.
/// `framework_root` is the Arcature workspace root (for the LICENSE copy).
/// `dependencies` is the list of direct Rust crate deps for the SBOM.
///
/// Returns the assembled [`Bundle`] (root + bundled file list + deps).
///
/// The argument count is intentional: every input is a distinct, named
/// production concern (the bundle location, the two build artifacts, four
/// metadata strings, the workspace context for license discovery, and the
/// SBOM dependency list). Grouping them into a struct would be an
/// abstraction with a single caller (AGENTS.md §2); the named-argument
/// form is the clearer contract. Matches the `arcature-build` codegen
/// precedent.
#[allow(clippy::too_many_arguments)]
pub(crate) fn assemble(
    dist_root: &Path,
    app_target: &str,
    app_binary: &Path,
    public_build: &Path,
    application: &str,
    framework_version: &str,
    target: &str,
    created_at: &str,
    framework_root: &Path,
    app_root: &Path,
    dependencies: Vec<(String, String)>,
) -> Result<Bundle, PackageError> {
    let bundle_root = dist_root.join(app_target);
    // Clean a stale bundle for reproducibility.
    if bundle_root.exists() {
        std::fs::remove_dir_all(&bundle_root).map_err(|source| PackageError::Write {
            path: bundle_root.clone(),
            source,
        })?;
    }
    std::fs::create_dir_all(&bundle_root).map_err(|source| PackageError::Write {
        path: bundle_root.clone(),
        source,
    })?;

    let mut bundled: Vec<PathBuf> = Vec::new();

    // 1. The app binary, copied as `app-binary` (stable name; the deploy
    //    orchestrator and runtime know this name, not the app's package
    //    name — so the same deploy tooling works for any app).
    if !app_binary.is_file() {
        return Err(PackageError::Missing {
            what: "app binary",
            path: app_binary.to_path_buf(),
        });
    }
    let binary_dest = bundle_root.join("app-binary");
    std::fs::copy(app_binary, &binary_dest).map_err(|err| PackageError::Copy {
        what: "app binary",
        from: app_binary.to_path_buf(),
        source: err,
    })?;
    bundled.push(binary_dest);

    // 2. The Vite production assets, copied into `public/build/`.
    if !public_build.is_dir() {
        return Err(PackageError::Missing {
            what: "frontend build",
            path: public_build.to_path_buf(),
        });
    }
    let assets_dest = bundle_root.join("public").join("build");
    std::fs::create_dir_all(&assets_dest).map_err(|source| PackageError::Write {
        path: assets_dest.clone(),
        source,
    })?;
    bundled.extend(copy_dir_filtered(public_build, &assets_dest, &bundle_root)?);

    // 3. The license inventory.
    let licenses_dir = bundle_root.join("licenses");
    let inv = LicenseInventory::discover(app_root, framework_root)?;
    let copied_licenses = inv.write(&licenses_dir)?;
    for (_name, dest) in copied_licenses {
        bundled.push(dest);
    }

    // Build the manifest file entries (path + size + sha256). The checksums
    // are computed once and reused for both the manifest and the
    // checksums.sha256 file (deterministic, no double-read).
    let mut manifest_files = Vec::with_capacity(bundled.len());
    let mut checksum_entries: Vec<(String, String)> = Vec::with_capacity(bundled.len());
    for file in &bundled {
        let rel = relative_path(&bundle_root, file);
        let size = std::fs::metadata(file)
            .map_err(|source| PackageError::Read {
                path: file.clone(),
                source,
            })?
            .len();
        let sha = checksums::file_sha256(file)?;
        manifest_files.push(ManifestFile {
            path: rel.clone(),
            size,
            sha256: sha.clone(),
        });
        checksum_entries.push((sha, rel));
    }

    // 4. The manifest.
    let manifest = Manifest::new(
        application.to_owned(),
        framework_version.to_owned(),
        target.to_owned(),
        created_at.to_owned(),
        manifest_files,
    );
    let manifest_path = bundle_root.join("manifest.json");
    manifest.write(&manifest_path)?;
    bundled.push(manifest_path.clone());

    // 5. The checksums (sha256sum -c compatible, sorted by path).
    checksum_entries.sort_by(|a, b| a.1.cmp(&b.1));
    let mut checksums_content = String::new();
    for (sha, rel) in &checksum_entries {
        checksums_content.push_str(sha);
        checksums_content.push_str("  ");
        checksums_content.push_str(rel);
        checksums_content.push('\n');
    }
    let checksums_path = bundle_root.join("checksums.sha256");
    checksums::write_checksums(&checksums_path, &checksums_content)?;
    bundled.push(checksums_path.clone());

    // 6. The SPDX SBOM.
    let sbom = SpdxDocument::new(application, framework_version, created_at, &dependencies);
    let sbom_path = bundle_root.join("sbom.spdx.json");
    sbom.write(&sbom_path)?;
    bundled.push(sbom_path.clone());

    // Sort the bundled list for deterministic enumeration (the manifest
    // and checksums already sorted their slices; this sorts the top-level
    // list the caller uses).
    bundled.sort();

    Ok(Bundle {
        root: bundle_root,
        files: bundled,
    })
}

#[cfg(test)]
mod tests {
    use super::{assemble, is_forbidden};
    use std::fs;
    use std::path::Path;

    /// A tiny fixture app: a fake binary, a fake `public/build/`, a
    /// LICENSE, and a Cargo.lock with one dep. Used by the package tests.
    pub(crate) fn build_fixture(root: &Path) {
        // The release binary.
        let bin_dir = root.join("target").join("release");
        fs::create_dir_all(&bin_dir).expect("dir");
        fs::write(bin_dir.join("demo"), b"#!/bin/sh\necho demo\n").expect("binary");
        // The frontend build.
        let build_dir = root.join("public").join("build").join("assets");
        fs::create_dir_all(&build_dir).expect("dir");
        fs::write(build_dir.join("app.js"), b"console.log('app');\n").expect("app.js");
        fs::write(build_dir.join("style.css"), b"body{color:#000}\n").expect("css");
        fs::write(
            root.join("public").join("build").join("manifest.json"),
            b"{}\n",
        )
        .expect("manifest");
        // The LICENSE.
        fs::write(root.join("LICENSE"), b"MIT\n").expect("license");
    }

    #[test]
    fn forbidlist_catches_secrets_and_dev_source() {
        assert!(is_forbidden(Path::new(".env")));
        assert!(is_forbidden(Path::new(".env.local")));
        assert!(is_forbidden(Path::new(".env.production")));
        assert!(is_forbidden(Path::new("secret.pem")));
        assert!(is_forbidden(Path::new("id_rsa.key")));
        assert!(is_forbidden(Path::new("src/main.rs")));
        assert!(is_forbidden(Path::new("src/App.tsx")));
        assert!(is_forbidden(Path::new("frontend/src/main.ts")));
        assert!(is_forbidden(Path::new("schema.sql")));
        assert!(is_forbidden(Path::new("node_modules/react/index.js")));
        assert!(is_forbidden(Path::new(".git/config")));
        assert!(is_forbidden(Path::new("target/release/demo")));
        assert!(is_forbidden(Path::new(".arcature/app-manifest.json")));
    }

    #[test]
    fn forbidlist_allows_production_assets() {
        assert!(!is_forbidden(Path::new("app-binary")));
        assert!(!is_forbidden(Path::new("public/build/assets/app.js")));
        assert!(!is_forbidden(Path::new("public/build/assets/style.css")));
        assert!(!is_forbidden(Path::new("public/build/manifest.json")));
        assert!(!is_forbidden(Path::new("manifest.json")));
        assert!(!is_forbidden(Path::new("checksums.sha256")));
        assert!(!is_forbidden(Path::new("sbom.spdx.json")));
        assert!(!is_forbidden(Path::new("licenses/LICENSE")));
        assert!(!is_forbidden(Path::new("licenses/LICENSE-arcature")));
    }

    #[test]
    fn assemble_produces_full_bundle_layout() {
        let dir = tempfile::tempdir().expect("tempdir");
        let app_root = dir.path().join("app");
        fs::create_dir_all(&app_root).expect("dir");
        build_fixture(&app_root);

        let dist_root = dir.path().join("dist");
        let bundle = assemble(
            &dist_root,
            "demo-x86_64-unknown-linux-gnu",
            &app_root.join("target").join("release").join("demo"),
            &app_root.join("public").join("build"),
            "demo",
            "2026.1.0",
            "x86_64-unknown-linux-gnu",
            "2026-08-17T00:00:00Z",
            dir.path(), // framework root (no LICENSE; skipped)
            &app_root,
            vec![("serde".to_owned(), "1.0.229".to_owned())],
        )
        .expect("assemble");

        // The bundle root exists with the expected layout.
        assert!(bundle.root.join("app-binary").is_file());
        assert!(bundle.root.join("public/build/assets/app.js").is_file());
        assert!(bundle.root.join("public/build/assets/style.css").is_file());
        assert!(bundle.root.join("public/build/manifest.json").is_file());
        assert!(bundle.root.join("manifest.json").is_file());
        assert!(bundle.root.join("checksums.sha256").is_file());
        assert!(bundle.root.join("sbom.spdx.json").is_file());
        assert!(bundle.root.join("licenses/LICENSE").is_file());

        // The manifest lists every bundled file with sha256 + size.
        let manifest_text =
            fs::read_to_string(bundle.root.join("manifest.json")).expect("manifest");
        let manifest: serde_json::Value =
            serde_json::from_str(&manifest_text).expect("parse manifest");
        assert_eq!(manifest["schema_version"], 1);
        assert_eq!(manifest["application"], "demo");
        assert_eq!(manifest["framework_version"], "2026.1.0");
        assert_eq!(manifest["target"], "x86_64-unknown-linux-gnu");
        let files = manifest["files"].as_array().expect("files array");
        assert!(files.iter().any(|f| f["path"] == "app-binary"));
        assert!(
            files
                .iter()
                .any(|f| f["path"] == "public/build/assets/app.js")
        );
        // Every file has a 64-char hex sha256.
        for f in files {
            let sha = f["sha256"].as_str().expect("sha");
            assert_eq!(sha.len(), 64);
            assert!(sha.chars().all(|c| c.is_ascii_hexdigit()));
        }

        // The checksums file is sha256sum-compatible and sorted.
        let checksums_text =
            fs::read_to_string(bundle.root.join("checksums.sha256")).expect("checksums");
        let lines: Vec<&str> = checksums_text.lines().collect();
        assert!(lines.iter().all(|l| l.contains("  ")));
        // Sorted by path.
        let paths: Vec<&str> = lines
            .iter()
            .map(|l| l.split("  ").nth(1).unwrap_or(""))
            .collect();
        let mut sorted = paths.clone();
        sorted.sort();
        assert_eq!(paths, sorted);
        // No backslash even on Windows.
        assert!(!checksums_text.contains('\\'));

        // The SBOM is valid SPDX 2.3 JSON.
        let sbom_text = fs::read_to_string(bundle.root.join("sbom.spdx.json")).expect("sbom");
        let sbom: serde_json::Value = serde_json::from_str(&sbom_text).expect("parse sbom");
        assert_eq!(sbom["spdxVersion"], "SPDX-2.3");
        assert_eq!(sbom["dataLicense"], "CC0-1.0");
        // Application + Arcature + 1 dep = 3 packages.
        let packages = sbom["packages"].as_array().expect("packages");
        assert_eq!(packages.len(), 3);

        let _ = Path::new(&bundle.root);
    }

    #[test]
    fn assemble_refuses_to_bundle_secrets() {
        let dir = tempfile::tempdir().expect("tempdir");
        let app_root = dir.path().join("app");
        fs::create_dir_all(&app_root).expect("dir");
        build_fixture(&app_root);
        // Sneak a .env into the frontend build (a misconfigured Vite outDir).
        fs::write(
            app_root.join("public").join("build").join(".env"),
            b"SECRET=leaked\n",
        )
        .expect("env");

        let dist_root = dir.path().join("dist");
        let result = assemble(
            &dist_root,
            "demo",
            &app_root.join("target").join("release").join("demo"),
            &app_root.join("public").join("build"),
            "demo",
            "2026.1.0",
            "x86_64-unknown-linux-gnu",
            "2026-08-17T00:00:00Z",
            dir.path(),
            &app_root,
            vec![],
        );
        assert!(
            matches!(result, Err(super::PackageError::Forbidden { .. })),
            "must refuse to bundle .env, got: {result:?}"
        );
    }

    #[test]
    fn assemble_fails_without_app_binary() {
        let dir = tempfile::tempdir().expect("tempdir");
        let app_root = dir.path().join("app");
        fs::create_dir_all(&app_root).expect("dir");
        // No binary, no build.
        let dist_root = dir.path().join("dist");
        let result = assemble(
            &dist_root,
            "demo",
            &app_root.join("target").join("release").join("demo"),
            &app_root.join("public").join("build"),
            "demo",
            "2026.1.0",
            "x86_64-unknown-linux-gnu",
            "2026-08-17T00:00:00Z",
            dir.path(),
            &app_root,
            vec![],
        );
        assert!(matches!(result, Err(super::PackageError::Missing { .. })));
    }

    #[test]
    fn assemble_is_reproducible() {
        let dir = tempfile::tempdir().expect("tempdir");
        let app_root = dir.path().join("app");
        fs::create_dir_all(&app_root).expect("dir");
        build_fixture(&app_root);
        let dist_root = dir.path().join("dist");

        let assemble_once = || {
            let bundle = assemble(
                &dist_root,
                "demo",
                &app_root.join("target").join("release").join("demo"),
                &app_root.join("public").join("build"),
                "demo",
                "2026.1.0",
                "x86_64-unknown-linux-gnu",
                "2026-08-17T00:00:00Z",
                dir.path(),
                &app_root,
                vec![],
            )
            .expect("assemble");
            (
                fs::read_to_string(bundle.root.join("manifest.json")).expect("manifest"),
                fs::read_to_string(bundle.root.join("checksums.sha256")).expect("checksums"),
                fs::read_to_string(bundle.root.join("sbom.spdx.json")).expect("sbom"),
            )
        };
        let (m1, c1, s1) = assemble_once();
        let (m2, c2, s2) = assemble_once();
        assert_eq!(m1, m2, "manifest deterministic");
        assert_eq!(c1, c2, "checksums deterministic");
        assert_eq!(s1, s2, "sbom deterministic");
    }
}