@moxuli/moremote 0.1.2 → 0.1.5

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 (41) hide show
  1. package/README.md +69 -50
  2. package/bin/moremote-cli.js +11 -4
  3. package/dist/cli.js +33 -7
  4. package/dist/cloud-client.d.ts +2 -9
  5. package/dist/cloud-client.js +3 -8
  6. package/dist/config.d.ts +7 -0
  7. package/dist/config.js +23 -4
  8. package/dist/enrollment-files.d.ts +37 -0
  9. package/dist/enrollment-files.js +225 -0
  10. package/dist/enrollment-protocol.d.ts +50 -0
  11. package/dist/enrollment-protocol.js +44 -0
  12. package/dist/local-enrollment.d.ts +25 -0
  13. package/dist/local-enrollment.js +160 -0
  14. package/dist/notification-state.d.ts +10 -0
  15. package/dist/notification-state.js +36 -0
  16. package/dist/official-client.d.ts +25 -65
  17. package/dist/official-client.js +83 -35
  18. package/dist/operations.d.ts +1 -0
  19. package/dist/operations.js +24 -4
  20. package/dist/projection.d.ts +3 -15
  21. package/dist/projection.js +11 -21
  22. package/dist/resources.d.ts +2 -1
  23. package/dist/resources.js +67 -31
  24. package/dist/runtime.d.ts +10 -1
  25. package/dist/runtime.js +81 -59
  26. package/dist/setup-upgrade.d.ts +2 -0
  27. package/dist/setup-upgrade.js +65 -0
  28. package/dist/setup.d.ts +12 -0
  29. package/dist/setup.js +38 -0
  30. package/docs/STATE.md +197 -13
  31. package/docs/configuration.md +70 -49
  32. package/docs/native-enrollment-acceptance.md +21 -0
  33. package/docs/specs/01-architecture.md +14 -1
  34. package/docs/specs/02-encrypted-delivery.md +4 -4
  35. package/docs/specs/03-api-contract.md +18 -123
  36. package/docs/specs/04-control-and-receipt-lifecycle.md +12 -0
  37. package/docs/specs/05-endpoint-and-lifecycle.md +126 -2
  38. package/docs/specs/06-managed-updates.md +25 -0
  39. package/package.json +29 -6
  40. package/dist/activity.d.ts +0 -77
  41. package/dist/activity.js +0 -193
