@xenosystem/primitives 0.4.0 → 0.6.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/dist/cjs/private-file/index.d.ts +41 -0
- package/dist/cjs/private-file/index.js +91 -0
- package/dist/cjs/process/here.d.ts +1 -0
- package/dist/cjs/process/here.js +3 -0
- package/dist/cjs/process/index.d.ts +50 -0
- package/dist/cjs/process/index.js +203 -0
- package/dist/esm/private-file/index.d.ts +41 -0
- package/dist/esm/private-file/index.js +86 -0
- package/dist/esm/process/here.d.ts +1 -0
- package/dist/esm/process/here.js +6 -0
- package/dist/esm/process/index.d.ts +50 -0
- package/dist/esm/process/index.js +199 -0
- package/native/THIRD_PARTY_NOTICES.md +1136 -0
- package/native/win32-x64/process.node +0 -0
- package/package.json +25 -3
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Largest file this family reads or writes (1 MiB). */
|
|
2
|
+
export declare const PRIVATE_FILE_MAX_BYTES = 1048576;
|
|
3
|
+
export interface PrivateFileReceipt {
|
|
4
|
+
/**
|
|
5
|
+
* `committed`: done (for a read or delete this is also the answer when there was no file).
|
|
6
|
+
* `exists`: a write with `ifAbsent` found a file and left it alone.
|
|
7
|
+
* `not-committed`: refused or failed before anything was published.
|
|
8
|
+
* `uncertain`: failed during publication; the target may hold either version. `retainedFiles` are kept as evidence.
|
|
9
|
+
*/
|
|
10
|
+
outcome: 'committed' | 'not-committed' | 'uncertain' | 'exists';
|
|
11
|
+
/** The step that was running when the operation ended. */
|
|
12
|
+
phase: string;
|
|
13
|
+
/** The Windows error code of a failure, 0 on success. */
|
|
14
|
+
errorCode: number;
|
|
15
|
+
/** Temp or backup files left behind in the directory (file names only). */
|
|
16
|
+
retainedFiles: string[];
|
|
17
|
+
/** A read's bytes, or null when the file does not exist. */
|
|
18
|
+
data: Uint8Array | null;
|
|
19
|
+
/** True when a delete removed a file. */
|
|
20
|
+
deleted: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface PrivateFileRequest {
|
|
23
|
+
path: string;
|
|
24
|
+
operation: 'read' | 'write' | 'delete';
|
|
25
|
+
/** The bytes to write. */
|
|
26
|
+
payload?: Uint8Array;
|
|
27
|
+
/** Write only when the file does not exist yet. */
|
|
28
|
+
ifAbsent?: boolean;
|
|
29
|
+
/** A lower-case UUID naming this operation's temp and backup files. */
|
|
30
|
+
operationId: string;
|
|
31
|
+
}
|
|
32
|
+
/** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
|
|
33
|
+
export declare function privateFileSupport(): {
|
|
34
|
+
available: boolean;
|
|
35
|
+
reason?: string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
|
|
39
|
+
* binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
|
|
40
|
+
*/
|
|
41
|
+
export declare function privateFileOperation(request: PrivateFileRequest): PrivateFileReceipt;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PRIVATE_FILE_MAX_BYTES = void 0;
|
|
4
|
+
exports.privateFileSupport = privateFileSupport;
|
|
5
|
+
exports.privateFileOperation = privateFileOperation;
|
|
6
|
+
/**
|
|
7
|
+
* `@xenosystem/primitives/private-file` — read, write or delete one file that only its owner and SYSTEM may open.
|
|
8
|
+
*
|
|
9
|
+
* Each operation takes a gate file in the same directory (so processes take turns), and a write is published so
|
|
10
|
+
* that a reader sees the old bytes or the new bytes, never a partial file: new bytes go to a private temp file,
|
|
11
|
+
* are flushed, and replace the target in one step (`ReplaceFileW`), or are linked into place when the target does
|
|
12
|
+
* not exist yet (so a create never overwrites).
|
|
13
|
+
*
|
|
14
|
+
* Why this exists: the agent SDK ran exactly this through a PowerShell helper that compiled C# on every call.
|
|
15
|
+
* Measured 2026-11-11: 0.6 to 1.2 s per operation on a quiet machine, more under load. A sign-out does many of
|
|
16
|
+
* them, passed the 30 s the Agent host allows one account request, and left the owner signed in on a blank
|
|
17
|
+
* window. Here the same steps run inside the calling process from a binary that ships in this package
|
|
18
|
+
* (`native/win32-<arch>/process.node`); nothing is compiled or started at run time.
|
|
19
|
+
*
|
|
20
|
+
* The files on disk are the same as the helper's (gate `.xeno-protected-write.lock`, temp and backup
|
|
21
|
+
* `.xeno-protected-<operation id>.tmp|.backup`), so a process still using the helper and a process using this
|
|
22
|
+
* can share a directory and still take turns.
|
|
23
|
+
*
|
|
24
|
+
* Windows only. `privateFileSupport()` says whether it can be used; a caller keeps its own fallback otherwise.
|
|
25
|
+
*/
|
|
26
|
+
const node_fs_1 = require("node:fs");
|
|
27
|
+
const node_module_1 = require("node:module");
|
|
28
|
+
const node_path_1 = require("node:path");
|
|
29
|
+
const here_ts_1 = require("../process/here.js");
|
|
30
|
+
/** Largest file this family reads or writes (1 MiB). */
|
|
31
|
+
exports.PRIVATE_FILE_MAX_BYTES = 1_048_576;
|
|
32
|
+
let nativeCache;
|
|
33
|
+
function loadNative() {
|
|
34
|
+
if (nativeCache)
|
|
35
|
+
return nativeCache;
|
|
36
|
+
if (process.platform !== 'win32')
|
|
37
|
+
return (nativeCache = { reason: 'not Windows' });
|
|
38
|
+
const name = `win32-${process.arch}`;
|
|
39
|
+
// src/private-file (tests) and dist/{esm,cjs}/private-file (published) both sit under the package directory.
|
|
40
|
+
const candidates = [(0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', 'native', name, 'process.node'), (0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', '..', 'native', name, 'process.node')];
|
|
41
|
+
const file = candidates.find((p) => (0, node_fs_1.existsSync)(p));
|
|
42
|
+
if (!file)
|
|
43
|
+
return (nativeCache = { reason: `no native binary for ${name}` });
|
|
44
|
+
try {
|
|
45
|
+
const binding = (0, node_module_1.createRequire)(file)(file);
|
|
46
|
+
if (typeof binding.privateFileOperation !== 'function')
|
|
47
|
+
return (nativeCache = { reason: 'native binary has no privateFileOperation' });
|
|
48
|
+
return (nativeCache = { run: binding.privateFileOperation });
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
|
|
55
|
+
function privateFileSupport() {
|
|
56
|
+
const native = loadNative();
|
|
57
|
+
return native.run ? { available: true } : { available: false, ...(native.reason ? { reason: native.reason } : {}) };
|
|
58
|
+
}
|
|
59
|
+
const OUTCOMES = new Set(['committed', 'not-committed', 'uncertain', 'exists']);
|
|
60
|
+
/**
|
|
61
|
+
* Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
|
|
62
|
+
* binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
|
|
63
|
+
*/
|
|
64
|
+
function privateFileOperation(request) {
|
|
65
|
+
const native = loadNative();
|
|
66
|
+
if (!native.run)
|
|
67
|
+
throw new Error(`private-file is unavailable: ${native.reason ?? 'unknown reason'}`);
|
|
68
|
+
if (typeof request.path !== 'string' || !request.path)
|
|
69
|
+
throw new TypeError('private-file: path is required');
|
|
70
|
+
if (!['read', 'write', 'delete'].includes(request.operation))
|
|
71
|
+
throw new TypeError('private-file: unknown operation');
|
|
72
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request.operationId))
|
|
73
|
+
throw new TypeError('private-file: operationId must be a lower-case UUID');
|
|
74
|
+
const payload = request.operation === 'write' ? request.payload ?? new Uint8Array(0) : null;
|
|
75
|
+
if (payload && payload.byteLength > exports.PRIVATE_FILE_MAX_BYTES) {
|
|
76
|
+
return { outcome: 'not-committed', phase: 'validate', errorCode: 0, retainedFiles: [], data: null, deleted: false };
|
|
77
|
+
}
|
|
78
|
+
// The binding takes a Buffer; a plain Uint8Array view is wrapped without copying.
|
|
79
|
+
const bytes = payload ? Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength) : null;
|
|
80
|
+
const raw = native.run(request.path, request.operation, bytes, request.ifAbsent === true, request.operationId);
|
|
81
|
+
if (!OUTCOMES.has(raw.outcome))
|
|
82
|
+
throw new Error('private-file: native binary returned an unknown outcome');
|
|
83
|
+
return {
|
|
84
|
+
outcome: raw.outcome,
|
|
85
|
+
phase: raw.phase,
|
|
86
|
+
errorCode: raw.errorCode,
|
|
87
|
+
retainedFiles: [...raw.retainedFiles],
|
|
88
|
+
data: raw.data ?? null,
|
|
89
|
+
deleted: raw.deleted === true,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const moduleDir: string;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
|
|
3
|
+
*
|
|
4
|
+
* A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
|
|
5
|
+
* shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
|
|
6
|
+
* groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
|
|
7
|
+
* Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
|
|
8
|
+
* kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
|
|
9
|
+
* breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
|
|
10
|
+
*
|
|
11
|
+
* Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
|
|
12
|
+
* as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
|
|
13
|
+
* started anything yet; only then does it start the real command, with the same stdio.
|
|
14
|
+
*
|
|
15
|
+
* The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
|
|
16
|
+
* is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
|
|
17
|
+
* Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
|
|
18
|
+
* that needs the guarantee can refuse rather than assume it.
|
|
19
|
+
*/
|
|
20
|
+
import { type ChildProcess } from 'node:child_process';
|
|
21
|
+
/** How stopping reaches the command's descendants. */
|
|
22
|
+
export type Containment = 'job' | 'process-group' | 'tree-walk';
|
|
23
|
+
export interface ProcessGroupOptions {
|
|
24
|
+
cwd?: string;
|
|
25
|
+
env?: NodeJS.ProcessEnv;
|
|
26
|
+
windowsHide?: boolean;
|
|
27
|
+
/** Pass argv to the program exactly as given (needed when the program is `cmd.exe`, which has its own parser). */
|
|
28
|
+
windowsVerbatimArguments?: boolean;
|
|
29
|
+
/** stdin, stdout, stderr. Default: all piped. */
|
|
30
|
+
stdio?: readonly ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit'];
|
|
31
|
+
}
|
|
32
|
+
export interface ProcessGroup {
|
|
33
|
+
/** The process that was started. On Windows with a job, this is the launcher; its exit code is the command's. */
|
|
34
|
+
readonly child: ChildProcess;
|
|
35
|
+
readonly containment: Containment;
|
|
36
|
+
/** Stop the command and everything it started. `force` matters on POSIX only (SIGKILL instead of SIGTERM). */
|
|
37
|
+
stop(force?: boolean): void;
|
|
38
|
+
/** Processes still running in the group, where the platform can count them (Windows job only). */
|
|
39
|
+
activeProcesses(): number | undefined;
|
|
40
|
+
}
|
|
41
|
+
/** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
|
|
42
|
+
export declare function processGroupSupport(): {
|
|
43
|
+
containment: Containment;
|
|
44
|
+
reason?: string;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
|
|
48
|
+
* `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
|
|
49
|
+
*/
|
|
50
|
+
export declare function spawnProcessGroup(command: string, args: readonly string[], options?: ProcessGroupOptions): ProcessGroup;
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.processGroupSupport = processGroupSupport;
|
|
4
|
+
exports.spawnProcessGroup = spawnProcessGroup;
|
|
5
|
+
/**
|
|
6
|
+
* `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
|
|
7
|
+
*
|
|
8
|
+
* A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
|
|
9
|
+
* shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
|
|
10
|
+
* groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
|
|
11
|
+
* Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
|
|
12
|
+
* kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
|
|
13
|
+
* breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
|
|
14
|
+
*
|
|
15
|
+
* Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
|
|
16
|
+
* as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
|
|
17
|
+
* started anything yet; only then does it start the real command, with the same stdio.
|
|
18
|
+
*
|
|
19
|
+
* The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
|
|
20
|
+
* is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
|
|
21
|
+
* Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
|
|
22
|
+
* that needs the guarantee can refuse rather than assume it.
|
|
23
|
+
*/
|
|
24
|
+
const node_child_process_1 = require("node:child_process");
|
|
25
|
+
const node_fs_1 = require("node:fs");
|
|
26
|
+
const node_module_1 = require("node:module");
|
|
27
|
+
const node_path_1 = require("node:path");
|
|
28
|
+
const here_ts_1 = require("./here.js");
|
|
29
|
+
let nativeCache;
|
|
30
|
+
/** The native job binding, or why it is not available. Windows only. */
|
|
31
|
+
function loadNative() {
|
|
32
|
+
if (nativeCache)
|
|
33
|
+
return nativeCache;
|
|
34
|
+
if (process.platform !== 'win32')
|
|
35
|
+
return (nativeCache = { reason: 'not Windows' });
|
|
36
|
+
const name = `win32-${process.arch}`;
|
|
37
|
+
// src/process (tests) and dist/{esm,cjs}/process (published) both sit under the package directory.
|
|
38
|
+
const candidates = [(0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', 'native', name, 'process.node'), (0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', '..', 'native', name, 'process.node')];
|
|
39
|
+
const file = candidates.find((p) => (0, node_fs_1.existsSync)(p));
|
|
40
|
+
if (!file)
|
|
41
|
+
return (nativeCache = { reason: `no native binary for ${name}` });
|
|
42
|
+
try {
|
|
43
|
+
const binding = (0, node_module_1.createRequire)(file)(file);
|
|
44
|
+
if (typeof binding.ProcessJob !== 'function')
|
|
45
|
+
return (nativeCache = { reason: 'native binary has no ProcessJob' });
|
|
46
|
+
return (nativeCache = { ctor: binding.ProcessJob });
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
|
|
53
|
+
function processGroupSupport() {
|
|
54
|
+
if (process.platform !== 'win32')
|
|
55
|
+
return { containment: 'process-group' };
|
|
56
|
+
const native = loadNative();
|
|
57
|
+
return native.ctor ? { containment: 'job' } : { containment: 'tree-walk', ...(native.reason ? { reason: native.reason } : {}) };
|
|
58
|
+
}
|
|
59
|
+
// The launcher: reads one JSON line of instructions from fd 3, then starts the real command with fds 0-2 inherited
|
|
60
|
+
// and exits with its exit code. A failure to start is reported back on fd 3 so the caller can raise `error`.
|
|
61
|
+
const LAUNCHER = [
|
|
62
|
+
"const fs=require('fs'),cp=require('child_process');",
|
|
63
|
+
"let t='';const b=Buffer.alloc(65536);",
|
|
64
|
+
"for(;;){const n=fs.readSync(3,b,0,b.length,null);if(n===0)process.exit(126);t+=b.toString('utf8',0,n);const i=t.indexOf('\\n');if(i>=0){t=t.slice(0,i);break}}",
|
|
65
|
+
'const s=JSON.parse(t);const env={...process.env};if(!s.keepRunAsNode)delete env.ELECTRON_RUN_AS_NODE;',
|
|
66
|
+
"const fail=(e)=>{try{fs.writeSync(3,JSON.stringify({error:{message:String(e&&e.message||e),code:e&&e.code}})+'\\n')}catch{}process.exit(127)};",
|
|
67
|
+
"let c;try{c=cp.spawn(s.command,s.args,{stdio:'inherit',windowsHide:s.windowsHide,windowsVerbatimArguments:s.verbatim,env})}catch(e){fail(e)}",
|
|
68
|
+
"c.on('error',fail);c.on('exit',(code)=>process.exit(code===null?1:code));",
|
|
69
|
+
].join('');
|
|
70
|
+
/**
|
|
71
|
+
* Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
|
|
72
|
+
* `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
|
|
73
|
+
*/
|
|
74
|
+
function spawnProcessGroup(command, args, options = {}) {
|
|
75
|
+
const stdio = options.stdio ?? ['pipe', 'pipe', 'pipe'];
|
|
76
|
+
const env = options.env ?? process.env;
|
|
77
|
+
const base = { cwd: options.cwd, env, windowsHide: options.windowsHide ?? true, shell: false };
|
|
78
|
+
if (process.platform !== 'win32') {
|
|
79
|
+
const child = (0, node_child_process_1.spawn)(command, [...args], { ...base, stdio: [...stdio], detached: true });
|
|
80
|
+
return {
|
|
81
|
+
child,
|
|
82
|
+
containment: 'process-group',
|
|
83
|
+
stop(force = false) {
|
|
84
|
+
const pid = child.pid;
|
|
85
|
+
if (pid === undefined)
|
|
86
|
+
return;
|
|
87
|
+
try {
|
|
88
|
+
process.kill(-pid, force ? 'SIGKILL' : 'SIGTERM');
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
try {
|
|
92
|
+
child.kill(force ? 'SIGKILL' : 'SIGTERM');
|
|
93
|
+
}
|
|
94
|
+
catch { /* already gone */ }
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
activeProcesses: () => undefined,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
const native = loadNative();
|
|
101
|
+
if (!native.ctor) {
|
|
102
|
+
const child = (0, node_child_process_1.spawn)(command, [...args], { ...base, stdio: [...stdio], windowsVerbatimArguments: options.windowsVerbatimArguments ?? false });
|
|
103
|
+
return {
|
|
104
|
+
child,
|
|
105
|
+
containment: 'tree-walk',
|
|
106
|
+
stop() {
|
|
107
|
+
const pid = child.pid;
|
|
108
|
+
if (pid === undefined)
|
|
109
|
+
return;
|
|
110
|
+
const killer = (0, node_child_process_1.spawn)('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
111
|
+
killer.on('error', () => { try {
|
|
112
|
+
child.kill();
|
|
113
|
+
}
|
|
114
|
+
catch { /* already gone */ } });
|
|
115
|
+
},
|
|
116
|
+
activeProcesses: () => undefined,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
const job = new native.ctor();
|
|
120
|
+
let jobOpen = true;
|
|
121
|
+
const endJob = (how) => {
|
|
122
|
+
if (!jobOpen)
|
|
123
|
+
return;
|
|
124
|
+
jobOpen = false;
|
|
125
|
+
try {
|
|
126
|
+
if (how === 'terminate')
|
|
127
|
+
job.close();
|
|
128
|
+
else
|
|
129
|
+
job.release();
|
|
130
|
+
}
|
|
131
|
+
catch { /* the handle is gone either way */ }
|
|
132
|
+
};
|
|
133
|
+
const runAsNode = process.versions.electron !== undefined;
|
|
134
|
+
const launcherEnv = runAsNode ? { ...env, ELECTRON_RUN_AS_NODE: '1' } : env;
|
|
135
|
+
const child = (0, node_child_process_1.spawn)(process.execPath, ['-e', LAUNCHER], { ...base, env: launcherEnv, stdio: [...stdio, 'pipe'] });
|
|
136
|
+
const control = child.stdio[3];
|
|
137
|
+
if (child.pid !== undefined && control) {
|
|
138
|
+
try {
|
|
139
|
+
job.assign(child.pid);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
// A command that is not in its group is not started: stopping it could not reach what it starts.
|
|
143
|
+
try {
|
|
144
|
+
child.kill();
|
|
145
|
+
}
|
|
146
|
+
catch { /* already gone */ }
|
|
147
|
+
endJob('terminate');
|
|
148
|
+
queueMicrotask(() => child.emit('error', new Error(`could not place the command in a job: ${error.message}`)));
|
|
149
|
+
return { child, containment: 'job', stop() { }, activeProcesses: () => undefined };
|
|
150
|
+
}
|
|
151
|
+
let received = '';
|
|
152
|
+
control.on('data', (chunk) => {
|
|
153
|
+
received += chunk.toString();
|
|
154
|
+
const line = received.split('\n')[0];
|
|
155
|
+
if (received.includes('\n') && line) {
|
|
156
|
+
try {
|
|
157
|
+
const message = JSON.parse(line);
|
|
158
|
+
if (message.error)
|
|
159
|
+
child.emit('error', Object.assign(new Error(message.error.message), message.error.code ? { code: message.error.code } : {}));
|
|
160
|
+
}
|
|
161
|
+
catch { /* not ours */ }
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
control.on('error', () => { });
|
|
165
|
+
control.write(JSON.stringify({
|
|
166
|
+
command,
|
|
167
|
+
args,
|
|
168
|
+
verbatim: options.windowsVerbatimArguments ?? false,
|
|
169
|
+
windowsHide: options.windowsHide ?? true,
|
|
170
|
+
keepRunAsNode: runAsNode && env.ELECTRON_RUN_AS_NODE !== undefined,
|
|
171
|
+
}) + '\n');
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
endJob('terminate');
|
|
175
|
+
}
|
|
176
|
+
// A command that ended on its own keeps today's behaviour for anything it left running; only stop() ends those.
|
|
177
|
+
child.once('close', () => endJob('release'));
|
|
178
|
+
child.once('error', () => { if (child.exitCode !== null || child.pid === undefined)
|
|
179
|
+
endJob('release'); });
|
|
180
|
+
return {
|
|
181
|
+
child,
|
|
182
|
+
containment: 'job',
|
|
183
|
+
stop() {
|
|
184
|
+
if (!jobOpen)
|
|
185
|
+
return;
|
|
186
|
+
try {
|
|
187
|
+
job.terminate(1);
|
|
188
|
+
}
|
|
189
|
+
catch { /* fall through: closing the handle ends every member too */ }
|
|
190
|
+
endJob('terminate');
|
|
191
|
+
},
|
|
192
|
+
activeProcesses() {
|
|
193
|
+
if (!jobOpen)
|
|
194
|
+
return 0;
|
|
195
|
+
try {
|
|
196
|
+
return job.activeProcesses();
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return undefined;
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Largest file this family reads or writes (1 MiB). */
|
|
2
|
+
export declare const PRIVATE_FILE_MAX_BYTES = 1048576;
|
|
3
|
+
export interface PrivateFileReceipt {
|
|
4
|
+
/**
|
|
5
|
+
* `committed`: done (for a read or delete this is also the answer when there was no file).
|
|
6
|
+
* `exists`: a write with `ifAbsent` found a file and left it alone.
|
|
7
|
+
* `not-committed`: refused or failed before anything was published.
|
|
8
|
+
* `uncertain`: failed during publication; the target may hold either version. `retainedFiles` are kept as evidence.
|
|
9
|
+
*/
|
|
10
|
+
outcome: 'committed' | 'not-committed' | 'uncertain' | 'exists';
|
|
11
|
+
/** The step that was running when the operation ended. */
|
|
12
|
+
phase: string;
|
|
13
|
+
/** The Windows error code of a failure, 0 on success. */
|
|
14
|
+
errorCode: number;
|
|
15
|
+
/** Temp or backup files left behind in the directory (file names only). */
|
|
16
|
+
retainedFiles: string[];
|
|
17
|
+
/** A read's bytes, or null when the file does not exist. */
|
|
18
|
+
data: Uint8Array | null;
|
|
19
|
+
/** True when a delete removed a file. */
|
|
20
|
+
deleted: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface PrivateFileRequest {
|
|
23
|
+
path: string;
|
|
24
|
+
operation: 'read' | 'write' | 'delete';
|
|
25
|
+
/** The bytes to write. */
|
|
26
|
+
payload?: Uint8Array;
|
|
27
|
+
/** Write only when the file does not exist yet. */
|
|
28
|
+
ifAbsent?: boolean;
|
|
29
|
+
/** A lower-case UUID naming this operation's temp and backup files. */
|
|
30
|
+
operationId: string;
|
|
31
|
+
}
|
|
32
|
+
/** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
|
|
33
|
+
export declare function privateFileSupport(): {
|
|
34
|
+
available: boolean;
|
|
35
|
+
reason?: string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
|
|
39
|
+
* binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
|
|
40
|
+
*/
|
|
41
|
+
export declare function privateFileOperation(request: PrivateFileRequest): PrivateFileReceipt;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xenosystem/primitives/private-file` — read, write or delete one file that only its owner and SYSTEM may open.
|
|
3
|
+
*
|
|
4
|
+
* Each operation takes a gate file in the same directory (so processes take turns), and a write is published so
|
|
5
|
+
* that a reader sees the old bytes or the new bytes, never a partial file: new bytes go to a private temp file,
|
|
6
|
+
* are flushed, and replace the target in one step (`ReplaceFileW`), or are linked into place when the target does
|
|
7
|
+
* not exist yet (so a create never overwrites).
|
|
8
|
+
*
|
|
9
|
+
* Why this exists: the agent SDK ran exactly this through a PowerShell helper that compiled C# on every call.
|
|
10
|
+
* Measured 2026-11-11: 0.6 to 1.2 s per operation on a quiet machine, more under load. A sign-out does many of
|
|
11
|
+
* them, passed the 30 s the Agent host allows one account request, and left the owner signed in on a blank
|
|
12
|
+
* window. Here the same steps run inside the calling process from a binary that ships in this package
|
|
13
|
+
* (`native/win32-<arch>/process.node`); nothing is compiled or started at run time.
|
|
14
|
+
*
|
|
15
|
+
* The files on disk are the same as the helper's (gate `.xeno-protected-write.lock`, temp and backup
|
|
16
|
+
* `.xeno-protected-<operation id>.tmp|.backup`), so a process still using the helper and a process using this
|
|
17
|
+
* can share a directory and still take turns.
|
|
18
|
+
*
|
|
19
|
+
* Windows only. `privateFileSupport()` says whether it can be used; a caller keeps its own fallback otherwise.
|
|
20
|
+
*/
|
|
21
|
+
import { existsSync } from 'node:fs';
|
|
22
|
+
import { createRequire } from 'node:module';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { moduleDir } from "../process/here.js";
|
|
25
|
+
/** Largest file this family reads or writes (1 MiB). */
|
|
26
|
+
export const PRIVATE_FILE_MAX_BYTES = 1_048_576;
|
|
27
|
+
let nativeCache;
|
|
28
|
+
function loadNative() {
|
|
29
|
+
if (nativeCache)
|
|
30
|
+
return nativeCache;
|
|
31
|
+
if (process.platform !== 'win32')
|
|
32
|
+
return (nativeCache = { reason: 'not Windows' });
|
|
33
|
+
const name = `win32-${process.arch}`;
|
|
34
|
+
// src/private-file (tests) and dist/{esm,cjs}/private-file (published) both sit under the package directory.
|
|
35
|
+
const candidates = [join(moduleDir, '..', '..', 'native', name, 'process.node'), join(moduleDir, '..', '..', '..', 'native', name, 'process.node')];
|
|
36
|
+
const file = candidates.find((p) => existsSync(p));
|
|
37
|
+
if (!file)
|
|
38
|
+
return (nativeCache = { reason: `no native binary for ${name}` });
|
|
39
|
+
try {
|
|
40
|
+
const binding = createRequire(file)(file);
|
|
41
|
+
if (typeof binding.privateFileOperation !== 'function')
|
|
42
|
+
return (nativeCache = { reason: 'native binary has no privateFileOperation' });
|
|
43
|
+
return (nativeCache = { run: binding.privateFileOperation });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
|
|
50
|
+
export function privateFileSupport() {
|
|
51
|
+
const native = loadNative();
|
|
52
|
+
return native.run ? { available: true } : { available: false, ...(native.reason ? { reason: native.reason } : {}) };
|
|
53
|
+
}
|
|
54
|
+
const OUTCOMES = new Set(['committed', 'not-committed', 'uncertain', 'exists']);
|
|
55
|
+
/**
|
|
56
|
+
* Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
|
|
57
|
+
* binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
|
|
58
|
+
*/
|
|
59
|
+
export function privateFileOperation(request) {
|
|
60
|
+
const native = loadNative();
|
|
61
|
+
if (!native.run)
|
|
62
|
+
throw new Error(`private-file is unavailable: ${native.reason ?? 'unknown reason'}`);
|
|
63
|
+
if (typeof request.path !== 'string' || !request.path)
|
|
64
|
+
throw new TypeError('private-file: path is required');
|
|
65
|
+
if (!['read', 'write', 'delete'].includes(request.operation))
|
|
66
|
+
throw new TypeError('private-file: unknown operation');
|
|
67
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request.operationId))
|
|
68
|
+
throw new TypeError('private-file: operationId must be a lower-case UUID');
|
|
69
|
+
const payload = request.operation === 'write' ? request.payload ?? new Uint8Array(0) : null;
|
|
70
|
+
if (payload && payload.byteLength > PRIVATE_FILE_MAX_BYTES) {
|
|
71
|
+
return { outcome: 'not-committed', phase: 'validate', errorCode: 0, retainedFiles: [], data: null, deleted: false };
|
|
72
|
+
}
|
|
73
|
+
// The binding takes a Buffer; a plain Uint8Array view is wrapped without copying.
|
|
74
|
+
const bytes = payload ? Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength) : null;
|
|
75
|
+
const raw = native.run(request.path, request.operation, bytes, request.ifAbsent === true, request.operationId);
|
|
76
|
+
if (!OUTCOMES.has(raw.outcome))
|
|
77
|
+
throw new Error('private-file: native binary returned an unknown outcome');
|
|
78
|
+
return {
|
|
79
|
+
outcome: raw.outcome,
|
|
80
|
+
phase: raw.phase,
|
|
81
|
+
errorCode: raw.errorCode,
|
|
82
|
+
retainedFiles: [...raw.retainedFiles],
|
|
83
|
+
data: raw.data ?? null,
|
|
84
|
+
deleted: raw.deleted === true,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const moduleDir: string;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
// This module's own directory, used to find the bundled native binary. The CommonJS build replaces this file with
|
|
4
|
+
// `exports.moduleDir = __dirname` (scripts/build-ts.mjs), because CommonJS cannot parse `import.meta`.
|
|
5
|
+
// @ts-ignore TS1343 in the CommonJS compile only; that emitted file is overwritten.
|
|
6
|
+
export const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
|
|
3
|
+
*
|
|
4
|
+
* A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
|
|
5
|
+
* shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
|
|
6
|
+
* groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
|
|
7
|
+
* Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
|
|
8
|
+
* kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
|
|
9
|
+
* breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
|
|
10
|
+
*
|
|
11
|
+
* Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
|
|
12
|
+
* as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
|
|
13
|
+
* started anything yet; only then does it start the real command, with the same stdio.
|
|
14
|
+
*
|
|
15
|
+
* The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
|
|
16
|
+
* is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
|
|
17
|
+
* Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
|
|
18
|
+
* that needs the guarantee can refuse rather than assume it.
|
|
19
|
+
*/
|
|
20
|
+
import { type ChildProcess } from 'node:child_process';
|
|
21
|
+
/** How stopping reaches the command's descendants. */
|
|
22
|
+
export type Containment = 'job' | 'process-group' | 'tree-walk';
|
|
23
|
+
export interface ProcessGroupOptions {
|
|
24
|
+
cwd?: string;
|
|
25
|
+
env?: NodeJS.ProcessEnv;
|
|
26
|
+
windowsHide?: boolean;
|
|
27
|
+
/** Pass argv to the program exactly as given (needed when the program is `cmd.exe`, which has its own parser). */
|
|
28
|
+
windowsVerbatimArguments?: boolean;
|
|
29
|
+
/** stdin, stdout, stderr. Default: all piped. */
|
|
30
|
+
stdio?: readonly ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit'];
|
|
31
|
+
}
|
|
32
|
+
export interface ProcessGroup {
|
|
33
|
+
/** The process that was started. On Windows with a job, this is the launcher; its exit code is the command's. */
|
|
34
|
+
readonly child: ChildProcess;
|
|
35
|
+
readonly containment: Containment;
|
|
36
|
+
/** Stop the command and everything it started. `force` matters on POSIX only (SIGKILL instead of SIGTERM). */
|
|
37
|
+
stop(force?: boolean): void;
|
|
38
|
+
/** Processes still running in the group, where the platform can count them (Windows job only). */
|
|
39
|
+
activeProcesses(): number | undefined;
|
|
40
|
+
}
|
|
41
|
+
/** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
|
|
42
|
+
export declare function processGroupSupport(): {
|
|
43
|
+
containment: Containment;
|
|
44
|
+
reason?: string;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
|
|
48
|
+
* `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
|
|
49
|
+
*/
|
|
50
|
+
export declare function spawnProcessGroup(command: string, args: readonly string[], options?: ProcessGroupOptions): ProcessGroup;
|