mapsource-node 0.0.0-stage → 0.1.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.
@@ -0,0 +1,531 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ mkdtemp,
7
+ open,
8
+ opendir,
9
+ readFile,
10
+ readlink,
11
+ readdir,
12
+ realpath,
13
+ rename,
14
+ rm,
15
+ stat,
16
+ statfs,
17
+ utimes,
18
+ writeFile,
19
+ } from "node:fs/promises";
20
+ import { tmpdir, userInfo } from "node:os";
21
+ import path from "node:path";
22
+ import { fileURLToPath } from "node:url";
23
+
24
+ export const REPO_ROOT = fileURLToPath(new URL("../", import.meta.url));
25
+ export const PROJECT_TEMP_PREFIXES = ["mapsource-"];
26
+ export const DEFAULT_FREE_SPACE_FLOOR_BYTES = 10 * 1024 ** 3;
27
+
28
+ const DAY = 86_400_000;
29
+ // The directory descriptor protects callbacks from other processes' scanners;
30
+ // this set also protects same-process cleanup, including injected reference
31
+ // inventories, without relying on a callback's cwd, argv or ordinary files.
32
+ const activeTempDirectories = new Set();
33
+
34
+ /**
35
+ * Retained diagnostics are deliberately separate from runtime databases.
36
+ * Anything worth preserving longer belongs in docs/ or another reviewed,
37
+ * durable store rather than having these ceilings raised indefinitely.
38
+ */
39
+ export const RETAINED_ARTIFACT_POLICIES = Object.freeze({
40
+ diagnostics: Object.freeze({
41
+ id: "diagnostics",
42
+ root: path.join(REPO_ROOT, ".local", "diagnostics"),
43
+ maxFileBytes: 16 * 1024 ** 2,
44
+ maxBytes: 256 * 1024 ** 2,
45
+ maxCount: 80,
46
+ maxAgeMs: 14 * DAY,
47
+ freeSpaceFloorBytes: DEFAULT_FREE_SPACE_FLOOR_BYTES,
48
+ }),
49
+ qualification: Object.freeze({
50
+ id: "qualification",
51
+ root: path.join(REPO_ROOT, ".aiwg", "testing"),
52
+ maxFileBytes: 32 * 1024 ** 2,
53
+ maxBytes: 512 * 1024 ** 2,
54
+ maxCount: 120,
55
+ maxAgeMs: 90 * DAY,
56
+ freeSpaceFloorBytes: DEFAULT_FREE_SPACE_FLOOR_BYTES,
57
+ }),
58
+ });
59
+
60
+ function errorCode(error) {
61
+ return error && typeof error === "object" && "code" in error ? error.code : undefined;
62
+ }
63
+
64
+ function currentUid() {
65
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
66
+ }
67
+
68
+ function within(root, target) {
69
+ const relative = path.relative(path.resolve(root), path.resolve(target));
70
+ return relative !== "" && !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
71
+ }
72
+
73
+ /** Resolve two directories through a single visible Linux mount. Separate bind
74
+ * mounts can report the same device while rename(2) still rejects crossing
75
+ * their mount IDs. Only aliases of the same backing paths are considered. */
76
+ export function publicationAliases(mountInfo, source, destinationParent) {
77
+ const decode = value => value.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
78
+ const mounts = mountInfo.trim().split("\n").map(line => {
79
+ const [id, , device, root, target] = line.split(" ");
80
+ return { id, device, root: decode(root), target: decode(target) };
81
+ });
82
+ const contains = (root, target) => root === target || within(root, target);
83
+ const mountAt = filename => mounts.reduce((selected, mount) =>
84
+ contains(mount.target, filename) && (!selected || mount.target.length >= selected.target.length) ? mount : selected, undefined);
85
+ const from = mountAt(source), to = mountAt(destinationParent);
86
+ if (!from || !to || from.device !== to.device) throw new Error("Release publication requires the same filesystem");
87
+ if (from.id === to.id) return [source, destinationParent];
88
+ const sourcePath = path.join(from.root, path.relative(from.target, source));
89
+ const parentPath = path.join(to.root, path.relative(to.target, destinationParent));
90
+ for (const mount of mounts) {
91
+ if (mount.device !== from.device || !contains(mount.root, sourcePath) || !contains(mount.root, parentPath)) continue;
92
+ const sourceAlias = path.join(mount.target, path.relative(mount.root, sourcePath));
93
+ const parentAlias = path.join(mount.target, path.relative(mount.root, parentPath));
94
+ if (mountAt(sourceAlias)?.id === mount.id && mountAt(parentAlias)?.id === mount.id) return [sourceAlias, parentAlias];
95
+ }
96
+ throw new Error("Release publication requires a visible common mount for its staging and destination directories");
97
+ }
98
+
99
+ export async function atomicPublicationPaths(source, destination) {
100
+ if (process.platform !== "linux") return [source, destination];
101
+ const parent = path.dirname(destination);
102
+ const [from, to, mounts] = await Promise.all([realpath(source), realpath(parent), readFile("/proc/self/mountinfo", "utf8")]);
103
+ if (from !== source || to !== parent) throw new Error("Release publication paths must not traverse symlinks");
104
+ const [sourceAlias, parentAlias] = publicationAliases(mounts, source, parent);
105
+ for (const [original, alias] of [[source, sourceAlias], [parent, parentAlias]]) {
106
+ if (alias === original) continue;
107
+ const [identity, resolved, canonical] = await Promise.all([lstat(original), lstat(alias), realpath(alias)]);
108
+ if (canonical !== alias || identity.dev !== resolved.dev || identity.ino !== resolved.ino) {
109
+ throw new Error("Release publication mount alias no longer identifies the original directory");
110
+ }
111
+ }
112
+ return [sourceAlias, path.join(parentAlias, path.basename(destination))];
113
+ }
114
+
115
+ function directChild(root, target) {
116
+ return path.dirname(path.resolve(target)) === path.resolve(root);
117
+ }
118
+
119
+ function allocatedBytes(info) {
120
+ return Number.isFinite(info.blocks) ? Number(info.blocks) * 512 : Number(info.size);
121
+ }
122
+
123
+ async function nearestExistingDirectory(target) {
124
+ let current = path.resolve(target);
125
+ while (true) {
126
+ try {
127
+ const info = await stat(current);
128
+ return info.isDirectory() ? current : path.dirname(current);
129
+ } catch (error) {
130
+ if (errorCode(error) !== "ENOENT") throw error;
131
+ const parent = path.dirname(current);
132
+ if (parent === current) throw error;
133
+ current = parent;
134
+ }
135
+ }
136
+ }
137
+
138
+ export async function freeSpacePreflight({ target, projectedBytes, floorBytes = DEFAULT_FREE_SPACE_FLOOR_BYTES }) {
139
+ if (!Number.isSafeInteger(projectedBytes) || projectedBytes < 0) throw new Error("projectedBytes must be a non-negative safe integer");
140
+ if (!Number.isSafeInteger(floorBytes) || floorBytes < 0) throw new Error("floorBytes must be a non-negative safe integer");
141
+ const directory = await nearestExistingDirectory(target);
142
+ const filesystem = await statfs(directory);
143
+ const availableBytes = Number(filesystem.bavail) * Number(filesystem.bsize);
144
+ const accepted = availableBytes - projectedBytes >= floorBytes;
145
+ const result = { target: path.resolve(target), filesystem: directory, availableBytes, projectedBytes, floorBytes, accepted };
146
+ if (!accepted) {
147
+ const error = new Error(`insufficient free space for ${result.target}: ${availableBytes} available, ${projectedBytes} projected, ${floorBytes} safety floor`);
148
+ error.storage = result;
149
+ throw error;
150
+ }
151
+ return result;
152
+ }
153
+
154
+ async function inspectTree(target, expectedUid, expectedDevice) {
155
+ const result = {
156
+ bytes: 0,
157
+ allocatedBytes: 0,
158
+ entries: 0,
159
+ oldestMtimeMs: Number.POSITIVE_INFINITY,
160
+ newestMtimeMs: 0,
161
+ ownershipValid: true,
162
+ mountBoundaryValid: true,
163
+ };
164
+
165
+ async function visit(current) {
166
+ const info = await lstat(current);
167
+ result.entries += 1;
168
+ result.bytes += Number(info.size);
169
+ result.allocatedBytes += allocatedBytes(info);
170
+ result.oldestMtimeMs = Math.min(result.oldestMtimeMs, info.mtimeMs);
171
+ result.newestMtimeMs = Math.max(result.newestMtimeMs, info.mtimeMs);
172
+ if (expectedUid !== undefined && info.uid !== expectedUid) result.ownershipValid = false;
173
+ if (info.dev !== expectedDevice) result.mountBoundaryValid = false;
174
+ if (!info.isDirectory() || info.isSymbolicLink()) return;
175
+ const directory = await opendir(current);
176
+ for await (const entry of directory) await visit(path.join(current, entry.name));
177
+ }
178
+
179
+ await visit(target);
180
+ if (!Number.isFinite(result.oldestMtimeMs)) result.oldestMtimeMs = 0;
181
+ return result;
182
+ }
183
+
184
+ export async function inspectManagedTree(target) {
185
+ const resolved = path.resolve(target);
186
+ try {
187
+ const info = await lstat(resolved);
188
+ const details = await inspectTree(resolved, currentUid(), info.dev);
189
+ return { path: resolved, exists: true, ...details };
190
+ } catch (error) {
191
+ if (errorCode(error) === "ENOENT") {
192
+ return { path: resolved, exists: false, bytes: 0, allocatedBytes: 0, entries: 0, oldestMtimeMs: 0, newestMtimeMs: 0, ownershipValid: true, mountBoundaryValid: true };
193
+ }
194
+ throw error;
195
+ }
196
+ }
197
+
198
+ async function processReferenceTexts(procRoot = "/proc") {
199
+ const texts = [];
200
+ let entries;
201
+ try { entries = await readdir(procRoot, { withFileTypes: true }); } catch { return texts; }
202
+ for (const entry of entries) {
203
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name) || Number(entry.name) === process.pid) continue;
204
+ const base = path.join(procRoot, entry.name);
205
+ try { texts.push((await readFile(path.join(base, "cmdline"))).toString("utf8")); } catch { /* process exited */ }
206
+ try { texts.push(await readlink(path.join(base, "cwd"))); } catch { /* restricted or exited */ }
207
+ try {
208
+ const descriptors = await readdir(path.join(base, "fd"));
209
+ for (const descriptor of descriptors) {
210
+ try { texts.push((await readlink(path.join(base, "fd", descriptor))).replace(/ \(deleted\)$/, "")); } catch { /* descriptor closed */ }
211
+ }
212
+ } catch { /* restricted or exited */ }
213
+ try {
214
+ const maps = await readFile(path.join(base, "maps"), "utf8");
215
+ texts.push(maps);
216
+ } catch { /* kernel thread, restricted, or exited */ }
217
+ }
218
+ return texts;
219
+ }
220
+
221
+ function referenced(target, references) {
222
+ const resolved = path.resolve(target);
223
+ return references.some((reference) => reference === resolved
224
+ || reference.startsWith(`${resolved}${path.sep}`)
225
+ || reference.includes(resolved));
226
+ }
227
+
228
+ function producerFor(name) {
229
+ const producers = [
230
+ ["mapsource-fonts-", "services/gateway/src/fonts.test.ts"],
231
+ ["mapsource-places-", "services/gateway/src/place-index.test.ts"],
232
+ ["mapsource-facilitator-", "services/facilitator/src/config.test.ts"],
233
+ ["mapsource-render-", "services/gateway/src/browser.ts (Chromium profile)"],
234
+ ["mapsource-geoip-test-", "services/gateway/src/geoip-download.test.ts"],
235
+ ["mapsource-account-usage-test-", "scripts/account-coordinator.test.ts"],
236
+ ["mapsource-cutover-test-", "services/gateway/src/overpass-readiness.test.ts"],
237
+ ["mapsource-workflows-", "services/gateway/src/reference-workflows.test.ts"],
238
+ ["mapsource-distribution-test-", "packages/contracts/src/distribution-planner.test.ts"],
239
+ ["mapsource-vps-seed-", "scripts/deploy-vps.mjs"],
240
+ ["mapsource-distribution-seed-", "scripts/deploy-vps.mjs"],
241
+ ];
242
+ return producers.find(([prefix]) => name.startsWith(prefix))?.[1] ?? "operator/diagnostic command (not emitted by a tracked writer)";
243
+ }
244
+
245
+ /**
246
+ * Inspect or remove only direct children of the selected temp root whose names
247
+ * begin with the Mapsource prefix. No glob is expanded and symlinks are never
248
+ * followed. A target is rejected if ownership, age, mount, or liveness cannot
249
+ * be proven safe.
250
+ */
251
+ export async function scavengeProjectTemp({
252
+ root = tmpdir(),
253
+ prefixes = PROJECT_TEMP_PREFIXES,
254
+ minimumAgeMs = 6 * 60 * 60_000,
255
+ dryRun = true,
256
+ now = Date.now(),
257
+ activeReferences,
258
+ } = {}) {
259
+ if (!Array.isArray(prefixes) || prefixes.length === 0
260
+ || prefixes.some((prefix) => !PROJECT_TEMP_PREFIXES.includes(prefix))) {
261
+ throw new Error(`temporary cleanup prefixes must be selected from: ${PROJECT_TEMP_PREFIXES.join(", ")}`);
262
+ }
263
+ const resolvedRoot = await realpath(path.resolve(root));
264
+ const rootInfo = await stat(resolvedRoot);
265
+ if (!rootInfo.isDirectory()) throw new Error(`temporary root is not a directory: ${resolvedRoot}`);
266
+ const uid = currentUid();
267
+ const references = activeReferences ?? await processReferenceTexts();
268
+ const entries = await readdir(resolvedRoot, { withFileTypes: true });
269
+ const candidates = entries
270
+ .filter((entry) => prefixes.some((prefix) => entry.name.startsWith(prefix)))
271
+ .map((entry) => path.join(resolvedRoot, entry.name))
272
+ .sort();
273
+ const report = {
274
+ schema: "mapsource-artifact-scavenge.v1",
275
+ checkedAt: new Date(now).toISOString(),
276
+ root: resolvedRoot,
277
+ dryRun,
278
+ minimumAgeMs,
279
+ prefixes,
280
+ current: { count: 0, bytes: 0, allocatedBytes: 0, oldestMtime: null, newestMtime: null },
281
+ removed: { count: 0, bytes: 0, allocatedBytes: 0, paths: [] },
282
+ eligible: [],
283
+ rejectedCleanupTargets: [],
284
+ artifacts: [],
285
+ };
286
+
287
+ for (const target of candidates) {
288
+ const name = path.basename(target);
289
+ const rejection = [];
290
+ if (!directChild(resolvedRoot, target) || !prefixes.some((prefix) => name.startsWith(prefix))) rejection.push("invalid-target");
291
+ let details;
292
+ try {
293
+ details = await inspectTree(target, uid, rootInfo.dev);
294
+ } catch (error) {
295
+ rejection.push(`inspection-failed:${errorCode(error) ?? "unknown"}`);
296
+ details = { bytes: 0, allocatedBytes: 0, entries: 0, oldestMtimeMs: 0, newestMtimeMs: now, ownershipValid: false, mountBoundaryValid: false };
297
+ }
298
+ if (!details.ownershipValid) rejection.push("ownership-mismatch");
299
+ if (!details.mountBoundaryValid) rejection.push("mount-boundary");
300
+ if (now - details.newestMtimeMs < minimumAgeMs) rejection.push("too-young");
301
+ if (referenced(target, references) || referenced(target, [...activeTempDirectories])) rejection.push("active-process-reference");
302
+ const artifact = {
303
+ path: target,
304
+ owner: userInfo().username,
305
+ ownerUid: uid,
306
+ producer: producerFor(name),
307
+ bytes: details.bytes,
308
+ allocatedBytes: details.allocatedBytes,
309
+ entries: details.entries,
310
+ oldestMtime: details.oldestMtimeMs ? new Date(details.oldestMtimeMs).toISOString() : null,
311
+ newestMtime: details.newestMtimeMs ? new Date(details.newestMtimeMs).toISOString() : null,
312
+ rejection,
313
+ };
314
+ report.artifacts.push(artifact);
315
+ report.current.count += 1;
316
+ report.current.bytes += details.bytes;
317
+ report.current.allocatedBytes += details.allocatedBytes;
318
+ if (!report.current.oldestMtime || artifact.oldestMtime < report.current.oldestMtime) report.current.oldestMtime = artifact.oldestMtime;
319
+ if (!report.current.newestMtime || artifact.newestMtime > report.current.newestMtime) report.current.newestMtime = artifact.newestMtime;
320
+ if (rejection.length) {
321
+ report.rejectedCleanupTargets.push({ path: target, reasons: rejection });
322
+ continue;
323
+ }
324
+ report.eligible.push(target);
325
+ if (dryRun) continue;
326
+ await rm(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
327
+ report.removed.count += 1;
328
+ report.removed.bytes += details.bytes;
329
+ report.removed.allocatedBytes += details.allocatedBytes;
330
+ report.removed.paths.push(target);
331
+ }
332
+ return report;
333
+ }
334
+
335
+ export async function withProjectTempDirectory(prefix, action, {
336
+ root = tmpdir(),
337
+ projectedBytes = 0,
338
+ freeSpaceFloorBytes = DEFAULT_FREE_SPACE_FLOOR_BYTES,
339
+ } = {}) {
340
+ if (!PROJECT_TEMP_PREFIXES.some((known) => prefix.startsWith(known)) || /[\\/]/.test(prefix)) {
341
+ throw new Error(`temporary prefix is not Mapsource-owned: ${prefix}`);
342
+ }
343
+ await freeSpacePreflight({ target: root, projectedBytes, floorBytes: freeSpaceFloorBytes });
344
+ const directory = await mkdtemp(path.join(path.resolve(root), prefix));
345
+ let lease, canonical;
346
+ try {
347
+ lease = await open(directory, "r");
348
+ canonical = await realpath(directory);
349
+ activeTempDirectories.add(canonical);
350
+ return await action(directory);
351
+ } finally {
352
+ activeTempDirectories.delete(canonical);
353
+ try { await lease?.close(); }
354
+ finally { await rm(directory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); }
355
+ }
356
+ }
357
+
358
+ async function processAlive(pid) {
359
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
360
+ try { process.kill(pid, 0); return true; } catch (error) { return errorCode(error) === "EPERM"; }
361
+ }
362
+
363
+ export async function withProjectLock(name, action, { root = path.join(REPO_ROOT, ".local", "locks"), staleAfterMs = 60_000 } = {}) {
364
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) throw new Error(`invalid lock name: ${name}`);
365
+ const resolvedRoot = path.resolve(root);
366
+ await mkdir(resolvedRoot, { recursive: true, mode: 0o700 });
367
+ const lock = path.join(resolvedRoot, `mapsource-${name}.lock`);
368
+ const claim = async () => {
369
+ try {
370
+ await mkdir(lock, { mode: 0o700 });
371
+ await writeFile(path.join(lock, "owner.json"), `${JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() })}\n`, { flag: "wx", mode: 0o600 });
372
+ return;
373
+ } catch (error) {
374
+ if (errorCode(error) !== "EEXIST") throw error;
375
+ }
376
+ let owner;
377
+ let info;
378
+ try { owner = JSON.parse(await readFile(path.join(lock, "owner.json"), "utf8")); } catch { owner = {}; }
379
+ try { info = await lstat(lock); } catch (error) { if (errorCode(error) === "ENOENT") return claim(); throw error; }
380
+ if (info.uid !== currentUid()) throw new Error(`lock is not owned by this user: ${lock}`);
381
+ if (await processAlive(Number(owner.pid))) throw new Error(`overlapping ${name} run is active as pid ${owner.pid}`);
382
+ if (Date.now() - info.mtimeMs < staleAfterMs) throw new Error(`inactive ${name} lock is younger than the stale threshold: ${lock}`);
383
+ await rm(lock, { recursive: true, force: true });
384
+ return claim();
385
+ };
386
+ await claim();
387
+ try {
388
+ return await action();
389
+ } finally {
390
+ await rm(lock, { recursive: true, force: true });
391
+ }
392
+ }
393
+
394
+ async function listRetainedFiles(policy) {
395
+ const root = path.resolve(policy.root);
396
+ let rootInfo;
397
+ try { rootInfo = await stat(root); } catch (error) { if (errorCode(error) === "ENOENT") return []; throw error; }
398
+ const uid = currentUid();
399
+ const files = [];
400
+ async function visit(directory) {
401
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
402
+ const target = path.join(directory, entry.name);
403
+ const info = await lstat(target);
404
+ if (info.uid !== uid || info.dev !== rootInfo.dev || info.isSymbolicLink()) {
405
+ files.push({ path: target, rejected: "ownership-mount-or-symlink", bytes: 0, allocatedBytes: 0, mtimeMs: info.mtimeMs });
406
+ } else if (info.isDirectory()) await visit(target);
407
+ else if (info.isFile()) files.push({ path: target, bytes: Number(info.size), allocatedBytes: allocatedBytes(info), mtimeMs: info.mtimeMs });
408
+ }
409
+ }
410
+ await visit(root);
411
+ return files;
412
+ }
413
+
414
+ export async function retainedArtifactStatus(policy, now = Date.now()) {
415
+ const files = await listRetainedFiles(policy);
416
+ const accepted = files.filter((file) => !file.rejected);
417
+ return {
418
+ id: policy.id,
419
+ root: path.resolve(policy.root),
420
+ limits: {
421
+ maxFileBytes: policy.maxFileBytes,
422
+ maxBytes: policy.maxBytes,
423
+ maxCount: policy.maxCount,
424
+ maxAgeMs: policy.maxAgeMs,
425
+ freeSpaceFloorBytes: policy.freeSpaceFloorBytes,
426
+ },
427
+ current: {
428
+ count: accepted.length,
429
+ bytes: accepted.reduce((total, file) => total + file.bytes, 0),
430
+ allocatedBytes: accepted.reduce((total, file) => total + file.allocatedBytes, 0),
431
+ oldestArtifact: accepted.length ? new Date(Math.min(...accepted.map((file) => file.mtimeMs))).toISOString() : null,
432
+ },
433
+ rejectedCleanupTargets: files.filter((file) => file.rejected).map((file) => ({ path: file.path, reason: file.rejected })),
434
+ expiredCount: accepted.filter((file) => now - file.mtimeMs > policy.maxAgeMs).length,
435
+ };
436
+ }
437
+
438
+ export async function enforceRetainedArtifactPolicy(policy, { dryRun = true, protect = [], now = Date.now() } = {}) {
439
+ const files = await listRetainedFiles(policy);
440
+ const rejectedCleanupTargets = files.filter((file) => file.rejected).map((file) => ({ path: file.path, reason: file.rejected }));
441
+ const candidates = files.filter((file) => !file.rejected).sort((left, right) => left.mtimeMs - right.mtimeMs || left.path.localeCompare(right.path));
442
+ const protectedPaths = new Set(protect.map((target) => path.resolve(target)));
443
+ const sizeOf = file => policy.allocated ? file.allocatedBytes : file.bytes;
444
+ let count = candidates.length;
445
+ let bytes = candidates.reduce((total, file) => total + sizeOf(file), 0);
446
+ const selected = [];
447
+ for (const file of candidates) {
448
+ const expired = now - file.mtimeMs > policy.maxAgeMs;
449
+ const oversized = sizeOf(file) > policy.maxFileBytes;
450
+ const overAggregate = count > policy.maxCount || bytes > policy.maxBytes;
451
+ if ((!expired && !oversized && !overAggregate) || protectedPaths.has(path.resolve(file.path))) continue;
452
+ selected.push(file);
453
+ count -= 1;
454
+ bytes -= sizeOf(file);
455
+ }
456
+ if (count > policy.maxCount || bytes > policy.maxBytes) {
457
+ throw new Error(`retention limits cannot be met without deleting a protected artifact in ${policy.root}`);
458
+ }
459
+ if (!dryRun) for (const file of selected) await rm(file.path, { force: true });
460
+ return {
461
+ id: policy.id,
462
+ root: path.resolve(policy.root),
463
+ dryRun,
464
+ removed: { count: dryRun ? 0 : selected.length, bytes: dryRun ? 0 : selected.reduce((total, file) => total + file.bytes, 0), paths: dryRun ? [] : selected.map((file) => file.path) },
465
+ eligible: selected.map((file) => file.path),
466
+ rejectedCleanupTargets,
467
+ remaining: { count, bytes },
468
+ };
469
+ }
470
+
471
+ export async function writeRetainedArtifact(policy, relativeTarget, data) {
472
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
473
+ return writeRetained(policy, relativeTarget, buffer.byteLength, handle => handle.writeFile(buffer));
474
+ }
475
+
476
+ export async function writeRetainedArtifactFromFile(policy, relativeTarget, source) {
477
+ const info = await lstat(source);
478
+ if (!info.isFile() || info.uid !== currentUid()) throw new Error("Retained artifact source must be a regular file owned by this user");
479
+ return writeRetained(policy, relativeTarget, info.size, async handle => {
480
+ const input = createReadStream(source);
481
+ let written = 0;
482
+ for await (const data of input) {
483
+ if (written + data.length > info.size) throw new Error("Retained artifact grew during copy");
484
+ await handle.writeFile(data);
485
+ written += data.length;
486
+ }
487
+ if (written !== info.size) throw new Error("Retained artifact shrank during copy");
488
+ });
489
+ }
490
+
491
+ async function writeRetained(policy, relativeTarget, bytes, write) {
492
+ const target = path.resolve(policy.root, relativeTarget);
493
+ if (!within(policy.root, target)) throw new Error(`artifact target escapes ${policy.root}: ${relativeTarget}`);
494
+ if (!policy.diskBounded && bytes > policy.maxFileBytes) throw new Error(`artifact exceeds ${policy.maxFileBytes} byte per-file limit: ${target}`);
495
+ await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
496
+ const rootInfo = await stat(policy.root);
497
+ const parentInfo = await stat(path.dirname(target));
498
+ const canonicalRoot = await realpath(policy.root);
499
+ const canonicalParent = await realpath(path.dirname(target));
500
+ if (canonicalParent !== canonicalRoot && !within(canonicalRoot, canonicalParent)) {
501
+ throw new Error(`artifact target has a parent outside the managed root: ${target}`);
502
+ }
503
+ if (rootInfo.uid !== currentUid() || parentInfo.uid !== currentUid() || rootInfo.dev !== parentInfo.dev) {
504
+ throw new Error(`artifact target failed ownership or mount validation: ${target}`);
505
+ }
506
+ return withProjectLock(`artifacts-${policy.id}`, async () => {
507
+ const storage = await freeSpacePreflight({ target, projectedBytes: bytes, floorBytes: policy.freeSpaceFloorBytes });
508
+ const available = storage.availableBytes - storage.floorBytes;
509
+ const retained = policy.diskBounded ? (await retainedArtifactStatus(policy)).current.allocatedBytes : 0;
510
+ // The live filesystem budget applies to checkpoint bytes. Count and age
511
+ // still bound history, independent of how large one snapshot becomes.
512
+ const limits = policy.diskBounded ? { ...policy, maxFileBytes: retained + available, maxBytes: retained + available, allocated: true } : policy;
513
+ const temporary = path.join(path.dirname(target), `.mapsource-write-${process.pid}-${randomUUID()}.tmp`);
514
+ try {
515
+ const handle = await open(temporary, "wx", 0o600);
516
+ try { await write(handle); await handle.sync(); } finally { await handle.close(); }
517
+ if (policy.diskBounded) await freeSpacePreflight({ target, projectedBytes: 0, floorBytes: policy.freeSpaceFloorBytes });
518
+ await rename(temporary, target);
519
+ const retention = await enforceRetainedArtifactPolicy(limits, { dryRun: false, protect: [target] });
520
+ return { target, bytes, storage, retention };
521
+ } finally {
522
+ await rm(temporary, { force: true });
523
+ }
524
+ });
525
+ }
526
+
527
+ /** Test helper: make an artifact old without shelling out. */
528
+ export async function ageArtifact(target, ageMs) {
529
+ const at = new Date(Date.now() - ageMs);
530
+ await utimes(target, at, at);
531
+ }
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ // Network-independent discovery. DNS carries signed public membership only;
3
+ // neither account credentials nor Cloudflare account API tokens live here.
4
+ import assert from "node:assert/strict";
5
+ import { readFile, mkdir, rename, open } from "node:fs/promises";
6
+ import { resolveTxt } from "node:dns/promises";
7
+ import path from "node:path";
8
+ import { parseArgs } from "node:util";
9
+ import { machineIdentityHash, verifiedMembership, readMembershipRecords, memberSshConfig } from "./mirror-mesh-membership.mjs";
10
+
11
+ const { values } = parseArgs({ options: { root: { type: "string" }, once: { type: "boolean" } } });
12
+ assert.ok(values.root); const root = path.resolve(values.root);
13
+ const identity = JSON.parse(await readFile(path.join(root, "enrollment.json"), "utf8"));
14
+ assert.equal((await readFile("/etc/machine-id", "utf8")).trim(), identity.machineId);
15
+ const publicKey = await readFile(path.join(root, "signing-public.pem"), "utf8");
16
+ const peerPublicKey = (await readFile(path.join(root, "peer-key.pub"), "utf8")).trim().split(/\s+/).slice(0, 2).join(" ");
17
+ let version = 0, envelope;
18
+ const atomicText = async (file, contents) => {
19
+ const pending = `${file}.pending`, handle = await open(pending, "w", 0o600);
20
+ try { await handle.writeFile(contents); await handle.sync(); } finally { await handle.close(); }
21
+ await rename(pending, file);
22
+ };
23
+ async function apply(next) {
24
+ const body = verifiedMembership(next, publicKey, { domain: identity.domain, minimumVersion: version });
25
+ if (body.version === version) { assert.equal(JSON.stringify(next), JSON.stringify(envelope), "Same membership version changed bytes."); return; }
26
+ const own = body.members.find(member => member.node === identity.node);
27
+ assert.ok(own && own.identityHash === machineIdentityHash(identity.machineId) && own.peerPublicKey === peerPublicKey
28
+ && own.hostPublicKey === identity.hostPublicKey.split(/\s+/).slice(0, 2).join(" "), "Local node is not an enrolled mesh member.");
29
+ const peers = body.members.filter(member => member.node !== identity.node);
30
+ await mkdir(path.join(root, "ssh"), { recursive: true, mode: 0o700 });
31
+ for (const member of peers) await atomicText(path.join(root, "ssh", `${member.node}.conf`), memberSshConfig(member, root));
32
+ await atomicText(path.join(root, "ssh/known_hosts"), peers.map(member => `mapsource-mesh-node-${member.identityHash} ${member.hostPublicKey}`).join("\n") + "\n");
33
+ const restrictions = 'restrict,port-forwarding,permitopen="127.0.0.1:8989",permitopen="127.0.0.1:8990",permitopen="127.0.0.1:19390",command="/bin/false"';
34
+ await atomicText(path.join(root, "authorized-peers"), peers.map(member => `${restrictions} ${member.peerPublicKey}`).join("\n") + "\n");
35
+ await atomicText(path.join(root, "membership.json"), JSON.stringify(next) + "\n");
36
+ const directory = await open(root, "r"); try { await directory.sync(); } finally { await directory.close(); }
37
+ version = body.version; envelope = next;
38
+ console.log(JSON.stringify({ event: "mesh-membership-ready", node: identity.node, version, peers: peers.map(peer => peer.node), discovery: "signed-dns", accountAuthorityChanged: false }));
39
+ }
40
+ try { await apply(JSON.parse(await readFile(path.join(root, "membership.json"), "utf8"))); }
41
+ catch (error) { if (error.code !== "ENOENT") throw error; }
42
+ let stopped = false;
43
+ const poll = async () => {
44
+ try { await apply(readMembershipRecords(await resolveTxt(`_mapsource-mesh.${identity.domain}`))); }
45
+ catch { console.log(JSON.stringify({ event: "mesh-discovery-retry", node: identity.node, retainedVersion: version })); }
46
+ };
47
+ await poll();
48
+ if (values.once) assert.ok(version > 0, "No verified mesh membership is available.");
49
+ if (!values.once) {
50
+ while (!stopped) {
51
+ await new Promise(resolve => {
52
+ const finish = () => { clearTimeout(timer); process.off("SIGTERM", end); process.off("SIGINT", end); resolve(); };
53
+ const end = () => { stopped = true; finish(); };
54
+ const timer = setTimeout(finish, 60_000); process.once("SIGTERM", end); process.once("SIGINT", end);
55
+ });
56
+ if (!stopped) await poll();
57
+ }
58
+ }
@@ -0,0 +1,39 @@
1
+ import assert from "node:assert/strict";
2
+
3
+ // Includes forwarded socket buffers and kernel/file cache charged to sshd,
4
+ // not just the daemon's RSS. Operator bulk jobs use separate supervised units.
5
+ export const meshSshBudget = Object.freeze({ highMiB: 384, maxMiB: 512 });
6
+
7
+ export function meshIdentity(input) {
8
+ const { node, machineId, domain = "mapsource.io", sshPort = 22991 } = input;
9
+ assert.match(node ?? "", /^[a-z][a-z0-9-]{0,31}$/);
10
+ assert.match(machineId ?? "", /^[a-f0-9]{32}$/);
11
+ assert.match(domain, /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/);
12
+ assert.ok(Number.isInteger(sshPort) && sshPort >= 1024 && sshPort <= 65535);
13
+ return { schema: "mapsource-portable-peer.v1", node, machineId, domain, sshPort,
14
+ hostname: `mapsource-peer-${node}.${domain}`, tunnelName: `mapsource-peer-${node}`,
15
+ hostKeyAlias: `mapsource-mesh-${machineId}`, alias: `mapsource-${node}` };
16
+ }
17
+
18
+ export function meshSshServer(identity, { user, root, authorizedKeys }) {
19
+ meshIdentity(identity);
20
+ assert.match(user, /^[a-z_][a-z0-9_-]{0,31}$/);
21
+ for (const value of [root, authorizedKeys]) assert.match(value, /^\/[a-zA-Z0-9_./-]+$/);
22
+ return `ListenAddress 127.0.0.1\nPort ${identity.sshPort}\nHostKey ${root}/host-key\nAuthorizedKeysFile ${authorizedKeys} ${root}/authorized-peers\nPidFile ${root}/sshd.pid\nUsePAM no\nStrictModes yes\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nAuthenticationMethods publickey\nAllowUsers ${user}\nPermitRootLogin no\nSubsystem sftp internal-sftp\nAllowTcpForwarding local\nAllowAgentForwarding no\nX11Forwarding no\nPermitTunnel no\nPermitUserEnvironment no\nLogLevel ERROR\nMaxAuthTries 3\nLoginGraceTime 15\n`;
23
+ }
24
+
25
+ export function meshSshClient(identity, { user, key, knownHosts, cloudflared }) {
26
+ assert.deepEqual(meshIdentity(identity), Object.fromEntries(Object.keys(meshIdentity(identity)).map(key => [key, identity[key]])));
27
+ assert.match(user, /^[a-z_][a-z0-9_-]{0,31}$/);
28
+ assert.match(identity.hostPublicKey ?? "", /^ssh-ed25519 [A-Za-z0-9+/=]+(?: [^\r\n]*)?$/);
29
+ for (const value of [key, knownHosts, cloudflared]) assert.match(value, /^\/[a-zA-Z0-9_./-]+$/);
30
+ return `Host ${identity.alias}\n HostName ${identity.hostname}\n User ${user}\n IdentityFile ${key}\n IdentitiesOnly yes\n BatchMode yes\n StrictHostKeyChecking yes\n HostKeyAlias ${identity.hostKeyAlias}\n UserKnownHostsFile ${knownHosts}\n ProxyCommand ${cloudflared} access ssh --hostname %h\n ConnectTimeout 10\n ServerAliveInterval 5\n ServerAliveCountMax 3\n ExitOnForwardFailure yes\n`;
31
+ }
32
+
33
+ export function meshLinkUnit({ node, user, clientConfig, localPort, targetPort }) {
34
+ assert.match(node ?? "", /^[a-z][a-z0-9-]{0,31}$/);
35
+ assert.match(user ?? "", /^[a-z_][a-z0-9_-]{0,31}$/);
36
+ assert.match(clientConfig, /^\/[a-zA-Z0-9_./-]+$/);
37
+ for (const port of [localPort, targetPort]) assert.ok(Number.isInteger(port) && port >= 1024 && port <= 65535);
38
+ return `[Unit]\nDescription=Mapsource outbound private peer link to ${node}\nAfter=network-online.target mapsource-mesh-agent.service\nWants=network-online.target mapsource-mesh-agent.service\nStartLimitIntervalSec=0\n[Service]\nUser=${user}\nEnvironment=BROWSER=/bin/false\nExecStart=/usr/bin/ssh -F ${clientConfig} -N -T -L 127.0.0.1:${localPort}:127.0.0.1:${targetPort} mapsource-${node}\nRestart=always\nRestartSec=3\nMemoryMax=192M\nTasksMax=32\nNoNewPrivileges=true\nPrivateTmp=true\nProtectSystem=strict\nProtectHome=read-only\nLogNamespace=mapsource-mirror\n[Install]\nWantedBy=multi-user.target\n`;
39
+ }