day-cli 0.3.0

Declarative app development API using native UI toolkits
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
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! macos-appkit → .app assembly → codesign (inside-out, never `--deep`) → .dmg (UDZO) →
//! notarytool submit (ASC API key) → stapler → verify. Stage order is normative (hoppack lineage,
//! DESIGN.md §16.5). Ad-hoc signing remains the default when no identity is configured.

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

use super::settings::{PackOptions, resolve_degradable};
use super::{Artifact, PackError, SignTier, run_tool};
use crate::meta::Project;
use crate::ops::{self, status};
use crate::targets::Target;

pub fn pack(
    project: &Project,
    target: &'static Target,
    opts: &PackOptions,
    dist: &Path,
) -> Result<Artifact, PackError> {
    let outcome = ops::build(project, target, opts.profile).map_err(PackError::Other)?;
    let name = &project.manifest.app.name;
    // A scaffolded app (platform/macos/, §17.4) builds as a whole `.app`; this packer still
    // assembles its own bundle, so take the inner binary — the bundle's single
    // Contents/MacOS entry, named by the pbxproj's PRODUCT_NAME rather than the crate.
    // (Packing the Xcode bundle as-is is the planned follow-up — signing/dmg/notarization
    // stay identical either way.)
    let built_binary = if outcome.artifact.extension().and_then(|e| e.to_str()) == Some("app") {
        let macos_dir = outcome.artifact.join("Contents/MacOS");
        std::fs::read_dir(&macos_dir)
            .ok()
            .and_then(|rd| rd.flatten().map(|e| e.path()).next())
            .ok_or_else(|| {
                PackError::Other(format!("no executable under {}", macos_dir.display()))
            })?
    } else {
        outcome.artifact.clone()
    };
    let title = project
        .manifest
        .app
        .title
        .clone()
        .unwrap_or_else(|| name.clone());
    let version = &project.manifest.app.version;

    // --- assemble ---------------------------------------------------------
    let stage = project.root.join("build/day/pack/macos-appkit");
    let app = stage.join(format!("{title}.app"));
    let _ = std::fs::remove_dir_all(&stage);
    let macos_dir = app.join("Contents/MacOS");
    let res_dir = app.join("Contents/Resources");
    std::fs::create_dir_all(&macos_dir).map_err(|e| PackError::Other(e.to_string()))?;
    std::fs::create_dir_all(&res_dir).map_err(|e| PackError::Other(e.to_string()))?;
    std::fs::copy(&built_binary, macos_dir.join(name))
        .map_err(|e| PackError::Other(e.to_string()))?;
    let assets = project.root.join("resource/assets");
    if assets.is_dir() {
        super::copy_tree(&assets, &res_dir.join("assets")).map_err(PackError::Other)?;
    }
    // Bundled images (§18.3): day-appkit resolves `image("name")` through the exe-relative
    // `../Resources/images` probe when the `day launch` env roots are absent.
    let images = project.root.join("resource/images");
    if images.is_dir() {
        super::copy_tree(&images, &res_dir.join("images")).map_err(PackError::Other)?;
    }
    // Vector glyphs (docs/vectors.md): the staged SVGs (`Resources/vectors/svg`, what
    // day-appkit renders — NSImage draws SVG at display size) plus the raster cache
    // (`Resources/vectors/raster`, the shared fallback resolution).
    for (from, to) in [
        (crate::resources::vector_svg_dir(project), "vectors/svg"),
        (
            crate::resources::vector_fallback_dir(project, target.toolkit),
            "vectors/raster",
        ),
    ] {
        if from.is_dir() {
            super::copy_tree(&from, &res_dir.join(to)).map_err(PackError::Other)?;
        }
    }
    // Bundled fonts (§18.4): day-appkit registers Resources/fonts with CoreText at startup.
    let fonts = project.root.join("resource/fonts");
    if fonts.is_dir() {
        super::copy_tree(&fonts, &res_dir.join("fonts")).map_err(PackError::Other)?;
    }
    // SBOM into the bundle when [sbom] mode = embed (§20.4), so the app can read its own
    // license notices at runtime.
    if project.manifest.sbom.mode == crate::meta::SbomMode::Embed {
        crate::provenance::embed_into(&project.root.join("build/day/sbom"), &res_dir)
            .map_err(PackError::Other)?;
    }
    let icon_entry = build_icns(project, &res_dir)
        .map(|_| "  <key>CFBundleIconFile</key><string>AppIcon</string>\n")
        .unwrap_or_default();
    let plist = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>CFBundleExecutable</key><string>{name}</string>
  <key>CFBundleIdentifier</key><string>{id}</string>
  <key>CFBundleName</key><string>{title}</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>CFBundleShortVersionString</key><string>{version}</string>
  <key>CFBundleVersion</key><string>{build}</string>
  <key>NSHighResolutionCapable</key><true/>
{icon_entry}</dict></plist>
"#,
        id = project.manifest.app.id,
        build = project.manifest.app.build,
    );
    std::fs::write(app.join("Contents/Info.plist"), plist)
        .map_err(|e| PackError::Other(e.to_string()))?;

    // --- sign ---------------------------------------------------------------
    let tier = if opts.no_sign {
        status("Signing", "skipped (--no-sign)");
        SignTier::Unsigned
    } else {
        sign_app(project, &app).map_err(PackError::Sign)?
    };

    // --- package (dmg) ------------------------------------------------------
    // The staging folder holds the .app plus an /Applications symlink for drag-install.
    #[cfg(unix)]
    {
        let link = stage.join("Applications");
        if !link.exists() {
            let _ = std::os::unix::fs::symlink("/Applications", &link);
        }
    }
    // The .app inside keeps the display title (that is what /Applications shows); the container
    // takes the shared release name, so it matches every other target's artifact (§20.4).
    let dmg = dist.join(super::naming::artifact_file(
        project,
        target,
        opts,
        &[],
        "dmg",
    ));
    let _ = std::fs::remove_file(&dmg);
    status("Packing", "hdiutil create (UDZO)");
    run_tool(
        Command::new("hdiutil")
            .args(["create", "-quiet", "-volname", &title, "-srcfolder"])
            .arg(&stage)
            .args(["-ov", "-format", "UDZO"])
            .arg(&dmg),
        "hdiutil",
    )
    .map_err(PackError::Other)?;

    if tier == SignTier::Release {
        // The dmg container gets its own signature (Developer ID Application identity).
        let identity = resolved_identity(project)
            .map_err(PackError::Sign)?
            .unwrap();
        status("Signing", "codesign (dmg)");
        run_tool(
            Command::new("codesign")
                .args(["--force", "--timestamp", "-s", &identity])
                .args(["-i", &format!("{}.dmg", project.manifest.app.id)])
                .arg(&dmg),
            "codesign (dmg)",
        )
        .map_err(PackError::Sign)?;

        // --- notarize + staple (outermost container only) --------------------
        if !opts.no_notarize {
            notarize(project, opts, &dmg)?;
        } else {
            status("Notarize", "skipped (--no-notarize)");
        }
    }

    Ok(Artifact {
        path: dmg,
        kind: "dmg",
        sha256: String::new(),
        tier,
    })
}

