@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/pairing.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
import { hostname } from 'node:os';
|
|
3
|
+
import { decode, openEnvelope, sealEnvelope } from './crypto.js';
|
|
4
|
+
import { exact, object, UUID, LIMITS } from './limits.js';
|
|
5
|
+
import { saveConfig } from './config.js';
|
|
6
|
+
export function tokenHash(token) { return createHash('sha256').update(token).digest('hex'); }
|
|
7
|
+
export function makeOffer(apiOrigin, now = Date.now()) {
|
|
8
|
+
const pair = { pairId: randomUUID(), apiOrigin, rootKey: randomBytes(32).toString('base64url'), hostToken: randomBytes(32).toString('base64url'), enrollmentToken: randomBytes(32).toString('base64url'), expiresAt: now + LIMITS.enrollmentMs, active: false };
|
|
9
|
+
return { pair, offer: { version: 1, apiOrigin, pairId: pair.pairId, enrollmentToken: pair.enrollmentToken, rootKey: pair.rootKey, expiresAt: pair.expiresAt } };
|
|
10
|
+
}
|
|
11
|
+
export async function verifyClaim(pair, pending, now) {
|
|
12
|
+
const clock = now === undefined ? Date.now : () => now;
|
|
13
|
+
now = now ?? clock();
|
|
14
|
+
if (!Number.isSafeInteger(pair.expiresAt) || now >= pair.expiresAt)
|
|
15
|
+
throw Error('PAIRING_EXPIRED');
|
|
16
|
+
const p = object(pending);
|
|
17
|
+
if (typeof p.claimId !== 'string' || !UUID.test(p.claimId) || typeof p.phoneTokenHash !== 'string' || !/^([a-f0-9]{64})$/.test(p.phoneTokenHash))
|
|
18
|
+
throw Error('INVALID_CLAIM');
|
|
19
|
+
const envelope = object(p.proof);
|
|
20
|
+
if (envelope.pairId !== pair.pairId || envelope.id !== p.claimId || envelope.channel !== 'enrollment' || Number(envelope.issuedAt) < pair.expiresAt - LIMITS.enrollmentMs || Number(envelope.expiresAt) > pair.expiresAt)
|
|
21
|
+
throw Error('CLAIM_CONTEXT_MISMATCH');
|
|
22
|
+
const body = object(await openEnvelope(decode(pair.rootKey, 32), p.proof, now));
|
|
23
|
+
exact(body, ['type', 'claimId', 'phoneTokenHash']);
|
|
24
|
+
if (body.type !== 'phoneHello' || body.claimId !== p.claimId || body.phoneTokenHash !== p.phoneTokenHash)
|
|
25
|
+
throw Error('CLAIM_PROOF_MISMATCH');
|
|
26
|
+
if (clock() >= pair.expiresAt)
|
|
27
|
+
throw Error('PAIRING_EXPIRED');
|
|
28
|
+
return { claimId: p.claimId, phoneTokenHash: p.phoneTokenHash };
|
|
29
|
+
}
|
|
30
|
+
export async function activatePending(config, dir, pair, cloud, daemonServerId, hostName = hostname()) {
|
|
31
|
+
if (pair.revokedAt !== undefined || pair.relayRetiredAt !== undefined)
|
|
32
|
+
return false;
|
|
33
|
+
if (pair.active)
|
|
34
|
+
return true;
|
|
35
|
+
const result = await cloud.pair();
|
|
36
|
+
const state = object(result.pair);
|
|
37
|
+
if (state.state === 'revoked' || state.state === 'expired') {
|
|
38
|
+
pair.active = false;
|
|
39
|
+
pair.relayRetiredAt ??= Date.now();
|
|
40
|
+
await saveConfig(dir, config);
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (!Number.isSafeInteger(pair.expiresAt) || Date.now() >= pair.expiresAt)
|
|
44
|
+
throw Error('PAIRING_EXPIRED');
|
|
45
|
+
if (!state.pendingClaim)
|
|
46
|
+
return false;
|
|
47
|
+
const accepted = await verifyClaim(pair, state.pendingClaim);
|
|
48
|
+
if (pair.claimId && (pair.claimId !== accepted.claimId || pair.phoneTokenHash !== accepted.phoneTokenHash))
|
|
49
|
+
throw Error('CLAIM_REPLACEMENT_REFUSED');
|
|
50
|
+
pair.claimId = accepted.claimId;
|
|
51
|
+
pair.phoneTokenHash = accepted.phoneTokenHash;
|
|
52
|
+
pair.daemonServerId = daemonServerId;
|
|
53
|
+
if (!pair.activationProof) {
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
pair.activationProof = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: accepted.claimId, channel: 'activation', issuedAt: now, expiresAt: Math.min(pair.expiresAt || now + LIMITS.enrollmentMs, now + LIMITS.enrollmentMs) }, { type: 'companionHello', ...accepted, daemonServerId, hostName: hostName.slice(0, 256) });
|
|
56
|
+
}
|
|
57
|
+
// Bind accepted phone durably before activation; execute only after exact cloud confirmation.
|
|
58
|
+
await saveConfig(dir, config);
|
|
59
|
+
if (Date.now() >= pair.expiresAt)
|
|
60
|
+
throw Error('PAIRING_EXPIRED');
|
|
61
|
+
await cloud.activate({ claimId: accepted.claimId, proof: pair.activationProof });
|
|
62
|
+
if (Date.now() >= pair.expiresAt)
|
|
63
|
+
throw Error('PAIRING_EXPIRED');
|
|
64
|
+
pair.active = true;
|
|
65
|
+
delete pair.enrollmentToken;
|
|
66
|
+
await saveConfig(dir, config);
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AgentPermissionResponse } from '@getpaseo/protocol/agent-types';
|
|
2
|
+
interface RequestInput {
|
|
3
|
+
kind?: string;
|
|
4
|
+
input?: unknown;
|
|
5
|
+
suggestions?: unknown[];
|
|
6
|
+
}
|
|
7
|
+
/** Matches PermissionCardRequest.response: copy input, edit original strings, add exact question-header answers. */
|
|
8
|
+
export declare function validatePermissionInput(request: RequestInput, response: AgentPermissionResponse): void;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { object, text } from './limits.js';
|
|
3
|
+
function validSelectedLabels(answer, labels, multi) { if (!multi)
|
|
4
|
+
return labels.includes(answer); let positions = new Set([0]); for (const label of labels) {
|
|
5
|
+
const next = new Set(positions);
|
|
6
|
+
for (const pos of positions) {
|
|
7
|
+
const prefix = pos === 0 ? label : ', ' + label;
|
|
8
|
+
if (answer.startsWith(prefix, pos))
|
|
9
|
+
next.add(pos + prefix.length);
|
|
10
|
+
}
|
|
11
|
+
positions = next;
|
|
12
|
+
} return answer.length > 0 && positions.has(answer.length); }
|
|
13
|
+
/** Matches PermissionCardRequest.response: copy input, edit original strings, add exact question-header answers. */
|
|
14
|
+
export function validatePermissionInput(request, response) {
|
|
15
|
+
if (response.behavior !== 'allow')
|
|
16
|
+
return;
|
|
17
|
+
if (response.updatedPermissions?.some((grant, index, all) => !request.suggestions?.some(offered => isDeepStrictEqual(grant, offered)) || all.slice(0, index).some(other => isDeepStrictEqual(grant, other))))
|
|
18
|
+
throw Error('UNSUPPORTED_PERMISSION_UPDATE');
|
|
19
|
+
const input = request.input === undefined ? {} : object(request.input);
|
|
20
|
+
let questions = [];
|
|
21
|
+
if (request.kind === 'question') {
|
|
22
|
+
if (!Array.isArray(input.questions) || !input.questions.length)
|
|
23
|
+
throw Error('UNSUPPORTED_QUESTION_FORM');
|
|
24
|
+
if (input.questions.length > 20)
|
|
25
|
+
throw Error('QUESTION_LIMIT');
|
|
26
|
+
questions = input.questions.map(q => object(q));
|
|
27
|
+
}
|
|
28
|
+
const headers = new Set();
|
|
29
|
+
for (const q of questions) {
|
|
30
|
+
text(q.header);
|
|
31
|
+
text(q.question, 8192);
|
|
32
|
+
if (headers.has(q.header) || !Array.isArray(q.options) || q.options.length > 32)
|
|
33
|
+
throw Error('INVALID_QUESTION');
|
|
34
|
+
headers.add(q.header);
|
|
35
|
+
}
|
|
36
|
+
const updated = response.updatedInput === undefined ? input : object(response.updatedInput);
|
|
37
|
+
for (const [key, value] of Object.entries(input)) {
|
|
38
|
+
if (typeof value === 'string') {
|
|
39
|
+
if (typeof updated[key] !== 'string')
|
|
40
|
+
throw Error('INPUT_SHAPE_CHANGED');
|
|
41
|
+
}
|
|
42
|
+
else if (!isDeepStrictEqual(value, updated[key]))
|
|
43
|
+
throw Error('INPUT_SHAPE_CHANGED');
|
|
44
|
+
}
|
|
45
|
+
for (const key of Object.keys(updated))
|
|
46
|
+
if (!Object.hasOwn(input, key) && !(questions.length && key === 'answers'))
|
|
47
|
+
throw Error('INPUT_SCOPE_CHANGED');
|
|
48
|
+
if (questions.length) {
|
|
49
|
+
const answers = object(updated.answers);
|
|
50
|
+
if (Object.keys(answers).length !== questions.length || Object.keys(answers).some(k => !headers.has(k)))
|
|
51
|
+
throw Error('INCOMPLETE_ANSWERS');
|
|
52
|
+
for (const q of questions) {
|
|
53
|
+
const answer = answers[q.header];
|
|
54
|
+
if (typeof answer !== 'string' || Buffer.byteLength(answer) > 8192)
|
|
55
|
+
throw Error('INVALID_ANSWER');
|
|
56
|
+
const options = q.options;
|
|
57
|
+
const labels = options.map(o => text(object(o).label, 4096));
|
|
58
|
+
const allowOther = options.length === 0 || q.allowOther === true || q.isOther === true;
|
|
59
|
+
const allowEmpty = q.allowEmpty === true && allowOther;
|
|
60
|
+
if (!allowEmpty && !answer.trim())
|
|
61
|
+
throw Error('INCOMPLETE_ANSWERS');
|
|
62
|
+
if (!allowOther && !validSelectedLabels(answer, labels, q.multiSelect === true))
|
|
63
|
+
throw Error('INVALID_ANSWER_CHOICE');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { OfficialClient } from './official-client.js';
|
|
2
|
+
import type { Pair } from './config.js';
|
|
3
|
+
import { type OperationJournal } from './journal.js';
|
|
4
|
+
export declare function projectSnapshot(source: Awaited<ReturnType<OfficialClient['snapshot']>>, pair: Pair, journal: OperationJournal, generation: string): Promise<{
|
|
5
|
+
tasks: {
|
|
6
|
+
pendingRequests: {
|
|
7
|
+
requestId: string;
|
|
8
|
+
requestBinding: string;
|
|
9
|
+
request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
|
|
10
|
+
}[];
|
|
11
|
+
agentId: string;
|
|
12
|
+
title: string | null;
|
|
13
|
+
status: "error" | "initializing" | "idle" | "running" | "closed";
|
|
14
|
+
updatedAt: string;
|
|
15
|
+
requiresAttention: boolean;
|
|
16
|
+
attentionReason: "permission" | "finished" | "error" | null;
|
|
17
|
+
}[];
|
|
18
|
+
tasksTruncated: boolean;
|
|
19
|
+
version: number;
|
|
20
|
+
daemonServerId: string;
|
|
21
|
+
hostName: string;
|
|
22
|
+
measuredAt: number;
|
|
23
|
+
usage: unknown;
|
|
24
|
+
}>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { canonical, digest } from './journal.js';
|
|
2
|
+
import { occurrenceBinding } from './bindings.js';
|
|
3
|
+
export async function projectSnapshot(source, pair, journal, generation) {
|
|
4
|
+
const tasks = [];
|
|
5
|
+
let tasksTruncated = false;
|
|
6
|
+
for (const task of source.tasks) {
|
|
7
|
+
if (Buffer.byteLength(task.agentId) > 256) {
|
|
8
|
+
tasksTruncated = true;
|
|
9
|
+
continue;
|
|
10
|
+
}
|
|
11
|
+
const pendingRequests = [];
|
|
12
|
+
for (const pending of task.pendingRequests) {
|
|
13
|
+
if (Buffer.byteLength(pending.requestId) > 256 || Buffer.byteLength(JSON.stringify(pending.request)) > 8192) {
|
|
14
|
+
tasksTruncated = true;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const occurrence = journal.currentOccurrence(source.daemonServerId, task.agentId, pending.requestId);
|
|
18
|
+
if (!occurrence || occurrence.generation !== generation || occurrence.fingerprint !== digest(canonical(pending.request)))
|
|
19
|
+
continue;
|
|
20
|
+
const requestBinding = await occurrenceBinding(pair, occurrence);
|
|
21
|
+
if (!journal.isCurrent(occurrence))
|
|
22
|
+
continue;
|
|
23
|
+
pendingRequests.push({ requestId: pending.requestId, requestBinding, request: pending.request });
|
|
24
|
+
}
|
|
25
|
+
tasks.push({ ...task, pendingRequests });
|
|
26
|
+
}
|
|
27
|
+
const result = { ...source, tasks, tasksTruncated };
|
|
28
|
+
while (Buffer.byteLength(JSON.stringify(result)) > 60000 && result.tasks.length) {
|
|
29
|
+
result.tasks.pop();
|
|
30
|
+
result.tasksTruncated = true;
|
|
31
|
+
}
|
|
32
|
+
if (Buffer.byteLength(JSON.stringify(result)) > 60000)
|
|
33
|
+
throw Error('SNAPSHOT_LIMIT');
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { type Stats } from 'node:fs';
|
|
2
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
export declare const JOURNAL_APPLICATION_ID = 1297236785;
|
|
4
|
+
export declare const RUNTIME_OWNER = "MoRemote CLI runtime";
|
|
5
|
+
export interface ResourceIdentity {
|
|
6
|
+
dev: number;
|
|
7
|
+
ino: number;
|
|
8
|
+
}
|
|
9
|
+
export interface RuntimeOwner {
|
|
10
|
+
owner: typeof RUNTIME_OWNER;
|
|
11
|
+
version: 1;
|
|
12
|
+
instanceId: string;
|
|
13
|
+
pid: number;
|
|
14
|
+
startedAt: number;
|
|
15
|
+
token: string;
|
|
16
|
+
}
|
|
17
|
+
export interface RuntimeLock extends RuntimeOwner {
|
|
18
|
+
staging?: ResourceIdentity;
|
|
19
|
+
}
|
|
20
|
+
export interface RuntimeRecord extends RuntimeOwner {
|
|
21
|
+
socket: ResourceIdentity | null;
|
|
22
|
+
}
|
|
23
|
+
export interface RuntimeResources {
|
|
24
|
+
lock: {
|
|
25
|
+
value: RuntimeLock;
|
|
26
|
+
identity: ResourceIdentity;
|
|
27
|
+
} | null;
|
|
28
|
+
record: {
|
|
29
|
+
value: RuntimeRecord;
|
|
30
|
+
identity: ResourceIdentity;
|
|
31
|
+
} | null;
|
|
32
|
+
socket: ResourceIdentity | null;
|
|
33
|
+
staged: {
|
|
34
|
+
path: string;
|
|
35
|
+
identity: ResourceIdentity;
|
|
36
|
+
} | null;
|
|
37
|
+
}
|
|
38
|
+
export declare function hasCode(error: unknown, code: string): boolean;
|
|
39
|
+
export declare function sameResource(left: ResourceIdentity, right: ResourceIdentity): boolean;
|
|
40
|
+
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
|
+
text: string;
|
|
43
|
+
identity: {
|
|
44
|
+
dev: number;
|
|
45
|
+
ino: number;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
export declare function assertStateRoot(dir: string): void;
|
|
49
|
+
export declare function readRuntimeOwner(path: string): {
|
|
50
|
+
value: RuntimeLock;
|
|
51
|
+
identity: ResourceIdentity;
|
|
52
|
+
};
|
|
53
|
+
export declare function readRuntimeRecord(path: string): {
|
|
54
|
+
value: {
|
|
55
|
+
socket: ResourceIdentity | null;
|
|
56
|
+
owner: typeof RUNTIME_OWNER;
|
|
57
|
+
version: 1;
|
|
58
|
+
instanceId: string;
|
|
59
|
+
pid: number;
|
|
60
|
+
startedAt: number;
|
|
61
|
+
token: string;
|
|
62
|
+
};
|
|
63
|
+
identity: {
|
|
64
|
+
dev: number;
|
|
65
|
+
ino: number;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
export declare function runtimeMatches(lock: RuntimeOwner, record: RuntimeOwner): boolean;
|
|
69
|
+
export declare function inspectRuntime(dir: string): RuntimeResources;
|
|
70
|
+
export declare function validateJournalPath(path: string): ResourceIdentity | null;
|
|
71
|
+
export declare function removeOwnedResource(path: string, identity: ResourceIdentity, kind?: 'file' | 'socket', privateMode?: boolean): boolean;
|
|
72
|
+
export declare function createPrivateFile(path: string, text: string): ResourceIdentity;
|
|
73
|
+
export declare function openOwnedJournal(path: string): DatabaseSync;
|
|
74
|
+
export declare function writePrivateAtomic(path: string, value: unknown): ResourceIdentity;
|
|
75
|
+
export declare function assertTaskResource(dir: string, platform?: NodeJS.Platform): void;
|
|
76
|
+
export declare function assertStateResource(dir: string, name: string): void;
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { constants, lstatSync, openSync, closeSync, fstatSync, readSync, writeFileSync, fsyncSync, unlinkSync, renameSync, readdirSync } from 'node:fs';
|
|
2
|
+
import { dirname, basename, join } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
export const JOURNAL_APPLICATION_ID = 0x4d524331;
|
|
7
|
+
export const RUNTIME_OWNER = 'MoRemote CLI runtime';
|
|
8
|
+
export function hasCode(error, code) { return error instanceof Error && 'code' in error && error.code === code; }
|
|
9
|
+
export function sameResource(left, right) { return left.dev === right.dev && left.ino === right.ino; }
|
|
10
|
+
export function inspectResource(path, kind, optional = false, privateMode = true) {
|
|
11
|
+
let stat;
|
|
12
|
+
try {
|
|
13
|
+
stat = lstatSync(path);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (optional && hasCode(error, 'ENOENT'))
|
|
17
|
+
return null;
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
if (stat.isSymbolicLink() || !(kind === 'file' ? stat.isFile() : kind === 'directory' ? stat.isDirectory() : stat.isSocket()))
|
|
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');
|
|
28
|
+
return stat;
|
|
29
|
+
}
|
|
30
|
+
export function readPrivateText(path, limit, encoding = 'utf8') {
|
|
31
|
+
const before = inspectResource(path, 'file');
|
|
32
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
33
|
+
try {
|
|
34
|
+
const opened = fstatSync(fd);
|
|
35
|
+
if (!before || !sameResource(before, opened) || !opened.isFile() || opened.nlink !== 1 || opened.size > limit)
|
|
36
|
+
throw Error('FOREIGN_RESOURCE_LIMIT');
|
|
37
|
+
const bytes = Buffer.alloc(limit + 1);
|
|
38
|
+
let size = 0;
|
|
39
|
+
while (size < bytes.length) {
|
|
40
|
+
const count = readSync(fd, bytes, size, bytes.length - size, null);
|
|
41
|
+
if (count === 0)
|
|
42
|
+
break;
|
|
43
|
+
size += count;
|
|
44
|
+
}
|
|
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
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export function assertStateRoot(dir) {
|
|
55
|
+
inspectResource(dir, 'directory');
|
|
56
|
+
if (readPrivateText(join(dir, '.moremote-cli-owner'), 128).text !== 'MoRemote CLI state v1\n')
|
|
57
|
+
throw Error('FOREIGN_DATA_DIRECTORY');
|
|
58
|
+
}
|
|
59
|
+
function object(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
|
|
60
|
+
function integer(value, min, max = Number.MAX_SAFE_INTEGER) { return typeof value === 'number' && Number.isSafeInteger(value) && value >= min && value <= max; }
|
|
61
|
+
function resourceIdentity(value) { return object(value) && Object.keys(value).length === 2 && integer(value.dev, 0) && integer(value.ino, 0); }
|
|
62
|
+
function runtimeOwner(value) {
|
|
63
|
+
return object(value) && value.owner === RUNTIME_OWNER && value.version === 1 && 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) && integer(value.pid, 1, 2147483647) && integer(value.startedAt, 1) && typeof value.token === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value.token) && Buffer.from(value.token, 'base64url').toString('base64url') === value.token;
|
|
64
|
+
}
|
|
65
|
+
export function readRuntimeOwner(path) {
|
|
66
|
+
const file = readPrivateText(path, 2048);
|
|
67
|
+
const value = JSON.parse(file.text);
|
|
68
|
+
if (!runtimeOwner(value))
|
|
69
|
+
throw Error('INVALID_RUNTIME_LOCK');
|
|
70
|
+
if (Object.keys(value).length === 6)
|
|
71
|
+
return { value, identity: file.identity };
|
|
72
|
+
if (Object.keys(value).length === 7 && 'staging' in value && resourceIdentity(value.staging))
|
|
73
|
+
return { value: { ...value, staging: value.staging }, identity: file.identity };
|
|
74
|
+
throw Error('INVALID_RUNTIME_LOCK');
|
|
75
|
+
}
|
|
76
|
+
export function readRuntimeRecord(path) {
|
|
77
|
+
const file = readPrivateText(path, 2048);
|
|
78
|
+
const value = JSON.parse(file.text);
|
|
79
|
+
if (!runtimeOwner(value) || !('socket' in value) || Object.keys(value).length !== 7 || !(value.socket === null || resourceIdentity(value.socket)))
|
|
80
|
+
throw Error('INVALID_RUNTIME_RECORD');
|
|
81
|
+
return { value: { ...value, socket: value.socket }, identity: file.identity };
|
|
82
|
+
}
|
|
83
|
+
export function runtimeMatches(lock, record) {
|
|
84
|
+
return lock.instanceId === record.instanceId && lock.pid === record.pid && lock.startedAt === record.startedAt && lock.token === record.token;
|
|
85
|
+
}
|
|
86
|
+
export function inspectRuntime(dir) {
|
|
87
|
+
const lockPath = join(dir, 'runtime.lock'), recordPath = join(dir, 'runtime.json');
|
|
88
|
+
const lock = inspectResource(lockPath, 'file', true) ? readRuntimeOwner(lockPath) : null;
|
|
89
|
+
const record = inspectResource(recordPath, 'file', true) ? readRuntimeRecord(recordPath) : null;
|
|
90
|
+
const socket = process.platform === 'win32' ? null : inspectResource(join(dir, 'runtime.sock'), 'socket', true);
|
|
91
|
+
const stageNames = readdirSync(dir).filter(name => /^s\.[0-9a-f]{8}$/.test(name));
|
|
92
|
+
if (stageNames.some(name => !lock || name !== 's.' + lock.value.instanceId.slice(0, 8)))
|
|
93
|
+
throw Error('RUNTIME_UNPROVEN_STAGE');
|
|
94
|
+
let staged = null;
|
|
95
|
+
if (lock && process.platform !== 'win32') {
|
|
96
|
+
const path = join(dir, 's.' + lock.value.instanceId.slice(0, 8));
|
|
97
|
+
const stat = inspectResource(path, 'socket', true, false);
|
|
98
|
+
if (stat) {
|
|
99
|
+
// A pre-chmod crash is recoverable only with an inode durably bound to
|
|
100
|
+
// the marked lock. A filename or private mode alone is not ownership.
|
|
101
|
+
if (!lock.value.staging || !sameResource(stat, lock.value.staging) || (stat.mode & 0o7000) !== 0)
|
|
102
|
+
throw Error('RUNTIME_UNPROVEN_STAGE');
|
|
103
|
+
staged = { path, identity: { dev: stat.dev, ino: stat.ino } };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (record && (!lock || !runtimeMatches(lock.value, record.value)))
|
|
107
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
108
|
+
if (socket && !(record?.value.socket && sameResource(socket, record.value.socket)) && !(lock?.value.staging && sameResource(socket, lock.value.staging)))
|
|
109
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
110
|
+
if (record && process.platform !== 'win32' && record.value.socket === null)
|
|
111
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
112
|
+
if (record && process.platform === 'win32' && record.value.socket !== null)
|
|
113
|
+
throw Error('RUNTIME_RESOURCE_COLLISION');
|
|
114
|
+
return { lock, record, socket, staged };
|
|
115
|
+
}
|
|
116
|
+
export function validateJournalPath(path) {
|
|
117
|
+
inspectResource(dirname(path), 'directory');
|
|
118
|
+
const existing = inspectResource(path, 'file', true);
|
|
119
|
+
const sidecars = ['-wal', '-shm', '-journal'].map(suffix => inspectResource(path + suffix, 'file', true));
|
|
120
|
+
if (!existing) {
|
|
121
|
+
if (sidecars.some(Boolean))
|
|
122
|
+
throw Error('FOREIGN_JOURNAL_SIDECAR');
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
126
|
+
try {
|
|
127
|
+
if (!sameResource(existing, fstatSync(fd)))
|
|
128
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
129
|
+
// immutable avoids SQLite creating or updating WAL/SHM while probing ownership.
|
|
130
|
+
const probe = new DatabaseSync(pathToFileURL(path).href + '?mode=ro&immutable=1', { readOnly: true, enableForeignKeyConstraints: false });
|
|
131
|
+
try {
|
|
132
|
+
if (probe.prepare('PRAGMA application_id').get()?.application_id !== JOURNAL_APPLICATION_ID)
|
|
133
|
+
throw Error('FOREIGN_JOURNAL');
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
probe.close();
|
|
137
|
+
}
|
|
138
|
+
const after = inspectResource(path, 'file');
|
|
139
|
+
if (!after || !sameResource(existing, after))
|
|
140
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
141
|
+
return { dev: existing.dev, ino: existing.ino };
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
closeSync(fd);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
export function removeOwnedResource(path, identity, kind = 'file', privateMode = true) {
|
|
148
|
+
let current;
|
|
149
|
+
try {
|
|
150
|
+
current = inspectResource(path, kind, true, privateMode);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
if (!current || !sameResource(current, identity))
|
|
156
|
+
return false;
|
|
157
|
+
unlinkSync(path);
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
160
|
+
export function createPrivateFile(path, text) {
|
|
161
|
+
const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
162
|
+
const identity = fstatSync(fd);
|
|
163
|
+
try {
|
|
164
|
+
writeFileSync(fd, text);
|
|
165
|
+
fsyncSync(fd);
|
|
166
|
+
return { dev: identity.dev, ino: identity.ino };
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
removeOwnedResource(path, identity);
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
closeSync(fd);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
export function openOwnedJournal(path) {
|
|
177
|
+
const existing = validateJournalPath(path);
|
|
178
|
+
const identity = existing ?? createPrivateFile(path, '');
|
|
179
|
+
const current = inspectResource(path, 'file');
|
|
180
|
+
if (!current || !sameResource(current, identity))
|
|
181
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
182
|
+
let db;
|
|
183
|
+
try {
|
|
184
|
+
db = new DatabaseSync(path);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
if (!existing)
|
|
188
|
+
removeOwnedResource(path, identity);
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
if (!existing)
|
|
193
|
+
db.exec(`PRAGMA application_id=${JOURNAL_APPLICATION_ID}`);
|
|
194
|
+
if (db.prepare('PRAGMA application_id').get()?.application_id !== JOURNAL_APPLICATION_ID)
|
|
195
|
+
throw Error('FOREIGN_JOURNAL');
|
|
196
|
+
const after = inspectResource(path, 'file');
|
|
197
|
+
if (!after || !sameResource(after, identity))
|
|
198
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
199
|
+
return db;
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
db.close();
|
|
203
|
+
if (!existing)
|
|
204
|
+
removeOwnedResource(path, identity);
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
export function writePrivateAtomic(path, value) {
|
|
209
|
+
const dir = dirname(path), name = basename(path);
|
|
210
|
+
assertStateRoot(dir);
|
|
211
|
+
if (name !== 'config.json' && name !== 'runtime.json' && name !== 'runtime.lock')
|
|
212
|
+
throw Error('FOREIGN_RESOURCE_NAME');
|
|
213
|
+
const before = inspectResource(path, 'file', true);
|
|
214
|
+
if (before) {
|
|
215
|
+
if (name === 'runtime.lock')
|
|
216
|
+
readRuntimeOwner(path);
|
|
217
|
+
else
|
|
218
|
+
assertStateResource(dir, name);
|
|
219
|
+
}
|
|
220
|
+
const temp = path + '.' + randomUUID() + '.tmp';
|
|
221
|
+
const identity = createPrivateFile(temp, JSON.stringify(value) + '\n');
|
|
222
|
+
try {
|
|
223
|
+
const current = inspectResource(path, 'file', true);
|
|
224
|
+
if (before ? (!current || !sameResource(before, current)) : current !== null)
|
|
225
|
+
throw Error('FOREIGN_RESOURCE_CHANGED');
|
|
226
|
+
renameSync(temp, path);
|
|
227
|
+
if (process.platform !== 'win32') {
|
|
228
|
+
const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
229
|
+
try {
|
|
230
|
+
fsyncSync(fd);
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
closeSync(fd);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return identity;
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
removeOwnedResource(temp, identity);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
export function assertTaskResource(dir, platform = process.platform) {
|
|
243
|
+
if (platform !== 'win32')
|
|
244
|
+
throw Error('FOREIGN_TASK_RESOURCE');
|
|
245
|
+
const text = readPrivateText(join(dir, 'moremote-cli-task.xml'), 131072, 'utf16le').text;
|
|
246
|
+
const marker = 'Managed by moremote-cli; per-user ownership v1; owner=' + createHash('sha256').update(dir).digest('hex');
|
|
247
|
+
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
|
+
throw Error('FOREIGN_TASK_RESOURCE');
|
|
249
|
+
}
|
|
250
|
+
export function assertStateResource(dir, name) {
|
|
251
|
+
const path = join(dir, name);
|
|
252
|
+
if (name === '.moremote-cli-owner') {
|
|
253
|
+
assertStateRoot(dir);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (name === 'journal.sqlite') {
|
|
257
|
+
validateJournalPath(path);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (/^journal\.sqlite-(wal|shm|journal)$/.test(name)) {
|
|
261
|
+
validateJournalPath(join(dir, 'journal.sqlite'));
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (name === 'runtime.lock' || name === 'runtime.json' || name === 'runtime.sock') {
|
|
265
|
+
inspectRuntime(dir);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (name === 'managed') {
|
|
269
|
+
inspectResource(path, 'directory');
|
|
270
|
+
if (readPrivateText(join(path, '.moremote-cli-managed-owner'), 128).text !== 'MoRemote CLI managed package v1\n')
|
|
271
|
+
throw Error('FOREIGN_MANAGED_DIRECTORY');
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (/^s\.[0-9a-f]{8}$/.test(name)) {
|
|
275
|
+
const runtime = inspectRuntime(dir);
|
|
276
|
+
if (!runtime.staged || runtime.staged.path !== path)
|
|
277
|
+
throw Error('RUNTIME_UNPROVEN_STAGE');
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (name === 'config.json' || /^config\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
|
|
281
|
+
const value = JSON.parse(readPrivateText(path, 131072).text);
|
|
282
|
+
if (!object(value) || value.version !== 1 || typeof value.clientId !== 'string' || !value.clientId.startsWith('moremote-cli-') || value.clientId.length > 256)
|
|
283
|
+
throw Error('FOREIGN_CONFIG');
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (/^runtime\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
|
|
287
|
+
readRuntimeRecord(path);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if (/^runtime\.lock\.[0-9a-f-]{36}\.tmp$/.test(name)) {
|
|
291
|
+
readRuntimeOwner(path);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (name === 'moremote-cli-task.xml') {
|
|
295
|
+
assertTaskResource(dir);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
throw Error('FOREIGN_DATA_DIRECTORY');
|
|
299
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Pair } from './config.js';
|
|
2
|
+
import { type Attention } from './official-client.js';
|
|
3
|
+
import { OperationJournal, type Occurrence } from './journal.js';
|
|
4
|
+
export declare function queueAttention(journal: OperationJournal, pair: Pair, event: Attention & {
|
|
5
|
+
sourceFingerprint?: string;
|
|
6
|
+
occurrence?: Occurrence;
|
|
7
|
+
}, now?: number): Promise<void>;
|
|
8
|
+
export declare function runRuntime(dir: string, version?: string): Promise<void>;
|