@koed-labs/server 0.10.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +3 -3
  2. package/bin/koed.js +1 -1
  3. package/package.json +2 -2
  4. package/vendor/chunk-273NMYXE.js +605 -0
  5. package/vendor/{chunk-VPC5NLZG.js → chunk-4DHYSJJT.js} +1 -1
  6. package/vendor/{chunk-HK2H3MVE.js → chunk-53ZFCDHP.js} +4 -0
  7. package/vendor/{chunk-YCDEMYY6.js → chunk-54UL4U2E.js} +261 -110
  8. package/vendor/{chunk-X6M525ZJ.js → chunk-64AST7WZ.js} +5 -5
  9. package/vendor/{chunk-JKOG52PE.js → chunk-7FSHVVTZ.js} +1 -1
  10. package/vendor/chunk-7HLNJ2BI.js +1669 -0
  11. package/vendor/chunk-ALJUSOF7.js +175 -0
  12. package/vendor/{chunk-A6WMU2GG.js → chunk-AOZ3LMTF.js} +5 -4
  13. package/vendor/{chunk-KUIWH33N.js → chunk-AVQCUFYQ.js} +1 -1
  14. package/vendor/{chunk-JJNLH5GA.js → chunk-BYN6KXNP.js} +21 -19
  15. package/vendor/{chunk-PY5LYLV7.js → chunk-DWWMBGHX.js} +26 -21
  16. package/vendor/chunk-E6YVGIEW.js +12518 -0
  17. package/vendor/{chunk-C3N4N5HR.js → chunk-EEBIYWTE.js} +26 -21
  18. package/vendor/{chunk-YOFI4PCH.js → chunk-F77ZTTNS.js} +7 -1
  19. package/vendor/{chunk-RVYJKKWA.js → chunk-F7AMEDDU.js} +5 -4
  20. package/vendor/{chunk-473OA62O.js → chunk-FSNLU46W.js} +218 -12497
  21. package/vendor/{chunk-2S3OGPUC.js → chunk-GY5GATZL.js} +2 -2
  22. package/vendor/chunk-ILQVLZ2I.js +50 -0
  23. package/vendor/{chunk-QIIKMG3M.js → chunk-IY2HRXOZ.js} +1 -5
  24. package/vendor/{chunk-ZUGNCQZE.js → chunk-JYK6UL6D.js} +22 -8
  25. package/vendor/chunk-KG3RANR4.js +75 -0
  26. package/vendor/{chunk-YJ6XUZT6.js → chunk-KRBZZ6GS.js} +23 -16
  27. package/vendor/{chunk-AFLKCQHF.js → chunk-L4RD3TAZ.js} +2 -2
  28. package/vendor/{chunk-XNFVSVBS.js → chunk-LHUMBHG7.js} +1 -1
  29. package/vendor/{chunk-J2L726BC.js → chunk-NGV45YWB.js} +3 -3
  30. package/vendor/{chunk-A4NKL2PK.js → chunk-OG7G6DIR.js} +1 -1
  31. package/vendor/{chunk-DXTAWHY3.js → chunk-OZU6JFB4.js} +8 -7
  32. package/vendor/chunk-QV3WPU7A.js +8 -0
  33. package/vendor/{chunk-ZXX4ZNJY.js → chunk-S6HD3MDU.js} +3 -2
  34. package/vendor/{chunk-NEWIOOM6.js → chunk-SQZ2OSP6.js} +3 -2
  35. package/vendor/{chunk-G4IIVVJO.js → chunk-T6UB5PNX.js} +70 -2
  36. package/vendor/{chunk-SKVYP7NY.js → chunk-T7OGE5E5.js} +8 -8
  37. package/vendor/{chunk-GELDEJJ2.js → chunk-TIBYKMRW.js} +173 -51
  38. package/vendor/{chunk-HFM6ROJL.js → chunk-TISYUUEJ.js} +1 -1
  39. package/vendor/{chunk-K2EIFEQF.js → chunk-TSAYTRX3.js} +1 -1
  40. package/vendor/{chunk-PT3AUPGE.js → chunk-UB6JCVQ3.js} +3 -1
  41. package/vendor/{chunk-NM5NXCVM.js → chunk-UCOHFZ77.js} +626 -996
  42. package/vendor/{chunk-2BWTLF7A.js → chunk-UIMUUIH7.js} +45 -21
  43. package/vendor/{chunk-HZJK5RWC.js → chunk-USHFSJT7.js} +695 -280
  44. package/vendor/chunk-VGL5AZN5.js +152 -0
  45. package/vendor/{chunk-TSRPHKAC.js → chunk-VLP72QWX.js} +16 -42
  46. package/vendor/chunk-W6632NOX.js +14 -0
  47. package/vendor/{chunk-YJWREXN6.js → chunk-WBMO7YCO.js} +1 -1
  48. package/vendor/chunk-XCO3RV3Z.js +11 -0
  49. package/vendor/chunk-XKXSC6YS.js +373 -0
  50. package/vendor/{chunk-YK4F4VY2.js → chunk-Y6GE52OP.js} +51 -30
  51. package/vendor/{chunk-UI5RLBKQ.js → chunk-YZLQZU5E.js} +17 -1
  52. package/vendor/chunk-ZKKWLLPU.js +18 -0
  53. package/vendor/cli.js +1 -1
  54. package/vendor/component-manifest-catalog.js +2 -1
  55. package/vendor/control-plane.js +11 -6
  56. package/vendor/chunk-2DA7EFZV.js +0 -924
