@rome-os/node-core 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Frame } from "./frame.js";
2
- import { type GatewayMessage, type OutboundEnvelope } from "./protocol.js";
2
+ import { type GatewayMessage, type GatewayNotification, type OutboundEnvelope } from "./protocol.js";
3
3
  export interface ClientSocket {
4
4
  readyState: number;
5
5
  send(data: string | Uint8Array): void;
@@ -22,6 +22,7 @@ export interface GatewayClientOptions {
22
22
  onMessage(message: GatewayMessage): void;
23
23
  onFrame?(frame: Frame): void;
24
24
  onStatus?(status: ConnectionStatus): void;
25
+ onNotification?(notification: GatewayNotification): void;
25
26
  random?(): number;
26
27
  beforeConnect?(): Promise<string | null>;
27
28
  }
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { encodeFrame, FRAME_TYPE, frameFits, isUuid, parseFrame } from "./frame.js";
2
2
  import { parseGatewayUrl } from "./gateway-url.js";
3
3
  import { isJwt } from "./signer.js";
4
- import { CLOSE, gatewayMessage, outboundEnvelope, } from "./protocol.js";
4
+ import { CLOSE, gatewayMessage, gatewayNotification, outboundEnvelope, } from "./protocol.js";
5
5
  const REAUTH_INTERVAL_MS = 60_000;
6
6
  const DEVICE_TOKEN = /^(?:romedev_|romemob_)[A-Za-z0-9_-]{43}$/;
7
7
  export function connectGateway(options) {
@@ -118,13 +118,22 @@ export function connectGateway(options) {
118
118
  options.onFrame?.(frame);
119
119
  return;
120
120
  }
121
- let message;
121
+ let json;
122
122
  try {
123
- message = gatewayMessage(JSON.parse(data));
123
+ json = JSON.parse(data);
124
124
  }
125
125
  catch {
126
126
  return;
127
127
  }
128
+ const notification = gatewayNotification(json);
129
+ if (notification) {
130
+ try {
131
+ options.onNotification?.(notification);
132
+ }
133
+ catch { }
134
+ return;
135
+ }
136
+ const message = gatewayMessage(json);
128
137
  if (message)
129
138
  options.onMessage(message);
130
139
  });
package/dist/connect.d.ts CHANGED
@@ -1,28 +1,7 @@
1
- import type { DeviceSession } from "./login.js";
2
- import type { CredentialStore } from "./storage.js";
3
1
  import { type HostAudit } from "./executor.js";
