@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.
Files changed (45) hide show
  1. package/README.md +85 -7
  2. package/bin/moremote-cli.js +11 -4
  3. package/dist/activity.d.ts +79 -0
  4. package/dist/activity.js +193 -0
  5. package/dist/cli.js +36 -41
  6. package/dist/cloud-client.d.ts +13 -4
  7. package/dist/cloud-client.js +60 -15
  8. package/dist/config.d.ts +7 -0
  9. package/dist/config.js +23 -4
  10. package/dist/control.d.ts +1 -0
  11. package/dist/control.js +9 -0
  12. package/dist/crypto.d.ts +1 -1
  13. package/dist/crypto.js +2 -2
  14. package/dist/enrollment-files.d.ts +37 -0
  15. package/dist/enrollment-files.js +225 -0
  16. package/dist/enrollment-protocol.d.ts +50 -0
  17. package/dist/enrollment-protocol.js +44 -0
  18. package/dist/journal.js +2 -1
  19. package/dist/local-enrollment.d.ts +25 -0
  20. package/dist/local-enrollment.js +160 -0
  21. package/dist/official-client.d.ts +87 -6
  22. package/dist/official-client.js +135 -32
  23. package/dist/operations.d.ts +1 -0
  24. package/dist/operations.js +24 -4
  25. package/dist/projection.d.ts +7 -2
  26. package/dist/resources.d.ts +2 -1
  27. package/dist/resources.js +69 -32
  28. package/dist/runtime.d.ts +10 -1
  29. package/dist/runtime.js +111 -10
  30. package/dist/service.js +43 -8
  31. package/dist/setup-upgrade.d.ts +2 -0
  32. package/dist/setup-upgrade.js +65 -0
  33. package/dist/setup.d.ts +12 -0
  34. package/dist/setup.js +38 -0
  35. package/dist/supervisor.d.ts +1 -0
  36. package/dist/supervisor.js +44 -1
  37. package/docs/README.md +4 -3
  38. package/docs/STATE.md +327 -10
  39. package/docs/configuration.md +119 -5
  40. package/docs/plans/2026-11-11-native-service-acceptance.md +168 -0
  41. package/docs/specs/03-api-contract.md +122 -2
  42. package/docs/specs/04-control-and-receipt-lifecycle.md +12 -0
  43. package/docs/specs/05-endpoint-and-lifecycle.md +126 -2
  44. package/docs/specs/06-managed-updates.md +34 -1
  45. package/package.json +2 -2
