@xenosystem/primitives 0.0.0-stage → 0.2.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.
- package/README.md +29 -2
- package/dist/cjs/dirs/atomic.d.ts +9 -0
- package/dist/cjs/dirs/atomic.js +59 -0
- package/dist/cjs/dirs/check-cli.d.ts +2 -0
- package/dist/cjs/dirs/check-cli.js +50 -0
- package/dist/cjs/dirs/check.d.ts +49 -0
- package/dist/cjs/dirs/check.js +158 -0
- package/dist/cjs/dirs/cli.d.ts +2 -0
- package/dist/cjs/dirs/cli.js +72 -0
- package/dist/cjs/dirs/dirs.d.ts +57 -0
- package/dist/cjs/dirs/dirs.js +135 -0
- package/dist/cjs/dirs/doctor.d.ts +31 -0
- package/dist/cjs/dirs/doctor.js +80 -0
- package/dist/cjs/dirs/errors.d.ts +8 -0
- package/dist/cjs/dirs/errors.js +19 -0
- package/dist/cjs/dirs/host.d.ts +4 -0
- package/dist/cjs/dirs/host.js +26 -0
- package/dist/cjs/dirs/index.d.ts +13 -0
- package/dist/cjs/dirs/index.js +55 -0
- package/dist/cjs/dirs/inputs.d.ts +14 -0
- package/dist/cjs/dirs/inputs.js +14 -0
- package/dist/cjs/dirs/layout.d.ts +16 -0
- package/dist/cjs/dirs/layout.js +25 -0
- package/dist/cjs/dirs/lock.d.ts +38 -0
- package/dist/cjs/dirs/lock.js +128 -0
- package/dist/cjs/dirs/migrate.d.ts +134 -0
- package/dist/cjs/dirs/migrate.js +437 -0
- package/dist/cjs/dirs/procinfo.d.ts +10 -0
- package/dist/cjs/dirs/procinfo.js +67 -0
- package/dist/cjs/dirs/registry.d.ts +27 -0
- package/dist/cjs/dirs/registry.js +78 -0
- package/dist/cjs/dirs/roots.d.ts +23 -0
- package/dist/cjs/dirs/roots.js +114 -0
- package/dist/cjs/dirs/segments.d.ts +7 -0
- package/dist/cjs/dirs/segments.js +39 -0
- package/dist/cjs/generated/contract.d.ts +134 -0
- package/dist/cjs/generated/contract.js +233 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/secrets/envelope.d.ts +37 -0
- package/dist/cjs/secrets/envelope.js +90 -0
- package/dist/cjs/secrets/errors.d.ts +10 -0
- package/dist/cjs/secrets/errors.js +20 -0
- package/dist/cjs/secrets/index.d.ts +4 -0
- package/dist/cjs/secrets/index.js +17 -0
- package/dist/cjs/secrets/keystore.d.ts +37 -0
- package/dist/cjs/secrets/keystore.js +41 -0
- package/dist/cjs/secrets/os-stores.d.ts +17 -0
- package/dist/cjs/secrets/os-stores.js +195 -0
- package/dist/cjs/secrets/store.d.ts +32 -0
- package/dist/cjs/secrets/store.js +161 -0
- package/dist/cjs/secrets/testing.d.ts +5 -0
- package/dist/cjs/secrets/testing.js +20 -0
- package/dist/cjs/updates/index.d.ts +67 -0
- package/dist/cjs/updates/index.js +102 -0
- package/dist/esm/dirs/atomic.d.ts +9 -0
- package/dist/esm/dirs/atomic.js +56 -0
- package/dist/esm/dirs/check-cli.d.ts +2 -0
- package/dist/esm/dirs/check-cli.js +48 -0
- package/dist/esm/dirs/check.d.ts +49 -0
- package/dist/esm/dirs/check.js +152 -0
- package/dist/esm/dirs/cli.d.ts +2 -0
- package/dist/esm/dirs/cli.js +70 -0
- package/dist/esm/dirs/dirs.d.ts +57 -0
- package/dist/esm/dirs/dirs.js +129 -0
- package/dist/esm/dirs/doctor.d.ts +31 -0
- package/dist/esm/dirs/doctor.js +77 -0
- package/dist/esm/dirs/errors.d.ts +8 -0
- package/dist/esm/dirs/errors.js +14 -0
- package/dist/esm/dirs/host.d.ts +4 -0
- package/dist/esm/dirs/host.js +21 -0
- package/dist/esm/dirs/index.d.ts +13 -0
- package/dist/esm/dirs/index.js +13 -0
- package/dist/esm/dirs/inputs.d.ts +14 -0
- package/dist/esm/dirs/inputs.js +11 -0
- package/dist/esm/dirs/layout.d.ts +16 -0
- package/dist/esm/dirs/layout.js +21 -0
- package/dist/esm/dirs/lock.d.ts +38 -0
- package/dist/esm/dirs/lock.js +124 -0
- package/dist/esm/dirs/migrate.d.ts +134 -0
- package/dist/esm/dirs/migrate.js +428 -0
- package/dist/esm/dirs/procinfo.d.ts +10 -0
- package/dist/esm/dirs/procinfo.js +62 -0
- package/dist/esm/dirs/registry.d.ts +27 -0
- package/dist/esm/dirs/registry.js +71 -0
- package/dist/esm/dirs/roots.d.ts +23 -0
- package/dist/esm/dirs/roots.js +107 -0
- package/dist/esm/dirs/segments.d.ts +7 -0
- package/dist/esm/dirs/segments.js +35 -0
- package/dist/esm/generated/contract.d.ts +134 -0
- package/dist/esm/generated/contract.js +230 -0
- package/dist/esm/secrets/envelope.d.ts +37 -0
- package/dist/esm/secrets/envelope.js +81 -0
- package/dist/esm/secrets/errors.d.ts +10 -0
- package/dist/esm/secrets/errors.js +15 -0
- package/dist/esm/secrets/index.d.ts +4 -0
- package/dist/esm/secrets/index.js +4 -0
- package/dist/esm/secrets/keystore.d.ts +37 -0
- package/dist/esm/secrets/keystore.js +37 -0
- package/dist/esm/secrets/os-stores.d.ts +17 -0
- package/dist/esm/secrets/os-stores.js +189 -0
- package/dist/esm/secrets/store.d.ts +32 -0
- package/dist/esm/secrets/store.js +156 -0
- package/dist/esm/secrets/testing.d.ts +5 -0
- package/dist/esm/secrets/testing.js +12 -0
- package/dist/esm/updates/index.d.ts +67 -0
- package/dist/esm/updates/index.js +97 -0
- package/package.json +42 -4
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import type { XenoDirs } from './dirs.ts';
|
|
2
|
+
import type { Kind } from './roots.ts';
|
|
3
|
+
/**
|
|
4
|
+
* The copy-only migrator (XENO LOCAL HOME - SPEC.md section 10). It copies known legacy files to their registered
|
|
5
|
+
* locations, records source, destination and SHA-256 in a journal under state/platform/migrations/, verifies every
|
|
6
|
+
* copy by hash, refuses a destination that already holds different bytes and refuses links and junctions, converts
|
|
7
|
+
* plaintext credentials into encrypted secrets through a caller-supplied sink, leaves every legacy home in place, and
|
|
8
|
+
* reports whatever it found but could not place. It never deletes or moves anything, and it never guesses.
|
|
9
|
+
*/
|
|
10
|
+
export type MigrationRule = {
|
|
11
|
+
id: string;
|
|
12
|
+
legacyHome: string;
|
|
13
|
+
match: string;
|
|
14
|
+
action: 'copy';
|
|
15
|
+
target: {
|
|
16
|
+
kind: Kind;
|
|
17
|
+
area: string;
|
|
18
|
+
segments: string[];
|
|
19
|
+
};
|
|
20
|
+
} | {
|
|
21
|
+
id: string;
|
|
22
|
+
legacyHome: string;
|
|
23
|
+
match: string;
|
|
24
|
+
action: 'secret';
|
|
25
|
+
target: {
|
|
26
|
+
area: string;
|
|
27
|
+
name: string;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/** Rules the contract itself knows (only those the ecosystem documents state explicitly). Owners add their own. */
|
|
31
|
+
export declare const BUILTIN_RULES: readonly MigrationRule[];
|
|
32
|
+
export interface PlanEntry {
|
|
33
|
+
rule: string;
|
|
34
|
+
action: 'copy' | 'secret';
|
|
35
|
+
legacyHome: string;
|
|
36
|
+
sourceRel: string;
|
|
37
|
+
source: string;
|
|
38
|
+
bytes: number;
|
|
39
|
+
/** Absolute destination for a copy; null for a secret. */
|
|
40
|
+
dest: string | null;
|
|
41
|
+
/** Destination relative to its kind root, `/` separated (copy) or `area/name` (secret). */
|
|
42
|
+
destRel: string;
|
|
43
|
+
destKind: Kind | 'secret';
|
|
44
|
+
secret?: {
|
|
45
|
+
area: string;
|
|
46
|
+
name: string;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export interface Refusal {
|
|
50
|
+
path: string;
|
|
51
|
+
reason: string;
|
|
52
|
+
}
|
|
53
|
+
export interface MigrationPlan {
|
|
54
|
+
id: string;
|
|
55
|
+
homes: {
|
|
56
|
+
name: string;
|
|
57
|
+
path: string;
|
|
58
|
+
state: 'present' | 'absent' | 'refused-link';
|
|
59
|
+
}[];
|
|
60
|
+
entries: PlanEntry[];
|
|
61
|
+
refused: Refusal[];
|
|
62
|
+
unplaced: {
|
|
63
|
+
count: number;
|
|
64
|
+
sample: string[];
|
|
65
|
+
truncated: boolean;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Deterministic id: the same plan (rules, sources, destinations) always has the same journal. */
|
|
69
|
+
export declare function planId(entries: readonly {
|
|
70
|
+
rule: string;
|
|
71
|
+
sourceRel: string;
|
|
72
|
+
destRel: string;
|
|
73
|
+
legacyHome: string;
|
|
74
|
+
}[]): string;
|
|
75
|
+
export interface PlanOptions {
|
|
76
|
+
dirs: XenoDirs;
|
|
77
|
+
/** The person's home directory, where the legacy homes live. */
|
|
78
|
+
home: string;
|
|
79
|
+
rules?: readonly MigrationRule[];
|
|
80
|
+
legacyHomes?: readonly string[];
|
|
81
|
+
}
|
|
82
|
+
export declare function planMigration(options: PlanOptions): MigrationPlan;
|
|
83
|
+
export type EntryStatus = 'copied' | 'already' | 'secret' | 'conflict' | 'refused' | 'failed';
|
|
84
|
+
export interface EntryResult {
|
|
85
|
+
rule: string;
|
|
86
|
+
legacyHome: string;
|
|
87
|
+
sourceRel: string;
|
|
88
|
+
dest: string | null;
|
|
89
|
+
destRel: string;
|
|
90
|
+
status: EntryStatus;
|
|
91
|
+
bytes: number;
|
|
92
|
+
/** SHA-256 of the file's bytes. Never recorded for a secret. */
|
|
93
|
+
sha256?: string;
|
|
94
|
+
reason?: string;
|
|
95
|
+
}
|
|
96
|
+
export interface SecretSink {
|
|
97
|
+
set(area: string, name: string, value: Uint8Array): Promise<void>;
|
|
98
|
+
get(area: string, name: string): Promise<Uint8Array | null>;
|
|
99
|
+
}
|
|
100
|
+
export interface RunOptions {
|
|
101
|
+
dirs: XenoDirs;
|
|
102
|
+
/** Nothing is written unless this is true (dry run by default). */
|
|
103
|
+
confirm?: boolean;
|
|
104
|
+
/** Required to migrate `secret` entries; without it they are reported, not migrated. */
|
|
105
|
+
secrets?: SecretSink;
|
|
106
|
+
/** Write XENO-MIGRATED.txt into each legacy home (default true). */
|
|
107
|
+
writeNote?: boolean;
|
|
108
|
+
}
|
|
109
|
+
export interface MigrationResult {
|
|
110
|
+
id: string;
|
|
111
|
+
confirmed: boolean;
|
|
112
|
+
/** True only when every planned entry is copied/already/secret-verified and nothing was refused. A product may switch only on true. */
|
|
113
|
+
ok: boolean;
|
|
114
|
+
entries: EntryResult[];
|
|
115
|
+
refused: Refusal[];
|
|
116
|
+
unplaced: MigrationPlan['unplaced'];
|
|
117
|
+
journal: string | null;
|
|
118
|
+
/** Plaintext credential files that still sit in a legacy home; deleting them is a person's confirmed step. */
|
|
119
|
+
plaintextRemains: string[];
|
|
120
|
+
}
|
|
121
|
+
export declare function journalPath(dirs: XenoDirs, id: string): string;
|
|
122
|
+
export declare function readJournal(path: string): Promise<Record<string, unknown>[]>;
|
|
123
|
+
export declare function runMigration(plan: MigrationPlan, options: RunOptions): Promise<MigrationResult>;
|
|
124
|
+
export interface VerifyResult {
|
|
125
|
+
id: string;
|
|
126
|
+
complete: boolean;
|
|
127
|
+
checked: number;
|
|
128
|
+
problems: string[];
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Re-checks a finished migration against its journal: every copied destination still exists and still hashes to the
|
|
132
|
+
* recorded SHA-256. A product switches to the new location only when `complete` is true.
|
|
133
|
+
*/
|
|
134
|
+
export declare function verifyMigration(dirs: XenoDirs, id: string): Promise<VerifyResult>;
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { createReadStream, createWriteStream, lstatSync, readdirSync, promises as fsp } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
import { INPUTS_JSON, LEGACY_MAP_JSON } from "../generated/contract.js";
|
|
5
|
+
import { atomicWriteFile } from "./atomic.js";
|
|
6
|
+
import { DirsError } from "./errors.js";
|
|
7
|
+
import { assertSegment } from "./segments.js";
|
|
8
|
+
/** Rules the contract itself knows (only those the ecosystem documents state explicitly). Owners add their own. */
|
|
9
|
+
export const BUILTIN_RULES = LEGACY_MAP_JSON.rules;
|
|
10
|
+
const SAMPLE = 200;
|
|
11
|
+
const WALK_CAP = 500_000;
|
|
12
|
+
const isLink = (p) => lstatSync(p).isSymbolicLink();
|
|
13
|
+
function globMatch(pattern, name) {
|
|
14
|
+
if (!pattern.includes('*'))
|
|
15
|
+
return pattern === name;
|
|
16
|
+
const re = new RegExp('^' + pattern.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$');
|
|
17
|
+
return re.test(name);
|
|
18
|
+
}
|
|
19
|
+
function matchRule(rule, rel) {
|
|
20
|
+
const want = rule.match.split('/');
|
|
21
|
+
const got = rel.split('/');
|
|
22
|
+
if (want.length !== got.length)
|
|
23
|
+
return null;
|
|
24
|
+
for (let i = 0; i < want.length - 1; i++)
|
|
25
|
+
if (want[i] !== got[i])
|
|
26
|
+
return null;
|
|
27
|
+
const last = got[got.length - 1];
|
|
28
|
+
return globMatch(want[want.length - 1], last) ? { file: last } : null;
|
|
29
|
+
}
|
|
30
|
+
const fill = (s, file) => s.split('{file}').join(file);
|
|
31
|
+
/** Deterministic id: the same plan (rules, sources, destinations) always has the same journal. */
|
|
32
|
+
export function planId(entries) {
|
|
33
|
+
const lines = entries.map((e) => `${e.rule}\t${e.legacyHome}\t${e.sourceRel}\t${e.destRel}`).sort().join('\n');
|
|
34
|
+
return 'm-' + createHash('sha256').update(lines).digest('hex').slice(0, 12);
|
|
35
|
+
}
|
|
36
|
+
export function planMigration(options) {
|
|
37
|
+
const rules = [...BUILTIN_RULES, ...(options.rules ?? [])];
|
|
38
|
+
const seen = new Set();
|
|
39
|
+
for (const r of rules) {
|
|
40
|
+
if (seen.has(r.id))
|
|
41
|
+
throw new DirsError('invalid-argument', `duplicate migration rule id: ${r.id}`);
|
|
42
|
+
seen.add(r.id);
|
|
43
|
+
}
|
|
44
|
+
const names = options.legacyHomes ?? INPUTS_JSON.legacyHomes;
|
|
45
|
+
const homes = [];
|
|
46
|
+
const entries = [];
|
|
47
|
+
const refused = [];
|
|
48
|
+
const unplaced = { count: 0, sample: [], truncated: false };
|
|
49
|
+
let visited = 0;
|
|
50
|
+
const sep = options.dirs.platform === 'windows' ? '\\' : '/';
|
|
51
|
+
for (const name of names) {
|
|
52
|
+
const path = options.home + sep + name;
|
|
53
|
+
let st;
|
|
54
|
+
try {
|
|
55
|
+
st = lstatSync(path);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
homes.push({ name, path, state: 'absent' });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (st.isSymbolicLink()) {
|
|
62
|
+
homes.push({ name, path, state: 'refused-link' });
|
|
63
|
+
refused.push({ path, reason: 'the legacy home is a link or junction' });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!st.isDirectory()) {
|
|
67
|
+
homes.push({ name, path, state: 'absent' });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
homes.push({ name, path, state: 'present' });
|
|
71
|
+
const mine = rules.filter((r) => r.legacyHome === name);
|
|
72
|
+
const walk = (dir, rel) => {
|
|
73
|
+
let list;
|
|
74
|
+
try {
|
|
75
|
+
list = readdirSync(dir);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
refused.push({ path: dir, reason: 'unreadable directory' });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
for (const entry of list) {
|
|
82
|
+
if (++visited > WALK_CAP) {
|
|
83
|
+
unplaced.truncated = true;
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const abs = dir + sep + entry;
|
|
87
|
+
const r = rel ? `${rel}/${entry}` : entry;
|
|
88
|
+
const s = lstatSync(abs);
|
|
89
|
+
const hits = mine.map((rule) => ({ rule, m: matchRule(rule, r) })).filter((h) => h.m !== null);
|
|
90
|
+
if (s.isSymbolicLink()) {
|
|
91
|
+
if (hits.length > 0)
|
|
92
|
+
refused.push({ path: abs, reason: 'a link or junction is never followed' });
|
|
93
|
+
else {
|
|
94
|
+
unplaced.count++;
|
|
95
|
+
if (unplaced.sample.length < SAMPLE)
|
|
96
|
+
unplaced.sample.push(`${name}/${r} (link)`);
|
|
97
|
+
}
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (s.isDirectory()) {
|
|
101
|
+
walk(abs, r);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (hits.length === 0) {
|
|
105
|
+
unplaced.count++;
|
|
106
|
+
if (unplaced.sample.length < SAMPLE)
|
|
107
|
+
unplaced.sample.push(`${name}/${r}`);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (hits.length > 1) {
|
|
111
|
+
refused.push({ path: abs, reason: `ambiguous: rules ${hits.map((h) => h.rule.id).join(', ')} all match` });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const { rule, m } = hits[0];
|
|
115
|
+
try {
|
|
116
|
+
if (rule.action === 'copy') {
|
|
117
|
+
const segs = rule.target.segments.map((x) => fill(x, m.file));
|
|
118
|
+
const dest = options.dirs.path(rule.target.kind, rule.target.area, ...segs);
|
|
119
|
+
entries.push({ rule: rule.id, action: 'copy', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest, destRel: [rule.target.area, ...segs].join('/'), destKind: rule.target.kind });
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
const sn = fill(rule.target.name, m.file);
|
|
123
|
+
assertSegment(sn, 'secret name');
|
|
124
|
+
options.dirs.path('secrets', rule.target.area, sn + '.secret'); // validates area and kind
|
|
125
|
+
entries.push({ rule: rule.id, action: 'secret', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest: null, destRel: `${rule.target.area}/${sn}`, destKind: 'secret', secret: { area: rule.target.area, name: sn } });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
refused.push({ path: abs, reason: `rule ${rule.id}: ${e.message}` });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
walk(path, '');
|
|
134
|
+
}
|
|
135
|
+
// Two sources must never map to one destination.
|
|
136
|
+
const byDest = new Map();
|
|
137
|
+
for (const e of entries)
|
|
138
|
+
byDest.set(`${e.destKind}:${e.destRel}`, [...(byDest.get(`${e.destKind}:${e.destRel}`) ?? []), e]);
|
|
139
|
+
const clean = [];
|
|
140
|
+
for (const group of byDest.values()) {
|
|
141
|
+
if (group.length === 1)
|
|
142
|
+
clean.push(group[0]);
|
|
143
|
+
else
|
|
144
|
+
for (const e of group)
|
|
145
|
+
refused.push({ path: e.source, reason: `destination collision: ${group.length} sources map to ${e.destRel}` });
|
|
146
|
+
}
|
|
147
|
+
clean.sort((a, b) => { const x = a.legacyHome + a.sourceRel, y = b.legacyHome + b.sourceRel; return x < y ? -1 : x > y ? 1 : 0; });
|
|
148
|
+
return { id: planId(clean), homes, entries: clean, refused, unplaced };
|
|
149
|
+
}
|
|
150
|
+
const BUF = 1 << 20;
|
|
151
|
+
function hashFile(path) {
|
|
152
|
+
return new Promise((resolve, reject) => {
|
|
153
|
+
const h = createHash('sha256');
|
|
154
|
+
createReadStream(path, { highWaterMark: BUF }).on('data', (c) => h.update(c)).on('error', reject).on('end', () => resolve(h.digest('hex')));
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function assertNoLinksBelow(root, parts, sep) {
|
|
158
|
+
let cur = root;
|
|
159
|
+
for (const p of parts) {
|
|
160
|
+
cur += sep + p;
|
|
161
|
+
let st;
|
|
162
|
+
try {
|
|
163
|
+
st = lstatSync(cur);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (st.isSymbolicLink())
|
|
169
|
+
throw new DirsError('migration-refused', 'a link or junction on the path is never followed', { path: cur });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async function copyVerified(source, dest) {
|
|
173
|
+
await fsp.mkdir(dirname(dest), { recursive: true });
|
|
174
|
+
const tmp = join(dirname(dest), `.${basename(dest)}.${process.pid}.${randomBytes(6).toString('hex')}.migrating.tmp`);
|
|
175
|
+
const h = createHash('sha256');
|
|
176
|
+
let bytes = 0;
|
|
177
|
+
try {
|
|
178
|
+
await new Promise((resolve, reject) => {
|
|
179
|
+
const out = createWriteStream(tmp, { flags: 'wx' });
|
|
180
|
+
const src = createReadStream(source, { highWaterMark: BUF });
|
|
181
|
+
src.on('data', (c) => { h.update(c); bytes += c.length; });
|
|
182
|
+
src.on('error', reject);
|
|
183
|
+
out.on('error', reject);
|
|
184
|
+
out.on('finish', () => resolve());
|
|
185
|
+
src.pipe(out);
|
|
186
|
+
});
|
|
187
|
+
const fh = await fsp.open(tmp, 'r+');
|
|
188
|
+
try {
|
|
189
|
+
await fh.sync();
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
await fh.close();
|
|
193
|
+
}
|
|
194
|
+
const sha = h.digest('hex');
|
|
195
|
+
try {
|
|
196
|
+
await fsp.link(tmp, dest); // create-if-absent, atomically
|
|
197
|
+
}
|
|
198
|
+
catch (e) {
|
|
199
|
+
const code = e.code;
|
|
200
|
+
if (code === 'EEXIST')
|
|
201
|
+
return 'conflict';
|
|
202
|
+
if (code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EXDEV')
|
|
203
|
+
throw e;
|
|
204
|
+
// Filesystem without hard links: a no-clobber rename after re-checking the destination is still absent.
|
|
205
|
+
try {
|
|
206
|
+
await fsp.lstat(dest);
|
|
207
|
+
return 'conflict';
|
|
208
|
+
}
|
|
209
|
+
catch { /* absent */ }
|
|
210
|
+
await fsp.rename(tmp, dest);
|
|
211
|
+
}
|
|
212
|
+
if ((await hashFile(dest)) !== sha) {
|
|
213
|
+
await fsp.rm(dest, { force: true });
|
|
214
|
+
throw new DirsError('migration-refused', 'the copy did not verify by hash', { dest });
|
|
215
|
+
}
|
|
216
|
+
if ((await hashFile(source)) !== sha) {
|
|
217
|
+
await fsp.rm(dest, { force: true });
|
|
218
|
+
throw new DirsError('migration-refused', 'the source changed while it was being copied', { source });
|
|
219
|
+
}
|
|
220
|
+
return { sha256: sha, bytes };
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
await fsp.rm(tmp, { force: true }).catch(() => undefined);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
export function journalPath(dirs, id) {
|
|
227
|
+
return dirs.path('state', 'platform', 'migrations', `${id}.jsonl`);
|
|
228
|
+
}
|
|
229
|
+
async function appendJournal(path, record) {
|
|
230
|
+
await fsp.mkdir(dirname(path), { recursive: true });
|
|
231
|
+
const fh = await fsp.open(path, 'a');
|
|
232
|
+
try {
|
|
233
|
+
await fh.writeFile(JSON.stringify(record) + '\n');
|
|
234
|
+
await fh.sync();
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
await fh.close();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
export async function readJournal(path) {
|
|
241
|
+
let text;
|
|
242
|
+
try {
|
|
243
|
+
text = await fsp.readFile(path, 'utf8');
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
if (e.code === 'ENOENT')
|
|
247
|
+
return [];
|
|
248
|
+
throw e;
|
|
249
|
+
}
|
|
250
|
+
const out = [];
|
|
251
|
+
const lines = text.split('\n').filter((l) => l !== '');
|
|
252
|
+
lines.forEach((l, i) => {
|
|
253
|
+
try {
|
|
254
|
+
out.push(JSON.parse(l));
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
if (i !== lines.length - 1)
|
|
258
|
+
throw new DirsError('migration-refused', 'the migration journal is damaged before its last line', { path }); /* a torn last line is tolerated */
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
export async function runMigration(plan, options) {
|
|
264
|
+
const { dirs } = options;
|
|
265
|
+
const sep = dirs.platform === 'windows' ? '\\' : '/';
|
|
266
|
+
const base = {
|
|
267
|
+
id: plan.id, confirmed: options.confirm === true, ok: false, entries: [], refused: plan.refused, unplaced: plan.unplaced, journal: null, plaintextRemains: [],
|
|
268
|
+
};
|
|
269
|
+
if (options.confirm !== true) {
|
|
270
|
+
base.entries = plan.entries.map((e) => ({ rule: e.rule, legacyHome: e.legacyHome, sourceRel: e.sourceRel, dest: e.dest, destRel: e.destRel, status: 'refused', bytes: e.bytes, reason: 'dry run: pass confirm to migrate' }));
|
|
271
|
+
return base;
|
|
272
|
+
}
|
|
273
|
+
await dirs.ensureLayout();
|
|
274
|
+
const journal = journalPath(dirs, plan.id);
|
|
275
|
+
base.journal = journal;
|
|
276
|
+
return dirs.withLock('platform', 'migrate', async () => {
|
|
277
|
+
const prior = await readJournal(journal);
|
|
278
|
+
await appendJournal(journal, { op: prior.length === 0 ? 'begin' : 'resume', id: plan.id, at: new Date().toISOString(), entries: plan.entries.length, refused: plan.refused.length });
|
|
279
|
+
const results = [];
|
|
280
|
+
for (const e of plan.entries) {
|
|
281
|
+
const r = { rule: e.rule, legacyHome: e.legacyHome, sourceRel: e.sourceRel, dest: e.dest, destRel: e.destRel, status: 'failed', bytes: e.bytes };
|
|
282
|
+
try {
|
|
283
|
+
const home = plan.homes.find((h) => h.name === e.legacyHome);
|
|
284
|
+
assertNoLinksBelow(home.path, e.sourceRel.split('/'), sep);
|
|
285
|
+
if (isLink(home.path))
|
|
286
|
+
throw new DirsError('migration-refused', 'the legacy home is a link or junction');
|
|
287
|
+
if (!lstatSync(e.source).isFile())
|
|
288
|
+
throw new DirsError('migration-refused', 'the source is not a regular file');
|
|
289
|
+
if (e.action === 'copy') {
|
|
290
|
+
const dest = e.dest;
|
|
291
|
+
assertNoLinksBelow(dirs.root(e.destKind), e.destRel.split('/'), sep);
|
|
292
|
+
const srcHash = await hashFile(e.source);
|
|
293
|
+
let existing = null;
|
|
294
|
+
try {
|
|
295
|
+
if (lstatSync(dest).isFile())
|
|
296
|
+
existing = await hashFile(dest);
|
|
297
|
+
else
|
|
298
|
+
throw new DirsError('migration-refused', 'the destination exists and is not a file');
|
|
299
|
+
}
|
|
300
|
+
catch (err) {
|
|
301
|
+
if (err instanceof DirsError)
|
|
302
|
+
throw err;
|
|
303
|
+
}
|
|
304
|
+
if (existing !== null) {
|
|
305
|
+
if (existing === srcHash) {
|
|
306
|
+
r.status = 'already';
|
|
307
|
+
r.sha256 = srcHash;
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
r.status = 'conflict';
|
|
311
|
+
r.reason = 'the destination already holds different bytes; it is not overwritten';
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
const c = await copyVerified(e.source, dest);
|
|
316
|
+
if (c === 'conflict') {
|
|
317
|
+
r.status = 'conflict';
|
|
318
|
+
r.reason = 'the destination appeared with different bytes; it is not overwritten';
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
r.status = 'copied';
|
|
322
|
+
r.sha256 = c.sha256;
|
|
323
|
+
r.bytes = c.bytes;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
if (options.secrets === undefined) {
|
|
329
|
+
r.status = 'refused';
|
|
330
|
+
r.reason = 'no secret sink supplied; the plaintext file is left as it is';
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
const { area, name } = e.secret;
|
|
334
|
+
const bytes = await fsp.readFile(e.source);
|
|
335
|
+
const existing = await options.secrets.get(area, name);
|
|
336
|
+
if (existing !== null && !Buffer.from(existing).equals(bytes)) {
|
|
337
|
+
r.status = 'conflict';
|
|
338
|
+
r.reason = 'a different secret already exists at the destination; it is not overwritten';
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
if (existing === null)
|
|
342
|
+
await options.secrets.set(area, name, bytes);
|
|
343
|
+
const back = await options.secrets.get(area, name);
|
|
344
|
+
if (back === null || !Buffer.from(back).equals(bytes))
|
|
345
|
+
throw new DirsError('migration-refused', 'the secret did not verify after it was stored');
|
|
346
|
+
r.status = existing === null ? 'secret' : 'already';
|
|
347
|
+
}
|
|
348
|
+
bytes.fill(0);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
catch (err) {
|
|
353
|
+
r.status = err instanceof DirsError && err.code === 'migration-refused' ? 'refused' : 'failed';
|
|
354
|
+
r.reason = err.message;
|
|
355
|
+
}
|
|
356
|
+
results.push(r);
|
|
357
|
+
await appendJournal(journal, { op: r.status, rule: r.rule, home: r.legacyHome, source: r.sourceRel, dest: r.destRel, destPath: r.dest, bytes: r.bytes, ...(r.sha256 ? { sha256: r.sha256 } : {}), ...(r.reason ? { reason: r.reason } : {}) });
|
|
358
|
+
}
|
|
359
|
+
const good = (s) => s === 'copied' || s === 'already' || s === 'secret';
|
|
360
|
+
const ok = results.every((r) => good(r.status)) && plan.refused.length === 0;
|
|
361
|
+
await appendJournal(journal, { op: 'end', ok, at: new Date().toISOString(), counts: results.reduce((m, r) => ({ ...m, [r.status]: (m[r.status] ?? 0) + 1 }), {}), unplaced: plan.unplaced.count });
|
|
362
|
+
if (options.writeNote !== false) {
|
|
363
|
+
for (const h of plan.homes.filter((x) => x.state === 'present')) {
|
|
364
|
+
const mine = results.filter((r) => r.legacyHome === h.name && good(r.status));
|
|
365
|
+
const note = [
|
|
366
|
+
'XENO has copied what it recognised from this folder to the new XENO layout.',
|
|
367
|
+
'Nothing here was deleted or moved. Removing this folder is a step only you confirm.',
|
|
368
|
+
'',
|
|
369
|
+
`Journal: ${journal}`,
|
|
370
|
+
`Layout roots: ${['config', 'data', 'secrets', 'state', 'cache', 'run'].map((k) => `${k}=${dirs.root(k)}`).join('; ')}`,
|
|
371
|
+
'',
|
|
372
|
+
...(mine.length ? ['Copied or already present:', ...mine.map((r) => ` ${r.sourceRel} -> ${r.destRel}`)] : ['Nothing from this folder was copied.']),
|
|
373
|
+
'',
|
|
374
|
+
].join('\n');
|
|
375
|
+
try {
|
|
376
|
+
await atomicWriteFile(h.path + sep + 'XENO-MIGRATED.txt', note);
|
|
377
|
+
}
|
|
378
|
+
catch { /* a read-only legacy home is not a failure of the migration */ }
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
base.entries = results;
|
|
382
|
+
base.ok = ok;
|
|
383
|
+
base.plaintextRemains = plan.entries.filter((e) => e.action === 'secret' && results.some((r) => r.sourceRel === e.sourceRel && r.legacyHome === e.legacyHome && (r.status === 'secret' || r.status === 'already'))).map((e) => e.source);
|
|
384
|
+
return base;
|
|
385
|
+
}, { owner: 'migration', timeoutMs: 60_000 });
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Re-checks a finished migration against its journal: every copied destination still exists and still hashes to the
|
|
389
|
+
* recorded SHA-256. A product switches to the new location only when `complete` is true.
|
|
390
|
+
*/
|
|
391
|
+
export async function verifyMigration(dirs, id) {
|
|
392
|
+
const records = await readJournal(journalPath(dirs, id));
|
|
393
|
+
const problems = [];
|
|
394
|
+
let checked = 0;
|
|
395
|
+
if (records.length === 0)
|
|
396
|
+
return { id, complete: false, checked, problems: ['no journal'] };
|
|
397
|
+
const ends = records.filter((r) => r['op'] === 'end');
|
|
398
|
+
const last = ends[ends.length - 1];
|
|
399
|
+
if (!last)
|
|
400
|
+
problems.push('the migration never finished');
|
|
401
|
+
else if (last['ok'] !== true)
|
|
402
|
+
problems.push('the last run did not finish cleanly');
|
|
403
|
+
const latest = new Map();
|
|
404
|
+
for (const r of records)
|
|
405
|
+
if (typeof r['dest'] === 'string' && typeof r['source'] === 'string')
|
|
406
|
+
latest.set(`${String(r['home'])}:${String(r['source'])}`, r);
|
|
407
|
+
for (const r of latest.values()) {
|
|
408
|
+
const op = r['op'];
|
|
409
|
+
if ((op === 'copied' || op === 'already') && r['destPath'] !== null) {
|
|
410
|
+
checked++;
|
|
411
|
+
const dest = r['destPath'];
|
|
412
|
+
if (typeof dest !== 'string') {
|
|
413
|
+
problems.push(`${String(r['dest'])}: journal has no destination path`);
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
try {
|
|
417
|
+
if ((await hashFile(dest)) !== r['sha256'])
|
|
418
|
+
problems.push(`${String(r['dest'])}: bytes differ from the journal`);
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
problems.push(`${String(r['dest'])}: missing`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
else if (op !== 'secret' && op !== 'already')
|
|
425
|
+
problems.push(`${String(r['source'])}: ${String(op)}`);
|
|
426
|
+
}
|
|
427
|
+
return { id, complete: problems.length === 0, checked, problems };
|
|
428
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** True when a process with this pid exists (a process we may not signal still exists). */
|
|
2
|
+
export declare function isProcessAlive(pid: number): boolean;
|
|
3
|
+
/**
|
|
4
|
+
* An opaque, stable identifier for "this process, started at this moment", or null when it cannot be read.
|
|
5
|
+
* A pid alone is not an identity (pids are reused); pid + start time is. The value is only ever compared for
|
|
6
|
+
* equality with one this function returned earlier on the same machine.
|
|
7
|
+
*/
|
|
8
|
+
export declare function processStartTime(pid: number): Promise<string | null>;
|
|
9
|
+
/** Start-time identity of this process, computed once. */
|
|
10
|
+
export declare function ownProcessStartTime(): Promise<string | null>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
/** True when a process with this pid exists (a process we may not signal still exists). */
|
|
4
|
+
export function isProcessAlive(pid) {
|
|
5
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
6
|
+
return false;
|
|
7
|
+
try {
|
|
8
|
+
process.kill(pid, 0);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch (e) {
|
|
12
|
+
return e.code === 'EPERM';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function run(file, args, timeoutMs = 10_000) {
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
execFile(file, args, { timeout: timeoutMs, windowsHide: true }, (err, stdout) => resolve(err ? null : String(stdout).trim()));
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* An opaque, stable identifier for "this process, started at this moment", or null when it cannot be read.
|
|
22
|
+
* A pid alone is not an identity (pids are reused); pid + start time is. The value is only ever compared for
|
|
23
|
+
* equality with one this function returned earlier on the same machine.
|
|
24
|
+
*/
|
|
25
|
+
export async function processStartTime(pid) {
|
|
26
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
27
|
+
return null;
|
|
28
|
+
try {
|
|
29
|
+
if (process.platform === 'linux') {
|
|
30
|
+
const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
|
|
31
|
+
const rest = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
|
32
|
+
const ticks = rest[19];
|
|
33
|
+
if (!ticks)
|
|
34
|
+
return null;
|
|
35
|
+
const boot = (await readFile('/proc/sys/kernel/random/boot_id', 'utf8').catch(() => '')).trim();
|
|
36
|
+
return `linux:${boot}:${ticks}`;
|
|
37
|
+
}
|
|
38
|
+
if (process.platform === 'darwin') {
|
|
39
|
+
const out = await run('ps', ['-o', 'lstart=', '-p', String(pid)]);
|
|
40
|
+
return out ? `darwin:${out}` : null;
|
|
41
|
+
}
|
|
42
|
+
if (process.platform === 'win32') {
|
|
43
|
+
const root = process.env['SystemRoot'] ?? 'C:\\Windows';
|
|
44
|
+
const ps = `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
|
|
45
|
+
const out = await run(ps, [
|
|
46
|
+
'-NoProfile', '-NonInteractive', '-Command',
|
|
47
|
+
`$p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue; if ($p) { $p.StartTime.ToFileTimeUtc() }`,
|
|
48
|
+
], 30_000);
|
|
49
|
+
return out && /^\d+$/.test(out) ? `win32:${out}` : null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
let ownStart = null;
|
|
58
|
+
/** Start-time identity of this process, computed once. */
|
|
59
|
+
export function ownProcessStartTime() {
|
|
60
|
+
ownStart ??= processStartTime(process.pid);
|
|
61
|
+
return ownStart;
|
|
62
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Kind } from './roots.ts';
|
|
2
|
+
export interface AreaEntry {
|
|
3
|
+
/** Registered name, e.g. `agents/environments` or the pattern `apps/<slug>`. */
|
|
4
|
+
area: string;
|
|
5
|
+
owner: string;
|
|
6
|
+
responsibility: string;
|
|
7
|
+
uses: readonly Kind[];
|
|
8
|
+
slugPattern?: string;
|
|
9
|
+
kindNotes?: Readonly<Record<string, string>>;
|
|
10
|
+
}
|
|
11
|
+
export declare const AREAS: readonly AreaEntry[];
|
|
12
|
+
export declare const LOCK_SUFFIX: string;
|
|
13
|
+
/** Finds the registered entry for a concrete area name, or null. `apps/<slug>` matches by slug pattern. */
|
|
14
|
+
export declare function findArea(area: string): AreaEntry | null;
|
|
15
|
+
/**
|
|
16
|
+
* Resolves (kind, area, segments) against the registry and returns the path relative to the kind root with `/`
|
|
17
|
+
* separators. Refuses anything unregistered. A `run` entry for an area that does not use `run` accepts locks only.
|
|
18
|
+
*/
|
|
19
|
+
export declare function registeredRelativePath(kind: string, area: string, segments: readonly string[]): string;
|
|
20
|
+
/** Relative path of a lock file under the run root. Every registered area may hold locks (spec section 8). */
|
|
21
|
+
export declare function lockRelativePath(area: string, name: string): string;
|
|
22
|
+
/** Top-level directory names a root may legitimately hold, derived from the registry (used by doctor). */
|
|
23
|
+
export declare function expectedTopLevel(kind: Kind): {
|
|
24
|
+
names: Set<string>;
|
|
25
|
+
appSlugs: boolean;
|
|
26
|
+
nested: Map<string, Set<string>>;
|
|
27
|
+
};
|