@intflow/sentinelctl 0.8.0 → 0.10.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 +48 -6
- package/bin/sentinelctl.mjs +2 -2
- package/package.json +7 -3
- package/src/commands.mjs +456 -3
- package/src/main.mjs +23 -4
- package/src/update-core.mjs +223 -0
- package/src/update-runtime.mjs +152 -0
- package/src/update-store.mjs +205 -0
- package/src/updates.mjs +28 -0
package/src/main.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { browserLogin, openBrowser } from './login.mjs';
|
|
|
10
10
|
|
|
11
11
|
const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
12
12
|
const userAgent = `sentinelctl/${version} node/${process.versions.node}`;
|
|
13
|
-
const updateCommand = '
|
|
13
|
+
const updateCommand = 'sentinelctl update --apply';
|
|
14
14
|
|
|
15
15
|
function newer(latest, current) {
|
|
16
16
|
const a = latest.split('.').map(Number);
|
|
@@ -301,8 +301,15 @@ function apiHint(error, context, command) {
|
|
|
301
301
|
return command?.group === 'devices' || command?.group === 'metadata'
|
|
302
302
|
? 'Check the agent ID with `sentinelctl devices lookup <part of the name>`.' : 'Not found; check the ID.';
|
|
303
303
|
}
|
|
304
|
+
if (error.code === 'source_key_exists') return 'The source already has a valid write key. Add --replace to revoke it and issue a new one.';
|
|
305
|
+
if (error.code === 'source_exists') return 'A source with this ID is already registered; change it with `sentinelctl sources update`.';
|
|
306
|
+
if (error.code === 'source_retired') return 'A retired source is final; register a new source ID instead.';
|
|
307
|
+
if (error.code === 'stage_step') return 'Stages move one step at a time: store → shadow → live → cut_over (or one step back).';
|
|
308
|
+
if (error.code === 'incident_not_active') return 'The incident is already resolved; nothing to acknowledge.';
|
|
309
|
+
if (error.code === 'incident_acknowledged') return 'The incident was already acknowledged.';
|
|
310
|
+
if (error.code === 'silence_inactive') return 'That silence has already ended or been expired; see `sentinelctl silences list --all`.';
|
|
304
311
|
if (error.status === 409) return 'Someone saved a change first. Run the command again to apply on top of the latest revision.';
|
|
305
|
-
if (error.code === 'cli_upgrade_required') return `Update the CLI: ${updateCommand}
|
|
312
|
+
if (error.code === 'cli_upgrade_required') return `Update the CLI: ${updateCommand}, then rerun.`;
|
|
306
313
|
if (error.code === 'log_query_too_broad') {
|
|
307
314
|
return 'Narrow it: add -a <agent-id>, -s <source>, --service <name>, -p "<pattern>" (from `logs stats --by message`) or --case-sensitive with -q, or use a window of 7 days or less.';
|
|
308
315
|
}
|
|
@@ -364,7 +371,9 @@ export async function main(argv, {
|
|
|
364
371
|
else if (specialCommands[subcommand]) out(`Usage: ${specialCommands[subcommand].usage}\n\n${specialCommands[subcommand].summary}`);
|
|
365
372
|
else if (groups[subcommand] && !commandArguments[0]) out(groupHelp(subcommand));
|
|
366
373
|
else {
|
|
367
|
-
const target = groups[subcommand]
|
|
374
|
+
const target = groups[subcommand]
|
|
375
|
+
? findCommand(subcommand, commandArguments[0]) ?? findCommand(subcommand, commandArguments.slice(0, 2).join(' '))
|
|
376
|
+
: findCommand(null, subcommand);
|
|
368
377
|
if (!target) {
|
|
369
378
|
throw unknownCommandError([subcommand, commandArguments[0]].filter(Boolean).join(' '),
|
|
370
379
|
[...Object.keys(groups), ...Object.keys(specialCommands), ...catalog.filter((item) => !item.group).map((item) => item.name), 'agents'], 'help ');
|
|
@@ -389,8 +398,13 @@ export async function main(argv, {
|
|
|
389
398
|
return 0;
|
|
390
399
|
}
|
|
391
400
|
|
|
401
|
+
let consumed = 0;
|
|
392
402
|
if (groups[name]) {
|
|
393
403
|
command = findCommand(name, subcommand);
|
|
404
|
+
if (!command && subcommand && commandArguments.length) {
|
|
405
|
+
command = findCommand(name, `${subcommand} ${commandArguments[0]}`);
|
|
406
|
+
if (command) consumed = 1;
|
|
407
|
+
}
|
|
394
408
|
if (!command) {
|
|
395
409
|
if (!subcommand || wantsHelp) {
|
|
396
410
|
out(groupHelp(name));
|
|
@@ -402,11 +416,16 @@ export async function main(argv, {
|
|
|
402
416
|
command = findCommand(null, name);
|
|
403
417
|
if (!command) throw unknownCommandError(name, [...Object.keys(groups), ...Object.keys(specialCommands), ...catalog.filter((item) => !item.group).map((item) => item.name)]);
|
|
404
418
|
}
|
|
405
|
-
const commandArgv = command?.group ? commandArguments : [subcommand, ...commandArguments].filter((item) => item !== undefined);
|
|
419
|
+
const commandArgv = command?.group ? commandArguments.slice(consumed) : [subcommand, ...commandArguments].filter((item) => item !== undefined);
|
|
406
420
|
if (command && wantsHelp) {
|
|
407
421
|
out(commandHelp(command));
|
|
408
422
|
return 0;
|
|
409
423
|
}
|
|
424
|
+
if (command?.local) {
|
|
425
|
+
const parsed = parseArguments(commandArgv, command.options);
|
|
426
|
+
await command.run({ global, out, err }, parsed);
|
|
427
|
+
return 0;
|
|
428
|
+
}
|
|
410
429
|
|
|
411
430
|
if (global.server) global.server = normalizeServer(global.server);
|
|
412
431
|
const connection = await resolveConnection({ server: global.server, profile: global.profile ?? 'default', environment,
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { candidateTools, compare, metadata, stable } from './update-runtime.mjs';
|
|
5
|
+
import { commit, locked, record, save, snapshot, updateError } from './update-store.mjs';
|
|
6
|
+
|
|
7
|
+
const actionNames = new Set(['check', 'apply', 'status', 'auto', 'pin', 'unpin']);
|
|
8
|
+
const globalValues = new Set(['--url', '--server', '--profile', '-o', '--format', '--output', '--select']);
|
|
9
|
+
const reason = (error) => /^[a-z_]+$/.test(error?.code ?? '') ? error.code : 'update_failed';
|
|
10
|
+
const pointer = (value) => stable(value?.version) ? { version: value.version, release: value.release ?? null } : null;
|
|
11
|
+
const pointerVersion = (value) => stable(value?.version) ? value.version : null;
|
|
12
|
+
|
|
13
|
+
function commandIndex(argv) {
|
|
14
|
+
for (let index = 0; index < argv.length; index++) {
|
|
15
|
+
if (globalValues.has(argv[index])) { index++; continue; }
|
|
16
|
+
if (!argv[index].startsWith('-')) return index;
|
|
17
|
+
}
|
|
18
|
+
return -1;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function controlArguments(argv) {
|
|
22
|
+
const command = commandIndex(argv);
|
|
23
|
+
if (argv[command] !== 'update') return null;
|
|
24
|
+
const options = {};
|
|
25
|
+
for (let index = command + 1; index < argv.length; index++) {
|
|
26
|
+
const token = argv[index];
|
|
27
|
+
if (['--help', '-h'].includes(token)) return null;
|
|
28
|
+
if (['--json', '--quiet'].includes(token)) continue;
|
|
29
|
+
if (globalValues.has(token)) { index++; continue; }
|
|
30
|
+
const match = /^--([a-z]+)(?:=(.*))?$/.exec(token);
|
|
31
|
+
if (!match || !actionNames.has(match[1]) || Object.keys(options).length) throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
32
|
+
const key = match[1];
|
|
33
|
+
if (['auto', 'pin'].includes(key)) {
|
|
34
|
+
const value = match[2] ?? argv[++index];
|
|
35
|
+
if ((key === 'auto' && !['on', 'off'].includes(value)) || (key === 'pin' && !stable(value))) {
|
|
36
|
+
throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
37
|
+
}
|
|
38
|
+
options[key] = value;
|
|
39
|
+
} else {
|
|
40
|
+
if (match[2] !== undefined) throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
41
|
+
options[key] = true;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return Object.keys(options).length ? options : { check: true };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createUpdater(configuration, hooks = {}) {
|
|
48
|
+
const config = { legacy: {}, environment: () => process.env, ...configuration };
|
|
49
|
+
const environment = () => hooks.environment ?? config.environment();
|
|
50
|
+
const root = () => hooks.root ?? join(environment().LOCALAPPDATA ?? environment().XDG_CACHE_HOME ?? join(homedir(), '.cache'),
|
|
51
|
+
config.cacheName, `npm-${process.platform}-${process.arch}-${process.versions.node.split('.')[0]}`);
|
|
52
|
+
const tools = (hooks.candidates ?? candidateTools)({ ...config, environment }, hooks);
|
|
53
|
+
const lookup = hooks.lookup ?? ((version) => metadata(config.name, version, hooks.fetch ?? fetch));
|
|
54
|
+
const base = () => ({ version: config.version, release: null, main: async (args) => {
|
|
55
|
+
const module = await import(pathToFileURL(config.localMain).href);
|
|
56
|
+
return module.main(args);
|
|
57
|
+
} });
|
|
58
|
+
const disabled = () => config.legacy.check && environment()[config.legacy.check] === '0';
|
|
59
|
+
const automaticAllowed = (policy) => policy.automatic && environment().INTFLOW_CLI_AUTO_UPDATE !== '0'
|
|
60
|
+
&& (!config.legacy.auto || environment()[config.legacy.auto] !== '0');
|
|
61
|
+
|
|
62
|
+
async function selected(state) {
|
|
63
|
+
const expected = state.policy.pin;
|
|
64
|
+
if (expected === config.version) return base();
|
|
65
|
+
for (const value of [state.active, state.previous]) {
|
|
66
|
+
if (!value || (expected && value.version !== expected)) continue;
|
|
67
|
+
if (value.version === config.version && value.release === null) return base();
|
|
68
|
+
try { return await tools.validate(root(), value); } catch { continue; }
|
|
69
|
+
}
|
|
70
|
+
if (expected && expected !== config.version) {
|
|
71
|
+
const cached = await tools.cached(root(), expected);
|
|
72
|
+
if (cached) return cached;
|
|
73
|
+
throw updateError('pinned_runtime_unavailable');
|
|
74
|
+
}
|
|
75
|
+
return base();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function status() {
|
|
79
|
+
let state = { policy: { automatic: false, pin: null }, active: null, previous: null };
|
|
80
|
+
let value = base(), last = {}, failure = null;
|
|
81
|
+
try { state = await snapshot(root()); } catch (error) { failure = reason(error); }
|
|
82
|
+
if (!failure) {
|
|
83
|
+
try { value = disabled() ? base() : await selected(state); }
|
|
84
|
+
catch (error) { failure = reason(error); value = { version: null }; }
|
|
85
|
+
}
|
|
86
|
+
try { last = await record(root(), 'state.json', {}); } catch (error) { failure ??= reason(error); }
|
|
87
|
+
return { current: value.version, installed: config.version, active: pointerVersion(state.active), previous: pointerVersion(state.previous),
|
|
88
|
+
automatic: automaticAllowed(state.policy) && !disabled(), pin: state.policy.pin, protocol: 1,
|
|
89
|
+
last_check: typeof last.last_check === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(last.last_check) ? last.last_check : null,
|
|
90
|
+
last_error: failure ?? (typeof last.last_error === 'string' && /^[a-z_]{1,64}$/.test(last.last_error) ? last.last_error : null) };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function prepare(version, advertised = null) {
|
|
94
|
+
if (version === config.version) return base();
|
|
95
|
+
const cached = await tools.cached(root(), version);
|
|
96
|
+
if (cached) return cached;
|
|
97
|
+
const release = advertised ?? await lookup(version);
|
|
98
|
+
return tools.install(root(), version, release);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function activate(state, value, policy = state.policy) {
|
|
102
|
+
const next = pointer(value);
|
|
103
|
+
let prior;
|
|
104
|
+
try { prior = pointer(await selected(state)); } catch { prior = null; }
|
|
105
|
+
const previous = JSON.stringify(next) === JSON.stringify(state.active) ? state.previous
|
|
106
|
+
: JSON.stringify(prior) === JSON.stringify(next) ? null : prior;
|
|
107
|
+
await commit(root(), { policy, active: next, previous });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function check() {
|
|
111
|
+
const state = await snapshot(root());
|
|
112
|
+
const current = await selected(state);
|
|
113
|
+
try {
|
|
114
|
+
const release = await lookup(state.policy.pin ?? 'latest');
|
|
115
|
+
let compatible = true;
|
|
116
|
+
try { tools.compatible(release, release.version); } catch { compatible = false; }
|
|
117
|
+
return { ...await status(), latest: release.version, available: compatible && (state.policy.pin
|
|
118
|
+
? release.version !== current.version : compare(release.version, current.version) > 0), compatible };
|
|
119
|
+
} catch (error) { return { ...await status(), latest: null, available: false, compatible: false, last_error: reason(error) }; }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function control(options) {
|
|
123
|
+
if (Object.keys(options).length !== 1 || !actionNames.has(Object.keys(options)[0])) throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
124
|
+
if (('pin' in options && !stable(options.pin)) || ('auto' in options && !['on', 'off'].includes(options.auto))) {
|
|
125
|
+
throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
126
|
+
}
|
|
127
|
+
if (options.status) return status();
|
|
128
|
+
if (options.check) return check();
|
|
129
|
+
try { await locked(root(), async () => {
|
|
130
|
+
const state = await snapshot(root());
|
|
131
|
+
if ('auto' in options) {
|
|
132
|
+
if (!['on', 'off'].includes(options.auto)) throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
133
|
+
await commit(root(), { ...state, policy: { ...state.policy, automatic: options.auto === 'on' } });
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (options.unpin) {
|
|
137
|
+
await commit(root(), { ...state, policy: { ...state.policy, pin: null } });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
let target = options.pin ?? state.policy.pin;
|
|
141
|
+
let advertised = null;
|
|
142
|
+
if (target && !stable(target)) throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
143
|
+
if (!target) {
|
|
144
|
+
advertised = await lookup('latest');
|
|
145
|
+
target = advertised.version;
|
|
146
|
+
if (compare(target, (await selected(state)).version) <= 0) return;
|
|
147
|
+
}
|
|
148
|
+
const value = await prepare(target, advertised);
|
|
149
|
+
await save(root(), 'state.json', { last_check: new Date().toISOString(), last_error: null });
|
|
150
|
+
await activate(state, value, options.pin ? { ...state.policy, pin: target } : state.policy);
|
|
151
|
+
}, hooks.lockOptions); } catch (error) {
|
|
152
|
+
if (reason(error) !== 'update_locked') {
|
|
153
|
+
try { await locked(root(), () => save(root(), 'state.json', { last_check: new Date().toISOString(), last_error: reason(error) }), hooks.lockOptions); } catch { throw error; }
|
|
154
|
+
}
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
return status();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function refresh() {
|
|
161
|
+
if (disabled()) return base();
|
|
162
|
+
const initial = await snapshot(root());
|
|
163
|
+
let fallback;
|
|
164
|
+
try { fallback = await selected(initial); } catch (error) {
|
|
165
|
+
if (initial.policy.pin) throw error;
|
|
166
|
+
fallback = base();
|
|
167
|
+
}
|
|
168
|
+
if (!automaticAllowed(initial.policy) && !initial.policy.pin) return fallback;
|
|
169
|
+
if (environment().INTFLOW_CLI_AUTO_UPDATE === '0' || (config.legacy.auto && environment()[config.legacy.auto] === '0')) return fallback;
|
|
170
|
+
try {
|
|
171
|
+
return await locked(root(), async () => {
|
|
172
|
+
const state = await snapshot(root());
|
|
173
|
+
let current = await selected(state);
|
|
174
|
+
try {
|
|
175
|
+
if (state.policy.pin) {
|
|
176
|
+
if (current.version !== state.policy.pin) current = await prepare(state.policy.pin);
|
|
177
|
+
} else if (automaticAllowed(state.policy)) {
|
|
178
|
+
const release = await lookup('latest');
|
|
179
|
+
if (compare(release.version, current.version) > 0) {
|
|
180
|
+
tools.compatible(release, release.version);
|
|
181
|
+
current = await prepare(release.version, release);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (JSON.stringify(pointer(current)) !== JSON.stringify(state.active)) await activate(state, current);
|
|
185
|
+
await save(root(), 'state.json', { last_check: new Date().toISOString(), last_error: null });
|
|
186
|
+
return current;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (JSON.stringify(pointer(current)) !== JSON.stringify(state.active)) await activate(state, current);
|
|
189
|
+
await save(root(), 'state.json', { last_check: new Date().toISOString(), last_error: reason(error) });
|
|
190
|
+
return current;
|
|
191
|
+
}
|
|
192
|
+
}, hooks.lockOptions);
|
|
193
|
+
} catch { return fallback; }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function bootstrap(argv) {
|
|
197
|
+
const args = config.fullArgv ? argv.slice(2) : argv;
|
|
198
|
+
if (args.length === 1 && args[0] === '--runtime-probe') {
|
|
199
|
+
const module = await import(pathToFileURL(config.localMain).href);
|
|
200
|
+
if (typeof module.main !== 'function') throw updateError('invalid_entry');
|
|
201
|
+
process.stdout.write(JSON.stringify({ protocol: 1, package: config.name, version: config.version, runtime: 'node' }) + '\n');
|
|
202
|
+
return 0;
|
|
203
|
+
}
|
|
204
|
+
if (args.includes('--runtime-probe')) throw Object.assign(updateError('invalid_update_arguments'), { exitCode: 2 });
|
|
205
|
+
if (config.baseOnlyCommands?.includes(args[commandIndex(args)])) return base().main(argv);
|
|
206
|
+
const options = controlArguments(args);
|
|
207
|
+
if (options && !args.includes('--help')) {
|
|
208
|
+
process.stdout.write(JSON.stringify(await control(options)) + '\n');
|
|
209
|
+
return 0;
|
|
210
|
+
}
|
|
211
|
+
const readOnly = args.length === 0 || args[commandIndex(args)] === 'help'
|
|
212
|
+
|| args.some((value) => ['--help', '-h', '--version', '-V'].includes(value)) || options;
|
|
213
|
+
let value = base();
|
|
214
|
+
if (!disabled()) {
|
|
215
|
+
if (readOnly) {
|
|
216
|
+
try { value = await selected(await snapshot(root())); } catch { value = base(); }
|
|
217
|
+
} else value = await refresh();
|
|
218
|
+
}
|
|
219
|
+
return value.main(argv);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return { root, bootstrap, status, control, check, refresh };
|
|
223
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { lstat, readFile, readdir, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { privateDirectory, record, safePath, save, updateError } from './update-store.mjs';
|
|
8
|
+
|
|
9
|
+
const execute = promisify(execFile);
|
|
10
|
+
export const stable = (value) => typeof value === 'string' && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value);
|
|
11
|
+
export const compare = (left, right) => {
|
|
12
|
+
const a = left.split('.').map(Number), b = right.split('.').map(Number);
|
|
13
|
+
const index = a.findIndex((part, i) => part !== b[i]);
|
|
14
|
+
return index < 0 ? 0 : Math.sign(a[index] - b[index]);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function supportsNode(range, current = process.versions.node) {
|
|
18
|
+
if (typeof range !== 'string' || !range.trim()) return false;
|
|
19
|
+
return range.split('||').some((alternative) => alternative.trim().split(/\s+/).every((clause) => {
|
|
20
|
+
const match = /^(>=|<=|>|<|=)?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(clause);
|
|
21
|
+
if (!match) return false;
|
|
22
|
+
const value = [match[2], match[3] ?? '0', match[4] ?? '0'].join('.');
|
|
23
|
+
const delta = compare(current, value);
|
|
24
|
+
return ({ '>=': delta >= 0, '<=': delta <= 0, '>': delta > 0, '<': delta < 0, '=': delta === 0 })[match[1] ?? '='];
|
|
25
|
+
}));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function installerEnvironment(environment = process.env, legacy = {}) {
|
|
29
|
+
const allowed = /^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|HOME|USERPROFILE|LOCALAPPDATA|APPDATA|TEMP|TMP|TMPDIR|LANG|LC_ALL)$/i;
|
|
30
|
+
return { ...Object.fromEntries(Object.entries(environment).filter(([key]) => allowed.test(key))),
|
|
31
|
+
INTFLOW_CLI_AUTO_UPDATE: '0', ...Object.fromEntries(Object.values(legacy).filter(Boolean).map((key) => [key, '0'])) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function metadata(name, version = 'latest', fetcher = fetch) {
|
|
35
|
+
const response = await fetcher(`https://registry.npmjs.org/${encodeURIComponent(name)}/${encodeURIComponent(version)}`,
|
|
36
|
+
{ redirect: 'error', signal: globalThis.AbortSignal.timeout(3000), headers: { Accept: 'application/json' } });
|
|
37
|
+
if (!response.ok || !response.body) throw updateError(response.status === 404 ? 'release_unavailable' : 'registry_unavailable');
|
|
38
|
+
const chunks = [];
|
|
39
|
+
let length = 0;
|
|
40
|
+
for await (const chunk of response.body) {
|
|
41
|
+
length += chunk.byteLength;
|
|
42
|
+
if (length > 1048576) throw updateError('registry_response_too_large');
|
|
43
|
+
chunks.push(Buffer.from(chunk));
|
|
44
|
+
}
|
|
45
|
+
let value;
|
|
46
|
+
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw updateError('invalid_release'); }
|
|
47
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || value.name !== name || !stable(value.version)
|
|
48
|
+
|| (version !== 'latest' && value.version !== version)) throw updateError('invalid_release');
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function payload(root) {
|
|
53
|
+
const result = {};
|
|
54
|
+
let count = 0, size = 0;
|
|
55
|
+
async function visit(directory, prefix = '') {
|
|
56
|
+
for (const item of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
57
|
+
if (item.name === 'node_modules') continue;
|
|
58
|
+
const relative = prefix + item.name;
|
|
59
|
+
const path = await safePath(root, join(directory, item.name));
|
|
60
|
+
const info = await lstat(path);
|
|
61
|
+
if (info.isDirectory()) await visit(path, relative + '/');
|
|
62
|
+
else {
|
|
63
|
+
if (!info.isFile() || info.nlink !== 1 || ++count > 512 || (size += info.size) > 16777216) throw updateError('invalid_payload');
|
|
64
|
+
result[relative] = createHash('sha256').update(await readFile(path)).digest('hex');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
await visit(root);
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function candidateTools(config, hooks = {}) {
|
|
73
|
+
const runner = hooks.run ?? execute;
|
|
74
|
+
const cleanEnvironment = () => installerEnvironment(config.environment(), config.legacy);
|
|
75
|
+
const validDescriptor = (value) => value && stable(value.version) && typeof value.release === 'string'
|
|
76
|
+
&& /^release-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.release);
|
|
77
|
+
const packagePath = (root, descriptor) => join(root, descriptor.release, 'node_modules', ...config.name.split('/'));
|
|
78
|
+
function compatible(value, version) {
|
|
79
|
+
if (value.name !== config.name || value.version !== version || value.intflow?.cliUpdateProtocol !== 1
|
|
80
|
+
|| !supportsNode(value.engines?.node)) throw updateError('incompatible_release');
|
|
81
|
+
}
|
|
82
|
+
async function inspect(root, descriptor) {
|
|
83
|
+
if (!validDescriptor(descriptor)) throw updateError('invalid_pointer');
|
|
84
|
+
const stage = await safePath(root, join(root, descriptor.release));
|
|
85
|
+
if (!(await lstat(stage)).isDirectory()) throw updateError('invalid_stage');
|
|
86
|
+
await privateDirectory(stage);
|
|
87
|
+
const directory = packagePath(root, descriptor);
|
|
88
|
+
const manifestPath = await safePath(root, join(directory, 'package.json'));
|
|
89
|
+
const value = JSON.parse(await readFile(manifestPath, 'utf8'));
|
|
90
|
+
compatible(value, descriptor.version);
|
|
91
|
+
const entry = await safePath(root, join(directory, config.entry));
|
|
92
|
+
const main = await safePath(root, join(directory, config.main));
|
|
93
|
+
if (!(await lstat(entry)).isFile() || !(await lstat(main)).isFile()) throw updateError('invalid_entry');
|
|
94
|
+
return { directory, entry, main };
|
|
95
|
+
}
|
|
96
|
+
async function probe(paths, version) {
|
|
97
|
+
const options = { env: cleanEnvironment(), timeout: 5000, maxBuffer: 4096, windowsHide: true, cwd: paths.directory };
|
|
98
|
+
const result = await runner(process.execPath, [paths.entry, '--runtime-probe'], options);
|
|
99
|
+
let value;
|
|
100
|
+
try { value = JSON.parse(result.stdout); } catch { throw updateError('invalid_probe'); }
|
|
101
|
+
if (value.protocol !== 1 || value.package !== config.name || value.version !== version || value.runtime !== 'node') throw updateError('invalid_probe');
|
|
102
|
+
const reported = await runner(process.execPath, [paths.entry, '--version'], options);
|
|
103
|
+
if (reported.stdout.trim() !== version) throw updateError('invalid_probe');
|
|
104
|
+
}
|
|
105
|
+
async function validate(root, descriptor) {
|
|
106
|
+
const paths = await inspect(root, descriptor);
|
|
107
|
+
const proof = await record(join(root, descriptor.release), 'release.json');
|
|
108
|
+
if (proof?.version !== descriptor.version || proof?.package !== config.name || proof.protocol !== 1
|
|
109
|
+
|| JSON.stringify(proof.hashes) !== JSON.stringify(await payload(paths.directory))) throw updateError('runtime_tampered');
|
|
110
|
+
await probe(paths, descriptor.version);
|
|
111
|
+
const module = await import(pathToFileURL(paths.main).href);
|
|
112
|
+
if (typeof module.main !== 'function') throw updateError('invalid_entry');
|
|
113
|
+
return { ...descriptor, main: module.main };
|
|
114
|
+
}
|
|
115
|
+
async function install(root, version, advertised) {
|
|
116
|
+
compatible(advertised, version);
|
|
117
|
+
const descriptor = { version, release: 'release-' + randomUUID() };
|
|
118
|
+
const stage = await safePath(root, join(root, descriptor.release));
|
|
119
|
+
await privateDirectory(stage);
|
|
120
|
+
try {
|
|
121
|
+
for (const filename of ['.npmrc-user', '.npmrc-global']) await writeFile(join(stage, filename), '', { flag: 'wx', mode: 0o600 });
|
|
122
|
+
const args = ['install', '--prefix', stage, '--ignore-scripts', '--no-audit', '--no-fund', '--package-lock=false', '--prefer-online',
|
|
123
|
+
'--fetch-retries=0', '--fetch-timeout=30000', '--cache=' + join(stage, '.npm-cache'),
|
|
124
|
+
'--userconfig=' + join(stage, '.npmrc-user'), '--globalconfig=' + join(stage, '.npmrc-global'),
|
|
125
|
+
'--registry=https://registry.npmjs.org', config.name + '@' + version];
|
|
126
|
+
if (hooks.install) await hooks.install(stage, version, args, cleanEnvironment());
|
|
127
|
+
else {
|
|
128
|
+
const npm = process.platform === 'win32' ? join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js') : null;
|
|
129
|
+
await runner(npm ? process.execPath : 'npm', npm ? [npm, ...args] : args,
|
|
130
|
+
{ cwd: stage, env: cleanEnvironment(), timeout: 160000, maxBuffer: 1048576, windowsHide: true });
|
|
131
|
+
}
|
|
132
|
+
const paths = await inspect(root, descriptor);
|
|
133
|
+
await probe(paths, version);
|
|
134
|
+
await save(stage, 'release.json', { package: config.name, version, protocol: 1, hashes: await payload(paths.directory) });
|
|
135
|
+
return await validate(root, descriptor);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
await safePath(root, stage);
|
|
138
|
+
await rm(stage, { recursive: true, force: true });
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async function cached(root, version) {
|
|
143
|
+
let names;
|
|
144
|
+
try { names = await readdir(root); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
145
|
+
for (const release of names.slice(0, 128)) {
|
|
146
|
+
if (!validDescriptor({ version, release })) continue;
|
|
147
|
+
try { return await validate(root, { version, release }); } catch { continue; }
|
|
148
|
+
}
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
return { validate, install, cached, compatible };
|
|
152
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, mkdir, open, writeFile, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
|
|
8
|
+
const execute = promisify(execFile);
|
|
9
|
+
const windowsDirectories = new Map();
|
|
10
|
+
const directoryClaims = new Map();
|
|
11
|
+
|
|
12
|
+
async function windowsDirectory(path, created, info) {
|
|
13
|
+
const identity = `${info.dev}:${info.ino}:${info.birthtimeMs}`;
|
|
14
|
+
if (windowsDirectories.get(path) === identity) return;
|
|
15
|
+
const script = `$ErrorActionPreference='Stop';$p=$env:INTFLOW_CLI_ACL_PATH;$s=[Security.Principal.WindowsIdentity]::GetCurrent().User;$i=Get-Item -LiteralPath $p -Force;if(($i.Attributes -band [IO.FileAttributes]::ReparsePoint)-ne 0){throw 'path'};${created ? "$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetOwner($s);$a.SetAccessRuleProtection($true,$false);$r=New-Object Security.AccessControl.FileSystemAccessRule($s,'FullControl','ContainerInherit,ObjectInherit','None','Allow');$a.AddAccessRule($r);Set-Acl -LiteralPath $p -AclObject $a;" : ''}$a=Get-Acl -LiteralPath $p;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-ne $s.Value-or-not $a.AreAccessRulesProtected){throw 'owner'};$r=$a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]);if($r.Count-eq 0){throw 'empty'};foreach($v in $r){if($v.IdentityReference.Value-ne $s.Value-or $v.AccessControlType-ne 'Allow'){throw 'access'}}`;
|
|
16
|
+
const allowed = /^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|TEMP|TMP)$/i;
|
|
17
|
+
const env = { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => allowed.test(key))), INTFLOW_CLI_ACL_PATH: path };
|
|
18
|
+
try {
|
|
19
|
+
await execute('powershell.exe', ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
|
|
20
|
+
{ env, timeout: 10000, maxBuffer: 4096, windowsHide: true });
|
|
21
|
+
} catch { throw updateError('unsafe_cache'); }
|
|
22
|
+
windowsDirectories.set(path, identity);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function updateError(code) {
|
|
26
|
+
return Object.assign(new Error(code), { code });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function safePath(root, path = root) {
|
|
30
|
+
const base = resolve(root);
|
|
31
|
+
const target = resolve(path);
|
|
32
|
+
const tail = relative(base, target);
|
|
33
|
+
if (isAbsolute(tail) || tail.startsWith('..') || resolve(base, tail) !== target) throw updateError('invalid_path');
|
|
34
|
+
let cursor = parse(target).root;
|
|
35
|
+
for (const part of target.slice(cursor.length).split(/[\\/]/).filter(Boolean)) {
|
|
36
|
+
if (process.platform === 'win32' && (part.includes(':') || /[. ]$/.test(part))) throw updateError('invalid_path');
|
|
37
|
+
cursor = join(cursor, part);
|
|
38
|
+
try {
|
|
39
|
+
if ((await lstat(cursor)).isSymbolicLink()) throw updateError('invalid_path');
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error.code === 'ENOENT') break;
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return target;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function initializeDirectory(root) {
|
|
49
|
+
await safePath(root);
|
|
50
|
+
let created = false;
|
|
51
|
+
try { await mkdir(root, { mode: 0o700 }); created = true; } catch (error) {
|
|
52
|
+
if (error.code === 'ENOENT') {
|
|
53
|
+
await privateDirectory(dirname(root));
|
|
54
|
+
return initializeDirectory(root);
|
|
55
|
+
}
|
|
56
|
+
if (error.code !== 'EEXIST') throw error;
|
|
57
|
+
}
|
|
58
|
+
const info = await lstat(root);
|
|
59
|
+
if (!info.isDirectory() || (process.platform !== 'win32' && ((info.mode & 0o077) || info.uid !== process.getuid()))) {
|
|
60
|
+
throw updateError('unsafe_cache');
|
|
61
|
+
}
|
|
62
|
+
if (process.platform === 'win32') await windowsDirectory(root, created, info);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function privateDirectory(path) {
|
|
66
|
+
const root = resolve(path);
|
|
67
|
+
if (directoryClaims.has(root)) return directoryClaims.get(root);
|
|
68
|
+
const pending = initializeDirectory(root);
|
|
69
|
+
directoryClaims.set(root, pending);
|
|
70
|
+
try { return await pending; } finally { directoryClaims.delete(root); }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function record(root, name, fallback = null) {
|
|
74
|
+
const path = await safePath(root, join(root, name));
|
|
75
|
+
let handle;
|
|
76
|
+
try {
|
|
77
|
+
if (directoryClaims.has(resolve(root))) await directoryClaims.get(resolve(root));
|
|
78
|
+
if (process.platform === 'win32') await windowsDirectory(root, false, await lstat(root));
|
|
79
|
+
handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error.code === 'ENOENT') return fallback;
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const info = await handle.stat();
|
|
86
|
+
if (!info.isFile() || info.nlink > 1 || info.size > 65536
|
|
87
|
+
|| (process.platform !== 'win32' && ((info.mode & 0o077) || info.uid !== process.getuid()))) throw updateError('invalid_record');
|
|
88
|
+
const buffer = Buffer.alloc(65537);
|
|
89
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
90
|
+
if (bytesRead > 65536) throw updateError('invalid_record');
|
|
91
|
+
const value = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));
|
|
92
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw updateError('invalid_record');
|
|
93
|
+
return value;
|
|
94
|
+
} catch { throw updateError('invalid_record'); } finally { await handle.close(); }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function removeRecord(root, name) {
|
|
98
|
+
const path = await safePath(root, join(root, name));
|
|
99
|
+
try { await unlink(path); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function save(root, name, value) {
|
|
103
|
+
await privateDirectory(root);
|
|
104
|
+
await safePath(root, join(root, name));
|
|
105
|
+
const temporary = join(root, `.record-${randomUUID()}`);
|
|
106
|
+
try {
|
|
107
|
+
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
108
|
+
try { await handle.writeFile(JSON.stringify(value)); await handle.sync(); } finally { await handle.close(); }
|
|
109
|
+
await rename(temporary, join(root, name));
|
|
110
|
+
if (process.platform !== 'win32') {
|
|
111
|
+
const directory = await open(root, constants.O_RDONLY);
|
|
112
|
+
try { await directory.sync(); } finally { await directory.close(); }
|
|
113
|
+
}
|
|
114
|
+
} catch (error) {
|
|
115
|
+
await removeRecord(root, temporary.slice(root.length + 1));
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const defaultPolicy = () => ({ schema: 1, automatic: true, pin: null });
|
|
121
|
+
|
|
122
|
+
export function validPolicy(value) {
|
|
123
|
+
if (!value || value.schema !== 1 || typeof value.automatic !== 'boolean'
|
|
124
|
+
|| (value.pin !== null && (typeof value.pin !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value.pin)))) throw updateError('invalid_policy');
|
|
125
|
+
return { schema: 1, automatic: value.automatic, pin: value.pin };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function snapshot(root) {
|
|
129
|
+
const transaction = await record(root, 'transaction.json');
|
|
130
|
+
const values = transaction?.before ?? {
|
|
131
|
+
policy: await record(root, 'policy.json', defaultPolicy()),
|
|
132
|
+
active: await record(root, 'active.json'),
|
|
133
|
+
previous: await record(root, 'previous.json'),
|
|
134
|
+
};
|
|
135
|
+
return { policy: validPolicy(values.policy), active: values.active, previous: values.previous };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function restore(root, values) {
|
|
139
|
+
for (const name of ['active', 'previous', 'policy']) {
|
|
140
|
+
if (values[name] === null) await removeRecord(root, name + '.json');
|
|
141
|
+
else await save(root, name + '.json', values[name]);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function recover(root) {
|
|
146
|
+
const transaction = await record(root, 'transaction.json');
|
|
147
|
+
if (!transaction) return;
|
|
148
|
+
validPolicy(transaction.before?.policy);
|
|
149
|
+
await restore(root, transaction.before);
|
|
150
|
+
await removeRecord(root, 'transaction.json');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function commit(root, next) {
|
|
154
|
+
const before = await snapshot(root);
|
|
155
|
+
await save(root, 'transaction.json', { before });
|
|
156
|
+
try {
|
|
157
|
+
await restore(root, next);
|
|
158
|
+
await removeRecord(root, 'transaction.json');
|
|
159
|
+
} catch (error) {
|
|
160
|
+
await recover(root);
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function alive(pid) {
|
|
166
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return true;
|
|
167
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function reclaim(root) {
|
|
171
|
+
const path = join(root, 'reclaim.lock');
|
|
172
|
+
try { await writeFile(path, '', { flag: 'wx', mode: 0o600 }); } catch (error) {
|
|
173
|
+
if (error.code === 'EEXIST') return;
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
let prior;
|
|
178
|
+
try { prior = await record(root, 'install.lock'); } catch (error) {
|
|
179
|
+
if (error.code === 'invalid_record') return;
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
if (prior && Date.now() - Number(prior.at) > 200000 && !alive(prior.pid)) await removeRecord(root, 'install.lock');
|
|
183
|
+
} finally { await removeRecord(root, 'reclaim.lock'); }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function locked(root, action, { timeout = 2000 } = {}) {
|
|
187
|
+
await privateDirectory(root);
|
|
188
|
+
const token = randomUUID();
|
|
189
|
+
const deadline = Date.now() + timeout;
|
|
190
|
+
while (true) {
|
|
191
|
+
try {
|
|
192
|
+
await writeFile(join(root, 'install.lock'), JSON.stringify({ token, pid: process.pid, at: Date.now() }), { flag: 'wx', mode: 0o600 });
|
|
193
|
+
break;
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error.code !== 'EEXIST') throw error;
|
|
196
|
+
await reclaim(root);
|
|
197
|
+
if (Date.now() >= deadline) throw updateError('update_locked');
|
|
198
|
+
await new Promise((accept) => setTimeout(accept, 25));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
try { await recover(root); return await action(); } finally {
|
|
202
|
+
const current = await record(root, 'install.lock');
|
|
203
|
+
if (current?.token === token) await removeRecord(root, 'install.lock');
|
|
204
|
+
}
|
|
205
|
+
}
|