/// The resolved signing identity: None/"-" ⇒ ad-hoc. A missing secret degrades (§20), it never fails.
fn resolved_identity(project: &Project) -> Result<Option<String>, String> {
    let Some(mac) = project
        .manifest
        .signing
        .as_ref()
        .and_then(|s| s.macos.as_ref())
    else {
        return Ok(None);
    };
    let Some(raw) = mac.identity.as_ref() else {
        return Ok(None);
    };
    match resolve_degradable(raw, "signing.macos.identity")? {
        Some(id) if id != "-" && !id.is_empty() => Ok(Some(id)),
        _ => Ok(None),
    }
}

/// Sign the bundle inside-out: nested code first (Frameworks, non-main executables), the bundle
/// last. Never `--deep` — Apple's guidance, and the class of bug that bit macdeployqt/Tauri.
fn sign_app(project: &Project, app: &Path) -> Result<SignTier, String> {
    // Finder metadata xattrs make codesign fail with "resource fork, Finder information..." — strip.
    let _ = Command::new("xattr").args(["-crs"]).arg(app).status();

    let identity = resolved_identity(project)?;
    let entitlements: Option<PathBuf> = project
        .manifest
        .signing
        .as_ref()
        .and_then(|s| s.macos.as_ref())
        .and_then(|m| m.entitlements.as_ref())
        .map(|p| project.root.join(p));
    if let Some(e) = &entitlements
        && !e.exists()
    {
        return Err(format!("entitlements file not found: {}", e.display()));
    }

    let mut nested = nested_signables(app);
    nested.push(app.to_path_buf()); // the bundle itself is signed LAST

    match &identity {
        Some(id) => {
            status("Signing", &format!("codesign ({id})"));
            for item in &nested {
                let mut cmd = Command::new("codesign");
                cmd.args(["--force", "--timestamp", "--options", "runtime", "-s", id]);
                // Entitlements apply to the main executable (via the bundle), never to dylibs.
                if item == app
                    && let Some(e) = &entitlements
                {
                    cmd.arg("--entitlements").arg(e);
                }
                cmd.arg(item);
                run_tool(&mut cmd, "codesign")?;
            }
            Ok(SignTier::Release)
        }
        None => {
            status("Signing", "ad-hoc codesign (no signing.macos.identity)");
            for item in &nested {
                run_tool(
                    Command::new("codesign")
                        .args(["--force", "-s", "-"])
                        .arg(item),
                    "codesign (ad-hoc)",
                )?;
            }
            Ok(SignTier::DevSigned)
        }
    }
}

