@powerhousedao/desktop 6.2.3-dev.99 → 6.3.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,166 @@ import { execSync, spawn, spawnSync } from "node:child_process";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
8
  import { normalizePluginEntries } from "@powerhousedao/host-core";
9
9
  import { isPassthroughImageRef } from "@powerhousedao/shared/connect/image-ref";
10
+ //#region src/release.ts
11
+ /**
12
+ * What a build of an app with updates leaves for its release (app.json
13
+ * `updates`): under `<shell>/target/release/bundle/release/`, every installer
14
+ * it made, under a name no host rewrites, and the feed file that tells the
15
+ * running apps of this system about them. Attach every file in that folder to
16
+ * the release and the apps find it.
17
+ *
18
+ * One feed file per system and processor (`latest-linux-x86_64.json`), not one
19
+ * for the whole release: each system builds in its own job, and a job that
20
+ * fails then costs its own users the update and nobody else's. The app asks
21
+ * for its own file by name (FEED_FILE_TEMPLATE).
22
+ */
23
+ /** Under the bundle folder: this build's release files. */
24
+ const RELEASE_DIR = "release";
25
+ /** The feed file a build writes for its system and processor. */
26
+ function feedFileName(os, arch) {
27
+ return `latest-${os}-${arch}.json`;
28
+ }
29
+ /** That name in a feed address: the updater fills in the running app's own
30
+ * system (linux, darwin, windows) and processor (x86_64, aarch64, …). */
31
+ const FEED_FILE_TEMPLATE = "latest-{{target}}-{{arch}}.json";
32
+ /** The updater's names for the systems and processors Node reports. */
33
+ const UPDATER_OS = {
34
+ linux: "linux",
35
+ darwin: "darwin",
36
+ win32: "windows"
37
+ };
38
+ const UPDATER_ARCH = {
39
+ x64: "x86_64",
40
+ arm64: "aarch64",
41
+ ia32: "i686",
42
+ arm: "armv7"
43
+ };
44
+ const ARTIFACTS = {
45
+ linux: [
46
+ {
47
+ dir: "deb",
48
+ suffix: ".deb",
49
+ installer: "deb"
50
+ },
51
+ {
52
+ dir: "rpm",
53
+ suffix: ".rpm",
54
+ installer: "rpm"
55
+ },
56
+ {
57
+ dir: "appimage",
58
+ suffix: ".AppImage",
59
+ installer: "appimage"
60
+ }
61
+ ],
62
+ win32: [{
63
+ dir: "nsis",
64
+ suffix: "-setup.exe",
65
+ installer: "nsis"
66
+ }],
67
+ darwin: [{
68
+ dir: "dmg",
69
+ suffix: ".dmg"
70
+ }, {
71
+ dir: "macos",
72
+ suffix: ".app.tar.gz",
73
+ installer: "app"
74
+ }]
75
+ };
76
+ /** A file name every host keeps as it is: GitHub rewrites a space (and most
77
+ * punctuation) in a release file's name to a dot, and a feed that names the
78
+ * file as it was built would then point at nothing. */
79
+ function releaseFileName(name) {
80
+ return name.replace(/[^A-Za-z0-9._-]/g, ".");
81
+ }
82
+ /**
83
+ * Where a release's files are downloaded from: PH_DESKTOP_RELEASE_URL when
84
+ * set, else the GitHub release of app.json's `updates.github` under this
85
+ * build's tag (the tag a workflow runs for, else `v<version>`). null when
86
+ * neither says: the build then writes no feed file.
87
+ */
88
+ function releaseBaseUrl(updates, version, env) {
89
+ const given = env.PH_DESKTOP_RELEASE_URL?.trim();
90
+ if (given) {
91
+ let url = null;
92
+ try {
93
+ url = new URL(given);
94
+ } catch {}
95
+ if (url?.protocol !== "https:") throw new Error(`PH_DESKTOP_RELEASE_URL must be the https address the release's files are downloaded from, not "${given}".`);
96
+ return given.replace(/\/+$/, "");
97
+ }
98
+ if (!updates.github) return null;
99
+ const tag = env.GITHUB_REF_TYPE === "tag" && env.GITHUB_REF_NAME ? env.GITHUB_REF_NAME : `v${version ?? "0.1.0"}`;
100
+ return `https://github.com/${updates.github}/releases/download/${encodeURIComponent(tag)}`;
101
+ }
102
+ /** A second's slack: some filesystems keep a file's time to the second. */
103
+ const TIME_SLACK_MS = 1e3;
104
+ /** Gathers this build's release files and writes its feed file. */
105
+ function collectRelease(input) {
106
+ const platform = input.platform ?? process.platform;
107
+ const os = UPDATER_OS[platform];
108
+ const arch = UPDATER_ARCH[input.arch ?? process.arch];
109
+ const dir = path.join(input.bundleDir, RELEASE_DIR);
110
+ fs.rmSync(dir, {
111
+ recursive: true,
112
+ force: true
113
+ });
114
+ fs.mkdirSync(dir, { recursive: true });
115
+ const result = {
116
+ dir,
117
+ files: [],
118
+ feed: null,
119
+ targets: [],
120
+ unsigned: []
121
+ };
122
+ if (!os || !arch) return result;
123
+ const fresh = (file) => fs.existsSync(file) && (input.since === void 0 || fs.statSync(file).mtimeMs >= input.since - TIME_SLACK_MS);
124
+ const platforms = {};
125
+ for (const artifact of ARTIFACTS[platform] ?? []) {
126
+ const from = path.join(input.bundleDir, artifact.dir);
127
+ if (!fs.existsSync(from)) continue;
128
+ const built = fs.readdirSync(from).filter((name) => name.endsWith(artifact.suffix)).map((name) => path.join(from, name)).filter((file) => fs.statSync(file).isFile() && fresh(file)).sort((a, b) => fs.statSync(a).mtimeMs - fs.statSync(b).mtimeMs);
129
+ for (const file of built) {
130
+ const name = releaseFileName(artifact.installer === "app" ? `${input.productName}_${input.version}_${arch}${artifact.suffix}` : path.basename(file));
131
+ fs.copyFileSync(file, path.join(dir, name), fs.constants.COPYFILE_FICLONE);
132
+ result.files.push(name);
133
+ if (!artifact.installer) continue;
134
+ const signatureFile = `${file}.sig`;
135
+ if (!fresh(signatureFile)) {
136
+ result.unsigned.push(name);
137
+ continue;
138
+ }
139
+ if (input.baseUrl === null) continue;
140
+ platforms[`${os}-${arch}-${artifact.installer}`] = {
141
+ signature: fs.readFileSync(signatureFile, "utf8").trim(),
142
+ url: `${input.baseUrl}/${name}`
143
+ };
144
+ }
145
+ }
146
+ result.targets = Object.keys(platforms).sort();
147
+ if (result.targets.length > 0) {
148
+ const feed = feedFileName(os, arch);
149
+ fs.writeFileSync(path.join(dir, feed), JSON.stringify({
150
+ version: input.version,
151
+ pub_date: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
152
+ platforms
153
+ }, null, 2) + "\n");
154
+ result.feed = feed;
155
+ result.files.push(feed);
156
+ }
157
+ return result;
158
+ }
159
+ /** What a build says about the release files it gathered. */
160
+ function releaseReport(release, releaseUrl) {
161
+ if (release.files.length === 0) return ["no release files: the build made no installer."];
162
+ const lines = [`release files in ${release.dir}:`];
163
+ for (const file of release.files) lines.push(` ${file}`);
164
+ for (const file of release.unsigned) lines.push(`${file} has no signature, so the feed does not offer it.`);
165
+ if (release.feed) lines.push(`${release.feed} offers ${release.targets.join(", ")} from ${releaseUrl}: attach every file in that folder to the release there.`);
166
+ else if (releaseUrl === null) lines.push("no feed file: set PH_DESKTOP_RELEASE_URL to the address the release's files are downloaded from (app.json names its own feed, not a GitHub repository).");
167
+ return lines;
168
+ }
169
+ //#endregion
10
170
  //#region src/app-json.ts
