@moxuli/moremote 0.1.1 → 0.1.4
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 +85 -7
- package/bin/moremote-cli.js +11 -4
- package/dist/activity.d.ts +79 -0
- package/dist/activity.js +193 -0
- package/dist/cli.js +36 -41
- package/dist/cloud-client.d.ts +13 -4
- package/dist/cloud-client.js +60 -15
- package/dist/config.d.ts +7 -0
- package/dist/config.js +23 -4
- package/dist/control.d.ts +1 -0
- package/dist/control.js +9 -0
- package/dist/crypto.d.ts +1 -1
- package/dist/crypto.js +2 -2
- package/dist/enrollment-files.d.ts +37 -0
- package/dist/enrollment-files.js +225 -0
- package/dist/enrollment-protocol.d.ts +50 -0
- package/dist/enrollment-protocol.js +44 -0
- package/dist/journal.js +2 -1
- package/dist/local-enrollment.d.ts +25 -0
- package/dist/local-enrollment.js +160 -0
- package/dist/official-client.d.ts +87 -6
- package/dist/official-client.js +135 -32
- package/dist/operations.d.ts +1 -0
- package/dist/operations.js +24 -4
- package/dist/projection.d.ts +7 -2
- package/dist/resources.d.ts +2 -1
- package/dist/resources.js +69 -32
- package/dist/runtime.d.ts +10 -1
- package/dist/runtime.js +111 -10
- package/dist/service.js +43 -8
- package/dist/setup-upgrade.d.ts +2 -0
- package/dist/setup-upgrade.js +65 -0
- package/dist/setup.d.ts +12 -0
- package/dist/setup.js +38 -0
- package/dist/supervisor.d.ts +1 -0
- package/dist/supervisor.js +44 -1
- package/docs/README.md +4 -3
- package/docs/STATE.md +327 -10
- package/docs/configuration.md +119 -5
- package/docs/plans/2026-11-11-native-service-acceptance.md +168 -0
- package/docs/specs/03-api-contract.md +122 -2
- package/docs/specs/04-control-and-receipt-lifecycle.md +12 -0
- package/docs/specs/05-endpoint-and-lifecycle.md +126 -2
- package/docs/specs/06-managed-updates.md +34 -1
- package/package.json +2 -2
package/dist/resources.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type Stats } from 'node:fs';
|
|
2
2
|
import { DatabaseSync } from 'node:sqlite';
|
|
3
3
|
export declare const JOURNAL_APPLICATION_ID = 1297236785;
|
|
4
|
+
export declare const CONFIG_BYTES = 524288;
|
|
4
5
|
export declare const RUNTIME_OWNER = "MoRemote CLI runtime";
|
|
5
6
|
export interface ResourceIdentity {
|
|
6
7
|
dev: number;
|
|
@@ -38,7 +39,7 @@ export interface RuntimeResources {
|
|
|
38
39
|
export declare function hasCode(error: unknown, code: string): boolean;
|
|
39
40
|
export declare function sameResource(left: ResourceIdentity, right: ResourceIdentity): boolean;
|
|
40
41
|
export declare function inspectResource(path: string, kind: 'file' | 'directory' | 'socket', optional?: boolean, privateMode?: boolean): Stats | null;
|
|
41
|
-
export declare function readPrivateText(path: string, limit: number, encoding?: 'utf8' | 'utf16le'): {
|
|
42
|
+
export declare function readPrivateText(path: string, limit: number, encoding?: 'utf8' | 'utf16le', privateMode?: boolean): {
|
|
42
43
|
text: string;
|
|
43
44
|
identity: {
|
|
44
45
|
dev: number;
|
package/dist/resources.js
CHANGED
|
@@ -3,10 +3,22 @@ import { dirname, basename, join } from 'node:path';
|
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
4
|
import { DatabaseSync } from 'node:sqlite';
|
|
5
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { isUtf8 } from 'node:buffer';
|
|
6
7
|
export const JOURNAL_APPLICATION_ID = 0x4d524331;
|
|
8
|
+
export const CONFIG_BYTES = 524288;
|
|
7
9
|
export const RUNTIME_OWNER = 'MoRemote CLI runtime';
|
|
8
10
|
export function hasCode(error, code) { return error instanceof Error && 'code' in error && error.code === code; }
|
|
9
11
|
export function sameResource(left, right) { return left.dev === right.dev && left.ino === right.ino; }
|
|
12
|
+
function assertResource(stat, kind, privateMode, retiredFile = false) {
|
|
13
|
+
if (stat.isSymbolicLink() || !(kind === 'file' ? stat.isFile() : kind === 'directory' ? stat.isDirectory() : stat.isSocket()))
|
|
14
|
+
throw Error('FOREIGN_RESOURCE_KIND');
|
|
15
|
+
if (kind !== 'directory' && stat.nlink !== 1 && !(retiredFile && kind === 'file' && stat.nlink === 0))
|
|
16
|
+
throw Error('FOREIGN_RESOURCE_LINKS');
|
|
17
|
+
if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
|
|
18
|
+
throw Error('FOREIGN_RESOURCE_USER');
|
|
19
|
+
if (privateMode && process.platform !== 'win32' && ((stat.mode & 0o7077) !== 0 || (stat.mode & (kind === 'directory' ? 0o700 : 0o600)) !== (kind === 'directory' ? 0o700 : 0o600)))
|
|
20
|
+
throw Error('FOREIGN_RESOURCE_MODE');
|
|
21
|
+
}
|
|
10
22
|
export function inspectResource(path, kind, optional = false, privateMode = true) {
|
|
11
23
|
let stat;
|
|
12
24
|
try {
|
|
@@ -17,39 +29,60 @@ export function inspectResource(path, kind, optional = false, privateMode = true
|
|
|
17
29
|
return null;
|
|
18
30
|
throw error;
|
|
19
31
|
}
|
|
20
|
-
|
|
21
|
-
throw Error('FOREIGN_RESOURCE_KIND');
|
|
22
|
-
if (kind !== 'directory' && stat.nlink !== 1)
|
|
23
|
-
throw Error('FOREIGN_RESOURCE_LINKS');
|
|
24
|
-
if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
|
|
25
|
-
throw Error('FOREIGN_RESOURCE_USER');
|
|
26
|
-
if (privateMode && process.platform !== 'win32' && ((stat.mode & 0o7077) !== 0 || (stat.mode & (kind === 'directory' ? 0o700 : 0o600)) !== (kind === 'directory' ? 0o700 : 0o600)))
|
|
27
|
-
throw Error('FOREIGN_RESOURCE_MODE');
|
|
32
|
+
assertResource(stat, kind, privateMode);
|
|
28
33
|
return stat;
|
|
29
34
|
}
|
|
30
|
-
export function readPrivateText(path, limit, encoding = 'utf8') {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if (
|
|
42
|
-
|
|
43
|
-
|
|
35
|
+
export function readPrivateText(path, limit, encoding = 'utf8', privateMode = true) {
|
|
36
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
37
|
+
const before = inspectResource(path, 'file', false, privateMode);
|
|
38
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
39
|
+
try {
|
|
40
|
+
const opened = fstatSync(fd);
|
|
41
|
+
assertResource(opened, 'file', privateMode, true);
|
|
42
|
+
if (opened.size > limit)
|
|
43
|
+
throw Error('FOREIGN_RESOURCE_LIMIT');
|
|
44
|
+
// A rename can retire an already opened inode before fstat. Never read or
|
|
45
|
+
// return that unlinked handle; require a valid replacement and reopen it.
|
|
46
|
+
if (opened.nlink === 0) {
|
|
47
|
+
const replacement = inspectResource(path, 'file', false, privateMode);
|
|
48
|
+
if (!replacement || sameResource(opened, replacement))
|
|
49
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (!before || !sameResource(before, opened))
|
|
53
|
+
continue;
|
|
54
|
+
const bytes = Buffer.alloc(limit + 1);
|
|
55
|
+
let size = 0;
|
|
56
|
+
while (size < bytes.length) {
|
|
57
|
+
const count = readSync(fd, bytes, size, bytes.length - size, null);
|
|
58
|
+
if (count === 0)
|
|
59
|
+
break;
|
|
60
|
+
size += count;
|
|
61
|
+
}
|
|
62
|
+
if (size > limit)
|
|
63
|
+
throw Error('FOREIGN_RESOURCE_LIMIT');
|
|
64
|
+
const finished = fstatSync(fd);
|
|
65
|
+
assertResource(finished, 'file', privateMode, true);
|
|
66
|
+
// Content changes already observed on this handle remain failures even if a
|
|
67
|
+
// later atomic replacement would otherwise permit reopening the pathname.
|
|
68
|
+
if (opened.size !== size || opened.size !== finished.size || opened.mtimeMs !== finished.mtimeMs)
|
|
69
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
70
|
+
const after = inspectResource(path, 'file', false, privateMode);
|
|
71
|
+
// Only an ordinary owned replacement permits another read. Linked, foreign
|
|
72
|
+
// or insecure paths fail inspection, and in-place mutation is never retried.
|
|
73
|
+
if (after && !sameResource(opened, after))
|
|
74
|
+
continue;
|
|
75
|
+
if (!after || finished.nlink !== 1 || opened.size !== after.size || opened.mtimeMs !== after.mtimeMs || opened.ctimeMs !== after.ctimeMs || opened.ctimeMs !== finished.ctimeMs)
|
|
76
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
77
|
+
if (encoding === 'utf8' && !isUtf8(bytes.subarray(0, size)))
|
|
78
|
+
throw Error('FOREIGN_RESOURCE_ENCODING');
|
|
79
|
+
return { text: bytes.toString(encoding, 0, size), identity: { dev: opened.dev, ino: opened.ino } };
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
closeSync(fd);
|
|
44
83
|
}
|
|
45
|
-
const after = inspectResource(path, 'file');
|
|
46
|
-
if (size > limit || !after || !sameResource(opened, after) || opened.size !== after.size || opened.mtimeMs !== after.mtimeMs)
|
|
47
|
-
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
48
|
-
return { text: bytes.toString(encoding, 0, size), identity: { dev: opened.dev, ino: opened.ino } };
|
|
49
|
-
}
|
|
50
|
-
finally {
|
|
51
|
-
closeSync(fd);
|
|
52
84
|
}
|
|
85
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
53
86
|
}
|
|
54
87
|
export function assertStateRoot(dir) {
|
|
55
88
|
inspectResource(dir, 'directory');
|
|
@@ -210,6 +243,9 @@ export function writePrivateAtomic(path, value) {
|
|
|
210
243
|
assertStateRoot(dir);
|
|
211
244
|
if (name !== 'config.json' && name !== 'runtime.json' && name !== 'runtime.lock')
|
|
212
245
|
throw Error('FOREIGN_RESOURCE_NAME');
|
|
246
|
+
const bytes = JSON.stringify(value) + '\n';
|
|
247
|
+
if (name === 'config.json' && Buffer.byteLength(bytes) > CONFIG_BYTES)
|
|
248
|
+
throw Error('CONFIG_LIMIT');
|
|
213
249
|
const before = inspectResource(path, 'file', true);
|
|
214
250
|
if (before) {
|
|
215
251
|
if (name === 'runtime.lock')
|
|
@@ -218,7 +254,7 @@ export function writePrivateAtomic(path, value) {
|
|
|
218
254
|
assertStateResource(dir, name);
|
|
219
255
|
}
|
|
220
256
|
const temp = path + '.' + randomUUID() + '.tmp';
|
|
221
|
-
const identity = createPrivateFile(temp,
|
|
257
|
+
const identity = createPrivateFile(temp, bytes);
|
|
222
258
|
try {
|
|
223
259
|
const current = inspectResource(path, 'file', true);
|
|
224
260
|
if (before ? (!current || !sameResource(before, current)) : current !== null)
|
|
@@ -242,7 +278,8 @@ export function writePrivateAtomic(path, value) {
|
|
|
242
278
|
export function assertTaskResource(dir, platform = process.platform) {
|
|
243
279
|
if (platform !== 'win32')
|
|
244
280
|
throw Error('FOREIGN_TASK_RESOURCE');
|
|
245
|
-
const
|
|
281
|
+
const encoded = readPrivateText(join(dir, 'moremote-cli-task.xml'), 131072, 'utf16le').text;
|
|
282
|
+
const text = encoded.startsWith('\uFEFF') ? encoded.slice(1) : encoded;
|
|
246
283
|
const marker = 'Managed by moremote-cli; per-user ownership v1; owner=' + createHash('sha256').update(dir).digest('hex');
|
|
247
284
|
if (!text.startsWith('<?xml version="1.0" encoding="UTF-16"?>') || !text.includes('<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">') || !text.includes('<Description>' + marker + '</Description>') || !text.trimEnd().endsWith('</Task>'))
|
|
248
285
|
throw Error('FOREIGN_TASK_RESOURCE');
|
|
@@ -278,7 +315,7 @@ export function assertStateResource(dir, name) {
|
|
|
278
315
|
return;
|
|
279
316
|
}
|
|
280
317
|
if (name === 'config.json' || /^config\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
|
|
281
|
-
const value = JSON.parse(readPrivateText(path,
|
|
318
|
+
const value = JSON.parse(readPrivateText(path, CONFIG_BYTES).text);
|
|
282
319
|
if (!object(value) || value.version !== 1 || typeof value.clientId !== 'string' || !value.clientId.startsWith('moremote-cli-') || value.clientId.length > 256)
|
|
283
320
|
throw Error('FOREIGN_CONFIG');
|
|
284
321
|
return;
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import { type Pair } from './config.js';
|
|
2
|
-
import { type Attention } from './official-client.js';
|
|
2
|
+
import { OfficialClient, type Attention } from './official-client.js';
|
|
3
3
|
import { OperationJournal, type Occurrence } from './journal.js';
|
|
4
4
|
export declare function queueAttention(journal: OperationJournal, pair: Pair, event: Attention & {
|
|
5
5
|
sourceFingerprint?: string;
|
|
6
6
|
occurrence?: Occurrence;
|
|
7
7
|
}, now?: number): Promise<void>;
|
|
8
|
+
export declare function boundAttention(journal: OperationJournal, pair: Pair, event: Attention, official: Pick<OfficialClient, 'requestContext' | 'generation'>): Promise<Attention | {
|
|
9
|
+
occurrence: Occurrence;
|
|
10
|
+
sourceFingerprint: string;
|
|
11
|
+
requestBinding: string;
|
|
12
|
+
agentId: string;
|
|
13
|
+
requestId?: string;
|
|
14
|
+
kind: "finished" | "question" | "permission" | "error";
|
|
15
|
+
timestamp: number;
|
|
16
|
+
} | null>;
|
|
8
17
|
export declare function runRuntime(dir: string, version?: string): Promise<void>;
|
package/dist/runtime.js
CHANGED
|
@@ -13,12 +13,17 @@ import { occurrenceBinding } from './bindings.js';
|
|
|
13
13
|
import { projectSnapshot } from './projection.js';
|
|
14
14
|
import { ownRuntime } from './control.js';
|
|
15
15
|
import { LIMITS, object } from './limits.js';
|
|
16
|
+
import { ActivityPublisher, ActivityWorkLane, widgetFingerprint } from './activity.js';
|
|
17
|
+
import { LocalEnrollment } from './local-enrollment.js';
|
|
18
|
+
import { inspectResource } from './resources.js';
|
|
16
19
|
function stableId(value) { const h = createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 32); return h.slice(0, 8) + '-' + h.slice(8, 12) + '-' + h.slice(12, 16) + '-' + h.slice(16, 20) + '-' + h.slice(20); }
|
|
17
20
|
export async function queueAttention(journal, pair, event, now = Date.now()) {
|
|
18
21
|
if (event.timestamp + LIMITS.snapshotMs <= now || event.timestamp > now + LIMITS.futureMs)
|
|
19
22
|
return;
|
|
20
23
|
const payload = { agentId: event.agentId, kind: event.kind, timestamp: event.timestamp, ...(event.requestId ? { requestId: event.requestId } : {}), ...(event.requestBinding ? { requestBinding: event.requestBinding } : {}) };
|
|
21
|
-
|
|
24
|
+
// A bound request notice belongs to its exact occurrence, not its snapshot clock.
|
|
25
|
+
// Keep the legacy source identity for callers without authoritative occurrences.
|
|
26
|
+
const id = event.requestId && event.occurrence ? stableId([pair.pairId, event.agentId, event.kind, event.requestId, 'occurrence', event.occurrence.occurrenceId]) : stableId([pair.pairId, event.agentId, event.kind, event.requestId || '', event.sourceFingerprint || '', event.requestId && !event.sourceFingerprint ? null : event.timestamp]);
|
|
22
27
|
const issuedAt = event.timestamp;
|
|
23
28
|
const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id, channel: 'attention', issuedAt, expiresAt: issuedAt + LIMITS.snapshotMs }, payload);
|
|
24
29
|
const topic = await presenceTopic(decode(pair.rootKey, 32), pair.pairId, event.agentId);
|
|
@@ -26,10 +31,19 @@ export async function queueAttention(journal, pair, event, now = Date.now()) {
|
|
|
26
31
|
return;
|
|
27
32
|
journal.queueAttention(pair.pairId, id, envelope.expiresAt, { id, kind: event.kind, topic, envelope }, payload);
|
|
28
33
|
}
|
|
29
|
-
async function boundAttention(journal, pair, event, official) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
34
|
+
export async function boundAttention(journal, pair, event, official) {
|
|
35
|
+
if (!event.requestId)
|
|
36
|
+
return event;
|
|
37
|
+
// Bind the occurrence captured when this event was observed. Looking up a
|
|
38
|
+
// replacement here could give its identity an older cached event's clock.
|
|
39
|
+
const occurrence = event.occurrence;
|
|
40
|
+
if (!occurrence || occurrence.serverId !== official.requestContext().serverId || occurrence.agentId !== event.agentId || occurrence.requestId !== event.requestId || occurrence.generation !== official.generation || occurrence.createdAt !== event.timestamp || !journal.isCurrent(occurrence))
|
|
41
|
+
return null;
|
|
42
|
+
const requestBinding = await occurrenceBinding(pair, occurrence);
|
|
43
|
+
if (!journal.isCurrent(occurrence))
|
|
44
|
+
return null;
|
|
45
|
+
return { ...event, occurrence, sourceFingerprint: occurrence.fingerprint, requestBinding };
|
|
46
|
+
}
|
|
33
47
|
async function publishResolutions(journal, pair, cloud) { for (const event of journal.attentionResolutions(pair.pairId)) {
|
|
34
48
|
try {
|
|
35
49
|
await cloud.resolveAttention(event.id, event.resolvedAt);
|
|
@@ -82,7 +96,12 @@ export async function runRuntime(dir, version) {
|
|
|
82
96
|
const parentGone = () => { draining = true; drainWake.abort(); };
|
|
83
97
|
let detach, closeJournal;
|
|
84
98
|
const release = await ownRuntime(dir, () => ({ stage, lastError, activePairs, version: version ?? null }), stop);
|
|
99
|
+
const activityLane = new ActivityWorkLane();
|
|
100
|
+
let activityFailure = null, activityPairCursor = 0;
|
|
101
|
+
const enrollment = new LocalEnrollment(dir);
|
|
85
102
|
try {
|
|
103
|
+
if (!inspectResource(join(dir, 'config.json'), 'file', true))
|
|
104
|
+
await saveConfig(dir, await loadConfig(dir));
|
|
86
105
|
const journal = new OperationJournal(join(dir, 'journal.sqlite'));
|
|
87
106
|
closeJournal = () => journal.close();
|
|
88
107
|
if (process.send) {
|
|
@@ -98,6 +117,7 @@ export async function runRuntime(dir, version) {
|
|
|
98
117
|
let measuredAt = 0;
|
|
99
118
|
let snapshot;
|
|
100
119
|
const statePublications = new Map();
|
|
120
|
+
const activityPublisher = new ActivityPublisher();
|
|
101
121
|
const retryStates = new Map();
|
|
102
122
|
const pollOrigins = new Set();
|
|
103
123
|
process.once('SIGINT', stop);
|
|
@@ -108,7 +128,8 @@ export async function runRuntime(dir, version) {
|
|
|
108
128
|
journal.cleanup(now);
|
|
109
129
|
const config = await loadConfig(dir);
|
|
110
130
|
pollOrigins.clear();
|
|
111
|
-
let failure =
|
|
131
|
+
let failure = activityFailure;
|
|
132
|
+
activityFailure = null;
|
|
112
133
|
let acquisitionFailed = false;
|
|
113
134
|
const clouds = new Map();
|
|
114
135
|
const cycleFences = new Map();
|
|
@@ -122,6 +143,12 @@ export async function runRuntime(dir, version) {
|
|
|
122
143
|
if (pair.relayRetiredAt !== undefined)
|
|
123
144
|
pair.active = false;
|
|
124
145
|
}
|
|
146
|
+
try {
|
|
147
|
+
await enrollment.cleanup(config);
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
failure = error;
|
|
151
|
+
}
|
|
125
152
|
// Prune before any request: a retained 404 must not extend automatic recovery.
|
|
126
153
|
if (pruneRetiredPairs(config, now, journal))
|
|
127
154
|
await saveConfig(dir, config);
|
|
@@ -129,6 +156,7 @@ export async function runRuntime(dir, version) {
|
|
|
129
156
|
for (const pairId of statePublications.keys())
|
|
130
157
|
if (!config.pairs.some(pair => pair.pairId === pairId))
|
|
131
158
|
statePublications.delete(pairId);
|
|
159
|
+
activityPublisher.retain(config.cloudEnabled ? config.pairs.filter(pair => pair.active && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId)).map(pair => pair.pairId) : []);
|
|
132
160
|
for (const origin of retryStates.keys())
|
|
133
161
|
if (!config.pairs.some(pair => (pair.apiOrigin || config.apiOrigin) === origin))
|
|
134
162
|
retryStates.delete(origin);
|
|
@@ -140,6 +168,8 @@ export async function runRuntime(dir, version) {
|
|
|
140
168
|
const origin = pair.apiOrigin || config.apiOrigin;
|
|
141
169
|
if (!origin || (!pair.active && pair.revokedAt === undefined && pair.relayRetiredAt === undefined && pair.expiresAt !== undefined && pair.expiresAt <= Date.now()))
|
|
142
170
|
continue;
|
|
171
|
+
if (config.enrollmentRequests?.some(record => record.pairId === pair.pairId && !record.created))
|
|
172
|
+
continue;
|
|
143
173
|
pollOrigins.add(origin);
|
|
144
174
|
let retryState = retryStates.get(origin);
|
|
145
175
|
if (!retryState) {
|
|
@@ -153,6 +183,12 @@ export async function runRuntime(dir, version) {
|
|
|
153
183
|
}
|
|
154
184
|
const cloud = new CloudClient(origin, pair.pairId, pair.hostToken, config.allowLoopbackHttp, fetch, controller.signal, retryState, cycleFence);
|
|
155
185
|
let controlsVerified = true;
|
|
186
|
+
// Pending endpoints cannot use active-only control routes. Admit activation
|
|
187
|
+
// after official identity verification, without granting an execution lane.
|
|
188
|
+
if (!pair.active && pair.revokedAt === undefined && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId)) {
|
|
189
|
+
clouds.set(pair.pairId, cloud);
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
156
192
|
try {
|
|
157
193
|
for (const envelope of await cloud.controls()) {
|
|
158
194
|
try {
|
|
@@ -223,6 +259,26 @@ export async function runRuntime(dir, version) {
|
|
|
223
259
|
lastError = 'ATTENTION_QUEUE_LIMIT'; });
|
|
224
260
|
measuredAt = 0;
|
|
225
261
|
}
|
|
262
|
+
try {
|
|
263
|
+
await enrollment.cycle(config, official.info().serverId, pair => {
|
|
264
|
+
const origin = pair.apiOrigin || config.apiOrigin;
|
|
265
|
+
pollOrigins.add(origin);
|
|
266
|
+
let retry = retryStates.get(origin);
|
|
267
|
+
if (!retry) {
|
|
268
|
+
retry = {};
|
|
269
|
+
retryStates.set(origin, retry);
|
|
270
|
+
}
|
|
271
|
+
let fence = cycleFences.get(origin);
|
|
272
|
+
if (!fence) {
|
|
273
|
+
fence = {};
|
|
274
|
+
cycleFences.set(origin, fence);
|
|
275
|
+
}
|
|
276
|
+
return new CloudClient(origin, pair.pairId, pair.hostToken, config.allowLoopbackHttp, fetch, controller.signal, retry, fence);
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
failure = error;
|
|
281
|
+
}
|
|
226
282
|
if (snapshot === undefined || Date.now() - measuredAt >= 30000) {
|
|
227
283
|
snapshot = await official.snapshot();
|
|
228
284
|
measuredAt = snapshot.measuredAt;
|
|
@@ -238,6 +294,33 @@ export async function runRuntime(dir, version) {
|
|
|
238
294
|
if (bound)
|
|
239
295
|
await queueAttention(journal, pair, bound);
|
|
240
296
|
}
|
|
297
|
+
if (!stopped && !draining) {
|
|
298
|
+
const candidates = config.pairs.filter(pair => pair.active && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId) && clouds.has(pair.pairId));
|
|
299
|
+
const ordered = [...candidates.slice(activityPairCursor), ...candidates.slice(0, activityPairCursor)], activitySnapshot = snapshot, activityOfficial = official;
|
|
300
|
+
// Schedule cached terminal recovery before any optional normal discovery.
|
|
301
|
+
// The owned lane never delays command acquisition and is aborted/joined on drain.
|
|
302
|
+
if (activityLane.start(async (signal) => {
|
|
303
|
+
let optionalFailure;
|
|
304
|
+
for (const terminalOnly of [true, false])
|
|
305
|
+
for (const pair of ordered) {
|
|
306
|
+
signal.throwIfAborted();
|
|
307
|
+
if (!pair.active || journal.pairRevoked(pair.pairId))
|
|
308
|
+
continue;
|
|
309
|
+
const cloud = clouds.get(pair.pairId);
|
|
310
|
+
try {
|
|
311
|
+
await activityPublisher.publish(pair, cloud, activitySnapshot, Date.now(), (agentId, readSignal) => activityOfficial.activityTask(agentId, readSignal), { signal, terminalOnly });
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
if (signal.aborted)
|
|
315
|
+
throw error;
|
|
316
|
+
optionalFailure ??= error;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (optionalFailure)
|
|
320
|
+
throw optionalFailure;
|
|
321
|
+
}, error => { activityFailure = error; }, AbortSignal.any([controller.signal, drainWake.signal])))
|
|
322
|
+
activityPairCursor = (activityPairCursor + 1) % Math.max(1, candidates.length);
|
|
323
|
+
}
|
|
241
324
|
for (const pair of config.pairs) {
|
|
242
325
|
if (stopped)
|
|
243
326
|
break;
|
|
@@ -250,6 +333,12 @@ export async function runRuntime(dir, version) {
|
|
|
250
333
|
continue;
|
|
251
334
|
throw Error('PAIR_DAEMON_MISMATCH');
|
|
252
335
|
}
|
|
336
|
+
// A new activation gets no commands/state in this cycle. The next cycle must
|
|
337
|
+
// acquire and validate controls before it can execute any phone operation.
|
|
338
|
+
if (!pair.active && pair.revokedAt === undefined && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId)) {
|
|
339
|
+
await activatePending(config, dir, pair, cloud, official.info().serverId, snapshot.hostName);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
253
342
|
// Read-only reconciliation remains available after revoke and original message expiry.
|
|
254
343
|
if (await reconcileJournal({ pair, journal, official, cloud, clock: Date.now }))
|
|
255
344
|
failure = Error('RECEIPT_RECONCILIATION_FAILED');
|
|
@@ -265,11 +354,11 @@ export async function runRuntime(dir, version) {
|
|
|
265
354
|
if (!publication || publication.envelope.expiresAt <= Date.now() || (publication.acknowledged && publication.envelope.issuedAt !== snapshot.measuredAt)) {
|
|
266
355
|
const payload = await projectSnapshot(snapshot, pair, journal, official.generation);
|
|
267
356
|
const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'state', issuedAt: snapshot.measuredAt, expiresAt: snapshot.measuredAt + LIMITS.snapshotMs }, payload);
|
|
268
|
-
publication = { envelope, acknowledged: false };
|
|
357
|
+
publication = { envelope, widgetFingerprint: await widgetFingerprint(pair, payload), acknowledged: false };
|
|
269
358
|
statePublications.set(pair.pairId, publication);
|
|
270
359
|
}
|
|
271
360
|
if (!publication.acknowledged) {
|
|
272
|
-
await cloud.state(publication.envelope);
|
|
361
|
+
await cloud.state(publication.envelope, publication.widgetFingerprint);
|
|
273
362
|
publication.acknowledged = true;
|
|
274
363
|
}
|
|
275
364
|
}
|
|
@@ -319,6 +408,12 @@ export async function runRuntime(dir, version) {
|
|
|
319
408
|
acquisitionFailed = true;
|
|
320
409
|
}
|
|
321
410
|
}
|
|
411
|
+
try {
|
|
412
|
+
await enrollment.cleanup(config);
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
failure = error;
|
|
416
|
+
}
|
|
322
417
|
if (failure) {
|
|
323
418
|
lastError = failure instanceof CloudError ? failure.code : 'CLI_CYCLE_FAILED';
|
|
324
419
|
stage = 'degraded';
|
|
@@ -360,15 +455,21 @@ export async function runRuntime(dir, version) {
|
|
|
360
455
|
process.removeListener('message', parentMessage);
|
|
361
456
|
process.removeListener('disconnect', parentGone);
|
|
362
457
|
try {
|
|
458
|
+
await activityLane.close();
|
|
363
459
|
detach?.();
|
|
364
460
|
await official?.close().catch(() => { });
|
|
365
461
|
}
|
|
366
462
|
finally {
|
|
367
463
|
try {
|
|
368
|
-
|
|
464
|
+
enrollment.close();
|
|
369
465
|
}
|
|
370
466
|
finally {
|
|
371
|
-
|
|
467
|
+
try {
|
|
468
|
+
closeJournal?.();
|
|
469
|
+
}
|
|
470
|
+
finally {
|
|
471
|
+
await release();
|
|
472
|
+
}
|
|
372
473
|
}
|
|
373
474
|
}
|
|
374
475
|
}
|
package/dist/service.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
3
|
import { join, dirname } from 'node:path';
|
|
4
|
-
import { homedir, userInfo } from 'node:os';
|
|
4
|
+
import { homedir, userInfo, tmpdir } from 'node:os';
|
|
5
5
|
import { constants } from 'node:fs';
|
|
6
|
-
import { mkdir, readFile, unlink, access, lstat, open, rename, link, mkdtemp, rm } from 'node:fs/promises';
|
|
6
|
+
import { mkdir, readFile, unlink, access, lstat, open, rename, link, mkdtemp, rm, realpath } from 'node:fs/promises';
|
|
7
7
|
import { privateDirectory, privateManagedDirectory } from './config.js';
|
|
8
8
|
import { PACKAGE, exactVersion, updateLock } from './update-state.js';
|
|
9
9
|
const taskName = '\\MoRemoteCLI';
|
|
@@ -90,6 +90,21 @@ function xmlValue(content, element) {
|
|
|
90
90
|
const value = content.match(new RegExp('<' + element + '(?:\\s[^>]*)?>([\\s\\S]*?)</' + element + '>'))?.[1];
|
|
91
91
|
return value?.replaceAll('"', '"').replaceAll(''', "'").replaceAll('<', '<').replaceAll('>', '>').replaceAll('&', '&');
|
|
92
92
|
}
|
|
93
|
+
async function sameRegistrationPath(actual, expected) {
|
|
94
|
+
if (actual === expected)
|
|
95
|
+
return true;
|
|
96
|
+
if (!actual)
|
|
97
|
+
return false;
|
|
98
|
+
try {
|
|
99
|
+
const [loaded, file] = await Promise.all([lstat(actual), lstat(expected)]);
|
|
100
|
+
return loaded.isFile() && !loaded.isSymbolicLink() && file.isFile() && !file.isSymbolicLink()
|
|
101
|
+
&& loaded.dev === file.dev && loaded.ino === file.ino
|
|
102
|
+
&& await realpath(actual) === await realpath(expected);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
93
108
|
async function registration(def, content) {
|
|
94
109
|
if (def.platform === 'darwin') {
|
|
95
110
|
let raw;
|
|
@@ -102,7 +117,7 @@ async function registration(def, content) {
|
|
|
102
117
|
throw error;
|
|
103
118
|
}
|
|
104
119
|
const path = raw.match(/^\s*path = (.+)\s*$/m)?.[1]?.trim();
|
|
105
|
-
if (path
|
|
120
|
+
if (!await sameRegistrationPath(path, def.path))
|
|
106
121
|
throw Error('FOREIGN_SERVICE_REGISTRATION');
|
|
107
122
|
}
|
|
108
123
|
else if (def.platform === 'linux') {
|
|
@@ -110,7 +125,7 @@ async function registration(def, content) {
|
|
|
110
125
|
const path = raw.match(/^FragmentPath=(.*)$/m)?.[1], load = raw.match(/^LoadState=(.*)$/m)?.[1];
|
|
111
126
|
if (path === '' && load === 'not-found')
|
|
112
127
|
return 'absent';
|
|
113
|
-
if (path
|
|
128
|
+
if (!await sameRegistrationPath(path, def.path))
|
|
114
129
|
throw Error(path ? 'FOREIGN_SERVICE_REGISTRATION' : 'SERVICE_MANAGER_INVALID_RESPONSE');
|
|
115
130
|
}
|
|
116
131
|
else if (def.platform === 'win32') {
|
|
@@ -154,6 +169,8 @@ async function writeDefinition(def) {
|
|
|
154
169
|
const temp = def.path + '.' + randomUUID() + '.tmp';
|
|
155
170
|
const handle = await open(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
156
171
|
try {
|
|
172
|
+
// Retained public runtimes read this ownership file without stripping a BOM.
|
|
173
|
+
// The native-only import below supplies the scheduler's required byte order.
|
|
157
174
|
try {
|
|
158
175
|
await handle.writeFile(def.content, def.platform === 'win32' ? 'utf16le' : 'utf8');
|
|
159
176
|
await handle.sync();
|
|
@@ -179,6 +196,26 @@ async function writeDefinition(def) {
|
|
|
179
196
|
await rm(temp, { force: true });
|
|
180
197
|
}
|
|
181
198
|
}
|
|
199
|
+
async function registerWindowsService(def) {
|
|
200
|
+
// Keep native import bytes outside the shared state consumed by old runtimes.
|
|
201
|
+
const temporary = await mkdtemp(join(tmpdir(), 'moremote-cli-task-')), path = join(temporary, 'task.xml');
|
|
202
|
+
try {
|
|
203
|
+
const handle = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
204
|
+
try {
|
|
205
|
+
await handle.writeFile('\uFEFF' + def.content, 'utf16le');
|
|
206
|
+
await handle.sync();
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
await handle.close();
|
|
210
|
+
}
|
|
211
|
+
await command('schtasks', ['/Create', '/TN', taskName, '/XML', path, '/F']);
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
await rm(temporary, { recursive: true, force: true });
|
|
215
|
+
}
|
|
216
|
+
// Never leave the native-import copy present when the retained runtime starts.
|
|
217
|
+
await command('schtasks', ['/Run', '/TN', taskName]);
|
|
218
|
+
}
|
|
182
219
|
export async function installService(def) {
|
|
183
220
|
const status = await serviceStatus(def);
|
|
184
221
|
requireKnown(status);
|
|
@@ -192,10 +229,8 @@ export async function installService(def) {
|
|
|
192
229
|
await command('systemctl', ['--user', 'daemon-reload']);
|
|
193
230
|
await command('systemctl', ['--user', 'enable', '--now', 'moremote-cli.service']);
|
|
194
231
|
}
|
|
195
|
-
else
|
|
196
|
-
await
|
|
197
|
-
await command('schtasks', ['/Run', '/TN', taskName]);
|
|
198
|
-
}
|
|
232
|
+
else
|
|
233
|
+
await registerWindowsService(def);
|
|
199
234
|
}
|
|
200
235
|
export async function stopService(def) {
|
|
201
236
|
const status = await serviceStatus(def);
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { dirname, join } from 'node:path';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { privateDirectory, privateManagedDirectory } from './config.js';
|
|
4
|
+
import { CONFIG_BYTES } from './resources.js';
|
|
5
|
+
import { runtimeHasLiveOwner } from './control.js';
|
|
6
|
+
import { managedEntry, stagePackage } from './service.js';
|
|
7
|
+
import { packageManaged, packageVersion, compatibleEntry, serviceEntry } from './updater.js';
|
|
8
|
+
import { readUpdateState, writeUpdateState, initialUpdateState, updateLock, supervisorRunning, autoUpdateDisabled } from './update-state.js';
|
|
9
|
+
import { object } from './limits.js';
|
|
10
|
+
export async function supportsLocalEnrollment(entry) {
|
|
11
|
+
const manifest = object(JSON.parse(await readFile(join(dirname(dirname(entry)), 'package.json'), 'utf8')));
|
|
12
|
+
const capability = manifest.moremote ? object(manifest.moremote) : {};
|
|
13
|
+
return capability.localEnrollment === 1 && typeof capability.configBytes === 'number' && capability.configBytes >= CONFIG_BYTES && await compatibleEntry(entry);
|
|
14
|
+
}
|
|
15
|
+
// Explicit setup may upgrade only this owned CLI, even when automatic updates
|
|
16
|
+
// are opted out. Never select an older public package as a feature fallback.
|
|
17
|
+
export async function setupServiceEntry(directory, currentEntry) {
|
|
18
|
+
const selected = readUpdateState(directory);
|
|
19
|
+
if (!selected && !await packageManaged())
|
|
20
|
+
return currentEntry;
|
|
21
|
+
await privateDirectory(directory);
|
|
22
|
+
await privateManagedDirectory(join(directory, 'managed'));
|
|
23
|
+
await privateManagedDirectory(join(directory, 'managed', 'versions'));
|
|
24
|
+
await updateLock(directory, async () => {
|
|
25
|
+
if (supervisorRunning(directory) || runtimeHasLiveOwner(directory))
|
|
26
|
+
throw Error('STOP_CLI_BEFORE_SETUP');
|
|
27
|
+
let state = readUpdateState(directory);
|
|
28
|
+
let entry = state ? await managedEntry(directory, state.active) : undefined;
|
|
29
|
+
const capable = entry ? await supportsLocalEnrollment(entry) : false;
|
|
30
|
+
if (state && capable && state.bootstrap === state.active)
|
|
31
|
+
return;
|
|
32
|
+
if (!entry || !capable) {
|
|
33
|
+
const version = await packageVersion();
|
|
34
|
+
try {
|
|
35
|
+
entry = await stagePackage(directory, version);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (error instanceof Error && error.message.startsWith('FOREIGN_'))
|
|
39
|
+
throw error;
|
|
40
|
+
throw Error('SETUP_CURRENT_PACKAGE_UNAVAILABLE');
|
|
41
|
+
}
|
|
42
|
+
if (!await supportsLocalEnrollment(entry))
|
|
43
|
+
throw Error('SETUP_CAPABILITY_REQUIRED');
|
|
44
|
+
if (state) {
|
|
45
|
+
state.previous = state.active;
|
|
46
|
+
state.active = version;
|
|
47
|
+
}
|
|
48
|
+
else
|
|
49
|
+
state = initialUpdateState(version);
|
|
50
|
+
delete state.pending;
|
|
51
|
+
delete state.pendingManual;
|
|
52
|
+
delete state.activating;
|
|
53
|
+
delete state.manualRequired;
|
|
54
|
+
}
|
|
55
|
+
if (!state)
|
|
56
|
+
throw Error('SETUP_CAPABILITY_REQUIRED');
|
|
57
|
+
// The old bootstrap's compatibility reader cannot promise the enlarged
|
|
58
|
+
// config bound. Retain its immutable package/previous identity, not its loop.
|
|
59
|
+
state.bootstrap = state.active;
|
|
60
|
+
if (autoUpdateDisabled(directory))
|
|
61
|
+
state.enabled = false;
|
|
62
|
+
writeUpdateState(directory, state);
|
|
63
|
+
});
|
|
64
|
+
return serviceEntry(directory);
|
|
65
|
+
}
|
package/dist/setup.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Config } from './config.js';
|
|
2
|
+
export interface SetupDependencies {
|
|
3
|
+
yes: boolean;
|
|
4
|
+
home?: string;
|
|
5
|
+
stopOwned: () => Promise<void>;
|
|
6
|
+
authenticate: (config: Config) => Promise<{
|
|
7
|
+
serverId: string;
|
|
8
|
+
}>;
|
|
9
|
+
prepare?: () => Promise<void>;
|
|
10
|
+
install: () => Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
export declare function setupEnrollment(directory: string, dependencies: SetupDependencies): Promise<Config>;
|
package/dist/setup.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { loadConfig, saveConfig, privateDirectory, validateOrigin } from './config.js';
|
|
4
|
+
import { DEFAULT_API_ORIGIN } from './local-enrollment.js';
|
|
5
|
+
import { ownRuntime } from './control.js';
|
|
6
|
+
// Lifecycle and identity I/O are injectable: consumer tests never register a
|
|
7
|
+
// service or touch the real home. Callers must use the owned lifecycle adapters.
|
|
8
|
+
export async function setupEnrollment(directory, dependencies) {
|
|
9
|
+
if (!dependencies.yes)
|
|
10
|
+
throw Error('EXPLICIT_YES_REQUIRED');
|
|
11
|
+
await dependencies.stopOwned();
|
|
12
|
+
// Preparation can stage an owned managed version, but never reads or writes
|
|
13
|
+
// enrollment configuration. A concurrent run wins safely before we claim it.
|
|
14
|
+
await dependencies.prepare?.();
|
|
15
|
+
await privateDirectory(directory);
|
|
16
|
+
let cancelled = false;
|
|
17
|
+
const release = await ownRuntime(directory, () => ({ stage: 'setup' }), () => { cancelled = true; });
|
|
18
|
+
let config;
|
|
19
|
+
try {
|
|
20
|
+
config = await loadConfig(directory);
|
|
21
|
+
const origin = validateOrigin(config.apiOrigin ?? DEFAULT_API_ORIGIN, false);
|
|
22
|
+
const identity = await dependencies.authenticate(config);
|
|
23
|
+
if (cancelled)
|
|
24
|
+
throw Error('SETUP_CANCELLED');
|
|
25
|
+
if (!identity.serverId || Buffer.byteLength(identity.serverId) > 512 || config.daemonServerId && config.daemonServerId !== identity.serverId || config.pairs.some(pair => pair.revokedAt === undefined && pair.relayRetiredAt === undefined && pair.daemonServerId && pair.daemonServerId !== identity.serverId))
|
|
26
|
+
throw Error('DAEMON_IDENTITY_CHANGED');
|
|
27
|
+
config.apiOrigin = origin;
|
|
28
|
+
config.cloudEnabled = true;
|
|
29
|
+
config.daemonServerId = identity.serverId;
|
|
30
|
+
config.localEnrollment = { home: resolve(dependencies.home ?? homedir()) };
|
|
31
|
+
await saveConfig(directory, config);
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
await release();
|
|
35
|
+
}
|
|
36
|
+
await dependencies.install();
|
|
37
|
+
return config;
|
|
38
|
+
}
|