@moxuli/moremote 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +31 -0
- package/README.md +73 -2
- package/bin/moremote-cli.js +34 -0
- package/bin/moremote-service.js +7 -0
- package/dist/bindings.d.ts +6 -0
- package/dist/bindings.js +4 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +308 -0
- package/dist/cloud-client.d.ts +43 -0
- package/dist/cloud-client.js +128 -0
- package/dist/config.d.ts +36 -0
- package/dist/config.js +68 -0
- package/dist/control.d.ts +3 -0
- package/dist/control.js +226 -0
- package/dist/controls.d.ts +15 -0
- package/dist/controls.js +36 -0
- package/dist/crypto.d.ts +23 -0
- package/dist/crypto.js +68 -0
- package/dist/evidence.d.ts +19 -0
- package/dist/evidence.js +4 -0
- package/dist/journal.d.ts +104 -0
- package/dist/journal.js +132 -0
- package/dist/limits.d.ts +21 -0
- package/dist/limits.js +8 -0
- package/dist/official-client.d.ts +120 -0
- package/dist/official-client.js +162 -0
- package/dist/operations.d.ts +71 -0
- package/dist/operations.js +210 -0
- package/dist/pairing.d.ts +19 -0
- package/dist/pairing.js +68 -0
- package/dist/permission.d.ts +9 -0
- package/dist/permission.js +66 -0
- package/dist/projection.d.ts +24 -0
- package/dist/projection.js +35 -0
- package/dist/resources.d.ts +76 -0
- package/dist/resources.js +299 -0
- package/dist/runtime.d.ts +8 -0
- package/dist/runtime.js +375 -0
- package/dist/service.d.ts +21 -0
- package/dist/service.js +310 -0
- package/dist/supervisor.d.ts +15 -0
- package/dist/supervisor.js +175 -0
- package/dist/update-state.d.ts +30 -0
- package/dist/update-state.js +158 -0
- package/dist/updater.d.ts +9 -0
- package/dist/updater.js +152 -0
- package/docs/README.md +23 -0
- package/docs/STATE.md +132 -0
- package/docs/configuration.md +37 -0
- package/docs/conventions.md +9 -0
- package/docs/decisions/0001-managed-updates.md +19 -0
- package/docs/plans/2026-11-10-managed-updates.md +26 -0
- package/docs/plans/2026-11-10-notification-delivery.md +118 -0
- package/docs/releasing.md +38 -0
- package/docs/specs/01-architecture.md +102 -0
- package/docs/specs/02-encrypted-delivery.md +194 -0
- package/docs/specs/03-api-contract.md +397 -0
- package/docs/specs/04-control-and-receipt-lifecycle.md +175 -0
- package/docs/specs/05-endpoint-and-lifecycle.md +57 -0
- package/docs/specs/06-managed-updates.md +49 -0
- package/licenses/Paseo-0.15.3.txt +211 -0
- package/package.json +37 -4
- package/vectors/bearer-v1.json +6 -0
- package/vectors/envelope-v1.json +24 -0
package/dist/service.js
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { join, dirname } from 'node:path';
|
|
4
|
+
import { homedir, userInfo } from 'node:os';
|
|
5
|
+
import { constants } from 'node:fs';
|
|
6
|
+
import { mkdir, readFile, unlink, access, lstat, open, rename, link, mkdtemp, rm } from 'node:fs/promises';
|
|
7
|
+
import { privateDirectory, privateManagedDirectory } from './config.js';
|
|
8
|
+
import { PACKAGE, exactVersion, updateLock } from './update-state.js';
|
|
9
|
+
const taskName = '\\MoRemoteCLI';
|
|
10
|
+
function xml(s) { return s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); }
|
|
11
|
+
function systemd(s) { if (/[\r\n\0]/.test(s))
|
|
12
|
+
throw Error('INVALID_SERVICE_PATH'); return '"' + s.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%').replaceAll('$', () => '$$') + '"'; }
|
|
13
|
+
function windowsArg(s) { return '"' + s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1') + '"'; }
|
|
14
|
+
export function serviceDefinition(platform, home, node, entry, data) {
|
|
15
|
+
const marker = 'Managed by moremote-cli; per-user ownership v1; owner=' + createHash('sha256').update(data).digest('hex');
|
|
16
|
+
if (platform === 'darwin')
|
|
17
|
+
return { platform, entry, path: join(home, 'Library', 'LaunchAgents', 'com.moremote.cli.plist'), content: '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>com.moremote.cli</string><key>Description</key><string>' + marker + '</string><key>ProgramArguments</key><array>' + [node, entry, 'run', '--data-dir', data].map(s => '<string>' + xml(s) + '</string>').join('') + '</array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ProcessType</key><string>Background</string></dict></plist>\n' };
|
|
18
|
+
if (platform === 'linux')
|
|
19
|
+
return { platform, entry, path: join(process.env.XDG_CONFIG_HOME || join(home, '.config'), 'systemd', 'user', 'moremote-cli.service'), content: '[Unit]\nDescription=' + marker + '\n[Service]\nExecStart=' + [node, entry, 'run', '--data-dir', data].map(systemd).join(' ') + '\nRestart=on-failure\nRestartSec=5\n[Install]\nWantedBy=default.target\n' };
|
|
20
|
+
if (platform === 'win32')
|
|
21
|
+
return { platform, entry, path: join(data, 'moremote-cli-task.xml'), content: '<?xml version="1.0" encoding="UTF-16"?><Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Description>' + marker + '</Description></RegistrationInfo><Triggers><LogonTrigger><UserId>' + xml(userInfo().username) + '</UserId><Enabled>true</Enabled></LogonTrigger></Triggers><Principals><Principal id="CurrentUser"><UserId>' + xml(userInfo().username) + '</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Enabled>true</Enabled></Settings><Actions Context="CurrentUser"><Exec><Command>' + xml(node) + '</Command><Arguments>' + xml([entry, 'run', '--data-dir', data].map(windowsArg).join(' ')) + '</Arguments></Exec></Actions></Task>' };
|
|
22
|
+
throw Error('UNSUPPORTED_SERVICE_PLATFORM');
|
|
23
|
+
}
|
|
24
|
+
class CommandFailure extends Error {
|
|
25
|
+
program;
|
|
26
|
+
status;
|
|
27
|
+
output;
|
|
28
|
+
constructor(program, status, output) {
|
|
29
|
+
super('COMMAND_FAILED_' + program + '_' + status);
|
|
30
|
+
this.program = program;
|
|
31
|
+
this.status = status;
|
|
32
|
+
this.output = output;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function command(program, args, capture = true, timeout = 120000) {
|
|
36
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
37
|
+
const child = spawn(program, args, { stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit', shell: false, windowsHide: true });
|
|
38
|
+
let timedOut = false;
|
|
39
|
+
const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeout);
|
|
40
|
+
timer.unref();
|
|
41
|
+
let output = '', tooLarge = false;
|
|
42
|
+
if (capture)
|
|
43
|
+
for (const stream of [child.stdout, child.stderr])
|
|
44
|
+
stream?.on('data', chunk => {
|
|
45
|
+
output += chunk;
|
|
46
|
+
if (output.length > 65536) {
|
|
47
|
+
tooLarge = true;
|
|
48
|
+
child.kill();
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
child.once('error', error => { clearTimeout(timer); reject(error); });
|
|
52
|
+
child.once('close', code => { clearTimeout(timer); timedOut ? reject(Error('COMMAND_TIMEOUT')) : tooLarge ? reject(Error('COMMAND_OUTPUT_LIMIT')) : code === 0 ? resolve(output) : reject(new CommandFailure(program, code, output)); });
|
|
53
|
+
return promise;
|
|
54
|
+
}
|
|
55
|
+
function missing(error) { return error instanceof Error && 'code' in error && error.code === 'ENOENT'; }
|
|
56
|
+
function marker(def) {
|
|
57
|
+
const value = def.content.match(/Managed by moremote-cli; per-user ownership v1; owner=[0-9a-f]{64}/)?.[0];
|
|
58
|
+
if (!value)
|
|
59
|
+
throw Error('INVALID_SERVICE_DEFINITION');
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
async function ownedFile(def) {
|
|
63
|
+
let stat;
|
|
64
|
+
try {
|
|
65
|
+
stat = await lstat(def.path);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (missing(error))
|
|
69
|
+
return undefined;
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
if (!stat.isFile() || stat.isSymbolicLink() || (process.getuid && stat.uid !== process.getuid()))
|
|
73
|
+
throw Error('FOREIGN_SERVICE_FILE');
|
|
74
|
+
const handle = await open(def.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
75
|
+
try {
|
|
76
|
+
const actual = await handle.stat();
|
|
77
|
+
if (actual.dev !== stat.dev || actual.ino !== stat.ino)
|
|
78
|
+
throw Error('FOREIGN_SERVICE_FILE');
|
|
79
|
+
const content = await handle.readFile(def.platform === 'win32' ? 'utf16le' : 'utf8');
|
|
80
|
+
if (!content.includes(marker(def)))
|
|
81
|
+
throw Error('FOREIGN_SERVICE_FILE');
|
|
82
|
+
return { dev: stat.dev, ino: stat.ino, content };
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
await handle.close();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const windowsQuery = "$ErrorActionPreference='Stop'; try { $task=Get-ScheduledTask -TaskName 'MoRemoteCLI' -TaskPath '\\' -ErrorAction Stop; Export-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath } catch { if ($_.CategoryInfo.Category -eq 'ObjectNotFound') { exit 3 }; exit 1 }";
|
|
89
|
+
function xmlValue(content, element) {
|
|
90
|
+
const value = content.match(new RegExp('<' + element + '(?:\\s[^>]*)?>([\\s\\S]*?)</' + element + '>'))?.[1];
|
|
91
|
+
return value?.replaceAll('"', '"').replaceAll(''', "'").replaceAll('<', '<').replaceAll('>', '>').replaceAll('&', '&');
|
|
92
|
+
}
|
|
93
|
+
async function registration(def, content) {
|
|
94
|
+
if (def.platform === 'darwin') {
|
|
95
|
+
let raw;
|
|
96
|
+
try {
|
|
97
|
+
raw = await command('launchctl', ['print', 'gui/' + process.getuid() + '/com.moremote.cli'], true);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error instanceof CommandFailure && error.status === 113 && /Could not find service/.test(error.output))
|
|
101
|
+
return 'absent';
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
const path = raw.match(/^\s*path = (.+)\s*$/m)?.[1]?.trim();
|
|
105
|
+
if (path !== def.path)
|
|
106
|
+
throw Error('FOREIGN_SERVICE_REGISTRATION');
|
|
107
|
+
}
|
|
108
|
+
else if (def.platform === 'linux') {
|
|
109
|
+
const raw = await command('systemctl', ['--user', 'show', 'moremote-cli.service', '--property=FragmentPath,LoadState,ActiveState'], true);
|
|
110
|
+
const path = raw.match(/^FragmentPath=(.*)$/m)?.[1], load = raw.match(/^LoadState=(.*)$/m)?.[1];
|
|
111
|
+
if (path === '' && load === 'not-found')
|
|
112
|
+
return 'absent';
|
|
113
|
+
if (path !== def.path)
|
|
114
|
+
throw Error(path ? 'FOREIGN_SERVICE_REGISTRATION' : 'SERVICE_MANAGER_INVALID_RESPONSE');
|
|
115
|
+
}
|
|
116
|
+
else if (def.platform === 'win32') {
|
|
117
|
+
let raw;
|
|
118
|
+
try {
|
|
119
|
+
raw = await command('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', windowsQuery], true);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (error instanceof CommandFailure && error.status === 3)
|
|
123
|
+
return 'absent';
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
const expected = content ?? def.content;
|
|
127
|
+
if (!raw.includes(marker(def)) || !xmlValue(raw, 'Command') || xmlValue(raw, 'Command') !== xmlValue(expected, 'Command') || xmlValue(raw, 'Arguments') !== xmlValue(expected, 'Arguments'))
|
|
128
|
+
throw Error('FOREIGN_SERVICE_REGISTRATION');
|
|
129
|
+
}
|
|
130
|
+
else
|
|
131
|
+
throw Error('UNSUPPORTED_SERVICE_PLATFORM');
|
|
132
|
+
return 'registered';
|
|
133
|
+
}
|
|
134
|
+
export async function serviceStatus(def) {
|
|
135
|
+
const file = await ownedFile(def);
|
|
136
|
+
try {
|
|
137
|
+
return { owned: !!file, registration: await registration(def, file?.content) };
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (error instanceof Error && (error.message.startsWith('FOREIGN_') || error.message === 'UNSUPPORTED_SERVICE_PLATFORM'))
|
|
141
|
+
throw error;
|
|
142
|
+
return { owned: !!file, registration: 'unknown', error: missing(error) ? 'SERVICE_MANAGER_UNAVAILABLE' : 'SERVICE_MANAGER_FAILED' };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function requireKnown(status) {
|
|
146
|
+
if (status.registration === 'unknown')
|
|
147
|
+
throw Error('SERVICE_MANAGER_UNKNOWN');
|
|
148
|
+
if (status.registration === 'registered' && !status.owned)
|
|
149
|
+
throw Error('FOREIGN_SERVICE_REGISTRATION');
|
|
150
|
+
}
|
|
151
|
+
async function writeDefinition(def) {
|
|
152
|
+
const original = await ownedFile(def);
|
|
153
|
+
await mkdir(dirname(def.path), { recursive: true, mode: 0o700 });
|
|
154
|
+
const temp = def.path + '.' + randomUUID() + '.tmp';
|
|
155
|
+
const handle = await open(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
156
|
+
try {
|
|
157
|
+
try {
|
|
158
|
+
await handle.writeFile(def.content, def.platform === 'win32' ? 'utf16le' : 'utf8');
|
|
159
|
+
await handle.sync();
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
await handle.close();
|
|
163
|
+
}
|
|
164
|
+
const current = await ownedFile(def);
|
|
165
|
+
if (original) {
|
|
166
|
+
if (!current || current.dev !== original.dev || current.ino !== original.ino || current.content !== original.content)
|
|
167
|
+
throw Error('SERVICE_FILE_CHANGED');
|
|
168
|
+
await rename(temp, def.path);
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
if (current)
|
|
172
|
+
throw Error('SERVICE_FILE_CHANGED');
|
|
173
|
+
// Atomic no-clobber publication for an absent destination; replacement above
|
|
174
|
+
// uses rename only after checking the existing owned file.
|
|
175
|
+
await link(temp, def.path);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
finally {
|
|
179
|
+
await rm(temp, { force: true });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
export async function installService(def) {
|
|
183
|
+
const status = await serviceStatus(def);
|
|
184
|
+
requireKnown(status);
|
|
185
|
+
await access(def.entry);
|
|
186
|
+
if (status.registration === 'registered')
|
|
187
|
+
await stopService(def);
|
|
188
|
+
await writeDefinition(def);
|
|
189
|
+
if (def.platform === 'darwin')
|
|
190
|
+
await command('launchctl', ['bootstrap', 'gui/' + process.getuid(), def.path]);
|
|
191
|
+
else if (def.platform === 'linux') {
|
|
192
|
+
await command('systemctl', ['--user', 'daemon-reload']);
|
|
193
|
+
await command('systemctl', ['--user', 'enable', '--now', 'moremote-cli.service']);
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
await command('schtasks', ['/Create', '/TN', taskName, '/XML', def.path, '/F']);
|
|
197
|
+
await command('schtasks', ['/Run', '/TN', taskName]);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
export async function stopService(def) {
|
|
201
|
+
const status = await serviceStatus(def);
|
|
202
|
+
requireKnown(status);
|
|
203
|
+
if (status.registration === 'absent')
|
|
204
|
+
return;
|
|
205
|
+
if (def.platform === 'darwin')
|
|
206
|
+
await command('launchctl', ['bootout', 'gui/' + process.getuid() + '/com.moremote.cli']);
|
|
207
|
+
else if (def.platform === 'linux')
|
|
208
|
+
await command('systemctl', ['--user', 'stop', 'moremote-cli.service']);
|
|
209
|
+
else
|
|
210
|
+
await command('schtasks', ['/End', '/TN', taskName]);
|
|
211
|
+
}
|
|
212
|
+
export async function removeService(def) {
|
|
213
|
+
const status = await serviceStatus(def);
|
|
214
|
+
requireKnown(status);
|
|
215
|
+
if (status.registration === 'registered') {
|
|
216
|
+
if (def.platform === 'linux')
|
|
217
|
+
await command('systemctl', ['--user', 'disable', '--now', 'moremote-cli.service']);
|
|
218
|
+
else if (def.platform === 'darwin')
|
|
219
|
+
await stopService(def);
|
|
220
|
+
else
|
|
221
|
+
await command('schtasks', ['/Delete', '/TN', taskName, '/F']);
|
|
222
|
+
}
|
|
223
|
+
if (!status.owned)
|
|
224
|
+
return;
|
|
225
|
+
if (!await ownedFile(def))
|
|
226
|
+
throw Error('SERVICE_FILE_CHANGED');
|
|
227
|
+
await unlink(def.path);
|
|
228
|
+
if (def.platform === 'linux')
|
|
229
|
+
await command('systemctl', ['--user', 'daemon-reload']);
|
|
230
|
+
}
|
|
231
|
+
async function directory(path) {
|
|
232
|
+
const stat = await lstat(path);
|
|
233
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || process.getuid && stat.uid !== process.getuid())
|
|
234
|
+
throw Error('FOREIGN_MANAGED_DIRECTORY');
|
|
235
|
+
}
|
|
236
|
+
async function regular(path) {
|
|
237
|
+
const stat = await lstat(path);
|
|
238
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || process.getuid && stat.uid !== process.getuid())
|
|
239
|
+
throw Error('INVALID_MANAGED_INSTALL');
|
|
240
|
+
}
|
|
241
|
+
async function verifiedEntry(prefix, version) {
|
|
242
|
+
for (const path of [prefix, join(prefix, 'node_modules'), join(prefix, 'node_modules', '@moxuli'), join(prefix, 'node_modules', '@moxuli', 'moremote')])
|
|
243
|
+
await directory(path);
|
|
244
|
+
const root = join(prefix, 'node_modules', '@moxuli', 'moremote'), manifest = join(root, 'package.json');
|
|
245
|
+
await regular(manifest);
|
|
246
|
+
const pkg = JSON.parse(await readFile(manifest, 'utf8'));
|
|
247
|
+
if (typeof pkg !== 'object' || pkg === null || !('name' in pkg) || pkg.name !== PACKAGE || !('version' in pkg) || pkg.version !== version)
|
|
248
|
+
throw Error('UPDATE_IDENTITY_MISMATCH');
|
|
249
|
+
for (const path of [join(root, 'bin'), join(root, 'dist')])
|
|
250
|
+
await directory(path);
|
|
251
|
+
const entry = join(root, 'bin', 'moremote-cli.js');
|
|
252
|
+
await regular(entry);
|
|
253
|
+
await regular(join(root, 'dist', 'cli.js'));
|
|
254
|
+
return entry;
|
|
255
|
+
}
|
|
256
|
+
export async function managedEntry(dir, version) {
|
|
257
|
+
exactVersion(version);
|
|
258
|
+
await directory(join(dir, 'managed'));
|
|
259
|
+
await directory(join(dir, 'managed', 'versions'));
|
|
260
|
+
return verifiedEntry(join(dir, 'managed', 'versions', version), version);
|
|
261
|
+
}
|
|
262
|
+
export async function updatePackage(dir, version) {
|
|
263
|
+
exactVersion(version);
|
|
264
|
+
await privateDirectory(dir);
|
|
265
|
+
await privateManagedDirectory(join(dir, 'managed'));
|
|
266
|
+
await privateManagedDirectory(join(dir, 'managed', 'versions'));
|
|
267
|
+
return updateLock(dir, () => stagePackage(dir, version));
|
|
268
|
+
}
|
|
269
|
+
// Caller holds the updater writer lock through installation and state publication.
|
|
270
|
+
export async function stagePackage(dir, version) {
|
|
271
|
+
exactVersion(version);
|
|
272
|
+
const managed = join(dir, 'managed'), versions = join(managed, 'versions'), destination = join(versions, version);
|
|
273
|
+
await privateManagedDirectory(managed);
|
|
274
|
+
await privateManagedDirectory(versions);
|
|
275
|
+
let exists = true;
|
|
276
|
+
try {
|
|
277
|
+
await lstat(destination);
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
if (missing(error))
|
|
281
|
+
exists = false;
|
|
282
|
+
else
|
|
283
|
+
throw error;
|
|
284
|
+
}
|
|
285
|
+
if (exists)
|
|
286
|
+
return managedEntry(dir, version);
|
|
287
|
+
const candidates = [process.env.npm_execpath, join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'), join(dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')].filter((p) => !!p && p.endsWith('npm-cli.js'));
|
|
288
|
+
let npmCli;
|
|
289
|
+
for (const path of candidates) {
|
|
290
|
+
try {
|
|
291
|
+
await access(path);
|
|
292
|
+
npmCli = path;
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
catch { }
|
|
296
|
+
}
|
|
297
|
+
if (!npmCli)
|
|
298
|
+
throw Error('NPM_CLI_NOT_FOUND');
|
|
299
|
+
const staging = await mkdtemp(join(versions, '.install-'));
|
|
300
|
+
try {
|
|
301
|
+
await command(process.execPath, [npmCli, 'install', '--prefix', staging, '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact', '--fetch-retries=0', '--fetch-timeout=60000', '--registry=https://registry.npmjs.org', '--@moxuli:registry=https://registry.npmjs.org', PACKAGE + '@' + version], true, 120000);
|
|
302
|
+
await verifiedEntry(staging, version);
|
|
303
|
+
await rename(staging, destination);
|
|
304
|
+
return managedEntry(dir, version);
|
|
305
|
+
}
|
|
306
|
+
finally {
|
|
307
|
+
await rm(staging, { recursive: true, force: true });
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
export function currentDefinition(entry, dir) { return serviceDefinition(process.platform, homedir(), process.execPath, entry, dir); }
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type ChildProcess } from 'node:child_process';
|
|
2
|
+
export interface ManagedRuntime {
|
|
3
|
+
child: ChildProcess;
|
|
4
|
+
exit: Promise<number>;
|
|
5
|
+
ready: () => boolean;
|
|
6
|
+
closed: () => boolean;
|
|
7
|
+
}
|
|
8
|
+
export declare function launchRuntime(entry: string, dir: string, onReady?: () => void): ManagedRuntime;
|
|
9
|
+
export declare function drainRuntime(runtime: ManagedRuntime): Promise<number>;
|
|
10
|
+
export declare function startupHealthy(runtime: ManagedRuntime, signal?: AbortSignal, grace?: number, deadline?: number, cancel?: () => boolean): Promise<boolean>;
|
|
11
|
+
export declare function runSupervisor(dir: string, timing?: {
|
|
12
|
+
pollMs?: number;
|
|
13
|
+
startupGraceMs?: number;
|
|
14
|
+
startupDeadlineMs?: number;
|
|
15
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
|
+
import { managedEntry } from './service.js';
|
|
4
|
+
import { checkForUpdate, compatibleEntry } from './updater.js';
|
|
5
|
+
import { readUpdateState, writeUpdateState, updateLock, supervisorStopRequested } from './update-state.js';
|
|
6
|
+
export function launchRuntime(entry, dir, onReady = () => { }) {
|
|
7
|
+
const child = spawn(process.execPath, [entry, 'run', '--data-dir', dir], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'], windowsHide: true, env: { ...process.env, MOREMOTE_MANAGED_CHILD: '1' } });
|
|
8
|
+
let ready = false, closed = false;
|
|
9
|
+
const exit = Promise.withResolvers();
|
|
10
|
+
child.on('message', message => { if (!ready && message && typeof message === 'object' && 'kind' in message && message.kind === 'moremote-ready') {
|
|
11
|
+
ready = true;
|
|
12
|
+
onReady();
|
|
13
|
+
} });
|
|
14
|
+
child.once('error', () => { closed = true; exit.resolve(1); });
|
|
15
|
+
child.once('exit', code => { closed = true; exit.resolve(code ?? 1); });
|
|
16
|
+
return { child, exit: exit.promise, ready: () => ready, closed: () => closed };
|
|
17
|
+
}
|
|
18
|
+
export async function drainRuntime(runtime) {
|
|
19
|
+
if (!runtime.closed() && runtime.child.connected)
|
|
20
|
+
runtime.child.send({ kind: 'moremote-drain' }, () => { });
|
|
21
|
+
// Never signal/kill during an uncertain write. Completion releases journal + ownership.
|
|
22
|
+
return runtime.exit;
|
|
23
|
+
}
|
|
24
|
+
export async function startupHealthy(runtime, signal, grace = 10000, deadline = 30000, cancel = () => false) {
|
|
25
|
+
const start = Date.now();
|
|
26
|
+
while (!runtime.closed() && !signal?.aborted && !cancel()) {
|
|
27
|
+
if (runtime.ready() && Date.now() - start >= grace)
|
|
28
|
+
return true;
|
|
29
|
+
if (Date.now() - start >= deadline)
|
|
30
|
+
return false;
|
|
31
|
+
await sleep(100, undefined, { signal }).catch(() => { });
|
|
32
|
+
}
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
export async function runSupervisor(dir, timing = {}) {
|
|
36
|
+
return updateLock(dir, async () => {
|
|
37
|
+
let state = readUpdateState(dir);
|
|
38
|
+
if (!state)
|
|
39
|
+
throw Error('MANAGED_INSTALL_REQUIRED');
|
|
40
|
+
supervisorStopRequested(dir, true);
|
|
41
|
+
// Crash before commit must never turn a candidate into a last-known-good version.
|
|
42
|
+
if (state.activating)
|
|
43
|
+
await updateLock(dir, async () => { state = readUpdateState(dir); state.failed = state.activating; state.error = 'UPDATE_INTERRUPTED'; delete state.activating; delete state.pending; delete state.pendingManual; writeUpdateState(dir, state); });
|
|
44
|
+
const publishReady = (version) => { if (process.send && process.connected)
|
|
45
|
+
process.send({ kind: 'moremote-ready', version }, undefined, undefined, () => { }); };
|
|
46
|
+
const initialVersion = state.active;
|
|
47
|
+
let runtime = launchRuntime(await managedEntry(dir, initialVersion), dir, () => publishReady(initialVersion)), stopping = false;
|
|
48
|
+
const controller = new AbortController();
|
|
49
|
+
const stop = () => { stopping = true; controller.abort(); void drainRuntime(runtime); };
|
|
50
|
+
const resumeActive = async (version) => { const entry = await managedEntry(dir, version); if (supervisorStopRequested(dir))
|
|
51
|
+
stop(); if (!stopping)
|
|
52
|
+
runtime = launchRuntime(entry, dir, () => publishReady(version)); };
|
|
53
|
+
const parentMessage = (message) => { if (message && typeof message === 'object' && 'kind' in message && message.kind === 'moremote-parent-stop')
|
|
54
|
+
stop(); };
|
|
55
|
+
if (process.send) {
|
|
56
|
+
process.once('disconnect', stop);
|
|
57
|
+
process.on('message', parentMessage);
|
|
58
|
+
if (!process.connected)
|
|
59
|
+
stop();
|
|
60
|
+
}
|
|
61
|
+
process.once('SIGINT', stop);
|
|
62
|
+
process.once('SIGTERM', stop);
|
|
63
|
+
try {
|
|
64
|
+
while (!stopping && !runtime.closed()) {
|
|
65
|
+
// Discovery/install happens alongside the old runtime, never in its polling loop.
|
|
66
|
+
try {
|
|
67
|
+
await checkForUpdate(dir);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
if (!(error instanceof Error && error.message === 'UPDATE_BUSY'))
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
if (supervisorStopRequested(dir))
|
|
74
|
+
stop();
|
|
75
|
+
if (stopping || runtime.closed())
|
|
76
|
+
break;
|
|
77
|
+
state = readUpdateState(dir);
|
|
78
|
+
if (state.pending && state.enabled && !state.manualRequired) {
|
|
79
|
+
try {
|
|
80
|
+
await updateLock(dir, async () => {
|
|
81
|
+
state = readUpdateState(dir);
|
|
82
|
+
if (!state.pending || !state.enabled || state.manualRequired)
|
|
83
|
+
return;
|
|
84
|
+
const candidate = state.pending;
|
|
85
|
+
const entry = await managedEntry(dir, candidate);
|
|
86
|
+
if (!await compatibleEntry(entry)) {
|
|
87
|
+
state.manualRequired = candidate;
|
|
88
|
+
state.error = 'UPDATE_MANUAL_COMPATIBILITY_REQUIRED';
|
|
89
|
+
writeUpdateState(dir, state);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
state.activating = candidate;
|
|
93
|
+
writeUpdateState(dir, state);
|
|
94
|
+
await drainRuntime(runtime);
|
|
95
|
+
if (supervisorStopRequested(dir))
|
|
96
|
+
stop();
|
|
97
|
+
if (stopping) {
|
|
98
|
+
delete state.activating;
|
|
99
|
+
writeUpdateState(dir, state);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
state = readUpdateState(dir);
|
|
103
|
+
if (!state.enabled) {
|
|
104
|
+
delete state.activating;
|
|
105
|
+
writeUpdateState(dir, state);
|
|
106
|
+
await resumeActive(state.active);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
runtime = launchRuntime(entry, dir, () => publishReady(candidate));
|
|
110
|
+
const healthy = await startupHealthy(runtime, controller.signal, timing.startupGraceMs, timing.startupDeadlineMs, () => !readUpdateState(dir).enabled);
|
|
111
|
+
if (supervisorStopRequested(dir))
|
|
112
|
+
stop();
|
|
113
|
+
if (stopping) {
|
|
114
|
+
await drainRuntime(runtime);
|
|
115
|
+
state = readUpdateState(dir);
|
|
116
|
+
delete state.activating;
|
|
117
|
+
writeUpdateState(dir, state);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
state = readUpdateState(dir);
|
|
121
|
+
if (!state.enabled) {
|
|
122
|
+
await drainRuntime(runtime);
|
|
123
|
+
delete state.activating;
|
|
124
|
+
writeUpdateState(dir, state);
|
|
125
|
+
await resumeActive(state.active);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
state = readUpdateState(dir);
|
|
129
|
+
if (healthy) {
|
|
130
|
+
state.previous = state.active;
|
|
131
|
+
state.active = candidate;
|
|
132
|
+
delete state.error;
|
|
133
|
+
delete state.failed;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
state.failed = candidate;
|
|
137
|
+
state.error = 'UPDATE_START_FAILED';
|
|
138
|
+
await drainRuntime(runtime);
|
|
139
|
+
await resumeActive(state.active);
|
|
140
|
+
}
|
|
141
|
+
delete state.activating;
|
|
142
|
+
delete state.pending;
|
|
143
|
+
delete state.pendingManual;
|
|
144
|
+
writeUpdateState(dir, state);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (!(error instanceof Error && error.message === 'UPDATE_BUSY'))
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (supervisorStopRequested(dir))
|
|
153
|
+
stop();
|
|
154
|
+
if (stopping || runtime.closed())
|
|
155
|
+
break;
|
|
156
|
+
const wake = new AbortController();
|
|
157
|
+
try {
|
|
158
|
+
await Promise.race([sleep(timing.pollMs ?? 60000, undefined, { signal: AbortSignal.any([controller.signal, wake.signal]) }).catch(() => { }), runtime.exit]);
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
wake.abort();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return await runtime.exit;
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
process.removeListener('SIGINT', stop);
|
|
168
|
+
process.removeListener('SIGTERM', stop);
|
|
169
|
+
process.removeListener('disconnect', stop);
|
|
170
|
+
process.removeListener('message', parentMessage);
|
|
171
|
+
if (!runtime.closed())
|
|
172
|
+
await drainRuntime(runtime);
|
|
173
|
+
}
|
|
174
|
+
}, 'supervisor');
|
|
175
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export declare const PACKAGE = "@moxuli/moremote";
|
|
2
|
+
export declare const CHECK_INTERVAL: number;
|
|
3
|
+
declare const OWNER = "MoRemote CLI updater v1";
|
|
4
|
+
export interface UpdateState {
|
|
5
|
+
owner: typeof OWNER;
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
active: string;
|
|
8
|
+
bootstrap: string;
|
|
9
|
+
previous?: string;
|
|
10
|
+
pending?: string;
|
|
11
|
+
pendingManual?: boolean;
|
|
12
|
+
activating?: string;
|
|
13
|
+
failed?: string;
|
|
14
|
+
manualRequired?: string;
|
|
15
|
+
lastCheck?: number;
|
|
16
|
+
nextCheck?: number;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function exactVersion(value: string): string;
|
|
20
|
+
export declare function managedRoot(dir: string): string;
|
|
21
|
+
export declare function readUpdateState(dir: string): UpdateState | undefined;
|
|
22
|
+
export declare function initialUpdateState(version: string): UpdateState;
|
|
23
|
+
export declare function writeUpdateState(dir: string, state: UpdateState): void;
|
|
24
|
+
export declare function updateLock<T>(dir: string, work: () => Promise<T>, name?: string): Promise<T>;
|
|
25
|
+
export declare function supervisorRunning(dir: string): boolean;
|
|
26
|
+
export declare function supervisorStopRequested(dir: string, clear?: boolean): boolean;
|
|
27
|
+
export declare function requestSupervisorStop(dir: string): void;
|
|
28
|
+
export declare function autoUpdateDisabled(dir: string, clear?: boolean): boolean;
|
|
29
|
+
export declare function disableAutoUpdate(dir: string): void;
|
|
30
|
+
export {};
|