@rome-os/node-core 0.1.6 → 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/auth.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { type NodeConfig } from "./local.js";
2
2
  export declare function configureCaller(origin: string, token: string, config: NodeConfig): Promise<void>;
3
+ export declare function configureSignerCaller(origin: string, signerSocket: string, config: NodeConfig): Promise<void>;
3
4
  export declare function authorizeServer(origin: string, instanceToken: string | undefined, config: NodeConfig, onRetry?: () => void): Promise<void>;
package/dist/auth.js CHANGED
@@ -20,6 +20,19 @@ export async function configureCaller(origin, token, config) {
20
20
  await gatewayConfig(origin, token);
21
21
  await writePrivateJson(callerCredentialPath(config), { cloudUrl: origin, token });
22
22
  }
23
+ export async function configureSignerCaller(origin, signerSocket, config) {
24
+ const cloudUrl = cloudOrigin(origin);
25
+ const existing = await readOptionalCallerCredential(config);
26
+ if (existing?.cloudUrl === cloudUrl && existing.signerSocket === signerSocket)
27
+ return;
28
+ if (await daemonStatus(config))
29
+ throw new CallerConfigurationError("daemon_running", "Stop the caller daemon before changing credentials.");
30
+ await writePrivateJson(callerCredentialPath(config), {
31
+ version: 2,
32
+ cloudUrl,
33
+ signerSocket,
34
+ });
35
+ }
23
36
  async function exchangeInstanceToken(origin, token) {
24
37
  let response;
25
38
  try {
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;
@@ -16,11 +16,13 @@ export interface ClientSocket {
16
16
  export type ConnectionStatus = "connecting" | "online" | "retrying" | "revoked" | "superseded" | "stopped";
17
17
  export interface GatewayClientOptions {
18
18
  gatewayUrl: string;
19
- deviceToken: string;
19
+ getToken(): string | Promise<string>;
20
+ fetch?: typeof fetch;
20
21
  createSocket(url: string, authorization: string): ClientSocket;
21
22
  onMessage(message: GatewayMessage): void;
22
23
  onFrame?(frame: Frame): void;
23
24
  onStatus?(status: ConnectionStatus): void;
25
+ onNotification?(notification: GatewayNotification): void;
24
26
  random?(): number;
25
27
  beforeConnect?(): Promise<string | null>;
26
28
  }
package/dist/client.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { encodeFrame, FRAME_TYPE, frameFits, isUuid, parseFrame } from "./frame.js";
2
2
  import { parseGatewayUrl } from "./gateway-url.js";
3
- import { CLOSE, gatewayMessage, outboundEnvelope, } from "./protocol.js";
3
+ import { isJwt } from "./signer.js";
4
+ import { CLOSE, gatewayMessage, gatewayNotification, outboundEnvelope, } from "./protocol.js";
5
+ const REAUTH_INTERVAL_MS = 60_000;
6
+ const DEVICE_TOKEN = /^(?:romedev_|romemob_)[A-Za-z0-9_-]{43}$/;
4
7
  export function connectGateway(options) {
5
8
  let url = parseGatewayUrl(options.gatewayUrl);
6
- if (!/^(?:romedev_|romemob_)[A-Za-z0-9_-]{43}$/.test(options.deviceToken))
7
- throw new Error("Invalid device token format");
8
9
  let stopped = false;
9
10
  let socket = null;
10
11
  let attempt = 0;
11
12
  let timer;
12
13
  let connectingTimer;
13
14
  let stableTimer;
15
+ let reauthTimer;
14
16
  const status = (value) => options.onStatus?.(value);
15
17
  const schedule = () => {
16
18
  if (stopped || timer)
@@ -22,12 +24,31 @@ export function connectGateway(options) {
22
24
  void open();
23
25
  }, delay * (0.75 + (options.random ?? Math.random)() * 0.5));
24
26
  };
27
+ const refresh = async (current, reauth) => {
28
+ try {
29
+ const response = await (options.fetch ?? fetch)(reauth, {
30
+ method: "POST",
31
+ headers: { Authorization: `Bearer ${await options.getToken()}` },
32
+ redirect: "error",
33
+ signal: AbortSignal.timeout(10_000),
34
+ cache: "no-store",
35
+ });
36
+ if (response.status === 404 && socket === current)
37
+ current.close();
38
+ }
39
+ catch { }
40
+ };
25
41
  const open = async () => {
26
42
  if (stopped)
27
43
  return;
28
44
  status("connecting");
29
45
  let current;
46
+ let token;
30
47
  try {
48
+ const pending = options.getToken();
49
+ token = typeof pending === "string" ? pending : await pending;
50
+ if (!DEVICE_TOKEN.test(token) && !isJwt(token))
51
+ throw new Error("Invalid token format");
31
52
  if (options.beforeConnect) {
32
53
  const next = await options.beforeConnect();
33
54
  if (stopped)
@@ -39,7 +60,7 @@ export function connectGateway(options) {
39
60
  }
40
61
  url = parseGatewayUrl(next);
41
62
  }
42
- current = options.createSocket(url.toString(), `Bearer ${options.deviceToken}`);
63
+ current = options.createSocket(url.toString(), `Bearer ${token}`);
43
64
  }
44
65
  catch {
45
66
  schedule();
@@ -53,6 +74,7 @@ export function connectGateway(options) {
53
74
  finished = true;
54
75
  clearTimeout(connectingTimer);
55
76
  clearTimeout(stableTimer);
77
+ clearInterval(reauthTimer);
56
78
  socket = null;
57
79
  if (code === CLOSE.revoked || code === CLOSE.superseded) {
58
80
  stopped = true;
@@ -75,6 +97,12 @@ export function connectGateway(options) {
75
97
  attempt = 0;
76
98
  }, 30_000);
77
99
  status("online");
100
+ if (isJwt(token)) {
101
+ const reauth = new URL(url);
102
+ reauth.protocol = url.protocol === "wss:" ? "https:" : "http:";
103
+ reauth.pathname = "/reauth";
104
+ reauthTimer = setInterval(() => void refresh(current, reauth), REAUTH_INTERVAL_MS);
105
+ }
78
106
  });
79
107
  current.addEventListener("message", ({ data }) => {
80
108
  if (stopped || socket !== current)
@@ -90,13 +118,22 @@ export function connectGateway(options) {
90
118
  options.onFrame?.(frame);
91
119
  return;
92
120
  }
93
- let message;
121
+ let json;
94
122
  try {
95
- message = gatewayMessage(JSON.parse(data));
123
+ json = JSON.parse(data);
96
124
  }
97
125
  catch {
98
126
  return;
99
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);
100
137
  if (message)
101
138
  options.onMessage(message);
102
139
  });
@@ -150,6 +187,7 @@ export function connectGateway(options) {
150
187
  clearTimeout(timer);
151
188
  clearTimeout(connectingTimer);
152
189
  clearTimeout(stableTimer);
190
+ clearInterval(reauthTimer);
153
191
  const previous = socket;
154
192
  socket = null;
155
193
  previous?.close(1000, "client stopped");
package/dist/cloud.d.ts CHANGED
@@ -3,5 +3,6 @@ export declare class CloudError extends Error {
3
3
  constructor(code: string);
4
4
  }
5
5
  export declare function cloudOrigin(value: string): string;
6
- export declare function cloudRequest(origin: string, path: string, token: string, method?: string, json?: unknown): Promise<unknown>;
7
- export declare function gatewayConfig(origin: string, token: string): Promise<string>;
6
+ export type TokenSource = string | (() => string | Promise<string>);
7
+ export declare function cloudRequest(origin: string, path: string, token: TokenSource, method?: string, json?: unknown): Promise<unknown>;
8
+ export declare function gatewayConfig(origin: string, token: TokenSource): Promise<string>;
package/dist/cloud.js CHANGED
@@ -32,7 +32,7 @@ export async function cloudRequest(origin, path, token, method = "GET", json) {
32
32
  response = await fetch(new URL(path, cloudOrigin(origin)), {
33
33
  method,
34
34
  headers: {
35
- Authorization: `Bearer ${token}`,
35
+ Authorization: `Bearer ${typeof token === "string" ? token : await token()}`,
36
36
  ...(json === undefined ? {} : { "content-type": "application/json" }),
37
37
  },
38
38
  body: json === undefined ? undefined : JSON.stringify(json),
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
- deviceToken: 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, "")
@@ -1,6 +1,6 @@
1
1
  import { type ActionResponse, type BinaryActionResult } from "./actions.js";
2
2
  import { connectGateway, type ConnectionStatus } from "./client.js";
3
- import type { CallerCredential } from "./local.js";
3
+ import { type CallerCredential } from "./local.js";
4
4
  import type { ChannelEvents, TransferChannel } from "./transfer.js";
5
5
  export interface DeviceConnectorOptions {
6
6
  credential: CallerCredential;
package/dist/connector.js CHANGED
@@ -5,6 +5,7 @@ import { cloudRequest, CloudError, gatewayConfig } from "./cloud.js";
5
5
  import { decodeMeta, encodeMeta, FRAME_TYPE, frameFits, isUuid, MAX_FRAME_BYTES, } from "./frame.js";
6
6
  import { validId } from "./protocol.js";
7
7
  import { createNodeSocket } from "./socket.js";
8
+ import { callerToken } from "./local.js";
8
9
  const MAX_PENDING = 128;
9
10
  export class DeviceConnector {
10
11
  options;
@@ -37,13 +38,14 @@ export class DeviceConnector {
37
38
  }
38
39
  }
39
40
  async initialize() {
40
- const { cloudUrl, token } = this.options.credential;
41
+ const { cloudUrl } = this.options.credential;
42
+ const token = callerToken(this.options.credential);
41
43
  const gatewayUrl = await gatewayConfig(cloudUrl, token);
42
44
  if (this.stopped)
43
45
  throw new Error("connector_stopped");
44
46
  this.connection = (this.options.connect ?? connectGateway)({
45
47
  gatewayUrl,
46
- deviceToken: token,
48
+ getToken: token,
47
49
  createSocket: createNodeSocket,
48
50
  beforeConnect: async () => {
49
51
  try {
@@ -74,8 +76,8 @@ export class DeviceConnector {
74
76
  async list() {
75
77
  if (this.stopped)
76
78
  throw new Error("connector_stopped");
77
- const { cloudUrl, token } = this.options.credential;
78
- const body = await cloudRequest(cloudUrl, "/api/account/devices", token);
79
+ const { cloudUrl } = this.options.credential;
80
+ const body = await cloudRequest(cloudUrl, "/api/account/devices", callerToken(this.options.credential));
79
81
  if (!isRecord(body) || !Array.isArray(body.items))
80
82
  throw new CloudError("invalid_response");
81
83
  return { items: body.items };
@@ -85,7 +87,8 @@ export class DeviceConnector {
85
87
  throw new Error("connector_stopped");
86
88
  if (!isUuid(deviceId))
87
89
  throw new CloudError("device_not_found");
88
- const { cloudUrl, token } = this.options.credential;
90
+ const { cloudUrl } = this.options.credential;
91
+ const token = callerToken(this.options.credential);
89
92
  await cloudRequest(cloudUrl, `/api/account/devices/${deviceId}`, token, "PATCH", { name });
90
93
  }
91
94
  async remove(deviceId) {
@@ -93,7 +96,8 @@ export class DeviceConnector {
93
96
  throw new Error("connector_stopped");
94
97
  if (!isUuid(deviceId))
95
98
  throw new CloudError("device_not_found");
96
- const { cloudUrl, token } = this.options.credential;
99
+ const { cloudUrl } = this.options.credential;
100
+ const token = callerToken(this.options.credential);
97
101
  await cloudRequest(cloudUrl, `/api/account/devices/${deviceId}`, token, "DELETE");
98
102
  }
99
103
  receive(message) {
package/dist/daemon.js CHANGED
@@ -89,7 +89,7 @@ export async function serveDaemon(config, signal) {
89
89
  let closing = false;
90
90
  const store = new ObserveStore({
91
91
  path: join(config.directory, "observe.db"),
92
- secrets: [credential.token, state.token],
92
+ secrets: credential.token ? [credential.token, state.token] : [state.token],
93
93
  });
94
94
  const caller = {
95
95
  connection: "stopped",
@@ -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
+ }
package/dist/local.d.ts CHANGED
@@ -11,8 +11,10 @@ export declare const callerCredentialPath: (config: NodeConfig) => string;
11
11
  export declare const daemonStatePath: (config: NodeConfig) => string;
12
12
  export interface CallerCredential {
13
13
  cloudUrl: string;
14
- token: string;
14
+ token?: string;
15
+ signerSocket?: string;
15
16
  }
17
+ export declare function callerToken(credential: CallerCredential): () => string | Promise<string>;
16
18
  export declare class CallerConfigurationError extends Error {
17
19
  readonly code: "not_configured" | "daemon_running" | "instance_token_required";
18
20
  constructor(code: "not_configured" | "daemon_running" | "instance_token_required", message: string);
package/dist/local.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { homedir } from "node:os";
3
- import { join, resolve } from "node:path";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
4
  import { isRecord } from "./actions.js";
5
5
  import { cloudOrigin } from "./cloud.js";
6
+ import { requestSignerToken } from "./signer.js";
6
7
  import { readPrivateJson } from "./storage.js";
7
8
  export function createNodeConfig(options) {
8
9
  const directory = resolve(options.directory);
@@ -23,6 +24,10 @@ export function nodeConfigFromEnvironment(env) {
23
24
  }
24
25
  export const callerCredentialPath = (config) => join(config.directory, "caller.json");
25
26
  export const daemonStatePath = (config) => join(config.directory, "daemon.json");
27
+ export function callerToken(credential) {
28
+ const { signerSocket, token } = credential;
29
+ return signerSocket ? () => requestSignerToken(signerSocket) : () => token;
30
+ }
26
31
  export class CallerConfigurationError extends Error {
27
32
  code;
28
33
  constructor(code, message) {
@@ -32,10 +37,13 @@ export class CallerConfigurationError extends Error {
32
37
  }
33
38
  export async function readOptionalCallerCredential(config) {
34
39
  const value = await readPrivateJson(callerCredentialPath(config));
35
- if (!isRecord(value) ||
36
- typeof value.cloudUrl !== "string" ||
37
- typeof value.token !== "string" ||
38
- !/^romedev_[A-Za-z0-9_-]{43}$/.test(value.token))
40
+ if (!isRecord(value) || typeof value.cloudUrl !== "string")
41
+ return null;
42
+ if (value.version === 2)
43
+ return typeof value.signerSocket === "string" && isAbsolute(value.signerSocket)
44
+ ? { cloudUrl: cloudOrigin(value.cloudUrl), signerSocket: value.signerSocket }
45
+ : null;
46
+ if (typeof value.token !== "string" || !/^romedev_[A-Za-z0-9_-]{43}$/.test(value.token))
39
47
  return null;
40
48
  return { cloudUrl: cloudOrigin(value.cloudUrl), token: value.token };
41
49
  }
@@ -3,6 +3,7 @@ export declare const CLOSE: {
3
3
  readonly revoked: 4001;
4
4
  readonly superseded: 4002;
5
5
  readonly outputLimit: 4003;
6
+ readonly expired: 4004;
6
7
  readonly invalid: 1008;
7
8
  readonly tooLarge: 1009;
8
9
  };
@@ -25,5 +26,18 @@ export type GatewayMessage = InboundEnvelope | RouteError;
25
26
  export declare function validId(value: unknown): value is string;
26
27
  export declare function outboundEnvelope(value: unknown): OutboundEnvelope | null;
27
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;
28
42
  export declare function byteLength(value: string): number;
29
43
  export {};
package/dist/protocol.js CHANGED
@@ -3,6 +3,7 @@ export const CLOSE = {
3
3
  revoked: 4001,
4
4
  superseded: 4002,
5
5
  outputLimit: 4003,
6
+ expired: 4004,
6
7
  invalid: 1008,
7
8
  tooLarge: 1009,
8
9
  };
@@ -34,6 +35,35 @@ export function gatewayMessage(value) {
34
35
  return { id: item.id, from: item.from, payload: item.payload };
35
36
  return null;
36
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
+ }
37
67
  export function byteLength(value) {
38
68
  return new TextEncoder().encode(value).byteLength;
39
69
  }
@@ -0,0 +1,10 @@
1
+ export declare function isJwt(value: string): boolean;
2
+ export declare class SignerError extends Error {
3
+ readonly code: "signer_unavailable" | "rate_limited";
4
+ constructor(code: "signer_unavailable" | "rate_limited");
5
+ }
6
+ export declare function requestSignerToken(socketPath: string): Promise<string>;
7
+ export declare function signerHealth(socketPath: string): Promise<{
8
+ jkt: string;
9
+ aud: string;
10
+ }>;
package/dist/signer.js ADDED
@@ -0,0 +1,52 @@
1
+ import { request } from "node:http";
2
+ import { isRecord } from "./actions.js";
3
+ const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
4
+ export function isJwt(value) {
5
+ return value.length <= 2048 && JWT_SHAPE.test(value);
6
+ }
7
+ export class SignerError extends Error {
8
+ code;
9
+ constructor(code) {
10
+ super(code === "rate_limited"
11
+ ? "The signer is rate limited."
12
+ : "The signing service is not running.");
13
+ this.code = code;
14
+ }
15
+ }
16
+ function signerCall(socketPath, method, path) {
17
+ return new Promise((resolve, reject) => {
18
+ const req = request({ socketPath, method, path, timeout: 2000 }, (res) => {
19
+ const chunks = [];
20
+ res.on("data", (chunk) => chunks.push(chunk));
21
+ res.on("error", () => reject(new SignerError("signer_unavailable")));
22
+ res.on("end", () => {
23
+ if (res.statusCode === 200) {
24
+ try {
25
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
26
+ return;
27
+ }
28
+ catch { }
29
+ }
30
+ reject(new SignerError(res.statusCode === 429 ? "rate_limited" : "signer_unavailable"));
31
+ });
32
+ });
33
+ req.on("timeout", () => req.destroy());
34
+ req.on("error", () => reject(new SignerError("signer_unavailable")));
35
+ req.end();
36
+ });
37
+ }
38
+ export async function requestSignerToken(socketPath) {
39
+ const body = await signerCall(socketPath, "POST", "/v1/token");
40
+ if (!isRecord(body) || typeof body.token !== "string" || !isJwt(body.token))
41
+ throw new SignerError("signer_unavailable");
42
+ return body.token;
43
+ }
44
+ export async function signerHealth(socketPath) {
45
+ const body = await signerCall(socketPath, "GET", "/v1/health");
46
+ if (!isRecord(body) ||
47
+ body.ok !== true ||
48
+ typeof body.jkt !== "string" ||
49
+ typeof body.aud !== "string")
50
+ throw new SignerError("signer_unavailable");
51
+ return { jkt: body.jkt, aud: body.aud };
52
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rome-os/node-core",
3
- "version": "0.1.6",
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",
@@ -37,6 +37,10 @@
37
37
  "types": "./dist/auth.d.ts",
38
38
  "default": "./dist/auth.js"
39
39
  },
40
+ "./signer": {
41
+ "types": "./dist/signer.d.ts",
42
+ "default": "./dist/signer.js"
43
+ },
40
44
  "./socket": {
41
45
  "types": "./dist/socket.d.ts",
42
46
  "default": "./dist/socket.js"