@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
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Optional, independent Apache-2.0 computer companion for MoRemote and an **unmodified Paseo 0.15.3** daemon. Existing official-only clients keep working without this project or its cloud.
4
4
 
5
5
  Canonical repository/command: `moremote-cli`; public npm package:
6
- **`@moxuli/moremote`** (published **0.1.1**); source entry: `bin/moremote-cli.js`.
6
+ **`@moxuli/moremote`** (published **0.1.2**); source entry: `bin/moremote-cli.js`.
7
7
  There is no unscoped npm alias or automatic adoption of foreign/old state.
8
8
 
9
9
  ## Install the published package
@@ -21,7 +21,7 @@ alone stays manual. No command starts/upgrades the official daemon.
21
21
 
22
22
  ## Build and foreground use
23
23
 
24
- Requires Node **24.13.0 or later on Node 24** and npm. No installer scripts or service registration run during setup.
24
+ Requires Node **24.13.0 or later on Node 24** and npm. Dependency installation and builds do not register a service; only explicit lifecycle commands do.
25
25
 
26
26
  ```sh
27
27
  npm ci --ignore-scripts
@@ -34,66 +34,78 @@ node bin/moremote-cli.js run
34
34
 
35
35
  The example endpoint is synthetic. Omit `--target` to use the official `paseo.pid` listen address under `PASEO_HOME` (otherwise the platform home’s `.paseo`). Auth follows the official CLI: target password, then `PASEO_PASSWORD`, otherwise a rotating local credential only when the selected target exactly matches the pid listen address after official normalization. Credentials are never printed or uploaded. No automatic daemon start or upgrade.
36
36
 
37
- ## Connect to the hosted MoRemote service
37
+ ## Connect once through official Paseo
38
38
 
39
- After the published package is installed, explicitly enable the optional cloud
40
- connection while leaving the official Paseo daemon unchanged:
39
+ Single-pairing setup requires **MoRemote CLI0.1.4 or later**. Update an older
40
+ CLI before using this command. Publication and platform acceptance receipts are
41
+ recorded in `docs/STATE.md`.
42
+
43
+ With the official Paseo daemon already running:
41
44
 
42
45
  ```sh