/// Nested code that must be signed before the bundle: dylibs and frameworks under
/// Contents/Frameworks, and helper executables in Contents/MacOS beyond the main binary.
/// Today's Day bundles carry none of these — the walk future-proofs piece-contributed dylibs.
fn nested_signables(app: &Path) -> Vec<PathBuf> {
    let mut items = Vec::new();
    let frameworks = app.join("Contents/Frameworks");
    if let Ok(entries) = std::fs::read_dir(&frameworks) {
        for e in entries.flatten() {
            items.push(e.path()); // dylib or .framework — codesign handles either
        }
    }
    items
}

/// notarytool submit → (wait) → staple → gatekeeper verify.
fn notarize(project: &Project, opts: &PackOptions, dmg: &Path) -> Result<(), PackError> {
    let Some(not) = project
        .manifest
        .signing
        .as_ref()
        .and_then(|s| s.macos.as_ref())
        .and_then(|m| m.notarize.as_ref())
    else {
        status(
            "Notarize",
            "skipped — no signing.macos.notarize config (artifact will not pass Gatekeeper)",
        );
        return Ok(());
    };
    // Missing notary secrets degrade to "signed but not notarized" (§20) — loudly, never fatally.
    let resolved = (
        resolve_degradable(&not.key_id, "signing.macos.notarize.key-id")
            .map_err(PackError::Sign)?,
        resolve_degradable(&not.issuer, "signing.macos.notarize.issuer")
            .map_err(PackError::Sign)?,
        resolve_degradable(&not.key_path, "signing.macos.notarize.key-path")
            .map_err(PackError::Sign)?,
    );
    let (Some(key_id), Some(issuer), Some(key_path)) = resolved else {
        status(
            "Notarize",
            "skipped — notary secrets unresolved (artifact is signed but NOT notarized)",
        );
        return Ok(());
    };
    if !Path::new(&key_path).exists() {
        return Err(PackError::Sign(format!(
            "notarize key file not found: {key_path}"
        )));
    }

    status("Notarize", "notarytool submit");
    let mut cmd = Command::new("xcrun");
    cmd.args(["notarytool", "submit"])
        .arg(dmg)
        .args(["--key", &key_path, "--key-id", &key_id, "--issuer", &issuer])
        .args(["--output-format", "json"]);
    if !opts.no_wait {
        cmd.arg("--wait");
    }
    let out = cmd
        .output()
        .map_err(|e| PackError::Sign(format!("notarytool: {e}")))?;
    let stdout = String::from_utf8_lossy(&out.stdout);
    let json: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_default();
    let id = json["id"].as_str().unwrap_or("<unknown>").to_string();
    if !out.status.success() {
        return Err(PackError::Sign(format!(
            "notarytool submit failed (submission {id}):\n{}",
            String::from_utf8_lossy(&out.stderr)
        )));
    }
    if opts.no_wait {
        status(
            "Notarize",
            &format!("submitted {id} — check later: day sign --notarize-status {id}"),
        );
        return Ok(());
    }
    let notary_status = json["status"].as_str().unwrap_or("");
    if notary_status != "Accepted" {
        // Pull the notary log into the error — the status alone ("Invalid") is undiagnosable.
        let log = Command::new("xcrun")
            .args(["notarytool", "log", &id])
            .args(["--key", &key_path, "--key-id", &key_id, "--issuer", &issuer])
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
            .unwrap_or_default();
        return Err(PackError::Sign(format!(
            "notarization {notary_status} (submission {id}):\n{log}"
        )));
    }
    status("Notarize", &format!("accepted ({id})"));

    status("Stapling", "xcrun stapler staple");
    run_tool(
        Command::new("xcrun").args(["stapler", "staple"]).arg(dmg),
        "stapler",
    )
    .map_err(PackError::Sign)?;

    // Verify what Gatekeeper will actually do with the shipped container.
    let ok = Command::new("spctl")
        .args(["-a", "-t", "open", "--context", "context:primary-signature"])
        .arg(dmg)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if ok {
        status("Verified", "spctl accepts the notarized dmg");
    } else {
        status(
            "Warning",
            "spctl did not accept the dmg (check staple/notarization)",
        );
    }
    Ok(())
}

