@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/cli.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { resolve, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { rm } from 'node:fs/promises';
|
|
5
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
6
|
+
import QRCode from 'qrcode';
|
|
7
|
+
import { dataDirectory, loadConfig, saveConfig, validateOrigin, assertOwnedDirectory, pruneRetiredPairs } from './config.js';
|
|
8
|
+
import { OfficialClient } from './official-client.js';
|
|
9
|
+
import { CloudClient } from './cloud-client.js';
|
|
10
|
+
import { makeOffer, tokenHash, activatePending } from './pairing.js';
|
|
11
|
+
import { runRuntime } from './runtime.js';
|
|
12
|
+
import { requestControl } from './control.js';
|
|
13
|
+
import { currentDefinition, installService, removeService, stopService, serviceStatus } from './service.js';
|
|
14
|
+
import { ensureManaged, packageManaged, packageVersion, queueUpdate, setAutoUpdate, readUpdateState, serviceEntry } from './updater.js';
|
|
15
|
+
import { runSupervisor } from './supervisor.js';
|
|
16
|
+
import { requestSupervisorStop, supervisorRunning } from './update-state.js';
|
|
17
|
+
import { OperationJournal } from './journal.js';
|
|
18
|
+
const VERSION = await packageVersion();
|
|
19
|
+
const HELP = `MoRemote CLI ${VERSION} — optional Paseo 0.15.3 enhancement
|
|
20
|
+
Usage: moremote-cli <command> [options]
|
|
21
|
+
configure --target <official-target> --api-origin <https-origin> [--cloud-on]
|
|
22
|
+
[--paseo-home <directory>] [--allow-loopback-http]
|
|
23
|
+
check [--connect] Redacted local checks; --connect is read-only
|
|
24
|
+
pair [--json] Display one secret phone QR/link; wait for activation
|
|
25
|
+
run Foreground observer and scoped command consumer
|
|
26
|
+
status Redacted runtime/config/owned-service/update state
|
|
27
|
+
service-install --yes Explicit per-user managed CLI login registration
|
|
28
|
+
auto-update --enable | --disable Persistent managed-update policy
|
|
29
|
+
unpair --pair-id <id> Disable exact phone locally and relay-revoke it
|
|
30
|
+
cloud-disable Stop cloud/local execution; attempt relay revocation
|
|
31
|
+
stop Stop only CLI runtime and owned service
|
|
32
|
+
update --version X.Y.Z --yes Queue exact verified scoped npm version
|
|
33
|
+
uninstall [--purge] --yes Remove own registration/install; purge deletes own keys/journal
|
|
34
|
+
--data-dir <directory> Override CLI-only state
|
|
35
|
+
--help | --version
|
|
36
|
+
No command starts/stops/updates Paseo. Foreground run needs no installed service.
|
|
37
|
+
`;
|
|
38
|
+
const versionOnly = process.argv.length === 3 && process.argv[2] === '--version';
|
|
39
|
+
const supportedNode = Number(process.versions.node.split('.')[0]) === 24 && Number(process.versions.node.split('.')[1]) >= 13;
|
|
40
|
+
const parsed = (() => { try {
|
|
41
|
+
return parseArgs({ args: versionOnly ? [] : process.argv.slice(2), allowPositionals: true, options: { help: { type: 'boolean' }, version: { type: 'string' }, 'data-dir': { type: 'string' }, target: { type: 'string' }, 'paseo-home': { type: 'string' }, 'api-origin': { type: 'string' }, 'cloud-on': { type: 'boolean' }, 'allow-loopback-http': { type: 'boolean' }, connect: { type: 'boolean' }, json: { type: 'boolean' }, yes: { type: 'boolean' }, purge: { type: 'boolean' }, enable: { type: 'boolean' }, disable: { type: 'boolean' }, 'pair-id': { type: 'string' } } });
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
console.error('INVALID_ARGUMENTS');
|
|
45
|
+
process.exit(1);
|
|
46
|
+
} })();
|
|
47
|
+
const args = parsed.values;
|
|
48
|
+
const action = parsed.positionals[0];
|
|
49
|
+
async function stopped(dir) { if (await requestControl(dir, 'status'))
|
|
50
|
+
throw Error('STOP_CLI_BEFORE_CONFIGURATION'); }
|
|
51
|
+
async function stopRuntime(dir) { if (!await requestControl(dir, 'stop'))
|
|
52
|
+
return; for (let i = 0; i < 300; i++) {
|
|
53
|
+
await sleep(200);
|
|
54
|
+
if (!await requestControl(dir, 'status'))
|
|
55
|
+
return;
|
|
56
|
+
} throw Error('STOP_TIMEOUT'); }
|
|
57
|
+
async function stopManaged(dir) { requestSupervisorStop(dir); await stopRuntime(dir); if (readUpdateState(dir))
|
|
58
|
+
for (let i = 0; i < 900; i++) {
|
|
59
|
+
if (!supervisorRunning(dir))
|
|
60
|
+
return;
|
|
61
|
+
await sleep(200);
|
|
62
|
+
} if (readUpdateState(dir) && supervisorRunning(dir))
|
|
63
|
+
throw Error('SUPERVISOR_STOP_TIMEOUT'); }
|
|
64
|
+
async function stopOwned(dir, definition) { await stopService(definition); await stopManaged(dir); }
|
|
65
|
+
async function main() {
|
|
66
|
+
if (args.help || !action) {
|
|
67
|
+
console.log(HELP);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (action === 'version') {
|
|
71
|
+
console.log(VERSION);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (action !== 'check' && !supportedNode)
|
|
75
|
+
throw Error('NODE_24_13_REQUIRED');
|
|
76
|
+
const dir = resolve(args['data-dir'] || dataDirectory());
|
|
77
|
+
const config = await loadConfig(dir);
|
|
78
|
+
const definition = currentDefinition(fileURLToPath(new URL('../bin/moremote-cli.js', import.meta.url)), dir);
|
|
79
|
+
const selected = readUpdateState(dir);
|
|
80
|
+
if (action === 'check') {
|
|
81
|
+
const checks = [{ name: 'node24.13+', ok: supportedNode }, { name: 'configuration', ok: !!config.target || !!config.paseoHome }, { name: 'cloud-opt-in', ok: !config.cloudEnabled || !!config.apiOrigin }];
|
|
82
|
+
if (args.connect) {
|
|
83
|
+
let official;
|
|
84
|
+
try {
|
|
85
|
+
official = new OfficialClient(config);
|
|
86
|
+
await official.connect();
|
|
87
|
+
checks.push({ name: 'official-read-only-connection', ok: true });
|
|
88
|
+
checks.push({ name: 'explicit-event-subscriptions', ok: official.info()?.features?.explicitEventSubscriptions === true });
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
checks.push({ name: 'official-read-only-connection', ok: false, code: 'OFFICIAL_CONNECTION_FAILED' });
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await official?.close();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
console.log(JSON.stringify({ ok: checks.every(c => c.ok), checks }, null, 2));
|
|
98
|
+
if (checks.some(c => !c.ok))
|
|
99
|
+
process.exitCode = 1;
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (action === 'status') {
|
|
103
|
+
const installed = selected ? false : await packageManaged();
|
|
104
|
+
console.log(JSON.stringify({ version: VERSION, configured: !!config.target, cloudEnabled: config.cloudEnabled, apiOrigin: config.apiOrigin || null, pairings: config.pairs.map(p => ({ pairId: p.pairId, apiOrigin: p.apiOrigin || config.apiOrigin || null, active: p.active, revokedAt: p.revokedAt || null, expiresAt: p.expiresAt || null })), runtime: await requestControl(dir, 'status'), service: await serviceStatus(definition), updates: selected ?? { enabled: installed, reason: installed ? 'MANAGED_BOOTSTRAP_REQUIRED' : 'SOURCE_CHECKOUT_MANUAL' } }, null, 2));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (action === 'run') {
|
|
108
|
+
await saveConfig(dir, config);
|
|
109
|
+
if (process.env.MOREMOTE_MANAGED_CHILD) {
|
|
110
|
+
try {
|
|
111
|
+
await runRuntime(dir, VERSION);
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
if (process.connected)
|
|
115
|
+
process.disconnect();
|
|
116
|
+
}
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (selected || await packageManaged()) {
|
|
120
|
+
await ensureManaged(dir);
|
|
121
|
+
try {
|
|
122
|
+
process.exitCode = await runSupervisor(dir);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
if (process.connected)
|
|
126
|
+
process.disconnect();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
else
|
|
130
|
+
await runRuntime(dir, VERSION);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (action === 'stop') {
|
|
134
|
+
await stopOwned(dir, definition);
|
|
135
|
+
console.log('MoRemote CLI stopped; official Paseo unchanged.');
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (action === 'configure') {
|
|
139
|
+
await stopped(dir);
|
|
140
|
+
pruneRetiredPairs(config);
|
|
141
|
+
if (config.pairs.some(p => p.revokedAt === undefined) && ((args.target && args.target !== config.target) || (args['api-origin'] && args['api-origin'] !== config.apiOrigin) || (args['paseo-home'] && resolve(args['paseo-home']) !== config.paseoHome)))
|
|
142
|
+
throw Error('DISABLE_OR_UNPAIR_BEFORE_RETARGETING');
|
|
143
|
+
for (const pair of config.pairs)
|
|
144
|
+
if (!pair.apiOrigin && config.apiOrigin)
|
|
145
|
+
pair.apiOrigin = config.apiOrigin;
|
|
146
|
+
if (args.target && args.target !== config.target) {
|
|
147
|
+
config.target = args.target;
|
|
148
|
+
delete config.daemonServerId;
|
|
149
|
+
}
|
|
150
|
+
if (args['paseo-home'] && resolve(args['paseo-home']) !== config.paseoHome) {
|
|
151
|
+
config.paseoHome = resolve(args['paseo-home']);
|
|
152
|
+
delete config.daemonServerId;
|
|
153
|
+
}
|
|
154
|
+
if (args['allow-loopback-http'])
|
|
155
|
+
config.allowLoopbackHttp = true;
|
|
156
|
+
if (args['api-origin'])
|
|
157
|
+
config.apiOrigin = validateOrigin(args['api-origin'], config.allowLoopbackHttp);
|
|
158
|
+
if (args['cloud-on']) {
|
|
159
|
+
if (!config.apiOrigin)
|
|
160
|
+
throw Error('API_ORIGIN_REQUIRED');
|
|
161
|
+
config.cloudEnabled = true;
|
|
162
|
+
}
|
|
163
|
+
await saveConfig(dir, config);
|
|
164
|
+
console.log('Configuration saved. Foreground: moremote-cli run. No service installed.');
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (action === 'pair') {
|
|
168
|
+
await stopped(dir);
|
|
169
|
+
if (!config.apiOrigin || !config.cloudEnabled)
|
|
170
|
+
throw Error('CONFIGURE_AND_OPT_IN_CLOUD_FIRST');
|
|
171
|
+
if (config.pairs.length >= 16)
|
|
172
|
+
throw Error('PAIRING_LIMIT');
|
|
173
|
+
const official = new OfficialClient(config);
|
|
174
|
+
try {
|
|
175
|
+
await official.connect();
|
|
176
|
+
const info = official.info();
|
|
177
|
+
config.daemonServerId = info.serverId;
|
|
178
|
+
const { pair, offer } = makeOffer(config.apiOrigin);
|
|
179
|
+
pair.daemonServerId = info.serverId;
|
|
180
|
+
config.pairs.push(pair);
|
|
181
|
+
await saveConfig(dir, config);
|
|
182
|
+
const cloud = new CloudClient(config.apiOrigin, pair.pairId, pair.hostToken, config.allowLoopbackHttp);
|
|
183
|
+
await cloud.create({ pairId: pair.pairId, hostTokenHash: tokenHash(pair.hostToken), enrollmentTokenHash: tokenHash(pair.enrollmentToken), expiresAt: pair.expiresAt });
|
|
184
|
+
const offerJSON = JSON.stringify(offer);
|
|
185
|
+
if (args.json)
|
|
186
|
+
console.log(offerJSON);
|
|
187
|
+
else {
|
|
188
|
+
const link = 'moremote://enhance#' + Buffer.from(offerJSON).toString('base64url');
|
|
189
|
+
console.log('Secret one-phone offer; scan privately. Expires in ten minutes.');
|
|
190
|
+
console.log(await QRCode.toString(link, { type: 'terminal', small: true }));
|
|
191
|
+
console.log(link);
|
|
192
|
+
}
|
|
193
|
+
while (Date.now() < pair.expiresAt) {
|
|
194
|
+
if (await activatePending(config, dir, pair, cloud, info.serverId, info.hostname ?? undefined)) {
|
|
195
|
+
console.error('Pairing activated. Run the CLI to deliver encrypted state/actions.');
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
await sleep(3000);
|
|
199
|
+
}
|
|
200
|
+
throw Error('PAIRING_EXPIRED');
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
await official.close();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (action === 'cloud-disable') {
|
|
207
|
+
await stopOwned(dir, definition);
|
|
208
|
+
Object.assign(config, await loadConfig(dir));
|
|
209
|
+
config.cloudEnabled = false;
|
|
210
|
+
await saveConfig(dir, config);
|
|
211
|
+
const journal = new OperationJournal(join(dir, 'journal.sqlite'));
|
|
212
|
+
const failures = [];
|
|
213
|
+
try {
|
|
214
|
+
for (const pair of config.pairs) {
|
|
215
|
+
journal.revokePair(pair.pairId);
|
|
216
|
+
pair.active = false;
|
|
217
|
+
pair.revokedAt ??= Date.now();
|
|
218
|
+
}
|
|
219
|
+
await saveConfig(dir, config);
|
|
220
|
+
for (const pair of config.pairs) {
|
|
221
|
+
try {
|
|
222
|
+
const origin = pair.apiOrigin || config.apiOrigin;
|
|
223
|
+
if (!origin)
|
|
224
|
+
throw Error('MISSING_ORIGIN');
|
|
225
|
+
await new CloudClient(origin, pair.pairId, pair.hostToken, config.allowLoopbackHttp).revoke();
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
failures.push(pair.pairId);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
journal.close();
|
|
234
|
+
}
|
|
235
|
+
console.log(JSON.stringify({ cloudEnabled: false, endpointExecution: 'disabled-locally', relayRevocationPending: failures, officialData: 'unchanged' }));
|
|
236
|
+
if (failures.length)
|
|
237
|
+
process.exitCode = 1;
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (action === 'unpair') {
|
|
241
|
+
await stopped(dir);
|
|
242
|
+
const pair = config.pairs.find(p => p.pairId === args['pair-id']);
|
|
243
|
+
const origin = pair?.apiOrigin || config.apiOrigin;
|
|
244
|
+
if (!pair || !origin)
|
|
245
|
+
throw Error('EXACT_PAIR_REQUIRED');
|
|
246
|
+
const journal = new OperationJournal(join(dir, 'journal.sqlite'));
|
|
247
|
+
try {
|
|
248
|
+
journal.revokePair(pair.pairId);
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
journal.close();
|
|
252
|
+
}
|
|
253
|
+
pair.active = false;
|
|
254
|
+
pair.revokedAt ??= Date.now();
|
|
255
|
+
await saveConfig(dir, config);
|
|
256
|
+
await new CloudClient(origin, pair.pairId, pair.hostToken, config.allowLoopbackHttp).revoke();
|
|
257
|
+
console.log('Exact phone pairing disabled locally and relay-revoked; other pairings and official data unchanged. Protected keys retained for final control receipts.');
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (action === 'service-install') {
|
|
261
|
+
if (!args.yes)
|
|
262
|
+
throw Error('EXPLICIT_YES_REQUIRED');
|
|
263
|
+
await stopped(dir);
|
|
264
|
+
await saveConfig(dir, config);
|
|
265
|
+
await installService(currentDefinition(await serviceEntry(dir), dir));
|
|
266
|
+
console.log('MoRemote CLI per-user managed login registration installed; automatic updates enabled unless opted out. Official service unchanged.');
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (action === 'auto-update') {
|
|
270
|
+
if (!!args.enable === !!args.disable)
|
|
271
|
+
throw Error('SELECT_ENABLE_OR_DISABLE');
|
|
272
|
+
console.log(JSON.stringify(await setAutoUpdate(dir, !!args.enable)));
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (action === 'update') {
|
|
276
|
+
if (!args.yes || !args.version)
|
|
277
|
+
throw Error('EXACT_VERSION_AND_YES_REQUIRED');
|
|
278
|
+
const state = await queueUpdate(dir, args.version);
|
|
279
|
+
console.log(JSON.stringify({ installedVersion: args.version, activeVersion: state.active, activation: state.pending ? 'queued-for-supervisor-safe-boundary' : 'already-active', next: state.pending ? 'A running managed supervisor activates automatically; otherwise start run or service-install --yes.' : null }));
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (action === 'uninstall') {
|
|
283
|
+
if (!args.yes)
|
|
284
|
+
throw Error('EXPLICIT_YES_REQUIRED');
|
|
285
|
+
try {
|
|
286
|
+
await assertOwnedDirectory(dir);
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
if (error.code !== 'ENOENT')
|
|
290
|
+
throw error;
|
|
291
|
+
}
|
|
292
|
+
await removeService(definition);
|
|
293
|
+
await stopManaged(dir);
|
|
294
|
+
if (!args.purge)
|
|
295
|
+
await saveConfig(dir, config);
|
|
296
|
+
await rm(join(dir, 'managed'), { recursive: true, force: true });
|
|
297
|
+
if (args.purge)
|
|
298
|
+
await rm(dir, { recursive: true, force: true });
|
|
299
|
+
console.log(args.purge ? 'MoRemote CLI-owned registration, managed install and local keys/journal removed. Official data unchanged.' : 'MoRemote CLI registration and managed install removed; local pairing keys/journal retained. Source checkout/global package removal remains with its package manager.');
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
throw Error('UNKNOWN_COMMAND');
|
|
303
|
+
}
|
|
304
|
+
if (process.argv.includes('--version') && !action) {
|
|
305
|
+
console.log(VERSION);
|
|
306
|
+
}
|
|
307
|
+
else
|
|
308
|
+
main().catch(error => { const code = error instanceof Error && /^[A-Z0-9_]+$/.test(error.message) ? error.message : 'CLI_COMMAND_FAILED'; console.error(code); process.exitCode = 1; });
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Envelope } from './crypto.js';
|
|
2
|
+
import type { ReceiptState } from './journal.js';
|
|
3
|
+
export declare class CloudError extends Error {
|
|
4
|
+
readonly status: number;
|
|
5
|
+
readonly retryAt?: number | undefined;
|
|
6
|
+
readonly code: string;
|
|
7
|
+
constructor(code: string, status: number, retryAt?: number | undefined);
|
|
8
|
+
}
|
|
9
|
+
export interface CloudRetryState {
|
|
10
|
+
error?: CloudError;
|
|
11
|
+
}
|
|
12
|
+
export declare class CloudClient {
|
|
13
|
+
readonly pairId: string;
|
|
14
|
+
private token;
|
|
15
|
+
private fetcher;
|
|
16
|
+
private signal?;
|
|
17
|
+
private retryState;
|
|
18
|
+
private cycleFence?;
|
|
19
|
+
readonly origin: string;
|
|
20
|
+
constructor(origin: string, pairId: string, token: string, allowLoopback?: boolean, fetcher?: typeof fetch, signal?: AbortSignal | undefined, retryState?: CloudRetryState, cycleFence?: CloudRetryState | undefined);
|
|
21
|
+
request(method: string, path: string, body?: unknown): Promise<Record<string, unknown>>;
|
|
22
|
+
private path;
|
|
23
|
+
create(body: unknown): Promise<Record<string, unknown>>;
|
|
24
|
+
pair(): Promise<Record<string, unknown>>;
|
|
25
|
+
activate(body: unknown): Promise<Record<string, unknown>>;
|
|
26
|
+
revoke(): Promise<Record<string, unknown>>;
|
|
27
|
+
commands(): Promise<Envelope[]>;
|
|
28
|
+
dispatch(id: string): Promise<{
|
|
29
|
+
dispatchAllowed: boolean;
|
|
30
|
+
}>;
|
|
31
|
+
receipt(id: string, body: {
|
|
32
|
+
state: ReceiptState;
|
|
33
|
+
revision: number;
|
|
34
|
+
envelope: Envelope;
|
|
35
|
+
}): Promise<Record<string, unknown>>;
|
|
36
|
+
state(envelope: Envelope): Promise<Record<string, unknown>>;
|
|
37
|
+
attention(body: unknown): Promise<Record<string, unknown>>;
|
|
38
|
+
controls(): Promise<Envelope[]>;
|
|
39
|
+
controlReceipt(id: string, body: {
|
|
40
|
+
envelope: Envelope;
|
|
41
|
+
}): Promise<Record<string, unknown>>;
|
|
42
|
+
resolveAttention(id: string, resolvedAt: number): Promise<Record<string, unknown>>;
|
|
43
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { validateOrigin } from './config.js';
|
|
2
|
+
import { LIMITS, object } from './limits.js';
|
|
3
|
+
export class CloudError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
retryAt;
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, status, retryAt) {
|
|
8
|
+
const safe = /^[A-Z0-9_]{1,64}$/.test(code) ? code : 'CLOUD_HTTP_ERROR';
|
|
9
|
+
super(safe);
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.retryAt = retryAt;
|
|
12
|
+
this.code = safe;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function retryDeadline(value, status, now) {
|
|
16
|
+
if (value === null || ![429, 503].includes(status))
|
|
17
|
+
return;
|
|
18
|
+
const maxDelay = 86400000;
|
|
19
|
+
if (/^\d+$/.test(value)) {
|
|
20
|
+
const seconds = Number(value);
|
|
21
|
+
if (!Number.isFinite(seconds))
|
|
22
|
+
return;
|
|
23
|
+
return now + Math.min(seconds, maxDelay / 1000) * 1000;
|
|
24
|
+
}
|
|
25
|
+
// Date.parse alone also accepts numeric/ISO dates and normalizes impossible
|
|
26
|
+
// calendar dates. Accept only a valid canonical HTTP-date, never a new TTL.
|
|
27
|
+
if (!/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value))
|
|
28
|
+
return;
|
|
29
|
+
const date = Date.parse(value);
|
|
30
|
+
if (!Number.isFinite(date) || new Date(date).toUTCString() !== value || date <= now)
|
|
31
|
+
return;
|
|
32
|
+
return Math.min(date, now + maxDelay);
|
|
33
|
+
}
|
|
34
|
+
export class CloudClient {
|
|
35
|
+
pairId;
|
|
36
|
+
token;
|
|
37
|
+
fetcher;
|
|
38
|
+
signal;
|
|
39
|
+
retryState;
|
|
40
|
+
cycleFence;
|
|
41
|
+
origin;
|
|
42
|
+
constructor(origin, pairId, token, allowLoopback = false, fetcher = fetch, signal, retryState = {}, cycleFence) {
|
|
43
|
+
this.pairId = pairId;
|
|
44
|
+
this.token = token;
|
|
45
|
+
this.fetcher = fetcher;
|
|
46
|
+
this.signal = signal;
|
|
47
|
+
this.retryState = retryState;
|
|
48
|
+
this.cycleFence = cycleFence;
|
|
49
|
+
this.origin = validateOrigin(origin, allowLoopback);
|
|
50
|
+
}
|
|
51
|
+
async request(method, path, body) {
|
|
52
|
+
// A runtime cycle that observed a pause must reacquire controls in a new
|
|
53
|
+
// cycle, even if an intervening SDK call outlasted the wall-clock deadline.
|
|
54
|
+
if (this.cycleFence?.error)
|
|
55
|
+
throw this.cycleFence.error;
|
|
56
|
+
const paused = this.retryState.error;
|
|
57
|
+
if (paused?.retryAt !== undefined && paused.retryAt > Date.now()) {
|
|
58
|
+
if (this.cycleFence)
|
|
59
|
+
this.cycleFence.error = paused;
|
|
60
|
+
throw paused;
|
|
61
|
+
}
|
|
62
|
+
this.retryState.error = undefined;
|
|
63
|
+
const json = body === undefined ? undefined : JSON.stringify(body);
|
|
64
|
+
if (json && Buffer.byteLength(json) > LIMITS.envelopeBytes)
|
|
65
|
+
throw Error('REQUEST_LIMIT');
|
|
66
|
+
const response = await this.fetcher(this.origin + '/v1' + path, { method, headers: { authorization: 'Bearer ' + this.token, ...(json ? { 'content-type': 'application/json' } : {}) }, body: json, signal: AbortSignal.any([AbortSignal.timeout(20000), ...(this.signal ? [this.signal] : [])]), redirect: 'error' });
|
|
67
|
+
const retryAt = retryDeadline(response.headers.get('Retry-After'), response.status, Date.now());
|
|
68
|
+
if (retryAt !== undefined) {
|
|
69
|
+
const failure = new CloudError('CLOUD_HTTP_ERROR', response.status, retryAt);
|
|
70
|
+
this.retryState.error = failure;
|
|
71
|
+
if (this.cycleFence)
|
|
72
|
+
this.cycleFence.error = failure;
|
|
73
|
+
}
|
|
74
|
+
const reader = response.body?.getReader();
|
|
75
|
+
let size = 0;
|
|
76
|
+
const chunks = [];
|
|
77
|
+
if (reader) {
|
|
78
|
+
try {
|
|
79
|
+
while (true) {
|
|
80
|
+
const r = await reader.read();
|
|
81
|
+
if (r.done)
|
|
82
|
+
break;
|
|
83
|
+
size += r.value.byteLength;
|
|
84
|
+
if (size > LIMITS.responseBytes)
|
|
85
|
+
throw Error('RESPONSE_LIMIT');
|
|
86
|
+
chunks.push(r.value);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
await reader.cancel();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
let result;
|
|
94
|
+
try {
|
|
95
|
+
result = object(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw Error('INVALID_CLOUD_RESPONSE');
|
|
99
|
+
}
|
|
100
|
+
if (!response.ok || result.ok !== true) {
|
|
101
|
+
const error = result.error && typeof result.error === 'object' ? result.error : {};
|
|
102
|
+
const failure = new CloudError(typeof error.code === 'string' ? error.code : 'CLOUD_HTTP_ERROR', response.status, retryAt);
|
|
103
|
+
if (retryAt !== undefined) {
|
|
104
|
+
this.retryState.error = failure;
|
|
105
|
+
if (this.cycleFence)
|
|
106
|
+
this.cycleFence.error = failure;
|
|
107
|
+
}
|
|
108
|
+
throw failure;
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
path(suffix = '') { return '/pairs/' + this.pairId + suffix; }
|
|
113
|
+
create(body) { return this.request('POST', '/pairs', body); }
|
|
114
|
+
pair() { return this.request('GET', this.path()); }
|
|
115
|
+
activate(body) { return this.request('POST', this.path('/activate'), body); }
|
|
116
|
+
revoke() { return this.request('DELETE', this.path()); }
|
|
117
|
+
async commands() { const result = await this.request('GET', this.path('/commands')); if (!Array.isArray(result.commands) || result.commands.length > 100)
|
|
118
|
+
throw Error('INVALID_COMMAND_PAGE'); return result.commands.map(row => object(row).envelope).filter(Boolean); }
|
|
119
|
+
async dispatch(id) { const r = await this.request('POST', this.path('/commands/' + id + '/dispatch'), {}); if (typeof r.dispatchAllowed !== 'boolean')
|
|
120
|
+
throw Error('INVALID_DISPATCH_RESPONSE'); return { dispatchAllowed: r.dispatchAllowed }; }
|
|
121
|
+
receipt(id, body) { return this.request('POST', this.path('/commands/' + id + '/receipt'), body); }
|
|
122
|
+
state(envelope) { return this.request('PUT', this.path('/state'), { envelope }); }
|
|
123
|
+
attention(body) { return this.request('POST', this.path('/attention'), body); }
|
|
124
|
+
async controls() { const result = await this.request('GET', this.path('/controls')); if (!Array.isArray(result.controls) || result.controls.length > 100)
|
|
125
|
+
throw Error('INVALID_CONTROL_PAGE'); return result.controls.map(row => object(row).envelope).filter(Boolean); }
|
|
126
|
+
controlReceipt(id, body) { return this.request('POST', this.path('/controls/' + id + '/receipt'), body); }
|
|
127
|
+
resolveAttention(id, resolvedAt) { return this.request('POST', this.path('/attention/' + id + '/resolve'), { resolvedAt }); }
|
|
128
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { OperationJournal } from './journal.js';
|
|
2
|
+
export interface Pair {
|
|
3
|
+
pairId: string;
|
|
4
|
+
rootKey: string;
|
|
5
|
+
hostToken: string;
|
|
6
|
+
apiOrigin?: string;
|
|
7
|
+
enrollmentToken?: string;
|
|
8
|
+
expiresAt?: number;
|
|
9
|
+
active: boolean;
|
|
10
|
+
claimId?: string;
|
|
11
|
+
phoneTokenHash?: string;
|
|
12
|
+
activationProof?: unknown;
|
|
13
|
+
daemonServerId?: string;
|
|
14
|
+
revokedAt?: number;
|
|
15
|
+
relayRetiredAt?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface Config {
|
|
18
|
+
version: 1;
|
|
19
|
+
clientId: string;
|
|
20
|
+
target?: string;
|
|
21
|
+
paseoHome: string;
|
|
22
|
+
apiOrigin?: string;
|
|
23
|
+
allowLoopbackHttp: boolean;
|
|
24
|
+
cloudEnabled: boolean;
|
|
25
|
+
daemonServerId?: string;
|
|
26
|
+
pairs: Pair[];
|
|
27
|
+
}
|
|
28
|
+
export declare function dataDirectory(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, home?: string): string;
|
|
29
|
+
export declare function validateOrigin(value: string, allowLoopback: boolean): string;
|
|
30
|
+
export declare function privateManagedDirectory(dir: string): Promise<void>;
|
|
31
|
+
export declare function assertOwnedDirectory(dir: string): Promise<void>;
|
|
32
|
+
export declare function privateDirectory(dir: string): Promise<void>;
|
|
33
|
+
export declare function atomicJson(path: string, value: unknown): Promise<void>;
|
|
34
|
+
export declare function loadConfig(dir: string): Promise<Config>;
|
|
35
|
+
export declare function saveConfig(dir: string, config: Config): Promise<void>;
|
|
36
|
+
export declare function pruneRetiredPairs(config: Config, now?: number, journal?: OperationJournal): boolean;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join, resolve, sep } from 'node:path';
|
|
3
|
+
import { mkdir, readdir } from 'node:fs/promises';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { decode } from './crypto.js';
|
|
6
|
+
import { UUID, LIMITS } from './limits.js';
|
|
7
|
+
import { assertStateRoot, assertStateResource, inspectResource, readPrivateText, createPrivateFile, writePrivateAtomic } from './resources.js';
|
|
8
|
+
export function dataDirectory(env = process.env, platform = process.platform, home = homedir()) { return resolve(env.MOREMOTE_CLI_HOME || (platform === 'win32' ? join(env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'MoRemoteCLI') : platform === 'darwin' ? join(home, 'Library', 'Application Support', 'MoRemoteCLI') : join(env.XDG_STATE_HOME || join(home, '.local', 'state'), 'moremote-cli'))); }
|
|
9
|
+
export function validateOrigin(value, allowLoopback) { const u = new URL(value); if (u.username || u.password || u.search || u.hash || u.pathname !== '/')
|
|
10
|
+
throw Error('INVALID_API_ORIGIN'); if (u.protocol !== 'https:' && !(allowLoopback && u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname)))
|
|
11
|
+
throw Error('HTTPS_REQUIRED'); return u.origin; }
|
|
12
|
+
const ownerFile = '.moremote-cli-owner';
|
|
13
|
+
const ownerText = 'MoRemote CLI state v1\n';
|
|
14
|
+
const managedFile = '.moremote-cli-managed-owner';
|
|
15
|
+
const managedText = 'MoRemote CLI managed package v1\n';
|
|
16
|
+
async function assertManagedDirectory(dir) { inspectResource(dir, 'directory'); if (readPrivateText(join(dir, managedFile), 128).text !== managedText)
|
|
17
|
+
throw Error('FOREIGN_MANAGED_DIRECTORY'); }
|
|
18
|
+
export async function privateManagedDirectory(dir) { await mkdir(dir, { recursive: true, mode: 0o700 }); inspectResource(dir, 'directory'); const names = await readdir(dir); if (!names.includes(managedFile)) {
|
|
19
|
+
if (names.length)
|
|
20
|
+
throw Error('FOREIGN_MANAGED_DIRECTORY');
|
|
21
|
+
createPrivateFile(join(dir, managedFile), managedText);
|
|
22
|
+
} await assertManagedDirectory(dir); }
|
|
23
|
+
export async function assertOwnedDirectory(dir) { inspectResource(dir, 'directory'); try {
|
|
24
|
+
assertStateRoot(dir);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
throw Error('FOREIGN_DATA_DIRECTORY');
|
|
28
|
+
} for (const name of await readdir(dir))
|
|
29
|
+
assertStateResource(dir, name); }
|
|
30
|
+
export async function privateDirectory(dir) { await mkdir(dir, { recursive: true, mode: 0o700 }); inspectResource(dir, 'directory'); const names = await readdir(dir); if (!names.includes(ownerFile)) {
|
|
31
|
+
if (names.length)
|
|
32
|
+
throw Error('FOREIGN_DATA_DIRECTORY');
|
|
33
|
+
createPrivateFile(join(dir, ownerFile), ownerText);
|
|
34
|
+
} await assertOwnedDirectory(dir); }
|
|
35
|
+
export async function atomicJson(path, value) { writePrivateAtomic(path, value); }
|
|
36
|
+
export async function loadConfig(dir) {
|
|
37
|
+
let raw;
|
|
38
|
+
try {
|
|
39
|
+
assertStateRoot(dir);
|
|
40
|
+
raw = readPrivateText(join(dir, 'config.json'), 131072).text;
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
if (e.code !== 'ENOENT')
|
|
44
|
+
throw e;
|
|
45
|
+
return { version: 1, clientId: 'moremote-cli-' + randomUUID(), paseoHome: process.env.PASEO_HOME || join(homedir(), '.paseo'), allowLoopbackHttp: false, cloudEnabled: false, pairs: [] };
|
|
46
|
+
}
|
|
47
|
+
if (Buffer.byteLength(raw) > 131072)
|
|
48
|
+
throw Error('CONFIG_LIMIT');
|
|
49
|
+
const c = JSON.parse(raw);
|
|
50
|
+
if (c.version !== 1 || typeof c.clientId !== 'string' || !c.clientId.startsWith('moremote-cli-') || c.clientId.length > 256 || typeof c.paseoHome !== 'string' || !c.paseoHome || c.paseoHome.length > 4096 || c.target !== undefined && (typeof c.target !== 'string' || !c.target || c.target.length > 16384) || !Array.isArray(c.pairs) || c.pairs.length > 16 || typeof c.cloudEnabled !== 'boolean' || typeof c.allowLoopbackHttp !== 'boolean')
|
|
51
|
+
throw Error('INVALID_CONFIG');
|
|
52
|
+
if (c.apiOrigin)
|
|
53
|
+
c.apiOrigin = validateOrigin(c.apiOrigin, c.allowLoopbackHttp);
|
|
54
|
+
const identities = new Set();
|
|
55
|
+
for (const p of c.pairs) {
|
|
56
|
+
if (!UUID.test(p.pairId) || identities.has(p.pairId) || typeof p.active !== 'boolean' || p.expiresAt !== undefined && (!Number.isSafeInteger(p.expiresAt) || p.expiresAt < 0) || p.revokedAt !== undefined && (!Number.isSafeInteger(p.revokedAt) || p.revokedAt < 0) || p.relayRetiredAt !== undefined && (!Number.isSafeInteger(p.relayRetiredAt) || p.relayRetiredAt < 0))
|
|
57
|
+
throw Error('INVALID_PAIR');
|
|
58
|
+
identities.add(p.pairId);
|
|
59
|
+
decode(p.rootKey, 32);
|
|
60
|
+
decode(p.hostToken, 32);
|
|
61
|
+
if (p.apiOrigin)
|
|
62
|
+
p.apiOrigin = validateOrigin(p.apiOrigin, c.allowLoopbackHttp);
|
|
63
|
+
}
|
|
64
|
+
return c;
|
|
65
|
+
}
|
|
66
|
+
export async function saveConfig(dir, config) { const a = resolve(dir), b = resolve(config.paseoHome); const left = process.platform === 'win32' ? a.toLowerCase() : a, right = process.platform === 'win32' ? b.toLowerCase() : b; if (left === right || left.startsWith(right + sep) || right.startsWith(left + sep))
|
|
67
|
+
throw Error('OFFICIAL_DATA_OVERLAP'); await privateDirectory(dir); await atomicJson(join(dir, 'config.json'), config); }
|
|
68
|
+
export function pruneRetiredPairs(config, now = Date.now(), journal) { const before = config.pairs.length; config.pairs = config.pairs.filter(p => { const retiredAt = p.revokedAt === undefined ? p.relayRetiredAt : Math.max(p.revokedAt, p.relayRetiredAt ?? 0); return retiredAt === undefined ? !(p.active === false && p.expiresAt !== undefined && now >= p.expiresAt + LIMITS.retentionMs) : !journal || now < journal.retirementDeadline(p.pairId, retiredAt); }); return before !== config.pairs.length; }
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare function controlEndpoint(dir: string): string;
|
|
2
|
+
export declare function requestControl(dir: string, action: 'status' | 'stop'): Promise<Record<string, unknown> | null>;
|
|
3
|
+
export declare function ownRuntime(dir: string, status: () => unknown, stop: () => void): Promise<() => Promise<void>>;
|