@rome-os/node-core 0.1.5 → 0.1.7

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.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 { isJwt } from "./signer.js";
3
4
  import { CLOSE, gatewayMessage, 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)
@@ -150,6 +178,7 @@ export function connectGateway(options) {
150
178
  clearTimeout(timer);
151
179
  clearTimeout(connectingTimer);
152
180
  clearTimeout(stableTimer);
181
+ clearInterval(reauthTimer);
153
182
  const previous = socket;
154
183
  socket = null;
155
184
  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,5 +1,6 @@
1
1
  import type { DeviceSession } from "./login.js";
2
2
  import type { CredentialStore } from "./storage.js";
3
+ import { type HostAudit } from "./executor.js";
3
4
  export type HostCredential = DeviceSession & {
4
5
  name: string;
5
6
  };
@@ -22,6 +23,7 @@ export interface HostOptions {
22
23
  credentials: CredentialStore<HostCredential>;
23
24
  authorize(cloudUrl: string, name: string, signal: AbortSignal): Promise<DeviceSession>;
24
25
  onEvent?(event: HostEvent): void;
26
+ audit: HostAudit;
25
27
  }
26
28
  export declare function connectHost(options: HostOptions): Promise<void>;
27
29
  export declare const defaultDeviceName: () => string;
package/dist/connect.js CHANGED
@@ -59,7 +59,7 @@ export async function connectHost(options) {
59
59
  const active = session;
60
60
  options.onEvent?.({ type: "device", name: active.name, deviceId: active.deviceId });
61
61
  await new Promise((resolve, reject) => {
62
- const executor = createExecutor(active.name, (message) => connection.send(message), [active.token], (frame) => connection.sendFrame(frame));
62
+ const executor = createExecutor(active.name, options.audit, (message) => connection.send(message), [active.token], (frame) => connection.sendFrame(frame));
63
63
  let finished = false;
64
64
  const finish = (error) => {
65
65
  if (finished)
@@ -68,15 +68,12 @@ export async function connectHost(options) {
68
68
  signal.removeEventListener("abort", abort);
69
69
  executor.disconnect();
70
70
  connection.stop();
71
- if (error)
72
- reject(error);
73
- else
74
- resolve();
71
+ void Promise.race([executor.idle(), delay(3000, undefined, { ref: false })]).then(() => error ? reject(error) : resolve());
75
72
  };
76
73
  const abort = () => finish();
77
74
  const connection = connectGateway({
78
75
  gatewayUrl,
79
- deviceToken: active.token,
76
+ getToken: () => active.token,
80
77
  createSocket: createNodeSocket,
81
78
  beforeConnect: async () => {
82
79
  try {
@@ -94,6 +91,13 @@ export async function connectHost(options) {
94
91
  },
95
92
  onFrame: (frame) => void executor.receiveFrame(frame),
96
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]);
97
101
  options.onEvent?.({ type: "connection", status });
98
102
  if (status !== "online" && status !== "connecting")
99
103
  executor.disconnect();
@@ -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",
@@ -5,6 +5,11 @@ export interface DeviceStatus {
5
5
  name: string;
6
6
  platform: string | null;
7
7
  status: "connected" | "not_connected" | "unknown" | "revoked";
8
+ audit?: {
9
+ state: "ok" | "unavailable";
10
+ code?: string;
11
+ message?: string;
12
+ };
8
13
  }
9
14
  export interface DevicesStatus {
10
15
  connection: ConnectionStatus;
@@ -55,6 +55,13 @@ export class DeviceStatusReader {
55
55
  : response.error.code === "target_unavailable"
56
56
  ? "not_connected"
57
57
  : "unknown";
58
+ const audit = response.ok && isRecord(response.result) ? response.result.audit : undefined;
59
+ if (isRecord(audit) && (audit.state === "ok" || audit.state === "unavailable"))
60
+ device.audit = {
61
+ state: audit.state,
62
+ ...(typeof audit.code === "string" ? { code: audit.code } : {}),
63
+ ...(typeof audit.message === "string" ? { message: audit.message } : {}),
64
+ };
58
65
  }
59
66
  }));
60
67
  const connection = this.connector.getStatus();
@@ -1,9 +1,12 @@
1
+ import { type AuditStore } from "./audit.js";
1
2
  import { type Frame } from "./frame.js";
2
3
  import type { InboundEnvelope, OutboundEnvelope } from "./protocol.js";
3
4
  export declare const FS_LIST_LIMIT = 1000;
4
5
  export declare function redactBytes(data: Buffer, secrets: string[]): Buffer;
5
- export declare function createExecutor(name: string, send: (message: OutboundEnvelope) => boolean, secrets?: string[], sendFrame?: (frame: Frame) => boolean): {
6
- receive(message: InboundEnvelope): Promise<void>;
7
- receiveFrame(frame: Frame): Promise<void>;
8
- disconnect(): void;
6
+ export type HostAudit = Pick<AuditStore, "start" | "end" | "host" | "status" | "hint">;
7
+ export declare function createExecutor(name: string, audit: HostAudit, send: (message: OutboundEnvelope) => boolean, secrets?: string[], sendFrame?: (frame: Frame) => boolean): {
8
+ receive: (message: InboundEnvelope) => Promise<void>;
9
+ receiveFrame: (frame: Frame) => Promise<void>;
10
+ idle: () => Promise<void>;
11
+ disconnect: () => void;
9
12
  };
package/dist/executor.js CHANGED
@@ -3,6 +3,7 @@ import { readdir, realpath, stat } from "node:fs/promises";
3
3
  import { homedir, platform } from "node:os";
4
4
  import { dirname, resolve } from "node:path";
5
5
  import { actionError, isRecord } from "./actions.js";
6
+ import { AUDIT_PUSH_BYTES } from "./audit.js";
6
7
  import { decodeMeta, encodeMeta, FRAME_TYPE, frameFits, MAX_FRAME_BYTES, } from "./frame.js";
7
8
  import { parseTransferMessage, TRANSFER_VERSION, TransferHost } from "./transfer.js";
8
9
  function execInput(input) {
@@ -82,11 +83,26 @@ export function redactBytes(data, secrets) {
82
83
  }
83
84
  return data;
84
85
  }
85
- export function createExecutor(name, send, secrets = [], sendFrame = () => false) {
86
+ function childEnvironment() {
87
+ return Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:ROME_.*(?:TOKEN|SECRET|CREDENTIAL)|NODE_OPTIONS)$/i.test(key)));
88
+ }
89
+ function outcomeOf(response, interrupted) {
90
+ if (interrupted)
91
+ return "interrupted";
92
+ if (!response.ok)
93
+ return "error";
94
+ const result = response.result;
95
+ return isRecord(result) &&
96
+ Object.hasOwn(result, "exitCode") &&
97
+ (result.exitCode !== 0 || result.signal !== null)
98
+ ? "exit_nonzero"
99
+ : "ok";
100
+ }
101
+ export function createExecutor(name, audit, send, secrets = [], sendFrame = () => false) {
86
102
  const children = new Set();
87
- const transfers = new TransferHost();
103
+ const transfers = new TransferHost({ keepBytes: AUDIT_PUSH_BYTES });
88
104
  let generation = 0;
89
- const info = () => ({
105
+ const info = async () => ({
90
106
  type: "response",
91
107
  ok: true,
92
108
  result: {
@@ -95,19 +111,40 @@ export function createExecutor(name, send, secrets = [], sendFrame = () => false
95
111
  actions: ["system.info", "exec", "fs.list"],
96
112
  frameVersion: 1,
97
113
  transferVersion: TRANSFER_VERSION,
114
+ audit: await audit.status(),
98
115
  },
99
116
  });
117
+ const refused = () => actionError("audit_unavailable", `This computer could not record the request in its audit log, so it did not run it. ${audit.hint}`);
118
+ const replaced = () => actionError("connection_replaced", "The connection was replaced before the request ran.");
119
+ const startRecord = (action, args, extra) => ({
120
+ ...extra,
121
+ args,
122
+ ...(action === "exec" ? { envKeys: Object.keys(childEnvironment()).sort() } : {}),
123
+ });
124
+ function endRecord(action, startSeq, started, response, interrupted, notes, replyBytes) {
125
+ const fields = {
126
+ durationMs: Date.now() - started,
127
+ ...notes.fields,
128
+ ...(response.ok ? {} : { errorCode: response.error.code }),
129
+ replyBytes: interrupted ? 0 : replyBytes,
130
+ };
131
+ if (action === "fs.list" && response.ok && isRecord(response.result)) {
132
+ fields.path = response.result.path;
133
+ fields.entries = response.result.entries;
134
+ fields.truncated = response.result.truncated;
135
+ }
136
+ audit.end(startSeq, action, outcomeOf(response, interrupted), fields, notes.content, secrets);
137
+ }
100
138
  const invalidExec = () => actionError("invalid_args", "exec requires command, optional string args[], and optional cwd.");
101
- function runProgram({ command, args, cwd }, stdin) {
139
+ function runProgram({ command, args, cwd }, notes, stdin) {
102
140
  if (children.size >= 8)
103
141
  return Promise.resolve(actionError("busy", "The computer is already running eight programs."));
104
142
  return new Promise((resolve) => {
105
- const environment = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:ROME_.*(?:TOKEN|SECRET|CREDENTIAL)|NODE_OPTIONS)$/i.test(key)));
106
143
  let child;
107
144
  try {
108
145
  child = spawn(command, args, {
109
146
  cwd,
110
- env: environment,
147
+ env: childEnvironment(),
111
148
  shell: false,
112
149
  windowsHide: true,
113
150
  stdio: [stdin ? "pipe" : "ignore", "pipe", "pipe"],
@@ -118,6 +155,7 @@ export function createExecutor(name, send, secrets = [], sendFrame = () => false
118
155
  return;
119
156
  }
120
157
  children.add(child);
158
+ notes.fields.pid = child.pid ?? null;
121
159
  if (stdin && child.stdin) {
122
160
  child.stdin.on("error", () => { });
123
161
  child.stdin.end(stdin);
@@ -134,24 +172,28 @@ export function createExecutor(name, send, secrets = [], sendFrame = () => false
134
172
  });
135
173
  child.once("close", (exitCode, signal) => {
136
174
  children.delete(child);
137
- resolve({
175
+ const result = {
138
176
  exitCode,
139
177
  signal,
140
178
  stdout: Buffer.concat(output.stdout),
141
179
  stderr: Buffer.concat(output.stderr),
142
- });
180
+ };
181
+ notes.fields.exitCode = exitCode;
182
+ notes.fields.signal = signal;
183
+ notes.content = { stdout: result.stdout, stderr: result.stderr };
184
+ resolve(result);
143
185
  });
144
186
  });
145
187
  }
146
188
  const redactText = (data) => secrets.reduce((text, secret) => text.replaceAll(secret, "[redacted]"), data.toString("utf8"));
147
189
  const isOutput = (value) => !("type" in value);
148
190
  const handlers = {
149
- "system.info": async () => info(),
150
- exec: async (input) => {
191
+ "system.info": () => info(),
192
+ exec: async (input, notes) => {
151
193
  const parsed = execInput(input);
152
194
  if (!parsed)
153
195
  return invalidExec();
154
- const output = await runProgram(parsed);
196
+ const output = await runProgram(parsed, notes);
155
197
  if (!isOutput(output))
156
198
  return output;
157
199
  return {
@@ -170,13 +212,13 @@ export function createExecutor(name, send, secrets = [], sendFrame = () => false
170
212
  };
171
213
  const empty = new Uint8Array();
172
214
  const frameHandlers = {
173
- "system.info": async () => ({ response: info(), body: empty }),
215
+ "system.info": async () => ({ response: await info(), body: empty }),
174
216
  "fs.list": async (input) => ({ response: await listFolder(input), body: empty }),
175
- exec: async (input, body) => {
217
+ exec: async (input, body, notes) => {
176
218
  const parsed = execInput(input);
177
219
  if (!parsed)
178
220
  return { response: invalidExec(), body: empty };
179
- const output = await runProgram(parsed, body);
221
+ const output = await runProgram(parsed, notes, body);
180
222
  if (!isOutput(output))
181
223
  return { response: output, body: empty };
182
224
  return {
@@ -194,81 +236,152 @@ export function createExecutor(name, send, secrets = [], sendFrame = () => false
194
236
  };
195
237
  },
196
238
  };
239
+ let running = 0;
240
+ const drained = [];
241
+ async function track(work) {
242
+ running++;
243
+ try {
244
+ await work();
245
+ }
246
+ finally {
247
+ if (--running === 0)
248
+ for (const resolve of drained.splice(0))
249
+ resolve();
250
+ }
251
+ }
197
252
  return {
198
- async receive(message) {
199
- const request = message.payload;
200
- if (!isRecord(request) || request.type !== "request" || typeof request.action !== "string")
201
- return;
202
- const current = generation;
203
- const handler = Object.hasOwn(handlers, request.action)
204
- ? handlers[request.action]
205
- : undefined;
206
- const payload = handler
207
- ? await handler(request.args).catch(() => actionError("exec_failed", "The action failed."))
208
- : actionError("unsupported_action", "The computer does not support this action.");
209
- const reply = { id: message.id, to: message.from, payload };
210
- if (current === generation)
211
- send(reply);
212
- },
213
- async receiveFrame(frame) {
214
- if (frame.type !== FRAME_TYPE.request)
215
- return;
216
- const request = decodeMeta(frame.meta);
217
- const transfer = parseTransferMessage(request);
218
- if (transfer) {
219
- transfers.receive(frame.id, frame.peer, transfer, frame.body);
220
- return;
221
- }
222
- if (!isRecord(request) || request.type !== "request" || typeof request.action !== "string")
223
- return;
224
- const current = generation;
225
- if (request.action === "transfer.open") {
226
- void transfers.open(frame.id, frame.peer, request.args, (meta, body = empty) => {
227
- if (current !== generation)
228
- return false;
229
- return sendFrame({
230
- type: FRAME_TYPE.response,
231
- id: frame.id,
232
- peer: frame.peer,
233
- meta: encodeMeta(meta),
234
- body,
235
- });
236
- });
237
- return;
238
- }
239
- const handler = Object.hasOwn(frameHandlers, request.action)
240
- ? frameHandlers[request.action]
241
- : undefined;
242
- const result = handler
243
- ? await handler(request.args, frame.body).catch(() => ({
244
- response: actionError("exec_failed", "The action failed."),
245
- body: empty,
246
- }))
247
- : {
248
- response: actionError("unsupported_action", "The computer does not support this action."),
249
- body: empty,
250
- };
251
- if (current !== generation)
252
- return;
253
- let meta = encodeMeta(result.response);
254
- let body = result.body;
255
- if (!frameFits(meta.byteLength, body.byteLength)) {
256
- meta = encodeMeta(actionError("output_too_large", `The output does not fit in one ${MAX_FRAME_BYTES / 1024 / 1024} MiB frame and was discarded. The program ran. Use rome-node cp to copy large files.`));
257
- body = empty;
258
- }
259
- sendFrame({ type: FRAME_TYPE.response, id: frame.id, peer: frame.peer, meta, body });
260
- },
261
- disconnect() {
262
- generation++;
263
- transfers.abortAll();
264
- for (const child of children) {
265
- child.kill("SIGTERM");
266
- const timer = setTimeout(() => {
267
- if (child.exitCode === null && child.signalCode === null)
268
- child.kill("SIGKILL");
269
- }, 1000);
270
- timer.unref();
271
- }
272
- },
253
+ receive: (message) => track(() => receive(message)),
254
+ receiveFrame: (frame) => track(() => receiveFrame(frame)),
255
+ idle: () => running ? new Promise((resolve) => drained.push(resolve)) : Promise.resolve(),
256
+ disconnect,
273
257
  };
258
+ async function receive(message) {
259
+ const request = message.payload;
260
+ if (!isRecord(request) || request.type !== "request" || typeof request.action !== "string")
261
+ return;
262
+ const current = generation;
263
+ const action = request.action;
264
+ const handler = Object.hasOwn(handlers, action) ? handlers[action] : undefined;
265
+ const notes = { fields: {}, content: {} };
266
+ const started = Date.now();
267
+ const seq = action === "system.info"
268
+ ? 0
269
+ : await audit.start(action, startRecord(action, request.args, {
270
+ requestId: message.id,
271
+ from: message.from,
272
+ transport: "json",
273
+ generation: current,
274
+ }), {}, secrets);
275
+ const payload = seq === null
276
+ ? refused()
277
+ : current !== generation
278
+ ? replaced()
279
+ : handler
280
+ ? await handler(request.args, notes).catch(() => actionError("exec_failed", "The action failed."))
281
+ : actionError("unsupported_action", "The computer does not support this action.");
282
+ const reply = { id: message.id, to: message.from, payload };
283
+ const interrupted = current !== generation;
284
+ if (seq)
285
+ endRecord(action, seq, started, payload, interrupted, notes, interrupted ? 0 : Buffer.byteLength(JSON.stringify(reply)));
286
+ if (!interrupted)
287
+ send(reply);
288
+ }
289
+ async function receiveFrame(frame) {
290
+ if (frame.type !== FRAME_TYPE.request)
291
+ return;
292
+ const request = decodeMeta(frame.meta);
293
+ const transfer = parseTransferMessage(request);
294
+ if (transfer) {
295
+ transfers.receive(frame.id, frame.peer, transfer, frame.body);
296
+ return;
297
+ }
298
+ if (!isRecord(request) || request.type !== "request" || typeof request.action !== "string")
299
+ return;
300
+ const current = generation;
301
+ const action = request.action;
302
+ const respond = (response) => current === generation &&
303
+ sendFrame({
304
+ type: FRAME_TYPE.response,
305
+ id: frame.id,
306
+ peer: frame.peer,
307
+ meta: encodeMeta(response),
308
+ body: empty,
309
+ });
310
+ const started = Date.now();
311
+ const seq = action === "system.info"
312
+ ? 0
313
+ : await audit.start(action, startRecord(action, request.args, {
314
+ requestId: frame.id,
315
+ from: frame.peer,
316
+ transport: "binary",
317
+ generation: current,
318
+ }), { stdin: frame.body }, secrets);
319
+ if (seq === null) {
320
+ respond(refused());
321
+ return;
322
+ }
323
+ if (current !== generation) {
324
+ endRecord(action, seq, started, replaced(), true, { fields: {}, content: {} }, 0);
325
+ return;
326
+ }
327
+ if (action === "transfer.open") {
328
+ const transfer = transfers.open(frame.id, frame.peer, request.args, (meta, body = empty) => {
329
+ if (current !== generation)
330
+ return false;
331
+ return sendFrame({
332
+ type: FRAME_TYPE.response,
333
+ id: frame.id,
334
+ peer: frame.peer,
335
+ meta: encodeMeta(meta),
336
+ body,
337
+ });
338
+ });
339
+ void track(() => transfer.then(({ code, file, ...fields }) => {
340
+ const response = code
341
+ ? actionError(code, "")
342
+ : { type: "response", ok: true, result: null };
343
+ endRecord(action, seq, started, response, current !== generation, { fields, content: file ? { file } : {} }, 0);
344
+ }));
345
+ return;
346
+ }
347
+ const handler = Object.hasOwn(frameHandlers, action) ? frameHandlers[action] : undefined;
348
+ const notes = { fields: {}, content: {} };
349
+ const result = handler
350
+ ? await handler(request.args, frame.body, notes).catch(() => ({
351
+ response: actionError("exec_failed", "The action failed."),
352
+ body: empty,
353
+ }))
354
+ : {
355
+ response: actionError("unsupported_action", "The computer does not support this action."),
356
+ body: empty,
357
+ };
358
+ const interrupted = current !== generation;
359
+ let response = result.response;
360
+ let meta = encodeMeta(response);
361
+ let body = result.body;
362
+ if (!frameFits(meta.byteLength, body.byteLength)) {
363
+ response = actionError("output_too_large", `The output does not fit in one ${MAX_FRAME_BYTES / 1024 / 1024} MiB frame and was discarded. The program ran. Use rome-node cp to copy large files.`);
364
+ meta = encodeMeta(response);
365
+ body = empty;
366
+ }
367
+ if (seq)
368
+ endRecord(action, seq, started, response, interrupted, notes, meta.byteLength + body.byteLength);
369
+ if (interrupted)
370
+ return;
371
+ sendFrame({ type: FRAME_TYPE.response, id: frame.id, peer: frame.peer, meta, body });
372
+ }
373
+ function disconnect() {
374
+ generation++;
375
+ transfers.abortAll();
376
+ for (const child of children) {
377
+ child.kill("SIGTERM");
378
+ const timer = setTimeout(() => {
379
+ if (child.exitCode === null && child.signalCode === null)
380
+ child.kill("SIGKILL");
381
+ child.stdout?.destroy();
382
+ child.stderr?.destroy();
383
+ }, 1000);
384
+ timer.unref();
385
+ }
386
+ }
274
387
  }
package/dist/host.d.ts CHANGED
@@ -2,3 +2,4 @@ export { connectHost, defaultDeviceName, type HostCredential, type HostEvent, ty
2
2
  export { loginDevice, type DeviceSession } from "./login.js";
3
3
  export { loginDeviceCode, type DeviceAuthorizationPrompt } from "./device-authorization.js";
4
4
  export { createFileCredentialStore, type CredentialStore } from "./storage.js";
5
+ export { AuditStore, type AuditItem, type AuditQuery, type AuditResult, type AuditStats, type AuditStatus, type AuditSummary, type ContentName, } from "./audit.js";
package/dist/host.js CHANGED
@@ -2,3 +2,4 @@ export { connectHost, defaultDeviceName, } from "./connect.js";
2
2
  export { loginDevice } from "./login.js";
3
3
  export { loginDeviceCode } from "./device-authorization.js";
4
4
  export { createFileCredentialStore } from "./storage.js";
5
+ export { AuditStore, } from "./audit.js";