/// Build Contents/Resources/AppIcon.icns from the project's icons/macos PNGs via sips + iconutil.
/// Best-effort: a missing icon set or tool must not fail the pack (the dmg just has no icon).
fn build_icns(project: &Project, res_dir: &Path) -> Option<()> {
    let source = crate::resources::app_icon(project, "appkit")?;
    let iconset = project.root.join("build/day/pack/AppIcon.iconset");
    let _ = std::fs::remove_dir_all(&iconset);
    std::fs::create_dir_all(&iconset).ok()?;
    // The canonical iconset slots, rendered from the largest available PNG.
    for (px, name) in [
        (16, "icon_16x16.png"),
        (32, "icon_16x16@2x.png"),
        (32, "icon_32x32.png"),
        (64, "icon_32x32@2x.png"),
        (128, "icon_128x128.png"),
        (256, "icon_128x128@2x.png"),
        (256, "icon_256x256.png"),
        (512, "icon_256x256@2x.png"),
        (512, "icon_512x512.png"),
        (1024, "icon_512x512@2x.png"),
    ] {
        let px_s = px.to_string();
        let ok = Command::new("sips")
            .args(["-z", &px_s, &px_s])
            .arg(&source)
            .arg("--out")
            .arg(iconset.join(name))
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        if !ok {
            return None;
        }
    }
    let ok = Command::new("iconutil")
        .args(["-c", "icns", "-o"])
        .arg(res_dir.join("AppIcon.icns"))
        .arg(&iconset)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    ok.then_some(())
}