@moxuli/moremote 0.0.0-stage → 0.1.1
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 +325 -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-transport.d.ts +4 -0
- package/dist/control-transport.js +68 -0
- package/dist/control.d.ts +3 -0
- package/dist/control.js +297 -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 +155 -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 +34 -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 +55 -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
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { openSync, closeSync, fsyncSync, renameSync } from 'node:fs';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { privateManagedDirectory } from './config.js';
|
|
5
|
+
import { managedRoot } from './update-state.js';
|
|
6
|
+
import { inspectResource, readPrivateText, createPrivateFile, removeOwnedResource, sameResource } from './resources.js';
|
|
7
|
+
const OWNER = 'MoRemote CLI control transport';
|
|
8
|
+
function readDescriptor(dir) {
|
|
9
|
+
if (!inspectResource(join(dir, 'managed'), 'directory', true))
|
|
10
|
+
return null;
|
|
11
|
+
const root = managedRoot(dir), path = join(root, 'runtime-transport.json');
|
|
12
|
+
if (!inspectResource(path, 'file', true))
|
|
13
|
+
return null;
|
|
14
|
+
const file = readPrivateText(path, 2048);
|
|
15
|
+
let value;
|
|
16
|
+
try {
|
|
17
|
+
value = JSON.parse(file.text);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
throw Error('INVALID_CONTROL_TRANSPORT');
|
|
21
|
+
}
|
|
22
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 7 || value.owner !== OWNER || value.version !== 1 || value.framing !== 'json-lines-v1' || typeof value.instanceId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.instanceId) || !Number.isSafeInteger(value.pid) || value.pid < 1 || value.pid > 2147483647 || !Number.isSafeInteger(value.startedAt) || value.startedAt < 1 || typeof value.tokenHash !== 'string' || !/^[0-9a-f]{64}$/.test(value.tokenHash))
|
|
23
|
+
throw Error('INVALID_CONTROL_TRANSPORT');
|
|
24
|
+
return { ...file, value };
|
|
25
|
+
}
|
|
26
|
+
function matches(value, owner) { return value.instanceId === owner.instanceId && value.pid === owner.pid && value.startedAt === owner.startedAt && value.tokenHash === createHash('sha256').update(owner.token).digest('hex'); }
|
|
27
|
+
export function controlFraming(dir, owner) {
|
|
28
|
+
const descriptor = readDescriptor(dir);
|
|
29
|
+
return descriptor && matches(descriptor.value, owner) ? 'json-lines-v1' : 'legacy-eof';
|
|
30
|
+
}
|
|
31
|
+
export async function publishControlTransport(dir, owner) {
|
|
32
|
+
// Nested managed resources are understood/ignored by the published 0.1.0
|
|
33
|
+
// root reader; its exact six/seven-key runtime lock/record stays unchanged.
|
|
34
|
+
await privateManagedDirectory(join(dir, 'managed'));
|
|
35
|
+
const root = managedRoot(dir), path = join(root, 'runtime-transport.json'), before = readDescriptor(dir);
|
|
36
|
+
const value = { owner: OWNER, version: 1, framing: 'json-lines-v1', instanceId: owner.instanceId, pid: owner.pid, startedAt: owner.startedAt, tokenHash: createHash('sha256').update(owner.token).digest('hex') };
|
|
37
|
+
const temp = path + '.' + randomUUID() + '.tmp', identity = createPrivateFile(temp, JSON.stringify(value) + '\n');
|
|
38
|
+
try {
|
|
39
|
+
const current = readDescriptor(dir);
|
|
40
|
+
if (before ? (!current || !sameResource(before.identity, current.identity) || before.text !== current.text) : current !== null)
|
|
41
|
+
throw Error('CONTROL_TRANSPORT_CHANGED');
|
|
42
|
+
renameSync(temp, path);
|
|
43
|
+
if (process.platform !== 'win32') {
|
|
44
|
+
const fd = openSync(root, 'r');
|
|
45
|
+
try {
|
|
46
|
+
fsyncSync(fd);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
closeSync(fd);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return identity;
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
removeOwnedResource(temp, identity);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export function removeControlTransport(dir, identity, owner) {
|
|
59
|
+
try {
|
|
60
|
+
const current = readDescriptor(dir);
|
|
61
|
+
if (!current || !sameResource(current.identity, identity) || !matches(current.value, owner))
|
|
62
|
+
return false;
|
|
63
|
+
return removeOwnedResource(join(managedRoot(dir), 'runtime-transport.json'), identity);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -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>>;
|
package/dist/control.js
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { createServer, createConnection } from 'node:net';
|
|
2
|
+
import { randomBytes, randomUUID, timingSafeEqual, createHash } from 'node:crypto';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { chmodSync, renameSync, readdirSync } from 'node:fs';
|
|
5
|
+
import { assertStateRoot, createPrivateFile, hasCode, inspectResource, inspectRuntime, readRuntimeOwner, readRuntimeRecord, removeOwnedResource, runtimeMatches, RUNTIME_OWNER, sameResource, writePrivateAtomic } from './resources.js';
|
|
6
|
+
import { controlFraming, publishControlTransport, removeControlTransport } from './control-transport.js';
|
|
7
|
+
export function controlEndpoint(dir) { return process.platform === 'win32' ? '\\\\.\\pipe\\moremote-cli-' + createHash('sha256').update(dir).digest('hex').slice(0, 24) : join(dir, 'runtime.sock'); }
|
|
8
|
+
function object(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
|
|
9
|
+
function removeRuntimeFile(path, identity, owner, record = false) {
|
|
10
|
+
try {
|
|
11
|
+
const current = record ? readRuntimeRecord(path) : readRuntimeOwner(path);
|
|
12
|
+
if (!sameResource(current.identity, identity) || !runtimeMatches(current.value, owner))
|
|
13
|
+
return false;
|
|
14
|
+
return removeOwnedResource(path, identity);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function running(pid) {
|
|
21
|
+
try {
|
|
22
|
+
process.kill(pid, 0);
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (hasCode(error, 'ESRCH'))
|
|
27
|
+
return false;
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export async function requestControl(dir, action) {
|
|
32
|
+
if (!inspectResource(dir, 'directory', true))
|
|
33
|
+
return null;
|
|
34
|
+
if (readdirSync(dir).length === 0)
|
|
35
|
+
return null;
|
|
36
|
+
assertStateRoot(dir);
|
|
37
|
+
const resources = inspectRuntime(dir);
|
|
38
|
+
if (!resources.record)
|
|
39
|
+
return null;
|
|
40
|
+
if (process.platform !== 'win32' && !resources.socket)
|
|
41
|
+
return null;
|
|
42
|
+
const expectedRecord = resources.record.identity;
|
|
43
|
+
const record = resources.record.value;
|
|
44
|
+
const framing = controlFraming(dir, record);
|
|
45
|
+
if (framing === 'legacy-eof' && process.platform === 'win32') {
|
|
46
|
+
if (!running(record.pid))
|
|
47
|
+
return null;
|
|
48
|
+
throw Error('LEGACY_WINDOWS_CONTROL_UNAVAILABLE');
|
|
49
|
+
}
|
|
50
|
+
const ownerEnded = () => { const path = join(dir, 'runtime.json'); if (!inspectResource(path, 'file', true))
|
|
51
|
+
return true; const current = readRuntimeRecord(path); return !sameResource(current.identity, expectedRecord) || !runtimeMatches(current.value, record); };
|
|
52
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
53
|
+
const socket = createConnection(controlEndpoint(dir));
|
|
54
|
+
let raw = '', settled = false;
|
|
55
|
+
socket.setEncoding('utf8');
|
|
56
|
+
const succeed = (value) => { if (settled)
|
|
57
|
+
return; settled = true; clearTimeout(timer); socket.destroy(); resolve(value); };
|
|
58
|
+
const fail = (error) => { if (settled)
|
|
59
|
+
return; settled = true; clearTimeout(timer); socket.destroy(); reject(error); };
|
|
60
|
+
const disconnected = () => { if (settled)
|
|
61
|
+
return; if (raw) {
|
|
62
|
+
fail(Error('CONTROL_INVALID_RESPONSE'));
|
|
63
|
+
return;
|
|
64
|
+
} try {
|
|
65
|
+
if (ownerEnded())
|
|
66
|
+
succeed(null);
|
|
67
|
+
else
|
|
68
|
+
fail(Error('CONTROL_CONNECTION_CLOSED'));
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
fail(error);
|
|
72
|
+
} };
|
|
73
|
+
const parseResponse = (frame) => { try {
|
|
74
|
+
const value = JSON.parse(frame);
|
|
75
|
+
if (!object(value))
|
|
76
|
+
throw Error('CONTROL_INVALID_RESPONSE');
|
|
77
|
+
succeed(value);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
fail(Error('CONTROL_INVALID_RESPONSE'));
|
|
81
|
+
} };
|
|
82
|
+
const timer = setTimeout(() => fail(Error('CONTROL_TIMEOUT')), 2000);
|
|
83
|
+
socket.on('connect', () => {
|
|
84
|
+
try {
|
|
85
|
+
const current = inspectRuntime(dir);
|
|
86
|
+
if (!current.record || !sameResource(current.record.identity, expectedRecord) || !runtimeMatches(current.record.value, record))
|
|
87
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
88
|
+
if (controlFraming(dir, current.record.value) !== framing)
|
|
89
|
+
throw Error('CONTROL_TRANSPORT_CHANGED');
|
|
90
|
+
const payload = JSON.stringify({ token: record.token, action }) + '\n';
|
|
91
|
+
// The owned generation fact selects exactly one exchange, never a timeout
|
|
92
|
+
// probe/replay. Published 0.1.0 uses EOF; new named pipes remain duplex.
|
|
93
|
+
if (framing === 'legacy-eof')
|
|
94
|
+
socket.end(payload);
|
|
95
|
+
else
|
|
96
|
+
socket.write(payload);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
fail(error);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
socket.on('data', chunk => {
|
|
103
|
+
if (settled)
|
|
104
|
+
return;
|
|
105
|
+
raw += chunk;
|
|
106
|
+
if (Buffer.byteLength(raw) > 4096) {
|
|
107
|
+
fail(Error('CONTROL_LIMIT'));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (framing === 'legacy-eof')
|
|
111
|
+
return;
|
|
112
|
+
const end = raw.indexOf('\n');
|
|
113
|
+
if (end < 0)
|
|
114
|
+
return;
|
|
115
|
+
if (end !== raw.length - 1) {
|
|
116
|
+
fail(Error('CONTROL_INVALID_RESPONSE'));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
parseResponse(raw.slice(0, end));
|
|
120
|
+
});
|
|
121
|
+
socket.on('end', () => { if (framing === 'legacy-eof' && raw)
|
|
122
|
+
parseResponse(raw);
|
|
123
|
+
else
|
|
124
|
+
disconnected(); });
|
|
125
|
+
socket.on('close', disconnected);
|
|
126
|
+
socket.on('error', error => { if (settled)
|
|
127
|
+
return; if (hasCode(error, 'ECONNREFUSED') || hasCode(error, 'ENOENT'))
|
|
128
|
+
succeed(null);
|
|
129
|
+
else if (hasCode(error, 'ECONNRESET') || hasCode(error, 'EPIPE'))
|
|
130
|
+
disconnected();
|
|
131
|
+
else
|
|
132
|
+
fail(error); });
|
|
133
|
+
return promise;
|
|
134
|
+
}
|
|
135
|
+
function closeServer(server) {
|
|
136
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
137
|
+
server.close(() => resolve());
|
|
138
|
+
return promise;
|
|
139
|
+
}
|
|
140
|
+
async function assertPipeAbsent(endpoint) {
|
|
141
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
142
|
+
const socket = createConnection(endpoint);
|
|
143
|
+
socket.setTimeout(2000);
|
|
144
|
+
socket.once('connect', () => { socket.destroy(); reject(Error('RUNTIME_RESOURCE_COLLISION')); });
|
|
145
|
+
socket.once('timeout', () => { socket.destroy(); reject(Error('CONTROL_TIMEOUT')); });
|
|
146
|
+
socket.once('error', error => { if (hasCode(error, 'ENOENT') || hasCode(error, 'ECONNREFUSED'))
|
|
147
|
+
resolve();
|
|
148
|
+
else
|
|
149
|
+
reject(error); });
|
|
150
|
+
return promise;
|
|
151
|
+
}
|
|
152
|
+
export async function ownRuntime(dir, status, stop) {
|
|
153
|
+
assertStateRoot(dir);
|
|
154
|
+
let previous = inspectRuntime(dir);
|
|
155
|
+
const endpoint = controlEndpoint(dir);
|
|
156
|
+
if (process.platform === 'win32' && !previous.lock) {
|
|
157
|
+
await assertPipeAbsent(endpoint);
|
|
158
|
+
previous = inspectRuntime(dir);
|
|
159
|
+
}
|
|
160
|
+
// Validate every collision before replacing any lock, record or socket.
|
|
161
|
+
if (previous.lock && running(previous.lock.value.pid))
|
|
162
|
+
throw Error('CLI_ALREADY_RUNNING');
|
|
163
|
+
if (previous.socket && !previous.record && !(previous.lock?.value.staging && sameResource(previous.socket, previous.lock.value.staging)))
|
|
164
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
165
|
+
if (previous.staged) {
|
|
166
|
+
if (!previous.lock)
|
|
167
|
+
throw Error('RUNTIME_UNPROVEN_STAGE');
|
|
168
|
+
const current = readRuntimeOwner(join(dir, 'runtime.lock'));
|
|
169
|
+
if (!sameResource(current.identity, previous.lock.identity) || !runtimeMatches(current.value, previous.lock.value) || !current.value.staging || !sameResource(current.value.staging, previous.staged.identity))
|
|
170
|
+
throw Error('RUNTIME_UNPROVEN_STAGE');
|
|
171
|
+
if (!removeOwnedResource(previous.staged.path, previous.staged.identity, 'socket', false))
|
|
172
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
173
|
+
}
|
|
174
|
+
if (previous.socket && !removeOwnedResource(endpoint, previous.socket, 'socket'))
|
|
175
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
176
|
+
if (previous.record && !removeRuntimeFile(join(dir, 'runtime.json'), previous.record.identity, previous.record.value, true))
|
|
177
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
178
|
+
if (previous.lock && !removeRuntimeFile(join(dir, 'runtime.lock'), previous.lock.identity, previous.lock.value))
|
|
179
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
180
|
+
const owner = { owner: RUNTIME_OWNER, version: 1, instanceId: randomUUID(), pid: process.pid, startedAt: Date.now(), token: randomBytes(32).toString('base64url') };
|
|
181
|
+
const lockPath = join(dir, 'runtime.lock'), recordPath = join(dir, 'runtime.json');
|
|
182
|
+
let lock = createPrivateFile(lockPath, JSON.stringify(owner) + '\n');
|
|
183
|
+
const staging = process.platform === 'win32' ? endpoint : join(dir, 's.' + owner.instanceId.slice(0, 8));
|
|
184
|
+
let socketIdentity = null, recordIdentity = null, transportIdentity;
|
|
185
|
+
const server = createServer({ allowHalfOpen: true }, socket => {
|
|
186
|
+
let raw = '', handled = false;
|
|
187
|
+
socket.setEncoding('utf8');
|
|
188
|
+
const timer = setTimeout(() => socket.destroy(), 2000);
|
|
189
|
+
socket.once('close', () => clearTimeout(timer));
|
|
190
|
+
socket.on('error', () => { });
|
|
191
|
+
socket.on('end', () => socket.destroy());
|
|
192
|
+
const reply = (value) => { const frame = JSON.stringify(value) + '\n'; if (Buffer.byteLength(frame) > 4096)
|
|
193
|
+
socket.destroy();
|
|
194
|
+
else
|
|
195
|
+
socket.write(frame); };
|
|
196
|
+
socket.on('data', chunk => {
|
|
197
|
+
if (handled) {
|
|
198
|
+
socket.destroy();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
raw += chunk;
|
|
202
|
+
if (Buffer.byteLength(raw) > 4096) {
|
|
203
|
+
handled = true;
|
|
204
|
+
socket.destroy();
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const end = raw.indexOf('\n');
|
|
208
|
+
if (end < 0)
|
|
209
|
+
return;
|
|
210
|
+
handled = true;
|
|
211
|
+
try {
|
|
212
|
+
if (end !== raw.length - 1)
|
|
213
|
+
throw Error('CONTROL_FRAME');
|
|
214
|
+
const request = JSON.parse(raw.slice(0, end));
|
|
215
|
+
if (!object(request) || typeof request.token !== 'string' || request.token.length !== 43)
|
|
216
|
+
throw Error('CONTROL_AUTH');
|
|
217
|
+
const left = Buffer.from(request.token), right = Buffer.from(owner.token);
|
|
218
|
+
if (left.length !== right.length || !timingSafeEqual(left, right))
|
|
219
|
+
throw Error('CONTROL_AUTH');
|
|
220
|
+
if (request.action === 'stop') {
|
|
221
|
+
stop();
|
|
222
|
+
reply({ ok: true, stopping: true });
|
|
223
|
+
}
|
|
224
|
+
else if (request.action === 'status') {
|
|
225
|
+
const value = status();
|
|
226
|
+
if (!object(value))
|
|
227
|
+
throw Error('CONTROL_STATUS');
|
|
228
|
+
reply({ ok: true, ...value });
|
|
229
|
+
}
|
|
230
|
+
else
|
|
231
|
+
throw Error('CONTROL_ACTION');
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
reply({ ok: false });
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
try {
|
|
239
|
+
if (process.platform !== 'win32' && inspectResource(staging, 'socket', true))
|
|
240
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
241
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
242
|
+
server.once('error', reject);
|
|
243
|
+
server.listen(staging, resolve);
|
|
244
|
+
await promise;
|
|
245
|
+
server.removeListener('error', reject);
|
|
246
|
+
if (process.platform !== 'win32') {
|
|
247
|
+
const created = inspectResource(staging, 'socket', false, false);
|
|
248
|
+
if (!created)
|
|
249
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
250
|
+
const current = readRuntimeOwner(lockPath);
|
|
251
|
+
if (!sameResource(current.identity, lock) || !runtimeMatches(current.value, owner))
|
|
252
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
253
|
+
lock = writePrivateAtomic(lockPath, { ...owner, staging: { dev: created.dev, ino: created.ino } });
|
|
254
|
+
chmodSync(staging, 0o600);
|
|
255
|
+
const secured = inspectResource(staging, 'socket');
|
|
256
|
+
if (!secured || !sameResource(created, secured) || inspectResource(endpoint, 'socket', true))
|
|
257
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
258
|
+
// libuv closes/unlinks the bind path, not the public path. A replacement
|
|
259
|
+
// runtime.sock therefore cannot be removed implicitly by server.close().
|
|
260
|
+
renameSync(staging, endpoint);
|
|
261
|
+
socketIdentity = { dev: secured.dev, ino: secured.ino };
|
|
262
|
+
}
|
|
263
|
+
// Publish the generation fact durably before making its unchanged legacy-
|
|
264
|
+
// compatible record visible; readers can never select EOF for this record.
|
|
265
|
+
transportIdentity = await publishControlTransport(dir, owner);
|
|
266
|
+
recordIdentity = writePrivateAtomic(recordPath, { ...owner, socket: socketIdentity });
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
await closeServer(server);
|
|
270
|
+
if (socketIdentity)
|
|
271
|
+
removeOwnedResource(endpoint, socketIdentity, 'socket');
|
|
272
|
+
if (recordIdentity)
|
|
273
|
+
removeRuntimeFile(recordPath, recordIdentity, owner, true);
|
|
274
|
+
if (transportIdentity)
|
|
275
|
+
removeControlTransport(dir, transportIdentity, owner);
|
|
276
|
+
removeRuntimeFile(lockPath, lock, owner);
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
let closing;
|
|
280
|
+
return () => {
|
|
281
|
+
if (closing)
|
|
282
|
+
return closing;
|
|
283
|
+
if (process.platform !== 'win32' && inspectResource(staging, 'socket', true))
|
|
284
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
285
|
+
closing = (async () => {
|
|
286
|
+
await closeServer(server);
|
|
287
|
+
if (socketIdentity)
|
|
288
|
+
removeOwnedResource(endpoint, socketIdentity, 'socket');
|
|
289
|
+
if (recordIdentity)
|
|
290
|
+
removeRuntimeFile(recordPath, recordIdentity, owner, true);
|
|
291
|
+
removeRuntimeFile(lockPath, lock, owner);
|
|
292
|
+
if (transportIdentity)
|
|
293
|
+
removeControlTransport(dir, transportIdentity, owner);
|
|
294
|
+
})();
|
|
295
|
+
return closing;
|
|
296
|
+
};
|
|
297
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type Envelope } from './crypto.js';
|
|
2
|
+
import type { Pair } from './config.js';
|
|
3
|
+
import type { OperationJournal } from './journal.js';
|
|
4
|
+
interface Context {
|
|
5
|
+
pair: Pick<Pair, 'pairId' | 'rootKey'>;
|
|
6
|
+
journal: OperationJournal;
|
|
7
|
+
cloud: {
|
|
8
|
+
controlReceipt(id: string, body: {
|
|
9
|
+
envelope: Envelope;
|
|
10
|
+
}): Promise<unknown>;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export declare function processControl(ctx: Context, input: unknown, now?: number): Promise<string>;
|
|
14
|
+
export declare function retransmitControls(ctx: Context, now?: number): Promise<void>;
|
|
15
|
+
export {};
|
package/dist/controls.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { openEnvelope, sealEnvelope, decode, validateEnvelope } from './crypto.js';
|
|
2
|
+
import { object, exact, UUID, LIMITS } from './limits.js';
|
|
3
|
+
export async function processControl(ctx, input, now) {
|
|
4
|
+
const clock = now === undefined ? Date.now : () => now;
|
|
5
|
+
now = now ?? clock();
|
|
6
|
+
const e = validateEnvelope(input, now);
|
|
7
|
+
if (e.pairId !== ctx.pair.pairId || e.channel !== 'control')
|
|
8
|
+
throw Error('CONTROL_CONTEXT');
|
|
9
|
+
const payload = object(await openEnvelope(decode(ctx.pair.rootKey, 32), e, now));
|
|
10
|
+
if (payload.type === 'revoke')
|
|
11
|
+
exact(payload, ['type']);
|
|
12
|
+
else if (payload.type === 'cancel') {
|
|
13
|
+
exact(payload, ['type', 'operationId']);
|
|
14
|
+
if (typeof payload.operationId !== 'string' || !UUID.test(payload.operationId))
|
|
15
|
+
throw Error('INVALID_OPERATION_ID');
|
|
16
|
+
}
|
|
17
|
+
else
|
|
18
|
+
throw Error('INVALID_CONTROL');
|
|
19
|
+
if (e.expiresAt <= clock())
|
|
20
|
+
throw Error('EXPIRED_CONTROL');
|
|
21
|
+
ctx.journal.applyControl(e, payload.type, payload.operationId, clock());
|
|
22
|
+
return finishControl(ctx, e.id, clock());
|
|
23
|
+
}
|
|
24
|
+
async function finishControl(ctx, id, now) {
|
|
25
|
+
const record = ctx.journal.control(ctx.pair.pairId, id);
|
|
26
|
+
let receipt = record.receipt;
|
|
27
|
+
if (!receipt) {
|
|
28
|
+
receipt = await sealEnvelope(decode(ctx.pair.rootKey, 32), { version: 1, pairId: ctx.pair.pairId, id, channel: 'controlReceipt', issuedAt: now, expiresAt: now + LIMITS.snapshotMs }, { controlId: id, type: record.type, ...(record.type === 'cancel' ? { operationId: record.operationId } : {}), state: record.state, revision: 1 });
|
|
29
|
+
ctx.journal.controlReceipt(ctx.pair.pairId, id, receipt);
|
|
30
|
+
}
|
|
31
|
+
await ctx.cloud.controlReceipt(id, { envelope: receipt });
|
|
32
|
+
ctx.journal.controlReceiptSent(ctx.pair.pairId, id);
|
|
33
|
+
return record.state;
|
|
34
|
+
}
|
|
35
|
+
export async function retransmitControls(ctx, now = Date.now()) { for (const record of ctx.journal.controlReceipts(ctx.pair.pairId, now))
|
|
36
|
+
await finishControl(ctx, record.id, now); }
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export type Channel = 'enrollment' | 'activation' | 'command' | 'receipt' | 'state' | 'attention' | 'control' | 'controlReceipt';
|
|
2
|
+
export interface Metadata {
|
|
3
|
+
version: 1;
|
|
4
|
+
pairId: string;
|
|
5
|
+
id: string;
|
|
6
|
+
channel: Channel;
|
|
7
|
+
issuedAt: number;
|
|
8
|
+
expiresAt: number;
|
|
9
|
+
}
|
|
10
|
+
export interface Envelope extends Metadata {
|
|
11
|
+
nonce: string;
|
|
12
|
+
ciphertext: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function decode(value: unknown, length?: number): Buffer<ArrayBuffer>;
|
|
15
|
+
export declare function validateEnvelope(input: unknown, now: number, allowExpired?: boolean): Envelope;
|
|
16
|
+
export declare function deriveKey(root: Uint8Array, pairId: string, channel: Channel | 'presence' | 'requestBinding'): Promise<Uint8Array<ArrayBuffer>>;
|
|
17
|
+
export declare function sealEnvelope(root: Uint8Array, metadata: Metadata, payload: unknown, nonce?: Uint8Array): Promise<Envelope>;
|
|
18
|
+
export declare function openEnvelope(root: Uint8Array, input: unknown, now?: number): Promise<unknown>;
|
|
19
|
+
/** Display only: historical state/attention never authorizes any operation. */
|
|
20
|
+
export declare function openHistoricalSnapshot(root: Uint8Array, input: unknown, now?: number): Promise<unknown>;
|
|
21
|
+
/** Read-only outcome audit. This API can never decode a command or enrollment. */
|
|
22
|
+
export declare function openHistoricalReceipt(root: Uint8Array, input: unknown, now?: number): Promise<unknown>;
|
|
23
|
+
export declare function presenceTopic(root: Uint8Array, pairId: string, agentId: string): Promise<string>;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { webcrypto, randomBytes } from 'node:crypto';
|
|
2
|
+
import { LIMITS, UUID, object, exact } from './limits.js';
|
|
3
|
+
const subtle = webcrypto.subtle;
|
|
4
|
+
const channels = ['enrollment', 'activation', 'command', 'receipt', 'state', 'attention', 'control', 'controlReceipt'];
|
|
5
|
+
function bytes(v) { return Uint8Array.from(v); }
|
|
6
|
+
export function decode(value, length) { if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))
|
|
7
|
+
throw Error('INVALID_BASE64URL'); const b = Buffer.from(value, 'base64url'); if (b.toString('base64url') !== value || (length !== undefined && b.length !== length))
|
|
8
|
+
throw Error('INVALID_BASE64URL'); return b; }
|
|
9
|
+
export function validateEnvelope(input, now, allowExpired = false) {
|
|
10
|
+
const e = object(input);
|
|
11
|
+
exact(e, ['version', 'pairId', 'id', 'channel', 'issuedAt', 'expiresAt', 'nonce', 'ciphertext']);
|
|
12
|
+
if (Buffer.byteLength(JSON.stringify(e)) > LIMITS.envelopeBytes || e.version !== 1 || typeof e.pairId !== 'string' || !UUID.test(e.pairId) || typeof e.id !== 'string' || !UUID.test(e.id) || !channels.includes(String(e.channel)))
|
|
13
|
+
throw Error('INVALID_ENVELOPE');
|
|
14
|
+
if ((e.channel === 'receipt' || e.channel === 'controlReceipt') && Buffer.byteLength(JSON.stringify(e)) > LIMITS.receiptBytes)
|
|
15
|
+
throw Error('RECEIPT_LIMIT');
|
|
16
|
+
if (!Number.isSafeInteger(e.issuedAt) || !Number.isSafeInteger(e.expiresAt) || Number(e.issuedAt) < 0 || Number(e.expiresAt) <= Number(e.issuedAt))
|
|
17
|
+
throw Error('INVALID_TIME');
|
|
18
|
+
const ttl = e.channel === 'command' || e.channel === 'control' ? LIMITS.commandMs : LIMITS.enrollmentMs;
|
|
19
|
+
if (Number(e.expiresAt) - Number(e.issuedAt) > ttl || Number(e.issuedAt) > now + LIMITS.futureMs || (!allowExpired && Number(e.expiresAt) <= now))
|
|
20
|
+
throw Error('EXPIRED_OR_FUTURE');
|
|
21
|
+
decode(e.nonce, 12);
|
|
22
|
+
const c = decode(e.ciphertext);
|
|
23
|
+
if (c.length < 16 || c.length > LIMITS.plainBytes + 16)
|
|
24
|
+
throw Error('INVALID_CIPHERTEXT');
|
|
25
|
+
return e;
|
|
26
|
+
}
|
|
27
|
+
export async function deriveKey(root, pairId, channel) {
|
|
28
|
+
if (root.length !== 32 || !UUID.test(pairId))
|
|
29
|
+
throw Error('INVALID_KEY_CONTEXT');
|
|
30
|
+
const key = await subtle.importKey('raw', bytes(root), 'HKDF', false, ['deriveBits']);
|
|
31
|
+
return new Uint8Array(await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: Buffer.from('MoRemote pairing v1'), info: Buffer.from(JSON.stringify([1, pairId, channel])) }, key, 256));
|
|
32
|
+
}
|
|
33
|
+
function aad(m) { return Buffer.from(JSON.stringify([1, m.pairId, m.id, m.channel, m.issuedAt, m.expiresAt])); }
|
|
34
|
+
export async function sealEnvelope(root, metadata, payload, nonce = randomBytes(12)) {
|
|
35
|
+
const plain = Buffer.from(JSON.stringify(payload));
|
|
36
|
+
if (plain.length > LIMITS.plainBytes || nonce.length !== 12)
|
|
37
|
+
throw Error('PAYLOAD_LIMIT');
|
|
38
|
+
const key = await subtle.importKey('raw', bytes(await deriveKey(root, metadata.pairId, metadata.channel)), 'AES-GCM', false, ['encrypt']);
|
|
39
|
+
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv: bytes(nonce), additionalData: aad(metadata), tagLength: 128 }, key, plain);
|
|
40
|
+
const envelope = { ...metadata, nonce: Buffer.from(nonce).toString('base64url'), ciphertext: Buffer.from(encrypted).toString('base64url') };
|
|
41
|
+
validateEnvelope(envelope, metadata.issuedAt);
|
|
42
|
+
return envelope;
|
|
43
|
+
}
|
|
44
|
+
async function decryptEnvelope(root, e) {
|
|
45
|
+
const key = await subtle.importKey('raw', bytes(await deriveKey(root, e.pairId, e.channel)), 'AES-GCM', false, ['decrypt']);
|
|
46
|
+
const plain = await subtle.decrypt({ name: 'AES-GCM', iv: decode(e.nonce, 12), additionalData: aad(e), tagLength: 128 }, key, decode(e.ciphertext));
|
|
47
|
+
if (plain.byteLength > LIMITS.plainBytes)
|
|
48
|
+
throw Error('PAYLOAD_LIMIT');
|
|
49
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plain));
|
|
50
|
+
}
|
|
51
|
+
export async function openEnvelope(root, input, now = Date.now()) {
|
|
52
|
+
return decryptEnvelope(root, validateEnvelope(input, now));
|
|
53
|
+
}
|
|
54
|
+
/** Display only: historical state/attention never authorizes any operation. */
|
|
55
|
+
export async function openHistoricalSnapshot(root, input, now = Date.now()) {
|
|
56
|
+
const e = validateEnvelope(input, now, true);
|
|
57
|
+
if (e.channel !== 'state' && e.channel !== 'attention')
|
|
58
|
+
throw Error('HISTORICAL_AUTHORITY_REFUSED');
|
|
59
|
+
return decryptEnvelope(root, e);
|
|
60
|
+
}
|
|
61
|
+
/** Read-only outcome audit. This API can never decode a command or enrollment. */
|
|
62
|
+
export async function openHistoricalReceipt(root, input, now = Date.now()) {
|
|
63
|
+
const e = validateEnvelope(input, now, true);
|
|
64
|
+
if (e.channel !== 'receipt' && e.channel !== 'controlReceipt')
|
|
65
|
+
throw Error('HISTORICAL_AUTHORITY_REFUSED');
|
|
66
|
+
return decryptEnvelope(root, e);
|
|
67
|
+
}
|
|
68
|
+
export async function presenceTopic(root, pairId, agentId) { const key = await subtle.importKey('raw', bytes(await deriveKey(root, pairId, 'presence')), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return Buffer.from(await subtle.sign('HMAC', key, Buffer.from(agentId))).toString('base64url'); }
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Command } from './operations.js';
|
|
2
|
+
export type Evidence = ({
|
|
3
|
+
type: 'send';
|
|
4
|
+
serverId: string;
|
|
5
|
+
agentId: string;
|
|
6
|
+
messageId: string;
|
|
7
|
+
textDigest: string;
|
|
8
|
+
} | {
|
|
9
|
+
type: 'permission';
|
|
10
|
+
serverId: string;
|
|
11
|
+
agentId: string;
|
|
12
|
+
requestId: string;
|
|
13
|
+
requestBinding: string;
|
|
14
|
+
responseDigest: string;
|
|
15
|
+
}) & {
|
|
16
|
+
occurrenceId?: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function contentDigest(value: string): string;
|
|
19
|
+
export declare function evidenceForCommand(command: Command, serverId: string): Evidence;
|
package/dist/evidence.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonical } from './journal.js';
|
|
3
|
+
export function contentDigest(value) { return createHash('sha256').update(value).digest('hex'); }
|
|
4
|
+
export function evidenceForCommand(command, serverId) { return command.type === 'send' ? { type: 'send', serverId, agentId: command.agentId, messageId: command.messageId, textDigest: contentDigest(command.text) } : { type: 'permission', serverId, agentId: command.agentId, requestId: command.requestId, requestBinding: command.requestBinding, responseDigest: contentDigest(canonical(command.response)) }; }
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Envelope } from './crypto.js';
|
|
2
|
+
import type { Evidence } from './evidence.js';
|
|
3
|
+
export type ReceiptState = 'accepted' | 'resolved' | 'rejected' | 'unknown';
|
|
4
|
+
export interface JournalRecord {
|
|
5
|
+
pairId: string;
|
|
6
|
+
id: string;
|
|
7
|
+
digest: string;
|
|
8
|
+
expiresAt: number;
|
|
9
|
+
state: 'prepared' | 'dispatched' | ReceiptState;
|
|
10
|
+
envelope: Envelope | null;
|
|
11
|
+
receipt: Envelope | null;
|
|
12
|
+
code: string | null;
|
|
13
|
+
revision: number;
|
|
14
|
+
sentRevision: number;
|
|
15
|
+
evidence: Evidence | null;
|
|
16
|
+
}
|
|
17
|
+
export interface Occurrence {
|
|
18
|
+
occurrenceId: string;
|
|
19
|
+
serverId: string;
|
|
20
|
+
agentId: string;
|
|
21
|
+
requestId: string;
|
|
22
|
+
generation: string;
|
|
23
|
+
fingerprint: string;
|
|
24
|
+
active: number;
|
|
25
|
+
createdAt: number;
|
|
26
|
+
}
|
|
27
|
+
export declare function digest(value: unknown): string;
|
|
28
|
+
export declare function canonical(value: unknown): string;
|
|
29
|
+
export declare class OperationJournal {
|
|
30
|
+
private db;
|
|
31
|
+
constructor(path: string);
|
|
32
|
+
get(pairId: string, id: string): JournalRecord | undefined;
|
|
33
|
+
prepare(e: Envelope): {
|
|
34
|
+
record: JournalRecord;
|
|
35
|
+
fresh: boolean;
|
|
36
|
+
};
|
|
37
|
+
dispatched(pairId: string, id: string): void;
|
|
38
|
+
outcome(pairId: string, id: string, state: ReceiptState, receipt: Envelope, code?: string, revision?: number): void;
|
|
39
|
+
pending(pairId: string): JournalRecord[];
|
|
40
|
+
receipts(pairId: string, now: number): JournalRecord[];
|
|
41
|
+
receiptSent(pairId: string, id: string, revision: number): void;
|
|
42
|
+
evidence(pairId: string, id: string, evidence: Evidence): void;
|
|
43
|
+
evidenceOccurrence(pairId: string, id: string, occurrenceId: string): void;
|
|
44
|
+
reconciled(pairId: string, id: string, now: number): void;
|
|
45
|
+
revokePair(pairId: string, now?: number): void;
|
|
46
|
+
pairRevoked(pairId: string): boolean;
|
|
47
|
+
revocationTime(pairId: string): number | undefined;
|
|
48
|
+
retirementDeadline(pairId: string, revokedAt: number): number;
|
|
49
|
+
cleanupRevocations(retainedPairIds: string[], now: number): void;
|
|
50
|
+
blocked(pairId: string, id: string): boolean;
|
|
51
|
+
applyControl(e: Envelope, type: 'cancel' | 'revoke', operationId: string | undefined, now: number): Envelope | null;
|
|
52
|
+
control(pairId: string, id: string): {
|
|
53
|
+
receipt: Envelope | null;
|
|
54
|
+
state: string;
|
|
55
|
+
expiresAt: number;
|
|
56
|
+
type: "cancel" | "revoke";
|
|
57
|
+
operationId: string | null;
|
|
58
|
+
} | undefined;
|
|
59
|
+
controlReceipt(pairId: string, id: string, receipt: Envelope): void;
|
|
60
|
+
controlReceipts(pairId: string, now: number): {
|
|
61
|
+
id: string;
|
|
62
|
+
}[];
|
|
63
|
+
controlReceiptSent(pairId: string, id: string): void;
|
|
64
|
+
observe(serverId: string, agentId: string, generation: string, request: Record<string, unknown>, now?: number): Occurrence;
|
|
65
|
+
currentOccurrence(serverId: string, agentId: string, requestId: string): Occurrence | undefined;
|
|
66
|
+
isCurrent(occurrence: Occurrence): boolean;
|
|
67
|
+
syncRequests(serverId: string, agentId: string, generation: string, requests: {
|
|
68
|
+
id: string;
|
|
69
|
+
}[]): void;
|
|
70
|
+
retire(serverId: string, agentId: string, requestId: string): void;
|
|
71
|
+
retireGeneration(serverId: string, generation: string): void;
|
|
72
|
+
syncAttention(agentId: string, requiresAttention: boolean, timestamp: number | null): void;
|
|
73
|
+
resolution(serverId: string, agentId: string, requestId: string, generation: string, response: unknown, now?: number): void;
|
|
74
|
+
resolutionFacts(serverId: string, agentId: string, requestId: string): (Occurrence & {
|
|
75
|
+
response: string;
|
|
76
|
+
})[];
|
|
77
|
+
queueAttention(pairId: string, id: string, expiresAt: number, body: {
|
|
78
|
+
envelope: Envelope;
|
|
79
|
+
[key: string]: unknown;
|
|
80
|
+
}, event: {
|
|
81
|
+
agentId: string;
|
|
82
|
+
requestId?: string;
|
|
83
|
+
requestBinding?: string;
|
|
84
|
+
}): void;
|
|
85
|
+
attention(pairId: string, now: number): {
|
|
86
|
+
id: string;
|
|
87
|
+
body: any;
|
|
88
|
+
}[];
|
|
89
|
+
attentionSent(pairId: string, id: string): void;
|
|
90
|
+
attentionRecords(pairId: string): {
|
|
91
|
+
id: string;
|
|
92
|
+
agentId: string;
|
|
93
|
+
requestId: string | null;
|
|
94
|
+
requestBinding: string | null;
|
|
95
|
+
}[];
|
|
96
|
+
resolveAttention(pairId: string, id: string, now: number): void;
|
|
97
|
+
attentionResolutions(pairId: string): {
|
|
98
|
+
id: string;
|
|
99
|
+
resolvedAt: number;
|
|
100
|
+
}[];
|
|
101
|
+
attentionResolutionSent(pairId: string, id: string): void;
|
|
102
|
+
cleanup(now: number): void;
|
|
103
|
+
close(): void;
|
|
104
|
+
}
|