@@ -0,0 +1,1669 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ nativeKind
4
+ } from "./chunk-VGL5AZN5.js";
5
+ import {
6
+ lookupManifestPin
7
+ } from "./chunk-IY2HRXOZ.js";
8
+
9
+ // packages/koed-server/dist/native-payload-admission.js
10
+ import { createHash as createHash2 } from "node:crypto";
11
+ import { closeSync as closeSync2, constants as constants2, fstatSync as fstatSync2, fsyncSync, lstatSync as lstatSync2, openSync as openSync2, readFileSync, readSync as readSync2, readdirSync as readdirSync2, readlinkSync, realpathSync } from "node:fs";
12
+ import { dirname, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2 } from "node:path";
13
+
14
+ // packages/koed-server/dist/artifact-canonical-json.mjs
15
+ import { Buffer as Buffer2 } from "node:buffer";
16
+ function canonicalArtifactJson(value) {
17
+ const ancestors = /* @__PURE__ */ new Set();
18
+ const encode = (item) => {
19
+ if (item === null)
20
+ return "null";
21
+ if (typeof item === "string" || typeof item === "boolean")
22
+ return JSON.stringify(item);
23
+ if (typeof item === "number" && Number.isFinite(item))
24
+ return JSON.stringify(item);
25
+ if (typeof item !== "object")
26
+ throw new TypeError("artifact has unsupported JSON value");
27
+ const array = Array.isArray(item);
28
+ const prototype = Object.getPrototypeOf(item);
29
+ if (!array && prototype !== Object.prototype && prototype !== null)
30
+ throw new TypeError("artifact has unsupported JSON object");
31
+ if (Object.getOwnPropertySymbols(item).length)
32
+ throw new TypeError("artifact has unsupported JSON symbol key");
33
+ if (ancestors.has(item))
34
+ throw new TypeError("artifact has cyclic JSON value");
35
+ ancestors.add(item);
36
+ try {
37
+ if (array) {
38
+ const entries = [];
39
+ for (let index = 0; index < item.length; index++) {
40
+ if (!Object.hasOwn(item, index))
41
+ throw new TypeError("artifact has sparse JSON array");
42
+ entries.push(encode(item[index]));
43
+ }
44
+ return `[${entries.join(",")}]`;
45
+ }
46
+ return `{${Object.keys(item).sort().map((key) => `${JSON.stringify(key)}:${encode(item[key])}`).join(",")}}`;
47
+ } finally {
48
+ ancestors.delete(item);
49
+ }
50
+ };
51
+ return encode(value);
52
+ }
53
+ function canonicalArtifactBytes(value) {
54
+ return Buffer2.from(canonicalArtifactJson(value), "utf8");
55
+ }
56
+
57
+ // packages/koed-server/dist/component-verification.js
58
+ import { createHash } from "node:crypto";
59
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readSync } from "node:fs";
60
+ import { Readable } from "node:stream";
61
+ import { basename, isAbsolute, relative, resolve, sep } from "node:path";
62
+ import { createGunzip } from "node:zlib";
63
+
64
+ // packages/koed-server/dist/component-artifact-identity.mjs
65
+ var componentArchiveName = ({ component, productVersion, target, variant }) => `koed-${component}-${productVersion}-${target.platform}-${target.architecture}${variant === void 0 ? "" : `-${variant}`}.tar.gz`;
66
+ var validateComponentVariantIdentity = (value) => {
67
+ if (value.schemaVersion === 1 && !Object.hasOwn(value, "variant"))
68
+ return;
69
+ if (value.schemaVersion === 2 && value.component === "privacy" && value.target?.platform === "linux" && value.target.architecture === "x64" && ["cpu", "cuda"].includes(value.variant))
70
+ return;
71
+ throw new Error("Unsupported component variant identity; update to a compatible control plane.");
72
+ };
73
+
74
+ // packages/koed-server/dist/component-verification.js
75
+ var MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;
76
+ var MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
77
+ var MAX_EXPANDED_BYTES = 4 * 1024 * 1024 * 1024;
78
+ var MAX_FILE_BYTES = 1024 * 1024 * 1024;
79
+ var MAX_FILES = 1e5;
80
+ var MAX_DEPTH = 128;
81
+ var MAX_DIRECTORIES = 1e5;
82
+ var MAX_TAR_BYTES = MAX_EXPANDED_BYTES + MAX_FILES * 1024 + 1024;
83
+ var canonicalComponentManifestBytes = (manifest) => canonicalArtifactBytes(manifest);
84
+ function assertRecord(value, name, keys) {
85
+ if (!value || typeof value !== "object" || Array.isArray(value))
86
+ throw new Error(`${name} must be an object`);
87
+ const actual = Object.keys(value);
88
+ if (actual.length !== keys.length || keys.some((key) => !actual.includes(key)))
89
+ throw new Error(`${name} has invalid fields`);
90
+ }
91
+ function safeRelativePath(path, label) {
92
+ if (typeof path !== "string" || !path || path.includes("\\") || path.includes("\0") || isAbsolute(path) || path.split("/").some((part) => part === ".." || part === "." || !part)) {
93
+ throw new Error(`${label} is unsafe`);
94
+ }
95
+ }
96
+ function validateComponentManifest(value) {
97
+ assertRecord(value, "component manifest", [
98
+ "schemaVersion",
99
+ "productVersion",
100
+ "component",
101
+ "target",
102
+ "runtimes",
103
+ "archive",
104
+ "requiredFiles",
105
+ "files",
106
+ ...value && typeof value === "object" && Object.hasOwn(value, "variant") ? ["variant"] : []
107
+ ]);
108
+ const manifest = value;
109
+ if (![1, 2].includes(manifest.schemaVersion) || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(manifest.productVersion) || !["base", "privacy"].includes(manifest.component))
110
+ throw new Error("component manifest identity is invalid");
111
+ validateComponentVariantIdentity(manifest);
112
+ assertRecord(manifest.target, "component target", manifest.target.libc ? ["platform", "architecture", "libc"] : ["platform", "architecture"]);
113
+ if (!["macos", "linux"].includes(manifest.target.platform) || !["arm64", "x64"].includes(manifest.target.architecture))
114
+ throw new Error("unsupported component target");
115
+ if (manifest.target.libc) {
116
+ assertRecord(manifest.target.libc, "component libc target", [
117
+ "family",
118
+ "minimumVersion"
119
+ ]);
120
+ if (manifest.target.platform !== "linux" || manifest.target.libc.family !== "glibc" || !isVersion(manifest.target.libc.minimumVersion))
121
+ throw new Error("component libc target is invalid");
122
+ }
123
+ assertRecord(manifest.archive, "component archive", [
124
+ "name",
125
+ "bytes",
126
+ "sha256"
127
+ ]);
128
+ if (typeof manifest.archive.name !== "string" || basename(manifest.archive.name) !== manifest.archive.name || !Number.isSafeInteger(manifest.archive.bytes) || manifest.archive.bytes < 1 || !isHash(manifest.archive.sha256))
129
+ throw new Error("component archive metadata is invalid");
130
+ if (manifest.variant !== void 0 && manifest.archive.name !== componentArchiveName(manifest))
131
+ throw new Error("Component archive variant identity mismatch.");
132
+ if (!Array.isArray(manifest.runtimes) || manifest.runtimes.length === 0 || !Array.isArray(manifest.requiredFiles) || manifest.requiredFiles.length > MAX_FILES || !Array.isArray(manifest.files) || manifest.files.length > MAX_FILES)
133
+ throw new Error("component manifest lists are invalid");
134
+ for (const runtime of manifest.runtimes) {
135
+ if (!runtime || typeof runtime !== "object" || Array.isArray(runtime))
136
+ throw new Error("component runtime compatibility is invalid");
137
+ const runtimeRecord = runtime;
138
+ const runtimeKeys = [
139
+ "kind",
140
+ "runtimeRange",
141
+ "nodeRange",
142
+ ...runtimeRecord.modulesAbi === void 0 ? [] : ["modulesAbi"],
143
+ ...runtimeRecord.minimumNapi === void 0 ? [] : ["minimumNapi"]
144
+ ];
145
+ assertRecord(runtime, "component runtime compatibility", runtimeKeys);
146
+ if (typeof runtimeRecord.kind !== "string" || !["node", "electron"].includes(runtimeRecord.kind) || !validRange(runtime.runtimeRange) || !validRange(runtime.nodeRange) || runtimeRecord.modulesAbi !== void 0 && (typeof runtimeRecord.modulesAbi !== "string" || !/^\d+$/.test(runtimeRecord.modulesAbi)) || runtimeRecord.minimumNapi !== void 0 && (typeof runtimeRecord.minimumNapi !== "number" || !Number.isSafeInteger(runtimeRecord.minimumNapi) || runtimeRecord.minimumNapi < 1))
147
+ throw new Error("component runtime compatibility is invalid");
148
+ if (runtime.modulesAbi === void 0 && runtime.minimumNapi === void 0)
149
+ throw new Error("component runtime compatibility must bind ABI or N-API");
150
+ }
151
+ const paths = /* @__PURE__ */ new Set();
152
+ for (const item of manifest.files) {
153
+ assertRecord(item, "component file entry", ["path", "sha256"]);
154
+ safeRelativePath(item.path, "component file path");
155
+ if (!isHash(item.sha256) || paths.has(item.path))
156
+ throw new Error("component file inventory is invalid or duplicate");
157
+ paths.add(item.path);
158
+ }
159
+ const required = /* @__PURE__ */ new Set();
160
+ for (const path of manifest.requiredFiles) {
161
+ safeRelativePath(path, "required component path");
162
+ if (required.has(path) || !paths.has(path))
163
+ throw new Error("required component file is duplicate or missing from inventory");
164
+ required.add(path);
165
+ }
166
+ }
167
+ var isHash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
168
+ 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)));
169
+ function versionParts(value) {
170
+ if (typeof value !== "string" || !/^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2}$/.test(value))
171
+ return;
172
+ const parts = value.split(".").map(Number);
173
+ if (parts.some((part) => !Number.isSafeInteger(part)))
174
+ return;
175
+ return [...parts, 0, 0].slice(0, 3);
176
+ }
177
+ function compareVersions(a, b) {
178
+ const left = versionParts(a);
179
+ const right = versionParts(b);
180
+ if (!left || !right)
181
+ return;
182
+ for (let i = 0; i < 3; i++)
183
+ if (left[i] !== right[i])
184
+ return left[i] - right[i];
185
+ return 0;
186
+ }
187
+ function validRange(range) {
188
+ return typeof range === "string" && range.trim().length > 0 && range.split(/\s+/).every((part) => {
189
+ const match = /^(?:>=|>|<=|<|=)?((?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2})$/.exec(part);
190
+ return Boolean(match && versionParts(match[1]));
191
+ });
192
+ }
193
+ function satisfies(version, range) {
194
+ return range.split(/\s+/).every((part) => {
195
+ const match = /^(>=|>|<=|<|=)?((?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2})$/.exec(part);
196
+ if (!match)
197
+ return false;
198
+ const comparison = compareVersions(version, match[2]);
199
+ if (comparison === void 0)
200
+ return false;
201
+ switch (match[1]) {
202
+ case ">=":
203
+ return comparison >= 0;
204
+ case ">":
205
+ return comparison > 0;
206
+ case "<=":
207
+ return comparison <= 0;
208
+ case "<":
209
+ return comparison < 0;
210
+ default:
211
+ return comparison === 0;
212
+ }
213
+ });
214
+ }
215
+ function verifyCompatibility(manifest, input) {
216
+ if (manifest.component !== input.expectedComponent)
217
+ throw new Error("component mismatch");
218
+ if (manifest.variant !== input.expectedVariant)
219
+ throw new Error("component variant mismatch");
220
+ if (manifest.productVersion !== input.expectedVersion)
221
+ throw new Error("product version mismatch");
222
+ if (canonicalArtifactJson(manifest.target) !== canonicalArtifactJson(input.target))
223
+ throw new Error("component target mismatch");
224
+ if (manifest.target.platform !== input.runtime.platform || manifest.target.architecture !== input.runtime.architecture)
225
+ throw new Error("runtime target mismatch");
226
+ if (!isVersion(input.runtime.version) || !isVersion(input.runtime.nodeVersion) || typeof input.runtime.modulesAbi !== "string" || !/^\d+$/.test(input.runtime.modulesAbi) || !Number.isSafeInteger(input.runtime.napiVersion) || input.runtime.napiVersion < 0)
227
+ throw new Error("runtime identity is invalid");
228
+ const versionMatches = manifest.runtimes.filter((item) => item.kind === input.runtime.kind && satisfies(input.runtime.version, item.runtimeRange) && satisfies(input.runtime.nodeVersion, item.nodeRange));
229
+ if (!versionMatches.length)
230
+ throw new Error("runtime version is incompatible; reinstall components from a release supporting this runtime");
231
+ const abiMatches = versionMatches.filter((item) => item.modulesAbi === void 0 || item.modulesAbi === input.runtime.modulesAbi);
232
+ if (!abiMatches.length)
233
+ throw new Error("runtime ABI mismatch; reinstall components from a release supporting this runtime");
234
+ const compatibility = abiMatches.find((item) => item.minimumNapi === void 0 || input.runtime.napiVersion >= item.minimumNapi);
235
+ if (!compatibility)
236
+ throw new Error("runtime N-API version is incompatible");
237
+ if (manifest.target.libc) {
238
+ const comparison = isVersion(input.runtime.libcVersion) ? compareVersions(input.runtime.libcVersion, manifest.target.libc.minimumVersion) : void 0;
239
+ if (comparison === void 0 || comparison < 0)
240
+ throw new Error("runtime libc version is incompatible");
241
+ }
242
+ }
243
+ function tarString(header, offset, length) {
244
+ const value = header.subarray(offset, offset + length);
245
+ const end = value.indexOf(0);
246
+ return value.subarray(0, end < 0 ? value.length : end).toString("utf8");
247
+ }
248
+ function tarNumber(header, offset, length) {
249
+ const text = tarString(header, offset, length).trim();
250
+ if (!/^[0-7]+$/.test(text))
251
+ throw new Error("malformed component tar numeric field");
252
+ const number = Number.parseInt(text, 8);
253
+ if (!Number.isSafeInteger(number))
254
+ throw new Error("component tar field exceeds safe integer range");
255
+ return number;
256
+ }
257
+ function* archiveChunks(archiveFd) {
258
+ let position = 0;
259
+ while (true) {
260
+ const buffer = Buffer.allocUnsafe(64 * 1024);
261
+ const bytesRead = readSync(archiveFd, buffer, 0, buffer.length, position);
262
+ if (bytesRead === 0)
263
+ return;
264
+ position += bytesRead;
265
+ yield buffer.subarray(0, bytesRead);
266
+ }
267
+ }
268
+ async function* tarBlocks(stream) {
269
+ let pending = Buffer.alloc(0);
270
+ let totalBytes = 0;
271
+ for await (const chunk of stream) {
272
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
273
+ while (pending.length >= 512) {
274
+ totalBytes += 512;
275
+ if (totalBytes > MAX_TAR_BYTES)
276
+ throw new Error("component archive exceeds expanded size limit");
277
+ yield pending.subarray(0, 512);
278
+ pending = pending.subarray(512);
279
+ }
280
+ }
281
+ if (pending.length)
282
+ throw new Error("component archive has partial tar block");
283
+ }
284
+ async function verifyTarArchive(archiveFd, manifest) {
285
+ const contents = /* @__PURE__ */ new Map();
286
+ const seenPaths = /* @__PURE__ */ new Set();
287
+ let expandedBytes = 0;
288
+ let zeroBlocks = 0;
289
+ let ended = false;
290
+ const gunzip = createGunzip();
291
+ const archiveSource = Readable.from(archiveChunks(archiveFd));
292
+ const blocks = tarBlocks(archiveSource.pipe(gunzip));
293
+ try {
294
+ for await (const header of blocks) {
295
+ if (ended) {
296
+ if (!header.every((byte) => byte === 0))
297
+ throw new Error("component archive contains data after tar terminator");
298
+ continue;
299
+ }
300
+ if (header.every((byte) => byte === 0)) {
301
+ zeroBlocks++;
302
+ if (zeroBlocks === 2)
303
+ ended = true;
304
+ continue;
305
+ }
306
+ if (zeroBlocks)
307
+ throw new Error("component archive has incomplete tar terminator");
308
+ const storedChecksum = tarNumber(header, 148, 8);
309
+ const check = Buffer.from(header);
310
+ check.fill(32, 148, 156);
311
+ if (storedChecksum !== check.reduce((sum, byte) => sum + byte, 0))
312
+ throw new Error("malformed component tar header checksum");
313
+ const type = tarString(header, 156, 1) || "0";
314
+ if (type === "1")
315
+ throw new Error("component archives must not contain hard links");
316
+ if (type === "2")
317
+ throw new Error("component archives must not contain symbolic links");
318
+ if (type !== "0" && type !== "5")
319
+ throw new Error(`unsupported component tar entry type: ${type}`);
320
+ const name = tarString(header, 0, 100);
321
+ const prefix = tarString(header, 345, 155);
322
+ const rawPath = prefix ? `${prefix}/${name}` : name;
323
+ const path = rawPath.replace(/\/$/, "");
324
+ safeRelativePath(path, "component archive path");
325
+ const size = tarNumber(header, 124, 12);
326
+ if (type === "5" && size !== 0)
327
+ throw new Error("component directory tar entry must be empty");
328
+ if (size > MAX_FILE_BYTES)
329
+ throw new Error("component archive entry exceeds individual file limit");
330
+ expandedBytes += size;
331
+ if (expandedBytes > MAX_EXPANDED_BYTES)
332
+ throw new Error("component archive exceeds expanded size limit");
333
+ if (seenPaths.has(path))
334
+ throw new Error(`duplicate component archive path: ${path}`);
335
+ seenPaths.add(path);
336
+ if (seenPaths.size > MAX_FILES)
337
+ throw new Error("component archive exceeds file count limit");
338
+ if (type === "5")
339
+ continue;
340
+ const digest = createHash("sha256");
341
+ let remaining = size;
342
+ while (remaining > 0) {
343
+ const data = await blocks.next();
344
+ if (data.done)
345
+ throw new Error("component archive is truncated");
346
+ const count = Math.min(remaining, 512);
347
+ digest.update(data.value.subarray(0, count));
348
+ remaining -= count;
349
+ }
350
+ contents.set(path, digest.digest("hex"));
351
+ }
352
+ } finally {
353
+ archiveSource.destroy();
354
+ gunzip.destroy();
355
+ }
356
+ if (!ended)
357
+ throw new Error("component archive is missing tar terminator");
358
+ for (const path of contents.keys()) {
359
+ const parents = path.split("/").slice(0, -1);
360
+ for (let index = 1; index <= parents.length; index++) {
361
+ const parentPath = parents.slice(0, index).join("/");
362
+ if (contents.has(parentPath))
363
+ throw new Error(`component archive file path conflict: ${parentPath}`);
364
+ }
365
+ }
366
+ const expected = new Map(manifest.files.map((file) => [file.path, file.sha256]));
367
+ if (contents.size !== expected.size)
368
+ throw new Error("component archive file inventory mismatch");
369
+ for (const [path, digest] of contents)
370
+ if (!expected.has(path) || digest !== expected.get(path))
371
+ throw new Error(`component archive file hash mismatch: ${path}`);
372
+ for (const required of manifest.requiredFiles)
373
+ if (!contents.has(required))
374
+ throw new Error(`required component file is missing: ${required}`);
375
+ }
376
+ function verifyComponentManifestPin(input) {
377
+ if (input.manifestBytes.length > MAX_MANIFEST_BYTES)
378
+ throw new Error("component manifest exceeds size limit");
379
+ let parsed;
380
+ try {
381
+ parsed = JSON.parse(input.manifestBytes.toString("utf8"));
382
+ } catch {
383
+ throw new Error("component manifest JSON is invalid");
384
+ }
385
+ validateComponentManifest(parsed);
386
+ const manifest = parsed;
387
+ const canonical = canonicalComponentManifestBytes(manifest);
388
+ if (!canonical.equals(input.manifestBytes))
389
+ throw new Error("component manifest is not canonical");
390
+ const pinnedDigest = lookupManifestPin(input.manifestCatalog, {
391
+ component: input.expectedComponent,
392
+ ...input.expectedVariant === void 0 ? {} : { variant: input.expectedVariant },
393
+ productVersion: input.expectedVersion,
394
+ target: input.target
395
+ });
396
+ if (createHash("sha256").update(canonical).digest("hex") !== pinnedDigest)
397
+ throw new Error("component manifest pin mismatch");
398
+ if (manifest.component !== input.expectedComponent)
399
+ throw new Error("component mismatch");
400
+ if (manifest.variant !== input.expectedVariant)
401
+ throw new Error("component variant mismatch");
402
+ if (manifest.productVersion !== input.expectedVersion)
403
+ throw new Error("product version mismatch");
404
+ if (canonicalArtifactJson(manifest.target) !== canonicalArtifactJson(input.target))
405
+ throw new Error("component target mismatch");
406
+ return manifest;
407
+ }
408
+ async function verifyComponentSync(input) {
409
+ const manifest = verifyComponentManifestPin(input);
410
+ verifyCompatibility(manifest, input);
411
+ const stat = lstatSync(input.archivePath);
412
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_ARCHIVE_BYTES)
413
+ throw new Error("component archive is not a bounded regular file");
414
+ if (basename(input.archivePath) !== manifest.archive.name)
415
+ throw new Error("component archive name mismatch");
416
+ if (stat.size !== manifest.archive.bytes)
417
+ throw new Error("component archive size mismatch");
418
+ if (constants.O_NOFOLLOW === void 0)
419
+ throw new Error("component archive no-follow access is unavailable");
420
+ const archiveFd = openSync(input.archivePath, constants.O_RDONLY | constants.O_NOFOLLOW);
421
+ try {
422
+ const opened = fstatSync(archiveFd);
423
+ if (!opened.isFile() || !sameObject(stat, opened))
424
+ throw new Error("component archive changed during verification");
425
+ const archiveHash = createHash("sha256");
426
+ for (const chunk of archiveChunks(archiveFd))
427
+ archiveHash.update(chunk);
428
+ if (!sameArchiveState(opened, fstatSync(archiveFd)))
429
+ throw new Error("component archive changed during verification");
430
+ if (archiveHash.digest("hex") !== manifest.archive.sha256)
431
+ throw new Error("component archive SHA-256 mismatch");
432
+ await verifyTarArchive(archiveFd, manifest);
433
+ if (!sameArchiveState(opened, fstatSync(archiveFd)))
434
+ throw new Error("component archive changed during verification");
435
+ } finally {
436
+ closeSync(archiveFd);
437
+ }
438
+ return manifest;
439
+ }
440
+ var verifyComponent = (input) => verifyComponentSync(input);
441
+ function hashFileDescriptor(fd) {
442
+ const digest = createHash("sha256");
443
+ let position = 0;
444
+ while (true) {
445
+ const buffer = Buffer.allocUnsafe(64 * 1024);
446
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
447
+ if (bytesRead === 0)
448
+ return digest.digest("hex");
449
+ digest.update(buffer.subarray(0, bytesRead));
450
+ position += bytesRead;
451
+ }
452
+ }
453
+ function sameObject(left, right) {
454
+ return left.dev === right.dev && left.ino === right.ino;
455
+ }
456
+ function sameArchiveState(left, right) {
457
+ return sameObject(left, right) && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
458
+ }
459
+ var EXTRACTED_TREE_LIMITS = {
460
+ maxFileBytes: MAX_FILE_BYTES,
461
+ maxExpandedBytes: MAX_EXPANDED_BYTES,
462
+ maxFiles: MAX_FILES,
463
+ maxDirectories: MAX_DIRECTORIES,
464
+ maxDepth: MAX_DEPTH,
465
+ maxEntries: MAX_FILES + MAX_DIRECTORIES
466
+ };
467
+ function verifyExtractedComponentSync(root, manifest, seams = {}) {
468
+ validateComponentManifest(manifest);
469
+ const canonicalRoot = resolve(root);
470
+ const rootStat = lstatSync(canonicalRoot);
471
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory())
472
+ throw new Error("component root is not a regular directory");
473
+ const observed = /* @__PURE__ */ new Set();
474
+ const expectedFiles = new Map(manifest.files.map((file) => [file.path, file.sha256]));
475
+ const limits = { ...EXTRACTED_TREE_LIMITS, ...seams.limits };
476
+ const stack = [canonicalRoot];
477
+ let directories = 0;
478
+ let entries = 0;
479
+ let totalBytes = 0;
480
+ while (stack.length) {
481
+ const current = stack.pop();
482
+ const beforeDirectory = lstatSync(current);
483
+ if (!beforeDirectory.isDirectory() || beforeDirectory.isSymbolicLink())
484
+ throw new Error("component directory ancestry changed during verification");
485
+ seams.beforeReadDirectory?.(current);
486
+ const directoryEntries = readdirSync(current, { withFileTypes: true });
487
+ for (const entry of directoryEntries) {
488
+ if (++entries > limits.maxEntries)
489
+ throw new Error("component tree exceeds entry count limit");
490
+ const path = resolve(current, entry.name);
491
+ const relativePath = relative(canonicalRoot, path).split(sep).join("/");
492
+ safeRelativePath(relativePath, "extracted component path");
493
+ const stat = lstatSync(path);
494
+ if (stat.isSymbolicLink() || !stat.isFile() && !stat.isDirectory())
495
+ throw new Error("component files must not contain links or special files");
496
+ if (stat.isDirectory()) {
497
+ if (++directories > limits.maxDirectories)
498
+ throw new Error("component tree exceeds directory count limit");
499
+ const depth = relativePath.split("/").length;
500
+ if (depth > limits.maxDepth)
501
+ throw new Error("component tree exceeds directory depth limit");
502
+ stack.push(path);
503
+ continue;
504
+ }
505
+ if (stat.nlink > 1)
506
+ throw new Error("component files must not contain links or special files");
507
+ if (stat.size > limits.maxFileBytes)
508
+ throw new Error("component file exceeds individual file limit");
509
+ totalBytes += stat.size;
510
+ if (totalBytes > limits.maxExpandedBytes)
511
+ throw new Error("component tree exceeds expanded size limit");
512
+ if (observed.size >= limits.maxFiles)
513
+ throw new Error("component tree exceeds file count limit");
514
+ observed.add(relativePath);
515
+ const expectedHash = expectedFiles.get(relativePath);
516
+ seams.beforeOpenFile?.(path);
517
+ if (constants.O_NOFOLLOW === void 0)
518
+ throw new Error("component file no-follow access is unavailable");
519
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
520
+ try {
521
+ const opened = fstatSync(fd);
522
+ if (!opened.isFile() || !sameObject(stat, opened))
523
+ throw new Error("component file changed during verification");
524
+ const fileHash = hashFileDescriptor(fd);
525
+ const after = fstatSync(fd);
526
+ const afterPath = lstatSync(path);
527
+ if (!sameArchiveState(opened, after) || !sameArchiveState(after, afterPath))
528
+ throw new Error("component file changed during verification");
529
+ if (!expectedHash || fileHash !== expectedHash)
530
+ throw new Error(`component file hash mismatch: ${relativePath}`);
531
+ } finally {
532
+ closeSync(fd);
533
+ }
534
+ }
535
+ if (!sameObject(beforeDirectory, lstatSync(current)))
536
+ throw new Error("component directory ancestry changed during verification");
537
+ }
538
+ for (const file of manifest.files)
539
+ if (!observed.has(file.path))
540
+ throw new Error(`required component file is missing or incomplete: ${file.path}`);
541
+ for (const file of manifest.requiredFiles)
542
+ if (!observed.has(file))
543
+ throw new Error(`required component file is missing: ${file}`);
544
+ }
545
+ var verifyExtractedComponent = (root, manifest) => Promise.resolve().then(() => verifyExtractedComponentSync(root, manifest));
546
+
547
+ // packages/koed-server/dist/native-macos-policy.js
548
+ var executables = new Set(`clusterdb createdb createuser dropdb dropuser ecpg initdb oid2name pg_amcheck pg_archivecleanup pg_basebackup pg_checksums pg_combinebackup pg_config pg_controldata pg_createsubscriber pg_ctl pg_dump pg_dumpall pg_isready pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_test_fsync pg_test_timing pg_upgrade pg_verifybackup pg_waldump pg_walsummary pgbench postgres postmaster psql reindexdb vacuumdb vacuumlo`.split(" "));
549
+ var shareFiles = new Set(`errcodes.txt information_schema.sql pg_hba.conf.sample pg_ident.conf.sample pg_service.conf.sample postgres.bki postgresql.conf.sample psqlrc.sample snowball_create.sql sql_features.txt system_constraints.sql system_functions.sql system_views.sql`.split(" "));
550
+ function permitsMacFilePath(path) {
551
+ if ([
552
+ "native-core-manifest.json",
553
+ "runtime-asset-manifest.json",
554
+ "llama.cpp/llama-server"
555
+ ].includes(path))
556
+ return true;
557
+ if (path.startsWith("postgres/bin/"))
558
+ return executables.has(path.slice("postgres/bin/".length));
559
+ if (path.startsWith("postgres/lib/"))
560
+ return /\.(?:so|dylib)$/i.test(path) || /^postgres\/lib\/(?:postgresql\/)?pkgconfig\/[\w.-]+\.pc$/.test(path) || /^postgres\/lib\/(?:postgresql\/)?pgxs\/config\/(?:install-sh|missing)$/.test(path);
561
+ if (path.startsWith("llama.cpp/metal/"))
562
+ return /^llama\.cpp\/metal\/(?:llama-server|LICENSE|ggml-metal\.metal|[\w.+-]+\.dylib)$/.test(path);
563
+ if (path.startsWith("third-party-licenses/"))
564
+ return /(?:^|\/|__)(?:LICEN[CS]E|NOTICE|COPYING|COPYRIGHT)(?:[._-][\w.-]+)?$/i.test(path);
565
+ if (!path.startsWith("postgres/share/"))
566
+ return false;
567
+ const shared = path.slice("postgres/share/".length).replace(/^postgresql\//, "");
568
+ return shareFiles.has(shared) || /^extension\/[\w.-]+\.(?:sql|control)$/.test(shared) || /^timezone\/[\w.+/-]+$/.test(shared) || /^timezonesets\/(?:Africa|America|Antarctica|Asia|Atlantic|Australia|Default|Etc|Europe|India|Indian|Pacific)(?:\.txt)?$/.test(shared) || /^tsearch_data\/[\w.-]+\.(?:stop|affix|dict|ths|syn|rules)$/.test(shared) || /^man\/man[1-9]\/[\w.+-]+\.[1-9](?:\.gz)?$/.test(shared) || /^locale\/[\w@.-]+\/LC_MESSAGES\/[\w.+-]+\.mo$/.test(shared) || /^doc\/[\w./+-]+\.(?:html|css|png|svg|txt|pdf|example)$/.test(shared);
569
+ }
570
+ function validateMacFile(path, header, mode) {
571
+ const magic = header.subarray(0, 4).toString("hex");
572
+ const arm64 = header.length >= 16 && magic === "cffaedfe" && header.readUInt32LE(4) === 16777228;
573
+ const library = /\.(?:so|dylib)$/i.test(path);
574
+ const validType = arm64 && (library ? [6, 8].includes(header.readUInt32LE(12)) : header.readUInt32LE(12) === 2);
575
+ const binaryPath = path.startsWith("postgres/bin/") && executables.has(path.slice(13)) || path.startsWith("postgres/lib/") && library || path.startsWith("llama.cpp/metal/") && (path === "llama.cpp/metal/llama-server" || /\.dylib$/i.test(path));
576
+ const macho = [
577
+ "cffaedfe",
578
+ "feedfacf",
579
+ "cafebabe",
580
+ "bebafeca",
581
+ "cafebabf",
582
+ "bfbafeca",
583
+ "cefaedfe",
584
+ "feedface"
585
+ ].includes(magic);
586
+ const foreign = magic === "7f454c46" || header.subarray(0, 2).toString() === "MZ" || /\.(?:exe|dll|so\.\d+(?:\.\d+)*)$/i.test(path) || /(?:^|\/)libcu(?:da|blas|dart)/i.test(path);
587
+ const script = (path === "llama.cpp/llama-server" || /^postgres\/lib\/(?:postgresql\/)?pgxs\/config\/(?:install-sh|missing)$/.test(path)) && header.subarray(0, 2).toString() === "#!";
588
+ const timezone = /^postgres\/share\/(?:postgresql\/)?timezone\//.test(path);
589
+ if (!permitsMacFilePath(path) || timezone && magic !== "545a6966" || foreign || macho && (!validType || !binaryPath) || library && !validType || path.startsWith("postgres/bin/") && !validType || (mode & 73) !== 0 && !arm64 && !script)
590
+ throw new Error(`Invalid macOS native file or executable: ${path}`);
591
+ }
592
+
593
+ // packages/koed-server/dist/native-payload-admission.js
594
+ var nativeDigest = (value) => createHash2("sha256").update(value).digest("hex");
595
+ function nativeJsonObject(bytes) {
596
+ const data = JSON.parse(bytes.toString("utf8"));
597
+ if (typeof data !== "object" || data === null || Array.isArray(data))
598
+ throw new Error("Invalid native metadata document.");
599
+ return data;
600
+ }
601
+ function readNativeMetadata(path, limit) {
602
+ const fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
603
+ try {
604
+ const stat = fstatSync2(fd);
605
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > limit)
606
+ throw new Error("Invalid native metadata file.");
607
+ return readFileSync(fd);
608
+ } finally {
609
+ closeSync2(fd);
610
+ }
611
+ }
612
+ function syncNativeDirectory(path) {
613
+ const fd = openSync2(path, constants2.O_RDONLY | constants2.O_DIRECTORY | constants2.O_NOFOLLOW);
614
+ try {
615
+ fsyncSync(fd);
616
+ } finally {
617
+ closeSync2(fd);
618
+ }
619
+ }
620
+ function nativeFileDigest(path, bytes, durable = false) {
621
+ const fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
622
+ try {
623
+ const stat = fstatSync2(fd);
624
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size !== bytes)
625
+ throw new Error(`Native file size or type changed: ${path}`);
626
+ const digest = hashFileDescriptor(fd);
627
+ if (durable)
628
+ fsyncSync(fd);
629
+ return digest;
630
+ } finally {
631
+ closeSync2(fd);
632
+ }
633
+ }
634
+ function checkMacFile(file, path, mode) {
635
+ const fd = openSync2(file, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
636
+ try {
637
+ const header = Buffer.alloc(16);
638
+ const length = readSync2(fd, header, 0, header.length, 0);
639
+ validateMacFile(path, header.subarray(0, length), mode);
640
+ } finally {
641
+ closeSync2(fd);
642
+ }
643
+ }
644
+ function permitsNativeEntry(kind, path, directory, platform = "linux") {
645
+ if (path === "")
646
+ return directory;
647
+ if (kind === "core") {
648
+ if (platform === "linux")
649
+ return !["cuda", "metal"].some((backend) => path === `llama.cpp/${backend}` || path.startsWith(`llama.cpp/${backend}/`));
650
+ if (!directory)
651
+ return permitsMacFilePath(path);
652
+ return path === "postgres" || path.startsWith("postgres/") || path === "llama.cpp" || path === "llama.cpp/metal" || path === "third-party-licenses" || path.startsWith("third-party-licenses/");
653
+ }
654
+ if (path === "llama.cpp" || path === "llama.cpp/cuda")
655
+ return directory;
656
+ return path.startsWith("llama.cpp/cuda/") && !/(?:^|\/)libcuda\.so(?:\.\d+)*$/.test(path);
657
+ }
658
+ function verifyNativePayload(root, pin, durable = false) {
659
+ const kind = nativeKind(pin);
660
+ const name = kind === "core" ? "native-core-manifest.json" : "llama.cpp/cuda/native-cuda-manifest.json";
661
+ const boundary = kind === "core" ? root : resolve2(root, "llama.cpp/cuda");
662
+ if (!lstatSync2(root).isDirectory() || kind === "cuda" && ![dirname(boundary), boundary].every((path) => lstatSync2(path).isDirectory()))
663
+ throw new Error("Native payload directory links are not allowed.");
664
+ const file = resolve2(root, name);
665
+ const raw = readNativeMetadata(file, 8 * 1024 * 1024);
666
+ if (nativeDigest(raw) !== pin.manifestSha256 || (lstatSync2(file).mode & 4095) !== 420)
667
+ throw new Error(`Native ${kind} manifest differs from the admitted digest or mode.`);
668
+ const manifest = nativeJsonObject(raw);
669
+ if (manifest.kind !== kind || manifest.schemaVersion !== 1 || manifest.recipeId !== pin.recipeId || nativeDigest(canonicalArtifactJson(manifest.recipe)) !== pin.recipeId || manifest.runtimeVersion !== pin.runtimeVersion || canonicalArtifactJson(manifest.target) !== canonicalArtifactJson(pin.target) || canonicalArtifactJson(manifest.contracts) !== canonicalArtifactJson(pin.contracts) || ("components" in pin ? canonicalArtifactJson(manifest.components) !== canonicalArtifactJson(pin.components) : canonicalArtifactJson(manifest.llamaCpp) !== canonicalArtifactJson(pin.llamaCpp) || canonicalArtifactJson(manifest.cuda) !== canonicalArtifactJson(pin.cuda)))
670
+ throw new Error(`Native ${kind} manifest is incompatible with its pin.`);
671
+ if (!Array.isArray(manifest.inventory))
672
+ throw new Error("Missing native payload inventory.");
673
+ const inventory = manifest.inventory;
674
+ let index = 0;
675
+ const check = (entry) => {
676
+ if (index >= inventory.length || canonicalArtifactJson(entry) !== canonicalArtifactJson(inventory[index++]))
677
+ throw new Error(`Native ${kind} inventory changed at ${entry.path}. Inspect the damaged payload before repair.`);
678
+ };
679
+ let expanded = raw.length;
680
+ const required = /* @__PURE__ */ new Set([
681
+ "postgres/bin/postgres",
682
+ "postgres/bin/initdb",
683
+ "postgres/bin/pg_ctl",
684
+ "postgres/bin/psql",
685
+ "postgres/bin/pg_dump",
686
+ "postgres/bin/pg_restore",
687
+ "postgres/lib/vector.so",
688
+ "postgres/lib/pgcrypto.so",
689
+ "llama.cpp/llama-server",
690
+ "llama.cpp/metal/llama-server"
691
+ ]);
692
+ const walk = (directory) => {
693
+ let files = 0;
694
+ for (const entry of readdirSync2(directory).sort()) {
695
+ const path = resolve2(directory, entry), key = relative2(root, path);
696
+ if (key === name)
697
+ continue;
698
+ const stat = lstatSync2(path), mode = stat.mode & 4095;
699
+ if (pin.target.platform === "macos" && (mode & 3584) !== 0)
700
+ throw new Error(`Invalid macOS native special permission bits: ${key}`);
701
+ if (!permitsNativeEntry(kind, key, stat.isDirectory(), pin.target.platform))
702
+ throw new Error(`Unexpected native ${kind} entry: ${key}`);
703
+ if (stat.isDirectory()) {
704
+ if (pin.target.platform === "macos" && mode !== 493)
705
+ throw new Error(`Invalid macOS native directory mode: ${key}`);
706
+ check({ path: key, type: "directory", mode });
707
+ const descendants = walk(path);
708
+ if (pin.target.platform === "macos" && descendants === 0)
709
+ throw new Error(`Unexpected native ${kind} empty directory: ${key}`);
710
+ files += descendants;
711
+ } else if (stat.isFile()) {
712
+ files++;
713
+ if (required.has(key) && (!(key.startsWith("postgres/bin/") || key.endsWith("llama-server")) || (mode & 73) !== 0))
714
+ required.delete(key);
715
+ if (pin.target.platform === "macos")
716
+ checkMacFile(path, key, mode);
717
+ expanded += stat.size;
718
+ if (expanded > pin.expandedBytes)
719
+ throw new Error("Native inventory exceeds its pinned size.");
720
+ check({
721
+ path: key,
722
+ type: "file",
723
+ mode,
724
+ bytes: stat.size,
725
+ sha256: nativeFileDigest(path, stat.size, durable)
726
+ });
727
+ } else if (stat.isSymbolicLink()) {
728
+ const target = readlinkSync(path), dest = resolve2(dirname(path), target);
729
+ const rel = relative2(boundary, dest);
730
+ if (isAbsolute2(target) || rel.startsWith("../") || rel === ".." || !lstatSync2(dest).isFile() || realpathSync(path) !== resolve2(realpathSync(root), relative2(root, dest)))
731
+ throw new Error(`Unsafe native library link: ${key}`);
732
+ if (pin.target.platform === "macos")
733
+ checkMacFile(dest, key, lstatSync2(dest).mode & 511);
734
+ files++;
735
+ check({ path: key, type: "symlink", mode: 511, target });
736
+ } else
737
+ throw new Error(`Unsupported native file: ${key}`);
738
+ }
739
+ if (durable)
740
+ syncNativeDirectory(directory);
741
+ return files;
742
+ };
743
+ if (durable)
744
+ nativeFileDigest(file, raw.length, true);
745
+ walk(root);
746
+ if (pin.target.platform === "macos" && kind === "core" && required.size)
747
+ throw new Error(`Native macOS core is missing required executable or library: ${[...required][0]}`);
748
+ if (expanded !== pin.expandedBytes || index !== inventory.length)
749
+ throw new Error(`Native ${kind} inventory changed. Inspect the installed payload before repair.`);
750
+ }
751
+
752
+ // packages/koed-server/dist/package-runtime.js
753
+ import { createHash as createHash3, createPublicKey, verify } from "node:crypto";
754
+ import { createGunzip as createGunzip2 } from "node:zlib";
755
+ import { chmodSync, closeSync as closeSync3, cpSync, createReadStream, createWriteStream, existsSync, lstatSync as lstatSync3, openSync as openSync3, mkdirSync, readFileSync as readFileSync2, readdirSync as readdirSync3, readlinkSync as readlinkSync2, renameSync, rmSync, symlinkSync, writeSync } from "node:fs";
756
+ import { constants as fsConstants, statSync } from "node:fs";
757
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute3, posix, relative as relative3, resolve as resolve3 } from "node:path";
758
+ import { pipeline } from "node:stream/promises";
759
+ import { Readable as Readable2, Transform } from "node:stream";
760
+ var standalonePackageSchemaVersion = 2;
761
+ var standalonePackageId = "koed-server";
762
+ var standalonePackageKind = "app-runtime";
763
+ var packageProvenanceSchemaVersion = 1;
764
+ var packageExtractionLimits = {
765
+ compressedBytes: 2 * 1024 * 1024 * 1024,
766
+ expandedBytes: 8 * 1024 * 1024 * 1024,
767
+ fileCount: 2e5,
768
+ individualFileBytes: 2 * 1024 * 1024 * 1024,
769
+ pathBytes: 4096,
770
+ manifestBytes: 8 * 1024 * 1024,
771
+ paxHeaderBytes: 1024 * 1024
772
+ };
773
+ var requiredPackageRuntimeFiles = [
774
+ "api/dist/index.js",
775
+ "worker/dist/index.js",
776
+ "embedding-service/dist/index.js",
777
+ "mcp-server/dist/cli.js",
778
+ "mcp-server/dist/capture-hook.js",
779
+ "mcp-server/dist/prompts/codex-global-agent-guidance.md",
780
+ "node_modules/@koed-labs/db/dist/index.js",
781
+ "node_modules/@koed-labs/db/dist/connection.js",
782
+ "node_modules/@koed-labs/db/dist/user-api-token-repository.js",
783
+ "node_modules/@koed-labs/db/drizzle/meta/_journal.json"
784
+ ];
785
+ var excludedPackagePatterns = [
786
+ /^koed-runtime\/explorer-dist(?:\/|$)/,
787
+ /^koed-server\/dist\/explorer-static-(?:proxy|server)(?:\.|$)/,
788
+ /^koed-runtime\/postgres(?:\/|$)/,
789
+ /^koed-runtime\/llama\.cpp(?:\/|$)/,
790
+ /^koed-runtime\/runtime-asset-manifest\.json$/,
791
+ /^koed-runtime\/.*\.gguf$/,
792
+ /^koed-runtime\/.*\.safetensors$/,
793
+ /^koed-runtime\/.*\.onnx$/,
794
+ /^koed-runtime\/embedding-service\/\.venv(?:\/|$)/,
795
+ /^koed-runtime\/embedding-service\/.*\.py$/,
796
+ /^koed-runtime\/embedding-service\/requirements\.txt$/,
797
+ /^koed-runtime\/embedding-service\/pyproject\.toml$/
798
+ ];
799
+ var platformKey = (platform = process.platform) => {
800
+ if (platform === "darwin")
801
+ return "macos";
802
+ if (platform === "win32")
803
+ return "windows";
804
+ return platform;
805
+ };
806
+ var normalizeSha256 = (value) => {
807
+ const normalized = value.trim().toLowerCase().split(/\s+/)[0] ?? "";
808
+ if (!/^[a-f0-9]{64}$/.test(normalized)) {
809
+ throw new Error("Package SHA-256 must be 64 hex characters.");
810
+ }
811
+ return normalized;
812
+ };
813
+ var validatePackageVersion = (version) => {
814
+ if (!/^[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(version)) {
815
+ throw new Error("Package version must be a safe filename segment containing only letters, numbers, dots, underscores, plus signs, or hyphens.");
816
+ }
817
+ if (version === "." || version === ".." || version.includes("..")) {
818
+ throw new Error("Package version must not contain path traversal.");
819
+ }
820
+ return version;
821
+ };
822
+ var isInside = (base, child) => {
823
+ const rel = relative3(resolve3(base), resolve3(child));
824
+ return rel === "" || !rel.startsWith("..") && rel !== "..";
825
+ };
826
+ var safeResolve = (base, path) => {
827
+ if (path.includes("\0")) {
828
+ throw new Error(`Package path contains NUL byte: ${path}`);
829
+ }
830
+ const resolved = resolve3(base, path);
831
+ if (!isInside(base, resolved)) {
832
+ throw new Error(`Package path escapes base directory: ${path}`);
833
+ }
834
+ return resolved;
835
+ };
836
+ var packageRoot = (paths) => resolve3(paths.koedHome, "runtime", "koed-server");
837
+ var packageVersionsDir = (paths) => resolve3(packageRoot(paths), "versions");
838
+ var packageCacheDir = (paths) => resolve3(paths.cacheDir, "koed-server-packages");
839
+ var packageCurrentPath = (paths) => resolve3(packageRoot(paths), "current");
840
+ var listFiles = (root, dir = root) => readdirSync3(dir, { withFileTypes: true }).flatMap((entry) => {
841
+ const path = resolve3(dir, entry.name);
842
+ const relativePath = relative3(root, path).replaceAll("\\", "/");
843
+ if (entry.isDirectory())
844
+ return listFiles(root, path);
845
+ return [relativePath];
846
+ });
847
+ var sha256File = (path) => {
848
+ const hash = createHash3("sha256");
849
+ const stat = lstatSync3(path);
850
+ if (stat.isSymbolicLink()) {
851
+ hash.update("symlink");
852
+ hash.update("\0");
853
+ hash.update(readlinkSync2(path));
854
+ } else {
855
+ hash.update(readFileSync2(path));
856
+ }
857
+ return hash.digest("hex");
858
+ };
859
+ var sha256Files = (root, files) => {
860
+ const hash = createHash3("sha256");
861
+ for (const file of [...new Set(files)].sort()) {
862
+ const path = resolve3(root, file);
863
+ const stat = lstatSync3(path);
864
+ if (stat.isDirectory())
865
+ continue;
866
+ hash.update(file.replaceAll("\\", "/"));
867
+ hash.update("\0");
868
+ if (stat.isSymbolicLink()) {
869
+ hash.update("symlink");
870
+ hash.update("\0");
871
+ hash.update(readlinkSync2(path));
872
+ } else {
873
+ hash.update(readFileSync2(path));
874
+ }
875
+ hash.update("\0");
876
+ }
877
+ return hash.digest("hex");
878
+ };
879
+ var readJson = (path) => JSON.parse(readFileSync2(path, "utf8"));
880
+ var compareIdentifiers = (left, right) => {
881
+ if (left === right)
882
+ return 0;
883
+ const leftNumeric = /^\d+$/.test(left);
884
+ const rightNumeric = /^\d+$/.test(right);
885
+ if (leftNumeric && rightNumeric)
886
+ return BigInt(left) < BigInt(right) ? -1 : BigInt(left) > BigInt(right) ? 1 : 0;
887
+ if (leftNumeric !== rightNumeric)
888
+ return leftNumeric ? -1 : 1;
889
+ return left < right ? -1 : 1;
890
+ };
891
+ var compareVersions2 = (a, b) => {
892
+ const parts = (version) => {
893
+ const withoutBuild = version.split("+")[0];
894
+ const separator = withoutBuild.indexOf("-");
895
+ return {
896
+ core: (separator < 0 ? withoutBuild : withoutBuild.slice(0, separator)).split("."),
897
+ prerelease: separator < 0 ? [] : withoutBuild.slice(separator + 1).split(".")
898
+ };
899
+ };
900
+ const left = parts(a), right = parts(b);
901
+ for (let index = 0; index < 3; index++) {
902
+ const order = compareIdentifiers(left.core[index] ?? "0", right.core[index] ?? "0");
903
+ if (order)
904
+ return order;
905
+ }
906
+ if (!left.prerelease.length || !right.prerelease.length)
907
+ return Number(right.prerelease.length > 0) - Number(left.prerelease.length > 0);
908
+ for (let index = 0; index < Math.max(left.prerelease.length, right.prerelease.length); index++) {
909
+ const l = left.prerelease[index], r = right.prerelease[index];
910
+ if (l === void 0)
911
+ return -1;
912
+ if (r === void 0)
913
+ return 1;
914
+ const order = compareIdentifiers(l, r);
915
+ if (order)
916
+ return order;
917
+ }
918
+ return 0;
919
+ };
920
+ var validateManifestShape = (manifest) => {
921
+ const errors = [];
922
+ if (!manifest || typeof manifest !== "object") {
923
+ return ["Package manifest must be an object."];
924
+ }
925
+ if (manifest.schemaVersion !== standalonePackageSchemaVersion) {
926
+ errors.push("Package manifest schemaVersion must be 2 for shared staging; upgrade koed-server or rebuild the package with the current release tooling.");
927
+ }
928
+ if (manifest.id !== standalonePackageId) {
929
+ errors.push("Package manifest id must be koed-server.");
930
+ }
931
+ if (manifest.packageKind !== standalonePackageKind) {
932
+ errors.push("Package manifest packageKind must be app-runtime.");
933
+ }
934
+ for (const key of [
935
+ "version",
936
+ "platform",
937
+ "architecture",
938
+ "createdAt"
939
+ ]) {
940
+ const value = manifest[key];
941
+ if (typeof value !== "string" || value.length === 0) {
942
+ errors.push(`Package manifest ${key} must be a non-empty string.`);
943
+ }
944
+ }
945
+ if (typeof manifest.version === "string" && manifest.version.length > 0) {
946
+ try {
947
+ validatePackageVersion(manifest.version);
948
+ } catch (error) {
949
+ errors.push(error instanceof Error ? error.message : String(error));
950
+ }
951
+ }
952
+ if (manifest.koedRuntime?.path !== "koed-runtime") {
953
+ errors.push("Package manifest koedRuntime.path must be koed-runtime.");
954
+ }
955
+ if (!Array.isArray(manifest.koedRuntime?.requiredFiles)) {
956
+ errors.push("Package manifest koedRuntime.requiredFiles must be an array.");
957
+ }
958
+ if (!Array.isArray(manifest.files)) {
959
+ errors.push("Package manifest files must be an array.");
960
+ }
961
+ if (!/^[a-f0-9]{64}$/.test(manifest.sha256 ?? "")) {
962
+ errors.push("Package manifest sha256 must be 64 hex characters.");
963
+ }
964
+ if (!manifest.database || typeof manifest.database !== "object") {
965
+ errors.push("Package manifest database must be an object.");
966
+ }
967
+ if (!manifest.provenance || typeof manifest.provenance !== "object") {
968
+ errors.push("Package manifest provenance must be an object.");
969
+ }
970
+ return errors;
971
+ };
972
+ var validateCompatibility = (manifest, platform = platformKey(), architecture = process.arch, nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "0", 10)) => {
973
+ if (!manifest)
974
+ return [];
975
+ const errors = [];
976
+ if (manifest.platform !== platform) {
977
+ errors.push(`Package platform ${manifest.platform} is incompatible with ${platform}.`);
978
+ }
979
+ if (manifest.architecture !== architecture) {
980
+ errors.push(`Package architecture ${manifest.architecture} is incompatible with ${architecture}.`);
981
+ }
982
+ const minimumNodeMajor = manifest.nodeRuntime?.minimumNodeMajor;
983
+ if (typeof minimumNodeMajor === "number" && Number.isFinite(minimumNodeMajor) && nodeMajor < minimumNodeMajor) {
984
+ errors.push(`Package requires Node ${minimumNodeMajor} or newer; current Node major is ${nodeMajor}.`);
985
+ }
986
+ return errors;
987
+ };
988
+ var validateServerPackageRoot = (root) => {
989
+ const resolvedRoot = resolve3(root);
990
+ const manifestPath = resolve3(resolvedRoot, "koed-server-package-manifest.json");
991
+ const manifest = existsSync(manifestPath) ? readJson(manifestPath) : null;
992
+ const manifestErrors = validateManifestShape(manifest);
993
+ const runtimePath = manifest?.koedRuntime?.path ?? "koed-runtime";
994
+ const runtimeRoot = resolve3(resolvedRoot, runtimePath);
995
+ const requiredFiles = Array.isArray(manifest?.koedRuntime?.requiredFiles) ? manifest.koedRuntime.requiredFiles : requiredPackageRuntimeFiles;
996
+ const missing = [
997
+ !existsSync(manifestPath) ? "koed-server-package-manifest.json" : null,
998
+ !existsSync(resolve3(resolvedRoot, "README.txt")) ? "README.txt" : null,
999
+ !existsSync(resolve3(resolvedRoot, "bin", "koed")) && !existsSync(resolve3(resolvedRoot, "bin", "koed-server")) ? "bin/koed" : null,
1000
+ !existsSync(resolve3(runtimeRoot, "koed-server", "dist", "cli.js")) ? "koed-runtime/koed-server/dist/cli.js" : null,
1001
+ ...requiredFiles.map((file) => existsSync(resolve3(runtimeRoot, file)) ? null : `${runtimePath}/${file}`)
1002
+ ].filter((file) => Boolean(file));
1003
+ const files = existsSync(resolvedRoot) ? listFiles(resolvedRoot) : [];
1004
+ const excluded = files.filter((file) => excludedPackagePatterns.some((pattern) => pattern.test(file)));
1005
+ const actualFiles = files.filter((file) => file !== "koed-server-package-manifest.json");
1006
+ const actualSha256 = existsSync(resolvedRoot) && actualFiles.length > 0 ? sha256Files(resolvedRoot, actualFiles) : void 0;
1007
+ const manifestFileErrors = Array.isArray(manifest?.files) ? manifest.files.flatMap((entry) => {
1008
+ if (!entry || typeof entry.path !== "string" || !/^[a-f0-9]{64}$/.test(entry.sha256 ?? "")) {
1009
+ return ["Package manifest files entries require path and sha256."];
1010
+ }
1011
+ const path = safeResolve(resolvedRoot, entry.path);
1012
+ if (!existsSync(path))
1013
+ return [`Manifest file is missing: ${entry.path}`];
1014
+ const actual = sha256File(path);
1015
+ return actual === entry.sha256 ? [] : [`Manifest file SHA-256 mismatch: ${entry.path}`];
1016
+ }) : [];
1017
+ const shaErrors = manifest?.sha256 && actualSha256 && manifest.sha256 !== actualSha256 ? ["Package manifest sha256 does not match package files."] : [];
1018
+ const compatibilityErrors = validateCompatibility(manifest);
1019
+ const errors = [
1020
+ ...manifestErrors,
1021
+ ...missing.map((file) => `Missing required package file: ${file}`),
1022
+ ...excluded.map((file) => `Excluded file is present: ${file}`),
1023
+ ...manifestFileErrors,
1024
+ ...shaErrors,
1025
+ ...compatibilityErrors
1026
+ ];
1027
+ return {
1028
+ ok: errors.length === 0,
1029
+ packageRoot: resolvedRoot,
1030
+ manifestPath,
1031
+ manifest,
1032
+ version: manifest?.version,
1033
+ errors
1034
+ };
1035
+ };
1036
+ var summarizeManifest = (manifest) => {
1037
+ if (!manifest)
1038
+ return null;
1039
+ return {
1040
+ schemaVersion: manifest.schemaVersion,
1041
+ id: manifest.id,
1042
+ version: manifest.version,
1043
+ platform: manifest.platform,
1044
+ architecture: manifest.architecture,
1045
+ packageKind: manifest.packageKind,
1046
+ createdAt: manifest.createdAt,
1047
+ ...manifest.minimumDesktopVersion ? { minimumDesktopVersion: manifest.minimumDesktopVersion } : {},
1048
+ ...manifest.maximumDesktopMajor !== void 0 ? { maximumDesktopMajor: manifest.maximumDesktopMajor } : {},
1049
+ ...manifest.nodeRuntime ? { nodeRuntime: manifest.nodeRuntime } : {},
1050
+ ...manifest.koedRuntime ? { koedRuntime: manifest.koedRuntime } : {},
1051
+ ...manifest.database ? { database: manifest.database } : {},
1052
+ ...manifest.provenance ? { provenance: manifest.provenance } : {},
1053
+ ...manifest.sha256 ? { sha256: manifest.sha256 } : {},
1054
+ fileCount: manifest.files?.length ?? 0
1055
+ };
1056
+ };
1057
+ var readCurrentTarget = (paths) => {
1058
+ const current = packageCurrentPath(paths);
1059
+ if (!existsSync(current))
1060
+ return void 0;
1061
+ const stat = lstatSync3(current);
1062
+ return stat.isSymbolicLink() ? resolve3(dirname2(current), readlinkSync2(current)) : current;
1063
+ };
1064
+ var collectServerPackageStatus = (paths) => {
1065
+ const root = packageRoot(paths);
1066
+ const versionsDir = packageVersionsDir(paths);
1067
+ const cacheDir = packageCacheDir(paths);
1068
+ const currentPath = packageCurrentPath(paths);
1069
+ const currentTarget = readCurrentTarget(paths);
1070
+ const versionNames = existsSync(versionsDir) ? readdirSync3(versionsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort() : [];
1071
+ const installed = versionNames.map((version) => {
1072
+ const path = resolve3(versionsDir, version);
1073
+ const validation = validateServerPackageRoot(path);
1074
+ return {
1075
+ version,
1076
+ path,
1077
+ ok: validation.ok,
1078
+ active: currentTarget === path,
1079
+ manifest: summarizeManifest(validation.manifest),
1080
+ errors: validation.errors
1081
+ };
1082
+ });
1083
+ const active = installed.find((entry) => entry.active);
1084
+ const invalid = installed.filter((entry) => !entry.ok);
1085
+ const currentVersion = active?.version;
1086
+ const state = installed.length === 0 ? "missing" : active && active.ok && invalid.length === 0 ? "installed" : active && !active.ok ? "incompatible" : "partial";
1087
+ return {
1088
+ ok: state === "installed",
1089
+ state,
1090
+ koedHome: paths.koedHome,
1091
+ packageRoot: root,
1092
+ versionsDir,
1093
+ cacheDir,
1094
+ currentPath,
1095
+ ...currentVersion ? { currentVersion } : {},
1096
+ ...currentTarget ? { currentTarget } : {},
1097
+ installed,
1098
+ message: state === "installed" ? `koed-server package ${currentVersion} is active.` : state === "missing" ? "No koed-server package is installed." : "koed-server package installation needs attention.",
1099
+ ...state === "missing" ? {
1100
+ action: "Run koed package install --source <artifact> --sha256 <sha256>."
1101
+ } : {},
1102
+ ...invalid.length > 0 ? { errors: invalid.flatMap((entry) => entry.errors) } : {}
1103
+ };
1104
+ };
1105
+ var readExpectedSha256 = (options) => {
1106
+ if (options.sha256)
1107
+ return normalizeSha256(options.sha256);
1108
+ if (options.sha256File) {
1109
+ return normalizeSha256(readFileSync2(options.sha256File, "utf8"));
1110
+ }
1111
+ throw new Error("--sha256 or --sha256-file is required.");
1112
+ };
1113
+ var extractVerifiedPackageArchive = (archivePath, destination) => extractTarGz(archivePath, destination);
1114
+ var adjacentProvenancePath = (archivePath) => {
1115
+ const archiveName = basename2(archivePath);
1116
+ const releaseName = archiveName.replace(/^koed-server-/, "koed-server-app-runtime-").replace(/\.tar\.gz$/, ".provenance.json");
1117
+ const candidates = [
1118
+ `${archivePath}.provenance.json`,
1119
+ archivePath.replace(/\.tar\.gz$/, ".provenance.json"),
1120
+ resolve3(dirname2(archivePath), releaseName)
1121
+ ];
1122
+ return candidates.find((candidate) => existsSync(candidate));
1123
+ };
1124
+ var readTrustedPublicKey = (options) => {
1125
+ if (options.trustedPublicKey)
1126
+ return options.trustedPublicKey;
1127
+ if (options.trustedPublicKeyFile) {
1128
+ return readFileSync2(options.trustedPublicKeyFile, "utf8");
1129
+ }
1130
+ return process.env.KOED_SERVER_PACKAGE_TRUSTED_PUBLIC_KEY_PEM;
1131
+ };
1132
+ var verifyProvenanceSignature = ({ provenance, signature, publicKey }) => {
1133
+ if (provenance.signature?.algorithm !== "ed25519") {
1134
+ throw new Error("Package provenance signature algorithm must be ed25519.");
1135
+ }
1136
+ const key = createPublicKey(publicKey);
1137
+ const payload = canonicalArtifactBytes(provenance.statement);
1138
+ const ok = verify(null, payload, key, Buffer.from(signature, "base64"));
1139
+ if (!ok) {
1140
+ throw new Error("Package provenance signature verification failed.");
1141
+ }
1142
+ };
1143
+ var validatePackageProvenance = ({ options, archivePath, archiveSha256, manifest }) => {
1144
+ const policy = options.trustPolicy ?? "sha256-only";
1145
+ const provenancePath = options.provenanceFile ?? adjacentProvenancePath(archivePath);
1146
+ const publicKey = readTrustedPublicKey(options);
1147
+ if (!provenancePath) {
1148
+ if (policy === "sha256-only" && !publicKey) {
1149
+ return { status: "not_checked", policy };
1150
+ }
1151
+ throw new Error("Package provenance metadata is required.");
1152
+ }
1153
+ const provenance = readJson(provenancePath);
1154
+ const statement = provenance.statement;
1155
+ if (statement?.schemaVersion !== packageProvenanceSchemaVersion) {
1156
+ throw new Error("Package provenance schemaVersion must be 1.");
1157
+ }
1158
+ const subject = statement.subject;
1159
+ if (subject?.id !== manifest.id || subject.packageKind !== manifest.packageKind) {
1160
+ throw new Error("Package provenance subject does not match manifest.");
1161
+ }
1162
+ if (subject.version !== manifest.version || subject.platform !== manifest.platform || subject.architecture !== manifest.architecture) {
1163
+ throw new Error("Package provenance version target does not match manifest.");
1164
+ }
1165
+ if (subject.archiveSha256 !== archiveSha256) {
1166
+ throw new Error("Package provenance archive SHA-256 does not match.");
1167
+ }
1168
+ if (subject.packageSha256 !== manifest.sha256) {
1169
+ throw new Error("Package provenance package SHA-256 does not match.");
1170
+ }
1171
+ const inlineSignature = provenance.signature?.value ?? void 0;
1172
+ const signaturePath = options.signatureFile ?? (existsSync(`${provenancePath}.sig`) ? `${provenancePath}.sig` : void 0);
1173
+ const signature = signaturePath ? readFileSync2(signaturePath, "utf8").trim() : inlineSignature;
1174
+ if (publicKey) {
1175
+ if (!signature) {
1176
+ throw new Error("Package provenance signature is required.");
1177
+ }
1178
+ verifyProvenanceSignature({ provenance, signature, publicKey });
1179
+ return { status: "verified", policy, source: provenancePath };
1180
+ }
1181
+ if (policy === "require-signature") {
1182
+ throw new Error("Package signature trust root is required.");
1183
+ }
1184
+ if (provenance.signature?.status === "unsigned-placeholder") {
1185
+ return { status: "unsigned-placeholder", policy, source: provenancePath };
1186
+ }
1187
+ return { status: "not_checked", policy, source: provenancePath };
1188
+ };
1189
+ var activePackageManifest = (paths) => {
1190
+ const target = readCurrentTarget(paths);
1191
+ if (!target)
1192
+ return null;
1193
+ const validation = validateServerPackageRoot(target);
1194
+ return validation.ok ? validation.manifest : null;
1195
+ };
1196
+ var migrationTimestamp = (manifest) => {
1197
+ const value = manifest?.database?.migrationSet?.latestMigrationTimestamp;
1198
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1199
+ };
1200
+ var isVersionDowngrade = (currentVersion, candidateVersion) => compareVersions2(candidateVersion, currentVersion) < 0;
1201
+ var assertPackageMigrationCompatible = (currentManifest, nextManifest, allowDowngrade = false) => {
1202
+ if (!isVersionDowngrade(currentManifest.version, nextManifest.version))
1203
+ return;
1204
+ if (!allowDowngrade) {
1205
+ throw new Error(`Installing koed-server ${nextManifest.version} over active ${currentManifest.version} is a downgrade and requires --allow-downgrade.`);
1206
+ }
1207
+ const currentMigration = migrationTimestamp(currentManifest);
1208
+ const nextMigration = migrationTimestamp(nextManifest);
1209
+ if (currentMigration !== void 0 && nextMigration !== void 0 && nextMigration < currentMigration && nextManifest.database?.allowsRollback !== true) {
1210
+ throw new Error("Downgrade would roll back the package migration set, and the target package does not allow rollback.");
1211
+ }
1212
+ };
1213
+ var assertUpgradeCompatible = ({ paths, nextManifest, allowDowngrade = false }) => {
1214
+ const currentManifest = activePackageManifest(paths);
1215
+ if (!currentManifest?.version)
1216
+ return;
1217
+ assertPackageMigrationCompatible(currentManifest, nextManifest, allowDowngrade);
1218
+ };
1219
+ var copyAdjacentProvenanceSidecars = (sourcePath, targetPath) => {
1220
+ const provenancePath = adjacentProvenancePath(sourcePath);
1221
+ if (!provenancePath)
1222
+ return;
1223
+ const targetProvenancePath = resolve3(dirname2(targetPath), basename2(provenancePath));
1224
+ if (provenancePath !== targetProvenancePath) {
1225
+ cpSync(provenancePath, targetProvenancePath);
1226
+ }
1227
+ const signaturePath = `${provenancePath}.sig`;
1228
+ if (!existsSync(signaturePath))
1229
+ return;
1230
+ const targetSignaturePath = `${targetProvenancePath}.sig`;
1231
+ if (signaturePath !== targetSignaturePath) {
1232
+ cpSync(signaturePath, targetSignaturePath);
1233
+ }
1234
+ };
1235
+ var copyOrDownloadArchive = async (source, cacheDir) => {
1236
+ mkdirSync(cacheDir, { recursive: true, mode: 448 });
1237
+ if (/^https?:\/\//i.test(source)) {
1238
+ const response = await fetch(source);
1239
+ if (!response.ok) {
1240
+ throw new Error(`Package download failed with HTTP ${response.status}.`);
1241
+ }
1242
+ if (!response.body)
1243
+ throw new Error("Package download returned no body.");
1244
+ const target2 = resolve3(cacheDir, basename2(new URL(source).pathname));
1245
+ const temporaryTarget = `${target2}.download-${process.pid}-${Date.now()}`;
1246
+ let received = 0;
1247
+ const limiter = new Transform({
1248
+ transform(chunk, _encoding, callback) {
1249
+ received += chunk.length;
1250
+ callback(received > packageExtractionLimits.compressedBytes ? new Error("Package archive exceeds the compressed byte limit.") : null, chunk);
1251
+ }
1252
+ });
1253
+ try {
1254
+ await pipeline(Readable2.fromWeb(response.body), limiter, createWriteStream(temporaryTarget, { flags: "wx", mode: 384 }));
1255
+ renameSync(temporaryTarget, target2);
1256
+ } catch (error) {
1257
+ rmSync(temporaryTarget, { force: true });
1258
+ throw error;
1259
+ }
1260
+ return target2;
1261
+ }
1262
+ const sourcePath = resolve3(source);
1263
+ const target = resolve3(cacheDir, basename2(sourcePath));
1264
+ if (sourcePath !== target) {
1265
+ cpSync(sourcePath, target);
1266
+ }
1267
+ copyAdjacentProvenanceSidecars(sourcePath, target);
1268
+ return target;
1269
+ };
1270
+ var tarString2 = (buffer, start, length) => buffer.subarray(start, start + length).toString("utf8").replace(/\0.*$/s, "");
1271
+ var tarNumber2 = (buffer, start, length) => {
1272
+ const value = tarString2(buffer, start, length).trim();
1273
+ if (!value)
1274
+ return 0;
1275
+ if (!/^[0-7]+$/.test(value))
1276
+ throw new Error("Malformed tar numeric field.");
1277
+ const result = Number.parseInt(value, 8);
1278
+ if (!Number.isSafeInteger(result))
1279
+ throw new Error("Oversized tar numeric field.");
1280
+ return result;
1281
+ };
1282
+ var parsePax = (content) => {
1283
+ const result = {};
1284
+ let offset = 0;
1285
+ while (offset < content.length) {
1286
+ const space = content.indexOf(32, offset);
1287
+ if (space < 0)
1288
+ throw new Error("Malformed pax header.");
1289
+ const lengthText = content.subarray(offset, space).toString("ascii");
1290
+ if (!/^\d+$/.test(lengthText))
1291
+ throw new Error("Malformed pax header length.");
1292
+ const length = Number.parseInt(lengthText, 10);
1293
+ if (length <= space - offset + 1 || offset + length > content.length) {
1294
+ throw new Error("Truncated pax header.");
1295
+ }
1296
+ const record = content.subarray(space + 1, offset + length - 1).toString("utf8");
1297
+ const equals = record.indexOf("=");
1298
+ if (equals <= 0)
1299
+ throw new Error("Malformed pax header record.");
1300
+ result[record.slice(0, equals)] = record.slice(equals + 1);
1301
+ offset += length;
1302
+ }
1303
+ return result;
1304
+ };
1305
+ var assertSafeParents = (destination, target) => {
1306
+ let current = dirname2(target);
1307
+ while (current !== destination) {
1308
+ if (existsSync(current) && lstatSync3(current).isSymbolicLink()) {
1309
+ throw new Error("Package archive would write through a symlinked parent.");
1310
+ }
1311
+ const next = dirname2(current);
1312
+ if (next === current)
1313
+ throw new Error("Package archive path escaped destination.");
1314
+ current = next;
1315
+ }
1316
+ };
1317
+ var extractTarGz = async (archivePath, destination, native) => {
1318
+ if (statSync(archivePath).size > packageExtractionLimits.compressedBytes) {
1319
+ throw new Error("Package archive exceeds the compressed byte limit.");
1320
+ }
1321
+ mkdirSync(destination, { recursive: true, mode: 448 });
1322
+ const input = createReadStream(archivePath, { signal: native?.signal });
1323
+ const stream = createGunzip2();
1324
+ input.on("error", (error) => stream.destroy(error));
1325
+ input.pipe(stream);
1326
+ const links = /* @__PURE__ */ new Map();
1327
+ let regularBytes = 0;
1328
+ let buffer = Buffer.alloc(0);
1329
+ let pax = {};
1330
+ const seen = /* @__PURE__ */ new Set();
1331
+ let expandedBytes = 0;
1332
+ let fileCount = 0;
1333
+ let current;
1334
+ let ended = false;
1335
+ try {
1336
+ for await (const chunk of stream) {
1337
+ const bytes = Buffer.from(chunk);
1338
+ buffer = buffer.length === 0 ? bytes : Buffer.concat([buffer, bytes]);
1339
+ while (true) {
1340
+ if (current) {
1341
+ if (current.remaining > 0 && buffer.length > 0) {
1342
+ const length = Math.min(current.remaining, buffer.length);
1343
+ const part = buffer.subarray(0, length);
1344
+ buffer = buffer.subarray(length);
1345
+ current.remaining -= length;
1346
+ if (current.fd !== void 0)
1347
+ writeSync(current.fd, part);
1348
+ else
1349
+ current.chunks?.push(Buffer.from(part));
1350
+ }
1351
+ if (current.remaining > 0)
1352
+ break;
1353
+ if (current.fd !== void 0) {
1354
+ closeSync3(current.fd);
1355
+ current.fd = void 0;
1356
+ if (current.path && current.mode !== void 0) {
1357
+ chmodSync(current.path, current.mode);
1358
+ }
1359
+ }
1360
+ if (buffer.length < current.padding)
1361
+ break;
1362
+ buffer = buffer.subarray(current.padding);
1363
+ if (current.type === "x")
1364
+ pax = parsePax(Buffer.concat(current.chunks ?? []));
1365
+ current = void 0;
1366
+ continue;
1367
+ }
1368
+ if (buffer.length < 512)
1369
+ break;
1370
+ const header = buffer.subarray(0, 512);
1371
+ buffer = buffer.subarray(512);
1372
+ if (header.every((byte) => byte === 0)) {
1373
+ ended = true;
1374
+ break;
1375
+ }
1376
+ const storedChecksum = tarNumber2(header, 148, 8);
1377
+ const checksumHeader = Buffer.from(header);
1378
+ checksumHeader.fill(32, 148, 156);
1379
+ const actualChecksum = checksumHeader.reduce((sum, byte) => sum + byte, 0);
1380
+ if (storedChecksum !== actualChecksum)
1381
+ throw new Error("Malformed tar header checksum.");
1382
+ const type = tarString2(header, 156, 1) || "0";
1383
+ const size = tarNumber2(header, 124, 12);
1384
+ if (size > packageExtractionLimits.individualFileBytes) {
1385
+ throw new Error("Package archive entry exceeds the individual file limit.");
1386
+ }
1387
+ expandedBytes += size;
1388
+ if (expandedBytes > packageExtractionLimits.expandedBytes) {
1389
+ throw new Error("Package archive exceeds the expanded byte limit.");
1390
+ }
1391
+ const padding = (512 - size % 512) % 512;
1392
+ if (type === "x") {
1393
+ if (size > packageExtractionLimits.paxHeaderBytes) {
1394
+ throw new Error("Pax header exceeds limit.");
1395
+ }
1396
+ current = { type, remaining: size, padding, chunks: [] };
1397
+ continue;
1398
+ }
1399
+ const name = tarString2(header, 0, 100);
1400
+ const prefix = tarString2(header, 345, 155);
1401
+ const link = pax.linkpath ?? tarString2(header, 157, 100);
1402
+ const rawPath = pax.path ?? (prefix ? `${prefix}/${name}` : name);
1403
+ pax = {};
1404
+ if (Buffer.byteLength(rawPath) > packageExtractionLimits.pathBytes) {
1405
+ throw new Error("Package archive path exceeds the path length limit.");
1406
+ }
1407
+ const entryMode = tarNumber2(header, 100, 8);
1408
+ if (native) {
1409
+ const path = rawPath.replace(/\/$/, "");
1410
+ if (!(path === "koed-runtime" || path.startsWith("koed-runtime/")) || !permitsNativeEntry(native.kind, path.slice("koed-runtime/".length), type === "5", native.platform) || path.split("/").some((part) => !part || part === "." || part === "..") || path.includes("\\") || (entryMode & ~511) !== 0)
1411
+ throw new Error("Unsafe native archive path or mode.");
1412
+ if (type === "0")
1413
+ regularBytes += size;
1414
+ if (regularBytes > native.expandedBytes || seen.size >= packageExtractionLimits.fileCount)
1415
+ throw new Error("Native archive exceeds its extraction budget.");
1416
+ }
1417
+ const target = safeResolve(destination, rawPath);
1418
+ const normalized = relative3(destination, target).replaceAll("\\", "/");
1419
+ if (seen.has(normalized))
1420
+ throw new Error(`Duplicate package archive path: ${normalized}`);
1421
+ seen.add(normalized);
1422
+ if (type === "5") {
1423
+ if (size !== 0)
1424
+ throw new Error("Directory tar entry must be empty.");
1425
+ assertSafeParents(destination, target);
1426
+ mkdirSync(target, { recursive: true, mode: 493 });
1427
+ if (native) {
1428
+ if (entryMode !== 493)
1429
+ throw new Error("Unexpected native directory mode.");
1430
+ chmodSync(target, entryMode);
1431
+ }
1432
+ } else if (type === "0" || type === "") {
1433
+ fileCount += 1;
1434
+ if (fileCount > packageExtractionLimits.fileCount)
1435
+ throw new Error("Package archive exceeds the file count limit.");
1436
+ if (basename2(target) === "koed-server-package-manifest.json" && size > packageExtractionLimits.manifestBytes) {
1437
+ throw new Error("Package manifest exceeds the manifest size limit.");
1438
+ }
1439
+ assertSafeParents(destination, target);
1440
+ mkdirSync(dirname2(target), { recursive: true, mode: 493 });
1441
+ const mode = native ? entryMode : entryMode & 73 ? 493 : 420;
1442
+ const flags = fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0);
1443
+ const fd = openSync3(target, flags, mode);
1444
+ current = { type, remaining: size, padding, fd, path: target, mode };
1445
+ continue;
1446
+ } else if (type === "1") {
1447
+ throw new Error("Package archives must not contain hard links.");
1448
+ } else if (type === "2") {
1449
+ if (!native)
1450
+ throw new Error("Package archives must not contain symbolic links.");
1451
+ if (size !== 0 || !link || link.includes("\\") || link.includes("\0") || isAbsolute3(link) || posix.normalize(link) !== link || Buffer.byteLength(link) > packageExtractionLimits.pathBytes)
1452
+ throw new Error("Unsafe native library link.");
1453
+ links.set(target, link);
1454
+ } else {
1455
+ throw new Error(`Package archives contain unsupported tar entry type: ${type}`);
1456
+ }
1457
+ }
1458
+ if (ended)
1459
+ break;
1460
+ }
1461
+ } finally {
1462
+ input.destroy();
1463
+ stream.destroy();
1464
+ if (current?.fd !== void 0)
1465
+ closeSync3(current.fd);
1466
+ }
1467
+ if (current || !ended)
1468
+ throw new Error("Package archive is truncated.");
1469
+ if (native && regularBytes !== native.expandedBytes)
1470
+ throw new Error("Native archive expanded size differs from its pin.");
1471
+ for (const [path, link] of links) {
1472
+ const target = resolve3(dirname2(path), link);
1473
+ if (!isInside(resolve3(destination, native?.kind === "cuda" ? "koed-runtime/llama.cpp/cuda" : "koed-runtime"), target) || links.has(target))
1474
+ throw new Error("Native library link escapes the payload or targets another link.");
1475
+ assertSafeParents(destination, target);
1476
+ assertSafeParents(destination, path);
1477
+ if (!lstatSync3(target).isFile())
1478
+ throw new Error("Native library link requires a regular file.");
1479
+ symlinkSync(link, path);
1480
+ }
1481
+ };
1482
+ var extractNativeArchive = (kind, archive, destination, expandedBytes, signal, platform = "linux") => {
1483
+ mkdirSync(destination, { mode: 448 });
1484
+ return extractTarGz(archive, destination, {
1485
+ kind,
1486
+ expandedBytes,
1487
+ signal,
1488
+ platform
1489
+ });
1490
+ };
1491
+ var findExtractedPackageRoot = (extractDir) => {
1492
+ const entries = readdirSync3(extractDir, { withFileTypes: true }).filter((entry) => entry.isDirectory());
1493
+ if (entries.length !== 1) {
1494
+ throw new Error("Package archive must contain exactly one root directory.");
1495
+ }
1496
+ return resolve3(extractDir, entries[0].name);
1497
+ };
1498
+ var activateVersion = (paths, version, options = {}) => {
1499
+ const versionsDir = packageVersionsDir(paths);
1500
+ const safeVersion = validatePackageVersion(version);
1501
+ const target = safeResolve(versionsDir, safeVersion);
1502
+ const validation = validateServerPackageRoot(target);
1503
+ if (!validation.ok) {
1504
+ throw new Error(validation.errors.join(" "));
1505
+ }
1506
+ if (!validation.manifest) {
1507
+ throw new Error("Package manifest is required.");
1508
+ }
1509
+ assertUpgradeCompatible({
1510
+ paths,
1511
+ nextManifest: validation.manifest,
1512
+ allowDowngrade: options.allowDowngrade
1513
+ });
1514
+ const current = packageCurrentPath(paths);
1515
+ mkdirSync(dirname2(current), { recursive: true, mode: 448 });
1516
+ const tempLink = resolve3(dirname2(current), `.current-${process.pid}-${Date.now()}`);
1517
+ rmSync(tempLink, { force: true, recursive: true });
1518
+ symlinkSync(relative3(dirname2(current), target), tempLink, "dir");
1519
+ renameSync(tempLink, current);
1520
+ const status = collectServerPackageStatus(paths);
1521
+ return {
1522
+ ...status,
1523
+ ok: true,
1524
+ state: "activated",
1525
+ activatedVersion: safeVersion,
1526
+ message: `koed-server package ${safeVersion} activated.`
1527
+ };
1528
+ };
1529
+ var installServerPackage = async (paths, options) => {
1530
+ const expectedSha256 = readExpectedSha256(options);
1531
+ const cacheDir = packageCacheDir(paths);
1532
+ const archivePath = await copyOrDownloadArchive(options.source, cacheDir);
1533
+ const actualSha256 = sha256File(archivePath);
1534
+ if (actualSha256 !== expectedSha256) {
1535
+ throw new Error("Package archive SHA-256 mismatch.");
1536
+ }
1537
+ const root = packageRoot(paths);
1538
+ const versionsDir = packageVersionsDir(paths);
1539
+ mkdirSync(versionsDir, { recursive: true, mode: 448 });
1540
+ const extractDir = resolve3(root, `.install-${process.pid}-${Date.now()}`);
1541
+ rmSync(extractDir, { recursive: true, force: true });
1542
+ try {
1543
+ await extractTarGz(archivePath, extractDir);
1544
+ const extractedRoot = findExtractedPackageRoot(extractDir);
1545
+ const validation = validateServerPackageRoot(extractedRoot);
1546
+ if (!validation.ok || !validation.version) {
1547
+ throw new Error(validation.errors.join(" "));
1548
+ }
1549
+ if (!validation.manifest) {
1550
+ throw new Error("Package manifest is required.");
1551
+ }
1552
+ assertUpgradeCompatible({
1553
+ paths,
1554
+ nextManifest: validation.manifest,
1555
+ allowDowngrade: options.allowDowngrade
1556
+ });
1557
+ const provenanceValidation = validatePackageProvenance({
1558
+ options,
1559
+ archivePath,
1560
+ archiveSha256: actualSha256,
1561
+ manifest: validation.manifest
1562
+ });
1563
+ const safeVersion = validatePackageVersion(validation.version);
1564
+ const target = safeResolve(versionsDir, safeVersion);
1565
+ const tempTarget = resolve3(versionsDir, `.${safeVersion}-${process.pid}-${Date.now()}`);
1566
+ rmSync(tempTarget, { recursive: true, force: true });
1567
+ renameSync(extractedRoot, tempTarget);
1568
+ rmSync(target, { recursive: true, force: true });
1569
+ renameSync(tempTarget, target);
1570
+ rmSync(extractDir, { recursive: true, force: true });
1571
+ const status = options.activate ? activateVersion(paths, validation.version, {
1572
+ allowDowngrade: options.allowDowngrade
1573
+ }) : collectServerPackageStatus(paths);
1574
+ return {
1575
+ ...status,
1576
+ ok: true,
1577
+ state: options.activate ? "activated" : "installed",
1578
+ archivePath,
1579
+ archiveSha256: actualSha256,
1580
+ installedPath: target,
1581
+ provenance: provenanceValidation,
1582
+ message: options.activate ? `koed-server package ${safeVersion} installed and activated.` : `koed-server package ${safeVersion} installed.`
1583
+ };
1584
+ } catch (error) {
1585
+ rmSync(extractDir, { recursive: true, force: true });
1586
+ throw error;
1587
+ }
1588
+ };
1589
+ var activateServerPackage = (paths, version, options = {}) => activateVersion(paths, version, options);
1590
+ var compareVersionsDesc = (a, b) => {
1591
+ const left = a.split(".").map((part) => Number.parseInt(part, 10));
1592
+ const right = b.split(".").map((part) => Number.parseInt(part, 10));
1593
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
1594
+ const diff = (right[index] ?? 0) - (left[index] ?? 0);
1595
+ if (diff !== 0)
1596
+ return diff;
1597
+ }
1598
+ return b.localeCompare(a);
1599
+ };
1600
+ var cleanupServerPackages = (paths, keep = 1) => {
1601
+ if (!Number.isInteger(keep) || keep < 0) {
1602
+ throw new Error("--keep must be a non-negative integer.");
1603
+ }
1604
+ const status = collectServerPackageStatus(paths);
1605
+ const activeVersion = status.currentVersion;
1606
+ const inactive = status.installed.filter((entry) => entry.version !== activeVersion).map((entry) => entry.version).sort(compareVersionsDesc);
1607
+ const retained = new Set(inactive.slice(0, keep));
1608
+ const removedVersions = [];
1609
+ for (const version of inactive) {
1610
+ if (retained.has(version))
1611
+ continue;
1612
+ rmSync(safeResolve(packageVersionsDir(paths), validatePackageVersion(version)), {
1613
+ recursive: true,
1614
+ force: true
1615
+ });
1616
+ removedVersions.push(version);
1617
+ }
1618
+ const removedCacheEntries = [];
1619
+ const cacheDir = packageCacheDir(paths);
1620
+ if (existsSync(cacheDir)) {
1621
+ for (const entry of readdirSync3(cacheDir)) {
1622
+ const path = resolve3(cacheDir, entry);
1623
+ const keepCache = activeVersion && entry.includes(activeVersion) ? true : [...retained].some((version) => entry.includes(version));
1624
+ if (!keepCache) {
1625
+ rmSync(path, { recursive: true, force: true });
1626
+ removedCacheEntries.push(path);
1627
+ }
1628
+ }
1629
+ }
1630
+ const next = collectServerPackageStatus(paths);
1631
+ return {
1632
+ ...next,
1633
+ ok: true,
1634
+ state: "cleaned",
1635
+ removedVersions,
1636
+ removedCacheEntries,
1637
+ message: `Removed ${removedVersions.length} inactive package version(s) and ${removedCacheEntries.length} cached package artifact(s).`
1638
+ };
1639
+ };
1640
+
1641
+ export {
1642
+ canonicalArtifactJson,
1643
+ validateComponentManifest,
1644
+ verifyComponentManifestPin,
1645
+ verifyComponent,
1646
+ verifyExtractedComponent,
1647
+ nativeDigest,
1648
+ nativeJsonObject,
1649
+ readNativeMetadata,
1650
+ syncNativeDirectory,
1651
+ nativeFileDigest,
1652
+ verifyNativePayload,
1653
+ standalonePackageSchemaVersion,
1654
+ standalonePackageId,
1655
+ standalonePackageKind,
1656
+ packageProvenanceSchemaVersion,
1657
+ packageExtractionLimits,
1658
+ requiredPackageRuntimeFiles,
1659
+ sha256File,
1660
+ validateServerPackageRoot,
1661
+ collectServerPackageStatus,
1662
+ extractVerifiedPackageArchive,
1663
+ isVersionDowngrade,
1664
+ assertPackageMigrationCompatible,
1665
+ extractNativeArchive,
1666
+ installServerPackage,
1667
+ activateServerPackage,
1668
+ cleanupServerPackages
1669
+ };