@koed-labs/server 0.0.0-stage → 0.11.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.
- package/LICENSE +201 -0
- package/README.md +64 -2
- package/bin/koed.js +7 -0
- package/package.json +26 -4
- package/third-party-notices.json +92 -0
- package/vendor/chunk-2XKSVKQA.js +49 -0
- package/vendor/chunk-4OO6VAU3.js +259 -0
- package/vendor/chunk-53ZFCDHP.js +332 -0
- package/vendor/chunk-6JRWGOQG.js +236 -0
- package/vendor/chunk-6KS67EQE.js +75 -0
- package/vendor/chunk-7EGSY3E4.js +8 -0
- package/vendor/chunk-7FSHVVTZ.js +128 -0
- package/vendor/chunk-7NOQSX4T.js +14 -0
- package/vendor/chunk-7NXKPDF3.js +1586 -0
- package/vendor/chunk-ALJUSOF7.js +175 -0
- package/vendor/chunk-AVQCUFYQ.js +16 -0
- package/vendor/chunk-BGENSONI.js +18 -0
- package/vendor/chunk-BTS4ZTF3.js +43 -0
- package/vendor/chunk-BUIM2M4R.js +22 -0
- package/vendor/chunk-C4V72GXC.js +194 -0
- package/vendor/chunk-C5SNDPAP.js +2472 -0
- package/vendor/chunk-CHMH4LH5.js +2497 -0
- package/vendor/chunk-EA4QDDQA.js +58 -0
- package/vendor/chunk-EDPNYIX5.js +5448 -0
- package/vendor/chunk-FN3HUUO2.js +1974 -0
- package/vendor/chunk-FSNLU46W.js +14548 -0
- package/vendor/chunk-FYYRFX4U.js +4423 -0
- package/vendor/chunk-GFASBPV2.js +42 -0
- package/vendor/chunk-HC76426R.js +48 -0
- package/vendor/chunk-IY2HRXOZ.js +99 -0
- package/vendor/chunk-JBGD4JLR.js +3779 -0
- package/vendor/chunk-JYK6UL6D.js +261 -0
- package/vendor/chunk-LRP66XEY.js +13907 -0
- package/vendor/chunk-NOU7RHYZ.js +26 -0
- package/vendor/chunk-NVTMIAAF.js +113 -0
- package/vendor/chunk-O7DW2VAV.js +14 -0
- package/vendor/chunk-OCILJ737.js +299 -0
- package/vendor/chunk-PL3LWC5C.js +754 -0
- package/vendor/chunk-QRKHHWJJ.js +104 -0
- package/vendor/chunk-QT24SAW6.js +110 -0
- package/vendor/chunk-RCR4XPE3.js +26020 -0
- package/vendor/chunk-SHLRINKO.js +73 -0
- package/vendor/chunk-SNKWETM5.js +35 -0
- package/vendor/chunk-SRKIBFOE.js +242 -0
- package/vendor/chunk-T6UB5PNX.js +124 -0
- package/vendor/chunk-TG26CZGQ.js +23 -0
- package/vendor/chunk-TISYUUEJ.js +188 -0
- package/vendor/chunk-TSAYTRX3.js +89 -0
- package/vendor/chunk-TVYEB2GN.js +343 -0
- package/vendor/chunk-UB6JCVQ3.js +461 -0
- package/vendor/chunk-V67IQB7H.js +153 -0
- package/vendor/chunk-VGIYSDNU.js +522 -0
- package/vendor/chunk-W2HNI6AA.js +75 -0
- package/vendor/chunk-W2OJZZ6X.js +20 -0
- package/vendor/chunk-WDFERJG3.js +2208 -0
- package/vendor/chunk-WPIEF4LY.js +1647 -0
- package/vendor/chunk-XIZVLPHZ.js +18 -0
- package/vendor/chunk-YZLQZU5E.js +46 -0
- package/vendor/chunk-Z5WCAUA6.js +148 -0
- package/vendor/chunk-ZIOKV2X6.js +1589 -0
- package/vendor/chunk-ZOHNXUDY.js +12501 -0
- package/vendor/chunk-ZUDSZGVO.js +11 -0
- package/vendor/cli.js +7 -0
- package/vendor/component-manifest-catalog.js +9 -0
- package/vendor/control-plane.js +28 -0
- package/vendor/package.json +1 -0
- package/vendor/privacy-service-bootstrap.js +6 -0
|
@@ -0,0 +1,1974 @@
|
|
|
1
|
+
import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
isRuntimeGenerationState
|
|
4
|
+
} from "./chunk-T6UB5PNX.js";
|
|
5
|
+
import {
|
|
6
|
+
productionComponentManifestCatalog
|
|
7
|
+
} from "./chunk-ZUDSZGVO.js";
|
|
8
|
+
import {
|
|
9
|
+
canonicalArtifactJson,
|
|
10
|
+
extractVerifiedPackageArchive,
|
|
11
|
+
isVersionDowngrade,
|
|
12
|
+
validateComponentManifest,
|
|
13
|
+
verifyComponent,
|
|
14
|
+
verifyComponentManifestPin,
|
|
15
|
+
verifyExtractedComponent
|
|
16
|
+
} from "./chunk-ZIOKV2X6.js";
|
|
17
|
+
import {
|
|
18
|
+
lookupManifestPin,
|
|
19
|
+
validateManifestCatalog
|
|
20
|
+
} from "./chunk-IY2HRXOZ.js";
|
|
21
|
+
|
|
22
|
+
// packages/koed-server/dist/generation-lifecycle.js
|
|
23
|
+
import { createHash as createHash3, randomBytes } from "node:crypto";
|
|
24
|
+
import { existsSync as existsSync2, closeSync as closeSync5, constants as constants4, fstatSync as fstatSync3, openSync as openSync5, readSync, lstatSync as lstatSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync3, renameSync as renameSync3, rmSync as rmSync6, statSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
25
|
+
import { dirname as dirname2, isAbsolute as isAbsolute3, parse as parse2, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
|
|
26
|
+
|
|
27
|
+
// packages/koed-server/dist/desktop-runtime-capability.js
|
|
28
|
+
import { createHash } from "node:crypto";
|
|
29
|
+
import { closeSync, constants, lstatSync, openSync, readFileSync, readlinkSync, readdirSync, realpathSync } from "node:fs";
|
|
30
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
31
|
+
var issuedCapabilities = /* @__PURE__ */ new WeakSet();
|
|
32
|
+
var hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
33
|
+
function validateDesktopRuntimeManifest(value) {
|
|
34
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
35
|
+
throw new Error("Desktop runtime bundle manifest is invalid");
|
|
36
|
+
const record = value;
|
|
37
|
+
const target = record.target;
|
|
38
|
+
if (record.schemaVersion !== 1 || record.component !== "base" || typeof record.productVersion !== "string" || !target || typeof target !== "object" || Array.isArray(target) || target.platform !== "macos" && target.platform !== "linux" || target.architecture !== "arm64" && target.architecture !== "x64" || !Array.isArray(record.files))
|
|
39
|
+
throw new Error("Desktop runtime bundle manifest is invalid");
|
|
40
|
+
for (const item of record.files) {
|
|
41
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
42
|
+
throw new Error("Desktop runtime bundle manifest is invalid");
|
|
43
|
+
const entry = item;
|
|
44
|
+
if (typeof entry.path !== "string" || typeof entry.sha256 !== "string" || entry.kind !== "file" && entry.kind !== "symlink")
|
|
45
|
+
throw new Error("Desktop runtime bundle manifest is invalid");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
var regularFile = (path) => {
|
|
49
|
+
if (constants.O_NOFOLLOW === void 0)
|
|
50
|
+
throw new Error("Desktop bundle no-follow access is unavailable");
|
|
51
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
52
|
+
try {
|
|
53
|
+
if (!lstatSync(path).isFile())
|
|
54
|
+
throw new Error("Desktop runtime bundle entry is not a regular file");
|
|
55
|
+
return readFileSync(fd);
|
|
56
|
+
} finally {
|
|
57
|
+
closeSync(fd);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
function verifyDesktopRuntimeBundle(resourcesPath) {
|
|
61
|
+
const actualResources = realpathSync.native(resolve(resourcesPath));
|
|
62
|
+
const runtimeRoot = resolve(actualResources, "koed-runtime");
|
|
63
|
+
const manifestPath = resolve(runtimeRoot, "desktop-bundle-manifest.json");
|
|
64
|
+
const manifestBytes = regularFile(manifestPath);
|
|
65
|
+
const manifest = JSON.parse(manifestBytes.toString("utf8"));
|
|
66
|
+
validateDesktopRuntimeManifest(manifest);
|
|
67
|
+
const record = manifest;
|
|
68
|
+
const seen = /* @__PURE__ */ new Set();
|
|
69
|
+
for (const entry of record.files) {
|
|
70
|
+
const path = entry.path;
|
|
71
|
+
const absolute = resolve(runtimeRoot, path);
|
|
72
|
+
const rel = relative(runtimeRoot, absolute);
|
|
73
|
+
if (!path || !/^[a-f0-9]{64}$/.test(entry.sha256) || path.split("/").some((part) => !part || part === "." || part === "..") || path.startsWith("privacy-service/") || isAbsolute(path) || rel === ".." || rel.startsWith(`..${sep}`) || seen.has(path)) {
|
|
74
|
+
throw new Error("Desktop runtime bundle manifest path is invalid");
|
|
75
|
+
}
|
|
76
|
+
seen.add(path);
|
|
77
|
+
const actualDigest = entry.kind === "file" ? hash(regularFile(absolute)) : hash(readlinkSync(absolute));
|
|
78
|
+
if (actualDigest !== entry.sha256) {
|
|
79
|
+
throw new Error("Desktop runtime bundle file digest mismatch");
|
|
80
|
+
}
|
|
81
|
+
if (entry.kind === "symlink") {
|
|
82
|
+
const target = realpathSync.native(absolute);
|
|
83
|
+
const targetRelative = relative(runtimeRoot, target);
|
|
84
|
+
if (targetRelative === ".." || targetRelative.startsWith(`..${sep}`) || isAbsolute(targetRelative)) {
|
|
85
|
+
throw new Error("Desktop runtime bundle symlink escaped resources");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const actualFiles = [];
|
|
90
|
+
const collectFiles = (directory, prefix = "") => {
|
|
91
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
92
|
+
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
93
|
+
if (entry.isDirectory())
|
|
94
|
+
collectFiles(resolve(directory, entry.name), path);
|
|
95
|
+
else if (entry.isFile() || entry.isSymbolicLink()) {
|
|
96
|
+
if (path !== "desktop-bundle-manifest.json")
|
|
97
|
+
actualFiles.push(path);
|
|
98
|
+
} else
|
|
99
|
+
throw new Error("Desktop runtime bundle contains an unsupported entry");
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
collectFiles(runtimeRoot);
|
|
103
|
+
if (actualFiles.some((path) => !seen.has(path)) || actualFiles.length !== seen.size) {
|
|
104
|
+
throw new Error("Desktop runtime bundle contains an unlisted file");
|
|
105
|
+
}
|
|
106
|
+
const verifiedManifest = Object.freeze({
|
|
107
|
+
...record,
|
|
108
|
+
target: Object.freeze({ ...record.target }),
|
|
109
|
+
files: Object.freeze(record.files.map((entry) => Object.freeze({ ...entry })))
|
|
110
|
+
});
|
|
111
|
+
const capability = Object.freeze({
|
|
112
|
+
resourcesPath: actualResources,
|
|
113
|
+
productVersion: record.productVersion,
|
|
114
|
+
bundleDigest: hash(canonicalArtifactJson(record)),
|
|
115
|
+
manifest: verifiedManifest,
|
|
116
|
+
target: verifiedManifest.target
|
|
117
|
+
});
|
|
118
|
+
issuedCapabilities.add(capability);
|
|
119
|
+
return capability;
|
|
120
|
+
}
|
|
121
|
+
function validateDesktopRuntimeCapability(capability) {
|
|
122
|
+
return typeof capability === "object" && capability !== null && issuedCapabilities.has(capability);
|
|
123
|
+
}
|
|
124
|
+
function deriveDesktopRuntimeOwner(koedHome, stableInstallationIdentity) {
|
|
125
|
+
return {
|
|
126
|
+
kind: "desktop",
|
|
127
|
+
installationId: hash(`${resolve(koedHome)}
|
|
128
|
+
${resolve(stableInstallationIdentity)}`).slice(0, 32)
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function resolveDesktopRuntimeOwner(capability, koedHome) {
|
|
132
|
+
if (!validateDesktopRuntimeCapability(capability)) {
|
|
133
|
+
throw new Error("validated private Desktop runtime capability is required");
|
|
134
|
+
}
|
|
135
|
+
return deriveDesktopRuntimeOwner(koedHome, capability.resourcesPath);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// packages/koed-server/dist/component-store.js
|
|
139
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
140
|
+
import { chmodSync, closeSync as closeSync2, constants as constants2, copyFileSync, existsSync, fstatSync, lstatSync as lstatSync2, openSync as openSync2, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync2, readdirSync as readdirSync2, renameSync, rmSync as rmSync3, writeFileSync } from "node:fs";
|
|
141
|
+
import { dirname, isAbsolute as isAbsolute2, parse, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
|
|
142
|
+
|
|
143
|
+
// packages/koed-server/dist/bounded-download.js
|
|
144
|
+
import { createWriteStream, rmSync } from "node:fs";
|
|
145
|
+
import { basename } from "node:path";
|
|
146
|
+
import { Readable, Transform } from "node:stream";
|
|
147
|
+
import { pipeline } from "node:stream/promises";
|
|
148
|
+
var MAX_REDIRECTS = 5;
|
|
149
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
150
|
+
var abortedError = (signal, cause) => new Error(signal.reason?.name === "TimeoutError" ? "component installation timed out" : "component installation cancelled", cause === void 0 ? void 0 : { cause });
|
|
151
|
+
var stalledError = (cause) => new Error(`component download stalled: no data for ${REQUEST_TIMEOUT_MS / 1e3} s`, { cause });
|
|
152
|
+
var cancelBody = async (response) => {
|
|
153
|
+
try {
|
|
154
|
+
await response.body?.cancel();
|
|
155
|
+
} catch {
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
async function fetchBounded(urlText, destination, limit, signal, progress, collectBytes = true, attempt = 0) {
|
|
159
|
+
let url;
|
|
160
|
+
try {
|
|
161
|
+
url = new URL(urlText);
|
|
162
|
+
} catch {
|
|
163
|
+
throw new Error("component source URL is invalid");
|
|
164
|
+
}
|
|
165
|
+
if (url.protocol !== "https:" || url.username || url.password)
|
|
166
|
+
throw new Error("component downloads require safe HTTPS URLs");
|
|
167
|
+
for (let redirects = 0; ; redirects++) {
|
|
168
|
+
if (signal?.aborted)
|
|
169
|
+
throw abortedError(signal);
|
|
170
|
+
let response;
|
|
171
|
+
const timeoutController = new AbortController();
|
|
172
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
|
173
|
+
let timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
|
|
174
|
+
const resetIdleTimeout = () => {
|
|
175
|
+
clearTimeout(timeout);
|
|
176
|
+
timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
|
|
177
|
+
};
|
|
178
|
+
try {
|
|
179
|
+
response = await fetch(url, {
|
|
180
|
+
redirect: "manual",
|
|
181
|
+
signal: requestSignal
|
|
182
|
+
});
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (signal?.aborted)
|
|
185
|
+
throw abortedError(signal, error);
|
|
186
|
+
if (timeoutController.signal.aborted)
|
|
187
|
+
throw stalledError(error);
|
|
188
|
+
if (attempt < 2 && error instanceof TypeError) {
|
|
189
|
+
await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
|
|
190
|
+
return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
|
|
191
|
+
}
|
|
192
|
+
throw error;
|
|
193
|
+
} finally {
|
|
194
|
+
clearTimeout(timeout);
|
|
195
|
+
}
|
|
196
|
+
if (response.status >= 500 && attempt < 2) {
|
|
197
|
+
await cancelBody(response);
|
|
198
|
+
await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
|
|
199
|
+
return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
|
|
200
|
+
}
|
|
201
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
202
|
+
if (redirects >= MAX_REDIRECTS) {
|
|
203
|
+
await cancelBody(response);
|
|
204
|
+
throw new Error("too many component redirects");
|
|
205
|
+
}
|
|
206
|
+
const location = response.headers.get("location");
|
|
207
|
+
if (!location) {
|
|
208
|
+
await cancelBody(response);
|
|
209
|
+
throw new Error("component redirect has no location");
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
url = new URL(location, url);
|
|
213
|
+
} catch {
|
|
214
|
+
await cancelBody(response);
|
|
215
|
+
throw new Error("component redirect URL is invalid");
|
|
216
|
+
}
|
|
217
|
+
if (url.protocol !== "https:" || url.username || url.password) {
|
|
218
|
+
await cancelBody(response);
|
|
219
|
+
throw new Error("component redirect requires safe HTTPS");
|
|
220
|
+
}
|
|
221
|
+
await cancelBody(response);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (!response.ok || !response.body) {
|
|
225
|
+
await cancelBody(response);
|
|
226
|
+
throw new Error(`component download failed with HTTP ${response.status}`);
|
|
227
|
+
}
|
|
228
|
+
const length = Number(response.headers.get("content-length"));
|
|
229
|
+
if (Number.isFinite(length) && length > limit) {
|
|
230
|
+
await cancelBody(response);
|
|
231
|
+
throw new Error("component download exceeds size limit");
|
|
232
|
+
}
|
|
233
|
+
let transferredBytes = 0;
|
|
234
|
+
const chunks = [];
|
|
235
|
+
const limiter = new Transform({
|
|
236
|
+
transform(chunk, _encoding, callback) {
|
|
237
|
+
resetIdleTimeout();
|
|
238
|
+
transferredBytes += chunk.length;
|
|
239
|
+
if (transferredBytes > limit) {
|
|
240
|
+
callback(new Error("component download exceeds size limit"));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
progress?.({
|
|
244
|
+
phase: basename(destination),
|
|
245
|
+
transferredBytes,
|
|
246
|
+
...Number.isFinite(length) && length > 0 ? { totalBytes: length } : {}
|
|
247
|
+
});
|
|
248
|
+
if (collectBytes)
|
|
249
|
+
chunks.push(Buffer.from(chunk));
|
|
250
|
+
callback(null, chunk);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
const output = createWriteStream(destination, { flags: "wx", mode: 384 });
|
|
254
|
+
resetIdleTimeout();
|
|
255
|
+
try {
|
|
256
|
+
await pipeline(Readable.fromWeb(response.body), limiter, output, { signal: requestSignal });
|
|
257
|
+
} catch (error) {
|
|
258
|
+
rmSync(destination, { force: true });
|
|
259
|
+
if (signal?.aborted)
|
|
260
|
+
throw abortedError(signal, error);
|
|
261
|
+
if (timeoutController.signal.aborted)
|
|
262
|
+
throw stalledError(error);
|
|
263
|
+
if (attempt < 2 && error instanceof TypeError) {
|
|
264
|
+
await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
|
|
265
|
+
return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
|
|
266
|
+
}
|
|
267
|
+
throw error;
|
|
268
|
+
} finally {
|
|
269
|
+
clearTimeout(timeout);
|
|
270
|
+
}
|
|
271
|
+
return collectBytes ? Buffer.concat(chunks) : void 0;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// packages/koed-server/dist/directory-lock.js
|
|
276
|
+
import { mkdirSync, rmSync as rmSync2 } from "node:fs";
|
|
277
|
+
var acquireDirectoryLock = (path) => {
|
|
278
|
+
try {
|
|
279
|
+
mkdirSync(path, { mode: 448 });
|
|
280
|
+
} catch (error) {
|
|
281
|
+
if (error.code !== "EEXIST")
|
|
282
|
+
throw error;
|
|
283
|
+
throw Object.assign(new Error("lock is already held"), { code: "ELOCKED" });
|
|
284
|
+
}
|
|
285
|
+
let released = false;
|
|
286
|
+
return () => {
|
|
287
|
+
if (released)
|
|
288
|
+
return;
|
|
289
|
+
released = true;
|
|
290
|
+
rmSync2(path, { recursive: true, force: true });
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
// packages/koed-server/dist/component-runtime-identity.js
|
|
295
|
+
import process2 from "node:process";
|
|
296
|
+
var isVersion = (value) => typeof value === "string" && /^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){1,2}$/.test(value) && value.split(".").every((part) => Number.isSafeInteger(Number(part)));
|
|
297
|
+
function discoverRuntimeIdentityFromProcess(source) {
|
|
298
|
+
const platform = source.platform === "darwin" ? "macos" : source.platform === "linux" ? "linux" : void 0;
|
|
299
|
+
const architecture = source.arch === "arm64" || source.arch === "x64" ? source.arch : void 0;
|
|
300
|
+
const runtimeVersion = source.versions.electron ?? source.versions.node;
|
|
301
|
+
const nodeVersion = source.versions.node;
|
|
302
|
+
const modulesAbi = source.versions.modules;
|
|
303
|
+
const napiVersion = Number(source.versions.napi ?? "0");
|
|
304
|
+
let libcVersion;
|
|
305
|
+
if (platform === "linux") {
|
|
306
|
+
try {
|
|
307
|
+
libcVersion = source.report?.getReport().header?.glibcVersionRuntime;
|
|
308
|
+
} catch {
|
|
309
|
+
throw new Error("actual runtime identity is unsupported or incomplete");
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (!platform || !architecture || !isVersion(runtimeVersion) || !isVersion(nodeVersion) || typeof modulesAbi !== "string" || !/^\d+$/.test(modulesAbi) || !Number.isSafeInteger(napiVersion) || napiVersion < 0 || platform === "linux" && !isVersion(libcVersion))
|
|
313
|
+
throw new Error("actual runtime identity is unsupported or incomplete");
|
|
314
|
+
return {
|
|
315
|
+
kind: source.versions.electron === void 0 ? "node" : "electron",
|
|
316
|
+
version: runtimeVersion,
|
|
317
|
+
nodeVersion,
|
|
318
|
+
modulesAbi,
|
|
319
|
+
napiVersion,
|
|
320
|
+
platform,
|
|
321
|
+
architecture,
|
|
322
|
+
...libcVersion === void 0 ? {} : { libcVersion }
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
function discoverActualRuntimeIdentity() {
|
|
326
|
+
return discoverRuntimeIdentityFromProcess(process2);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// packages/koed-server/dist/component-store.js
|
|
330
|
+
var MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
|
|
331
|
+
var MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;
|
|
332
|
+
var MAX_GENERATION_RECORD_BYTES = 2 * MAX_MANIFEST_BYTES + 1024 * 1024;
|
|
333
|
+
var hash2 = (value) => createHash2("sha256").update(value).digest("hex");
|
|
334
|
+
var isPlainRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
335
|
+
var aborted = (signal) => {
|
|
336
|
+
if (signal?.aborted)
|
|
337
|
+
throw new Error("component installation cancelled");
|
|
338
|
+
};
|
|
339
|
+
var exactKeys = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
340
|
+
var assertInside = (base, path) => {
|
|
341
|
+
const rel = relative2(resolve2(base), resolve2(path));
|
|
342
|
+
if (rel.startsWith("..") || isAbsolute2(rel))
|
|
343
|
+
throw new Error("component store path escaped KOED_HOME");
|
|
344
|
+
};
|
|
345
|
+
var assertDirectoryChain = (base, path) => {
|
|
346
|
+
assertInside(base, path);
|
|
347
|
+
const absolute = resolve2(path);
|
|
348
|
+
let cursor = parse(absolute).root;
|
|
349
|
+
for (const part of absolute.slice(cursor.length).split(sep2).filter(Boolean)) {
|
|
350
|
+
cursor = resolve2(cursor, part);
|
|
351
|
+
let stat;
|
|
352
|
+
try {
|
|
353
|
+
stat = lstatSync2(cursor);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
if (error.code === "ENOENT")
|
|
356
|
+
return;
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
359
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
360
|
+
throw new Error("component store path contains a non-directory or symbolic link");
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
var ensureSecureDirectory = (home, directory) => {
|
|
364
|
+
assertDirectoryChain(home, directory);
|
|
365
|
+
mkdirSync2(directory, { recursive: true, mode: 448 });
|
|
366
|
+
assertDirectoryChain(home, directory);
|
|
367
|
+
};
|
|
368
|
+
var privateDirectory = (path) => {
|
|
369
|
+
mkdirSync2(path, { recursive: true, mode: 448 });
|
|
370
|
+
const stat = lstatSync2(path);
|
|
371
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
372
|
+
throw new Error("component store directory is not a regular directory");
|
|
373
|
+
chmodSync(path, 448);
|
|
374
|
+
};
|
|
375
|
+
var runtimeMatches = (given, actual) => canonicalArtifactJson(given) === canonicalArtifactJson(actual);
|
|
376
|
+
var readProductionManifestPinCatalog = () => productionComponentManifestCatalog === null ? null : validateManifestCatalog(productionComponentManifestCatalog);
|
|
377
|
+
var compareNumericVersions = (left, right) => {
|
|
378
|
+
const parse3 = (value) => {
|
|
379
|
+
if (!/^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2}$/.test(value))
|
|
380
|
+
return void 0;
|
|
381
|
+
const parts = value.split(".").map(Number);
|
|
382
|
+
if (parts.some((part) => !Number.isSafeInteger(part)))
|
|
383
|
+
return void 0;
|
|
384
|
+
return [...parts, 0, 0].slice(0, 3);
|
|
385
|
+
};
|
|
386
|
+
const leftParts = parse3(left);
|
|
387
|
+
const rightParts = parse3(right);
|
|
388
|
+
if (!leftParts || !rightParts)
|
|
389
|
+
return void 0;
|
|
390
|
+
for (let index = 0; index < 3; index++)
|
|
391
|
+
if (leftParts[index] !== rightParts[index])
|
|
392
|
+
return leftParts[index] - rightParts[index];
|
|
393
|
+
return 0;
|
|
394
|
+
};
|
|
395
|
+
var resolvePinnedTarget = (catalog, component, productVersion, target, libcVersion, variant) => {
|
|
396
|
+
if (!catalog) {
|
|
397
|
+
lookupManifestPin(null, { component, productVersion, target, variant });
|
|
398
|
+
throw new Error("Component manifest pin catalog is unavailable");
|
|
399
|
+
}
|
|
400
|
+
if (catalog.productVersion !== productVersion)
|
|
401
|
+
lookupManifestPin(catalog, { component, productVersion, target, variant });
|
|
402
|
+
if (target.libc)
|
|
403
|
+
return target;
|
|
404
|
+
const matches = catalog.entries.filter((entry) => entry.component === component && entry.variant === variant && entry.target.platform === target.platform && entry.target.architecture === target.architecture);
|
|
405
|
+
if (matches.length === 1)
|
|
406
|
+
return matches[0].target;
|
|
407
|
+
const compatibleLibcTargets = matches.filter((entry) => libcVersion !== void 0 && entry.target.libc !== void 0 && (compareNumericVersions(libcVersion, entry.target.libc.minimumVersion) ?? -1) >= 0).sort((left, right) => compareNumericVersions(right.target.libc.minimumVersion, left.target.libc.minimumVersion) ?? 0);
|
|
408
|
+
if (compatibleLibcTargets.length > 0)
|
|
409
|
+
return compatibleLibcTargets[0].target;
|
|
410
|
+
const platformTargets = matches.filter((entry) => !entry.target.libc);
|
|
411
|
+
if (platformTargets.length === 1)
|
|
412
|
+
return platformTargets[0].target;
|
|
413
|
+
if (matches.length > 1)
|
|
414
|
+
throw new Error("Component manifest pin target is ambiguous; exact libc target is required.");
|
|
415
|
+
lookupManifestPin(catalog, { component, productVersion, target, variant });
|
|
416
|
+
throw new Error("Required component manifest pin is missing.");
|
|
417
|
+
};
|
|
418
|
+
var resolveComponentManifestPinTarget = (catalog, input) => {
|
|
419
|
+
const target = resolvePinnedTarget(catalog, input.component, input.productVersion, input.target, input.runtime.libcVersion, input.variant);
|
|
420
|
+
lookupManifestPin(catalog, {
|
|
421
|
+
component: input.component,
|
|
422
|
+
variant: input.variant,
|
|
423
|
+
productVersion: input.productVersion,
|
|
424
|
+
target
|
|
425
|
+
});
|
|
426
|
+
return target;
|
|
427
|
+
};
|
|
428
|
+
var parseJsonFile = (path, maxBytes, requireCanonical = false) => {
|
|
429
|
+
if (constants2.O_NOFOLLOW === void 0)
|
|
430
|
+
throw new Error("component metadata no-follow access is unavailable");
|
|
431
|
+
const descriptor = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
|
|
432
|
+
try {
|
|
433
|
+
const stat = fstatSync(descriptor);
|
|
434
|
+
if (!stat.isFile() || stat.size > maxBytes)
|
|
435
|
+
throw new Error("component metadata is not a bounded regular file");
|
|
436
|
+
const bytes = readFileSync2(descriptor, "utf8");
|
|
437
|
+
const value = JSON.parse(bytes);
|
|
438
|
+
if (requireCanonical && canonicalArtifactJson(value) !== bytes)
|
|
439
|
+
throw new Error("component metadata is not canonical JSON");
|
|
440
|
+
return value;
|
|
441
|
+
} finally {
|
|
442
|
+
closeSync2(descriptor);
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
var readOfflineSource = (source) => {
|
|
446
|
+
const archivePath = resolve2(source.archivePath);
|
|
447
|
+
const archiveStat = lstatSync2(archivePath);
|
|
448
|
+
if (!archiveStat.isFile() || archiveStat.isSymbolicLink() || archiveStat.size > MAX_ARCHIVE_BYTES)
|
|
449
|
+
throw new Error("component archive is not a bounded regular file");
|
|
450
|
+
return {
|
|
451
|
+
archivePath,
|
|
452
|
+
manifestBytes: readBoundedFile(source.manifestPath, MAX_MANIFEST_BYTES)
|
|
453
|
+
};
|
|
454
|
+
};
|
|
455
|
+
var readBoundedFile = (path, limit) => {
|
|
456
|
+
const stat = lstatSync2(path);
|
|
457
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit)
|
|
458
|
+
throw new Error("component metadata is not a bounded regular file");
|
|
459
|
+
return readFileSync2(path);
|
|
460
|
+
};
|
|
461
|
+
async function acquireLock(home, root, signal, fn) {
|
|
462
|
+
ensureSecureDirectory(home, root);
|
|
463
|
+
let release;
|
|
464
|
+
for (let attempt = 0; !release; attempt++) {
|
|
465
|
+
aborted(signal);
|
|
466
|
+
assertDirectoryChain(home, root);
|
|
467
|
+
try {
|
|
468
|
+
release = acquireDirectoryLock(`${root}.lock`);
|
|
469
|
+
} catch (error) {
|
|
470
|
+
if (error.code !== "ELOCKED" || attempt >= 20)
|
|
471
|
+
throw error;
|
|
472
|
+
await new Promise((resolveDelay, reject) => {
|
|
473
|
+
const cleanup = () => signal?.removeEventListener("abort", cancel);
|
|
474
|
+
const timer = setTimeout(() => {
|
|
475
|
+
cleanup();
|
|
476
|
+
resolveDelay();
|
|
477
|
+
}, 25);
|
|
478
|
+
const cancel = () => {
|
|
479
|
+
clearTimeout(timer);
|
|
480
|
+
cleanup();
|
|
481
|
+
reject(new Error("component installation cancelled"));
|
|
482
|
+
};
|
|
483
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
484
|
+
if (signal?.aborted)
|
|
485
|
+
cancel();
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
try {
|
|
490
|
+
aborted(signal);
|
|
491
|
+
assertDirectoryChain(home, root);
|
|
492
|
+
return await fn();
|
|
493
|
+
} finally {
|
|
494
|
+
release();
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function targetKey(manifest) {
|
|
498
|
+
return hash2(canonicalArtifactJson({
|
|
499
|
+
component: manifest.component,
|
|
500
|
+
...manifest.variant === void 0 ? {} : { variant: manifest.variant },
|
|
501
|
+
productVersion: manifest.productVersion,
|
|
502
|
+
target: manifest.target
|
|
503
|
+
})).slice(0, 24);
|
|
504
|
+
}
|
|
505
|
+
function validateOwner(owner) {
|
|
506
|
+
if (!isPlainRecord(owner) || !exactKeys(owner, ["kind", "installationId"]) || !["cli", "desktop", "standalone"].includes(String(owner.kind)) || typeof owner.installationId !== "string" || !/^[A-Za-z0-9._-]{1,128}$/.test(owner.installationId))
|
|
507
|
+
throw new Error("runtime owner is invalid");
|
|
508
|
+
}
|
|
509
|
+
function writeIndex(home, indexPath, manifestDigest, tempRoot, signal) {
|
|
510
|
+
const temporaryIndex = resolve2(tempRoot, `index-${manifestDigest}.json`);
|
|
511
|
+
writeFileSync(temporaryIndex, JSON.stringify({ manifestDigest }), {
|
|
512
|
+
flag: "wx",
|
|
513
|
+
mode: 384
|
|
514
|
+
});
|
|
515
|
+
aborted(signal);
|
|
516
|
+
assertDirectoryChain(home, dirname(indexPath));
|
|
517
|
+
renameSync(temporaryIndex, indexPath);
|
|
518
|
+
}
|
|
519
|
+
function componentRecordPath(root) {
|
|
520
|
+
return resolve2(root, "component.json");
|
|
521
|
+
}
|
|
522
|
+
function componentPayloadPath(root) {
|
|
523
|
+
return resolve2(root, "payload");
|
|
524
|
+
}
|
|
525
|
+
function readComponentRecord(path) {
|
|
526
|
+
const value = parseJsonFile(path, MAX_MANIFEST_BYTES + 32768);
|
|
527
|
+
if (isPlainRecord(value) && value.schemaVersion === 1)
|
|
528
|
+
throw new Error("Stored component predates manifest pin admission; reinstall components using a trusted versioned control plane.");
|
|
529
|
+
if (!isPlainRecord(value) || !exactKeys(value, [
|
|
530
|
+
"schemaVersion",
|
|
531
|
+
"manifest",
|
|
532
|
+
"manifestDigest",
|
|
533
|
+
"archivePath"
|
|
534
|
+
]) || value.schemaVersion !== 2 || !isPlainRecord(value.manifest) || typeof value.manifestDigest !== "string" || typeof value.archivePath !== "string")
|
|
535
|
+
throw new Error("stored component record is invalid");
|
|
536
|
+
return {
|
|
537
|
+
schemaVersion: 2,
|
|
538
|
+
manifest: value.manifest,
|
|
539
|
+
manifestDigest: value.manifestDigest,
|
|
540
|
+
archivePath: value.archivePath
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
async function verifyStoredComponent(home, root, expected) {
|
|
544
|
+
assertDirectoryChain(home, root);
|
|
545
|
+
const record = readComponentRecord(componentRecordPath(root));
|
|
546
|
+
validateComponentManifest(record.manifest);
|
|
547
|
+
const manifestBytes = Buffer.from(canonicalArtifactJson(record.manifest));
|
|
548
|
+
if (hash2(manifestBytes) !== record.manifestDigest)
|
|
549
|
+
throw new Error("stored component manifest digest mismatch");
|
|
550
|
+
const catalog = readProductionManifestPinCatalog();
|
|
551
|
+
const productVersion = expected.productVersion ?? catalog?.productVersion;
|
|
552
|
+
if (!productVersion)
|
|
553
|
+
throw new Error("Component manifest pin catalog is unavailable");
|
|
554
|
+
const target = resolveComponentManifestPinTarget(catalog, {
|
|
555
|
+
component: expected.component,
|
|
556
|
+
variant: record.manifest.variant,
|
|
557
|
+
productVersion,
|
|
558
|
+
target: expected.target ?? {
|
|
559
|
+
platform: expected.runtime.platform,
|
|
560
|
+
architecture: expected.runtime.architecture
|
|
561
|
+
},
|
|
562
|
+
runtime: expected.runtime
|
|
563
|
+
});
|
|
564
|
+
const archivePath = resolve2(root, record.archivePath);
|
|
565
|
+
assertInside(root, archivePath);
|
|
566
|
+
const manifest = await verifyComponent({
|
|
567
|
+
manifestBytes,
|
|
568
|
+
manifestCatalog: catalog,
|
|
569
|
+
archivePath,
|
|
570
|
+
expectedComponent: expected.component,
|
|
571
|
+
expectedVariant: record.manifest.variant,
|
|
572
|
+
expectedVersion: productVersion,
|
|
573
|
+
target,
|
|
574
|
+
runtime: expected.runtime
|
|
575
|
+
});
|
|
576
|
+
if (archivePath !== resolve2(root, manifest.archive.name))
|
|
577
|
+
throw new Error("stored component archive path is invalid");
|
|
578
|
+
const archiveStat = lstatSync2(archivePath);
|
|
579
|
+
if (!archiveStat.isFile() || archiveStat.isSymbolicLink())
|
|
580
|
+
throw new Error("stored component archive is not a regular file");
|
|
581
|
+
const payload = componentPayloadPath(root);
|
|
582
|
+
assertDirectoryChain(root, payload);
|
|
583
|
+
await verifyExtractedComponent(payload, manifest);
|
|
584
|
+
return {
|
|
585
|
+
kind: "manifest-pinned-component",
|
|
586
|
+
manifest,
|
|
587
|
+
root: payload,
|
|
588
|
+
manifestDigest: record.manifestDigest
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
async function stageComponentInternal(paths, source, context, runtime) {
|
|
592
|
+
aborted(context.signal);
|
|
593
|
+
const storeRoot = resolve2(paths.componentsDir);
|
|
594
|
+
assertInside(paths.koedHome, storeRoot);
|
|
595
|
+
assertDirectoryChain(paths.koedHome, storeRoot);
|
|
596
|
+
ensureSecureDirectory(paths.koedHome, storeRoot);
|
|
597
|
+
const tempRoot = mkdtempSync(resolve2(storeRoot, ".stage-"));
|
|
598
|
+
chmodSync(tempRoot, 448);
|
|
599
|
+
try {
|
|
600
|
+
const catalog = readProductionManifestPinCatalog();
|
|
601
|
+
let manifestBytes;
|
|
602
|
+
if (source.kind === "offline") {
|
|
603
|
+
manifestBytes = readOfflineSource(source).manifestBytes;
|
|
604
|
+
} else {
|
|
605
|
+
manifestBytes = await fetchBounded(source.manifestUrl, resolve2(tempRoot, "manifest.json"), MAX_MANIFEST_BYTES, context.signal, context.progress);
|
|
606
|
+
}
|
|
607
|
+
if (context.target.platform !== runtime.platform || context.target.architecture !== runtime.architecture)
|
|
608
|
+
throw new Error("component target does not match actual runtime");
|
|
609
|
+
const target = resolveComponentManifestPinTarget(catalog, {
|
|
610
|
+
component: context.expectedComponent,
|
|
611
|
+
variant: context.expectedVariant,
|
|
612
|
+
productVersion: context.expectedVersion,
|
|
613
|
+
target: context.target,
|
|
614
|
+
runtime
|
|
615
|
+
});
|
|
616
|
+
const manifest = verifyComponentManifestPin({
|
|
617
|
+
manifestBytes,
|
|
618
|
+
manifestCatalog: catalog,
|
|
619
|
+
expectedComponent: context.expectedComponent,
|
|
620
|
+
expectedVariant: context.expectedVariant,
|
|
621
|
+
expectedVersion: context.expectedVersion,
|
|
622
|
+
target
|
|
623
|
+
});
|
|
624
|
+
const archivePath = resolve2(tempRoot, manifest.archive.name);
|
|
625
|
+
if (source.kind === "offline") {
|
|
626
|
+
copyFileSync(resolve2(source.archivePath), archivePath, 1);
|
|
627
|
+
chmodSync(archivePath, 384);
|
|
628
|
+
} else {
|
|
629
|
+
await fetchBounded(source.archiveUrl, archivePath, MAX_ARCHIVE_BYTES, context.signal, context.progress, false);
|
|
630
|
+
}
|
|
631
|
+
aborted(context.signal);
|
|
632
|
+
context.progress?.({ phase: "verify", transferredBytes: 0 });
|
|
633
|
+
await verifyComponent({
|
|
634
|
+
manifestBytes,
|
|
635
|
+
manifestCatalog: catalog,
|
|
636
|
+
archivePath,
|
|
637
|
+
expectedComponent: context.expectedComponent,
|
|
638
|
+
expectedVariant: context.expectedVariant,
|
|
639
|
+
expectedVersion: context.expectedVersion,
|
|
640
|
+
target,
|
|
641
|
+
runtime
|
|
642
|
+
});
|
|
643
|
+
aborted(context.signal);
|
|
644
|
+
const manifestDigest = hash2(manifestBytes);
|
|
645
|
+
const componentDir = resolve2(storeRoot, manifest.component);
|
|
646
|
+
assertDirectoryChain(paths.koedHome, componentDir);
|
|
647
|
+
const indexPath = resolve2(componentDir, `${targetKey(manifest)}.json`);
|
|
648
|
+
const versionRoot = resolve2(componentDir, manifest.productVersion, manifestDigest);
|
|
649
|
+
const stagedRoot = resolve2(tempRoot, "verified");
|
|
650
|
+
const completeRoot = resolve2(tempRoot, "complete");
|
|
651
|
+
aborted(context.signal);
|
|
652
|
+
context.progress?.({ phase: "extract", transferredBytes: 0 });
|
|
653
|
+
await extractVerifiedPackageArchive(archivePath, stagedRoot);
|
|
654
|
+
aborted(context.signal);
|
|
655
|
+
await verifyExtractedComponent(stagedRoot, manifest);
|
|
656
|
+
aborted(context.signal);
|
|
657
|
+
privateDirectory(completeRoot);
|
|
658
|
+
renameSync(stagedRoot, resolve2(completeRoot, "payload"));
|
|
659
|
+
renameSync(archivePath, resolve2(completeRoot, manifest.archive.name));
|
|
660
|
+
writeFileSync(componentRecordPath(completeRoot), JSON.stringify({
|
|
661
|
+
schemaVersion: 2,
|
|
662
|
+
manifest,
|
|
663
|
+
manifestDigest,
|
|
664
|
+
archivePath: resolve2(versionRoot, manifest.archive.name)
|
|
665
|
+
}), { flag: "wx", mode: 384 });
|
|
666
|
+
return await acquireLock(paths.koedHome, storeRoot, context.signal, async () => {
|
|
667
|
+
ensureSecureDirectory(paths.koedHome, componentDir);
|
|
668
|
+
assertDirectoryChain(paths.koedHome, versionRoot);
|
|
669
|
+
assertDirectoryChain(paths.koedHome, dirname(indexPath));
|
|
670
|
+
if (existsSync(indexPath)) {
|
|
671
|
+
const index = parseJsonFile(indexPath, 4096);
|
|
672
|
+
if (!isPlainRecord(index) || index.manifestDigest !== manifestDigest)
|
|
673
|
+
throw new Error("component version already installed with different digest");
|
|
674
|
+
}
|
|
675
|
+
if (existsSync(versionRoot)) {
|
|
676
|
+
const cached = await verifyStoredComponent(paths.koedHome, versionRoot, {
|
|
677
|
+
component: manifest.component,
|
|
678
|
+
productVersion: manifest.productVersion,
|
|
679
|
+
target: manifest.target,
|
|
680
|
+
runtime
|
|
681
|
+
});
|
|
682
|
+
aborted(context.signal);
|
|
683
|
+
if (cached.manifestDigest !== manifestDigest)
|
|
684
|
+
throw new Error("component version already installed with different digest");
|
|
685
|
+
if (!existsSync(indexPath)) {
|
|
686
|
+
aborted(context.signal);
|
|
687
|
+
assertDirectoryChain(paths.koedHome, dirname(indexPath));
|
|
688
|
+
writeIndex(paths.koedHome, indexPath, manifestDigest, tempRoot, context.signal);
|
|
689
|
+
}
|
|
690
|
+
return cached;
|
|
691
|
+
}
|
|
692
|
+
if (existsSync(indexPath))
|
|
693
|
+
throw new Error("component cache record is missing");
|
|
694
|
+
ensureSecureDirectory(paths.koedHome, dirname(versionRoot));
|
|
695
|
+
let publishedRoot;
|
|
696
|
+
let committed = false;
|
|
697
|
+
try {
|
|
698
|
+
aborted(context.signal);
|
|
699
|
+
assertDirectoryChain(paths.koedHome, dirname(versionRoot));
|
|
700
|
+
renameSync(completeRoot, versionRoot);
|
|
701
|
+
publishedRoot = versionRoot;
|
|
702
|
+
aborted(context.signal);
|
|
703
|
+
assertDirectoryChain(paths.koedHome, dirname(indexPath));
|
|
704
|
+
writeIndex(paths.koedHome, indexPath, manifestDigest, tempRoot, context.signal);
|
|
705
|
+
committed = true;
|
|
706
|
+
return {
|
|
707
|
+
kind: "manifest-pinned-component",
|
|
708
|
+
manifest,
|
|
709
|
+
root: componentPayloadPath(versionRoot),
|
|
710
|
+
manifestDigest
|
|
711
|
+
};
|
|
712
|
+
} finally {
|
|
713
|
+
if (publishedRoot && !committed)
|
|
714
|
+
rmSync3(publishedRoot, { recursive: true, force: true });
|
|
715
|
+
}
|
|
716
|
+
});
|
|
717
|
+
} finally {
|
|
718
|
+
rmSync3(tempRoot, { recursive: true, force: true });
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
async function stageComponent(paths, input, context) {
|
|
722
|
+
const actualRuntime = discoverActualRuntimeIdentity();
|
|
723
|
+
if (!runtimeMatches(context.runtime, actualRuntime))
|
|
724
|
+
throw new Error("caller runtime identity does not match actual runtime");
|
|
725
|
+
return stageComponentInternal(paths, input, context, actualRuntime);
|
|
726
|
+
}
|
|
727
|
+
async function stageGeneration(paths, input) {
|
|
728
|
+
const actualRuntime = discoverActualRuntimeIdentity();
|
|
729
|
+
validateOwner(input.owner);
|
|
730
|
+
const { base, privacy } = input;
|
|
731
|
+
assertDirectoryChain(paths.koedHome, paths.componentsDir);
|
|
732
|
+
assertDirectoryChain(paths.componentsDir, dirname(base.root));
|
|
733
|
+
const baseVerified = await verifyStoredComponent(paths.koedHome, dirname(base.root), {
|
|
734
|
+
component: "base",
|
|
735
|
+
runtime: actualRuntime
|
|
736
|
+
});
|
|
737
|
+
if (baseVerified.manifestDigest !== base.manifestDigest || resolve2(baseVerified.root) !== resolve2(base.root))
|
|
738
|
+
throw new Error("base component is not a verified store entry");
|
|
739
|
+
let privacyVerified;
|
|
740
|
+
if (privacy) {
|
|
741
|
+
assertDirectoryChain(paths.componentsDir, dirname(privacy.root));
|
|
742
|
+
privacyVerified = await verifyStoredComponent(paths.koedHome, dirname(privacy.root), {
|
|
743
|
+
component: "privacy",
|
|
744
|
+
runtime: actualRuntime
|
|
745
|
+
});
|
|
746
|
+
if (privacyVerified.manifestDigest !== privacy.manifestDigest || resolve2(privacyVerified.root) !== resolve2(privacy.root))
|
|
747
|
+
throw new Error("privacy component is not a verified store entry");
|
|
748
|
+
}
|
|
749
|
+
if (privacyVerified && baseVerified.manifest.productVersion !== privacyVerified.manifest.productVersion)
|
|
750
|
+
throw new Error("mixed component versions");
|
|
751
|
+
if (privacyVerified && canonicalArtifactJson(baseVerified.manifest.target) !== canonicalArtifactJson(privacyVerified.manifest.target))
|
|
752
|
+
throw new Error("mixed component targets");
|
|
753
|
+
const identity = {
|
|
754
|
+
schemaVersion: 1,
|
|
755
|
+
productVersion: baseVerified.manifest.productVersion,
|
|
756
|
+
owner: input.owner,
|
|
757
|
+
base: {
|
|
758
|
+
manifestDigest: baseVerified.manifestDigest,
|
|
759
|
+
root: relative2(paths.koedHome, baseVerified.root)
|
|
760
|
+
},
|
|
761
|
+
...privacyVerified ? {
|
|
762
|
+
privacy: {
|
|
763
|
+
manifestDigest: privacyVerified.manifestDigest,
|
|
764
|
+
root: relative2(paths.koedHome, privacyVerified.root)
|
|
765
|
+
}
|
|
766
|
+
} : {}
|
|
767
|
+
};
|
|
768
|
+
const id = hash2(canonicalArtifactJson(identity));
|
|
769
|
+
const generationRoot = resolve2(paths.generationsDir, id);
|
|
770
|
+
assertDirectoryChain(paths.koedHome, generationRoot);
|
|
771
|
+
assertDirectoryChain(paths.koedHome, paths.generationsDir);
|
|
772
|
+
return acquireLock(paths.koedHome, paths.generationsDir, void 0, async () => {
|
|
773
|
+
if (existsSync(generationRoot))
|
|
774
|
+
return readStagedGeneration(paths, id);
|
|
775
|
+
ensureSecureDirectory(paths.koedHome, paths.generationsDir);
|
|
776
|
+
const tempRoot = mkdtempSync(resolve2(paths.generationsDir, ".stage-"));
|
|
777
|
+
chmodSync(tempRoot, 448);
|
|
778
|
+
try {
|
|
779
|
+
const freshBase = await verifyStoredComponent(paths.koedHome, dirname(baseVerified.root), {
|
|
780
|
+
component: "base",
|
|
781
|
+
runtime: actualRuntime
|
|
782
|
+
});
|
|
783
|
+
const freshPrivacy = privacyVerified ? await verifyStoredComponent(paths.koedHome, dirname(privacyVerified.root), {
|
|
784
|
+
component: "privacy",
|
|
785
|
+
runtime: actualRuntime
|
|
786
|
+
}) : void 0;
|
|
787
|
+
const record = {
|
|
788
|
+
...identity,
|
|
789
|
+
id,
|
|
790
|
+
components: {
|
|
791
|
+
base: {
|
|
792
|
+
manifest: freshBase.manifest,
|
|
793
|
+
manifestDigest: freshBase.manifestDigest
|
|
794
|
+
},
|
|
795
|
+
...privacyVerified ? {
|
|
796
|
+
privacy: {
|
|
797
|
+
manifest: freshPrivacy.manifest,
|
|
798
|
+
manifestDigest: freshPrivacy.manifestDigest
|
|
799
|
+
}
|
|
800
|
+
} : {}
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
const recordBytes = Buffer.from(canonicalArtifactJson(record));
|
|
804
|
+
if (recordBytes.length > MAX_GENERATION_RECORD_BYTES)
|
|
805
|
+
throw new Error("generation record exceeds size limit");
|
|
806
|
+
writeFileSync(resolve2(tempRoot, "generation.json"), recordBytes, {
|
|
807
|
+
flag: "wx",
|
|
808
|
+
mode: 384
|
|
809
|
+
});
|
|
810
|
+
assertDirectoryChain(paths.koedHome, paths.generationsDir);
|
|
811
|
+
assertDirectoryChain(paths.generationsDir, generationRoot);
|
|
812
|
+
renameSync(tempRoot, generationRoot);
|
|
813
|
+
return {
|
|
814
|
+
id,
|
|
815
|
+
productVersion: identity.productVersion,
|
|
816
|
+
base: baseVerified,
|
|
817
|
+
...privacyVerified ? { privacy: privacyVerified } : {},
|
|
818
|
+
owner: input.owner
|
|
819
|
+
};
|
|
820
|
+
} finally {
|
|
821
|
+
if (existsSync(tempRoot))
|
|
822
|
+
rmSync3(tempRoot, { recursive: true, force: true });
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
async function readStoredComponents(paths, runtime) {
|
|
827
|
+
const components = [];
|
|
828
|
+
for (const component of ["base", "privacy"]) {
|
|
829
|
+
const componentRoot = resolve2(paths.componentsDir, component);
|
|
830
|
+
if (!existsSync(componentRoot))
|
|
831
|
+
continue;
|
|
832
|
+
assertDirectoryChain(paths.koedHome, componentRoot);
|
|
833
|
+
for (const versionEntry of readdirSync2(componentRoot, {
|
|
834
|
+
withFileTypes: true
|
|
835
|
+
})) {
|
|
836
|
+
if (!versionEntry.isDirectory() || !/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*))?(?:-[0-9A-Za-z.-]+)?$/.test(versionEntry.name))
|
|
837
|
+
continue;
|
|
838
|
+
const versionRoot = resolve2(componentRoot, versionEntry.name);
|
|
839
|
+
for (const digestEntry of readdirSync2(versionRoot, {
|
|
840
|
+
withFileTypes: true
|
|
841
|
+
})) {
|
|
842
|
+
if (!digestEntry.isDirectory() || !/^[a-f0-9]{64}$/.test(digestEntry.name))
|
|
843
|
+
continue;
|
|
844
|
+
try {
|
|
845
|
+
components.push(await verifyStoredComponent(paths.koedHome, resolve2(versionRoot, digestEntry.name), {
|
|
846
|
+
component,
|
|
847
|
+
productVersion: versionEntry.name,
|
|
848
|
+
runtime
|
|
849
|
+
}));
|
|
850
|
+
} catch (error) {
|
|
851
|
+
if (error instanceof Error && error.message.startsWith("Stored component predates manifest pin admission;"))
|
|
852
|
+
throw error;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
return components;
|
|
858
|
+
}
|
|
859
|
+
var readDesktopPrivacyGeneration = async (paths, id, record) => {
|
|
860
|
+
if (!exactKeys(record, [
|
|
861
|
+
"schemaVersion",
|
|
862
|
+
"kind",
|
|
863
|
+
"id",
|
|
864
|
+
"productVersion",
|
|
865
|
+
"owner",
|
|
866
|
+
"resourcesPath",
|
|
867
|
+
"bundleDigest",
|
|
868
|
+
"privacy"
|
|
869
|
+
]) || record.schemaVersion !== 1 || record.kind !== "desktop-bundle-with-privacy" || record.id !== id || typeof record.productVersion !== "string" || typeof record.resourcesPath !== "string" || typeof record.bundleDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.bundleDigest) || !isPlainRecord(record.privacy) || !exactKeys(record.privacy, ["root", "manifestDigest"]) || typeof record.privacy.root !== "string" || typeof record.privacy.manifestDigest !== "string")
|
|
870
|
+
throw new Error("stored Desktop privacy generation record is invalid");
|
|
871
|
+
validateOwner(record.owner);
|
|
872
|
+
const bundle = verifyDesktopRuntimeBundle(record.resourcesPath);
|
|
873
|
+
if (bundle.productVersion !== record.productVersion || bundle.bundleDigest !== record.bundleDigest)
|
|
874
|
+
throw new Error("Desktop runtime bundle changed after generation staging");
|
|
875
|
+
const runtime = discoverActualRuntimeIdentity();
|
|
876
|
+
const privacyRoot = resolve2(paths.koedHome, record.privacy.root);
|
|
877
|
+
assertInside(paths.koedHome, privacyRoot);
|
|
878
|
+
const privacy = await verifyStoredComponent(paths.koedHome, dirname(privacyRoot), {
|
|
879
|
+
component: "privacy",
|
|
880
|
+
productVersion: bundle.productVersion,
|
|
881
|
+
target: bundle.target,
|
|
882
|
+
runtime
|
|
883
|
+
});
|
|
884
|
+
if (privacy.root !== privacyRoot || privacy.manifestDigest !== record.privacy.manifestDigest)
|
|
885
|
+
throw new Error("Desktop privacy generation differs from verified component");
|
|
886
|
+
const identity = {
|
|
887
|
+
schemaVersion: 1,
|
|
888
|
+
kind: "desktop-bundle-with-privacy",
|
|
889
|
+
productVersion: bundle.productVersion,
|
|
890
|
+
owner: record.owner,
|
|
891
|
+
resourcesPath: bundle.resourcesPath,
|
|
892
|
+
bundleDigest: bundle.bundleDigest,
|
|
893
|
+
privacy: {
|
|
894
|
+
root: relative2(paths.koedHome, privacy.root),
|
|
895
|
+
manifestDigest: privacy.manifestDigest
|
|
896
|
+
}
|
|
897
|
+
};
|
|
898
|
+
if (hash2(canonicalArtifactJson(identity)) !== id)
|
|
899
|
+
throw new Error("Desktop privacy generation digest mismatch");
|
|
900
|
+
return {
|
|
901
|
+
id,
|
|
902
|
+
productVersion: bundle.productVersion,
|
|
903
|
+
base: {
|
|
904
|
+
kind: "desktop-bundle",
|
|
905
|
+
manifest: bundle.manifest,
|
|
906
|
+
root: resolve2(bundle.resourcesPath, "koed-runtime"),
|
|
907
|
+
manifestDigest: bundle.bundleDigest
|
|
908
|
+
},
|
|
909
|
+
privacy,
|
|
910
|
+
owner: record.owner
|
|
911
|
+
};
|
|
912
|
+
};
|
|
913
|
+
function readGenerationRecord(paths, id) {
|
|
914
|
+
if (!/^[a-f0-9]{64}$/.test(id))
|
|
915
|
+
throw new Error("generation id is invalid");
|
|
916
|
+
assertDirectoryChain(paths.koedHome, paths.generationsDir);
|
|
917
|
+
const root = resolve2(paths.generationsDir, id);
|
|
918
|
+
assertDirectoryChain(paths.generationsDir, root);
|
|
919
|
+
return parseJsonFile(resolve2(root, "generation.json"), MAX_GENERATION_RECORD_BYTES, true);
|
|
920
|
+
}
|
|
921
|
+
function assertOrderingStoreMetadata(root, manifest, digest) {
|
|
922
|
+
const stored = readComponentRecord(componentRecordPath(root));
|
|
923
|
+
if (stored.manifestDigest !== digest || canonicalArtifactJson(stored.manifest) !== canonicalArtifactJson(manifest) || stored.archivePath !== resolve2(root, manifest.archive.name))
|
|
924
|
+
throw new Error("generation component metadata differs from store");
|
|
925
|
+
}
|
|
926
|
+
function readOrderingComponent(paths, component, version, reference, embedded) {
|
|
927
|
+
if (!isPlainRecord(reference) || !exactKeys(reference, ["root", "manifestDigest"]) || typeof reference.root !== "string" || !isPlainRecord(embedded) || !exactKeys(embedded, ["manifest", "manifestDigest"]))
|
|
928
|
+
throw new Error("stored generation component reference is invalid");
|
|
929
|
+
validateComponentManifest(embedded.manifest);
|
|
930
|
+
const manifest = embedded.manifest;
|
|
931
|
+
const digest = hash2(canonicalArtifactJson(manifest));
|
|
932
|
+
if (manifest.component !== component || manifest.productVersion !== version || reference.manifestDigest !== digest || embedded.manifestDigest !== digest)
|
|
933
|
+
throw new Error("generation component identity mismatch");
|
|
934
|
+
const componentRoot = resolve2(paths.componentsDir, component, version, digest);
|
|
935
|
+
const payload = componentPayloadPath(componentRoot);
|
|
936
|
+
assertInside(paths.koedHome, componentRoot);
|
|
937
|
+
if (reference.root !== relative2(paths.koedHome, payload))
|
|
938
|
+
throw new Error("stored generation root is invalid");
|
|
939
|
+
assertDirectoryChain(paths.koedHome, payload);
|
|
940
|
+
assertOrderingStoreMetadata(componentRoot, manifest, digest);
|
|
941
|
+
return manifest;
|
|
942
|
+
}
|
|
943
|
+
function parseOrderingRecord(record, id) {
|
|
944
|
+
if (!isPlainRecord(record) || !exactKeys(record, [
|
|
945
|
+
"schemaVersion",
|
|
946
|
+
"productVersion",
|
|
947
|
+
"owner",
|
|
948
|
+
"base",
|
|
949
|
+
"components",
|
|
950
|
+
"id",
|
|
951
|
+
...Object.hasOwn(record, "privacy") ? ["privacy"] : []
|
|
952
|
+
]) || record.schemaVersion !== 1 || record.id !== id || typeof record.productVersion !== "string" || !isPlainRecord(record.components) || !exactKeys(record.components, [
|
|
953
|
+
"base",
|
|
954
|
+
...Object.hasOwn(record, "privacy") ? ["privacy"] : []
|
|
955
|
+
]))
|
|
956
|
+
throw new Error("stored generation record is invalid");
|
|
957
|
+
validateOwner(record.owner);
|
|
958
|
+
return {
|
|
959
|
+
...record,
|
|
960
|
+
productVersion: record.productVersion,
|
|
961
|
+
owner: record.owner,
|
|
962
|
+
components: record.components
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
function readConsistentOrderingRecord(paths, id) {
|
|
966
|
+
const record = parseOrderingRecord(readGenerationRecord(paths, id), id);
|
|
967
|
+
const base = readOrderingComponent(paths, "base", record.productVersion, record.base, record.components.base);
|
|
968
|
+
if (Object.hasOwn(record, "privacy")) {
|
|
969
|
+
const privacy = readOrderingComponent(paths, "privacy", record.productVersion, record.privacy, record.components.privacy);
|
|
970
|
+
if (canonicalArtifactJson(privacy.target) !== canonicalArtifactJson(base.target))
|
|
971
|
+
throw new Error("generation component target mismatch");
|
|
972
|
+
}
|
|
973
|
+
const identity = {
|
|
974
|
+
schemaVersion: 1,
|
|
975
|
+
productVersion: record.productVersion,
|
|
976
|
+
owner: record.owner,
|
|
977
|
+
base: record.base,
|
|
978
|
+
...Object.hasOwn(record, "privacy") ? { privacy: record.privacy } : {}
|
|
979
|
+
};
|
|
980
|
+
if (hash2(canonicalArtifactJson(identity)) !== id)
|
|
981
|
+
throw new Error("generation digest mismatch");
|
|
982
|
+
return record;
|
|
983
|
+
}
|
|
984
|
+
function readGenerationComponentPresence(paths, id) {
|
|
985
|
+
const record = readConsistentOrderingRecord(paths, id);
|
|
986
|
+
return Object.freeze(Object.hasOwn(record, "privacy") ? ["base", "privacy"] : ["base"]);
|
|
987
|
+
}
|
|
988
|
+
function readGenerationOrderingEvidence(paths, id) {
|
|
989
|
+
const record = readConsistentOrderingRecord(paths, id);
|
|
990
|
+
return Object.freeze({
|
|
991
|
+
kind: "generation-ordering-evidence",
|
|
992
|
+
id,
|
|
993
|
+
productVersion: record.productVersion,
|
|
994
|
+
owner: Object.freeze({ ...record.owner })
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
async function readStagedGeneration(paths, id) {
|
|
998
|
+
const record = readGenerationRecord(paths, id);
|
|
999
|
+
if (isPlainRecord(record) && record.kind === "desktop-bundle-with-privacy")
|
|
1000
|
+
return readDesktopPrivacyGeneration(paths, id, record);
|
|
1001
|
+
if (!isPlainRecord(record) || !exactKeys(record, [
|
|
1002
|
+
"schemaVersion",
|
|
1003
|
+
"productVersion",
|
|
1004
|
+
"owner",
|
|
1005
|
+
"base",
|
|
1006
|
+
"components",
|
|
1007
|
+
"id",
|
|
1008
|
+
...Object.hasOwn(record, "privacy") ? ["privacy"] : []
|
|
1009
|
+
]) || record.schemaVersion !== 1 || record.id !== id || typeof record.productVersion !== "string" || !isPlainRecord(record.base) || !exactKeys(record.base, ["manifestDigest", "root"]) || !isPlainRecord(record.components) || Object.hasOwn(record, "privacy") !== Object.hasOwn(record.components, "privacy") || !exactKeys(record.components, [
|
|
1010
|
+
"base",
|
|
1011
|
+
...Object.hasOwn(record.components, "privacy") ? ["privacy"] : []
|
|
1012
|
+
]) || Object.hasOwn(record, "privacy") && !isPlainRecord(record.privacy))
|
|
1013
|
+
throw new Error("stored generation record is invalid");
|
|
1014
|
+
validateOwner(record.owner);
|
|
1015
|
+
const runtime = discoverActualRuntimeIdentity();
|
|
1016
|
+
const baseRelative = record.base.root;
|
|
1017
|
+
if (typeof baseRelative !== "string")
|
|
1018
|
+
throw new Error("stored generation root is invalid");
|
|
1019
|
+
const baseRoot = resolve2(paths.koedHome, baseRelative);
|
|
1020
|
+
assertInside(paths.koedHome, baseRoot);
|
|
1021
|
+
const base = await verifyStoredComponent(paths.koedHome, dirname(baseRoot), {
|
|
1022
|
+
component: "base",
|
|
1023
|
+
runtime
|
|
1024
|
+
});
|
|
1025
|
+
if (base.root !== baseRoot || base.manifestDigest !== record.base.manifestDigest || !isPlainRecord(record.components.base) || !exactKeys(record.components.base, ["manifest", "manifestDigest"]) || record.components.base.manifestDigest !== base.manifestDigest || canonicalArtifactJson(record.components.base.manifest) !== canonicalArtifactJson(base.manifest))
|
|
1026
|
+
throw new Error("generation base reference differs from verified component");
|
|
1027
|
+
let privacy;
|
|
1028
|
+
if (Object.hasOwn(record, "privacy")) {
|
|
1029
|
+
const reference = record.privacy;
|
|
1030
|
+
if (!isPlainRecord(reference) || !exactKeys(reference, ["manifestDigest", "root"]) || typeof reference.root !== "string")
|
|
1031
|
+
throw new Error("stored generation privacy reference is invalid");
|
|
1032
|
+
const privacyRoot = resolve2(paths.koedHome, reference.root);
|
|
1033
|
+
assertInside(paths.koedHome, privacyRoot);
|
|
1034
|
+
privacy = await verifyStoredComponent(paths.koedHome, dirname(privacyRoot), {
|
|
1035
|
+
component: "privacy",
|
|
1036
|
+
runtime
|
|
1037
|
+
});
|
|
1038
|
+
if (privacy.root !== privacyRoot || privacy.manifestDigest !== reference.manifestDigest || !isPlainRecord(record.components.privacy) || !exactKeys(record.components.privacy, ["manifest", "manifestDigest"]) || record.components.privacy.manifestDigest !== privacy.manifestDigest || canonicalArtifactJson(record.components.privacy.manifest) !== canonicalArtifactJson(privacy.manifest) || privacy.manifest.productVersion !== base.manifest.productVersion || canonicalArtifactJson(privacy.manifest.target) !== canonicalArtifactJson(base.manifest.target))
|
|
1039
|
+
throw new Error("generation privacy reference differs from verified component");
|
|
1040
|
+
}
|
|
1041
|
+
if (record.productVersion !== base.manifest.productVersion)
|
|
1042
|
+
throw new Error("generation product version differs from verified component");
|
|
1043
|
+
const identity = {
|
|
1044
|
+
schemaVersion: 1,
|
|
1045
|
+
productVersion: base.manifest.productVersion,
|
|
1046
|
+
owner: record.owner,
|
|
1047
|
+
base: {
|
|
1048
|
+
manifestDigest: base.manifestDigest,
|
|
1049
|
+
root: relative2(paths.koedHome, base.root)
|
|
1050
|
+
},
|
|
1051
|
+
...privacy ? {
|
|
1052
|
+
privacy: {
|
|
1053
|
+
manifestDigest: privacy.manifestDigest,
|
|
1054
|
+
root: relative2(paths.koedHome, privacy.root)
|
|
1055
|
+
}
|
|
1056
|
+
} : {}
|
|
1057
|
+
};
|
|
1058
|
+
if (hash2(canonicalArtifactJson(identity)) !== id)
|
|
1059
|
+
throw new Error("generation digest mismatch");
|
|
1060
|
+
return {
|
|
1061
|
+
id,
|
|
1062
|
+
productVersion: base.manifest.productVersion,
|
|
1063
|
+
base,
|
|
1064
|
+
...privacy ? { privacy } : {},
|
|
1065
|
+
owner: record.owner
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// packages/koed-server/dist/supervisor-lock.js
|
|
1070
|
+
import { closeSync as closeSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync3, rmSync as rmSync4, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1071
|
+
import { spawnSync } from "node:child_process";
|
|
1072
|
+
import { hostname } from "node:os";
|
|
1073
|
+
import { resolve as resolve3 } from "node:path";
|
|
1074
|
+
var processIsRunning = (pid) => {
|
|
1075
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
1076
|
+
return false;
|
|
1077
|
+
try {
|
|
1078
|
+
process.kill(pid, 0);
|
|
1079
|
+
return true;
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
const code = error.code;
|
|
1082
|
+
return code !== "ESRCH";
|
|
1083
|
+
}
|
|
1084
|
+
};
|
|
1085
|
+
var resolveProcessIdentity = (pid) => {
|
|
1086
|
+
if (!processIsRunning(pid))
|
|
1087
|
+
return null;
|
|
1088
|
+
try {
|
|
1089
|
+
if (process.platform === "linux") {
|
|
1090
|
+
const stat = readFileSync3(`/proc/${pid}/stat`, "utf8");
|
|
1091
|
+
const commandEnd = stat.lastIndexOf(")");
|
|
1092
|
+
if (commandEnd < 0)
|
|
1093
|
+
return null;
|
|
1094
|
+
const fields = stat.slice(commandEnd + 2).trim().split(/\s+/);
|
|
1095
|
+
const startTime = fields[19];
|
|
1096
|
+
if (!startTime)
|
|
1097
|
+
return null;
|
|
1098
|
+
const bootId = readFileSync3("/proc/sys/kernel/random/boot_id", "utf8").trim();
|
|
1099
|
+
return `${hostname()}:linux:${bootId}:${startTime}`;
|
|
1100
|
+
}
|
|
1101
|
+
if (process.platform === "win32") {
|
|
1102
|
+
const result2 = spawnSync("powershell.exe", [
|
|
1103
|
+
"-NoProfile",
|
|
1104
|
+
"-NonInteractive",
|
|
1105
|
+
"-Command",
|
|
1106
|
+
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`
|
|
1107
|
+
], { encoding: "utf8", windowsHide: true, timeout: 2e3 });
|
|
1108
|
+
const startedAt2 = result2.status === 0 ? result2.stdout.trim() : "";
|
|
1109
|
+
return startedAt2 ? `${hostname()}:win32:${startedAt2}` : null;
|
|
1110
|
+
}
|
|
1111
|
+
const result = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
1112
|
+
encoding: "utf8",
|
|
1113
|
+
timeout: 2e3
|
|
1114
|
+
});
|
|
1115
|
+
const startedAt = result.status === 0 ? result.stdout.trim() : "";
|
|
1116
|
+
return startedAt ? `${hostname()}:${process.platform}:${startedAt}` : null;
|
|
1117
|
+
} catch {
|
|
1118
|
+
return null;
|
|
1119
|
+
}
|
|
1120
|
+
};
|
|
1121
|
+
var readLockText = (lockPath2) => {
|
|
1122
|
+
try {
|
|
1123
|
+
return readFileSync3(lockPath2, "utf8");
|
|
1124
|
+
} catch {
|
|
1125
|
+
return null;
|
|
1126
|
+
}
|
|
1127
|
+
};
|
|
1128
|
+
var readSupervisorLock = (lockPath2) => {
|
|
1129
|
+
const text = readLockText(lockPath2);
|
|
1130
|
+
return text === null ? null : parseSupervisorLock(text);
|
|
1131
|
+
};
|
|
1132
|
+
var parseSupervisorLock = (text) => {
|
|
1133
|
+
try {
|
|
1134
|
+
const value = JSON.parse(text);
|
|
1135
|
+
return Number.isInteger(value.pid) && Number(value.pid) > 0 ? {
|
|
1136
|
+
pid: Number(value.pid),
|
|
1137
|
+
acquiredAt: String(value.acquiredAt ?? "unknown"),
|
|
1138
|
+
...typeof value.processIdentity === "string" && value.processIdentity.length > 0 ? { processIdentity: value.processIdentity } : {}
|
|
1139
|
+
} : null;
|
|
1140
|
+
} catch {
|
|
1141
|
+
return null;
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
var acquireKoedServerSupervisorLock = (paths, options = {}) => {
|
|
1145
|
+
const pid = options.pid ?? process.pid;
|
|
1146
|
+
const exclusive = options.exclusive ?? ((action) => action());
|
|
1147
|
+
const isRunning = options.isProcessRunning ?? processIsRunning;
|
|
1148
|
+
const identify = options.resolveProcessIdentity ?? resolveProcessIdentity;
|
|
1149
|
+
const processIdentity = identify(pid);
|
|
1150
|
+
if (!processIdentity) {
|
|
1151
|
+
throw new Error(`Could not resolve process identity for PID ${pid}.`);
|
|
1152
|
+
}
|
|
1153
|
+
const lockPath2 = resolve3(paths.runDir, "koed-server.lock");
|
|
1154
|
+
mkdirSync3(paths.runDir, { recursive: true, mode: 448 });
|
|
1155
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1156
|
+
try {
|
|
1157
|
+
const descriptor = openSync3(lockPath2, "wx", 384);
|
|
1158
|
+
try {
|
|
1159
|
+
writeFileSync2(descriptor, `${JSON.stringify({
|
|
1160
|
+
pid,
|
|
1161
|
+
acquiredAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
|
|
1162
|
+
processIdentity
|
|
1163
|
+
}, null, 2)}
|
|
1164
|
+
`);
|
|
1165
|
+
} finally {
|
|
1166
|
+
closeSync3(descriptor);
|
|
1167
|
+
}
|
|
1168
|
+
return { acquired: true, lockPath: lockPath2, ownerPid: pid, processIdentity };
|
|
1169
|
+
} catch (error) {
|
|
1170
|
+
if (error.code !== "EEXIST")
|
|
1171
|
+
throw error;
|
|
1172
|
+
const observed = readLockText(lockPath2);
|
|
1173
|
+
const owner2 = observed === null ? null : parseSupervisorLock(observed);
|
|
1174
|
+
if (!owner2)
|
|
1175
|
+
return { acquired: false, lockPath: lockPath2 };
|
|
1176
|
+
if (isRunning(owner2.pid)) {
|
|
1177
|
+
const ownerIdentity = identify(owner2.pid);
|
|
1178
|
+
if (!ownerIdentity && isRunning(owner2.pid)) {
|
|
1179
|
+
return { acquired: false, lockPath: lockPath2, ownerPid: owner2.pid };
|
|
1180
|
+
}
|
|
1181
|
+
if (ownerIdentity) {
|
|
1182
|
+
if (!owner2.processIdentity && owner2.pid !== pid) {
|
|
1183
|
+
return { acquired: false, lockPath: lockPath2, ownerPid: owner2.pid };
|
|
1184
|
+
}
|
|
1185
|
+
if (owner2.processIdentity && ownerIdentity === owner2.processIdentity) {
|
|
1186
|
+
return { acquired: false, lockPath: lockPath2, ownerPid: owner2.pid };
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
exclusive(() => {
|
|
1191
|
+
if (readLockText(lockPath2) === observed)
|
|
1192
|
+
rmSync4(lockPath2, { force: true });
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
const owner = readSupervisorLock(lockPath2);
|
|
1197
|
+
return {
|
|
1198
|
+
acquired: false,
|
|
1199
|
+
lockPath: lockPath2,
|
|
1200
|
+
...owner ? { ownerPid: owner.pid } : {}
|
|
1201
|
+
};
|
|
1202
|
+
};
|
|
1203
|
+
var releaseKoedServerSupervisorLock = (lock, pid = process.pid) => {
|
|
1204
|
+
const owner = readSupervisorLock(lock.lockPath);
|
|
1205
|
+
if (!lock.acquired || owner?.pid !== pid || !lock.processIdentity || owner.processIdentity !== lock.processIdentity)
|
|
1206
|
+
return false;
|
|
1207
|
+
rmSync4(lock.lockPath, { force: true });
|
|
1208
|
+
return true;
|
|
1209
|
+
};
|
|
1210
|
+
|
|
1211
|
+
// packages/koed-server/dist/generation-lifecycle-filesystem.js
|
|
1212
|
+
import { renameSync as renameSync2 } from "node:fs";
|
|
1213
|
+
var renameAtomically = (source, destination) => renameSync2(source, destination);
|
|
1214
|
+
|
|
1215
|
+
// packages/koed-server/dist/stopped-runtime.js
|
|
1216
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
1217
|
+
import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync2, openSync as openSync4, readFileSync as readFileSync4, rmSync as rmSync5 } from "node:fs";
|
|
1218
|
+
import { resolve as resolve4 } from "node:path";
|
|
1219
|
+
var processState = (pid) => {
|
|
1220
|
+
try {
|
|
1221
|
+
process.kill(pid, 0);
|
|
1222
|
+
return "running";
|
|
1223
|
+
} catch (error) {
|
|
1224
|
+
return error.code === "ESRCH" ? "stopped" : "uncertain";
|
|
1225
|
+
}
|
|
1226
|
+
};
|
|
1227
|
+
var processSnapshot = () => {
|
|
1228
|
+
const result = spawnSync2("ps", ["-axww", "-o", "pid=,command="], {
|
|
1229
|
+
encoding: "utf8",
|
|
1230
|
+
timeout: 2e3,
|
|
1231
|
+
maxBuffer: 4 * 1024 * 1024
|
|
1232
|
+
});
|
|
1233
|
+
if (result.error || result.status !== 0 || !result.stdout.trim())
|
|
1234
|
+
throw new Error("Native process discovery failed.");
|
|
1235
|
+
return result.stdout.trim().split("\n").map((line) => {
|
|
1236
|
+
const match = line.trim().match(/^(\d+)\s+(.+)$/);
|
|
1237
|
+
if (!match)
|
|
1238
|
+
throw new Error("Native process discovery was incomplete.");
|
|
1239
|
+
return { pid: Number(match[1]), command: match[2] };
|
|
1240
|
+
});
|
|
1241
|
+
};
|
|
1242
|
+
var readState = (path) => {
|
|
1243
|
+
let descriptor;
|
|
1244
|
+
try {
|
|
1245
|
+
descriptor = openSync4(path, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
if (error.code === "ENOENT")
|
|
1248
|
+
return null;
|
|
1249
|
+
throw error;
|
|
1250
|
+
}
|
|
1251
|
+
try {
|
|
1252
|
+
const stat = fstatSync2(descriptor);
|
|
1253
|
+
if (!stat.isFile() || stat.size > 1024 * 1024)
|
|
1254
|
+
throw new Error("Runtime state is not a bounded regular file.");
|
|
1255
|
+
return readFileSync4(descriptor, "utf8");
|
|
1256
|
+
} finally {
|
|
1257
|
+
closeSync4(descriptor);
|
|
1258
|
+
}
|
|
1259
|
+
};
|
|
1260
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1261
|
+
var isPid = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
1262
|
+
function observeStoppedRuntime(paths, dependencies = {}) {
|
|
1263
|
+
const stateOf = dependencies.processState ?? processState;
|
|
1264
|
+
const identify = dependencies.processIdentity ?? resolveProcessIdentity;
|
|
1265
|
+
const uncertain = (message) => ({
|
|
1266
|
+
state: "uncertain",
|
|
1267
|
+
message
|
|
1268
|
+
});
|
|
1269
|
+
const staleRecords = [];
|
|
1270
|
+
try {
|
|
1271
|
+
for (const name of ["koed-server.lock", "runtime-generation.json"]) {
|
|
1272
|
+
const path = name === "runtime-generation.json" ? paths.generationStatePath ?? resolve4(paths.runDir, name) : resolve4(paths.runDir, name);
|
|
1273
|
+
const contents = readState(path);
|
|
1274
|
+
if (contents === null)
|
|
1275
|
+
continue;
|
|
1276
|
+
const value = JSON.parse(contents);
|
|
1277
|
+
if (!isRecord(value) || !isPid(value.pid) || typeof value.processIdentity !== "string" || name === "runtime-generation.json" && !isRuntimeGenerationState(value))
|
|
1278
|
+
return uncertain(`${name} is unreadable or lacks process identity.`);
|
|
1279
|
+
const identity = identify(value.pid);
|
|
1280
|
+
if (identity && identity === value.processIdentity)
|
|
1281
|
+
return {
|
|
1282
|
+
state: "running",
|
|
1283
|
+
pid: value.pid,
|
|
1284
|
+
message: "Koed is running or pinned."
|
|
1285
|
+
};
|
|
1286
|
+
if (stateOf(value.pid) === "stopped") {
|
|
1287
|
+
staleRecords.push({ path, contents });
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
return uncertain(`${name} is stale or its process identity is uncertain. Operator recovery is required.`);
|
|
1291
|
+
}
|
|
1292
|
+
const runtime = readState(paths.runtimeStatePath);
|
|
1293
|
+
if (runtime !== null) {
|
|
1294
|
+
const value = JSON.parse(runtime);
|
|
1295
|
+
if (!isRecord(value) || !isPid(value.pid) || value.processes !== void 0 && !isRecord(value.processes))
|
|
1296
|
+
return uncertain("Koed runtime process state is unreadable.");
|
|
1297
|
+
const pids = [
|
|
1298
|
+
value.pid,
|
|
1299
|
+
...Object.values(value.processes ?? {})
|
|
1300
|
+
];
|
|
1301
|
+
for (const pid of pids) {
|
|
1302
|
+
if (pid === 0)
|
|
1303
|
+
continue;
|
|
1304
|
+
if (!isPid(pid))
|
|
1305
|
+
return uncertain("Koed runtime contains an invalid process ID.");
|
|
1306
|
+
if (stateOf(pid) !== "stopped")
|
|
1307
|
+
return {
|
|
1308
|
+
state: "uncertain",
|
|
1309
|
+
pid,
|
|
1310
|
+
message: "A recorded Koed process is live or its identity is uncertain."
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
const postmaster = readState(resolve4(paths.postgresDataDir, "postmaster.pid"));
|
|
1315
|
+
if (postmaster !== null) {
|
|
1316
|
+
const line = postmaster.split("\n")[0];
|
|
1317
|
+
if (!/^-?[1-9]\d*$/.test(line) || !isPid(Math.abs(Number(line))))
|
|
1318
|
+
return uncertain("Postgres process state is unreadable.");
|
|
1319
|
+
const pid = Math.abs(Number(line));
|
|
1320
|
+
return {
|
|
1321
|
+
state: "uncertain",
|
|
1322
|
+
pid,
|
|
1323
|
+
message: "Postgres retains a process lock. Stop Postgres or complete Operator recovery before changing its runtime."
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
const roots = [resolve4(paths.koedHome, "runtime"), paths.postgresDataDir];
|
|
1327
|
+
const patterns = roots.map((root) => new RegExp(`(?:^|[\\s"'])${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[/\\s"']|$)`));
|
|
1328
|
+
const native = (dependencies.processes ?? processSnapshot)().find(({ pid, command }) => pid !== process.pid && patterns.some((pattern) => pattern.test(command)));
|
|
1329
|
+
if (native)
|
|
1330
|
+
return {
|
|
1331
|
+
state: "uncertain",
|
|
1332
|
+
pid: native.pid,
|
|
1333
|
+
message: "A process still references this native runtime or Postgres data directory."
|
|
1334
|
+
};
|
|
1335
|
+
return {
|
|
1336
|
+
state: "stopped",
|
|
1337
|
+
message: "Koed and its recorded native processes are stopped.",
|
|
1338
|
+
...staleRecords.length > 0 ? { staleRecords } : {}
|
|
1339
|
+
};
|
|
1340
|
+
} catch {
|
|
1341
|
+
return uncertain("Stopped runtime state could not be established. Inspect process state and runtime files before retrying.");
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
function removeStaleRuntimeRecords(observation) {
|
|
1345
|
+
if (observation.state !== "stopped")
|
|
1346
|
+
return;
|
|
1347
|
+
for (const record of observation.staleRecords ?? [])
|
|
1348
|
+
if (readState(record.path) === record.contents)
|
|
1349
|
+
rmSync5(record.path, { force: true });
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// packages/koed-server/dist/generation-lifecycle.js
|
|
1353
|
+
var generationStatePath = (paths) => paths.generationStatePath ?? resolve5(paths.runDir, "runtime-generation.json");
|
|
1354
|
+
var lockPath = (paths) => resolve5(paths.runDir, "generation-lifecycle.lock");
|
|
1355
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1356
|
+
var isRuntimeOwnerRecord = (value) => isRecord2(value) && Object.keys(value).length === 2 && ["cli", "desktop", "standalone"].includes(String(value.kind)) && typeof value.installationId === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value.installationId);
|
|
1357
|
+
var readRegularFile = (path) => {
|
|
1358
|
+
const stat = lstatSync3(path);
|
|
1359
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
1360
|
+
throw new Error("runtime lifecycle state is not a regular file");
|
|
1361
|
+
return readFileSync5(path, "utf8");
|
|
1362
|
+
};
|
|
1363
|
+
var sameOwner = (left, right) => left.kind === right.kind && left.installationId === right.installationId;
|
|
1364
|
+
var assertDirectoryChain2 = (base, target) => {
|
|
1365
|
+
const relativePath = relative3(resolve5(base), resolve5(target));
|
|
1366
|
+
if (relativePath.startsWith("..") || isAbsolute3(relativePath))
|
|
1367
|
+
throw new Error("runtime lifecycle path escaped KOED_HOME");
|
|
1368
|
+
const absolute = resolve5(target);
|
|
1369
|
+
let cursor = parse2(absolute).root;
|
|
1370
|
+
for (const part of absolute.slice(cursor.length).split(sep3).filter(Boolean)) {
|
|
1371
|
+
cursor = resolve5(cursor, part);
|
|
1372
|
+
try {
|
|
1373
|
+
const stat = lstatSync3(cursor);
|
|
1374
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
1375
|
+
throw new Error("runtime lifecycle path contains a symbolic link or non-directory");
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
if (error.code === "ENOENT")
|
|
1378
|
+
return;
|
|
1379
|
+
throw error;
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
var processIsRunning2 = (pid) => {
|
|
1384
|
+
try {
|
|
1385
|
+
process.kill(pid, 0);
|
|
1386
|
+
return true;
|
|
1387
|
+
} catch (error) {
|
|
1388
|
+
return error.code !== "ESRCH";
|
|
1389
|
+
}
|
|
1390
|
+
};
|
|
1391
|
+
var readLockRecord = (path) => {
|
|
1392
|
+
try {
|
|
1393
|
+
const parsed = JSON.parse(readRegularFile(resolve5(path, "owner.json")));
|
|
1394
|
+
if (!isRecord2(parsed))
|
|
1395
|
+
return null;
|
|
1396
|
+
const record = parsed;
|
|
1397
|
+
if (Object.keys(record).length !== 3 || typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0 || typeof record.processIdentity !== "string" || record.processIdentity.length === 0 || typeof record.token !== "string" || !/^[a-f0-9]{64}$/.test(record.token))
|
|
1398
|
+
return null;
|
|
1399
|
+
return {
|
|
1400
|
+
pid: Number(record.pid),
|
|
1401
|
+
processIdentity: record.processIdentity,
|
|
1402
|
+
token: record.token
|
|
1403
|
+
};
|
|
1404
|
+
} catch {
|
|
1405
|
+
return null;
|
|
1406
|
+
}
|
|
1407
|
+
};
|
|
1408
|
+
var acquireLifecycleLock = (paths) => {
|
|
1409
|
+
assertDirectoryChain2(paths.koedHome, paths.runDir);
|
|
1410
|
+
mkdirSync4(paths.runDir, { recursive: true, mode: 448 });
|
|
1411
|
+
assertDirectoryChain2(paths.koedHome, paths.runDir);
|
|
1412
|
+
const path = lockPath(paths);
|
|
1413
|
+
assertDirectoryChain2(paths.koedHome, path);
|
|
1414
|
+
const identity = resolveProcessIdentity(process.pid);
|
|
1415
|
+
if (!identity)
|
|
1416
|
+
throw new Error("runtime process identity is unavailable");
|
|
1417
|
+
const record = {
|
|
1418
|
+
pid: process.pid,
|
|
1419
|
+
processIdentity: identity,
|
|
1420
|
+
token: randomBytes(32).toString("hex")
|
|
1421
|
+
};
|
|
1422
|
+
try {
|
|
1423
|
+
mkdirSync4(path, { mode: 448 });
|
|
1424
|
+
assertDirectoryChain2(paths.koedHome, path);
|
|
1425
|
+
writeFileSync3(resolve5(path, "owner.json"), `${JSON.stringify(record)}
|
|
1426
|
+
`, {
|
|
1427
|
+
flag: "wx",
|
|
1428
|
+
mode: 384
|
|
1429
|
+
});
|
|
1430
|
+
return record;
|
|
1431
|
+
} catch (error) {
|
|
1432
|
+
if (error.code !== "EEXIST")
|
|
1433
|
+
throw error;
|
|
1434
|
+
throw new Error("runtime lifecycle is locked; if Koed is running, run koed stop and retry. Wait for any active installation. Stale locks require stopped-runtime operator recovery", { cause: error });
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
var releaseLifecycleLock = (paths, expected) => {
|
|
1438
|
+
const path = lockPath(paths);
|
|
1439
|
+
const actual = readLockRecord(path);
|
|
1440
|
+
if (!actual || actual.pid !== expected.pid || actual.token !== expected.token || actual.processIdentity !== expected.processIdentity)
|
|
1441
|
+
return;
|
|
1442
|
+
rmSync6(path, { recursive: true, force: true });
|
|
1443
|
+
};
|
|
1444
|
+
function withLifecycleLock(paths, action) {
|
|
1445
|
+
const lock = acquireLifecycleLock(paths);
|
|
1446
|
+
try {
|
|
1447
|
+
return action();
|
|
1448
|
+
} finally {
|
|
1449
|
+
releaseLifecycleLock(paths, lock);
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
var withStoreLock = async (paths, action) => {
|
|
1453
|
+
assertDirectoryChain2(paths.koedHome, paths.componentsDir);
|
|
1454
|
+
mkdirSync4(paths.componentsDir, { recursive: true, mode: 448 });
|
|
1455
|
+
assertDirectoryChain2(paths.koedHome, paths.componentsDir);
|
|
1456
|
+
const lockPath2 = `${paths.componentsDir}.lock`;
|
|
1457
|
+
assertDirectoryChain2(paths.koedHome, lockPath2);
|
|
1458
|
+
const release = acquireDirectoryLock(lockPath2);
|
|
1459
|
+
try {
|
|
1460
|
+
return await action();
|
|
1461
|
+
} finally {
|
|
1462
|
+
release();
|
|
1463
|
+
}
|
|
1464
|
+
};
|
|
1465
|
+
var readCurrentId = (paths) => {
|
|
1466
|
+
assertDirectoryChain2(paths.koedHome, paths.componentsDir);
|
|
1467
|
+
const pointerPath = resolve5(paths.componentsDir, "current.json");
|
|
1468
|
+
if (!existsSync2(pointerPath))
|
|
1469
|
+
return null;
|
|
1470
|
+
const value = JSON.parse(readRegularFile(pointerPath));
|
|
1471
|
+
if (!isRecord2(value))
|
|
1472
|
+
throw new Error("current generation pointer is invalid");
|
|
1473
|
+
const pointer = value;
|
|
1474
|
+
if (Object.keys(pointer).length !== 2 || pointer.schemaVersion !== 1 || typeof pointer.generationId !== "string" || !/^[a-f0-9]{64}$/.test(pointer.generationId))
|
|
1475
|
+
throw new Error("current generation pointer is invalid");
|
|
1476
|
+
return pointer.generationId;
|
|
1477
|
+
};
|
|
1478
|
+
var writeCurrentPointer = (paths, id) => {
|
|
1479
|
+
const pointer = resolve5(paths.componentsDir, "current.json");
|
|
1480
|
+
const temporary = resolve5(dirname2(pointer), `.current-${randomBytes(8).toString("hex")}.tmp`);
|
|
1481
|
+
writeFileSync3(temporary, `${JSON.stringify({ schemaVersion: 1, generationId: id })}
|
|
1482
|
+
`, { flag: "wx", mode: 384 });
|
|
1483
|
+
try {
|
|
1484
|
+
renameAtomically(temporary, pointer);
|
|
1485
|
+
} catch (error) {
|
|
1486
|
+
rmSync6(temporary, { force: true });
|
|
1487
|
+
throw error;
|
|
1488
|
+
}
|
|
1489
|
+
};
|
|
1490
|
+
var readPinState = (paths) => {
|
|
1491
|
+
const path = generationStatePath(paths);
|
|
1492
|
+
assertDirectoryChain2(paths.koedHome, dirname2(path));
|
|
1493
|
+
if (!existsSync2(path))
|
|
1494
|
+
return null;
|
|
1495
|
+
const parsed = JSON.parse(readRegularFile(path));
|
|
1496
|
+
if (!isRuntimeGenerationState(parsed))
|
|
1497
|
+
throw new Error("runtime generation state is invalid");
|
|
1498
|
+
return parsed;
|
|
1499
|
+
};
|
|
1500
|
+
var assertOwner = (generation, requester) => {
|
|
1501
|
+
if (!sameOwner(generation.owner, requester))
|
|
1502
|
+
throw new Error("runtime owner mismatch");
|
|
1503
|
+
};
|
|
1504
|
+
var assertNoActivePin = (paths, allowCurrentSupervisor = false) => {
|
|
1505
|
+
const pin = readPinState(paths);
|
|
1506
|
+
if (pin) {
|
|
1507
|
+
const identity2 = resolveProcessIdentity(pin.pid);
|
|
1508
|
+
if (identity2 === pin.processIdentity || !identity2 && processIsRunning2(pin.pid))
|
|
1509
|
+
throw new Error("runtime generation is running or pinned");
|
|
1510
|
+
rmSync6(generationStatePath(paths), { force: true });
|
|
1511
|
+
}
|
|
1512
|
+
const supervisorPath = resolve5(paths.runDir, "koed-server.lock");
|
|
1513
|
+
if (!existsSync2(supervisorPath))
|
|
1514
|
+
return;
|
|
1515
|
+
const supervisor = readSupervisorLock(supervisorPath);
|
|
1516
|
+
if (!supervisor)
|
|
1517
|
+
throw new Error("supervisor liveness is uncertain");
|
|
1518
|
+
const identity = resolveProcessIdentity(supervisor.pid);
|
|
1519
|
+
if (allowCurrentSupervisor && supervisor.pid === process.pid && identity !== null && identity === supervisor.processIdentity)
|
|
1520
|
+
return;
|
|
1521
|
+
if (identity === supervisor.processIdentity || !identity && processIsRunning2(supervisor.pid) || !supervisor.processIdentity && processIsRunning2(supervisor.pid))
|
|
1522
|
+
throw new Error("runtime generation is running or pinned");
|
|
1523
|
+
};
|
|
1524
|
+
function readCurrentGenerationOrderingEvidence(paths) {
|
|
1525
|
+
const id = readCurrentId(paths);
|
|
1526
|
+
if (!id)
|
|
1527
|
+
throw new Error("no active runtime generation");
|
|
1528
|
+
return readGenerationOrderingEvidence(paths, id);
|
|
1529
|
+
}
|
|
1530
|
+
async function readCurrentGeneration(paths) {
|
|
1531
|
+
const id = readCurrentId(paths);
|
|
1532
|
+
if (!id)
|
|
1533
|
+
throw new Error("no active runtime generation");
|
|
1534
|
+
return readStagedGeneration(paths, id);
|
|
1535
|
+
}
|
|
1536
|
+
var desktopBundleRecordPath = (paths, id) => resolve5(paths.generationsDir, id, "desktop-bundle.json");
|
|
1537
|
+
var persistDesktopBundleRecord = (paths, generation, capability) => {
|
|
1538
|
+
const root = resolve5(paths.generationsDir, generation.id);
|
|
1539
|
+
assertDirectoryChain2(paths.koedHome, root);
|
|
1540
|
+
mkdirSync4(root, { recursive: true, mode: 448 });
|
|
1541
|
+
const path = desktopBundleRecordPath(paths, generation.id);
|
|
1542
|
+
const record = {
|
|
1543
|
+
schemaVersion: 1,
|
|
1544
|
+
kind: "desktop-bundle",
|
|
1545
|
+
id: generation.id,
|
|
1546
|
+
productVersion: generation.productVersion,
|
|
1547
|
+
owner: generation.owner,
|
|
1548
|
+
bundleDigest: capability.bundleDigest,
|
|
1549
|
+
resourcesPath: capability.resourcesPath
|
|
1550
|
+
};
|
|
1551
|
+
try {
|
|
1552
|
+
writeFileSync3(path, `${JSON.stringify(record)}
|
|
1553
|
+
`, {
|
|
1554
|
+
flag: "wx",
|
|
1555
|
+
mode: 384
|
|
1556
|
+
});
|
|
1557
|
+
} catch (error) {
|
|
1558
|
+
if (error.code !== "EEXIST")
|
|
1559
|
+
throw error;
|
|
1560
|
+
const existing = JSON.parse(readRegularFile(path));
|
|
1561
|
+
if (!isRecord2(existing) || existing.schemaVersion !== record.schemaVersion || existing.kind !== record.kind || existing.id !== record.id || existing.productVersion !== record.productVersion || existing.bundleDigest !== record.bundleDigest || existing.resourcesPath !== record.resourcesPath || !isRecord2(existing.owner) || existing.owner.kind !== generation.owner.kind || existing.owner.installationId !== generation.owner.installationId)
|
|
1562
|
+
throw new Error("private Desktop bundle generation record is invalid", {
|
|
1563
|
+
cause: error
|
|
1564
|
+
});
|
|
1565
|
+
}
|
|
1566
|
+
};
|
|
1567
|
+
var readDesktopBundleGenerationById = async (paths, id, capability) => {
|
|
1568
|
+
const generation = await readDesktopBundleGeneration(paths, capability);
|
|
1569
|
+
if (generation.id !== id)
|
|
1570
|
+
throw new Error("runtime owner mismatch");
|
|
1571
|
+
const record = JSON.parse(readRegularFile(desktopBundleRecordPath(paths, id)));
|
|
1572
|
+
if (!isRecord2(record) || record.schemaVersion !== 1 || record.kind !== "desktop-bundle" || record.id !== generation.id || record.productVersion !== generation.productVersion || record.bundleDigest !== capability.bundleDigest || record.resourcesPath !== capability.resourcesPath || !isRecord2(record.owner) || record.owner.kind !== generation.owner.kind || record.owner.installationId !== generation.owner.installationId)
|
|
1573
|
+
throw new Error("private Desktop bundle generation record is invalid");
|
|
1574
|
+
return generation;
|
|
1575
|
+
};
|
|
1576
|
+
async function readDesktopGenerationForCapability(paths, id, capability) {
|
|
1577
|
+
if (!validateDesktopRuntimeCapability(capability))
|
|
1578
|
+
throw new Error("validated private Desktop runtime capability is required");
|
|
1579
|
+
try {
|
|
1580
|
+
return await readDesktopBundleGenerationById(paths, id, capability);
|
|
1581
|
+
} catch (error) {
|
|
1582
|
+
if (error instanceof Error && error.message === "runtime owner mismatch")
|
|
1583
|
+
return readStagedGeneration(paths, id);
|
|
1584
|
+
throw error;
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
async function readCurrentDesktopGeneration(paths, capability) {
|
|
1588
|
+
if (!validateDesktopRuntimeCapability(capability))
|
|
1589
|
+
throw new Error("validated private Desktop runtime capability is required");
|
|
1590
|
+
const id = readCurrentId(paths);
|
|
1591
|
+
if (!id)
|
|
1592
|
+
throw new Error("no active runtime generation");
|
|
1593
|
+
const generation = await readDesktopGenerationForCapability(paths, id, capability);
|
|
1594
|
+
assertOwner(generation, resolveDesktopRuntimeOwner(capability, paths.koedHome));
|
|
1595
|
+
return generation;
|
|
1596
|
+
}
|
|
1597
|
+
async function readCurrentGenerationForOwner(paths, requester) {
|
|
1598
|
+
const generation = await readCurrentGeneration(paths);
|
|
1599
|
+
assertOwner(generation, requester);
|
|
1600
|
+
return generation;
|
|
1601
|
+
}
|
|
1602
|
+
var readOrderingJournalFile = (path) => {
|
|
1603
|
+
if (constants4.O_NOFOLLOW === void 0)
|
|
1604
|
+
throw new Error("component metadata no-follow access is unavailable");
|
|
1605
|
+
const descriptor = openSync5(path, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
|
|
1606
|
+
try {
|
|
1607
|
+
const stat = fstatSync3(descriptor);
|
|
1608
|
+
if (!stat.isFile() || stat.size > 1024 * 1024)
|
|
1609
|
+
throw new Error("generation journal is not a bounded regular file");
|
|
1610
|
+
const bytes = Buffer.alloc(stat.size + 1);
|
|
1611
|
+
let length = 0;
|
|
1612
|
+
while (length < bytes.length) {
|
|
1613
|
+
const count = readSync(descriptor, bytes, length, bytes.length - length, null);
|
|
1614
|
+
if (count === 0)
|
|
1615
|
+
break;
|
|
1616
|
+
length += count;
|
|
1617
|
+
}
|
|
1618
|
+
if (length > stat.size)
|
|
1619
|
+
throw new Error("generation journal changed while reading");
|
|
1620
|
+
return bytes.subarray(0, length).toString("utf8");
|
|
1621
|
+
} finally {
|
|
1622
|
+
closeSync5(descriptor);
|
|
1623
|
+
}
|
|
1624
|
+
};
|
|
1625
|
+
var readDesktopOrderingJournal = (paths, id) => {
|
|
1626
|
+
const bundlePath = desktopBundleRecordPath(paths, id);
|
|
1627
|
+
const hasBundle = existsSync2(bundlePath);
|
|
1628
|
+
if (hasBundle)
|
|
1629
|
+
assertDirectoryChain2(paths.koedHome, dirname2(bundlePath));
|
|
1630
|
+
const record = hasBundle ? JSON.parse(readOrderingJournalFile(bundlePath)) : readGenerationRecord(paths, id);
|
|
1631
|
+
if (!isRecord2(record))
|
|
1632
|
+
throw new Error("generation record is invalid");
|
|
1633
|
+
if (record.kind !== "desktop-bundle" && record.kind !== "desktop-bundle-with-privacy")
|
|
1634
|
+
return null;
|
|
1635
|
+
validateDesktopOrderingJournal(record, id);
|
|
1636
|
+
return Object.freeze({
|
|
1637
|
+
kind: "desktop-generation-ordering-evidence",
|
|
1638
|
+
id,
|
|
1639
|
+
productVersion: record.productVersion,
|
|
1640
|
+
owner: Object.freeze({ ...record.owner }),
|
|
1641
|
+
bundleDigest: record.bundleDigest,
|
|
1642
|
+
resourcesPath: record.resourcesPath,
|
|
1643
|
+
components: Object.freeze(record.kind === "desktop-bundle" ? ["base"] : ["base", "privacy"])
|
|
1644
|
+
});
|
|
1645
|
+
};
|
|
1646
|
+
function validateDesktopOrderingJournal(record, id) {
|
|
1647
|
+
const privacy = record.kind === "desktop-bundle-with-privacy";
|
|
1648
|
+
const keys = [
|
|
1649
|
+
"schemaVersion",
|
|
1650
|
+
"kind",
|
|
1651
|
+
"id",
|
|
1652
|
+
"productVersion",
|
|
1653
|
+
"owner",
|
|
1654
|
+
"bundleDigest",
|
|
1655
|
+
"resourcesPath",
|
|
1656
|
+
...privacy ? ["privacy"] : []
|
|
1657
|
+
];
|
|
1658
|
+
if (Object.keys(record).length !== keys.length || !keys.every((key) => Object.hasOwn(record, key)) || record.schemaVersion !== 1 || record.id !== id || typeof record.productVersion !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(record.productVersion) || !isRuntimeOwnerRecord(record.owner) || record.owner.kind !== "desktop" || typeof record.resourcesPath !== "string" || !isAbsolute3(record.resourcesPath) || typeof record.bundleDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.bundleDigest))
|
|
1659
|
+
throw new Error("private Desktop bundle generation record is invalid");
|
|
1660
|
+
if (privacy)
|
|
1661
|
+
validateDesktopPrivacyJournal(record, id);
|
|
1662
|
+
else if (createHash3("sha256").update(`${record.owner.installationId}
|
|
1663
|
+
${record.bundleDigest}`).digest("hex") !== id)
|
|
1664
|
+
throw new Error("Desktop bundle generation identity mismatch");
|
|
1665
|
+
}
|
|
1666
|
+
function validateDesktopPrivacyJournal(record, id) {
|
|
1667
|
+
if (!isRecord2(record.privacy) || Object.keys(record.privacy).length !== 2 || typeof record.privacy.root !== "string" || isAbsolute3(record.privacy.root) || record.privacy.root.split(/[\\/]/).includes("..") || typeof record.privacy.manifestDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.privacy.manifestDigest))
|
|
1668
|
+
throw new Error("private Desktop privacy journal is invalid");
|
|
1669
|
+
const identity = { ...record };
|
|
1670
|
+
delete identity.id;
|
|
1671
|
+
if (createHash3("sha256").update(canonicalArtifactJson(identity)).digest("hex") !== id)
|
|
1672
|
+
throw new Error("Desktop privacy generation digest mismatch");
|
|
1673
|
+
}
|
|
1674
|
+
function readCurrentDesktopGenerationOrderingEvidence(paths, capability) {
|
|
1675
|
+
if (!validateDesktopRuntimeCapability(capability))
|
|
1676
|
+
throw new Error("validated private Desktop runtime capability is required");
|
|
1677
|
+
const id = readCurrentId(paths);
|
|
1678
|
+
if (!id)
|
|
1679
|
+
throw new Error("no active runtime generation");
|
|
1680
|
+
const evidence = readDesktopOrderingJournal(paths, id) ?? readGenerationOrderingEvidence(paths, id);
|
|
1681
|
+
if (evidence.kind === "desktop-generation-ordering-evidence" && evidence.resourcesPath !== capability.resourcesPath)
|
|
1682
|
+
throw new Error("runtime owner mismatch");
|
|
1683
|
+
assertOwner(evidence, resolveDesktopRuntimeOwner(capability, paths.koedHome));
|
|
1684
|
+
return evidence;
|
|
1685
|
+
}
|
|
1686
|
+
async function readCurrentRuntimeOwner(paths) {
|
|
1687
|
+
if (!existsSync2(resolve5(paths.componentsDir, "current.json")))
|
|
1688
|
+
return null;
|
|
1689
|
+
const id = readCurrentId(paths);
|
|
1690
|
+
if (!id)
|
|
1691
|
+
return null;
|
|
1692
|
+
return (await Promise.resolve(readDesktopOrderingJournal(paths, id) ?? readGenerationOrderingEvidence(paths, id))).owner;
|
|
1693
|
+
}
|
|
1694
|
+
function withSourceNativeStartLock(paths, check) {
|
|
1695
|
+
const lock = acquireLifecycleLock(paths);
|
|
1696
|
+
try {
|
|
1697
|
+
const owner = readSupervisorLock(resolve5(paths.runDir, "koed-server.lock"));
|
|
1698
|
+
if (!owner || owner.pid !== process.pid || !owner.processIdentity || owner.processIdentity !== resolveProcessIdentity(process.pid))
|
|
1699
|
+
throw new Error("Source native selection requires the active supervisor lock.");
|
|
1700
|
+
return check();
|
|
1701
|
+
} finally {
|
|
1702
|
+
releaseLifecycleLock(paths, lock);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
async function withStoppedRuntime(paths, requester, action) {
|
|
1706
|
+
const lock = acquireLifecycleLock(paths);
|
|
1707
|
+
try {
|
|
1708
|
+
assertDirectoryChain2(paths.koedHome, paths.postgresDataDir);
|
|
1709
|
+
assertDirectoryChain2(paths.koedHome, dirname2(paths.runtimeStatePath));
|
|
1710
|
+
assertDirectoryChain2(paths.koedHome, dirname2(generationStatePath(paths)));
|
|
1711
|
+
assertDirectoryChain2(paths.koedHome, paths.componentsDir);
|
|
1712
|
+
try {
|
|
1713
|
+
if (!lstatSync3(resolve5(paths.componentsDir, "current.json")).isFile())
|
|
1714
|
+
throw new Error("current generation pointer is not a regular file");
|
|
1715
|
+
} catch (error) {
|
|
1716
|
+
if (error.code !== "ENOENT")
|
|
1717
|
+
throw error;
|
|
1718
|
+
}
|
|
1719
|
+
const owner = await readCurrentRuntimeOwner(paths);
|
|
1720
|
+
if (owner)
|
|
1721
|
+
assertOwner({ owner }, requester);
|
|
1722
|
+
const observation = observeStoppedRuntime(paths);
|
|
1723
|
+
if (observation.state !== "stopped")
|
|
1724
|
+
throw new Error(`${observation.message} Run koed stop before retrying. Stale or unreadable locks require stopped-runtime Operator recovery.`);
|
|
1725
|
+
removeStaleRuntimeRecords(observation);
|
|
1726
|
+
return await action();
|
|
1727
|
+
} finally {
|
|
1728
|
+
releaseLifecycleLock(paths, lock);
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
var persistPinState = (paths, generation, requester, lock, source = "manifest-pinned-store") => {
|
|
1732
|
+
const processIdentity = resolveProcessIdentity(process.pid);
|
|
1733
|
+
if (!processIdentity)
|
|
1734
|
+
throw new Error("runtime process identity is unavailable");
|
|
1735
|
+
const state = {
|
|
1736
|
+
schemaVersion: 1,
|
|
1737
|
+
generationId: generation.id,
|
|
1738
|
+
pid: process.pid,
|
|
1739
|
+
processIdentity,
|
|
1740
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1741
|
+
owner: requester,
|
|
1742
|
+
pinToken: lock.token,
|
|
1743
|
+
...source === "desktop-bundle" ? { source } : {}
|
|
1744
|
+
};
|
|
1745
|
+
const path = generationStatePath(paths);
|
|
1746
|
+
mkdirSync4(dirname2(path), { recursive: true, mode: 448 });
|
|
1747
|
+
const temporary = `${path}.${lock.token}.tmp`;
|
|
1748
|
+
writeFileSync3(temporary, `${JSON.stringify(state)}
|
|
1749
|
+
`, {
|
|
1750
|
+
flag: "wx",
|
|
1751
|
+
mode: 384
|
|
1752
|
+
});
|
|
1753
|
+
renameSync3(temporary, path);
|
|
1754
|
+
return { path, processIdentity };
|
|
1755
|
+
};
|
|
1756
|
+
var createPinRelease = (paths, lock, pinPath, processIdentity) => {
|
|
1757
|
+
let released = false;
|
|
1758
|
+
return () => Promise.resolve().then(() => {
|
|
1759
|
+
if (released)
|
|
1760
|
+
return;
|
|
1761
|
+
released = true;
|
|
1762
|
+
try {
|
|
1763
|
+
const current = readPinState(paths);
|
|
1764
|
+
if (current?.pinToken === lock.token && current.processIdentity === processIdentity)
|
|
1765
|
+
rmSync6(pinPath, { force: true });
|
|
1766
|
+
} finally {
|
|
1767
|
+
releaseLifecycleLock(paths, lock);
|
|
1768
|
+
}
|
|
1769
|
+
});
|
|
1770
|
+
};
|
|
1771
|
+
function readDesktopBundleGeneration(paths, capability) {
|
|
1772
|
+
if (!validateDesktopRuntimeCapability(capability))
|
|
1773
|
+
throw new Error("validated private Desktop runtime capability is required");
|
|
1774
|
+
const currentCapability = verifyDesktopRuntimeBundle(capability.resourcesPath);
|
|
1775
|
+
if (currentCapability.productVersion !== capability.productVersion || currentCapability.bundleDigest !== capability.bundleDigest)
|
|
1776
|
+
throw new Error("Desktop runtime bundle changed after verification");
|
|
1777
|
+
const owner = resolveDesktopRuntimeOwner(capability, paths.koedHome);
|
|
1778
|
+
const generation = desktopBundleGeneration(currentCapability, owner);
|
|
1779
|
+
return Promise.resolve(generation);
|
|
1780
|
+
}
|
|
1781
|
+
async function stageDesktopBundleForRecovery(paths, capability) {
|
|
1782
|
+
return withStoreLock(paths, async () => {
|
|
1783
|
+
const generation = await readDesktopBundleGeneration(paths, capability);
|
|
1784
|
+
persistDesktopBundleRecord(paths, generation, capability);
|
|
1785
|
+
return generation;
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
async function pinDesktopBundleGenerationForStart(paths, capability) {
|
|
1789
|
+
if (!validateDesktopRuntimeCapability(capability))
|
|
1790
|
+
throw new Error("validated private Desktop runtime capability is required");
|
|
1791
|
+
const requester = resolveDesktopRuntimeOwner(capability, paths.koedHome);
|
|
1792
|
+
const lock = acquireLifecycleLock(paths);
|
|
1793
|
+
try {
|
|
1794
|
+
return await withStoreLock(paths, async () => {
|
|
1795
|
+
assertNoActivePin(paths, true);
|
|
1796
|
+
const bundled = await readDesktopBundleGeneration(paths, capability);
|
|
1797
|
+
const activeId = readCurrentId(paths);
|
|
1798
|
+
let active = null;
|
|
1799
|
+
if (activeId) {
|
|
1800
|
+
const prior = readCurrentDesktopGenerationOrderingEvidence(paths, capability);
|
|
1801
|
+
if (isVersionDowngrade(prior.productVersion, bundled.productVersion))
|
|
1802
|
+
throw new Error("Desktop generation downgrades are not supported.");
|
|
1803
|
+
if (prior.kind === "desktop-generation-ordering-evidence" ? prior.bundleDigest === capability.bundleDigest : prior.productVersion === bundled.productVersion) {
|
|
1804
|
+
active = await readDesktopGenerationForCapability(paths, activeId, capability);
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
if (active)
|
|
1808
|
+
assertOwner(active, requester);
|
|
1809
|
+
persistDesktopBundleRecord(paths, bundled, capability);
|
|
1810
|
+
const generation = active && sameOwner(active.owner, requester) && active.productVersion === bundled.productVersion && active.base.manifestDigest === bundled.base.manifestDigest ? active : bundled;
|
|
1811
|
+
if (activeId !== generation.id)
|
|
1812
|
+
writeCurrentPointer(paths, generation.id);
|
|
1813
|
+
const pin = persistPinState(paths, generation, requester, lock, "desktop-bundle");
|
|
1814
|
+
return {
|
|
1815
|
+
generation,
|
|
1816
|
+
release: createPinRelease(paths, lock, pin.path, pin.processIdentity)
|
|
1817
|
+
};
|
|
1818
|
+
});
|
|
1819
|
+
} catch (error) {
|
|
1820
|
+
releaseLifecycleLock(paths, lock);
|
|
1821
|
+
throw error;
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
var desktopBundleGeneration = (capability, owner) => {
|
|
1825
|
+
const manifest = capability.manifest;
|
|
1826
|
+
const id = createHash3("sha256").update(`${owner.installationId}
|
|
1827
|
+
${capability.bundleDigest}`).digest("hex");
|
|
1828
|
+
return {
|
|
1829
|
+
id,
|
|
1830
|
+
productVersion: capability.productVersion,
|
|
1831
|
+
base: {
|
|
1832
|
+
kind: "desktop-bundle",
|
|
1833
|
+
manifest,
|
|
1834
|
+
root: resolve5(capability.resourcesPath, "koed-runtime"),
|
|
1835
|
+
manifestDigest: capability.bundleDigest
|
|
1836
|
+
},
|
|
1837
|
+
owner
|
|
1838
|
+
};
|
|
1839
|
+
};
|
|
1840
|
+
async function pinGenerationForStart(paths, requester) {
|
|
1841
|
+
const lock = acquireLifecycleLock(paths);
|
|
1842
|
+
try {
|
|
1843
|
+
return await withStoreLock(paths, async () => {
|
|
1844
|
+
assertNoActivePin(paths, true);
|
|
1845
|
+
const generation = await readCurrentGeneration(paths);
|
|
1846
|
+
assertOwner(generation, requester);
|
|
1847
|
+
const pin = persistPinState(paths, generation, requester, lock);
|
|
1848
|
+
return {
|
|
1849
|
+
generation,
|
|
1850
|
+
release: createPinRelease(paths, lock, pin.path, pin.processIdentity)
|
|
1851
|
+
};
|
|
1852
|
+
});
|
|
1853
|
+
} catch (error) {
|
|
1854
|
+
releaseLifecycleLock(paths, lock);
|
|
1855
|
+
throw error;
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
async function activateGeneration(paths, id, requester, capability, selection) {
|
|
1859
|
+
const lock = acquireLifecycleLock(paths);
|
|
1860
|
+
try {
|
|
1861
|
+
return await withStoreLock(paths, async () => {
|
|
1862
|
+
assertNoActivePin(paths);
|
|
1863
|
+
const currentId = readCurrentId(paths);
|
|
1864
|
+
if (selection && currentId !== selection.expectedCurrentGeneration)
|
|
1865
|
+
throw new Error("Runtime selection changed during Privacy installation. Retry from the current selection; no generation was replaced.");
|
|
1866
|
+
const candidate = capability ? await readDesktopGenerationForCapability(paths, id, capability) : await readStagedGeneration(paths, id);
|
|
1867
|
+
assertOwner(candidate, requester);
|
|
1868
|
+
if (currentId) {
|
|
1869
|
+
const current = capability ? await readDesktopGenerationForCapability(paths, currentId, capability) : readGenerationOrderingEvidence(paths, currentId);
|
|
1870
|
+
assertOwner(current, requester);
|
|
1871
|
+
if (isVersionDowngrade(current.productVersion, candidate.productVersion))
|
|
1872
|
+
throw new Error(`Cannot activate generation ${candidate.productVersion} over active ${current.productVersion}: generation downgrades are not supported.`);
|
|
1873
|
+
}
|
|
1874
|
+
writeCurrentPointer(paths, candidate.id);
|
|
1875
|
+
return candidate;
|
|
1876
|
+
});
|
|
1877
|
+
} finally {
|
|
1878
|
+
releaseLifecycleLock(paths, lock);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
var listOwnedGenerations = async (paths, requester) => {
|
|
1882
|
+
assertDirectoryChain2(paths.koedHome, paths.generationsDir);
|
|
1883
|
+
let entries;
|
|
1884
|
+
try {
|
|
1885
|
+
entries = readdirSync3(paths.generationsDir, { withFileTypes: true });
|
|
1886
|
+
} catch (error) {
|
|
1887
|
+
if (error.code === "ENOENT")
|
|
1888
|
+
return [];
|
|
1889
|
+
throw error;
|
|
1890
|
+
}
|
|
1891
|
+
const candidates = entries.filter((entry) => entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)).map((entry) => ({
|
|
1892
|
+
id: entry.name,
|
|
1893
|
+
path: resolve5(paths.generationsDir, entry.name),
|
|
1894
|
+
mtime: statSync(resolve5(paths.generationsDir, entry.name)).mtimeMs
|
|
1895
|
+
})).sort((left, right) => right.mtime - left.mtime || left.id.localeCompare(right.id));
|
|
1896
|
+
const verified = [];
|
|
1897
|
+
for (const entry of candidates) {
|
|
1898
|
+
try {
|
|
1899
|
+
const generation = await readStagedGeneration(paths, entry.id);
|
|
1900
|
+
if (sameOwner(generation.owner, requester))
|
|
1901
|
+
verified.push(entry);
|
|
1902
|
+
} catch {
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
return verified;
|
|
1906
|
+
};
|
|
1907
|
+
var removeUnretainedGenerations = (generations, retain, currentId) => {
|
|
1908
|
+
const kept = new Set(generations.slice(0, retain).map((entry) => entry.id));
|
|
1909
|
+
if (currentId)
|
|
1910
|
+
kept.add(currentId);
|
|
1911
|
+
const removed = [];
|
|
1912
|
+
for (const entry of generations) {
|
|
1913
|
+
if (kept.has(entry.id))
|
|
1914
|
+
continue;
|
|
1915
|
+
rmSync6(entry.path, { recursive: true, force: true });
|
|
1916
|
+
removed.push(entry.id);
|
|
1917
|
+
}
|
|
1918
|
+
return removed;
|
|
1919
|
+
};
|
|
1920
|
+
async function cleanupGenerations(paths, retain, requester) {
|
|
1921
|
+
if (!Number.isInteger(retain) || retain < 1)
|
|
1922
|
+
throw new Error("generation retention must be a positive integer");
|
|
1923
|
+
const lock = acquireLifecycleLock(paths);
|
|
1924
|
+
try {
|
|
1925
|
+
return await withStoreLock(paths, async () => {
|
|
1926
|
+
assertNoActivePin(paths);
|
|
1927
|
+
const currentId = readCurrentId(paths);
|
|
1928
|
+
const current = currentId ? await readStagedGeneration(paths, currentId) : null;
|
|
1929
|
+
if (current)
|
|
1930
|
+
assertOwner(current, requester);
|
|
1931
|
+
const generations = await listOwnedGenerations(paths, requester);
|
|
1932
|
+
return removeUnretainedGenerations(generations, retain, currentId);
|
|
1933
|
+
});
|
|
1934
|
+
} finally {
|
|
1935
|
+
releaseLifecycleLock(paths, lock);
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
export {
|
|
1940
|
+
validateDesktopRuntimeCapability,
|
|
1941
|
+
resolveDesktopRuntimeOwner,
|
|
1942
|
+
fetchBounded,
|
|
1943
|
+
discoverActualRuntimeIdentity,
|
|
1944
|
+
resolveComponentManifestPinTarget,
|
|
1945
|
+
stageComponent,
|
|
1946
|
+
stageGeneration,
|
|
1947
|
+
readStoredComponents,
|
|
1948
|
+
readGenerationComponentPresence,
|
|
1949
|
+
readStagedGeneration,
|
|
1950
|
+
resolveProcessIdentity,
|
|
1951
|
+
readSupervisorLock,
|
|
1952
|
+
acquireKoedServerSupervisorLock,
|
|
1953
|
+
releaseKoedServerSupervisorLock,
|
|
1954
|
+
renameAtomically,
|
|
1955
|
+
observeStoppedRuntime,
|
|
1956
|
+
removeStaleRuntimeRecords,
|
|
1957
|
+
assertDirectoryChain2 as assertDirectoryChain,
|
|
1958
|
+
withLifecycleLock,
|
|
1959
|
+
readCurrentGenerationOrderingEvidence,
|
|
1960
|
+
readCurrentGeneration,
|
|
1961
|
+
readDesktopGenerationForCapability,
|
|
1962
|
+
readCurrentDesktopGeneration,
|
|
1963
|
+
readCurrentGenerationForOwner,
|
|
1964
|
+
readCurrentDesktopGenerationOrderingEvidence,
|
|
1965
|
+
readCurrentRuntimeOwner,
|
|
1966
|
+
withSourceNativeStartLock,
|
|
1967
|
+
withStoppedRuntime,
|
|
1968
|
+
readDesktopBundleGeneration,
|
|
1969
|
+
stageDesktopBundleForRecovery,
|
|
1970
|
+
pinDesktopBundleGenerationForStart,
|
|
1971
|
+
pinGenerationForStart,
|
|
1972
|
+
activateGeneration,
|
|
1973
|
+
cleanupGenerations
|
|
1974
|
+
};
|