43
- moremote-cli configure --api-origin https://moremote-cloud-ingress.pages.dev --cloud-on
44
- moremote-cli check --connect
45
- moremote-cli pair
46
- moremote-cli run
46
+ moremote-cli setup --yes
47
47
  ```
48
48
 
49
- Scan the private one-use offer in MoRemote's system integration setup. Keep
50
- `run` in the foreground, or separately choose background installation with
51
- `moremote-cli service install --yes`. Configuration and package installation do
52
- not silently register a service. The hosted backend operates continuously;
53
- cloud participation remains off until each CLI user explicitly enables it.
54
- Production TestFlight tokens use production APNs, not a sandbox backend.
55
-
56
-
57
- For a separately operated relay:
49
+ This explicit command authenticates the existing official daemon, enables cloud
50
+ and automatic local enrollment, and installs/starts only the CLI's owned per-user
51
+ background service. It preserves configured targets/custom HTTPS origins, active
52
+ and revoked phones, and existing update preferences. With no origin configured,
53
+ it selects `https://moremote-cloud-ingress.pages.dev`. It never starts, modifies
54
+ or upgrades Paseo or global tools. Source-checkout setup without managed state
55
+ binds the current source frontend and retains manual updates. Installed packages
56
+ or retained managed state require an enrollment-capable runtime: explicit setup
57
+ can install the exact current CLI version into owned private state, preserving
58
+ the automatic-update opt-out. A missing current package/capability fails clearly
59
+ before enabling enrollment, never by substituting old public code. The immutable
60
+ old package stays retained; its selected runtime/bootstrap move to capable code.
61
+
62
+ Pair the computer **only in official Paseo**. A compatible MoRemote app uses
63
+ that already authenticated connection's ordinary file channel to discover the
64
+ optional CLI and enroll its own phone automatically, even before a workspace
65
+ exists. There is no second QR, paste field, terminal, hidden workspace or relay.
66
+ Missing installation appears only in the enhancement surface. A previously
67
+ disabled/revoked phone is not silently re-enabled.
68
+
69
+ Discovery is private local state under
70
+ `<home>/.moremote-cli-connect/<sha256(daemonServerId)>/`. Descriptor origins are
71
+ pinned through that authenticated file channel; each bounded immutable request
72
+ gets its original per-phone offer and unchanged endpoint proof handshake. Secret
73
+ responses are never printed and are removed on activation/expiry. See the
74
+ [complete version-1 contract](docs/specs/05-endpoint-and-lifecycle.md#single-pairing-local-enrollment-v1-unreleased).
75
+
76
+ For an advanced custom authority, configure it before explicit setup:
58
77
 
59
78
  ```sh
60
- node bin/moremote-cli.js configure --api-origin https://relay.example.test --cloud-on
61
- node bin/moremote-cli.js pair
62
- node bin/moremote-cli.js run
79
+ moremote-cli configure --api-origin https://relay.example.test
80
+ moremote-cli setup --yes
63
81
  ```
64
82
 
65
- `pair` explicitly prints a **secret**, ten-minute, one-phone QR/link. Do not share screenshots or put it in logs. `--json` emits the canonical offer for explicit paste. It waits for the one-use claim and verifies the phone’s encrypted proof before activating that phone, within the original offer deadline. Each phone gets its own local 32-byte root key; only the phone receives it, never the relay. See [wire contracts](docs/specs/02-encrypted-delivery.md), [endpoint controls](docs/specs/04-control-and-receipt-lifecycle.md) and [endpoint behavior](docs/specs/05-endpoint-and-lifecycle.md).
66
-
67
- ## Optional activities and widget reloads — unreleased source
68
-
69
- Local source adds per-task encrypted Live Activity state and keyed widget-change
70
- fingerprints. These changes are **not in published 0.1.1**; the package version
71
- has not changed. They require a compatible native app and separately configured
72
- relay/APNs capabilities; installing the CLI alone enables neither surface.
73
- Cloud remains off by default.
74
-
75
- The phone owns task selection, encrypted read-only interest and native push
76
- tokens; the companion authenticates that interest against the pinned daemon and
77
- publishes bounded official task measurements. Up to eight interests per pairing
78
- expire within eight hours; activity states expire within ten minutes. Missing
79
- tasks are not reported finished. Acknowledged ongoing state renews from fresh
80
- measurements around every eight minutes; lost acknowledgements preserve exact
81
- ciphertext until expiry. Commands and controls do not await the optional activity
82
- lane. Widget reloads depend on meaningful snapshot changes, use the existing
83
- encrypted snapshot and are opportunistic, not realtime delivery.
84
-
85
- The relay sees opaque routing/equality tags, registration identities, tokens,
86
- environment, envelope metadata and ciphertext—not decrypted task titles or
87
- usage. Apple receives the token and push payload: encrypted activity content or
88
- a generic widget-change signal. Device rendering, widget freshness/offline
89
- behavior and APNs delivery for these new surfaces remain **pending acceptance**;
90
- APNs HTTP 200 means provider admission only. See [operator limits and failure
91
- semantics](docs/configuration.md#optional-activity-and-widget-surfaces-unreleased)
92
- and the [living wire contract](docs/specs/03-api-contract.md#opt-in-task-activities-and-widget-reloads).
83
+ Plain config loads, `check` and `status` stay passive; only `check --connect`
84
+ makes a read-only official connection. They do not enable cloud, enroll a phone,
85
+ create discovery or install a service.
86
+
87
+ ### Expert-only manual enrollment
88
+
89
+ `moremote-cli pair` remains an explicit expert tool, not the normal app flow.
90
+ It prints a **secret**, ten-minute, one-phone QR/link (`--json` prints canonical
91
+ offer JSON), enables cloud on the configured/default origin and waits for the
92
+ original encrypted claim/activation proof. Never share screenshots or log its
93
+ output. It installs no service. Existing custom origins and per-phone authority
94
+ remain unchanged. Published 0.1.2 requires explicit origin/cloud configuration
95
+ before using that legacy manual path.
96
+
97
+ ## Notification-only cloud boundary — unreleased source
98
+
99
+ Cloudflare supports native notifications and their explicit replies/approvals.
100
+ Widgets, Live Activities and ordinary app/extension sends use official Paseo
101
+ transport and shared device state; the companion no longer discovers activities,
102
+ registers system-surface tokens or uploads usage/directory snapshots. Current
103
+ notification forms retain exact occurrence bindings and immutable retry identity.
104
+ See [configuration](docs/configuration.md#notification-only-cloud-use).
93
105
 
94
106
  ## What leaves the computer
95
107
 
96
- The cloud sees pairing/operation/event identities, times, sizes, bounded transport states, scoped capability hashes and encrypted command/control/receipt/state/attention bodies. Attention routing includes a separately derived opaque conversation tag; default push text is generic. Endpoint-encrypted snapshots include verified daemon identity, host name, bounded task/title/current raw request metadata and actual available usage. Original supported question/approval forms are included only within strict bounds, to answer that exact request. No complete chat/history, code files, model keys or official Paseo passwords/local credentials are uploaded. The relay cannot decrypt or manufacture accepted commands. This is not forward secrecy.
108
+ The cloud sees pairing/operation/event identities, times, sizes, bounded transport states, scoped capability hashes and encrypted command/control/receipt/state/attention bodies. Attention routing includes a separately derived opaque conversation tag; default push text is generic. Endpoint-encrypted notification state includes only verified daemon identity and current occurrence-bound question/approval forms. Original supported question/approval forms are included only within strict bounds, to answer that exact request. No complete chat/history, code files, model keys or official Paseo passwords/local credentials are uploaded. The relay cannot decrypt or manufacture accepted commands. This is not forward secrecy.
97
109
 
98
110
  Only exact message sends and responses to an **actual current** question/approval are supported. Admission accepted is not task completion. Unknown official outcomes are reconciled, **never blindly resent**, even when the same message ID is available.
99
111
  Endpoint cancellation/revocation uses authenticated encrypted controls and durable local tombstones, not trust in a cloud DELETE result. An offline/withheld control is waiting/unknown, not endpoint-confirmed. A dispatched operation is too late to undo. Exact request-instance bindings retire on source/resolution/connection changes. Minimal revisioned encrypted receipts remain auditable for24h after original expiry, separately from short-lived user payloads; positive admission never regresses to unknown.
@@ -101,6 +113,7 @@ Endpoint cancellation/revocation uses authenticated encrypted controls and durab
101
113
  ## Lifecycle and ownership
102
114
 
103
115
  - `status` and `check` are redacted. Only explicit `check --connect` contacts the selected official daemon (read-only).
116
+ - `setup --yes`: explicit automatic-enrollment/cloud opt-in plus only the owned per-user background service; no second user pairing or official changes. Existing custom authorities, phone records and update opt-out survive.
104
117
  - `service-install --yes`: explicit per-user LaunchAgent on macOS, systemd user unit on Linux, or least-privilege interactive-user **logon task** on Windows (not an administrator Windows Service). Foreground `run` needs none of these. No sudo/admin installation.
105
118
  - `stop`: stop only the owned companion registration/runtime; never signal an official process. Linux/Windows registration remains available for a future login; macOS bootout leaves its owned plist available for explicit reinstallation.
106
119
  - `unpair --pair-id <exact-id>`: revoke one phone, leaving other phones unchanged. Stop the runtime first.
@@ -119,3 +132,9 @@ Default CLI state uses `LOCALAPPDATA/MoRemoteCLI` on Windows, `~/Library/Applica
119
132
 
120
133
  Public release prerequisites, existing-secret setup and exact verification commands:
121
134
  [releasing](docs/releasing.md). Checked-in workflows are not proof of a published package.
135
+
136
+ Widgets, Live Activities and ordinary app/extension sends connect through Paseo
137
+ and local device state. They do not use this Cloudflare notification service.
138
+ Current request forms remain encrypted here only for notification replies and
139
+ approvals; no task directory or usage feed is uploaded. Source changes are
140
+ unreleased; existing production is unchanged until a separately authorized rollout.
@@ -1,23 +1,30 @@
1
1
  #!/usr/bin/env node
2
- import {resolve} from 'node:path';
2
+ import {resolve,join,dirname} from 'node:path';
3
3
  import {fileURLToPath} from 'node:url';
4
4
  import {spawn} from 'node:child_process';
5
- import {realpath} from 'node:fs/promises';
5
+ import {realpath,readFile} from 'node:fs/promises';
6
6
  async function main(){
7
7
  const {dataDirectory}=await import('../dist/config.js');
8
8
  const {readUpdateState}=await import('../dist/update-state.js');
9
9
  const {managedEntry}=await import('../dist/service.js');
10
10
  // Dispatch before parsing: an old global frontend must accept a newer
11
11
  // selected CLI's flags, including --version. Never overwrite that frontend.
12
- let dir=dataDirectory();const args=process.argv.slice(2);
12
+ let dir=dataDirectory(),action;const args=process.argv.slice(2);
13
13
  for(let i=0;i<args.length&&args[i]!=='--';i++){
14
14
  if(args[i]==='--data-dir'&&args[i+1])dir=args[++i];
15
15
  else if(args[i].startsWith('--data-dir='))dir=args[i].slice(11);
16
+ else if(!args[i].startsWith('-')&&action===undefined)action=args[i];
16
17
  }
17
18
  const state=readUpdateState(resolve(dir));
19
+ const currentPackage=JSON.parse(await readFile(new URL('../package.json',import.meta.url),'utf8'));
20
+ // A retained selected runtime can predate setup. The current capability-owning
21
+ // package must handle that explicit migration instead of forwarding to old code.
22
+ const currentSetup=action==='setup'&&currentPackage.moremote?.localEnrollment===1;
18
23
  if(state&&!process.env.MOREMOTE_MANAGED_CHILD){
19
24
  const entry=await managedEntry(resolve(dir),state.active);
20
- if(await realpath(entry)!==await realpath(fileURLToPath(import.meta.url))){
25
+ const selectedPackage=currentSetup?JSON.parse(await readFile(join(dirname(dirname(entry)),'package.json'),'utf8')):undefined;
26
+ const selectedSetup=selectedPackage?.moremote?.localEnrollment===1&&selectedPackage.moremote.configBytes>=currentPackage.moremote.configBytes;
27
+ if((!currentSetup||selectedSetup)&&await realpath(entry)!==await realpath(fileURLToPath(import.meta.url))){
21
28
  const child=spawn(process.execPath,[entry,...args],{stdio:['inherit','inherit','inherit','ipc'],shell:false,windowsHide:true});
22
29
  const result=Promise.withResolvers();child.once('error',result.reject);child.once('exit',code=>result.resolve(code??1));
23
30
  const ready=message=>{if(message&&typeof message==='object'&&message.kind==='moremote-ready'&&typeof message.version==='string'&&process.send&&process.connected)process.send({kind:'moremote-ready',version:message.version},undefined,undefined,()=>{})};
package/dist/cli.js CHANGED
@@ -9,18 +9,21 @@ import { OfficialClient } from './official-client.js';
9
9
  import { CloudClient } from './cloud-client.js';
10
10
  import { makeOffer, tokenHash, activatePending } from './pairing.js';
11
11
  import { runRuntime } from './runtime.js';
12
- import { requestControl } from './control.js';
12
+ import { requestControl, runtimeHasLiveOwner } from './control.js';
13
13
  import { currentDefinition, installService, removeService, stopService, serviceStatus } from './service.js';
14
14
  import { ensureManaged, packageManaged, packageVersion, queueUpdate, setAutoUpdate, readUpdateState, serviceEntry } from './updater.js';
15
15
  import { runSupervisor, stopManagedRuntime } from './supervisor.js';
16
16
  import { OperationJournal } from './journal.js';
17
17
  const VERSION = await packageVersion();
18
+ import { setupEnrollment } from './setup.js';
19
+ import { setupServiceEntry } from './setup-upgrade.js';
18
20
  const HELP = `MoRemote CLI ${VERSION} — optional Paseo 0.15.3 enhancement
19
21
  Usage: moremote-cli <command> [options]
22
+ setup --yes Enable automatic enrollment and own background service
20
23
  configure --target <official-target> --api-origin <https-origin> [--cloud-on]
21
24
  [--paseo-home <directory>] [--allow-loopback-http]
22
25
  check [--connect] Redacted local checks; --connect is read-only
23
- pair [--json] Display one secret phone QR/link; wait for activation
26
+ pair [--json] Expert-only private one-phone offer and activation
24
27
  run Foreground observer and scoped command consumer
25
28
  status Redacted runtime/config/owned-service/update state
26
29
  service-install --yes Explicit per-user managed CLI login registration
@@ -91,7 +94,8 @@ async function main() {
91
94
  return;
92
95
  }
93
96
  if (action === 'run') {
94
- await saveConfig(dir, config);
97
+ if (runtimeHasLiveOwner(dir))
98
+ throw Error('CLI_ALREADY_RUNNING');
95
99
  if (process.env.MOREMOTE_MANAGED_CHILD) {
96
100
  try {
97
101
  await runRuntime(dir, VERSION);
@@ -121,6 +125,27 @@ async function main() {
121
125
  console.log('MoRemote CLI stopped; official Paseo unchanged.');
122
126
  return;
123
127
  }
128
+ if (action === 'setup') {
129
+ let preparedEntry;
130
+ await setupEnrollment(dir, { yes: !!args.yes, stopOwned: () => stopOwned(dir, definition), authenticate: async (current) => {
131
+ const official = new OfficialClient(current);
132
+ try {
133
+ await official.connect();
134
+ return { serverId: official.info().serverId };
135
+ }
136
+ finally {
137
+ await official.close();
138
+ }
139
+ }, prepare: async () => {
140
+ preparedEntry = await setupServiceEntry(dir, fileURLToPath(new URL('../bin/moremote-cli.js', import.meta.url)));
141
+ }, install: async () => {
142
+ if (!preparedEntry)
143
+ throw Error('SETUP_CAPABILITY_REQUIRED');
144
+ await installService(currentDefinition(preparedEntry, dir));
145
+ } });
146
+ console.log('MoRemote CLI automatic enrollment and owned per-user service enabled. Official Paseo unchanged.');
147
+ return;
148
+ }
124
149
  if (action === 'configure') {
125
150
  await stopped(dir);
126
151
  pruneRetiredPairs(config);
@@ -152,20 +177,21 @@ async function main() {
152
177
  }
153
178
  if (action === 'pair') {
154
179
  await stopped(dir);
155
- if (!config.apiOrigin || !config.cloudEnabled)
156
- throw Error('CONFIGURE_AND_OPT_IN_CLOUD_FIRST');
157
180
  if (config.pairs.length >= 16)
158
181
  throw Error('PAIRING_LIMIT');
182
+ const origin = validateOrigin(config.apiOrigin ?? 'https://moremote-cloud-ingress.pages.dev', config.allowLoopbackHttp);
159
183
  const official = new OfficialClient(config);
160
184
  try {
161
185
  await official.connect();
162
186
  const info = official.info();
187
+ config.apiOrigin = origin;
188
+ config.cloudEnabled = true;
163
189
  config.daemonServerId = info.serverId;
164
- const { pair, offer } = makeOffer(config.apiOrigin);
190
+ const { pair, offer } = makeOffer(origin);
165
191
  pair.daemonServerId = info.serverId;
166
192
  config.pairs.push(pair);
167
193
  await saveConfig(dir, config);
168
- const cloud = new CloudClient(config.apiOrigin, pair.pairId, pair.hostToken, config.allowLoopbackHttp);
194
+ const cloud = new CloudClient(origin, pair.pairId, pair.hostToken, config.allowLoopbackHttp);
169
195
  await cloud.create({ pairId: pair.pairId, hostTokenHash: tokenHash(pair.hostToken), enrollmentTokenHash: tokenHash(pair.enrollmentToken), expiresAt: pair.expiresAt });
170
196
  const offerJSON = JSON.stringify(offer);
171
197
  if (args.json)
@@ -22,7 +22,7 @@ export declare class CloudClient {
22
22
  constructor(origin: string, pairId: string, token: string, allowLoopback?: boolean, fetcher?: typeof fetch, signal?: AbortSignal | undefined, retryState?: CloudRetryState, cycleFence?: CloudRetryState | undefined);
23
23
  request(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>;
24
24
  private path;
25
- create(body: unknown): Promise<Record<string, unknown>>;
25
+ create(body: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>;
26
26
  pair(): Promise<Record<string, unknown>>;
27
27
  activate(body: unknown): Promise<Record<string, unknown>>;
28
28
  revoke(): Promise<Record<string, unknown>>;
@@ -35,18 +35,11 @@ export declare class CloudClient {
35
35
  revision: number;
36
36
  envelope: Envelope;
37
37
  }): Promise<Record<string, unknown>>;
38
- state(envelope: Envelope, widgetFingerprint?: string): Promise<Record<string, unknown>>;
38
+ state(envelope: Envelope): Promise<Record<string, unknown>>;
39
39
  attention(body: unknown): Promise<Record<string, unknown>>;
40
40
  controls(): Promise<Envelope[]>;
41
41
  controlReceipt(id: string, body: {
42
42
  envelope: Envelope;
43
43
  }): Promise<Record<string, unknown>>;
44
44
  resolveAttention(id: string, resolvedAt: number): Promise<Record<string, unknown>>;
45
- activities(signal?: AbortSignal): Promise<unknown[]>;
46
- activityState(id: string, body: {
47
- registrationId: string;
48
- topic: string;
49
- event: 'update' | 'end';
50
- envelope: Envelope;
51
- }, signal?: AbortSignal): Promise<Record<string, unknown>>;
52
45
  }
@@ -43,9 +43,7 @@ function recoveryRequest(method, path) {
43
43
  return suffix.length === 1 && ['GET', 'POST'].includes(method) || suffix.length === 2 && method === 'GET' || suffix.length === 3 && suffix[2] === 'receipt' && method === 'POST';
44
44
  if (suffix[0] === 'commands')
45
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';
46
+ return suffix[0] === 'attention' && suffix.length === 3 && suffix[2] === 'resolve' && method === 'POST';
49
47
  }
50
48
  export class CloudClient {
51
49
  pairId;
@@ -152,7 +150,7 @@ export class CloudClient {
152
150
  return result;
153
151
  }
154
152
  path(suffix = '') { return '/pairs/' + this.pairId + suffix; }
155
- create(body) { return this.request('POST', '/pairs', body); }
153
+ create(body, signal) { return this.request('POST', '/pairs', body, signal); }
156
154
  pair() { return this.request('GET', this.path()); }
157
155
  activate(body) { return this.request('POST', this.path('/activate'), body); }
158
156
  revoke() { return this.request('DELETE', this.path()); }
@@ -161,13 +159,10 @@ export class CloudClient {
161
159
  async dispatch(id) { const r = await this.request('POST', this.path('/commands/' + id + '/dispatch'), {}); if (typeof r.dispatchAllowed !== 'boolean')
162
160
  throw Error('INVALID_DISPATCH_RESPONSE'); return { dispatchAllowed: r.dispatchAllowed }; }
163
161
  receipt(id, body) { return this.request('POST', this.path('/commands/' + id + '/receipt'), body); }
164
- state(envelope, widgetFingerprint) { return this.request('PUT', this.path('/state'), { envelope, ...(widgetFingerprint ? { widgetFingerprint } : {}) }); }
162
+ state(envelope) { return this.request('PUT', this.path('/state'), { envelope }); }
165
163
  attention(body) { return this.request('POST', this.path('/attention'), body); }
166
164
  async controls() { const result = await this.request('GET', this.path('/controls')); if (!Array.isArray(result.controls) || result.controls.length > 100)
167
165
  throw Error('INVALID_CONTROL_PAGE'); return result.controls.map(row => object(row).envelope).filter(Boolean); }
168
166
  controlReceipt(id, body) { return this.request('POST', this.path('/controls/' + id + '/receipt'), body); }
169
167
  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); }
173
168
  }
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; }
@@ -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
+ }