akanjs 3.3.0 → 3.4.0-rc.0

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.
Files changed (62) hide show
  1. package/common/PipelinePlanSchema.ts +31 -7
  2. package/common/index.ts +6 -0
  3. package/common/pipelinePlan.ts +31 -5
  4. package/index.ts +7 -5
  5. package/package.json +1 -1
  6. package/pipelineConfig.ts +25 -2
  7. package/service/agentLoop/agentLoop.ts +19 -12
  8. package/service/predefinedAdaptor/anthropicTools.ts +8 -2
  9. package/types/common/index.d.ts +1 -1
  10. package/types/common/pipelinePlan.d.ts +35 -6
  11. package/types/index.d.ts +7 -5
  12. package/types/pipelineConfig.d.ts +20 -3
  13. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  14. package/types/service/predefinedAdaptor/anthropicTools.d.ts +1 -0
  15. package/types/vendor/@akanjs/native/packages/cli/src/api-updates.d.ts +149 -0
  16. package/types/vendor/@akanjs/native/packages/cli/src/api.d.ts +16 -162
  17. package/types/vendor/@akanjs/native/packages/cli/src/config.d.ts +3 -2
  18. package/types/vendor/@akanjs/native/packages/cli/src/lib/api-task.d.ts +79 -0
  19. package/types/vendor/@akanjs/native/packages/cli/src/lib/prepare.d.ts +1 -1
  20. package/types/vendor/@akanjs/native/packages/cli/src/lib/publish.d.ts +17 -5
  21. package/types/vendor/@akanjs/native/packages/cli/src/lib/updates.d.ts +29 -2
  22. package/types/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.d.ts +36 -0
  23. package/types/vendor/@akanjs/native/packages/cli/src/platforms/linux-install.d.ts +15 -0
  24. package/types/vendor/@akanjs/native/packages/core/src/kernel.d.ts +16 -5
  25. package/types/vendor/@akanjs/native/packages/desktop/src/commands.d.ts +81 -0
  26. package/types/vendor/@akanjs/native/packages/desktop/src/deeplinks.d.ts +5 -1
  27. package/types/vendor/@akanjs/native/packages/desktop/src/dispatcher.d.ts +3 -0
  28. package/types/vendor/@akanjs/native/packages/desktop/src/lifecycle.d.ts +8 -1
  29. package/types/vendor/@akanjs/native/packages/desktop/src/plugin.d.ts +21 -0
  30. package/types/vendor/@akanjs/native/packages/desktop/src/server.d.ts +1 -0
  31. package/types/vendor/@akanjs/native/plugins/updates/src/desktop.d.ts +4 -4
  32. package/types/vendor/@akanjs/native/plugins/updates/src/reports.d.ts +49 -0
  33. package/types/vendor/@akanjs/native/plugins/updates/src/signer.d.ts +21 -0
  34. package/types/vendor/@akanjs/native/plugins/window/src/index.d.ts +55 -3
  35. package/vendor/@akanjs/native/native/desktop/src/lib.rs +209 -54
  36. package/vendor/@akanjs/native/packages/cli/src/api-updates.ts +332 -0
  37. package/vendor/@akanjs/native/packages/cli/src/api.ts +67 -419
  38. package/vendor/@akanjs/native/packages/cli/src/commands/build.ts +4 -1
  39. package/vendor/@akanjs/native/packages/cli/src/config.ts +3 -2
  40. package/vendor/@akanjs/native/packages/cli/src/lib/api-task.ts +223 -0
  41. package/vendor/@akanjs/native/packages/cli/src/lib/prepare.ts +2 -7
  42. package/vendor/@akanjs/native/packages/cli/src/lib/publish.ts +164 -19
  43. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +90 -3
  44. package/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.ts +195 -43
  45. package/vendor/@akanjs/native/packages/cli/src/platforms/linux-appimage.ts +1 -1
  46. package/vendor/@akanjs/native/packages/cli/src/platforms/linux-install.ts +206 -0
  47. package/vendor/@akanjs/native/packages/cli/src/platforms/linux.ts +5 -1
  48. package/vendor/@akanjs/native/packages/core/src/kernel.ts +21 -6
  49. package/vendor/@akanjs/native/packages/core/vectors/updates.json +2 -1
  50. package/vendor/@akanjs/native/packages/desktop/src/commands.ts +380 -0
  51. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +20 -3
  52. package/vendor/@akanjs/native/packages/desktop/src/dispatcher.ts +28 -13
  53. package/vendor/@akanjs/native/packages/desktop/src/host.ts +6 -18
  54. package/vendor/@akanjs/native/packages/desktop/src/lifecycle.ts +8 -1
  55. package/vendor/@akanjs/native/packages/desktop/src/plugin.ts +21 -0
  56. package/vendor/@akanjs/native/packages/desktop/src/server.ts +1 -1
  57. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +90 -164
  58. package/vendor/@akanjs/native/plugins/updates/src/reports.ts +255 -0
  59. package/vendor/@akanjs/native/plugins/updates/src/signer.ts +133 -0
  60. package/vendor/@akanjs/native/plugins/window/native-plugin.json +6 -1
  61. package/vendor/@akanjs/native/plugins/window/src/desktop.ts +20 -4
  62. package/vendor/@akanjs/native/plugins/window/src/index.ts +55 -3