11
171
  /**
12
172
  * `hosts/desktop/app.json` — the builder's desktop identity (phase 7, mode 1:
@@ -105,6 +265,47 @@ const shellSourceSchema = z.strictObject({
105
265
  /** crates.io version requirement (default DEFAULT_SHELL_CRATE_VERSION). */
106
266
  version: z.string().min(1).optional()
107
267
  }).refine((s) => !(s.path && s.git), { message: "shell.source: set path OR git, not both" }).optional();
268
+ /** What is wrong with a release key, or null. The public half is base64 of a
269
+ * minisign public key, as `tauri signer generate` writes its .pub file; the
270
+ * private half looks alike at a glance and must never land in app.json. */
271
+ function pubkeyProblem(value) {
272
+ const text = Buffer.from(value.trim(), "base64").toString("utf8");
273
+ if (/secret key/i.test(text)) return "this is the PRIVATE key: put the public one here (the .pub file) and keep the private one in your CI secrets";
274
+ if (!/^untrusted comment: minisign public key/i.test(text)) return "not an update signing key: paste the content of the .pub file `tauri signer generate` writes";
275
+ return null;
276
+ }
277
+ /** An update feed's address: https, as a release build asks nothing else. */
278
+ const feedUrlSchema = z.string().refine((value) => {
279
+ try {
280
+ return new URL(value).protocol === "https:";
281
+ } catch {
282
+ return false;
283
+ }
284
+ }, "an update feed must be an https address");
285
+ /** Updates, for an app that wants them: where it asks for a newer version and
286
+ * the key its releases are signed with. The window then offers each newer
287
+ * release, downloads it, checks its signature and installs it. Omitted or
288
+ * null: the app never asks, and is installed by hand as before. */
289
+ const updatesSchema = z.strictObject({
290
+ /** The GitHub repository whose releases carry the app ("owner/name"): the
291
+ * app asks its latest release for the feed file a build of its system
292
+ * wrote (release.ts). */
293
+ github: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, "use \"owner/repository\"").optional(),
294
+ /** Or the feed's own addresses, asked in order. `{{target}}` and
295
+ * `{{arch}}` in one stand for the running app's system and processor,
296
+ * as in the feed file's name: `latest-{{target}}-{{arch}}.json`. */
297
+ endpoints: z.array(feedUrlSchema).min(1).optional(),
298
+ /** The public key the releases are signed with: the content of the .pub
299
+ * file `tauri signer generate` writes. The private key signs each build
300
+ * (TAURI_SIGNING_PRIVATE_KEY) and stays out of the repository. */
301
+ pubkey: z.string().min(1).superRefine((value, ctx) => {
302
+ const problem = pubkeyProblem(value);
303
+ if (problem) ctx.addIssue({
304
+ code: "custom",
305
+ message: problem
306
+ });
307
+ })
308
+ }).refine((u) => Boolean(u.github) !== Boolean(u.endpoints), { message: "updates: set github OR endpoints" }).nullable().optional();
108
309
  const appJsonSchema = z.strictObject({
109
310
  identifier: identifierSchema,
110
311
  productName: z.string().min(1),
@@ -129,14 +330,20 @@ const appJsonSchema = z.strictObject({
129
330
  loading: loadingSchema,
130
331
  window: windowSchema,
131
332
  fileAssociations: z.array(fileAssociationSchema).optional(),
333
+ updates: updatesSchema,
132
334
  shell: shellSourceSchema
133
335
  });
336
+ /** Where an app with updates asks for a newer version. */
337
+ function updateEndpoints(updates) {
338
+ return updates.endpoints ?? [`https://github.com/${updates.github}/releases/latest/download/latest-{{target}}-{{arch}}.json`];
339
+ }
134
340
  /** Default crates.io version requirement for the shell crate (D7.b: the flip
135
341
  * to crates.io default once published — the crate is live). A floor, not just
136
- * a series: 0.1.0 can't run a stack from ph-run, and a Cargo.lock that still
137
- * holds it satisfies "0.1", so a builder's lock would keep it forever. The
138
- * 0.1.0-dev.N releases sort below 0.1.0 and never match either. */
139
- const DEFAULT_SHELL_CRATE_VERSION = "0.1.1";
342
+ * a series: 0.1.0 can't run a stack from ph-run and 0.1.1 has no updater (an
343
+ * app with `updates` would build and never ask), and a Cargo.lock that still
344
+ * holds one of them satisfies "0.1", so a builder's lock would keep it
345
+ * forever. The 0.1.x-dev.N releases sort below 0.1.x and never match either. */
346
+ const DEFAULT_SHELL_CRATE_VERSION = "0.1.2";
140
347
  const APP_JSON_FILE = "app.json";
141
348
  /** Read + validate hosts/<host>/app.json. Throws with the field named on a
142
349
  * bad value, and a clear message when the file is absent. */
@@ -363,6 +570,16 @@ function vendoredFromLocal(stackDir) {
363
570
  const lock = path.join(stackDir, "package-lock.json");
364
571
  return fs.existsSync(lock) && fs.readFileSync(lock, "utf8").includes("\"resolved\": \"file:");
365
572
  }
573
+ /** A tree the backend bundle folded: its packages are chunks under
574
+ * `node_modules/.stack` and stubs npm would take for the installed packages. */
575
+ function foldedByBundle(stackDir) {
576
+ return fs.existsSync(path.join(stackDir, "node_modules", ".stack"));
577
+ }
578
+ /** Whether vendoring must drop the tree it finds instead of installing over
579
+ * it. */
580
+ function vendorsAfresh(stackDir, local) {
581
+ return local || vendoredFromLocal(stackDir) || foldedByBundle(stackDir);
582
+ }
366
583
  /** Types and source maps, which nothing reads at runtime. */
367
584
  const UNREAD_FILE = /\.(d\.[cm]?ts|map)$/i;
368
585
  const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
@@ -451,7 +668,7 @@ function bundleStack(options) {
451
668
  };
452
669
  const vendor = options.vendor !== false;
453
670
  const local = options.localPackagesDir ? readLocalPackages(options.localPackagesDir) : void 0;
454
- if (vendor && (local || vendoredFromLocal(stackDir))) for (const entry of ["node_modules", "package-lock.json"]) fs.rmSync(path.join(stackDir, entry), {
671
+ if (vendor && vendorsAfresh(stackDir, local !== void 0)) for (const entry of ["node_modules", "package-lock.json"]) fs.rmSync(path.join(stackDir, entry), {
455
672
  recursive: true,
456
673
  force: true
457
674
  });
@@ -508,6 +725,14 @@ function bundleStack(options) {
508
725
  const SHELL_DIR = "tauri-shell";
509
726
  /** The icon source the runner feeds to `tauri icon` (copied from app.icon). */
510
727
  const ICON_SOURCE = "app-icon.png";
728
+ /** Beside tauri.conf.json in an app with updates: the settings of a build
729
+ * that has no signing key to hand, which cannot be offered as an update. */
730
+ const UNSIGNED_BUILD_CONF = "tauri.unsigned.conf.json";
731
+ const UPDATE_PERMISSIONS = [
732
+ "update_state",
733
+ "update_check",
734
+ "update_install"
735
+ ].map((command) => `allow-${command.replaceAll("_", "-")}`);
511
736
  /** The version the installers and the macOS bundle carry: the numeric x.y.z
512
737
  * of the project's version, as Windows' bundlers take nothing else. */
513
738
  function bundleVersion(version) {
@@ -527,7 +752,7 @@ function shellDependency(source) {
527
752
  if (source.rev) parts.push(`rev = ${JSON.stringify(source.rev)}`);
528
753
  return `ph-desktop-shell = { ${parts.join(", ")} }`;
529
754
  }
530
- const version = source?.version ?? "0.1.1";
755
+ const version = source?.version ?? "0.1.2";
531
756
  return `ph-desktop-shell = ${JSON.stringify(version)}`;
532
757
  }
533
758
  function cargoToml(app, binName) {
@@ -548,7 +773,10 @@ tauri = { version = "2", features = ["tray-icon", "devtools"] }
548
773
  # permission manifests (shell:allow-spawn etc.) from direct dependencies.
549
774
  tauri-plugin-shell = "2"
550
775
  tauri-plugin-single-instance = "2"
551
- ${shellDependency(app.shell)}
776
+ ${app.updates ? `# The updater's settings are baked in by tauri::generate_context!, whose
777
+ # output names serde_json in this crate.
778
+ serde_json = "1"
779
+ ` : ""}${shellDependency(app.shell)}
552
780
 
553
781
  [[bin]]
554
782
  name = ${JSON.stringify(binName)}
@@ -593,6 +821,9 @@ fn main() {
593
821
  "adopt_old_data",
594
822
  "start_stack",
595
823
  "switch_identity",
824
+ "update_state",
825
+ "update_check",
826
+ "update_install",
596
827
  ]),
597
828
  ))
598
829
  .expect("failed to run tauri-build");
@@ -790,11 +1021,19 @@ function tauriConf(input) {
790
1021
  macOS: {
791
1022
  signingIdentity: "-",
792
1023
  hardenedRuntime: false
793
- }
794
- }
1024
+ },
1025
+ ...app.updates ? { createUpdaterArtifacts: true } : {}
1026
+ },
1027
+ ...app.updates ? { plugins: { updater: {
1028
+ pubkey: app.updates.pubkey.trim(),
1029
+ endpoints: updateEndpoints(app.updates),
1030
+ requireSignedVersion: true
1031
+ } } } : {}
795
1032
  };