4
- export type HostCredential = DeviceSession & {
5
- name: string;
6
- };
7
- export type HostEvent = {
8
- type: "authorization_required";
9
- } | {
10
- type: "retrying";
11
- } | {
12
- type: "device";
13
- name: string;
14
- deviceId: string;
15
- } | {
16
- type: "connection";
17
- status: import("./client.js").ConnectionStatus;
18
- };
19
- export interface HostOptions {
20
- cloudUrl: string;
21
- name: string;
22
- signal: AbortSignal;
23
- credentials: CredentialStore<HostCredential>;
24
- authorize(cloudUrl: string, name: string, signal: AbortSignal): Promise<DeviceSession>;
25
- onEvent?(event: HostEvent): void;
2
+ import { type HostConnectionOptions, type HostCredential, type HostEvent } from "./host-connection.js";
3
+ export type { HostCredential, HostEvent };
4
+ export interface HostOptions extends HostConnectionOptions {
26
5
  audit: HostAudit;
27
6
  }
28
7
  export declare function connectHost(options: HostOptions): Promise<void>;
package/dist/connect.js CHANGED
@@ -1,117 +1,8 @@
1
1
  import { hostname } from "node:os";
2
- import { setTimeout as delay } from "node:timers/promises";
3
- import { isRecord } from "./actions.js";
4
- import { cloudOrigin, cloudRequest, CloudError, gatewayConfig } from "./cloud.js";
5
- import { connectGateway } from "./client.js";
6
- import { createNodeSocket } from "./socket.js";
7
2
  import { createExecutor } from "./executor.js";
8
- import { validId } from "./protocol.js";
9
- export async function connectHost(options) {
10
- const { name, signal, credentials } = options;
11
- if (signal.aborted)
12
- return;
13
- const cloudUrl = cloudOrigin(options.cloudUrl);
14
- const stored = await credentials.load();
15
- let session = isRecord(stored) &&
16
- stored.cloudUrl === cloudUrl &&
17
- typeof stored.token === "string" &&
18
- /^(?:romedev|romemob)_[A-Za-z0-9_-]{43}$/.test(stored.token) &&
19
- validId(stored.deviceId) &&
20
- typeof stored.name === "string"
21
- ? { cloudUrl, token: stored.token, deviceId: stored.deviceId, name: stored.name }
22
- : null;
23
- let gatewayUrl = "";
24
- let attempt = 0;
25
- while (!signal.aborted) {
26
- if (!session) {
27
- options.onEvent?.({ type: "authorization_required" });
28
- session = { ...(await options.authorize(cloudUrl, name, signal)), name };
29
- await credentials.save(session);
30
- }
31
- try {
32
- gatewayUrl = await gatewayConfig(cloudUrl, session.token);
33
- break;
34
- }
35
- catch (error) {
36
- if (error instanceof CloudError && error.code === "invalid_device_session") {
37
- await credentials.clear();
38
- session = null;
39
- continue;
40
- }
41
- options.onEvent?.({ type: "retrying" });
42
- await delay(Math.min(60_000, 1000 * 2 ** Math.min(attempt++, 6)), undefined, {
43
- signal,
44
- }).catch(() => { });
45
- }
46
- }
47
- if (signal.aborted || !session)
48
- return;
49
- const devices = await cloudRequest(cloudUrl, "/api/account/devices", session.token).catch(() => null);
50
- if (isRecord(devices) && Array.isArray(devices.items)) {
51
- const device = devices.items.find((item) => isRecord(item) && item.id === session?.deviceId);
52
- if (isRecord(device) && typeof device.device_name === "string") {
53
- session.name = device.device_name;
54
- await credentials.save(session);
55
- }
56
- }
57
- if (signal.aborted)
58
- return;
59
- const active = session;
60
- options.onEvent?.({ type: "device", name: active.name, deviceId: active.deviceId });
61
- await new Promise((resolve, reject) => {
62
- const executor = createExecutor(active.name, options.audit, (message) => connection.send(message), [active.token], (frame) => connection.sendFrame(frame));
63
- let finished = false;
64
- const finish = (error) => {
65
- if (finished)
66
- return;
67
- finished = true;
68
- signal.removeEventListener("abort", abort);
69
- executor.disconnect();
70
- connection.stop();
71
- void Promise.race([executor.idle(), delay(3000, undefined, { ref: false })]).then(() => error ? reject(error) : resolve());
72
- };
73
- const abort = () => finish();
74
- const connection = connectGateway({
75
- gatewayUrl,
76
- getToken: () => active.token,
77
- createSocket: createNodeSocket,
78
- beforeConnect: async () => {
79
- try {
80
- return await gatewayConfig(cloudUrl, active.token);
81
- }
82
- catch (error) {
83
- if (error instanceof CloudError && error.code === "invalid_device_session")
84
- return null;
85
- throw error;
86
- }
87
- },
88
- onMessage: (message) => {
89
- if ("from" in message)
90
- void executor.receive(message);
91
- },
92
- onFrame: (frame) => void executor.receiveFrame(frame),
93
- onStatus: (status) => {
94
- options.audit.host({
95
- event: "connection",
96
- status,
97
- deviceId: active.deviceId,
98
- name: active.name,
99
- cloudOrigin: cloudUrl,
100
- }, [active.token]);
101
- options.onEvent?.({ type: "connection", status });
102
- if (status !== "online" && status !== "connecting")
103
- executor.disconnect();
104
- if (status === "revoked" || status === "superseded") {
105
- queueMicrotask(() => finish(new Error(status === "revoked"
106
- ? "Authorization revoked. Explicit authorization is required."
107
- : "Another connection replaced this device. This process has stopped.")));
108
- }
109
- },
110
- });
111
- signal.addEventListener("abort", abort, { once: true });
112
- if (signal.aborted)
113
- abort();
114
- });
3
+ import { runHostConnection, } from "./host-connection.js";
4
+ export function connectHost(options) {
5
+ return runHostConnection(options, (session, send, sendFrame, secrets) => createExecutor(session.name, options.audit, send, secrets, sendFrame));
115
6
  }
116
7
  export const defaultDeviceName = () => hostname()
117
8
  .replace(/[\u0000-\u001f\u007f]/g, "")
@@ -24,5 +24,6 @@ export declare class DeviceStatusReader {
24
24
  constructor(connector: Pick<DeviceConnector, "list" | "run" | "getStatus">);
25
25
  invalidate(): void;
26
26
  read(): Promise<DevicesStatus>;
27
+ private refresh;
27
28
  private check;
28
29
  }
@@ -1,4 +1,5 @@
1
1
  import { isRecord } from "./actions.js";
2
+ const REFRESH_AFTER_MS = 10_000;
2
3
  export class DeviceStatusReader {
3
4
  connector;
4
5
  cached;
@@ -10,23 +11,31 @@ export class DeviceStatusReader {
10
11
  invalidate() {
11
12
  this.generation++;
12
13
  this.cached = undefined;
14
+ this.pending = undefined;
13
15
  }
14
16
  async read() {
15
- if (this.cached && Date.now() - Date.parse(this.cached.checkedAt) < 10_000)
16
- return this.cached;
17
+ if (!this.cached)
18
+ return this.refresh();
19
+ if (Date.now() - Date.parse(this.cached.checkedAt) >= REFRESH_AFTER_MS)
20
+ this.refresh().catch(() => undefined);
21
+ return this.cached;
22
+ }
23
+ refresh() {
17
24
  if (this.pending)
18
25
  return this.pending;
19
26
  const generation = this.generation;
20
- this.pending = this.check()
27
+ const pending = this.check()
21
28
  .then((snapshot) => {
22
29
  if (generation === this.generation)
23
30
  this.cached = snapshot;
24
31
  return snapshot;
25
32
  })
26
33
  .finally(() => {
27
- this.pending = undefined;
34
+ if (this.pending === pending)
35
+ this.pending = undefined;
28
36
  });
29
- return this.pending;
37
+ this.pending = pending;
38
+ return pending;
30
39
  }
31
40
  async check() {
32
41
  const list = await this.connector.list();
@@ -0,0 +1,37 @@
1
+ import type { DeviceSession } from "./login.js";
2
+ import type { CredentialStore } from "./storage.js";
3
+ import type { Frame } from "./frame.js";
4
+ import type { HostAudit } from "./executor.js";
5
+ import { type GatewayNotification, type InboundEnvelope, type OutboundEnvelope } from "./protocol.js";
6
+ export type HostCredential = DeviceSession & {
7
+ name: string;
8
+ };
9
+ export type HostEvent = {
10
+ type: "authorization_required";
11
+ } | {
12
+ type: "retrying";
13
+ } | {
14
+ type: "device";
15
+ name: string;
16
+ deviceId: string;
17
+ } | {
18
+ type: "connection";
19
+ status: import("./client.js").ConnectionStatus;
20
+ };
21
+ export interface HostConnectionOptions {
22
+ cloudUrl: string;
23
+ name: string;
24
+ signal: AbortSignal;
25
+ credentials: CredentialStore<HostCredential>;
26
+ authorize(cloudUrl: string, name: string, signal: AbortSignal): Promise<DeviceSession>;
27
+ onEvent?(event: HostEvent): void;
28
+ onNotification?(notification: GatewayNotification): void;
29
+ audit?: Pick<HostAudit, "host">;
30
+ }
31
+ export interface HostResponder {
32
+ receive(message: InboundEnvelope): Promise<void> | void;
33
+ receiveFrame(frame: Frame): Promise<void> | void;
34
+ disconnect(): void;
35
+ idle(): Promise<void>;
36
+ }
37
+ export declare function runHostConnection(options: HostConnectionOptions, responder: (session: HostCredential, send: (message: OutboundEnvelope) => boolean, sendFrame: (frame: Frame) => boolean, secrets: string[]) => HostResponder): Promise<void>;
@@ -0,0 +1,114 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { isRecord } from "./actions.js";
3
+ import { cloudOrigin, cloudRequest, CloudError, gatewayConfig } from "./cloud.js";
4
+ import { connectGateway } from "./client.js";
5
+ import { createNodeSocket } from "./socket.js";
6
+ import { validId, } from "./protocol.js";
7
+ export async function runHostConnection(options, responder) {
8
+ const { name, signal, credentials } = options;
9
+ if (signal.aborted)
10
+ return;
11
+ const cloudUrl = cloudOrigin(options.cloudUrl);
12
+ const stored = await credentials.load();
13
+ let session = isRecord(stored) &&
14
+ stored.cloudUrl === cloudUrl &&
15
+ typeof stored.token === "string" &&
16
+ /^(?:romedev|romemob)_[A-Za-z0-9_-]{43}$/.test(stored.token) &&
17
+ validId(stored.deviceId) &&
18
+ typeof stored.name === "string"
19
+ ? { cloudUrl, token: stored.token, deviceId: stored.deviceId, name: stored.name }
20
+ : null;
21
+ let gatewayUrl = "";
22
+ let attempt = 0;
23
+ while (!signal.aborted) {
24
+ if (!session) {
25
+ options.onEvent?.({ type: "authorization_required" });
26
+ session = { ...(await options.authorize(cloudUrl, name, signal)), name };
27
+ await credentials.save(session);
28
+ }
29
+ try {
30
+ gatewayUrl = await gatewayConfig(cloudUrl, session.token);
31
+ break;
32
+ }
33
+ catch (error) {
34
+ if (error instanceof CloudError && error.code === "invalid_device_session") {
35
+ await credentials.clear();
36
+ session = null;
37
+ continue;
38
+ }
39
+ options.onEvent?.({ type: "retrying" });
40
+ await delay(Math.min(60_000, 1000 * 2 ** Math.min(attempt++, 6)), undefined, {
41
+ signal,
42
+ }).catch(() => { });
43
+ }
44
+ }
45
+ if (signal.aborted || !session)
46
+ return;
47
+ const devices = await cloudRequest(cloudUrl, "/api/account/devices", session.token).catch(() => null);
48
+ if (isRecord(devices) && Array.isArray(devices.items)) {
49
+ const device = devices.items.find((item) => isRecord(item) && item.id === session?.deviceId);
50
+ if (isRecord(device) && typeof device.device_name === "string") {
51
+ session.name = device.device_name;
52
+ await credentials.save(session);
53
+ }
54
+ }
55
+ if (signal.aborted)
56
+ return;
57
+ const active = session;
58
+ options.onEvent?.({ type: "device", name: active.name, deviceId: active.deviceId });
59
+ await new Promise((resolve, reject) => {
60
+ const executor = responder(active, (message) => connection.send(message), (frame) => connection.sendFrame(frame), [active.token]);
61
+ let finished = false;
62
+ const finish = (error) => {
63
+ if (finished)
64
+ return;
65
+ finished = true;
66
+ signal.removeEventListener("abort", abort);
67
+ executor.disconnect();
68
+ connection.stop();
69
+ void Promise.race([executor.idle(), delay(3000, undefined, { ref: false })]).then(() => error ? reject(error) : resolve());
70
+ };
71
+ const abort = () => finish();
72
+ const connection = connectGateway({
73
+ gatewayUrl,
74
+ getToken: () => active.token,
75
+ createSocket: createNodeSocket,
76
+ beforeConnect: async () => {
77
+ try {
78
+ return await gatewayConfig(cloudUrl, active.token);
79
+ }
80
+ catch (error) {
81
+ if (error instanceof CloudError && error.code === "invalid_device_session")
82
+ return null;
83
+ throw error;
84
+ }
85
+ },
86
+ onMessage: (message) => {
87
+ if ("from" in message)
88
+ void executor.receive(message);
89
+ },
90
+ onFrame: (frame) => void executor.receiveFrame(frame),
91
+ onNotification: options.onNotification,
92
+ onStatus: (status) => {
93
+ options.audit?.host({
94
+ event: "connection",
95
+ status,
96
+ deviceId: active.deviceId,
97
+ name: active.name,
98
+ cloudOrigin: cloudUrl,
99
+ }, [active.token]);
100
+ options.onEvent?.({ type: "connection", status });
101
+ if (status !== "online" && status !== "connecting")
102
+ executor.disconnect();
103
+ if (status === "revoked" || status === "superseded") {
104
+ queueMicrotask(() => finish(new Error(status === "revoked"
105
+ ? "Authorization revoked. Explicit authorization is required."
106
+ : "Another connection replaced this device. This process has stopped.")));
107
+ }
108
+ },
109
+ });
110
+ signal.addEventListener("abort", abort, { once: true });
111
+ if (signal.aborted)
112
+ abort();
113
+ });
114
+ }
package/dist/host.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export { connectHost, defaultDeviceName, type HostCredential, type HostEvent, type HostOptions, } from "./connect.js";
2
+ export { connectLimitedHost, type LimitedHostOptions } from "./limited-host.js";
2
3
  export { loginDevice, type DeviceSession } from "./login.js";
4
+ export { type GatewayNotification } from "./protocol.js";
3
5
  export { loginDeviceCode, type DeviceAuthorizationPrompt } from "./device-authorization.js";
4
6
  export { createFileCredentialStore, type CredentialStore } from "./storage.js";
5
7
  export { AuditStore, type AuditItem, type AuditQuery, type AuditResult, type AuditStats, type AuditStatus, type AuditSummary, type ContentName, } from "./audit.js";
package/dist/host.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { connectHost, defaultDeviceName, } from "./connect.js";
2
+ export { connectLimitedHost } from "./limited-host.js";
2
3
  export { loginDevice } from "./login.js";
3
4
  export { loginDeviceCode } from "./device-authorization.js";
4
5
  export { createFileCredentialStore } from "./storage.js";
@@ -0,0 +1,3 @@
1
+ import { type HostConnectionOptions } from "./host-connection.js";
2
+ export type LimitedHostOptions = HostConnectionOptions;
3
+ export declare function connectLimitedHost(options: LimitedHostOptions): Promise<void>;
@@ -0,0 +1,5 @@
1
+ import { runHostConnection } from "./host-connection.js";
2
+ import { createLimitedResponder } from "./limited.js";
3
+ export function connectLimitedHost(options) {
4
+ return runHostConnection(options, (session, send, sendFrame) => createLimitedResponder(session.name, send, sendFrame));
5
+ }
@@ -0,0 +1,10 @@
1
+ import { type ActionResponse } from "./actions.js";
2
+ import { type Frame } from "./frame.js";
3
+ import type { InboundEnvelope, OutboundEnvelope } from "./protocol.js";
4
+ export declare const COMPUTER_USE_OFF: ActionResponse;
5
+ export declare function createLimitedResponder(name: string, send: (message: OutboundEnvelope) => boolean, sendFrame?: (frame: Frame) => boolean): {
6
+ receive(message: InboundEnvelope): void;
7
+ receiveFrame(frame: Frame): void;
8
+ idle: () => Promise<void>;
9
+ disconnect(): void;
10
+ };
@@ -0,0 +1,43 @@
1
+ import { platform } from "node:os";
2
+ import { actionError, isRecord } from "./actions.js";
3
+ import { decodeMeta, encodeMeta, FRAME_TYPE } from "./frame.js";
4
+ export const COMPUTER_USE_OFF = actionError("computer_use_off", "Computer use is turned off on this Mac, so it did not run the request.");
5
+ const empty = new Uint8Array();
6
+ export function createLimitedResponder(name, send, sendFrame = () => false) {
7
+ const info = () => ({
8
+ type: "response",
9
+ ok: true,
10
+ result: {
11
+ name,
12
+ platform: platform() === "darwin" ? "macos" : platform() === "win32" ? "windows" : platform(),
13
+ actions: [],
14
+ computerUse: false,
15
+ frameVersion: 1,
16
+ },
17
+ });
18
+ const answer = (action) => action === "system.info" ? info() : COMPUTER_USE_OFF;
19
+ return {
20
+ receive(message) {
21
+ const request = message.payload;
22
+ if (!isRecord(request) || request.type !== "request" || typeof request.action !== "string")
23
+ return;
24
+ send({ id: message.id, to: message.from, payload: answer(request.action) });
25
+ },
26
+ receiveFrame(frame) {
27
+ if (frame.type !== FRAME_TYPE.request)
28
+ return;
29
+ const request = decodeMeta(frame.meta);
30
+ if (!isRecord(request) || request.type !== "request" || typeof request.action !== "string")
31
+ return;
32
+ sendFrame({
33
+ type: FRAME_TYPE.response,
34
+ id: frame.id,
35
+ peer: frame.peer,
36
+ meta: encodeMeta(answer(request.action)),
37
+ body: empty,
38
+ });
39
+ },
40
+ idle: () => Promise.resolve(),
41
+ disconnect() { },
42
+ };
43
+ }
@@ -26,5 +26,18 @@ export type GatewayMessage = InboundEnvelope | RouteError;
26
26
  export declare function validId(value: unknown): value is string;
27
27
  export declare function outboundEnvelope(value: unknown): OutboundEnvelope | null;
28
28
  export declare function gatewayMessage(value: unknown): GatewayMessage | null;
29
+ export interface GatewayNotification {
30
+ title: string;
31
+ body: string;
32
+ instanceId: string;
33
+ level?: "active" | "passive";
34
+ chatId?: string;
35
+ }
36
+ export declare const NOTIFICATION_LIMITS: {
37
+ readonly title: 200;
38
+ readonly body: 2000;
39
+ readonly id: 128;
40
+ };
41
+ export declare function gatewayNotification(value: unknown): GatewayNotification | null;
29
42
  export declare function byteLength(value: string): number;
30
43
  export {};
package/dist/protocol.js CHANGED
@@ -35,6 +35,35 @@ export function gatewayMessage(value) {
35
35
  return { id: item.id, from: item.from, payload: item.payload };
36
36
  return null;
37
37
  }
38
+ export const NOTIFICATION_LIMITS = { title: 200, body: 2000, id: 128 };
39
+ const text = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
40
+ export function gatewayNotification(value) {
41
+ if (!value || typeof value !== "object" || Array.isArray(value))
42
+ return null;
43
+ const item = value;
44
+ if (item.type !== "notification" || Object.hasOwn(item, "id") || Object.hasOwn(item, "from"))
45
+ return null;
46
+ if (!text(item.title, NOTIFICATION_LIMITS.title) ||
47
+ !text(item.body, NOTIFICATION_LIMITS.body) ||
48
+ !text(item.instanceId, NOTIFICATION_LIMITS.id))
49
+ return null;
50
+ const notification = {
51
+ title: item.title,
52
+ body: item.body,
53
+ instanceId: item.instanceId,
54
+ };
55
+ if (item.level !== undefined) {
56
+ if (item.level !== "active" && item.level !== "passive")
57
+ return null;
58
+ notification.level = item.level;
59
+ }
60
+ if (item.chatId !== undefined) {
61
+ if (!text(item.chatId, NOTIFICATION_LIMITS.id))
62
+ return null;
63
+ notification.chatId = item.chatId;
64
+ }
65
+ return notification;
66
+ }
38
67
  export function byteLength(value) {
39
68
  return new TextEncoder().encode(value).byteLength;
40
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rome-os/node-core",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "JavaScript APIs for Rome device hosts and shared caller daemons",
5
5
  "license": "MIT",
6
6
  "type": "module",