@adea-ai/app-framework-release-tools 0.11.3 → 0.11.4

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.
@@ -0,0 +1,73 @@
1
+ import { errorCode } from "../app/value-guards";
2
+ import { realpathSync } from "node:fs";
3
+ import { lstat, open, writeFile } from "node:fs/promises";
4
+ import { resolve } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { assertHostedRunner } from "./hosted-runner";
7
+ function DeniedWorker() {
8
+ throw Error("Nested workers forbidden in installer qualification");
9
+ }
10
+ export function interceptInstallerWorker(options) {
11
+ assertHostedRunner(options.env, "Worker guard");
12
+ if (!options.entry || !options.bootstrap || typeof options.globals.Worker !== "function")
13
+ throw Error("Missing worker guard context");
14
+ const Original = options.globals.Worker, expected = resolve(options.entry), matchesEntry = (path) => {
15
+ const actual = resolve(path);
16
+ if (actual === expected)
17
+ return !0;
18
+ try {
19
+ return realpathSync(actual) === realpathSync(expected);
20
+ } catch {
21
+ return !1;
22
+ }
23
+ };
24
+ let used = !1;
25
+
26
+ class GuardedWorker extends Original {
27
+ constructor(path, workerOptions) {
28
+ if (used || typeof path !== "string" || !matchesEntry(path) || workerOptions !== void 0 && (workerOptions === null || Object.getPrototypeOf(workerOptions) !== Object.prototype || Reflect.ownKeys(workerOptions).length !== 0))
29
+ throw Error("Unexpected Electrobun worker");
30
+ used = !0;
31
+ super(options.bootstrap);
32
+ }
33
+ }
34
+ if (!Reflect.set(options.globals, "Worker", GuardedWorker) || options.globals.Worker !== GuardedWorker)
35
+ throw Error("Cannot install application worker guard");
36
+ }
37
+ export async function awaitInstallerWorkerPermit(options) {
38
+ assertHostedRunner(options.env, "Worker guard");
39
+ const { entry, nonce, acknowledgement, permit } = options, timeoutMs = options.timeoutMs ?? 90000;
40
+ if (!entry || !/^[a-f0-9]{48}$/.test(nonce) || !acknowledgement || !permit || resolve(acknowledgement) === resolve(permit) || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 90000)
41
+ throw Error("Invalid worker guard context");
42
+ if (!Reflect.set(options.globals, "Worker", DeniedWorker) || options.globals.Worker !== DeniedWorker)
43
+ throw Error("Cannot block nested workers");
44
+ await writeFile(acknowledgement, nonce + `
45
+ `, { flag: "wx", mode: 384 });
46
+ const deadline = performance.now() + timeoutMs;
47
+ while (performance.now() < deadline) {
48
+ try {
49
+ const info = await lstat(permit);
50
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 49)
51
+ throw Error("Invalid worker permit");
52
+ const file = await open(permit, "r");
53
+ let contents;
54
+ try {
55
+ const buffer = Buffer.alloc(50), { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
56
+ contents = buffer.subarray(0, bytesRead).toString("utf8");
57
+ } finally {
58
+ await file.close();
59
+ }
60
+ const expected = nonce + `
61
+ `;
62
+ if (!expected.startsWith(contents))
63
+ throw Error("Invalid worker permit");
64
+ if (contents === expected)
65
+ return pathToFileURL(resolve(entry)).href;
66
+ } catch (error) {
67
+ if (errorCode(error) !== "ENOENT")
68
+ throw error;
69
+ }
70
+ await new Promise((done) => setTimeout(done, Math.min(100, Math.max(1, deadline - performance.now()))));
71
+ }
72
+ throw Error("Worker guard permit missing");
73
+ }
@@ -0,0 +1,51 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { containsAsciiControl } from "../desktop/string-policy";
4
+ export function bundleResourcesDirectory(entryDirectory) {
5
+ return join(entryDirectory, "..", "..");
6
+ }
7
+ const text = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !containsAsciiControl(value);
8
+ export function readPackagedVersion(entryDirectory) {
9
+ const file = join(bundleResourcesDirectory(entryDirectory), "version.json"), info = statSync(file);
10
+ if (!info.isFile() || info.size > 1048576)
11
+ throw Error("Invalid packaged version file");
12
+ const value = JSON.parse(readFileSync(file, "utf8"));
13
+ if (typeof value !== "object" || value === null || Array.isArray(value))
14
+ throw Error("Invalid packaged version file");
15
+ const record = value;
16
+ if (!text(record.version, 64))
17
+ throw Error("Invalid packaged version");
18
+ const result = {
19
+ version: record.version
20
+ };
21
+ for (const key of ["channel", "identifier", "hash"]) {
22
+ const field = record[key];
23
+ if (field === void 0 || field === "")
24
+ continue;
25
+ if (!text(field, 255))
26
+ throw Error(`Invalid packaged ${key}`);
27
+ result[key] = field;
28
+ }
29
+ return result;
30
+ }
31
+ export const SIDECAR_DIRECTORY = "sidecars";
32
+ export function assertSidecarNames(names, platform) {
33
+ const windows = platform === "win32" || platform === "windows-x64";
34
+ if (!Array.isArray(names) || names.length > 16 || names.some((name) => typeof name !== "string" || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name)) || windows && names.some((name) => /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) || new Set(names).size !== names.length)
35
+ throw Error("Invalid sidecar names");
36
+ return [...names];
37
+ }
38
+ export function sidecarFileName(name, platform) {
39
+ assertSidecarNames([name], platform);
40
+ return platform === "win32" || platform === "windows-x64" ? `${name}.exe` : name;
41
+ }
42
+ export function sidecarBundlePath(name, platform) {
43
+ return `Resources/app/${SIDECAR_DIRECTORY}/${sidecarFileName(name, platform)}`;
44
+ }
45
+ export function packagedSidecarPath(entryDirectory, name, platform = process.platform, options = {}) {
46
+ const executable = join(entryDirectory, "..", SIDECAR_DIRECTORY, sidecarFileName(name, platform));
47
+ return options.override ? options.override : executable;
48
+ }
49
+ export function packagedLauncherPath(execPath = process.execPath, platform = process.platform) {
50
+ return join(dirname(execPath), platform === "win32" ? "launcher.exe" : "launcher");
51
+ }
@@ -0,0 +1,103 @@
1
+ import { isGitSha } from "../app/value-guards";
2
+ import {
3
+ parseOfflinePolicy
4
+ } from "../updates/feed/release-config-contract";
5
+
6
+ export { parseOfflinePolicy };
7
+ function assert(condition, message) {
8
+ if (!condition)
9
+ throw Error(message);
10
+ }
11
+ function expectedAssets(requirements) {
12
+ if (Object.hasOwn(requirements, "offlinePolicy"))
13
+ parseOfflinePolicy(requirements.offlinePolicy);
14
+ const platforms = Object.entries(requirements.platforms);
15
+ assert(platforms.length > 0, "Missing platforms");
16
+ const names = [
17
+ ...platforms.flatMap(([platform, artifacts]) => {
18
+ assert(/^[a-z0-9-]+$/.test(platform) && artifacts.length > 0, "Invalid platform requirements");
19
+ return artifacts;
20
+ }),
21
+ ...Object.entries(requirements.commandArtifacts ?? {}).flatMap(([kind, byPlatform]) => {
22
+ assert(/^[a-z][a-z0-9-]{0,31}$/.test(kind) && Object.keys(byPlatform).length === platforms.length && platforms.every(([platform]) => typeof byPlatform[platform] === "string"), "Invalid command artifact requirements");
23
+ return Object.values(byPlatform);
24
+ }),
25
+ ...requirements.releaseAssets
26
+ ];
27
+ assert(names.length > 0 && names.every((name) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) && new Set(names).size === names.length, "Invalid or duplicate asset requirements");
28
+ return names;
29
+ }
30
+ function matches(saved, uploaded) {
31
+ return Boolean(saved && uploaded && saved.name === uploaded.name && Number.isSafeInteger(saved.size) && saved.size > 0 && saved.size === uploaded.size && /^sha256:[a-f0-9]{64}$/.test(saved.digest) && saved.digest === uploaded.digest);
32
+ }
33
+ function uniqueAsset(assets, name) {
34
+ const found = assets.filter((asset) => asset.name === name);
35
+ assert(found.length === 1, `Missing or duplicate asset: ${name}`);
36
+ return found[0];
37
+ }
38
+ function checkRenderer(value, offlinePolicy) {
39
+ const port = Number(value?.origin?.split(":").at(-1)), common = value && port >= 1024 && port <= 65535 && /^http:\/\/127\.0\.0\.1:[1-9]\d{3,4}$/.test(value.origin) && value.samples === 2 && value.guardInstalled === !0 && value.offlineObserved === !0 && value.unexpectedActivity === !1 && Number.isFinite(value.elapsedMs) && value.elapsedMs >= 3000 && value.visible === !0 && ["interactive", "complete"].includes(value.readyState) && Number.isFinite(value.width) && value.width >= 100 && Number.isFinite(value.height) && value.height >= 100 && Number.isSafeInteger(value.interactiveElements) && value.interactiveElements >= 1 && Number.isSafeInteger(value.textLength) && value.textLength >= 1;
40
+ if (!offlinePolicy) {
41
+ assert(common && value.method === "native-dom-raf-v1" && value.bootstrapDenied === !0, "Incomplete native renderer evidence");
42
+ return;
43
+ }
44
+ assert(value && value.offlinePolicy, "Incomplete native renderer evidence");
45
+ const policy = parseOfflinePolicy(offlinePolicy), observed = parseOfflinePolicy(value.offlinePolicy);
46
+ assert(common && value.method === "native-dom-raf-v2" && value.markerObserved === !0 && value.browserNetworkRestricted === !0 && observed.kind === policy.kind && observed.marker === policy.marker && (policy.kind === "standalone" ? value.bootstrapDenied === !1 : observed.kind === "local-bootstrap" && observed.path === policy.path && value.bootstrapDenied === !0), "Incomplete native renderer evidence");
47
+ }
48
+ export function validateInstallerReceipt(identity, entry, platform, names, assets, offlinePolicy) {
49
+ assertIdentity(identity, platform);
50
+ assert(Array.isArray(names) && new Set(names).size === names.length, "Invalid installer receipt context");
51
+ assert(entry && entry.platform === platform && entry.schema === 2 && entry.installed === !0 && entry.launched === !0 && entry.rendererReady === !0 && ["tag", "sourceSha", "workflowSha", "runId", "runAttempt"].every((key) => entry[key] === identity[key]), "Installer identity mismatch");
52
+ checkRenderer(entry.rendererEvidence, offlinePolicy);
53
+ assert(Array.isArray(entry.assets) && names.length > 0 && entry.assets.length === names.length, "Incorrect installer asset count");
54
+ for (const name of names)
55
+ assert(matches(uniqueAsset(entry.assets, name), uniqueAsset(assets, name)), `Installer asset mismatch: ${name}`);
56
+ return !0;
57
+ }
58
+ function assertIdentity(identity, platform) {
59
+ assert(/^v\d+\.\d+\.\d+$/.test(identity.tag) && isGitSha(identity.sourceSha) && isGitSha(identity.workflowSha) && /^[1-9]\d{0,19}$/.test(identity.runId) && Number.isSafeInteger(identity.runAttempt) && identity.runAttempt > 0 && /^[a-z0-9-]+$/.test(platform), "Invalid receipt context");
60
+ }
61
+ export function validateCommandReceipt(identity, entry, kind, platform, name, assets) {
62
+ assertIdentity(identity, platform);
63
+ assert(entry && entry.schema === 1 && entry.kind === kind && entry.platform === platform && entry.installed === !0 && entry.versionMatched === !0 && entry.probesPassed === !0 && entry.serviceStarted === !0 && entry.serviceStopped === (platform === "windows-x64" ? "process-tree" : "sigterm") && Object.keys(entry).length === 14 && ["tag", "sourceSha", "workflowSha", "runId", "runAttempt"].every((key) => entry[key] === identity[key]), "Command artifact receipt mismatch");
64
+ assert(matches(entry.asset, uniqueAsset(assets, name)), `Command artifact asset mismatch: ${name}`);
65
+ return !0;
66
+ }
67
+ export function validateCommandReceipts(identity, receipts, requirements, assets) {
68
+ const required = Object.entries(requirements.commandArtifacts ?? {}).flatMap(([kind, byPlatform]) => Object.entries(byPlatform).map(([platform, name]) => ({ kind, platform, name })));
69
+ if (!required.length) {
70
+ assert(receipts === void 0, "Unexpected command artifact receipts");
71
+ return;
72
+ }
73
+ assert(Array.isArray(receipts) && receipts.length === required.length, "Missing or duplicate command artifact receipts");
74
+ for (const { kind, platform, name } of required) {
75
+ const entries = receipts.filter((entry) => entry?.kind === kind && entry.platform === platform);
76
+ assert(entries.length === 1, `Missing or duplicate command artifact receipt: ${kind}`);
77
+ validateCommandReceipt(identity, entries[0], kind, platform, name, assets);
78
+ }
79
+ }
80
+ export function validateReleaseQualification(release, receipt, sourceSha, requirements) {
81
+ const required = expectedAssets(requirements), platforms = Object.keys(requirements.platforms);
82
+ assert(release.draft === !1 && receipt.schema === 2 && receipt.tag === release.tag_name && receipt.sourceSha === sourceSha && isGitSha(sourceSha) && isGitSha(receipt.workflowSha) && /^[1-9]\d*$/.test(receipt.runId) && Number.isSafeInteger(receipt.runAttempt) && receipt.runAttempt > 0, "Qualification identity mismatch");
83
+ assert(receipt.platforms.length === platforms.length && receipt.installerTests.length === platforms.length && receipt.installerReceipts.length === platforms.length && platforms.every((platform) => receipt.platforms.filter((x) => x === platform).length === 1 && receipt.installerTests.filter((x) => x === platform).length === 1), "Missing or duplicate platform tests");
84
+ for (const platform of platforms) {
85
+ const entries = receipt.installerReceipts.filter((entry) => entry.platform === platform);
86
+ assert(entries.length === 1, `Missing or duplicate installer receipt: ${platform}`);
87
+ validateInstallerReceipt(receipt, entries[0], platform, requirements.platforms[platform], release.assets, requirements.offlinePolicy);
88
+ }
89
+ validateCommandReceipts(receipt, receipt.commandReceipts, requirements, release.assets);
90
+ assert(receipt.assets.length === required.length, "Incorrect qualification asset count");
91
+ for (const name of required)
92
+ assert(matches(uniqueAsset(receipt.assets, name), uniqueAsset(release.assets, name)), `Qualification asset mismatch: ${name}`);
93
+ return !0;
94
+ }
95
+ export function validateQualificationRun(run, jobs, receipt, repository, requirements, assetsWorkflow) {
96
+ expectedAssets(requirements);
97
+ assert(String(run.id) === receipt.runId && run.run_attempt === receipt.runAttempt && run.conclusion === "success" && run.path === assetsWorkflow && run.repository.full_name === repository && run.head_sha === receipt.workflowSha && ["release", "workflow_dispatch"].includes(run.event), "Qualification run identity mismatch");
98
+ for (const platform of Object.keys(requirements.platforms)) {
99
+ const platformJobs = jobs.filter((job) => new RegExp(`^(?:[A-Za-z0-9_-]+ / )?Installer / ${platform}$`).test(job.name));
100
+ assert(platformJobs.length === 1 && platformJobs[0].conclusion === "success", `Missing successful installer job: ${platform}`);
101
+ }
102
+ return !0;
103
+ }
@@ -1 +1 @@
1
- {"version":"0.11.3","commit":"630cd5bee4ccc87fcc92da4b5e827a1ed294a3a6"}
1
+ {"version":"0.11.4","commit":"b5e763c3b29de055a4ad80c5c6a4446609fbe3a8"}
@@ -0,0 +1,96 @@
1
+ import { discardStream } from "./discard-stream";
2
+
3
+ export class BoundedBodyError extends Error {
4
+ reason;
5
+ constructor(reason, message = `Body ${reason}`, options) {
6
+ super(message, options);
7
+ this.name = "BoundedBodyError";
8
+ this.reason = reason;
9
+ }
10
+ }
11
+ const signalOf = (source, options) => options?.signal ?? (source instanceof Request ? source.signal : void 0);
12
+ export async function readBoundedBytes(source, limit, options) {
13
+ if (!Number.isSafeInteger(limit) || limit < 0)
14
+ throw RangeError("Invalid body limit");
15
+ const claimed = source.headers.get("content-length");
16
+ if (claimed !== null && (!/^\d+$/.test(claimed) || Number(claimed) > limit)) {
17
+ discardStream(source.body);
18
+ throw new BoundedBodyError("too-large");
19
+ }
20
+ const signal = signalOf(source, options);
21
+ if (signal?.aborted) {
22
+ discardStream(source.body);
23
+ throw new BoundedBodyError("aborted");
24
+ }
25
+ if (!source.body) {
26
+ if (options?.allowEmpty)
27
+ return new Uint8Array(0);
28
+ throw new BoundedBodyError("missing");
29
+ }
30
+ const reader = source.body.getReader();
31
+ let abort;
32
+ const aborted = signal ? new Promise((_, reject) => {
33
+ abort = () => {
34
+ discardStream(reader);
35
+ reject(new BoundedBodyError("aborted"));
36
+ };
37
+ signal.addEventListener("abort", abort, { once: !0 });
38
+ }) : void 0;
39
+ aborted?.catch(() => {});
40
+ const chunks = [];
41
+ let total = 0;
42
+ try {
43
+ for (;; ) {
44
+ const next = await (aborted ? Promise.race([reader.read(), aborted]) : reader.read());
45
+ if (signal?.aborted)
46
+ throw new BoundedBodyError("aborted");
47
+ if (next.done)
48
+ break;
49
+ total += next.value.byteLength;
50
+ if (total > limit) {
51
+ discardStream(reader);
52
+ throw new BoundedBodyError("too-large");
53
+ }
54
+ chunks.push(next.value);
55
+ }
56
+ } catch (error) {
57
+ if (error instanceof BoundedBodyError)
58
+ throw error;
59
+ throw new BoundedBodyError("invalid", "Body stream failed", { cause: error });
60
+ } finally {
61
+ if (abort)
62
+ signal?.removeEventListener("abort", abort);
63
+ try {
64
+ reader.releaseLock();
65
+ } catch {}
66
+ }
67
+ if (chunks.length === 1)
68
+ return chunks[0];
69
+ const bytes = new Uint8Array(total);
70
+ let offset = 0;
71
+ for (const chunk of chunks) {
72
+ bytes.set(chunk, offset);
73
+ offset += chunk.byteLength;
74
+ }
75
+ return bytes;
76
+ }
77
+ const strictUtf8 = new TextDecoder("utf-8", { fatal: !0 });
78
+ export async function readBoundedText(source, limit, options) {
79
+ const bytes = await readBoundedBytes(source, limit, options);
80
+ try {
81
+ return strictUtf8.decode(bytes);
82
+ } catch {
83
+ throw new BoundedBodyError("invalid", "Body is not UTF-8");
84
+ }
85
+ }
86
+ export async function readBoundedJson(source, limit, options) {
87
+ const text = await readBoundedText(source, limit, options);
88
+ try {
89
+ return JSON.parse(text);
90
+ } catch {
91
+ throw new BoundedBodyError("invalid", "Body is not JSON");
92
+ }
93
+ }
94
+ export function boundedBodyStatus(error) {
95
+ return error.reason === "too-large" ? 413 : error.reason === "aborted" ? 408 : 400;
96
+ }
@@ -0,0 +1,7 @@
1
+ export function discardStream(stream) {
2
+ if (!stream)
3
+ return;
4
+ try {
5
+ Promise.resolve(stream.cancel()).catch(() => {});
6
+ } catch {}
7
+ }
@@ -0,0 +1,137 @@
1
+ import { isRecord } from "../../app/value-guards";
2
+ import { containsAsciiControl } from "../../desktop/string-policy";
3
+ const packageName = /^[a-z0-9][a-z0-9@+._-]{0,63}$/, executableName = /^[a-z][a-z0-9-]{0,63}$/, licenseToken = /^[A-Za-z0-9][A-Za-z0-9.+:-]{0,63}$/, category = /^[A-Za-z][A-Za-z0-9-]{0,31}$/, relative = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/, optdependsEntry = /^[a-z0-9][a-z0-9@+._-]{0,63}(?:: [^<>\r\n]{1,128})?$/;
4
+ function assert(condition, message) {
5
+ if (!condition)
6
+ throw Error(message);
7
+ }
8
+ function text(value, maximum) {
9
+ return typeof value === "string" && value.length > 0 && value.length <= maximum && !containsAsciiControl(value) && value.trim() === value;
10
+ }
11
+ function httpsUrl(value) {
12
+ if (typeof value !== "string" || value.length > 300)
13
+ return !1;
14
+ let url;
15
+ try {
16
+ url = new URL(value);
17
+ } catch {
18
+ return !1;
19
+ }
20
+ return url.protocol === "https:" && (url.href === value || url.pathname === "/" && url.href === `${value}/`) && !url.username && !url.password && !url.port && !url.search && !url.hash;
21
+ }
22
+ function sourceTemplate(value) {
23
+ if (typeof value !== "string" || !value.includes("{tag}"))
24
+ return !1;
25
+ const rest = value.replaceAll("{tag}", "");
26
+ return !rest.includes("{") && !rest.includes("}") && httpsUrl(value.replaceAll("{tag}", "v1.0.0"));
27
+ }
28
+ function tokenList(value, options) {
29
+ assert(Array.isArray(value) && value.length >= options.minimum && value.length <= options.maximum && value.every((item) => typeof item === "string" && item.length <= 200 && options.pattern.test(item) && !containsAsciiControl(item)) && new Set(value).size === value.length, options.message);
30
+ return [...value];
31
+ }
32
+ function bundlePath(value, suffix) {
33
+ return typeof value === "string" && value.length <= 200 && relative.test(value) && !value.split("/").some((part) => part === "." || part === "..") && (suffix === void 0 || value.endsWith(suffix));
34
+ }
35
+ const policyKeys = new Set([
36
+ "pkgname",
37
+ "pkgdesc",
38
+ "maintainer",
39
+ "url",
40
+ "license",
41
+ "depends",
42
+ "optdepends",
43
+ "provides",
44
+ "conflicts",
45
+ "executable",
46
+ "setuid",
47
+ "desktop",
48
+ "icon",
49
+ "licenseSource",
50
+ "links",
51
+ "channel",
52
+ "repository"
53
+ ]);
54
+ export function parseArchPackage(value) {
55
+ assert(isRecord(value) && Object.keys(value).every((key) => policyKeys.has(key)), "Invalid Arch package configuration");
56
+ const policy = value, desktop = policy.desktop, links = policy.links ?? [];
57
+ assert(typeof policy.pkgname === "string" && packageName.test(policy.pkgname) && policy.pkgname.endsWith("-bin"), "Arch package name must be a lowercase pkgname ending in -bin");
58
+ assert(text(policy.pkgdesc, 256), "Invalid Arch package description");
59
+ assert(text(policy.maintainer, 128) && /^[^<>\r\n]{1,64} <[^<>\r\n]{3,64}>$/.test(policy.maintainer), "Invalid Arch package maintainer");
60
+ assert(httpsUrl(policy.url), "Invalid Arch package URL");
61
+ assert(text(policy.executable, 64) && executableName.test(policy.executable), "Invalid Arch executable");
62
+ assert(policy.icon === void 0 || bundlePath(policy.icon, ".svg"), "Invalid Arch package icon");
63
+ assert(policy.licenseSource === void 0 || sourceTemplate(policy.licenseSource), "Invalid Arch license source");
64
+ assert(isRecord(desktop) && Object.keys(desktop).every((key) => ["name", "comment", "categories"].includes(key)) && text(desktop.name, 64) && (desktop.comment === void 0 || text(desktop.comment, 128)) && "categories" in desktop, "Invalid Arch desktop entry");
65
+ assert(Array.isArray(links) && links.length <= 8 && links.every((link, index) => isRecord(link) && Object.keys(link).length === 2 && text(link.name, 64) && executableName.test(link.name) && link.name !== policy.executable && links.findIndex((item) => isRecord(item) && item.name === link.name) === index && bundlePath(link.target)), "Invalid Arch package links");
66
+ assert(policy.channel === void 0 || policy.channel === "stable" || policy.channel === "daily", "Invalid Arch package channel");
67
+ const repository = policy.repository;
68
+ assert(repository === void 0 || isRecord(repository) && Object.keys(repository).every((key) => ["name", "base", "publicKey", "keyFingerprint"].includes(key)) && typeof repository.name === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(repository.name) && httpsUrl(repository.base) && repository.base.endsWith("/") && httpsUrl(repository.publicKey) && (repository.keyFingerprint === void 0 || typeof repository.keyFingerprint === "string" && /^[0-9A-F]{40}$/.test(repository.keyFingerprint)), "Invalid Arch package repository");
69
+ return {
70
+ pkgname: policy.pkgname,
71
+ pkgdesc: policy.pkgdesc,
72
+ maintainer: policy.maintainer,
73
+ url: policy.url,
74
+ license: tokenList(policy.license, {
75
+ maximum: 8,
76
+ minimum: 1,
77
+ pattern: licenseToken,
78
+ message: "Invalid Arch package license"
79
+ }),
80
+ depends: tokenList(policy.depends, {
81
+ maximum: 64,
82
+ minimum: 1,
83
+ pattern: packageName,
84
+ message: "Invalid Arch package dependencies"
85
+ }),
86
+ optdepends: tokenList(policy.optdepends ?? [], {
87
+ maximum: 32,
88
+ minimum: 0,
89
+ pattern: optdependsEntry,
90
+ message: "Invalid Arch optional dependencies"
91
+ }),
92
+ provides: tokenList(policy.provides ?? [], {
93
+ maximum: 16,
94
+ minimum: 0,
95
+ pattern: packageName,
96
+ message: "Invalid Arch package provides"
97
+ }),
98
+ conflicts: tokenList(policy.conflicts ?? [], {
99
+ maximum: 16,
100
+ minimum: 0,
101
+ pattern: packageName,
102
+ message: "Invalid Arch package conflicts"
103
+ }),
104
+ executable: policy.executable,
105
+ setuid: tokenList(policy.setuid ?? [], {
106
+ maximum: 8,
107
+ minimum: 0,
108
+ pattern: /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+$/,
109
+ message: "Invalid Arch setuid executables"
110
+ }),
111
+ desktop: {
112
+ name: desktop.name,
113
+ ...desktop.comment === void 0 ? {} : { comment: desktop.comment },
114
+ categories: tokenList(desktop.categories, {
115
+ maximum: 8,
116
+ minimum: 1,
117
+ pattern: category,
118
+ message: "Invalid Arch desktop categories"
119
+ })
120
+ },
121
+ ...policy.icon === void 0 ? {} : { icon: policy.icon },
122
+ ...policy.licenseSource === void 0 ? {} : { licenseSource: policy.licenseSource },
123
+ links: links.map((link) => ({
124
+ name: link.name,
125
+ target: link.target
126
+ })),
127
+ channel: policy.channel ?? "stable",
128
+ ...repository === void 0 ? {} : {
129
+ repository: {
130
+ name: repository.name,
131
+ base: repository.base,
132
+ publicKey: repository.publicKey,
133
+ ...typeof repository.keyFingerprint === "string" ? { keyFingerprint: repository.keyFingerprint } : {}
134
+ }
135
+ }
136
+ };
137
+ }
@@ -0,0 +1,164 @@
1
+ import { isRecord } from "../../app/value-guards";
2
+ import { assertSidecarNames } from "../../native/app-bundle";
3
+ import { parseArchPackage } from "./arch-package-policy";
4
+ import { containsAsciiControl } from "../../desktop/string-policy";
5
+ import { parseReleaseFeed } from "./release-feed";
6
+ function assert(condition, message) {
7
+ if (!condition)
8
+ throw Error(message);
9
+ }
10
+ export function parseOfflinePolicy(value) {
11
+ assert(typeof value === "object" && value !== null && !Array.isArray(value), "Invalid offline policy");
12
+ const policy = value;
13
+ assert(typeof policy.marker === "string" && policy.marker.trim().length > 0 && policy.marker.length <= 256 && !containsAsciiControl(policy.marker), "Invalid offline marker");
14
+ if (policy.kind === "standalone") {
15
+ assert(Object.keys(policy).length === 2, "Invalid standalone offline policy");
16
+ return { kind: "standalone", marker: policy.marker };
17
+ }
18
+ assert(policy.kind === "local-bootstrap" && Object.keys(policy).length === 3 && typeof policy.path === "string" && policy.path.length <= 256 && /^\/(?:[A-Za-z0-9_~-]+\/)*[A-Za-z0-9_~-]+$/.test(policy.path) && !policy.path.startsWith("/__framework/"), "Invalid bootstrap offline policy");
19
+ return { kind: "local-bootstrap", marker: policy.marker, path: policy.path };
20
+ }
21
+ const strings = (value) => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string" && item.length <= 200 && /^[A-Za-z0-9][A-Za-z0-9._{}-]*$/.test(item) && !item.replaceAll("{tag}", "").includes("{") && !item.replaceAll("{tag}", "").includes("}")) && new Set(value).size === value.length;
22
+ export const appIdPattern = /^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/;
23
+ const token = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._=-]{0,63}$/.test(value), tokens = (value, minimum) => Array.isArray(value) && value.length >= minimum && value.length <= 8 && value.every(token), relativePath = (value) => typeof value === "string" && value.length <= 200 && /^[A-Za-z0-9._/-]+$/.test(value) && value.split("/").every((part) => part !== "" && part !== "." && part !== "..");
24
+ export const platformTargets = {
25
+ "macos-arm64": ["darwin", "arm64"],
26
+ "macos-x64": ["darwin", "x64"],
27
+ "windows-x64": ["win32", "x64"],
28
+ "linux-x64": ["linux", "x64"],
29
+ "linux-arm64": ["linux", "arm64"]
30
+ }, releasePlatforms = Object.keys(platformTargets), legacyDesktopPlatforms = [
31
+ "macos-arm64",
32
+ "windows-x64",
33
+ "linux-x64"
34
+ ];
35
+ export function requiredDesktopPlatforms(profile) {
36
+ return profile === "desktop-v2" ? releasePlatforms : legacyDesktopPlatforms;
37
+ }
38
+ function parseCommandArtifacts(value, platforms) {
39
+ if (value === void 0)
40
+ return [];
41
+ if (!isRecord(value) || Object.keys(value).length > 4)
42
+ throw Error("Invalid command artifacts");
43
+ return Object.entries(value).map(([kind, policy]) => {
44
+ const qualification = isRecord(policy) ? policy.qualification : void 0, env = isRecord(qualification) ? qualification.env : void 0;
45
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(kind) || !isRecord(policy) || Object.keys(policy).length !== 5 || typeof policy.appId !== "string" || policy.appId.length > 255 || !appIdPattern.test(policy.appId) || typeof policy.executable !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(policy.executable) || !relativePath(policy.build) || !isRecord(policy.platforms) || Object.keys(policy.platforms).length !== platforms.length || platforms.some((platform) => typeof policy.platforms[platform] !== "string" || !strings([policy.platforms[platform]]) || !policy.platforms[platform].endsWith(".tar.gz")) || !isRecord(qualification) || Object.keys(qualification).length !== 3 || !isRecord(env) || Object.keys(env).length > 16 || Object.entries(env).some(([name, item]) => !/^[A-Z][A-Z0-9_]{0,63}$/.test(name) || /^(?:PATH|HOME|USERPROFILE|TMP|TEMP|TMPDIR|SYSTEMROOT|WINDIR|COMSPEC|PATHEXT|LOCALAPPDATA|APPDATA|XDG_[A-Z_]+)$/.test(name) || typeof item !== "string" || item.length > 256 || containsAsciiControl(item)) || !Array.isArray(qualification.probes) || qualification.probes.length > 8 || !qualification.probes.every((probe) => tokens(probe, 1)) || !tokens(qualification.service, 1))
46
+ throw Error("Invalid command artifact");
47
+ return {
48
+ kind,
49
+ appId: policy.appId,
50
+ executable: policy.executable,
51
+ build: policy.build,
52
+ platforms: Object.fromEntries(platforms.map((platform) => [
53
+ platform,
54
+ policy.platforms[platform]
55
+ ])),
56
+ qualification: {
57
+ env: { ...env },
58
+ probes: qualification.probes.map((probe) => [...probe]),
59
+ service: [...qualification.service]
60
+ }
61
+ };
62
+ });
63
+ }
64
+ const workflowDirectory = ".github/workflows/";
65
+ export function hostedReleaseWorkflows(workflows) {
66
+ if (!workflows)
67
+ throw Error("Release configuration names no releaseWorkflows; release with --local");
68
+ return workflows;
69
+ }
70
+ export const workflowFile = (path) => path.slice(workflowDirectory.length);
71
+ const workflowPath = (value) => typeof value === "string" && value.length <= 200 && value.startsWith(workflowDirectory) && /^[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$/.test(workflowFile(value));
72
+ export function parseReleaseConfig(config) {
73
+ if (!isRecord(config) || !isRecord(config.platforms) || !strings(config.releaseAssets) || !strings(config.dailyDiscoveryAssets) || !strings(config.stableDiscoveryAssets) || !Number.isSafeInteger(config.soakHours) || Number(config.soakHours) < 0 || Number(config.soakHours) > 8760)
74
+ throw Error("Invalid release configuration");
75
+ const workflows = config.releaseWorkflows;
76
+ let releaseWorkflows;
77
+ if (workflows !== void 0) {
78
+ if (!isRecord(workflows) || Object.keys(workflows).length !== 2 || !workflowPath(workflows.control) || !workflowPath(workflows.assets) || workflows.control === workflows.assets)
79
+ throw Error("Invalid release workflows");
80
+ releaseWorkflows = { control: workflows.control, assets: workflows.assets };
81
+ }
82
+ const feed = parseReleaseFeed(config.releaseFeed);
83
+ let sidecars;
84
+ try {
85
+ sidecars = assertSidecarNames(config.sidecars ?? [], "windows-x64");
86
+ } catch {
87
+ throw Error("Invalid release sidecars");
88
+ }
89
+ const offlinePolicy = config.offlinePolicy === void 0 ? void 0 : parseOfflinePolicy(config.offlinePolicy), source = config.versionSource;
90
+ if (!isRecord(source) || Object.keys(source).length !== 2 || source.kind !== "source-manifest" || typeof source.path !== "string" || source.path.length > 200 || !/^[A-Za-z0-9._/-]+\.json$/.test(source.path) || source.path.startsWith("/") || !source.path.split("/").every((part) => part !== "" && part !== "." && part !== ".."))
91
+ throw Error("Invalid release version source");
92
+ const versionSource = { kind: "source-manifest", path: source.path }, releasePleaseManifestPath = source.path, expectedReads = config.offlineExpectedReads === void 0 ? [] : config.offlineExpectedReads;
93
+ if (!Array.isArray(expectedReads) || expectedReads.length > 32 || new Set(expectedReads).size !== expectedReads.length || JSON.stringify(expectedReads).length > 8192)
94
+ throw Error("Invalid offline expected reads");
95
+ for (const item of expectedReads) {
96
+ if (typeof item !== "string" || item.length > 2048)
97
+ throw Error("Invalid offline expected read");
98
+ let url;
99
+ try {
100
+ url = new URL(item);
101
+ } catch {
102
+ throw Error("Invalid offline expected read");
103
+ }
104
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || url.href !== item)
105
+ throw Error("Invalid offline expected read");
106
+ }
107
+ const platforms = config.platforms;
108
+ for (const required of requiredDesktopPlatforms(config.dailyReleaseProfile))
109
+ if (!Object.hasOwn(platforms, required))
110
+ throw Error("Releases require all supported desktop platforms");
111
+ for (const [platform, assets] of Object.entries(platforms))
112
+ if (!/^[a-z0-9-]+$/.test(platform) || !strings(assets))
113
+ throw Error("Invalid release platform configuration");
114
+ const platformSnapshot = Object.fromEntries(Object.entries(platforms).map(([platform, assets]) => [platform, [...assets]])), archPackage = config.archPackage === void 0 ? void 0 : parseArchPackage(config.archPackage), commandArtifacts = parseCommandArtifacts(config.commandArtifacts, Object.keys(platforms)), appIds = [config.appId, ...commandArtifacts.map((artifact) => artifact.appId)];
115
+ if (new Set(appIds).size !== appIds.length)
116
+ throw Error("Command artifacts need their own update identity");
117
+ const releaseAssets = [...config.releaseAssets], daily = [...config.dailyDiscoveryAssets], stable = [...config.stableDiscoveryAssets];
118
+ if (daily.some((name) => !releaseAssets.includes(name) || stable.includes(name)) || stable.some((name) => !releaseAssets.includes(name)))
119
+ throw Error("Daily and stable discovery assets must be distinct release assets");
120
+ const requirements = (tag) => {
121
+ if (!/^v\d+\.\d+\.\d+$/.test(tag) || tag.length > 65)
122
+ throw Error("Invalid release tag");
123
+ const substitute = (value) => value.replaceAll("{tag}", tag), result = {
124
+ platforms: Object.fromEntries(Object.entries(platformSnapshot).map(([platform, assets]) => [
125
+ platform,
126
+ assets.map(substitute)
127
+ ])),
128
+ releaseAssets: releaseAssets.map(substitute),
129
+ ...offlinePolicy ? { offlinePolicy: { ...offlinePolicy } } : {},
130
+ ...commandArtifacts.length ? {
131
+ commandArtifacts: Object.fromEntries(commandArtifacts.map((artifact) => [
132
+ artifact.kind,
133
+ Object.fromEntries(Object.entries(artifact.platforms).map(([platform, name]) => [
134
+ platform,
135
+ substitute(name)
136
+ ]))
137
+ ]))
138
+ } : {}
139
+ }, names = releaseAssetNames(result);
140
+ if (new Set(names).size !== names.length || names.some((name) => !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)))
141
+ throw Error("Invalid or duplicate release asset names");
142
+ return result;
143
+ };
144
+ requirements("v1.0.0");
145
+ return {
146
+ soakHours: config.soakHours,
147
+ expectedReads: [...expectedReads],
148
+ versionSource,
149
+ releasePleaseManifestPath,
150
+ sidecars,
151
+ releaseWorkflows,
152
+ feed,
153
+ archPackage,
154
+ commandArtifacts,
155
+ requirements
156
+ };
157
+ }
158
+ export function releaseAssetNames(requirements) {
159
+ return [
160
+ ...Object.values(requirements.platforms).flat(),
161
+ ...Object.values(requirements.commandArtifacts ?? {}).flatMap((byPlatform) => Object.values(byPlatform)),
162
+ ...requirements.releaseAssets
163
+ ];
164
+ }