796
1033
  return JSON.stringify(conf, null, 2) + "\n";
797
1034
  }
1035
+ /** Laid over tauri.conf.json for a build without the signing key. */
1036
+ const UNSIGNED_BUILD_CONF_JSON = JSON.stringify({ bundle: { createUpdaterArtifacts: false } }, null, 2) + "\n";
798
1037
  function defaultCapability() {
799
1038
  return JSON.stringify({
800
1039
  $schema: "../gen/schemas/desktop-schema.json",
@@ -806,6 +1045,7 @@ function defaultCapability() {
806
1045
  "allow-take-launch-files",
807
1046
  "allow-read-launch-file",
808
1047
  "allow-log-from-webview",
1048
+ ...UPDATE_PERMISSIONS,
809
1049
  {
810
1050
  identifier: "shell:allow-spawn",
811
1051
  allow: [{
@@ -847,7 +1087,8 @@ function connectCapability(connectPort) {
847
1087
  "allow-save-profile",
848
1088
  "allow-adopt-old-data",
849
1089
  "allow-start-stack",
850
- "allow-switch-identity"
1090
+ "allow-switch-identity",
1091
+ ...UPDATE_PERMISSIONS
851
1092
  ]
852
1093
  }, null, 2) + "\n";
853
1094
  }
@@ -951,8 +1192,16 @@ function projectShell(input) {
951
1192
  ["dist-stack/README.md", DIST_STACK_README]
952
1193
  ];
953
1194
  if (app.signIn) files.push(["ui/sign-in.html", loadingHtml(app, art, true)]);
1195
+ if (app.updates) files.push([UNSIGNED_BUILD_CONF, UNSIGNED_BUILD_CONF_JSON]);
954
1196
  let changed = false;
955
1197
  for (const [rel, content] of files) if (writeIfChanged(path.join(shellDir, rel), content)) changed = true;
1198
+ if (!app.updates) {
1199
+ const stale = path.join(shellDir, UNSIGNED_BUILD_CONF);
1200
+ if (fs.existsSync(stale)) {
1201
+ fs.rmSync(stale);
1202
+ changed = true;
1203
+ }
1204
+ }
956
1205
  if (!app.signIn) for (const file of ["sign-in.html", SIGN_IN_SCRIPT]) {
957
1206
  const stale = path.join(shellDir, "ui", file);
958
1207
  if (fs.existsSync(stale)) {
@@ -1052,6 +1301,19 @@ function tauriBundlesForHost(platform = process.platform) {
1052
1301
  default: return ["deb", "appimage"];
1053
1302
  }
1054
1303
  }
1304
+ /** `tauri build`'s arguments. An app with updates signs what it builds, so
1305
+ * without the key (`TAURI_SIGNING_PRIVATE_KEY`) the build would fail at its
1306
+ * last step: such a build leaves the signatures out instead, laying
1307
+ * `unsignedConf` over the configuration, and still makes its installers. */
1308
+ function tauriBuildArgs(bundles, updates) {
1309
+ const args = [
1310
+ "build",
1311
+ "--bundles",
1312
+ bundles.join(",")
1313
+ ];
1314
+ if (updates.on && !updates.signingKey) args.push("--config", updates.unsignedConf);
1315
+ return args;
1316
+ }
1055
1317
  /** Spawn parameters that avoid DEP0190 (args array + shell:true): cargo on
1056
1318
  * Windows needs the shell for PATH/.exe + subcommand resolution — pass ONE
1057
1319
  * string, empty args; everything else runs argv directly (shell:false). The
@@ -1155,11 +1417,10 @@ function resolvePhCliEntry(projectRoot) {
1155
1417
  const pkgPath = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href).resolve("@powerhousedao/ph-cli/package.json");
1156
1418
  return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
1157
1419
  }
1158
- /** The env trio (plus flag and userData) the shell's uniform-runners mode
1420
+ /** The env trio (plus userData) the shell's uniform-runners mode
1159
1421
  * reads — wired by the RUNNER so nobody exports variables by hand. */
1160
1422
  function shellEnv(projectRoot, connectPort, env) {
1161
1423
  return {
1162
- FEATURE_UNIFORM_RUNNERS_ENABLED: "1",
1163
1424
  PH_RUN_PROJECT: projectRoot,
1164
1425
  PH_RUN_CLI: resolvePhCliEntry(projectRoot),
1165
1426
  PH_WIN_CONNECT_PORT: String(connectPort),
@@ -1565,6 +1826,6 @@ async function bundleBackend(options) {
1565
1826
  };
1566
1827
  }
1567
1828
  //#endregion
1568
- export { appJsonSchema as C, DEFAULT_SHELL_CRATE_VERSION as S, loadAppJson as T, projectShell as _, shellEnv as a, pruneStack as b, fetchNodeSidecar as c, resolveTauriCommand as d, runTauriIcon as f, SHELL_DIR as g, ICON_SOURCE as h, resolveShell as i, nodeSidecarTarget as l, tauriSpawn as m, launchShell as n, tauriConfigPatch as o, tauriBundlesForHost as p, resolvePhCliEntry as r, detectToolchain as s, bundleBackend as t, preflightOrThrow as u, bundleStack as v, appSlug as w, APP_JSON_FILE as x, pluginPackagesOf as y };
1829
+ export { FEED_FILE_TEMPLATE as A, pruneStack as C, appSlug as D, appJsonSchema as E, releaseFileName as F, releaseReport as I, collectRelease as M, feedFileName as N, loadAppJson as O, releaseBaseUrl as P, pluginPackagesOf as S, DEFAULT_SHELL_CRATE_VERSION as T, SHELL_DIR as _, shellEnv as a, projectShell as b, fetchNodeSidecar as c, resolveTauriCommand as d, runTauriIcon as f, ICON_SOURCE as g, tauriSpawn as h, resolveShell as i, RELEASE_DIR as j, updateEndpoints as k, nodeSidecarTarget as l, tauriBundlesForHost as m, launchShell as n, tauriConfigPatch as o, tauriBuildArgs as p, resolvePhCliEntry as r, detectToolchain as s, bundleBackend as t, preflightOrThrow as u, UNSIGNED_BUILD_CONF as v, APP_JSON_FILE as w, bundleStack as x, bundleVersion as y };
1569
1830
 
1570
- //# sourceMappingURL=bundle-backend-CvUS8-oc.mjs.map
1831
+ //# sourceMappingURL=bundle-backend-Bndax_Fd.mjs.map