@@ -0,0 +1,223 @@
1
+
2
+
3
+ import { resolve } from "node:path";
4
+ import type { AkanNativeConfig } from "../config.ts";
5
+ import { PLATFORM_TARGETS, type TargetPlatform } from "../platforms/index.ts";
6
+ import { CancelledError, withSignal } from "./exec.ts";
7
+ import { CliError, type LogSink, ToolchainError, ToolError, withLogSink } from "./log.ts";
8
+ import {
9
+ type BuildContext,
10
+ type BuildOptions,
11
+ type BuildProfile,
12
+ type IosSigningResult,
13
+ prepare,
14
+ SigningError,
15
+ WebBuildError,
16
+ WebInputError,
17
+ } from "./prepare.ts";
18
+ import { ConfigError, type Project, projectFromConfig } from "./project.ts";
19
+
20
+ export type AkanNativeErrorCode =
21
+ | "CONFIG_INVALID"
22
+ | "TOOLCHAIN_MISSING"
23
+ | "WEB_INPUT_INVALID"
24
+ | "WEB_BUILD_FAILED"
25
+ | "NATIVE_BUILD_FAILED"
26
+ | "SIGNING_FAILED"
27
+ | "DEVICE_FAILED"
28
+ | "CANCELLED"
29
+ | "INTERNAL";
30
+
31
+ export class AkanNativeError extends Error {
32
+ constructor(
33
+ readonly code: AkanNativeErrorCode,
34
+ message: string,
35
+ readonly details: { problems?: string[]; hint?: string; logTail?: string[]; cause?: unknown } = {},
36
+ ) {
37
+ super(message);
38
+ this.name = "AkanNativeError";
39
+ }
40
+ get problems(): string[] | undefined {
41
+ return this.details.problems;
42
+ }
43
+ get hint(): string | undefined {
44
+ return this.details.hint;
45
+ }
46
+ get logTail(): string[] | undefined {
47
+ return this.details.logTail;
48
+ }
49
+ }
50
+
51
+ export interface TaskOptions {
52
+ /** Base of the config's relative paths (web.dir, icon, relative plugin folders). */
53
+ appDir: string;
54
+ /** What akan-native.config.ts would export. No file is read. */
55
+ config: AkanNativeConfig;
56
+ platform: TargetPlatform;
57
+ /** Default <appDir>/.akan/native/build/<platform>. */
58
+ outDir?: string;
59
+ /** Picks .env.<mode>. Default "production" for build, "development" for run. */
60
+ mode?: string;
61
+ /** false: no .env files from appDir. Default true. */
62
+ envFiles?: boolean;
63
+ /** PUBLIC_ values above .env files and config.env. */
64
+ env?: Record<string, string>;
65
+ /** Skip config.web.build and use web.dir as it is. */
66
+ skipWebBuild?: boolean;
67
+ /** Where plugin package names resolve from. Default appDir. */
68
+ resolveFrom?: string;
69
+ /** Receives the log. Without it nothing is logged. */
70
+ log?: LogSink;
71
+ /** Kills the running tools and rejects with CANCELLED. */
72
+ signal?: AbortSignal;
73
+ }
74
+
75
+ export interface Artifact {
76
+ kind: "app" | "apk" | "aab" | "ipa" | "folder" | "web" | "installer";
77
+ path: string;
78
+ signing: "none" | "adhoc" | "debug" | "development" | "distribution";
79
+ device?: "simulator" | "device";
80
+ }
81
+
82
+ export interface BuildResult {
83
+ platform: TargetPlatform;
84
+ profile: BuildProfile;
85
+ outDir: string;
86
+ artifacts: Artifact[];
87
+ warnings: string[];
88
+ durationMs: number;
89
+ /** iPhone builds: the identity and provisioning profile found (docs/api.md §3 "Finding the signing"). */
90
+ signing?: IosSigningResult;
91
+ /**
92
+ * Android builds that contain pinned libraries (push's FCM module, iap): the license notices file
93
+ * (akan-native-licenses.json, also served in the app at /akan-native-licenses.json).
94
+ */
95
+ licenses?: string;
96
+ }
97
+
98
+ /** Builds with one outDir at a time: a second call for the same folder waits for the first. */
99
+ const outDirLocks = new Map<string, Promise<unknown>>();
100
+
101
+ export async function buildIn(
102
+ options: TaskOptions,
103
+ profile: BuildProfile,
104
+ mode: string,
105
+ warnings: string[],
106
+ extra: Pick<
107
+ BuildOptions,
108
+ "android" | "ios" | "windows" | "macos" | "linux" | "arch" | "devServer" | "startPath"
109
+ > = {},
110
+ ): Promise<{ ctx: BuildContext; artifact: string; result: BuildResult }> {
111
+ const started = performance.now();
112
+ const appDir = resolve(options.appDir);
113
+ let project: Project;
114
+ try {
115
+ project = projectFromConfig(options.config, appDir, { resolveFrom: options.resolveFrom });
116
+ } catch (error) {
117
+ throw toAkanNativeError(error, "CONFIG_INVALID");
118
+ }
119
+ const outDir = resolve(options.outDir ?? resolve(appDir, ".akan", "native", "build", options.platform));
120
+ const previous = outDirLocks.get(outDir) ?? Promise.resolve();
121
+ const mine = previous
122
+ .catch(() => {})
123
+ .then(async () => {
124
+ const ctx = await prepare(project, options.platform, {
125
+ mode,
126
+ profile,
127
+ skipWebBuild: options.skipWebBuild ?? false,
128
+ outDir,
129
+ envFiles: options.envFiles,
130
+ env: options.env,
131
+ api: true,
132
+ ...extra,
133
+ }).catch((error) => {
134
+ throw toAkanNativeError(error, "CONFIG_INVALID");
135
+ });
136
+ const artifact = await PLATFORM_TARGETS[options.platform].build(ctx).catch((error) => {
137
+ throw toAkanNativeError(error, "NATIVE_BUILD_FAILED");
138
+ });
139
+ return { ctx, artifact };
140
+ });
141
+ outDirLocks.set(outDir, mine);
142
+ try {
143
+ const { ctx, artifact } = await mine;
144
+ const artifacts = [
145
+ describe(options.platform, artifact, ctx),
146
+ ...ctx.artifacts.map((a): Artifact => ({ kind: a.kind, path: a.path, signing: ctx.signedAs ?? "none" })),
147
+ ];
148
+ const result: BuildResult = {
149
+ platform: options.platform,
150
+ profile,
151
+ outDir: ctx.outDir,
152
+ artifacts,
153
+ warnings,
154
+ durationMs: Math.round(performance.now() - started),
155
+ ...(ctx.iosSigning ? { signing: ctx.iosSigning } : {}),
156
+ ...(ctx.licenses ? { licenses: ctx.licenses } : {}),
157
+ };
158
+ return { ctx, artifact, result };
159
+ } finally {
160
+ if (outDirLocks.get(outDir) === mine) outDirLocks.delete(outDir);
161
+ }
162
+ }
163
+
164
+ function describe(platform: TargetPlatform, path: string, ctx: BuildContext): Artifact {
165
+ switch (platform) {
166
+ case "web":
167
+ return { kind: "web", path, signing: "none" };
168
+ case "macos":
169
+ return { kind: "app", path, signing: ctx.signedAs ?? "adhoc" };
170
+ case "windows":
171
+ case "linux":
172
+ return { kind: "folder", path, signing: ctx.signedAs ?? "none" };
173
+ case "ios":
174
+ return ctx.ios?.device
175
+ ? { kind: "app", path, signing: ctx.signedAs ?? "development", device: "device" }
176
+ : { kind: "app", path, signing: "adhoc", device: "simulator" };
177
+ case "android":
178
+ return { kind: "apk", path, signing: ctx.signedAs ?? "debug" };
179
+ }
180
+ }
181
+
182
+ /** Runs an API call with its own log sink (warnings collected) and abort signal; failures become AkanNativeError. */
183
+ export async function task<T>(
184
+ options: { log?: LogSink; signal?: AbortSignal },
185
+ fn: (warnings: string[]) => Promise<T>,
186
+ ): Promise<T> {
187
+ const warnings: string[] = [];
188
+ const sink: LogSink = (event) => {
189
+ if (event.level === "warn") warnings.push(event.message);
190
+ options.log?.(event);
191
+ };
192
+ if (options.signal?.aborted) throw new AkanNativeError("CANCELLED", "cancelled before it started");
193
+ try {
194
+ return await withLogSink(sink, () => withSignal(options.signal, () => fn(warnings)));
195
+ } catch (error) {
196
+ throw toAkanNativeError(error, "INTERNAL");
197
+ }
198
+ }
199
+
200
+ /** An error as an AkanNativeError: its own kind decides the code, else the phase it happened in. */
201
+ export function toAkanNativeError(error: unknown, phase: AkanNativeErrorCode): AkanNativeError {
202
+ if (error instanceof AkanNativeError) return error;
203
+ if (error instanceof CancelledError || (error as Error)?.name === "AbortError")
204
+ return new AkanNativeError("CANCELLED", "cancelled", { cause: error });
205
+ if (error instanceof ConfigError)
206
+ return new AkanNativeError("CONFIG_INVALID", error.message, { problems: error.problems, cause: error });
207
+ if (error instanceof ToolchainError)
208
+ return new AkanNativeError("TOOLCHAIN_MISSING", error.message, { hint: "akan-native doctor", cause: error });
209
+ if (error instanceof WebBuildError) return new AkanNativeError("WEB_BUILD_FAILED", error.message, { cause: error });
210
+ if (error instanceof WebInputError) return new AkanNativeError("WEB_INPUT_INVALID", error.message, { cause: error });
211
+ if (error instanceof SigningError)
212
+ return new AkanNativeError("SIGNING_FAILED", error.message, {
213
+ ...(error.problems.length ? { problems: error.problems } : {}),
214
+ cause: error,
215
+ });
216
+ if (error instanceof ToolError)
217
+ return new AkanNativeError(phase === "CONFIG_INVALID" ? "NATIVE_BUILD_FAILED" : phase, error.message, {
218
+ logTail: error.tail,
219
+ cause: error,
220
+ });
221
+ if (error instanceof CliError) return new AkanNativeError(phase, error.message, { cause: error });
222
+ return new AkanNativeError("INTERNAL", (error as Error)?.message ?? String(error), { cause: error });
223
+ }
@@ -70,7 +70,7 @@ export interface BuildOptions {
70
70
  windows?: WindowsBuild;
71
71
  /** macOS: Developer ID signing, notarization and a dmg (lib/macossigning.ts). */
72
72
  macos?: MacosBuild;
73
- /** Linux: an AppImage beside the app folder (platforms/linux-appimage.ts). */
73
+ /** Linux: an AppImage (platforms/linux-appimage.ts) and a per-user installer (platforms/linux-install.ts). */
74
74
  linux?: LinuxBuild;
75
75
  /** Desktop builds: the CPU the app runs on, of the same OS; a macOS app is arm64 only. Default this computer's. */
76
76
  arch?: DesktopArch;
@@ -274,12 +274,7 @@ export async function prepare(project: Project, platform: Platform, options: Bui
274
274
  }
275
275
  const reportUrl = config.updates?.reportUrl;
276
276
 
277
- if (
278
- options.profile === "release" &&
279
- reportUrl &&
280
- (platform === "ios" || platform === "android") &&
281
- !secureUpdateUrl(reportUrl)
282
- )
277
+ if (options.profile === "release" && reportUrl && platform !== "web" && !secureUpdateUrl(reportUrl))
283
278
  throw new CliError(
284
279
  `updates.report.url must be https in a release build (http only for this machine): ${reportUrl}`,
285
280
  );
@@ -3,8 +3,10 @@
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { isUpdateKeyId, MAX_REVOKE_KEYS, updateDecision } from "../../../core/src/kernel.ts";
6
+ import type { DesktopOs } from "../platforms/desktop.ts";
6
7
  import { assertSameServer, publishAppUpdate } from "../platforms/desktop-update.ts";
7
8
  import { BUNDLE_FILE, readBundleInfo } from "./compat.ts";
9
+ import { currentSignal } from "./exec.ts";
8
10
  import { CliError, log } from "./log.ts";
9
11
  import type { BuildContext } from "./prepare.ts";
10
12
  import {
@@ -12,12 +14,15 @@ import {
12
14
  type DesktopArch,
13
15
  hostArch,
14
16
  keyIdOf,
17
+ manifestBytes,
15
18
  openEnvelope,
16
19
  sealManifest,
20
+ sha256,
17
21
  signingKey,
18
22
  signManifest,
19
23
  type UpdateEnvelope,
20
24
  type UpdateManifest,
25
+ type UpdatesConfig,
21
26
  updateKeyPath,
22
27
  webManifest,
23
28
  writeWebBundle,
@@ -252,11 +257,41 @@ function writeEnvelope(dir: string, channel: string, nativeApi: string, envelope
252
257
  return file;
253
258
  }
254
259
 
260
+ /** Where a desktop release's envelope stays once a later one took its place: what `--republish <bundle>` signs again. */
261
+ const keptEnvelope = (dir: string, channel: string, bundle: string) => join(dir, channel, "releases", `${bundle}.json`);
262
+
255
263
  /**
256
- * Writes the release of `artifact` (the app a release build made) and its envelope under `out`. A desktop release also
257
- * gets the v1 pair when signed with the first key, the only one an app built before protocol v2 trusts: that is how
258
- * such an app takes a binary that reads envelopes.
264
+ * Signs `manifest` and writes its envelope. A desktop release (`legacy`: the same release as schema 1) also gets the
265
+ * v1 pair when signed with the first key, the only one an app built before protocol v2 trusts: that is how such an app
266
+ * takes a binary that reads envelopes. Its envelope is kept under releases/ too.
259
267
  */
268
+ function writeRelease(
269
+ dir: string,
270
+ channel: string,
271
+ manifest: UpdateManifest,
272
+ legacy: UpdateManifest | null,
273
+ { publicKeys }: Pick<UpdatesConfig, "publicKeys">,
274
+ keyPath: string,
275
+ ): string {
276
+ mkdirSync(dir, { recursive: true });
277
+ const envelope = sealManifest(manifestBytes(manifest), keyPath, publicKeys);
278
+ const file = writeEnvelope(dir, channel, legacy ? "app" : (manifest.nativeApi ?? ""), envelope);
279
+ if (!legacy) return file;
280
+ const kept = keptEnvelope(dir, channel, manifest.bundle);
281
+ mkdirSync(join(kept, ".."), { recursive: true });
282
+ writeFileSync(kept, `${JSON.stringify(envelope)}\n`);
283
+ const { index, keyId } = signingKey(keyPath, publicKeys);
284
+ if (index === 0) {
285
+ const v1 = manifestBytes(legacy);
286
+ writeSigned(dir, channel, v1, `${signManifest(v1, keyPath, publicKeys)}\n`);
287
+ } else
288
+ log.warn(
289
+ `this release is signed with ${keyId}, not the first of updates.publicKeys: desktop apps built before protocol v2 trust only that key, so they do not see it`,
290
+ );
291
+ return file;
292
+ }
293
+
294
+ /** Writes the release of `artifact` (the app a release build made) and its envelope under `out`. */
260
295
  export async function publishRelease(
261
296
  ctx: BuildContext,
262
297
  platform: ReleasePlatform,
@@ -307,22 +342,132 @@ export async function publishRelease(
307
342
  }
308
343
  const { expiresIn } = config.updates;
309
344
  if (expiresIn) manifest = { ...manifest, expiresAt: Math.floor(Date.now() / 1000) + expiresIn };
310
- const encode = (value: UpdateManifest) => new TextEncoder().encode(`${JSON.stringify(value, null, 2)}\n`);
311
- const bytes = encode(manifest);
312
- const { publicKeys } = config.updates;
313
- mkdirSync(dir, { recursive: true });
314
- const name = desktop ? "app" : (manifest.nativeApi ?? "");
315
- const file = writeEnvelope(dir, channel, name, sealManifest(bytes, keyPath, publicKeys));
316
- if (legacy) {
317
- const { index, keyId } = signingKey(keyPath, publicKeys);
318
- if (index === 0) {
319
- const v1 = encode(legacy);
320
- writeSigned(dir, channel, v1, `${signManifest(v1, keyPath, publicKeys)}\n`);
321
- } else
322
- log.warn(
323
- `this release is signed with ${keyId}, not the first of updates.publicKeys: desktop apps built before protocol v2 trust only that key, so they do not see it`,
324
- );
325
- }
345
+ const file = writeRelease(dir, channel, manifest, legacy, config.updates, keyPath);
326
346
  for (const leftover of leftovers) rmSync(leftover, { force: true });
327
347
  return { dir, manifest, file };
328
348
  }
349
+
350
+ /** The bundle id an envelope file claims, unverified; undefined when it is no envelope. */
351
+ function claimedBundle(file: string): string | undefined {
352
+ try {
353
+ const { manifest } = JSON.parse(readFileSync(file, "utf8")) as Partial<UpdateEnvelope>;
354
+ return (JSON.parse(Buffer.from(manifest ?? "", "base64").toString("utf8")) as Partial<UpdateManifest>).bundle;
355
+ } catch {
356
+ return undefined;
357
+ }
358
+ }
359
+
360
+ /** The envelope of `bundle` in `dir`: the one kept at its publish, or a channel's newest when it is that release. */
361
+ function publishedEnvelope(dir: string, channel: string, bundle: string): string | null {
362
+ const others = existsSync(dir)
363
+ ? readdirSync(dir, { withFileTypes: true })
364
+ .filter((entry) => entry.isDirectory() && entry.name !== channel)
365
+ .map((entry) => entry.name)
366
+ : [];
367
+ for (const name of [channel, ...others]) {
368
+ const kept = keptEnvelope(dir, name, bundle);
369
+ if (existsSync(kept)) return kept;
370
+ const newest = join(dir, name, "app.json");
371
+ if (claimedBundle(newest) === bundle) return newest;
372
+ }
373
+ return null;
374
+ }
375
+
376
+ async function fromFeed(url: string, missing: string, hint = ""): Promise<Response> {
377
+ log.info(`${missing}: fetching ${url}`);
378
+ const signal = currentSignal();
379
+ const response = await fetch(url, { signal }).catch((error: unknown) => {
380
+ if (signal?.aborted) throw error;
381
+ throw new CliError(
382
+ `${missing}, and ${url} could not be read: ${error instanceof Error ? error.message : String(error)}`,
383
+ );
384
+ });
385
+ if (!response.ok) throw new CliError(`${missing}, and ${url} answered ${response.status}${hint}`);
386
+ return response;
387
+ }
388
+
389
+ async function feedEnvelope(dir: string, feed: string, channel: string, bundle: string): Promise<string> {
390
+ const hint = `: --republish signs again a release this target published (${join(dir, channel, "releases")} keeps their envelopes, and an upload sends them)`;
391
+ const url = `${feed}/${channel}/releases/${bundle}.json`;
392
+ return await (await fromFeed(url, `${dir} holds no release ${bundle}`, hint)).text();
393
+ }
394
+
395
+ /** The archive a manifest names, in `dir` or else fetched there from the feed, refused unless it is the one named. */
396
+ async function releaseArchive(dir: string, feed: string, archive: NonNullable<UpdateManifest["archive"]>) {
397
+ const file = join(dir, archive.url);
398
+ if (!existsSync(file)) {
399
+ const url = `${feed}/${archive.url}`;
400
+ const bytes = await (await fromFeed(url, `${file} is not here`)).bytes();
401
+ if (sha256(bytes) !== archive.gzSha256) throw new CliError(`${url} is not the archive the release names`);
402
+ mkdirSync(join(file, ".."), { recursive: true });
403
+ writeFileSync(file, bytes);
404
+ return;
405
+ }
406
+ if (sha256(readFileSync(file)) !== archive.gzSha256)
407
+ throw new CliError(`${file} is not the archive the release names: nothing was signed`);
408
+ }
409
+
410
+ /**
411
+ * Signs a desktop release this folder published again, as its channel's newest: the same archive under a new sequence
412
+ * and bundle id, with no patch. Every app of the channel on another build takes it whole, one on a later build too,
413
+ * which is how a release is rolled back. The archive is the one in `out`, or fetched from updates.url when it is gone.
414
+ */
415
+ export async function republishRelease(
416
+ project: { config: { app: { id: string }; updates?: UpdatesConfig | null } },
417
+ platform: DesktopOs,
418
+ bundle: string,
419
+ out: string,
420
+ channel: string,
421
+ request: RevocationRequest = {},
422
+ arch: DesktopArch = hostArch(),
423
+ ): Promise<PublishedRelease & { from: UpdateManifest }> {
424
+ const { config } = project;
425
+ if (!config.updates)
426
+ throw new CliError("akan-native.config.ts has no updates: { url, publicKeys } (run `akan-native update keygen`)");
427
+ const { updates } = config;
428
+ const dir = releaseDir(out, platform, arch);
429
+ const feed = `${updates.url}/${platform}-${arch}`;
430
+ assertChannel(channel);
431
+ assertSigningKey(config);
432
+ if (!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(bundle))
433
+ throw new CliError(`--republish takes a release's bundle id (<version>-<sequence>), not ${JSON.stringify(bundle)}`);
434
+ const envelope = publishedEnvelope(dir, channel, bundle) ?? `${feed}/${channel}/releases/${bundle}.json`;
435
+ const text = existsSync(envelope) ? readFileSync(envelope, "utf8") : await feedEnvelope(dir, feed, channel, bundle);
436
+ const opened = openEnvelope(text, updates.publicKeys, updates.revokedKeys);
437
+ const from = JSON.parse(new TextDecoder().decode(opened.manifest)) as UpdateManifest;
438
+ const { archive } = from;
439
+ if (from.bundle !== bundle || from.kind !== "app" || from.app !== config.app.id || !archive)
440
+ throw new CliError(`${envelope} is not release ${bundle} of ${config.app.id}`);
441
+ if (from.platform !== platform || from.arch !== arch)
442
+ throw new CliError(`${envelope} is a ${from.platform} ${from.arch} release, not a ${platform} ${arch} one`);
443
+
444
+ if ((from.target ?? null) !== (updates.target ?? null))
445
+ throw new CliError(
446
+ `${envelope} was built for target ${JSON.stringify(from.target ?? null)}, not ${JSON.stringify(updates.target ?? null)}: the app it holds would refuse every later release`,
447
+ );
448
+ if (typeof from.server === "boolean") assertSameServer(dir, channel, from.server);
449
+ const { revokeKeys, resetSequence } = releaseRevocations(config, platform, out, channel, request, arch);
450
+ warnRevocations(updates, revokeKeys);
451
+ await releaseArchive(dir, feed, archive);
452
+
453
+ const sequence = Math.max(nextSequence(dir, channel), from.sequence + 1);
454
+ const { target: _target, revokeKeys: _revoked, resetSequence: _reset, expiresAt: _expires, ...kept } = from;
455
+ const legacy: UpdateManifest = {
456
+ ...kept,
457
+ schema: 1,
458
+ channel,
459
+ sequence,
460
+ bundle: `${from.version}-${sequence}`,
461
+ patches: [],
462
+ };
463
+ const manifest: UpdateManifest = {
464
+ ...legacy,
465
+ schema: 2,
466
+ ...(updates.target ? { target: updates.target } : {}),
467
+ ...(revokeKeys.length ? { revokeKeys } : {}),
468
+ ...(resetSequence ? { resetSequence: true } : {}),
469
+ ...(updates.expiresIn ? { expiresAt: Math.floor(Date.now() / 1000) + updates.expiresIn } : {}),
470
+ };
471
+ const file = writeRelease(dir, channel, manifest, legacy, updates, updateKeyPath(config.app.id));
472
+ return { dir, manifest, file, from };
473
+ }
@@ -6,11 +6,13 @@ import { dirname, join } from "node:path";
6
6
  import type { Platform } from "../../../core/src/index.ts";
7
7
  import {
8
8
  checkUpdateEnvelope,
9
+ isBundleId,
9
10
  isChannelName,
10
11
  isStrictBase64,
11
12
  isUpdateKeyId,
12
13
  isUpdatePublicKey,
13
14
  MAX_REVOKE_KEYS,
15
+ MAX_UPDATE_MANIFEST,
14
16
  RESERVED_CHANNELS,
15
17
  } from "../../../core/src/kernel.ts";
16
18
  import { runtimeVersion } from "./boot.ts";
@@ -42,7 +44,7 @@ export interface UpdatesConfig {
42
44
  channel: string;
43
45
  /** How long a newly applied bundle has to call notifyReady() before it is rolled back, ms. Default 10000. */
44
46
  readyTimeout: number;
45
- /** Where a phone posts what became of each release (downloaded, applied, confirmed, rolled back, failed); null: no reports. */
47
+ /** Where an app posts what became of each release (downloaded, applied, confirmed, rolled back, failed); null: no reports. */
46
48
  reportUrl: string | null;
47
49
  /** Desktop: false leaves checking, downloading and applying to the app; a phone always takes a web bundle itself. */
48
50
  automatic: boolean;
@@ -376,7 +378,7 @@ export function signManifest(bytes: Uint8Array, keyPath: string, publicKeys: rea
376
378
  return sign(null, bytes, key).toString("base64");
377
379
  }
378
380
 
379
- /** A phone's envelope (protocol v2) for the manifest's exact bytes, signed with any key of `publicKeys`. */
381
+ /** The envelope (protocol v2) of the manifest's exact bytes, signed with the key at `keyPath`, any key of `publicKeys`. */
380
382
  export function sealManifest(bytes: Uint8Array, keyPath: string, publicKeys: readonly string[]): UpdateEnvelope {
381
383
  const { key, keyId } = signingKey(keyPath, publicKeys);
382
384
  return {
@@ -426,6 +428,91 @@ export function openEnvelope(
426
428
  }
427
429
  }
428
430
 
431
+ /** What whoever signs a pack decides: the rest of its manifest is the pack's `manifest.template.json`. */
432
+ export interface ManifestRelease {
433
+ channel: string;
434
+ /** Larger than every release the channel had; apps take no other. */
435
+ sequence: number;
436
+ /** A desktop app's defaults to `<version>-<sequence>`; a web bundle's is `<sequence>-<first 8 of web.hash>`. */
437
+ bundle?: string;
438
+ /** A desktop app: the deltas this release offers, instead of the template's. */
439
+ patches?: NonNullable<UpdateManifest["patches"]>;
440
+ revokeKeys?: readonly string[];
441
+ resetSequence?: boolean;
442
+ /** Unix seconds after which apps refuse the manifest. */
443
+ expiresAt?: number;
444
+ }
445
+
446
+ /**
447
+ * A pack's manifest template made the manifest of one release. Refuses what no app would take: a channel none could
448
+ * be configured for, a sequence or a bundle id that is not one, a revocation list a manifest may not hold.
449
+ */
450
+ export function fillManifest(template: UpdateManifest, release: ManifestRelease): UpdateManifest {
451
+ assertChannel(release.channel);
452
+ const { sequence, revokeKeys = [], patches } = release;
453
+ if (!Number.isSafeInteger(sequence) || sequence <= 0)
454
+ throw new CliError(`a release's sequence is a positive whole number, not ${sequence}`);
455
+ const bundle = release.bundle ?? (template.kind === "app" ? `${template.version}-${sequence}` : "");
456
+ if (!isBundleId(bundle))
457
+ throw new CliError(
458
+ bundle
459
+ ? `${JSON.stringify(bundle)} cannot name a release's bundle`
460
+ : "a web bundle's release needs its bundle id: <sequence>-<the first 8 of bundle.json's web.hash>",
461
+ );
462
+ if (revokeKeys.length > MAX_REVOKE_KEYS || !revokeKeys.every(isUpdateKeyId))
463
+ throw new CliError(`revokeKeys holds at most ${MAX_REVOKE_KEYS} keyIds, 16 hex digits each`);
464
+ if (release.resetSequence && !revokeKeys.length)
465
+ throw new CliError("resetSequence counts only in a release that revokes a key");
466
+ if (patches && template.kind !== "app") throw new CliError("only a desktop app's release has patches");
467
+ const { expiresAt } = release;
468
+ if (expiresAt !== undefined && (!Number.isSafeInteger(expiresAt) || expiresAt <= 0))
469
+ throw new CliError(`expiresAt is Unix seconds, not ${expiresAt}`);
470
+ const {
471
+ revokeKeys: _revokeKeys,
472
+ resetSequence: _resetSequence,
473
+ expiresAt: _expiresAt,
474
+ ...rest
475
+ } = { ...template, schema: 2 as const, channel: release.channel, sequence, bundle, ...(patches ? { patches } : {}) };
476
+ return {
477
+ ...rest,
478
+ ...(revokeKeys.length ? { revokeKeys: [...revokeKeys].sort((a, b) => a.localeCompare(b)) } : {}),
479
+ ...(release.resetSequence ? { resetSequence: true } : {}),
480
+ ...(expiresAt === undefined ? {} : { expiresAt }),
481
+ };
482
+ }
483
+
484
+ /** A manifest's exact bytes as `update publish` writes them: what the signature is over and the envelope holds. */
485
+ export function manifestBytes(manifest: UpdateManifest): Uint8Array {
486
+ const bytes = new TextEncoder().encode(`${JSON.stringify(manifest, null, 2)}\n`);
487
+ if (bytes.length > MAX_UPDATE_MANIFEST)
488
+ throw new CliError(`the manifest is ${bytes.length} bytes, and an app reads at most ${MAX_UPDATE_MANIFEST}`);
489
+ return bytes;
490
+ }
491
+
492
+ /**
493
+ * The envelope of manifest bytes signed elsewhere (a key service, a host that signs in process): `signature` is Ed25519
494
+ * over `bytes` by the private half of `publicKey`. Verified as an app verifies it before it is returned, so another
495
+ * key's signature, or one over other bytes, is refused here and not by every installed app.
496
+ */
497
+ export function updateEnvelope(bytes: Uint8Array, publicKey: string, signature: string | Uint8Array): UpdateEnvelope {
498
+ if (!isUpdatePublicKey(publicKey)) throw new CliError("the public key is not a raw 32-byte Ed25519 key in base64");
499
+ if (bytes.length > MAX_UPDATE_MANIFEST)
500
+ throw new CliError(`the manifest is ${bytes.length} bytes, and an app reads at most ${MAX_UPDATE_MANIFEST}`);
501
+ const raw =
502
+ typeof signature !== "string"
503
+ ? signature
504
+ : isStrictBase64(signature)
505
+ ? Buffer.from(signature, "base64")
506
+ : new Uint8Array();
507
+ if (raw.length !== 64 || !verifySignature(bytes, raw, publicKey))
508
+ throw new CliError(`the signature is not key ${keyIdOf(publicKey)}'s over these manifest bytes`);
509
+ return {
510
+ manifest: Buffer.from(bytes).toString("base64"),
511
+ keyId: keyIdOf(publicKey),
512
+ signature: Buffer.from(raw).toString("base64"),
513
+ };
514
+ }
515
+
429
516
  /** Verifies like the apps do: raw public key, base64 signature over the exact manifest bytes. */
430
517
  export function verifyManifest(bytes: Uint8Array, signature: string, publicKey: string): boolean {
431
518
  return verifySignature(bytes, Buffer.from(signature, "base64"), publicKey);
@@ -470,7 +557,7 @@ export function updatesResource(
470
557
  ...(updates.target && platform !== "ios" && platform !== "android" ? { target: updates.target } : {}),
471
558
  ...(updates.automatic === false && platform !== "ios" && platform !== "android" ? { automatic: false } : {}),
472
559
  ...(updates.windowsSigners?.length && platform === "windows" ? { windowsSigners: updates.windowsSigners } : {}),
473
- ...(updates.reportUrl && (platform === "ios" || platform === "android") ? { reportUrl: updates.reportUrl } : {}),
560
+ ...(updates.reportUrl && platform !== "web" ? { reportUrl: updates.reportUrl } : {}),
474
561
  });
475
562
  }
476
563