@@ -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
+ }
@@ -0,0 +1,25 @@
1
+ import { type Config, type Pair } from './config.js';
2
+ import { CloudClient } from './cloud-client.js';
3
+ import { EnrollmentFiles, type DiscoveryOptions } from './enrollment-files.js';
4
+ export declare const DEFAULT_API_ORIGIN = "https://moremote-cloud-ingress.pages.dev";
5
+ export interface LocalEnrollmentOptions {
6
+ clock?: () => number;
7
+ files?: (options: DiscoveryOptions) => EnrollmentFiles;
8
+ persist?: (directory: string, config: Config) => Promise<void>;
9
+ }
10
+ export type EnrollmentCloudFactory = (pair: Pair) => Pick<CloudClient, 'create'>;
11
+ export declare class LocalEnrollment {
12
+ private directory;
13
+ private options;
14
+ private files;
15
+ private config;
16
+ private cursor;
17
+ private readonly clock;
18
+ private readonly persist;
19
+ constructor(directory: string, options?: LocalEnrollmentOptions);
20
+ private storage;
21
+ cleanup(config: Config): Promise<void>;
22
+ cycle(config: Config, daemonServerId: string, cloud: EnrollmentCloudFactory): Promise<void>;
23
+ private response;
24
+ close(): void;
25
+ }
@@ -0,0 +1,160 @@
1
+ import { saveConfig, validateOrigin } from './config.js';
2
+ import { makeOffer, tokenHash } from './pairing.js';
3
+ import { EnrollmentFiles } from './enrollment-files.js';
4
+ import { parseEnrollmentRequest, requestFingerprint } from './enrollment-protocol.js';
5
+ export const DEFAULT_API_ORIGIN = 'https://moremote-cloud-ingress.pages.dev';
6
+ // The runtime's existing serialized cycle owns this consumer and its Config.
7
+ // No watcher, background config writer, listener or official mutation is added.
8
+ export class LocalEnrollment {
9
+ directory;
10
+ options;
11
+ files;
12
+ config;
13
+ cursor = 0;
14
+ clock;
15
+ persist;
16
+ constructor(directory, options = {}) {
17
+ this.directory = directory;
18
+ this.options = options;
19
+ this.clock = options.clock ?? Date.now;
20
+ this.persist = options.persist ?? saveConfig;
21
+ }
22
+ storage(config) {
23
+ if (!config.localEnrollment || !config.daemonServerId)
24
+ return;
25
+ this.files ??= (this.options.files ?? (options => new EnrollmentFiles(options)))({ home: config.localEnrollment.home, stateDirectory: this.directory, daemonServerId: config.daemonServerId });
26
+ this.files.open(config.enrollmentRequests ?? []);
27
+ return this.files;
28
+ }
29
+ async cleanup(config) {
30
+ this.config = config;
31
+ const files = this.storage(config);
32
+ if (!files)
33
+ return;
34
+ const now = this.clock(), records = config.enrollmentRequests ?? [];
35
+ let changed = false;
36
+ for (const record of records) {
37
+ const pair = config.pairs.find(pair => pair.pairId === record.pairId);
38
+ if (!config.cloudEnabled || pair?.active || pair?.revokedAt !== undefined || pair?.relayRetiredAt !== undefined || now >= record.offer.expiresAt)
39
+ files.removeResponse(record);
40
+ if (config.cloudEnabled && now < record.offer.expiresAt && (pair?.revokedAt !== undefined || pair?.relayRetiredAt !== undefined))
41
+ files.writeResponse(record, this.response(record, 'disabled'));
42
+ if (pair?.active || now >= record.offer.expiresAt) {
43
+ const name = record.request.id + '.json';
44
+ try {
45
+ const file = files.readRequest(name);
46
+ if (file.text === record.bytes)
47
+ files.removeRequest(name, file.identity);
48
+ }
49
+ catch (error) {
50
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
51
+ throw error;
52
+ }
53
+ }
54
+ }
55
+ const retained = records.filter(record => now < record.offer.expiresAt);
56
+ if (retained.length !== records.length) {
57
+ config.enrollmentRequests = retained;
58
+ changed = true;
59
+ }
60
+ if (changed)
61
+ await this.persist(this.directory, config);
62
+ }
63
+ async cycle(config, daemonServerId, cloud) {
64
+ if (!config.localEnrollment)
65
+ return;
66
+ if (!config.daemonServerId || config.daemonServerId !== daemonServerId)
67
+ throw Error('ENROLLMENT_DAEMON_MISMATCH');
68
+ await this.cleanup(config);
69
+ const files = this.storage(config);
70
+ const origin = validateOrigin(config.apiOrigin ?? DEFAULT_API_ORIGIN, false), now = this.clock();
71
+ files.publish(config.cloudEnabled, origin, now);
72
+ if (!config.cloudEnabled)
73
+ return;
74
+ const names = files.requestNames();
75
+ if (!names.length)
76
+ return;
77
+ const start = this.cursor % names.length, selected = [...names.slice(start), ...names.slice(0, start)].slice(0, 16);
78
+ this.cursor = (start + selected.length) % names.length;
79
+ let failure, creationAttempted = false;
80
+ for (const name of selected) {
81
+ try {
82
+ const file = files.readRequest(name), record = config.enrollmentRequests?.find(record => record.request.id === name.slice(0, -5));
83
+ if (record && record.bytes !== file.text) {
84
+ files.removeResponse(record);
85
+ throw Error('ENROLLMENT_REQUEST_CONFLICT');
86
+ }
87
+ if (file.text === '')
88
+ continue; // Official create/write is a two-step transaction.
89
+ const request = parseEnrollmentRequest(file.text);
90
+ if (request.id + '.json' !== name || request.daemonServerId !== daemonServerId)
91
+ throw Error('ENROLLMENT_DAEMON_MISMATCH');
92
+ if (request.expiresAt <= this.clock()) {
93
+ files.removeRequest(name, file.identity);
94
+ continue;
95
+ }
96
+ files.assertResponseAvailable(request.id, record);
97
+ if (request.issuedAt > this.clock())
98
+ throw Error('ENROLLMENT_REQUEST_FROM_FUTURE');
99
+ let owned = record;
100
+ if (!owned) {
101
+ if (creationAttempted)
102
+ continue;
103
+ if (config.pairs.some(pair => pair.automaticRequestId === request.id))
104
+ throw Error('ENROLLMENT_REQUEST_CONFLICT');
105
+ if (config.pairs.some(pair => pair.automaticClientId === request.clientId && pair.daemonServerId === daemonServerId && pair.revokedAt === undefined && pair.relayRetiredAt === undefined && (pair.active || pair.expiresAt === undefined || pair.expiresAt > this.clock())))
106
+ throw Error('ENROLLMENT_CLIENT_ALREADY_BOUND');
107
+ if (config.pairs.length >= 16 || (config.enrollmentRequests?.length ?? 0) >= 16)
108
+ throw Error('PAIRING_LIMIT');
109
+ const generated = makeOffer(origin, this.clock());
110
+ generated.pair.expiresAt = Math.min(generated.pair.expiresAt, request.expiresAt);
111
+ const pair = { ...generated.pair, daemonServerId, automaticClientId: request.clientId, automaticRequestId: request.id };
112
+ const offer = { ...generated.offer, version: 1, enrollmentToken: pair.enrollmentToken, expiresAt: pair.expiresAt };
113
+ const createBytes = JSON.stringify({ pairId: pair.pairId, hostTokenHash: tokenHash(pair.hostToken), enrollmentTokenHash: tokenHash(offer.enrollmentToken), expiresAt: offer.expiresAt });
114
+ owned = { request, bytes: file.text, fingerprint: requestFingerprint(file.text), pairId: pair.pairId, offer, createBytes, created: false };
115
+ config.pairs.push(pair);
116
+ (config.enrollmentRequests ??= []).push(owned);
117
+ await this.persist(this.directory, config); // Original keys/request precede all cloud I/O.
118
+ }
119
+ const pair = config.pairs.find(pair => pair.pairId === owned.pairId);
120
+ if (!pair)
121
+ throw Error('ENROLLMENT_PAIR_MISSING');
122
+ if (pair.active) {
123
+ files.removeResponse(owned);
124
+ files.removeRequest(name, file.identity);
125
+ continue;
126
+ }
127
+ if (pair.revokedAt !== undefined || pair.relayRetiredAt !== undefined) {
128
+ files.writeResponse(owned, this.response(owned, 'disabled'));
129
+ continue;
130
+ }
131
+ if (!owned.created) {
132
+ if (creationAttempted)
133
+ continue;
134
+ creationAttempted = true;
135
+ await cloud(pair).create(JSON.parse(owned.createBytes), AbortSignal.timeout(3000));
136
+ owned.created = true;
137
+ await this.persist(this.directory, config);
138
+ }
139
+ // An unknown create acknowledgement retries the same original body. Recheck
140
+ // the immutable local request and deadline after network/persistence awaits.
141
+ if (this.clock() >= owned.offer.expiresAt) {
142
+ files.removeResponse(owned);
143
+ continue;
144
+ }
145
+ if (files.readRequest(name).text !== owned.bytes) {
146
+ files.removeResponse(owned);
147
+ throw Error('ENROLLMENT_REQUEST_CONFLICT');
148
+ }
149
+ files.writeResponse(owned, { ...this.response(owned, 'offer'), offer: owned.offer });
150
+ }
151
+ catch (error) {
152
+ failure ??= error;
153
+ }
154
+ }
155
+ if (failure)
156
+ throw failure;
157
+ }
158
+ response(record, status) { return { version: 1, id: record.request.id, clientId: record.request.clientId, daemonServerId: record.request.daemonServerId, expiresAt: record.offer.expiresAt, status }; }
159
+ close() { this.files?.close(this.config?.enrollmentRequests ?? []); this.files = undefined; }
160
+ }
@@ -0,0 +1,10 @@
1
+ import type { Pair } from './config.js';
2
+ import type { CloudClient } from './cloud-client.js';
3
+ import type { projectSnapshot } from './projection.js';
4
+ type NotificationState = Awaited<ReturnType<typeof projectSnapshot>>;
5
+ export declare class NotificationStatePublisher {
6
+ private publications;
7
+ retain(ids: string[]): void;
8
+ publish(pair: Pick<Pair, 'pairId' | 'rootKey'>, cloud: Pick<CloudClient, 'state'>, payload: NotificationState, now?: number): Promise<boolean>;
9
+ }
10
+ export {};
@@ -0,0 +1,36 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { decode, sealEnvelope } from './crypto.js';
3
+ import { canonical, digest } from './journal.js';
4
+ import { LIMITS } from './limits.js';
5
+ // State is encrypted notification hydration, never a general system-surface feed.
6
+ // Callers serialize publication per pair. Unknown acknowledgements retain bytes.
7
+ export class NotificationStatePublisher {
8
+ publications = new Map();
9
+ retain(ids) { const keep = new Set(ids); for (const id of this.publications.keys())
10
+ if (!keep.has(id))
11
+ this.publications.delete(id); }
12
+ async publish(pair, cloud, payload, now = Date.now()) {
13
+ const fingerprint = digest(canonical(payload));
14
+ let publication = this.publications.get(pair.pairId);
15
+ if (!payload.tasks.length && (!publication || publication.acknowledged && publication.fingerprint === fingerprint))
16
+ return true;
17
+ // An earlier unknown attempt is retried before publishing a newer observation.
18
+ for (let attempt = 0; attempt < 2; attempt++) {
19
+ const changed = !publication || publication.fingerprint !== fingerprint;
20
+ const renewal = payload.tasks.length > 0 && !!publication && publication.envelope.expiresAt - now <= 120000;
21
+ if (!publication || publication.envelope.expiresAt <= now || publication.acknowledged && (changed || renewal)) {
22
+ const issuedAt = Math.max(now, (publication?.envelope.issuedAt ?? -1) + 1);
23
+ const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'state', issuedAt, expiresAt: issuedAt + LIMITS.snapshotMs }, payload);
24
+ publication = { envelope, fingerprint, acknowledged: false };
25
+ this.publications.set(pair.pairId, publication);
26
+ }
27
+ if (!publication.acknowledged) {
28
+ await cloud.state(publication.envelope);
29
+ publication.acknowledged = true;
30
+ }
31
+ if (publication.fingerprint === fingerprint)
32
+ return true;
33
+ }
34
+ return false;
35
+ }
36
+ }