@@ -3,12 +3,14 @@ import { LIMITS, object } from './limits.js';
3
3
  export class CloudError extends Error {
4
4
  status;
5
5
  retryAt;
6
+ pauseScope;
6
7
  code;
7
- constructor(code, status, retryAt) {
8
+ constructor(code, status, retryAt, pauseScope = 'origin') {
8
9
  const safe = /^[A-Z0-9_]{1,64}$/.test(code) ? code : 'CLOUD_HTTP_ERROR';
9
10
  super(safe);
10
11
  this.status = status;
11
12
  this.retryAt = retryAt;
13
+ this.pauseScope = pauseScope;
12
14
  this.code = safe;
13
15
  }
14
16
  }
@@ -31,6 +33,20 @@ function retryDeadline(value, status, now) {
31
33
  return;
32
34
  return Math.min(date, now + maxDelay);
33
35
  }
36
+ function recoveryRequest(method, path) {
37
+ const parts = path.split('/').filter(Boolean), suffix = parts.slice(2);
38
+ if (parts[0] !== 'pairs')
39
+ return false;
40
+ if (method === 'DELETE' && !suffix.length)
41
+ return true;
42
+ if (suffix[0] === 'controls')
43
+ return suffix.length === 1 && ['GET', 'POST'].includes(method) || suffix.length === 2 && method === 'GET' || suffix.length === 3 && suffix[2] === 'receipt' && method === 'POST';
44
+ if (suffix[0] === 'commands')
45
+ return suffix.length === 2 && method === 'GET' || suffix.length === 3 && suffix[2] === 'receipt' && method === 'POST';
46
+ return suffix[0] === 'attention' && suffix.length === 3 && suffix[2] === 'resolve' && method === 'POST'
47
+ || suffix[0] === 'activities' && (suffix.length === 2 && method === 'DELETE' || suffix.length === 3 && suffix[2] === 'end' && method === 'PUT')
48
+ || suffix[0] === 'widget-device' && suffix.length === 2 && method === 'DELETE';
49
+ }
34
50
  export class CloudClient {
35
51
  pairId;
36
52
  token;
@@ -48,9 +64,10 @@ export class CloudClient {
48
64
  this.cycleFence = cycleFence;
49
65
  this.origin = validateOrigin(origin, allowLoopback);
50
66
  }
51
- async request(method, path, body) {
67
+ async request(method, path, body, signal) {
52
68
  // A runtime cycle that observed a pause must reacquire controls in a new
53
69
  // cycle, even if an intervening SDK call outlasted the wall-clock deadline.
70
+ signal?.throwIfAborted();
54
71
  if (this.cycleFence?.error)
55
72
  throw this.cycleFence.error;
56
73
  const paused = this.retryState.error;
@@ -60,17 +77,22 @@ export class CloudClient {
60
77
  throw paused;
61
78
  }
62
79
  this.retryState.error = undefined;
80
+ if (!recoveryRequest(method, path)) {
81
+ if (this.cycleFence?.normalError)
82
+ throw this.cycleFence.normalError;
83
+ const normal = this.retryState.normalError;
84
+ if (normal?.retryAt !== undefined && normal.retryAt > Date.now()) {
85
+ if (this.cycleFence)
86
+ this.cycleFence.normalError = normal;
87
+ throw normal;
88
+ }
89
+ this.retryState.normalError = undefined;
90
+ }
63
91
  const json = body === undefined ? undefined : JSON.stringify(body);
64
92
  if (json && Buffer.byteLength(json) > LIMITS.envelopeBytes)
65
93
  throw Error('REQUEST_LIMIT');
66
- const response = await this.fetcher(this.origin + '/v1' + path, { method, headers: { authorization: 'Bearer ' + this.token, ...(json ? { 'content-type': 'application/json' } : {}) }, body: json, signal: AbortSignal.any([AbortSignal.timeout(20000), ...(this.signal ? [this.signal] : [])]), redirect: 'error' });
94
+ const response = await this.fetcher(this.origin + '/v1' + path, { method, headers: { authorization: 'Bearer ' + this.token, ...(json ? { 'content-type': 'application/json' } : {}) }, body: json, signal: AbortSignal.any([AbortSignal.timeout(20000), ...(this.signal ? [this.signal] : []), ...(signal ? [signal] : [])]), redirect: 'error' });
67
95
  const retryAt = retryDeadline(response.headers.get('Retry-After'), response.status, Date.now());
68
- if (retryAt !== undefined) {
69
- const failure = new CloudError('CLOUD_HTTP_ERROR', response.status, retryAt);
70
- this.retryState.error = failure;
71
- if (this.cycleFence)
72
- this.cycleFence.error = failure;
73
- }
74
96
  const reader = response.body?.getReader();
75
97
  let size = 0;
76
98
  const chunks = [];
@@ -86,6 +108,15 @@ export class CloudClient {
86
108
  chunks.push(r.value);
87
109
  }
88
110
  }
111
+ catch (error) {
112
+ if (retryAt !== undefined) {
113
+ const failure = new CloudError('CLOUD_HTTP_ERROR', response.status, retryAt);
114
+ this.retryState.error = failure;
115
+ if (this.cycleFence)
116
+ this.cycleFence.error = failure;
117
+ }
118
+ throw error;
119
+ }
89
120
  finally {
90
121
  await reader.cancel();
91
122
  }
@@ -95,22 +126,33 @@ export class CloudClient {
95
126
  result = object(JSON.parse(Buffer.concat(chunks).toString('utf8')));
96
127
  }
97
128
  catch {
129
+ if (retryAt !== undefined) {
130
+ const failure = new CloudError('CLOUD_HTTP_ERROR', response.status, retryAt);
131
+ this.retryState.error = failure;
132
+ if (this.cycleFence)
133
+ this.cycleFence.error = failure;
134
+ }
98
135
  throw Error('INVALID_CLOUD_RESPONSE');
99
136
  }
100
137
  if (!response.ok || result.ok !== true) {
101
- const error = result.error && typeof result.error === 'object' ? result.error : {};
102
- const failure = new CloudError(typeof error.code === 'string' ? error.code : 'CLOUD_HTTP_ERROR', response.status, retryAt);
138
+ const error = result.error && typeof result.error === 'object' ? result.error : {}, resetHeader = response.headers.get('x-moremote-reset'), reset = Number(resetHeader);
139
+ // Only an explicit, internally consistent daily normal-quota rejection can
140
+ // leave recovery open. Missing/malformed hints and outages remain origin-wide.
141
+ const normalOnly = response.status === 429 && error.code === 'daily_work_limit' && response.headers.get('x-moremote-budget') === 'normal'
142
+ && retryAt !== undefined && resetHeader !== null && /^\d{1,16}$/.test(resetHeader) && Number.isSafeInteger(reset) && reset > Date.now() && Math.abs(reset - retryAt) <= 1000;
143
+ const failure = new CloudError(typeof error.code === 'string' ? error.code : 'CLOUD_HTTP_ERROR', response.status, retryAt, normalOnly ? 'normal' : 'origin');
103
144
  if (retryAt !== undefined) {
104
- this.retryState.error = failure;
145
+ const field = normalOnly ? 'normalError' : 'error';
146
+ this.retryState[field] = failure;
105
147
  if (this.cycleFence)
106
- this.cycleFence.error = failure;
148
+ this.cycleFence[field] = failure;
107
149
  }
108
150
  throw failure;
109
151
  }
110
152
  return result;
111
153
  }
112
154
  path(suffix = '') { return '/pairs/' + this.pairId + suffix; }
113
- create(body) { return this.request('POST', '/pairs', body); }
155
+ create(body, signal) { return this.request('POST', '/pairs', body, signal); }
114
156
  pair() { return this.request('GET', this.path()); }
115
157
  activate(body) { return this.request('POST', this.path('/activate'), body); }
116
158
  revoke() { return this.request('DELETE', this.path()); }
@@ -119,10 +161,13 @@ export class CloudClient {
119
161
  async dispatch(id) { const r = await this.request('POST', this.path('/commands/' + id + '/dispatch'), {}); if (typeof r.dispatchAllowed !== 'boolean')
120
162
  throw Error('INVALID_DISPATCH_RESPONSE'); return { dispatchAllowed: r.dispatchAllowed }; }
121
163
  receipt(id, body) { return this.request('POST', this.path('/commands/' + id + '/receipt'), body); }
122
- state(envelope) { return this.request('PUT', this.path('/state'), { envelope }); }
164
+ state(envelope, widgetFingerprint) { return this.request('PUT', this.path('/state'), { envelope, ...(widgetFingerprint ? { widgetFingerprint } : {}) }); }
123
165
  attention(body) { return this.request('POST', this.path('/attention'), body); }
124
166
  async controls() { const result = await this.request('GET', this.path('/controls')); if (!Array.isArray(result.controls) || result.controls.length > 100)
125
167
  throw Error('INVALID_CONTROL_PAGE'); return result.controls.map(row => object(row).envelope).filter(Boolean); }
126
168
  controlReceipt(id, body) { return this.request('POST', this.path('/controls/' + id + '/receipt'), body); }
127
169
  resolveAttention(id, resolvedAt) { return this.request('POST', this.path('/attention/' + id + '/resolve'), { resolvedAt }); }
170
+ async activities(signal) { const result = await this.request('GET', this.path('/activities'), undefined, signal); if (!Array.isArray(result.subscriptions) || result.subscriptions.length > 8)
171
+ throw Error('INVALID_ACTIVITY_PAGE'); return result.subscriptions; }
172
+ activityState(id, body, signal) { return this.request('PUT', this.path('/activities/' + id + (body.event === 'end' ? '/end' : '/state')), body, signal); }
128
173
  }
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { OperationJournal } from './journal.js';
2
+ import { type EnrollmentRecord } from './enrollment-protocol.js';
2
3
  export interface Pair {
3
4
  pairId: string;
4
5
  rootKey: string;
@@ -13,6 +14,8 @@ export interface Pair {
13
14
  daemonServerId?: string;
14
15
  revokedAt?: number;
15
16
  relayRetiredAt?: number;
17
+ automaticClientId?: string;
18
+ automaticRequestId?: string;
16
19
  }
17
20
  export interface Config {
18
21
  version: 1;
@@ -24,6 +27,10 @@ export interface Config {
24
27
  cloudEnabled: boolean;
25
28
  daemonServerId?: string;
26
29
  pairs: Pair[];
30
+ localEnrollment?: {
31
+ home: string;
32
+ };
33
+ enrollmentRequests?: EnrollmentRecord[];
27
34
  }
28
35
  export declare function dataDirectory(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, home?: string): string;
29
36
  export declare function validateOrigin(value: string, allowLoopback: boolean): string;
package/dist/config.js CHANGED
@@ -4,7 +4,8 @@ import { mkdir, readdir } from 'node:fs/promises';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { decode } from './crypto.js';
6
6
  import { UUID, LIMITS } from './limits.js';
7
- import { assertStateRoot, assertStateResource, inspectResource, readPrivateText, createPrivateFile, writePrivateAtomic } from './resources.js';
7
+ import { CONFIG_BYTES, assertStateRoot, assertStateResource, inspectResource, readPrivateText, createPrivateFile, writePrivateAtomic } from './resources.js';
8
+ import { validateEnrollmentRecords, requestFingerprint } from './enrollment-protocol.js';
8
9
  export function dataDirectory(env = process.env, platform = process.platform, home = homedir()) { return resolve(env.MOREMOTE_CLI_HOME || (platform === 'win32' ? join(env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'MoRemoteCLI') : platform === 'darwin' ? join(home, 'Library', 'Application Support', 'MoRemoteCLI') : join(env.XDG_STATE_HOME || join(home, '.local', 'state'), 'moremote-cli'))); }
9
10
  export function validateOrigin(value, allowLoopback) { const u = new URL(value); if (u.username || u.password || u.search || u.hash || u.pathname !== '/')
10
11
  throw Error('INVALID_API_ORIGIN'); if (u.protocol !== 'https:' && !(allowLoopback && u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname)))
@@ -37,20 +38,37 @@ export async function loadConfig(dir) {
37
38
  let raw;
38
39
  try {
39
40
  assertStateRoot(dir);
40
- raw = readPrivateText(join(dir, 'config.json'), 131072).text;
41
+ raw = readPrivateText(join(dir, 'config.json'), CONFIG_BYTES).text;
41
42
  }
42
43
  catch (e) {
43
44
  if (e.code !== 'ENOENT')
44
45
  throw e;
45
46
  return { version: 1, clientId: 'moremote-cli-' + randomUUID(), paseoHome: process.env.PASEO_HOME || join(homedir(), '.paseo'), allowLoopbackHttp: false, cloudEnabled: false, pairs: [] };
46
47
  }
47
- if (Buffer.byteLength(raw) > 131072)
48
+ if (Buffer.byteLength(raw) > CONFIG_BYTES)
48
49
  throw Error('CONFIG_LIMIT');
49
50
  const c = JSON.parse(raw);
50
51
  if (c.version !== 1 || typeof c.clientId !== 'string' || !c.clientId.startsWith('moremote-cli-') || c.clientId.length > 256 || typeof c.paseoHome !== 'string' || !c.paseoHome || c.paseoHome.length > 4096 || c.target !== undefined && (typeof c.target !== 'string' || !c.target || c.target.length > 16384) || !Array.isArray(c.pairs) || c.pairs.length > 16 || typeof c.cloudEnabled !== 'boolean' || typeof c.allowLoopbackHttp !== 'boolean')
51
52
  throw Error('INVALID_CONFIG');
52
53
  if (c.apiOrigin)
53
54
  c.apiOrigin = validateOrigin(c.apiOrigin, c.allowLoopbackHttp);
55
+ if (c.localEnrollment && (typeof c.localEnrollment.home !== 'string' || !c.localEnrollment.home || c.localEnrollment.home.length > 4096 || resolve(c.localEnrollment.home) !== c.localEnrollment.home))
56
+ throw Error('INVALID_ENROLLMENT_HOME');
57
+ if (c.enrollmentRequests !== undefined) {
58
+ validateEnrollmentRecords(c.enrollmentRequests);
59
+ for (const record of c.enrollmentRequests) {
60
+ validateOrigin(record.offer.apiOrigin, false);
61
+ const pair = c.pairs.find(pair => pair.pairId === record.pairId);
62
+ if (!pair || pair.automaticClientId !== record.request.clientId || pair.automaticRequestId !== record.request.id || pair.daemonServerId !== record.request.daemonServerId || pair.rootKey !== record.offer.rootKey || pair.apiOrigin !== record.offer.apiOrigin || pair.expiresAt !== record.offer.expiresAt || JSON.parse(record.createBytes).hostTokenHash !== requestFingerprint(pair.hostToken) || pair.enrollmentToken !== undefined && pair.enrollmentToken !== record.offer.enrollmentToken)
63
+ throw Error('INVALID_ENROLLMENT_RECORD');
64
+ }
65
+ }
66
+ for (const pair of c.pairs)
67
+ if (pair.automaticClientId !== undefined && !UUID.test(pair.automaticClientId))
68
+ throw Error('INVALID_AUTOMATIC_CLIENT');
69
+ for (const pair of c.pairs)
70
+ if (pair.automaticRequestId !== undefined && !UUID.test(pair.automaticRequestId))
71
+ throw Error('INVALID_AUTOMATIC_REQUEST');
54
72
  const identities = new Set();
55
73
  for (const p of c.pairs) {
56
74
  if (!UUID.test(p.pairId) || identities.has(p.pairId) || typeof p.active !== 'boolean' || p.expiresAt !== undefined && (!Number.isSafeInteger(p.expiresAt) || p.expiresAt < 0) || p.revokedAt !== undefined && (!Number.isSafeInteger(p.revokedAt) || p.revokedAt < 0) || p.relayRetiredAt !== undefined && (!Number.isSafeInteger(p.relayRetiredAt) || p.relayRetiredAt < 0))
@@ -65,4 +83,5 @@ export async function loadConfig(dir) {
65
83
  }
66
84
  export async function saveConfig(dir, config) { const a = resolve(dir), b = resolve(config.paseoHome); const left = process.platform === 'win32' ? a.toLowerCase() : a, right = process.platform === 'win32' ? b.toLowerCase() : b; if (left === right || left.startsWith(right + sep) || right.startsWith(left + sep))
67
85
  throw Error('OFFICIAL_DATA_OVERLAP'); await privateDirectory(dir); await atomicJson(join(dir, 'config.json'), config); }
68
- export function pruneRetiredPairs(config, now = Date.now(), journal) { const before = config.pairs.length; config.pairs = config.pairs.filter(p => { const retiredAt = p.revokedAt === undefined ? p.relayRetiredAt : Math.max(p.revokedAt, p.relayRetiredAt ?? 0); return retiredAt === undefined ? !(p.active === false && p.expiresAt !== undefined && now >= p.expiresAt + LIMITS.retentionMs) : !journal || now < journal.retirementDeadline(p.pairId, retiredAt); }); return before !== config.pairs.length; }
86
+ export function pruneRetiredPairs(config, now = Date.now(), journal) { const before = config.pairs.length; config.pairs = config.pairs.filter(p => { if (config.enrollmentRequests?.some(record => record.pairId === p.pairId))
87
+ return true; const retiredAt = p.revokedAt === undefined ? p.relayRetiredAt : Math.max(p.revokedAt, p.relayRetiredAt ?? 0); return retiredAt === undefined ? !(p.active === false && p.expiresAt !== undefined && now >= p.expiresAt + LIMITS.retentionMs) : !journal || now < journal.retirementDeadline(p.pairId, retiredAt); }); return before !== config.pairs.length; }
package/dist/control.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export declare function controlEndpoint(dir: string): string;
2
+ export declare function runtimeHasLiveOwner(dir: string): boolean;
2
3
  export declare function requestControl(dir: string, action: 'status' | 'stop'): Promise<Record<string, unknown> | null>;
3
4
  export declare function ownRuntime(dir: string, status: () => unknown, stop: () => void): Promise<() => Promise<void>>;
package/dist/control.js CHANGED
@@ -28,6 +28,15 @@ function running(pid) {
28
28
  throw error;
29
29
  }
30
30
  }
31
+ export function runtimeHasLiveOwner(dir) {
32
+ if (!inspectResource(dir, 'directory', true))
33
+ return false;
34
+ if (readdirSync(dir).length === 0)
35
+ return false;
36
+ assertStateRoot(dir);
37
+ const { lock } = inspectRuntime(dir);
38
+ return lock !== null && running(lock.value.pid);
39
+ }
31
40
  export async function requestControl(dir, action) {
32
41
  if (!inspectResource(dir, 'directory', true))
33
42
  return null;
package/dist/crypto.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type Channel = 'enrollment' | 'activation' | 'command' | 'receipt' | 'state' | 'attention' | 'control' | 'controlReceipt';
1
+ export type Channel = 'enrollment' | 'activation' | 'command' | 'receipt' | 'state' | 'attention' | 'control' | 'controlReceipt' | 'activityInterest' | 'activityState';
2
2
  export interface Metadata {
3
3
  version: 1;
4
4
  pairId: string;
package/dist/crypto.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { webcrypto, randomBytes } from 'node:crypto';
2
2
  import { LIMITS, UUID, object, exact } from './limits.js';
3
3
  const subtle = webcrypto.subtle;
4
- const channels = ['enrollment', 'activation', 'command', 'receipt', 'state', 'attention', 'control', 'controlReceipt'];
4
+ const channels = ['enrollment', 'activation', 'command', 'receipt', 'state', 'attention', 'control', 'controlReceipt', 'activityInterest', 'activityState'];
5
5
  function bytes(v) { return Uint8Array.from(v); }
6
6
  export function decode(value, length) { if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))
7
7
  throw Error('INVALID_BASE64URL'); const b = Buffer.from(value, 'base64url'); if (b.toString('base64url') !== value || (length !== undefined && b.length !== length))
@@ -15,7 +15,7 @@ export function validateEnvelope(input, now, allowExpired = false) {
15
15
  throw Error('RECEIPT_LIMIT');
16
16
  if (!Number.isSafeInteger(e.issuedAt) || !Number.isSafeInteger(e.expiresAt) || Number(e.issuedAt) < 0 || Number(e.expiresAt) <= Number(e.issuedAt))
17
17
  throw Error('INVALID_TIME');
18
- const ttl = e.channel === 'command' || e.channel === 'control' ? LIMITS.commandMs : LIMITS.enrollmentMs;
18
+ const ttl = e.channel === 'activityInterest' ? 8 * 60 * 60 * 1000 : e.channel === 'command' || e.channel === 'control' ? LIMITS.commandMs : LIMITS.enrollmentMs;
19
19
  if (Number(e.expiresAt) - Number(e.issuedAt) > ttl || Number(e.issuedAt) > now + LIMITS.futureMs || (!allowExpired && Number(e.expiresAt) <= now))
20
20
  throw Error('EXPIRED_OR_FUTURE');
21
21
  decode(e.nonce, 12);
@@ -0,0 +1,37 @@
1
+ import { type ResourceIdentity } from './resources.js';
2
+ import { type EnrollmentRecord, type EnrollmentResponse } from './enrollment-protocol.js';
3
+ export declare function discoveryDirectory(home: string, daemonServerId: string): string;
4
+ export interface DiscoveryOptions {
5
+ home: string;
6
+ stateDirectory: string;
7
+ daemonServerId: string;
8
+ instanceId?: string;
9
+ isAlive?: (pid: number) => boolean;
10
+ }
11
+ export declare class EnrollmentFiles {
12
+ private options;
13
+ readonly path: string;
14
+ readonly instanceId: string;
15
+ private lock;
16
+ private measuredAt;
17
+ private enabled;
18
+ private readonly hostMarker;
19
+ constructor(options: DiscoveryOptions);
20
+ open(records?: EnrollmentRecord[]): void;
21
+ private assertOwner;
22
+ publish(enabled: boolean, apiOrigin: string, now: number): void;
23
+ requestNames(): string[];
24
+ readRequest(name: string): {
25
+ text: string;
26
+ identity: {
27
+ dev: number;
28
+ ino: number;
29
+ };
30
+ };
31
+ private responseIdentity;
32
+ assertResponseAvailable(id: string, record?: EnrollmentRecord): void;
33
+ writeResponse(record: EnrollmentRecord, response: EnrollmentResponse): void;
34
+ removeResponse(record: EnrollmentRecord): void;
35
+ removeRequest(name: string, identity: ResourceIdentity): void;
36
+ close(records?: EnrollmentRecord[]): void;
37
+ }
@@ -0,0 +1,225 @@
1
+ import { mkdirSync, readdirSync, renameSync, openSync, closeSync, fsyncSync, constants } from 'node:fs';
2
+ import { join, resolve, dirname } from 'node:path';
3
+ import { randomUUID, createHash } from 'node:crypto';
4
+ import { createPrivateFile, hasCode, inspectResource, readPrivateText, removeOwnedResource, sameResource } from './resources.js';
5
+ import { object, exact, UUID } from './limits.js';
6
+ import { DISCOVERY_NAME, descriptorLifetime, descriptorRenewal } from './enrollment-protocol.js';
7
+ import { validateOrigin } from './config.js';
8
+ const marker = '.moremote-cli-owner';
9
+ const rootMarker = 'MoRemote CLI discovery v1\n';
10
+ function alive(pid) { try {
11
+ process.kill(pid, 0);
12
+ return true;
13
+ }
14
+ catch (error) {
15
+ if (hasCode(error, 'ESRCH'))
16
+ return false;
17
+ throw error;
18
+ } }
19
+ function assertDirectory(path, text) {
20
+ inspectResource(path, 'directory');
21
+ if (readPrivateText(join(path, marker), 2048).text !== text)
22
+ throw Error('FOREIGN_DISCOVERY_DIRECTORY');
23
+ }
24
+ function directory(path, text) {
25
+ try {
26
+ mkdirSync(path, { mode: 0o700 });
27
+ createPrivateFile(join(path, marker), text);
28
+ }
29
+ catch (error) {
30
+ if (!hasCode(error, 'EEXIST'))
31
+ throw error;
32
+ }
33
+ assertDirectory(path, text);
34
+ }
35
+ function atomic(path, value, limit) {
36
+ const bytes = JSON.stringify(value);
37
+ if (Buffer.byteLength(bytes) > limit)
38
+ throw Error('ENROLLMENT_RESPONSE_LIMIT');
39
+ const before = inspectResource(path, 'file', true), temporary = path + '.' + randomUUID() + '.tmp';
40
+ const identity = createPrivateFile(temporary, bytes);
41
+ try {
42
+ const current = inspectResource(path, 'file', true);
43
+ if (before ? (!current || !sameResource(before, current)) : current !== null)
44
+ throw Error('DISCOVERY_RESOURCE_CHANGED');
45
+ renameSync(temporary, path);
46
+ if (process.platform !== 'win32') {
47
+ const fd = openSync(dirname(path), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
48
+ try {
49
+ fsyncSync(fd);
50
+ }
51
+ finally {
52
+ closeSync(fd);
53
+ }
54
+ }
55
+ }
56
+ finally {
57
+ removeOwnedResource(temporary, identity);
58
+ }
59
+ }
60
+ function validateDescriptor(path, daemon) {
61
+ const old = object(JSON.parse(readPrivateText(path, 4096).text));
62
+ exact(old, ['version', 'daemonServerId', 'instanceId', 'apiOrigin', 'enabled', 'measuredAt', 'expiresAt']);
63
+ if (old.version !== 1 || old.daemonServerId !== daemon || typeof old.instanceId !== 'string' || !UUID.test(old.instanceId) || typeof old.apiOrigin !== 'string' || typeof old.enabled !== 'boolean' || !Number.isSafeInteger(old.measuredAt) || Number(old.measuredAt) < 0 || Number(old.expiresAt) !== Number(old.measuredAt) + descriptorLifetime)
64
+ throw Error('FOREIGN_DISCOVERY_DESCRIPTOR');
65
+ if (validateOrigin(old.apiOrigin, false) !== old.apiOrigin)
66
+ throw Error('FOREIGN_DISCOVERY_DESCRIPTOR');
67
+ }
68
+ export function discoveryDirectory(home, daemonServerId) { return join(resolve(home), DISCOVERY_NAME, createHash('sha256').update(daemonServerId, 'utf8').digest('hex')); }
69
+ export class EnrollmentFiles {
70
+ options;
71
+ path;
72
+ instanceId;
73
+ lock;
74
+ measuredAt = -Infinity;
75
+ enabled;
76
+ hostMarker;
77
+ constructor(options) {
78
+ this.options = options;
79
+ this.instanceId = options.instanceId ?? randomUUID();
80
+ this.path = discoveryDirectory(options.home, options.daemonServerId);
81
+ this.hostMarker = JSON.stringify({ owner: 'MoRemote CLI discovery host', version: 1, daemonServerId: options.daemonServerId, stateDirectory: resolve(options.stateDirectory) }) + '\n';
82
+ }
83
+ open(records = []) {
84
+ if (this.lock) {
85
+ this.assertOwner();
86
+ return;
87
+ }
88
+ const home = resolve(this.options.home), root = join(home, DISCOVERY_NAME), daemon = this.options.daemonServerId;
89
+ inspectResource(home, 'directory', false, false);
90
+ directory(root, rootMarker);
91
+ for (const name of readdirSync(root)) {
92
+ if (name === marker)
93
+ continue;
94
+ if (!/^[0-9a-f]{64}$/.test(name))
95
+ throw Error('FOREIGN_DISCOVERY_DIRECTORY');
96
+ inspectResource(join(root, name), 'directory');
97
+ }
98
+ directory(this.path, this.hostMarker);
99
+ const stages = [];
100
+ for (const name of readdirSync(this.path)) {
101
+ if ([marker, 'runtime.lock', 'descriptor.json', 'requests', 'responses'].includes(name))
102
+ continue;
103
+ if (/^descriptor\.json\.[0-9a-f-]{36}\.tmp$/.test(name) && UUID.test(name.slice(16, -4))) {
104
+ stages.push({ path: join(this.path, name) });
105
+ continue;
106
+ }
107
+ throw Error('FOREIGN_DISCOVERY_RESOURCE');
108
+ }
109
+ for (const child of ['requests', 'responses']) {
110
+ directory(join(this.path, child), 'MoRemote CLI discovery ' + child + ' v1\n');
111
+ for (const name of readdirSync(join(this.path, child))) {
112
+ if (name === marker)
113
+ continue;
114
+ if (child === 'responses' && /^[0-9a-f-]{36}\.json\.[0-9a-f-]{36}\.tmp$/.test(name) && UUID.test(name.slice(0, 36)) && UUID.test(name.slice(42, -4))) {
115
+ stages.push({ path: join(this.path, child, name), id: name.slice(0, 36) });
116
+ continue;
117
+ }
118
+ if (!/^[0-9a-f-]{36}\.json$/.test(name) || !UUID.test(name.slice(0, -5)))
119
+ throw Error('FOREIGN_DISCOVERY_RESOURCE');
120
+ inspectResource(join(this.path, child, name), 'file', false, child !== 'requests');
121
+ }
122
+ }
123
+ const lockPath = join(this.path, 'runtime.lock');
124
+ if (inspectResource(lockPath, 'file', true)) {
125
+ const previous = readPrivateText(lockPath, 2048), owner = object(JSON.parse(previous.text));
126
+ exact(owner, ['owner', 'version', 'instanceId', 'pid', 'stateDirectory']);
127
+ if (owner.owner !== 'MoRemote CLI discovery runtime' || owner.version !== 1 || typeof owner.instanceId !== 'string' || !UUID.test(owner.instanceId) || !Number.isSafeInteger(owner.pid) || Number(owner.pid) < 1 || Number(owner.pid) > 2147483647 || owner.stateDirectory !== resolve(this.options.stateDirectory))
128
+ throw Error('FOREIGN_DISCOVERY_LOCK');
129
+ if ((this.options.isAlive ?? alive)(Number(owner.pid)))
130
+ throw Error('DISCOVERY_ALREADY_RUNNING');
131
+ if (!removeOwnedResource(lockPath, previous.identity))
132
+ throw Error('DISCOVERY_RESOURCE_CHANGED');
133
+ }
134
+ this.lock = createPrivateFile(lockPath, JSON.stringify({ owner: 'MoRemote CLI discovery runtime', version: 1, instanceId: this.instanceId, pid: process.pid, stateDirectory: resolve(this.options.stateDirectory) }));
135
+ try {
136
+ for (const stage of stages) {
137
+ if (stage.id)
138
+ this.responseIdentity(stage.id, records.find(record => record.request.id === stage.id), stage.path);
139
+ else
140
+ validateDescriptor(stage.path, daemon);
141
+ const file = readPrivateText(stage.path, 8192);
142
+ if (!removeOwnedResource(stage.path, file.identity))
143
+ throw Error('DISCOVERY_RESOURCE_CHANGED');
144
+ }
145
+ }
146
+ catch (error) {
147
+ removeOwnedResource(lockPath, this.lock);
148
+ this.lock = undefined;
149
+ throw error;
150
+ }
151
+ }
152
+ assertOwner() {
153
+ if (!this.lock)
154
+ throw Error('DISCOVERY_NOT_OWNED');
155
+ assertDirectory(join(resolve(this.options.home), DISCOVERY_NAME), rootMarker);
156
+ assertDirectory(this.path, this.hostMarker);
157
+ for (const child of ['requests', 'responses'])
158
+ assertDirectory(join(this.path, child), 'MoRemote CLI discovery ' + child + ' v1\n');
159
+ const lock = readPrivateText(join(this.path, 'runtime.lock'), 2048);
160
+ if (!sameResource(lock.identity, this.lock) || object(JSON.parse(lock.text)).instanceId !== this.instanceId)
161
+ throw Error('DISCOVERY_RESOURCE_CHANGED');
162
+ }
163
+ publish(enabled, apiOrigin, now) {
164
+ this.assertOwner();
165
+ if (now - this.measuredAt < descriptorRenewal && this.enabled === enabled)
166
+ return;
167
+ const path = join(this.path, 'descriptor.json');
168
+ if (inspectResource(path, 'file', true))
169
+ validateDescriptor(path, this.options.daemonServerId);
170
+ const descriptor = { version: 1, daemonServerId: this.options.daemonServerId, instanceId: this.instanceId, apiOrigin, enabled, measuredAt: now, expiresAt: now + descriptorLifetime };
171
+ atomic(path, descriptor, 4096);
172
+ this.measuredAt = now;
173
+ this.enabled = enabled;
174
+ }
175
+ requestNames() { this.assertOwner(); return readdirSync(join(this.path, 'requests')).filter(name => name !== marker).sort(); }
176
+ readRequest(name) {
177
+ this.assertOwner();
178
+ if (!/^[0-9a-f-]{36}\.json$/.test(name) || !UUID.test(name.slice(0, -5)))
179
+ throw Error('FOREIGN_DISCOVERY_RESOURCE');
180
+ // Official fs.entry.create may use 0644; the enclosing owned directories are 0700.
181
+ const path = join(this.path, 'requests', name), before = inspectResource(path, 'file', false, false);
182
+ const result = readPrivateText(path, 4096, 'utf8', false);
183
+ if (!sameResource(before, result.identity))
184
+ throw Error('DISCOVERY_RESOURCE_CHANGED');
185
+ return result;
186
+ }
187
+ responseIdentity(id, record, path = join(this.path, 'responses', id + '.json')) {
188
+ if (!inspectResource(path, 'file', true))
189
+ return;
190
+ const file = readPrivateText(path, 8192), response = object(JSON.parse(file.text));
191
+ exact(response, ['version', 'id', 'clientId', 'daemonServerId', 'expiresAt', 'status', 'offer', 'code']);
192
+ if (!record || response.version !== 1 || response.id !== id || response.clientId !== record.request.clientId || response.daemonServerId !== record.request.daemonServerId || response.expiresAt !== record.offer.expiresAt || !['pending', 'offer', 'active', 'disabled', 'error'].includes(String(response.status)) || response.code !== undefined && (typeof response.code !== 'string' || !/^[A-Z0-9_]{1,64}$/.test(response.code)))
193
+ throw Error('FOREIGN_DISCOVERY_RESPONSE');
194
+ if (response.status === 'offer' ? JSON.stringify(response.offer) !== JSON.stringify(record.offer) : response.offer !== undefined)
195
+ throw Error('FOREIGN_DISCOVERY_RESPONSE');
196
+ return file.identity;
197
+ }
198
+ assertResponseAvailable(id, record) { this.assertOwner(); this.responseIdentity(id, record); }
199
+ writeResponse(record, response) { this.assertOwner(); this.responseIdentity(record.request.id, record); atomic(join(this.path, 'responses', record.request.id + '.json'), response, 8192); }
200
+ removeResponse(record) { this.assertOwner(); const identity = this.responseIdentity(record.request.id, record); if (identity && !removeOwnedResource(join(this.path, 'responses', record.request.id + '.json'), identity))
201
+ throw Error('DISCOVERY_RESOURCE_CHANGED'); }
202
+ removeRequest(name, identity) { this.assertOwner(); if (!removeOwnedResource(join(this.path, 'requests', name), identity, 'file', false))
203
+ throw Error('DISCOVERY_RESOURCE_CHANGED'); }
204
+ close(records = []) {
205
+ if (!this.lock)
206
+ return;
207
+ this.assertOwner();
208
+ try {
209
+ for (const record of records)
210
+ this.removeResponse(record);
211
+ const descriptor = join(this.path, 'descriptor.json');
212
+ if (inspectResource(descriptor, 'file', true)) {
213
+ validateDescriptor(descriptor, this.options.daemonServerId);
214
+ const file = readPrivateText(descriptor, 4096);
215
+ if (object(JSON.parse(file.text)).instanceId === this.instanceId)
216
+ removeOwnedResource(descriptor, file.identity);
217
+ }
218
+ }
219
+ finally {
220
+ if (!removeOwnedResource(join(this.path, 'runtime.lock'), this.lock))
221
+ throw Error('DISCOVERY_RESOURCE_CHANGED');
222
+ this.lock = undefined;
223
+ }
224
+ }
225
+ }
@@ -0,0 +1,50 @@
1
+ export interface EnrollmentRequest {
2
+ version: 1;
3
+ id: string;
4
+ clientId: string;
5
+ daemonServerId: string;
6
+ issuedAt: number;
7
+ expiresAt: number;
8
+ }
9
+ export interface EnrollmentOffer {
10
+ version: 1;
11
+ apiOrigin: string;
12
+ pairId: string;
13
+ enrollmentToken: string;
14
+ rootKey: string;
15
+ expiresAt: number;
16
+ }
17
+ export interface EnrollmentRecord {
18
+ request: EnrollmentRequest;
19
+ bytes: string;
20
+ fingerprint: string;
21
+ pairId: string;
22
+ offer: EnrollmentOffer;
23
+ createBytes: string;
24
+ created: boolean;
25
+ }
26
+ export interface EnrollmentDescriptor {
27
+ version: 1;
28
+ daemonServerId: string;
29
+ instanceId: string;
30
+ apiOrigin: string;
31
+ enabled: boolean;
32
+ measuredAt: number;
33
+ expiresAt: number;
34
+ }
35
+ export interface EnrollmentResponse {
36
+ version: 1;
37
+ id: string;
38
+ clientId: string;
39
+ daemonServerId: string;
40
+ expiresAt: number;
41
+ status: 'pending' | 'offer' | 'active' | 'disabled' | 'error';
42
+ offer?: EnrollmentOffer;
43
+ code?: string;
44
+ }
45
+ export declare const DISCOVERY_NAME = ".moremote-cli-connect";
46
+ export declare const descriptorLifetime = 90000;
47
+ export declare const descriptorRenewal = 30000;
48
+ export declare function requestFingerprint(bytes: string): string;
49
+ export declare function parseEnrollmentRequest(bytes: string): EnrollmentRequest;
50
+ export declare function validateEnrollmentRecords(value: unknown): asserts value is EnrollmentRecord[];
@@ -0,0 +1,44 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { decode } from './crypto.js';
3
+ import { exact, object, UUID, LIMITS } from './limits.js';
4
+ export const DISCOVERY_NAME = '.moremote-cli-connect';
5
+ export const descriptorLifetime = 90000;
6
+ export const descriptorRenewal = 30000;
7
+ export function requestFingerprint(bytes) { return createHash('sha256').update(bytes, 'utf8').digest('hex'); }
8
+ export function parseEnrollmentRequest(bytes) {
9
+ if (Buffer.byteLength(bytes) > 4096)
10
+ throw Error('ENROLLMENT_REQUEST_LIMIT');
11
+ const request = object(JSON.parse(bytes));
12
+ exact(request, ['version', 'id', 'clientId', 'daemonServerId', 'issuedAt', 'expiresAt']);
13
+ if (request.version !== 1 || typeof request.id !== 'string' || !UUID.test(request.id) || typeof request.clientId !== 'string' || !UUID.test(request.clientId) || typeof request.daemonServerId !== 'string' || !request.daemonServerId || Buffer.byteLength(request.daemonServerId) > 512 || !Number.isSafeInteger(request.issuedAt) || Number(request.issuedAt) < 0 || !Number.isSafeInteger(request.expiresAt) || Number(request.expiresAt) <= Number(request.issuedAt) || Number(request.expiresAt) - Number(request.issuedAt) > LIMITS.enrollmentMs)
14
+ throw Error('INVALID_ENROLLMENT_REQUEST');
15
+ return request;
16
+ }
17
+ export function validateEnrollmentRecords(value) {
18
+ if (!Array.isArray(value) || value.length > 16)
19
+ throw Error('INVALID_ENROLLMENT_RECORDS');
20
+ const ids = new Set(), pairs = new Set();
21
+ for (const item of value) {
22
+ const record = object(item);
23
+ exact(record, ['request', 'bytes', 'fingerprint', 'pairId', 'offer', 'createBytes', 'created']);
24
+ if (typeof record.bytes !== 'string' || record.fingerprint !== requestFingerprint(record.bytes) || typeof record.created !== 'boolean' || typeof record.pairId !== 'string' || !UUID.test(record.pairId))
25
+ throw Error('INVALID_ENROLLMENT_RECORD');
26
+ const request = parseEnrollmentRequest(record.bytes);
27
+ if (JSON.stringify(record.request) !== JSON.stringify(request) || ids.has(request.id) || pairs.has(record.pairId))
28
+ throw Error('INVALID_ENROLLMENT_RECORD');
29
+ ids.add(request.id);
30
+ pairs.add(record.pairId);
31
+ const offer = object(record.offer);
32
+ exact(offer, ['version', 'apiOrigin', 'pairId', 'enrollmentToken', 'rootKey', 'expiresAt']);
33
+ if (offer.version !== 1 || offer.pairId !== record.pairId || typeof offer.apiOrigin !== 'string' || !Number.isSafeInteger(offer.expiresAt) || Number(offer.expiresAt) <= request.issuedAt || Number(offer.expiresAt) > request.expiresAt || typeof offer.rootKey !== 'string' || typeof offer.enrollmentToken !== 'string')
34
+ throw Error('INVALID_ENROLLMENT_OFFER');
35
+ decode(offer.rootKey, 32);
36
+ decode(offer.enrollmentToken, 32);
37
+ if (typeof record.createBytes !== 'string' || Buffer.byteLength(record.createBytes) > 1024)
38
+ throw Error('INVALID_ENROLLMENT_CREATE');
39
+ const body = object(JSON.parse(record.createBytes));
40
+ exact(body, ['pairId', 'hostTokenHash', 'enrollmentTokenHash', 'expiresAt']);
41
+ if (body.pairId !== record.pairId || body.expiresAt !== offer.expiresAt || typeof body.hostTokenHash !== 'string' || !/^[a-f0-9]{64}$/.test(body.hostTokenHash) || body.enrollmentTokenHash !== requestFingerprint(offer.enrollmentToken))
42
+ throw Error('INVALID_ENROLLMENT_CREATE');
43
+ }
44
+ }