@rome-os/node-core 0.1.5 → 0.1.6
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/audit.d.ts +112 -0
- package/dist/audit.js +506 -0
- package/dist/connect.d.ts +2 -0
- package/dist/connect.js +9 -5
- package/dist/devices-status.d.ts +5 -0
- package/dist/devices-status.js +7 -0
- package/dist/executor.d.ts +7 -4
- package/dist/executor.js +202 -89
- package/dist/host.d.ts +1 -0
- package/dist/host.js +1 -0
- package/dist/storage.d.ts +1 -0
- package/dist/storage.js +4 -2
- package/dist/transfer.d.ts +15 -1
- package/dist/transfer.js +44 -16
- package/package.json +1 -1
package/dist/audit.d.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
export declare const AUDIT_OUTPUT_BYTES: number;
|
|
2
|
+
export declare const AUDIT_PUSH_BYTES: number;
|
|
3
|
+
export type AuditKind = "host" | "start" | "end" | "prune";
|
|
4
|
+
export type AuditOutcome = "ok" | "exit_nonzero" | "error" | "interrupted";
|
|
5
|
+
export type ContentName = "stdin" | "stdout" | "stderr" | "file";
|
|
6
|
+
export type AuditUnavailableCode = "sqlite_missing" | "newer_schema" | "unreadable" | "io";
|
|
7
|
+
export type AuditStatus = {
|
|
8
|
+
state: "ok";
|
|
9
|
+
} | {
|
|
10
|
+
state: "unavailable";
|
|
11
|
+
code: AuditUnavailableCode;
|
|
12
|
+
message: string;
|
|
13
|
+
};
|
|
14
|
+
export interface AuditEvent {
|
|
15
|
+
seq: number;
|
|
16
|
+
at: number;
|
|
17
|
+
kind: AuditKind;
|
|
18
|
+
action: string | null;
|
|
19
|
+
startSeq: number | null;
|
|
20
|
+
outcome: AuditOutcome | null;
|
|
21
|
+
record: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
export interface AuditItem extends AuditEvent {
|
|
24
|
+
end: AuditEvent | null;
|
|
25
|
+
}
|
|
26
|
+
export interface AuditQuery {
|
|
27
|
+
beforeSeq?: number;
|
|
28
|
+
afterSeq?: number;
|
|
29
|
+
limit?: number;
|
|
30
|
+
since?: number;
|
|
31
|
+
until?: number;
|
|
32
|
+
action?: string;
|
|
33
|
+
outcome?: AuditOutcome | "no_end";
|
|
34
|
+
text?: string;
|
|
35
|
+
requestsOnly?: boolean;
|
|
36
|
+
result?: AuditResult;
|
|
37
|
+
}
|
|
38
|
+
export type AuditResult = "succeeded" | "failed" | "no_result";
|
|
39
|
+
export interface AuditStats {
|
|
40
|
+
since: number;
|
|
41
|
+
until: number;
|
|
42
|
+
bucketMs: number;
|
|
43
|
+
groups: {
|
|
44
|
+
peer: null;
|
|
45
|
+
bucket: number;
|
|
46
|
+
result: AuditResult;
|
|
47
|
+
count: number;
|
|
48
|
+
}[];
|
|
49
|
+
}
|
|
50
|
+
export interface AuditSummary {
|
|
51
|
+
path: string;
|
|
52
|
+
status: AuditStatus;
|
|
53
|
+
bytes: number;
|
|
54
|
+
records: number;
|
|
55
|
+
requests: number;
|
|
56
|
+
oldestAt: number | null;
|
|
57
|
+
newestAt: number | null;
|
|
58
|
+
lastPrune: AuditEvent | null;
|
|
59
|
+
retention: {
|
|
60
|
+
maxAgeDays: number;
|
|
61
|
+
maxBytes: number;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export interface AuditOpenOptions {
|
|
65
|
+
path: string;
|
|
66
|
+
entry: "cli" | "desktop";
|
|
67
|
+
hint: string;
|
|
68
|
+
version?: string;
|
|
69
|
+
readOnly?: boolean;
|
|
70
|
+
now?: () => number;
|
|
71
|
+
maxAgeMs?: number;
|
|
72
|
+
maxBytes?: number;
|
|
73
|
+
}
|
|
74
|
+
export declare class AuditStore {
|
|
75
|
+
private readonly options;
|
|
76
|
+
private db;
|
|
77
|
+
private current;
|
|
78
|
+
private lastAttempt;
|
|
79
|
+
private opening;
|
|
80
|
+
private pending;
|
|
81
|
+
private pruneTimer;
|
|
82
|
+
private readonly now;
|
|
83
|
+
private constructor();
|
|
84
|
+
get path(): string;
|
|
85
|
+
get hint(): string;
|
|
86
|
+
static open(options: AuditOpenOptions): Promise<AuditStore>;
|
|
87
|
+
ensure(): Promise<void>;
|
|
88
|
+
status(): Promise<AuditStatus>;
|
|
89
|
+
get state(): AuditStatus;
|
|
90
|
+
private fail;
|
|
91
|
+
private tryOpen;
|
|
92
|
+
private row;
|
|
93
|
+
private write;
|
|
94
|
+
private insert;
|
|
95
|
+
start(action: string, record: Record<string, unknown>, content?: {
|
|
96
|
+
stdin?: Uint8Array;
|
|
97
|
+
}, secrets?: string[]): Promise<number | null>;
|
|
98
|
+
end(startSeq: number, action: string, outcome: AuditOutcome, record: Record<string, unknown>, content?: Partial<Record<Exclude<ContentName, "stdin">, Uint8Array>>, secrets?: string[]): void;
|
|
99
|
+
host(record: Record<string, unknown>, secrets?: string[]): void;
|
|
100
|
+
private queue;
|
|
101
|
+
prune(): void;
|
|
102
|
+
close(): void;
|
|
103
|
+
private reader;
|
|
104
|
+
private event;
|
|
105
|
+
private withEnd;
|
|
106
|
+
list(query?: AuditQuery): AuditItem[];
|
|
107
|
+
resultCounts(): Record<AuditResult | "all", number>;
|
|
108
|
+
stats(since: number, until: number, bucketMs: number): AuditStats;
|
|
109
|
+
get(seq: number): AuditItem | null;
|
|
110
|
+
content(seq: number, name: ContentName): Buffer | null;
|
|
111
|
+
summary(): AuditSummary;
|
|
112
|
+
}
|
package/dist/audit.js
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, existsSync, openSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { ensurePrivateDirectory } from "./storage.js";
|
|
5
|
+
const AUDIT_SCHEMA_VERSION = 1;
|
|
6
|
+
const AUDIT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
7
|
+
const AUDIT_MAX_BYTES = 1024 * 1024 * 1024;
|
|
8
|
+
export const AUDIT_OUTPUT_BYTES = 32 * 1024 * 1024;
|
|
9
|
+
export const AUDIT_PUSH_BYTES = 10 * 1024 * 1024;
|
|
10
|
+
const RETRY_MS = 5000;
|
|
11
|
+
const PRUNE_MS = 60 * 60 * 1000;
|
|
12
|
+
const RESULT_SQL = `CASE WHEN e.seq IS NULL OR e.outcome = 'interrupted' THEN 'no_result'
|
|
13
|
+
WHEN e.outcome = 'ok' THEN 'succeeded' ELSE 'failed' END`;
|
|
14
|
+
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
|
|
15
|
+
function maskBytes(data, secrets) {
|
|
16
|
+
for (const secret of secrets) {
|
|
17
|
+
const needle = Buffer.from(secret);
|
|
18
|
+
if (!needle.byteLength)
|
|
19
|
+
continue;
|
|
20
|
+
for (let at = data.indexOf(needle); at !== -1; at = data.indexOf(needle, at + needle.length))
|
|
21
|
+
data.fill(0x2a, at, at + needle.byteLength);
|
|
22
|
+
}
|
|
23
|
+
return data;
|
|
24
|
+
}
|
|
25
|
+
function sqliteCode(error) {
|
|
26
|
+
const code = error?.errcode;
|
|
27
|
+
return code !== undefined && [11, 26].includes(code & 0xff) ? "unreadable" : "io";
|
|
28
|
+
}
|
|
29
|
+
const errorText = (error) => (error instanceof Error ? error.message : String(error));
|
|
30
|
+
export class AuditStore {
|
|
31
|
+
options;
|
|
32
|
+
db = null;
|
|
33
|
+
current = { state: "ok" };
|
|
34
|
+
lastAttempt = 0;
|
|
35
|
+
opening = null;
|
|
36
|
+
pending = [];
|
|
37
|
+
pruneTimer;
|
|
38
|
+
now;
|
|
39
|
+
constructor(options) {
|
|
40
|
+
this.options = options;
|
|
41
|
+
this.now = options.now ?? Date.now;
|
|
42
|
+
}
|
|
43
|
+
get path() {
|
|
44
|
+
return this.options.path;
|
|
45
|
+
}
|
|
46
|
+
get hint() {
|
|
47
|
+
return this.options.hint;
|
|
48
|
+
}
|
|
49
|
+
static async open(options) {
|
|
50
|
+
const store = new AuditStore(options);
|
|
51
|
+
if (!options.readOnly) {
|
|
52
|
+
try {
|
|
53
|
+
await ensurePrivateDirectory(dirname(options.path));
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
store.fail("io", `The audit folder cannot be created: ${errorText(error)}`);
|
|
57
|
+
store.lastAttempt = store.now();
|
|
58
|
+
return store;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
store.tryOpen();
|
|
62
|
+
if (!options.readOnly) {
|
|
63
|
+
store.pruneTimer = setInterval(() => store.prune(), PRUNE_MS);
|
|
64
|
+
store.pruneTimer.unref();
|
|
65
|
+
}
|
|
66
|
+
return store;
|
|
67
|
+
}
|
|
68
|
+
async ensure() {
|
|
69
|
+
if (this.db || this.now() - this.lastAttempt < RETRY_MS)
|
|
70
|
+
return;
|
|
71
|
+
this.opening ??= (async () => {
|
|
72
|
+
if (!this.options.readOnly)
|
|
73
|
+
await ensurePrivateDirectory(dirname(this.options.path)).catch(() => { });
|
|
74
|
+
this.tryOpen();
|
|
75
|
+
})().finally(() => {
|
|
76
|
+
this.opening = null;
|
|
77
|
+
});
|
|
78
|
+
await this.opening;
|
|
79
|
+
}
|
|
80
|
+
async status() {
|
|
81
|
+
await this.ensure();
|
|
82
|
+
return this.current;
|
|
83
|
+
}
|
|
84
|
+
get state() {
|
|
85
|
+
return this.current;
|
|
86
|
+
}
|
|
87
|
+
fail(code, message) {
|
|
88
|
+
this.current = { state: "unavailable", code, message: `${message} (${this.options.path})` };
|
|
89
|
+
}
|
|
90
|
+
tryOpen() {
|
|
91
|
+
this.lastAttempt = this.now();
|
|
92
|
+
const sqlite = process.getBuiltinModule?.("node:sqlite");
|
|
93
|
+
if (!sqlite?.DatabaseSync) {
|
|
94
|
+
this.fail("sqlite_missing", "This runtime has no built-in SQLite (node:sqlite).");
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const { path, readOnly } = this.options;
|
|
98
|
+
let db = null;
|
|
99
|
+
try {
|
|
100
|
+
if (readOnly && !existsSync(path)) {
|
|
101
|
+
this.fail("io", "There is no audit log yet. rome-node connect or the Rome app creates it when it first runs.");
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!readOnly && !existsSync(path))
|
|
105
|
+
closeSync(openSync(path, "a", 0o600));
|
|
106
|
+
db = new sqlite.DatabaseSync(path, readOnly ? { readOnly: true } : {});
|
|
107
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
108
|
+
const version = Number(db.prepare("PRAGMA user_version").get().user_version);
|
|
109
|
+
if (version > AUDIT_SCHEMA_VERSION) {
|
|
110
|
+
db.close();
|
|
111
|
+
this.fail("newer_schema", `The audit log was written by a newer version (schema ${version}). Update rome-node or the Rome app.`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (readOnly) {
|
|
115
|
+
if (version === 0)
|
|
116
|
+
throw Object.assign(new Error("Not an audit log."), { errcode: 26 });
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
if (version === 0)
|
|
120
|
+
db.exec("PRAGMA auto_vacuum = INCREMENTAL");
|
|
121
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
122
|
+
db.exec("PRAGMA synchronous = FULL");
|
|
123
|
+
if (process.platform === "darwin")
|
|
124
|
+
db.exec("PRAGMA fullfsync = ON; PRAGMA checkpoint_fullfsync = ON");
|
|
125
|
+
if (version === 0) {
|
|
126
|
+
db.exec(`BEGIN IMMEDIATE;
|
|
127
|
+
CREATE TABLE events (
|
|
128
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
129
|
+
at INTEGER NOT NULL,
|
|
130
|
+
kind TEXT NOT NULL,
|
|
131
|
+
action TEXT,
|
|
132
|
+
start_seq INTEGER,
|
|
133
|
+
outcome TEXT,
|
|
134
|
+
record TEXT NOT NULL
|
|
135
|
+
) STRICT;
|
|
136
|
+
CREATE INDEX events_at ON events(at);
|
|
137
|
+
CREATE INDEX events_start ON events(start_seq);
|
|
138
|
+
CREATE TABLE content (
|
|
139
|
+
seq INTEGER NOT NULL,
|
|
140
|
+
name TEXT NOT NULL,
|
|
141
|
+
data BLOB NOT NULL,
|
|
142
|
+
PRIMARY KEY (seq, name)
|
|
143
|
+
) STRICT;
|
|
144
|
+
PRAGMA user_version = ${AUDIT_SCHEMA_VERSION};
|
|
145
|
+
COMMIT;`);
|
|
146
|
+
}
|
|
147
|
+
db.exec(`BEGIN IMMEDIATE; PRAGMA user_version = ${AUDIT_SCHEMA_VERSION}; ROLLBACK;`);
|
|
148
|
+
}
|
|
149
|
+
db.prepare("SELECT seq FROM events ORDER BY seq DESC LIMIT 1").get();
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
try {
|
|
153
|
+
if (db?.isTransaction)
|
|
154
|
+
db.exec("ROLLBACK");
|
|
155
|
+
db?.close();
|
|
156
|
+
}
|
|
157
|
+
catch { }
|
|
158
|
+
const code = sqliteCode(error);
|
|
159
|
+
this.fail(code, code === "unreadable"
|
|
160
|
+
? "The audit log file is damaged or is not an audit log. Move it away to start a new log; Rome never deletes it."
|
|
161
|
+
: `The audit log cannot be ${readOnly ? "read" : "written"}: ${errorText(error)}`);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
this.db = db;
|
|
165
|
+
this.current = { state: "ok" };
|
|
166
|
+
if (readOnly)
|
|
167
|
+
return;
|
|
168
|
+
this.host({
|
|
169
|
+
event: "open",
|
|
170
|
+
pid: process.pid,
|
|
171
|
+
version: this.options.version ?? null,
|
|
172
|
+
entry: this.options.entry,
|
|
173
|
+
platform: process.platform,
|
|
174
|
+
hostCwd: process.cwd(),
|
|
175
|
+
path,
|
|
176
|
+
});
|
|
177
|
+
this.prune();
|
|
178
|
+
}
|
|
179
|
+
row(kind, action, startSeq, outcome, record, content, secrets, limits = {}) {
|
|
180
|
+
const stored = [];
|
|
181
|
+
const info = {};
|
|
182
|
+
for (const [name, data] of Object.entries(content)) {
|
|
183
|
+
if (!data?.byteLength)
|
|
184
|
+
continue;
|
|
185
|
+
const full = maskBytes(Buffer.from(data), secrets);
|
|
186
|
+
const kept = full.subarray(0, limits[name] ?? full.byteLength);
|
|
187
|
+
info[name] = { size: full.byteLength, sha256: sha256(full), storedBytes: kept.byteLength };
|
|
188
|
+
stored.push([name, kept]);
|
|
189
|
+
}
|
|
190
|
+
const body = Object.keys(info).length ? { ...record, content: info } : record;
|
|
191
|
+
const text = secrets.reduce((value, secret) => (secret ? value.replaceAll(secret, "[redacted]") : value), JSON.stringify(body));
|
|
192
|
+
return { at: this.now(), kind, action, startSeq, outcome, text, content: stored };
|
|
193
|
+
}
|
|
194
|
+
write(rows, inside) {
|
|
195
|
+
const db = this.db;
|
|
196
|
+
if (!db)
|
|
197
|
+
throw new Error("The audit log is not open.");
|
|
198
|
+
const seqs = [];
|
|
199
|
+
try {
|
|
200
|
+
db.exec("BEGIN IMMEDIATE");
|
|
201
|
+
inside?.(db);
|
|
202
|
+
for (const row of rows)
|
|
203
|
+
seqs.push(this.insert(db, row));
|
|
204
|
+
db.exec("COMMIT");
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
try {
|
|
208
|
+
if (db.isTransaction)
|
|
209
|
+
db.exec("ROLLBACK");
|
|
210
|
+
}
|
|
211
|
+
catch { }
|
|
212
|
+
this.fail(sqliteCode(error), `The audit log cannot be written: ${errorText(error)}`);
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
this.current = { state: "ok" };
|
|
216
|
+
return seqs;
|
|
217
|
+
}
|
|
218
|
+
insert(db, row) {
|
|
219
|
+
const seq = Number(db
|
|
220
|
+
.prepare("INSERT INTO events (at, kind, action, start_seq, outcome, record) VALUES (?, ?, ?, ?, ?, ?)")
|
|
221
|
+
.run(row.at, row.kind, row.action, row.startSeq, row.outcome, row.text).lastInsertRowid);
|
|
222
|
+
for (const [name, data] of row.content)
|
|
223
|
+
db.prepare("INSERT INTO content (seq, name, data) VALUES (?, ?, ?)").run(seq, name, data);
|
|
224
|
+
return seq;
|
|
225
|
+
}
|
|
226
|
+
async start(action, record, content = {}, secrets = []) {
|
|
227
|
+
if (this.options.readOnly)
|
|
228
|
+
return null;
|
|
229
|
+
await this.ensure();
|
|
230
|
+
if (!this.db)
|
|
231
|
+
return null;
|
|
232
|
+
const row = this.row("start", action, null, null, { action, ...record }, content, secrets);
|
|
233
|
+
try {
|
|
234
|
+
const seqs = this.write([...this.pending, row]);
|
|
235
|
+
this.pending = [];
|
|
236
|
+
return seqs[seqs.length - 1];
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
end(startSeq, action, outcome, record, content = {}, secrets = []) {
|
|
243
|
+
this.queue(this.row("end", action, startSeq, outcome, { startSeq, ...record }, content, secrets, {
|
|
244
|
+
stdout: AUDIT_OUTPUT_BYTES,
|
|
245
|
+
stderr: AUDIT_OUTPUT_BYTES,
|
|
246
|
+
}));
|
|
247
|
+
}
|
|
248
|
+
host(record, secrets = []) {
|
|
249
|
+
this.queue(this.row("host", null, null, null, { pid: process.pid, ...record }, {}, secrets));
|
|
250
|
+
}
|
|
251
|
+
queue(row) {
|
|
252
|
+
if (this.options.readOnly)
|
|
253
|
+
return;
|
|
254
|
+
this.pending.push(row);
|
|
255
|
+
if (!this.db)
|
|
256
|
+
return;
|
|
257
|
+
try {
|
|
258
|
+
this.write(this.pending);
|
|
259
|
+
this.pending = [];
|
|
260
|
+
}
|
|
261
|
+
catch { }
|
|
262
|
+
}
|
|
263
|
+
prune() {
|
|
264
|
+
if (this.options.readOnly || !this.db)
|
|
265
|
+
return;
|
|
266
|
+
const maxAge = this.options.maxAgeMs ?? AUDIT_MAX_AGE_MS;
|
|
267
|
+
const maxBytes = this.options.maxBytes ?? AUDIT_MAX_BYTES;
|
|
268
|
+
const target = Math.floor(maxBytes * 0.9);
|
|
269
|
+
let marker = null;
|
|
270
|
+
try {
|
|
271
|
+
this.write([], (db) => {
|
|
272
|
+
for (const row of this.pending)
|
|
273
|
+
this.insert(db, row);
|
|
274
|
+
let rowsThroughSeq = null;
|
|
275
|
+
let contentThroughSeq = null;
|
|
276
|
+
let reason = null;
|
|
277
|
+
const deleteRows = (through) => {
|
|
278
|
+
rowsThroughSeq = through;
|
|
279
|
+
contentThroughSeq = Math.max(contentThroughSeq ?? 0, through);
|
|
280
|
+
db.prepare("DELETE FROM content WHERE seq <= ?").run(through);
|
|
281
|
+
db.prepare("DELETE FROM events WHERE seq <= ?").run(through);
|
|
282
|
+
};
|
|
283
|
+
const aged = db
|
|
284
|
+
.prepare("SELECT max(seq) AS seq FROM events WHERE at < ?")
|
|
285
|
+
.get(this.now() - maxAge);
|
|
286
|
+
if (aged.seq !== null) {
|
|
287
|
+
deleteRows(Number(aged.seq));
|
|
288
|
+
reason = "age";
|
|
289
|
+
}
|
|
290
|
+
const used = () => {
|
|
291
|
+
const pages = db.prepare("PRAGMA page_count").get();
|
|
292
|
+
const free = db.prepare("PRAGMA freelist_count").get();
|
|
293
|
+
const size = db.prepare("PRAGMA page_size").get();
|
|
294
|
+
return (Number(pages.page_count) - Number(free.freelist_count)) * Number(size.page_size);
|
|
295
|
+
};
|
|
296
|
+
let bytes = used();
|
|
297
|
+
if (bytes > maxBytes) {
|
|
298
|
+
let freed = 0;
|
|
299
|
+
let through = null;
|
|
300
|
+
for (const row of db
|
|
301
|
+
.prepare("SELECT seq, sum(length(data)) AS bytes FROM content GROUP BY seq ORDER BY seq")
|
|
302
|
+
.iterate()) {
|
|
303
|
+
freed += Number(row.bytes);
|
|
304
|
+
through = Number(row.seq);
|
|
305
|
+
if (bytes - freed < target)
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
if (through !== null) {
|
|
309
|
+
db.prepare("DELETE FROM content WHERE seq <= ?").run(through);
|
|
310
|
+
contentThroughSeq = Math.max(contentThroughSeq ?? 0, through);
|
|
311
|
+
reason = "size";
|
|
312
|
+
}
|
|
313
|
+
bytes = used();
|
|
314
|
+
if (bytes > maxBytes) {
|
|
315
|
+
let rowsFreed = 0;
|
|
316
|
+
let rowsThrough = null;
|
|
317
|
+
for (const row of db
|
|
318
|
+
.prepare("SELECT seq, length(record) + 200 AS bytes FROM events ORDER BY seq")
|
|
319
|
+
.iterate()) {
|
|
320
|
+
rowsFreed += Number(row.bytes);
|
|
321
|
+
rowsThrough = Number(row.seq);
|
|
322
|
+
if (bytes - rowsFreed < target)
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
if (rowsThrough !== null) {
|
|
326
|
+
deleteRows(rowsThrough);
|
|
327
|
+
reason = "size";
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (!reason)
|
|
332
|
+
return;
|
|
333
|
+
marker = this.row("prune", null, null, null, { reason, rowsThroughSeq, contentThroughSeq }, {}, []);
|
|
334
|
+
this.insert(db, marker);
|
|
335
|
+
});
|
|
336
|
+
this.pending = [];
|
|
337
|
+
if (marker)
|
|
338
|
+
this.db.exec("PRAGMA incremental_vacuum");
|
|
339
|
+
}
|
|
340
|
+
catch { }
|
|
341
|
+
}
|
|
342
|
+
close() {
|
|
343
|
+
clearInterval(this.pruneTimer);
|
|
344
|
+
if (!this.options.readOnly)
|
|
345
|
+
this.host({ event: "close", pid: process.pid });
|
|
346
|
+
try {
|
|
347
|
+
this.db?.close();
|
|
348
|
+
}
|
|
349
|
+
catch { }
|
|
350
|
+
this.db = null;
|
|
351
|
+
}
|
|
352
|
+
reader() {
|
|
353
|
+
if (!this.db)
|
|
354
|
+
throw new Error(this.current.state === "unavailable" ? this.current.message : "The audit log is not open.");
|
|
355
|
+
return this.db;
|
|
356
|
+
}
|
|
357
|
+
event(row) {
|
|
358
|
+
return {
|
|
359
|
+
seq: Number(row.seq),
|
|
360
|
+
at: Number(row.at),
|
|
361
|
+
kind: row.kind,
|
|
362
|
+
action: row.action ?? null,
|
|
363
|
+
startSeq: row.start_seq === null ? null : Number(row.start_seq),
|
|
364
|
+
outcome: row.outcome ?? null,
|
|
365
|
+
record: JSON.parse(String(row.record)),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
withEnd(db, event) {
|
|
369
|
+
if (event.kind !== "start")
|
|
370
|
+
return { ...event, end: null };
|
|
371
|
+
const end = db
|
|
372
|
+
.prepare("SELECT * FROM events WHERE kind = 'end' AND start_seq = ? ORDER BY seq LIMIT 1")
|
|
373
|
+
.get(event.seq);
|
|
374
|
+
return { ...event, end: end ? this.event(end) : null };
|
|
375
|
+
}
|
|
376
|
+
list(query = {}) {
|
|
377
|
+
const db = this.reader();
|
|
378
|
+
const where = ["s.kind != 'end'"];
|
|
379
|
+
const params = [];
|
|
380
|
+
const add = (clause, ...values) => {
|
|
381
|
+
where.push(clause);
|
|
382
|
+
params.push(...values);
|
|
383
|
+
};
|
|
384
|
+
if (query.beforeSeq !== undefined)
|
|
385
|
+
add("s.seq < ?", query.beforeSeq);
|
|
386
|
+
if (query.afterSeq !== undefined)
|
|
387
|
+
add("s.seq > ?", query.afterSeq);
|
|
388
|
+
if (query.since !== undefined)
|
|
389
|
+
add("s.at >= ?", query.since);
|
|
390
|
+
if (query.until !== undefined)
|
|
391
|
+
add("s.at <= ?", query.until);
|
|
392
|
+
if (query.action !== undefined)
|
|
393
|
+
add("s.kind = 'start' AND s.action = ?", query.action);
|
|
394
|
+
if (query.outcome === "no_end")
|
|
395
|
+
add("s.kind = 'start' AND e.seq IS NULL");
|
|
396
|
+
else if (query.outcome !== undefined)
|
|
397
|
+
add("e.outcome = ?", query.outcome);
|
|
398
|
+
if (query.text)
|
|
399
|
+
add("(instr(s.record, ?) > 0 OR instr(e.record, ?) > 0)", query.text, query.text);
|
|
400
|
+
if (query.requestsOnly || query.result)
|
|
401
|
+
add("s.kind = 'start'");
|
|
402
|
+
if (query.result)
|
|
403
|
+
add(`${RESULT_SQL} = ?`, query.result);
|
|
404
|
+
const rows = db
|
|
405
|
+
.prepare(`SELECT s.*, e.seq AS e_seq, e.at AS e_at, e.kind AS e_kind, e.action AS e_action,
|
|
406
|
+
e.start_seq AS e_start_seq, e.outcome AS e_outcome, e.record AS e_record
|
|
407
|
+
FROM events s LEFT JOIN events e ON e.kind = 'end' AND e.start_seq = s.seq
|
|
408
|
+
WHERE ${where.join(" AND ")} ORDER BY s.seq DESC LIMIT ?`)
|
|
409
|
+
.all(...params, query.limit ?? 200);
|
|
410
|
+
return rows.map((row) => ({
|
|
411
|
+
...this.event(row),
|
|
412
|
+
end: row.e_seq === null
|
|
413
|
+
? null
|
|
414
|
+
: this.event({
|
|
415
|
+
seq: row.e_seq,
|
|
416
|
+
at: row.e_at,
|
|
417
|
+
kind: row.e_kind,
|
|
418
|
+
action: row.e_action,
|
|
419
|
+
start_seq: row.e_start_seq,
|
|
420
|
+
outcome: row.e_outcome,
|
|
421
|
+
record: row.e_record,
|
|
422
|
+
}),
|
|
423
|
+
}));
|
|
424
|
+
}
|
|
425
|
+
resultCounts() {
|
|
426
|
+
const counts = { all: 0, succeeded: 0, failed: 0, no_result: 0 };
|
|
427
|
+
const rows = this.reader()
|
|
428
|
+
.prepare(`SELECT ${RESULT_SQL} AS result, count(*) AS n FROM events s
|
|
429
|
+
LEFT JOIN events e ON e.kind = 'end' AND e.start_seq = s.seq
|
|
430
|
+
WHERE s.kind = 'start' GROUP BY result`)
|
|
431
|
+
.all();
|
|
432
|
+
for (const row of rows) {
|
|
433
|
+
counts[row.result] += Number(row.n);
|
|
434
|
+
counts.all += Number(row.n);
|
|
435
|
+
}
|
|
436
|
+
return counts;
|
|
437
|
+
}
|
|
438
|
+
stats(since, until, bucketMs) {
|
|
439
|
+
const groups = this.reader()
|
|
440
|
+
.prepare(`SELECT CAST((s.at - ?) / ? AS INTEGER) AS bucket, ${RESULT_SQL} AS result, count(*) AS n FROM events s
|
|
441
|
+
LEFT JOIN events e ON e.kind = 'end' AND e.start_seq = s.seq
|
|
442
|
+
WHERE s.kind = 'start' AND s.at >= ? AND s.at < ? GROUP BY bucket, result`)
|
|
443
|
+
.all(since, bucketMs, since, until);
|
|
444
|
+
return {
|
|
445
|
+
since,
|
|
446
|
+
until,
|
|
447
|
+
bucketMs,
|
|
448
|
+
groups: groups.map((row) => ({
|
|
449
|
+
peer: null,
|
|
450
|
+
bucket: Math.floor(Number(row.bucket)),
|
|
451
|
+
result: row.result,
|
|
452
|
+
count: Number(row.n),
|
|
453
|
+
})),
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
get(seq) {
|
|
457
|
+
const db = this.reader();
|
|
458
|
+
const row = db.prepare("SELECT * FROM events WHERE seq = ?").get(seq);
|
|
459
|
+
if (!row)
|
|
460
|
+
return null;
|
|
461
|
+
const event = this.event(row);
|
|
462
|
+
if (event.kind === "end" && event.startSeq !== null) {
|
|
463
|
+
const start = db.prepare("SELECT * FROM events WHERE seq = ?").get(event.startSeq);
|
|
464
|
+
if (start)
|
|
465
|
+
return { ...this.event(start), end: event };
|
|
466
|
+
}
|
|
467
|
+
return this.withEnd(db, event);
|
|
468
|
+
}
|
|
469
|
+
content(seq, name) {
|
|
470
|
+
const row = this.reader()
|
|
471
|
+
.prepare("SELECT data FROM content WHERE seq = ? AND name = ?")
|
|
472
|
+
.get(seq, name);
|
|
473
|
+
return row ? Buffer.from(row.data) : null;
|
|
474
|
+
}
|
|
475
|
+
summary() {
|
|
476
|
+
const retention = {
|
|
477
|
+
maxAgeDays: (this.options.maxAgeMs ?? AUDIT_MAX_AGE_MS) / 86_400_000,
|
|
478
|
+
maxBytes: this.options.maxBytes ?? AUDIT_MAX_BYTES,
|
|
479
|
+
};
|
|
480
|
+
let bytes = 0;
|
|
481
|
+
for (const suffix of ["", "-wal"]) {
|
|
482
|
+
try {
|
|
483
|
+
bytes += statSync(this.options.path + suffix).size;
|
|
484
|
+
}
|
|
485
|
+
catch { }
|
|
486
|
+
}
|
|
487
|
+
const base = { path: this.options.path, status: this.current, bytes, retention };
|
|
488
|
+
if (!this.db)
|
|
489
|
+
return { ...base, records: 0, requests: 0, oldestAt: null, newestAt: null, lastPrune: null };
|
|
490
|
+
const db = this.db;
|
|
491
|
+
const counts = db
|
|
492
|
+
.prepare("SELECT count(*) AS records, sum(kind = 'start') AS requests, min(at) AS oldest, max(at) AS newest FROM events")
|
|
493
|
+
.get();
|
|
494
|
+
const prune = db
|
|
495
|
+
.prepare("SELECT * FROM events WHERE kind = 'prune' ORDER BY seq DESC LIMIT 1")
|
|
496
|
+
.get();
|
|
497
|
+
return {
|
|
498
|
+
...base,
|
|
499
|
+
records: Number(counts.records ?? 0),
|
|
500
|
+
requests: Number(counts.requests ?? 0),
|
|
501
|
+
oldestAt: counts.oldest === null ? null : Number(counts.oldest),
|
|
502
|
+
newestAt: counts.newest === null ? null : Number(counts.newest),
|
|
503
|
+
lastPrune: prune ? this.event(prune) : null,
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
}
|
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,10 +68,7 @@ export async function connectHost(options) {
|
|
|
68
68
|
signal.removeEventListener("abort", abort);
|
|
69
69
|
executor.disconnect();
|
|
70
70
|
connection.stop();
|
|
71
|
-
|
|
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({
|
|
@@ -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();
|
package/dist/devices-status.d.ts
CHANGED
|
@@ -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;
|
package/dist/devices-status.js
CHANGED
|
@@ -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();
|
package/dist/executor.d.ts
CHANGED
|
@@ -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
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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":
|
|
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
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
package/dist/storage.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare function readPrivateJson(path: string): Promise<unknown>;
|
|
2
|
+
export declare function ensurePrivateDirectory(dir: string): Promise<void>;
|
|
2
3
|
export declare function writePrivateJson(path: string, value: unknown): Promise<void>;
|
|
3
4
|
export interface CredentialStore<T> {
|
|
4
5
|
load(): Promise<unknown>;
|
package/dist/storage.js
CHANGED
|
@@ -13,8 +13,7 @@ export async function readPrivateJson(path) {
|
|
|
13
13
|
throw new Error("Could not read the local credential file.");
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
-
export async function
|
|
17
|
-
const dir = dirname(path);
|
|
16
|
+
export async function ensurePrivateDirectory(dir) {
|
|
18
17
|
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
19
18
|
if (process.platform === "win32") {
|
|
20
19
|
const run = promisify(execFile);
|
|
@@ -37,6 +36,9 @@ export async function writePrivateJson(path, value) {
|
|
|
37
36
|
}
|
|
38
37
|
else
|
|
39
38
|
await chmod(dir, 0o700);
|
|
39
|
+
}
|
|
40
|
+
export async function writePrivateJson(path, value) {
|
|
41
|
+
await ensurePrivateDirectory(dirname(path));
|
|
40
42
|
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
41
43
|
try {
|
|
42
44
|
await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: "wx" });
|
package/dist/transfer.d.ts
CHANGED
|
@@ -73,13 +73,27 @@ export declare function createPartFile(path: string, id?: string): Promise<{
|
|
|
73
73
|
handle: FileHandle;
|
|
74
74
|
}>;
|
|
75
75
|
export declare function openDestination(path: string): Promise<Destination>;
|
|
76
|
+
export interface TransferResult {
|
|
77
|
+
code?: string;
|
|
78
|
+
direction?: "push" | "pull";
|
|
79
|
+
path?: string;
|
|
80
|
+
bytes?: number;
|
|
81
|
+
sha256?: string;
|
|
82
|
+
ackedBytes?: number;
|
|
83
|
+
replaced?: {
|
|
84
|
+
size: number;
|
|
85
|
+
mtimeMs: number;
|
|
86
|
+
} | null;
|
|
87
|
+
file?: Buffer;
|
|
88
|
+
}
|
|
76
89
|
export declare class TransferHost {
|
|
77
90
|
private options;
|
|
78
91
|
private transfers;
|
|
79
92
|
constructor(options?: TransferOptions & {
|
|
80
93
|
limit?: number;
|
|
94
|
+
keepBytes?: number;
|
|
81
95
|
});
|
|
82
|
-
open(id: string, peer: string, args: unknown, send: TransferSend): Promise<
|
|
96
|
+
open(id: string, peer: string, args: unknown, send: TransferSend): Promise<TransferResult>;
|
|
83
97
|
receive(id: string, peer: string, message: TransferMessage, body: Uint8Array): void;
|
|
84
98
|
abortAll(): void;
|
|
85
99
|
}
|
package/dist/transfer.js
CHANGED
|
@@ -349,30 +349,41 @@ export class TransferHost {
|
|
|
349
349
|
}
|
|
350
350
|
async open(id, peer, args, send) {
|
|
351
351
|
if (this.transfers.has(id))
|
|
352
|
-
return;
|
|
352
|
+
return { code: "duplicate_transfer" };
|
|
353
353
|
const request = parseOpen(args);
|
|
354
354
|
if (!request) {
|
|
355
355
|
send(actionError("invalid_args", "transfer.open requires direction push or pull, a path, and a size for push."));
|
|
356
|
-
return;
|
|
356
|
+
return { code: "invalid_args" };
|
|
357
357
|
}
|
|
358
358
|
if (this.transfers.size >= (this.options.limit ?? MAX_HOST_TRANSFERS)) {
|
|
359
359
|
send(actionError("busy", "The computer is already running its maximum number of transfers."));
|
|
360
|
-
return;
|
|
360
|
+
return { code: "busy" };
|
|
361
361
|
}
|
|
362
|
-
const
|
|
362
|
+
const { direction, path } = request;
|
|
363
|
+
const keep = direction === "push" && (request.size ?? 0) <= (this.options.keepBytes ?? 0);
|
|
364
|
+
const entry = { peer, canceled: false, acked: 0, chunks: keep ? [] : undefined };
|
|
365
|
+
const result = { direction, path };
|
|
363
366
|
this.transfers.set(id, entry);
|
|
364
367
|
try {
|
|
365
|
-
if (
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
368
|
+
if (direction === "push") {
|
|
369
|
+
const existing = await stat(path).catch(() => null);
|
|
370
|
+
result.replaced = existing?.isFile()
|
|
371
|
+
? { size: existing.size, mtimeMs: existing.mtimeMs }
|
|
372
|
+
: null;
|
|
373
|
+
const destination = await openDestination(path);
|
|
374
|
+
if (entry.canceled) {
|
|
375
|
+
await destination.cancel();
|
|
376
|
+
return { ...result, code: "canceled" };
|
|
377
|
+
}
|
|
369
378
|
entry.endpoint = destination.start(send, { ...this.options, size: request.size });
|
|
370
379
|
send({ type: "response", ok: true, result: {} });
|
|
371
380
|
}
|
|
372
381
|
else {
|
|
373
|
-
const source = await openSource(
|
|
374
|
-
if (entry.canceled)
|
|
375
|
-
|
|
382
|
+
const source = await openSource(path);
|
|
383
|
+
if (entry.canceled) {
|
|
384
|
+
await source.close();
|
|
385
|
+
return { ...result, code: "canceled" };
|
|
386
|
+
}
|
|
376
387
|
send({
|
|
377
388
|
type: "response",
|
|
378
389
|
ok: true,
|
|
@@ -380,13 +391,26 @@ export class TransferHost {
|
|
|
380
391
|
});
|
|
381
392
|
entry.endpoint = source.start(send, this.options);
|
|
382
393
|
}
|
|
383
|
-
await entry.endpoint.result
|
|
394
|
+
const summary = await entry.endpoint.result;
|
|
395
|
+
return {
|
|
396
|
+
...result,
|
|
397
|
+
bytes: summary.size,
|
|
398
|
+
sha256: summary.sha256,
|
|
399
|
+
...(direction === "pull" ? { ackedBytes: entry.acked } : {}),
|
|
400
|
+
...(entry.chunks ? { file: Buffer.concat(entry.chunks) } : {}),
|
|
401
|
+
};
|
|
384
402
|
}
|
|
385
403
|
catch (error) {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
404
|
+
const failure = error instanceof TransferError
|
|
405
|
+
? error
|
|
406
|
+
: new TransferError("io_error", "The transfer failed.");
|
|
407
|
+
if (!entry.canceled && !entry.endpoint)
|
|
408
|
+
send(actionError(failure.code, failure.message));
|
|
409
|
+
return {
|
|
410
|
+
...result,
|
|
411
|
+
code: failure.code,
|
|
412
|
+
...(direction === "pull" ? { ackedBytes: entry.acked } : {}),
|
|
413
|
+
};
|
|
390
414
|
}
|
|
391
415
|
finally {
|
|
392
416
|
this.transfers.delete(id);
|
|
@@ -396,6 +420,10 @@ export class TransferHost {
|
|
|
396
420
|
const entry = this.transfers.get(id);
|
|
397
421
|
if (!entry || entry.peer !== peer)
|
|
398
422
|
return;
|
|
423
|
+
if (message.kind === "data")
|
|
424
|
+
entry.chunks?.push(Buffer.from(body));
|
|
425
|
+
else if (message.kind === "ack")
|
|
426
|
+
entry.acked = Math.max(entry.acked, message.offset);
|
|
399
427
|
if (entry.endpoint)
|
|
400
428
|
entry.endpoint.receive(message, body);
|
|
401
429
|
else if (message.kind === "abort")
|