@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,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `@xenosystem/primitives/updates` — an installed XENO app updates only for an account allowed to.
|
|
4
|
+
*
|
|
5
|
+
* Owner, 2026-10-25: "nobody without a plan should be able to download them." The platform serves each app's
|
|
6
|
+
* update feed behind sign-in and the plan (`GET /api/updates/<slug>/feed/latest.yml`, xeno-platform
|
|
7
|
+
* `productDownloadRoutes.js`): every installer URL in it is a five-minute grant for exactly that version, and
|
|
8
|
+
* the sha512 is untouched, so electron-updater still verifies the bytes. This family points an app's
|
|
9
|
+
* electron-updater at that feed with the account's own token. It is the ONE place every app does this, so the
|
|
10
|
+
* gate cannot be implemented differently, or forgotten, per app (`docs/DOWNLOAD-GATE.md` Phase 3b).
|
|
11
|
+
*
|
|
12
|
+
* Model-free and dependency-free: the app passes its own `autoUpdater` and a function that returns its current
|
|
13
|
+
* access token (its account SDK). Nothing here stores a token, and no token appears in any result or error.
|
|
14
|
+
*
|
|
15
|
+
* Outcomes are states, not exceptions, because "not signed in" and "no plan" are normal for a free install:
|
|
16
|
+
* signed-out no token: the network is never touched
|
|
17
|
+
* not-entitled the platform said 401/403: the account has no plan that allows updates
|
|
18
|
+
* up-to-date / available / error
|
|
19
|
+
*/
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.gatedFeedUrl = gatedFeedUrl;
|
|
22
|
+
exports.isNewer = isNewer;
|
|
23
|
+
exports.createGrantedUpdater = createGrantedUpdater;
|
|
24
|
+
/** The gated feed for a product. electron-updater appends `/latest.yml` (or `-linux`/`-mac`) itself. */
|
|
25
|
+
function gatedFeedUrl(platformBase, slug) {
|
|
26
|
+
if (!/^[a-z0-9-]+$/.test(slug))
|
|
27
|
+
throw new Error(`invalid product slug: ${slug}`);
|
|
28
|
+
const base = String(platformBase).replace(/\/+$/, '');
|
|
29
|
+
if (!/^https:\/\//.test(base) && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(base)) {
|
|
30
|
+
// A token must never ride plain HTTP to anything but a local test server.
|
|
31
|
+
throw new Error('platformBase must be https (or a loopback test server)');
|
|
32
|
+
}
|
|
33
|
+
return `${base}/api/updates/${slug}/feed`;
|
|
34
|
+
}
|
|
35
|
+
/** Compare dotted versions numerically; a pre-release tag sorts below its release. */
|
|
36
|
+
function isNewer(candidate, current) {
|
|
37
|
+
const parse = (v) => {
|
|
38
|
+
const [core = '', pre] = String(v).replace(/^v/i, '').split('-', 2);
|
|
39
|
+
return { nums: core.split('.').map((n) => Number.parseInt(n, 10) || 0), pre: pre ?? null };
|
|
40
|
+
};
|
|
41
|
+
const a = parse(candidate);
|
|
42
|
+
const b = parse(current);
|
|
43
|
+
for (let i = 0; i < Math.max(a.nums.length, b.nums.length); i += 1) {
|
|
44
|
+
const d = (a.nums[i] ?? 0) - (b.nums[i] ?? 0);
|
|
45
|
+
if (d !== 0)
|
|
46
|
+
return d > 0;
|
|
47
|
+
}
|
|
48
|
+
if (a.pre === b.pre)
|
|
49
|
+
return false;
|
|
50
|
+
if (a.pre === null)
|
|
51
|
+
return true;
|
|
52
|
+
if (b.pre === null)
|
|
53
|
+
return false;
|
|
54
|
+
return a.pre > b.pre;
|
|
55
|
+
}
|
|
56
|
+
const statusOf = (error) => {
|
|
57
|
+
const e = error;
|
|
58
|
+
const direct = Number(e?.statusCode ?? e?.status);
|
|
59
|
+
if (Number.isInteger(direct) && direct > 0)
|
|
60
|
+
return direct;
|
|
61
|
+
// electron-updater's HttpError message starts with the status ("403 Forbidden …")
|
|
62
|
+
const m = /\b(4\d\d|5\d\d)\b/.exec(String(e?.message ?? ''));
|
|
63
|
+
return m ? Number(m[1]) : null;
|
|
64
|
+
};
|
|
65
|
+
function createGrantedUpdater(options) {
|
|
66
|
+
const { slug, platformBase, getAccessToken, updater, currentVersion } = options;
|
|
67
|
+
const url = gatedFeedUrl(platformBase, slug);
|
|
68
|
+
return {
|
|
69
|
+
feedUrl: url,
|
|
70
|
+
/** Configure the updater with a FRESH token and ask the gated feed. Call before every check. */
|
|
71
|
+
async check() {
|
|
72
|
+
let token = null;
|
|
73
|
+
try {
|
|
74
|
+
token = await getAccessToken();
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
token = null;
|
|
78
|
+
}
|
|
79
|
+
if (!token) {
|
|
80
|
+
updater.requestHeaders = null;
|
|
81
|
+
return { state: 'signed-out' };
|
|
82
|
+
}
|
|
83
|
+
updater.setFeedURL({ provider: 'generic', url });
|
|
84
|
+
updater.requestHeaders = { Authorization: `Bearer ${token}` };
|
|
85
|
+
// A grant URL with `.blockmap` appended is not a file; a full download is correct and is what runs.
|
|
86
|
+
updater.disableDifferentialDownload = true;
|
|
87
|
+
try {
|
|
88
|
+
const result = await updater.checkForUpdates();
|
|
89
|
+
const version = result?.updateInfo?.version;
|
|
90
|
+
if (!version)
|
|
91
|
+
return { state: 'up-to-date', version: currentVersion };
|
|
92
|
+
return isNewer(version, currentVersion) ? { state: 'available', version } : { state: 'up-to-date', version: currentVersion };
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
const status = statusOf(error);
|
|
96
|
+
if (status === 401 || status === 403)
|
|
97
|
+
return { state: status === 401 ? 'signed-out' : 'not-entitled' };
|
|
98
|
+
return { state: 'error', code: status ? `http_${status}` : 'network' };
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface AtomicWriteOptions {
|
|
2
|
+
/** POSIX mode for the new file (ignored on Windows). Default 0o644; secrets use 0o600. */
|
|
3
|
+
mode?: number;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Atomic replace (spec section 8): write a temporary file in the same directory, flush it to disk, rename it over the
|
|
7
|
+
* target, flush the directory. A reader sees the old bytes or the new bytes, never a prefix.
|
|
8
|
+
*/
|
|
9
|
+
export declare function atomicWriteFile(target: string, data: string | Uint8Array, options?: AtomicWriteOptions): Promise<void>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { promises as fsp } from 'node:fs';
|
|
3
|
+
import { dirname, basename, join } from 'node:path';
|
|
4
|
+
const RETRYABLE = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
|
5
|
+
async function renameWithRetry(from, to) {
|
|
6
|
+
// On Windows a rename onto a file another process has open (a virus scanner, an indexer) fails transiently.
|
|
7
|
+
for (let attempt = 0;; attempt++) {
|
|
8
|
+
try {
|
|
9
|
+
await fsp.rename(from, to);
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
catch (e) {
|
|
13
|
+
const code = e.code ?? '';
|
|
14
|
+
if (process.platform !== 'win32' || !RETRYABLE.has(code) || attempt >= 15)
|
|
15
|
+
throw e;
|
|
16
|
+
await new Promise((r) => setTimeout(r, 20 + attempt * 10));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function syncDirectory(dir) {
|
|
21
|
+
// Windows cannot open a directory for fsync from Node; NTFS journals the rename itself.
|
|
22
|
+
if (process.platform === 'win32')
|
|
23
|
+
return;
|
|
24
|
+
const h = await fsp.open(dir, 'r');
|
|
25
|
+
try {
|
|
26
|
+
await h.sync();
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
await h.close();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Atomic replace (spec section 8): write a temporary file in the same directory, flush it to disk, rename it over the
|
|
34
|
+
* target, flush the directory. A reader sees the old bytes or the new bytes, never a prefix.
|
|
35
|
+
*/
|
|
36
|
+
export async function atomicWriteFile(target, data, options = {}) {
|
|
37
|
+
const dir = dirname(target);
|
|
38
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
39
|
+
const tmp = join(dir, `.${basename(target)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
|
|
40
|
+
let handle = null;
|
|
41
|
+
try {
|
|
42
|
+
handle = await fsp.open(tmp, 'wx', options.mode ?? 0o644);
|
|
43
|
+
await handle.writeFile(data);
|
|
44
|
+
await handle.sync();
|
|
45
|
+
await handle.close();
|
|
46
|
+
handle = null;
|
|
47
|
+
await renameWithRetry(tmp, target);
|
|
48
|
+
await syncDirectory(dir);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
if (handle !== null)
|
|
52
|
+
await handle.close().catch(() => undefined);
|
|
53
|
+
await fsp.rm(tmp, { force: true }).catch(() => undefined);
|
|
54
|
+
throw e;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// xeno-dirs-check [dir] [--json] [--self-test]
|
|
3
|
+
// Exit 0: clean. 1: violations (or the self-test could not fail). 2: usage.
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { checkSource, RULES, scanText } from "./check.js";
|
|
6
|
+
const args = process.argv.slice(2);
|
|
7
|
+
const flag = (n) => args.includes(n);
|
|
8
|
+
const positional = args.filter((a) => !a.startsWith('--'));
|
|
9
|
+
/** Proves the check can fail: every rule must fire on its own sample. Samples are assembled so this file stays clean. */
|
|
10
|
+
function selfTest() {
|
|
11
|
+
const h = 'home', d = 'dir';
|
|
12
|
+
const samples = {
|
|
13
|
+
'homedir-call': ['ts', `const p = os.${h}${d}();`],
|
|
14
|
+
'platform-dir-read': ['ts', `const a = process.env.APP${'DATA'};`],
|
|
15
|
+
'legacy-home-name': ['ts', `const x = join(base, '.xeno-${'agent'}');`],
|
|
16
|
+
'legacy-home-path': ['ts', `const x = '~/.${'xeno'}/config';`],
|
|
17
|
+
'legacy-home-env': ['ts', `const x = process.env.XENO_AGENT_${'HOME'};`],
|
|
18
|
+
};
|
|
19
|
+
let bad = 0;
|
|
20
|
+
for (const id of new Set(RULES.map((r) => r.id))) {
|
|
21
|
+
const [lang, text] = samples[id];
|
|
22
|
+
const hit = scanText('sample', text, lang).some((v) => v.rule === id);
|
|
23
|
+
const clean = scanText('sample', `// ${text}`, lang).length === 0;
|
|
24
|
+
const allowed = scanText('sample', `${text} // xeno-dirs-allow: self-test of the allow marker`, lang).length === 0;
|
|
25
|
+
if (!hit || !clean || !allowed) {
|
|
26
|
+
console.error(`self-test FAILED for ${id}: fires=${hit} comment-ignored=${clean} allow-honoured=${allowed}`);
|
|
27
|
+
bad++;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
console.log(bad === 0 ? `self-test ok: ${new Set(RULES.map((r) => r.id)).size} rules fire, comments and allow markers are honoured` : 'self-test FAILED');
|
|
31
|
+
return bad === 0 ? 0 : 1;
|
|
32
|
+
}
|
|
33
|
+
if (flag('--self-test'))
|
|
34
|
+
process.exit(selfTest());
|
|
35
|
+
if (positional.length > 1) {
|
|
36
|
+
console.error('usage: xeno-dirs-check [dir] [--json] [--self-test]');
|
|
37
|
+
process.exit(2);
|
|
38
|
+
}
|
|
39
|
+
const root = resolve(positional[0] ?? '.');
|
|
40
|
+
const result = checkSource(root);
|
|
41
|
+
if (flag('--json'))
|
|
42
|
+
console.log(JSON.stringify(result, null, 2));
|
|
43
|
+
else {
|
|
44
|
+
for (const v of result.violations)
|
|
45
|
+
console.log(`${v.file}:${v.line} ${v.rule} ${v.description}\n ${v.text}`);
|
|
46
|
+
console.log(result.ok ? `ok: ${result.filesScanned} files, no home-directory lookup or hard-coded XENO path outside the resolver` : `${result.violations.length} violation(s) in ${result.filesScanned} files`);
|
|
47
|
+
}
|
|
48
|
+
process.exit(result.ok ? 0 : 1);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The reusable static check every product runs in CI (XENO LOCAL HOME - SPEC.md section 8, check 1): no home-directory
|
|
3
|
+
* lookup and no hard-coded XENO location outside the resolver. A violation is a defect, not a convenience.
|
|
4
|
+
*
|
|
5
|
+
* Rules (each with a stable id so an allow entry names exactly one):
|
|
6
|
+
* homedir-call a call that asks the OS for the home directory (homedir(), home_dir(), Path.home(), UserHomeDir())
|
|
7
|
+
* platform-dir-read reading HOME, USERPROFILE, APPDATA, LOCALAPPDATA or XDG_* from the environment to build a path
|
|
8
|
+
* legacy-home-name the legacy folders .xeno-agent, .xeno-anima, .xeno-code
|
|
9
|
+
* legacy-home-path ~/.xeno, %USERPROFILE%\.xeno, $HOME/.xeno and the %APPDATA%\XENO form (a per-project `.xeno/` is fine)
|
|
10
|
+
* legacy-home-env a XENO_*_HOME variable other than XENO_HOME (the thirteen legacy overrides)
|
|
11
|
+
* A line (or the line above it) carrying `xeno-dirs-allow: <reason>` is exempt; the reason is mandatory.
|
|
12
|
+
*/
|
|
13
|
+
export interface Rule {
|
|
14
|
+
id: string;
|
|
15
|
+
description: string;
|
|
16
|
+
re: RegExp;
|
|
17
|
+
langs: readonly string[];
|
|
18
|
+
}
|
|
19
|
+
export declare const RULES: readonly Rule[];
|
|
20
|
+
export interface Violation {
|
|
21
|
+
file: string;
|
|
22
|
+
line: number;
|
|
23
|
+
rule: string;
|
|
24
|
+
description: string;
|
|
25
|
+
text: string;
|
|
26
|
+
}
|
|
27
|
+
export interface CheckConfig {
|
|
28
|
+
/** Files (relative, `/` separated, or `dir/**`) that are the resolver itself and may do what the rules forbid. */
|
|
29
|
+
resolverFiles?: string[];
|
|
30
|
+
exclude?: string[];
|
|
31
|
+
allow?: {
|
|
32
|
+
file: string;
|
|
33
|
+
rule: string;
|
|
34
|
+
reason: string;
|
|
35
|
+
}[];
|
|
36
|
+
}
|
|
37
|
+
export interface CheckResult {
|
|
38
|
+
ok: boolean;
|
|
39
|
+
filesScanned: number;
|
|
40
|
+
violations: Violation[];
|
|
41
|
+
config: string | null;
|
|
42
|
+
}
|
|
43
|
+
export declare const CONFIG_NAME = "xeno-dirs-check.json";
|
|
44
|
+
export declare function loadConfig(root: string): {
|
|
45
|
+
config: CheckConfig;
|
|
46
|
+
path: string | null;
|
|
47
|
+
};
|
|
48
|
+
export declare function scanText(file: string, text: string, lang: string): Violation[];
|
|
49
|
+
export declare function checkSource(root: string, override?: CheckConfig): CheckResult;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { lstatSync, readdirSync, readFileSync, existsSync } from 'node:fs';
|
|
2
|
+
import { join, relative, sep } from 'node:path';
|
|
3
|
+
const JS = ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts'];
|
|
4
|
+
export const RULES = [
|
|
5
|
+
{ id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\b(?:os\.)?homedir\s*\(|\.userInfo\s*\(\s*\)\s*\.homedir\b/, langs: JS },
|
|
6
|
+
{ id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\b(?:dirs::|env::)?home_dir\s*\(|\bdirs::(?:config|data|data_local|cache|state)_dir\s*\(|\bProjectDirs::from\b/, langs: ['rs'] },
|
|
7
|
+
{ id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\bPath\.home\s*\(|\bexpanduser\s*\(|\bplatformdirs\b|\buser_(?:config|data|cache|state)_dir\s*\(/, langs: ['py'] },
|
|
8
|
+
{ id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\bos\.User(?:Home|Config|Cache)Dir\s*\(/, langs: ['go'] },
|
|
9
|
+
{ id: 'platform-dir-read', description: 'reads a platform directory variable; use the dirs resolver', re: /\b(?:process\.env|env)(?:\.|\s*\[\s*['"])(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA|XDG_[A-Z_]+)\b/, langs: JS },
|
|
10
|
+
{ id: 'platform-dir-read', description: 'reads a platform directory variable; use the dirs resolver', re: /\bvar(?:_os)?\s*\(\s*"(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA|XDG_[A-Z_]+)"/, langs: ['rs'] },
|
|
11
|
+
{ id: 'platform-dir-read', description: 'reads a platform directory variable; use the dirs resolver', re: /\b(?:os\.environ(?:\.get\s*\(|\s*\[)|os\.getenv\s*\()\s*['"](?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA|XDG_[A-Z_]+)['"]/, langs: ['py'] },
|
|
12
|
+
{ id: 'legacy-home-name', description: 'names a legacy XENO home; use the dirs resolver', re: /(?<![\w-])\.xeno-(?:agent|anima|code)(?![\w-])/, langs: [...JS, 'rs', 'py', 'go'] },
|
|
13
|
+
{ id: 'legacy-home-path', description: 'builds a path into the legacy home folder or the XENO app-data folder by hand', re: /(?:~|\$\{?HOME\}?|%USERPROFILE%|%HOMEPATH%|\$env:USERPROFILE)[\\/]+\.xeno(?![\w-])|(?:%APPDATA%|%LOCALAPPDATA%|AppData[\\/]+(?:Roaming|Local))[\\/]+XENO\b/, langs: [...JS, 'rs', 'py', 'go'] },
|
|
14
|
+
{ id: 'legacy-home-env', description: 'uses a legacy XENO_*_HOME variable; XENO_HOME is the only override', re: /\bXENO_(?!HOME\b)[A-Z0-9_]*_HOME\b/, langs: [...JS, 'rs', 'py', 'go'] },
|
|
15
|
+
];
|
|
16
|
+
const DEFAULT_EXCLUDE_DIRS = new Set(['node_modules', 'dist', 'build', 'target', '.git', 'coverage', '.next', 'out', '.turbo', '.venv', '__pycache__', 'release', '.worktrees']);
|
|
17
|
+
const EXT_LANG = Object.fromEntries([...JS.map((e) => [e, e]), ['rs', 'rs'], ['py', 'py'], ['go', 'go']]);
|
|
18
|
+
const MAX_BYTES = 2_000_000;
|
|
19
|
+
function globToRe(g) {
|
|
20
|
+
// Placeholders first, so the expansions below are not themselves rewritten by the single-star rule.
|
|
21
|
+
const esc = g
|
|
22
|
+
.replace(/\*\*\//g, '@@DIR@@')
|
|
23
|
+
.replace(/\*\*/g, '@@ANY@@')
|
|
24
|
+
.replace(/\*/g, '@@SEG@@')
|
|
25
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
26
|
+
.replace(/@@DIR@@/g, '(?:.*/)?')
|
|
27
|
+
.replace(/@@ANY@@/g, '.*')
|
|
28
|
+
.replace(/@@SEG@@/g, '[^/]*');
|
|
29
|
+
return new RegExp(`^${esc}$`);
|
|
30
|
+
}
|
|
31
|
+
export const CONFIG_NAME = 'xeno-dirs-check.json';
|
|
32
|
+
export function loadConfig(root) {
|
|
33
|
+
const p = join(root, CONFIG_NAME);
|
|
34
|
+
if (!existsSync(p))
|
|
35
|
+
return { config: {}, path: null };
|
|
36
|
+
const c = JSON.parse(readFileSync(p, 'utf8'));
|
|
37
|
+
for (const a of c.allow ?? [])
|
|
38
|
+
if (!a.reason || a.reason.trim().length < 8)
|
|
39
|
+
throw new Error(`${CONFIG_NAME}: allow entry for ${a.file} / ${a.rule} needs a real reason`);
|
|
40
|
+
return { config: c, path: p };
|
|
41
|
+
}
|
|
42
|
+
/** Strips comment text so documentation that names a path is not a violation. Keeps line numbering. */
|
|
43
|
+
function codeLines(text, lang) {
|
|
44
|
+
const out = [];
|
|
45
|
+
let block = false;
|
|
46
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
47
|
+
let line = raw;
|
|
48
|
+
let comment = '';
|
|
49
|
+
if (lang === 'py') {
|
|
50
|
+
const i = line.indexOf('#');
|
|
51
|
+
if (i >= 0) {
|
|
52
|
+
comment = line.slice(i);
|
|
53
|
+
line = line.slice(0, i);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
if (block) {
|
|
58
|
+
const end = line.indexOf('*/');
|
|
59
|
+
if (end < 0) {
|
|
60
|
+
out.push({ code: '', comment: line });
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
comment = line.slice(0, end + 2);
|
|
64
|
+
line = line.slice(end + 2);
|
|
65
|
+
block = false;
|
|
66
|
+
}
|
|
67
|
+
const t = line.trimStart();
|
|
68
|
+
if (t.startsWith('//')) {
|
|
69
|
+
out.push({ code: '', comment: line });
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const open = line.indexOf('/*');
|
|
73
|
+
if (open >= 0 && !/['"`].*\/\*.*['"`]/.test(line)) {
|
|
74
|
+
const close = line.indexOf('*/', open + 2);
|
|
75
|
+
if (close < 0) {
|
|
76
|
+
block = true;
|
|
77
|
+
comment += line.slice(open);
|
|
78
|
+
line = line.slice(0, open);
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
comment += line.slice(open, close + 2);
|
|
82
|
+
line = line.slice(0, open) + line.slice(close + 2);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const trailing = line.search(/\s\/\/\s/);
|
|
86
|
+
if (trailing >= 0) {
|
|
87
|
+
comment += line.slice(trailing);
|
|
88
|
+
line = line.slice(0, trailing);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
out.push({ code: line, comment });
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
const ALLOW = /xeno-dirs-allow:\s*(\S.*)$/;
|
|
96
|
+
export function scanText(file, text, lang) {
|
|
97
|
+
const lines = codeLines(text, lang);
|
|
98
|
+
const found = [];
|
|
99
|
+
const rules = RULES.filter((r) => r.langs.includes(lang));
|
|
100
|
+
lines.forEach((l, i) => {
|
|
101
|
+
const allowHere = ALLOW.exec(l.comment) ?? (i > 0 ? ALLOW.exec(lines[i - 1].comment) : null);
|
|
102
|
+
if (/xeno-dirs-allow:\s*$/.test(l.comment) || (allowHere !== null && allowHere[1].trim().length < 4)) {
|
|
103
|
+
found.push({ file, line: i + 1, rule: 'allow-without-reason', description: 'xeno-dirs-allow needs a reason', text: l.comment.trim().slice(0, 160) });
|
|
104
|
+
}
|
|
105
|
+
if (l.code.trim() === '')
|
|
106
|
+
return;
|
|
107
|
+
for (const r of rules) {
|
|
108
|
+
if (r.re.test(l.code) && allowHere === null) {
|
|
109
|
+
if (!found.some((f) => f.line === i + 1 && f.rule === r.id))
|
|
110
|
+
found.push({ file, line: i + 1, rule: r.id, description: r.description, text: l.code.trim().slice(0, 160) });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
return found;
|
|
115
|
+
}
|
|
116
|
+
export function checkSource(root, override) {
|
|
117
|
+
const { config: fileConfig, path } = loadConfig(root);
|
|
118
|
+
const config = { ...fileConfig, ...override };
|
|
119
|
+
const resolver = (config.resolverFiles ?? []).map(globToRe);
|
|
120
|
+
const exclude = (config.exclude ?? []).map(globToRe);
|
|
121
|
+
const allow = (config.allow ?? []).map((a) => ({ f: globToRe(a.file), rule: a.rule }));
|
|
122
|
+
const violations = [];
|
|
123
|
+
let scanned = 0;
|
|
124
|
+
const walk = (dir) => {
|
|
125
|
+
for (const name of readdirSync(dir)) {
|
|
126
|
+
const abs = join(dir, name);
|
|
127
|
+
const st = lstatSync(abs);
|
|
128
|
+
if (st.isSymbolicLink())
|
|
129
|
+
continue; // never follow a link out of the tree
|
|
130
|
+
const rel = relative(root, abs).split(sep).join('/');
|
|
131
|
+
if (st.isDirectory()) {
|
|
132
|
+
if (!DEFAULT_EXCLUDE_DIRS.has(name) && !exclude.some((e) => e.test(rel + '/')))
|
|
133
|
+
walk(abs);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '';
|
|
137
|
+
const lang = EXT_LANG[ext];
|
|
138
|
+
if (lang === undefined || st.size > MAX_BYTES || name.endsWith('.min.js') || name.endsWith('.d.ts'))
|
|
139
|
+
continue;
|
|
140
|
+
if (exclude.some((e) => e.test(rel)) || resolver.some((e) => e.test(rel)))
|
|
141
|
+
continue;
|
|
142
|
+
scanned++;
|
|
143
|
+
for (const v of scanText(rel, readFileSync(abs, 'utf8'), lang)) {
|
|
144
|
+
if (allow.some((a) => a.f.test(rel) && a.rule === v.rule))
|
|
145
|
+
continue;
|
|
146
|
+
violations.push(v);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
walk(root);
|
|
151
|
+
return { ok: violations.length === 0, filesScanned: scanned, violations, config: path };
|
|
152
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// xeno-home print every resolved location (the engine behind `xeno home`)
|
|
3
|
+
// xeno-home doctor [--json] list entries no registry path allows (`xeno home doctor`; exit 1 if any)
|
|
4
|
+
// xeno-home migrate [--confirm] copy legacy homes into the layout (dry run unless --confirm; never deletes)
|
|
5
|
+
// xeno-home inputs show the owner-decided contract inputs
|
|
6
|
+
import { contractInputs } from "./inputs.js";
|
|
7
|
+
import { createDirs } from "./dirs.js";
|
|
8
|
+
import { doctor } from "./doctor.js";
|
|
9
|
+
import { hostHome } from "./host.js";
|
|
10
|
+
import { planMigration, runMigration } from "./migrate.js";
|
|
11
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
12
|
+
const json = rest.includes('--json');
|
|
13
|
+
const out = (v) => console.log(JSON.stringify(v, null, 2));
|
|
14
|
+
async function main() {
|
|
15
|
+
const dirs = createDirs();
|
|
16
|
+
if (cmd === undefined || cmd === 'home') {
|
|
17
|
+
const d = dirs.describe();
|
|
18
|
+
if (json)
|
|
19
|
+
out(d);
|
|
20
|
+
else {
|
|
21
|
+
console.log(`platform: ${d.platform}${d.overridden ? ' (XENO_HOME override)' : ''}`);
|
|
22
|
+
for (const [k, v] of Object.entries(d.roots))
|
|
23
|
+
console.log(`${k.padEnd(8)}${v}`);
|
|
24
|
+
console.log(`layout: ${d.layout.state}${'layout' in d.layout ? ` (${d.layout.layout})` : ''}`);
|
|
25
|
+
for (const w of d.warnings)
|
|
26
|
+
console.log(`warning: ${w}`);
|
|
27
|
+
}
|
|
28
|
+
return 0;
|
|
29
|
+
}
|
|
30
|
+
if (cmd === 'doctor') {
|
|
31
|
+
const r = doctor(dirs, { home: hostHome() });
|
|
32
|
+
if (json)
|
|
33
|
+
out(r);
|
|
34
|
+
else {
|
|
35
|
+
for (const u of r.unregistered)
|
|
36
|
+
console.log(`UNREGISTERED ${u.kind}/${u.path} (${u.type}; ${u.reason})`);
|
|
37
|
+
for (const l of r.legacy.filter((x) => x.present))
|
|
38
|
+
console.log(`legacy home ${l.path} (run: xeno-home migrate)`);
|
|
39
|
+
console.log(r.ok ? 'ok: no unregistered entry in any XENO root' : `${r.unregistered.length} unregistered entr${r.unregistered.length === 1 ? 'y' : 'ies'}`);
|
|
40
|
+
}
|
|
41
|
+
return r.ok ? 0 : 1;
|
|
42
|
+
}
|
|
43
|
+
if (cmd === 'migrate') {
|
|
44
|
+
const plan = planMigration({ dirs, home: hostHome() });
|
|
45
|
+
const confirm = rest.includes('--confirm');
|
|
46
|
+
const result = await runMigration(plan, { dirs, confirm });
|
|
47
|
+
if (json)
|
|
48
|
+
out({ plan: { id: plan.id, homes: plan.homes, entries: plan.entries.length }, result });
|
|
49
|
+
else {
|
|
50
|
+
console.log(`${confirm ? 'migrated' : 'DRY RUN (nothing written; pass --confirm)'} plan ${plan.id}`);
|
|
51
|
+
for (const h of plan.homes)
|
|
52
|
+
console.log(` ${h.name.padEnd(14)}${h.state}`);
|
|
53
|
+
for (const e of result.entries)
|
|
54
|
+
console.log(` ${e.status.padEnd(9)}${e.legacyHome}/${e.sourceRel} -> ${e.destRel}${e.reason ? ` (${e.reason})` : ''}`);
|
|
55
|
+
for (const r of result.refused)
|
|
56
|
+
console.log(` refused ${r.path} (${r.reason})`);
|
|
57
|
+
console.log(` unplaced: ${result.unplaced.count}${result.unplaced.truncated ? '+' : ''} (reported, never guessed)`);
|
|
58
|
+
if (confirm)
|
|
59
|
+
console.log(result.ok ? 'ok: every copy verified by hash; legacy homes left in place' : 'NOT ok: a product must not switch yet');
|
|
60
|
+
}
|
|
61
|
+
return confirm && !result.ok ? 1 : 0;
|
|
62
|
+
}
|
|
63
|
+
if (cmd === 'inputs') {
|
|
64
|
+
out(contractInputs());
|
|
65
|
+
return 0;
|
|
66
|
+
}
|
|
67
|
+
console.error('usage: xeno-home [home|doctor|migrate [--confirm]|inputs] [--json]');
|
|
68
|
+
return 2;
|
|
69
|
+
}
|
|
70
|
+
main().then((c) => process.exit(c), (e) => { console.error(`error: ${e.message}`); process.exit(1); });
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type AtomicWriteOptions } from './atomic.ts';
|
|
2
|
+
import { type LayoutState } from './layout.ts';
|
|
3
|
+
import { type AcquireOptions, type LockHandle } from './lock.ts';
|
|
4
|
+
import { type Kind, type Platform, type ResolvedRoots } from './roots.ts';
|
|
5
|
+
export interface CreateDirsOptions {
|
|
6
|
+
platform?: Platform;
|
|
7
|
+
home?: string;
|
|
8
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The resolver. Every XENO path comes from here; nothing else may build one. It refuses anything the registry does
|
|
12
|
+
* not list, and refuses to write when the layout on disk is newer than this build understands.
|
|
13
|
+
*/
|
|
14
|
+
export declare class XenoDirs {
|
|
15
|
+
readonly platform: Platform;
|
|
16
|
+
readonly roots: Readonly<Record<Kind, string>>;
|
|
17
|
+
readonly warnings: readonly string[];
|
|
18
|
+
readonly overridden: boolean;
|
|
19
|
+
constructor(resolved: ResolvedRoots);
|
|
20
|
+
/** Root directory of a kind. */
|
|
21
|
+
root(kind: Kind): string;
|
|
22
|
+
/** Path relative to the kind root, `/`-separated, after registry validation. */
|
|
23
|
+
relative(kind: string, area: string, ...segments: string[]): string;
|
|
24
|
+
/** Absolute path for (kind, area, ...segments). Throws DirsError for anything unregistered or invalid. */
|
|
25
|
+
path(kind: Kind, area: string, ...segments: string[]): string;
|
|
26
|
+
/** `run/<area>/<name>.lock`. */
|
|
27
|
+
lockPath(area: string, name: string): string;
|
|
28
|
+
/** `data/layout.json`. */
|
|
29
|
+
layoutPath(): string;
|
|
30
|
+
/** `<kind>/<area>/area.json`, the optional per-area schema marker. */
|
|
31
|
+
areaMetaPath(kind: Kind, area: string): string;
|
|
32
|
+
/** Reads data/layout.json. Never throws for a missing file. */
|
|
33
|
+
readLayout(): LayoutState;
|
|
34
|
+
/** Throws unless this build may write: a newer or unreadable layout marker refuses (spec section 8). */
|
|
35
|
+
assertWritable(): LayoutState;
|
|
36
|
+
/** Creates data/layout.json at the supported version if absent; otherwise checks it. */
|
|
37
|
+
ensureLayout(): Promise<LayoutState>;
|
|
38
|
+
/** The only sanctioned way to write below the roots: registry check, layout check, atomic replace. */
|
|
39
|
+
writeFile(kind: Kind, area: string, segments: readonly string[], data: string | Uint8Array, options?: AtomicWriteOptions): Promise<string>;
|
|
40
|
+
/** Reads a registered file; returns null when absent. */
|
|
41
|
+
readFile(kind: Kind, area: string, segments: readonly string[]): Promise<Buffer | null>;
|
|
42
|
+
/** Acquires `run/<area>/<name>.lock` (spec section 8). */
|
|
43
|
+
acquireLock(area: string, name: string, options?: AcquireOptions): Promise<LockHandle>;
|
|
44
|
+
withLock<T>(area: string, name: string, fn: () => Promise<T>, options?: AcquireOptions): Promise<T>;
|
|
45
|
+
/** Every resolved location, for `xeno home`. */
|
|
46
|
+
describe(): {
|
|
47
|
+
platform: Platform;
|
|
48
|
+
overridden: boolean;
|
|
49
|
+
roots: Record<Kind, string>;
|
|
50
|
+
warnings: readonly string[];
|
|
51
|
+
layout: LayoutState;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** Builds a resolver from the host (default) or from explicit inputs (tests, vectors, a fixture root). */
|
|
55
|
+
export declare function createDirs(options?: CreateDirsOptions): XenoDirs;
|
|
56
|
+
/** A resolver rooted entirely under one directory via XENO_HOME; the supported way to isolate tests and fixtures. */
|
|
57
|
+
export declare function createDirsAt(xenoHome: string, platform?: Platform): XenoDirs;
|