@rome-os/node-core 0.1.4 → 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/README.md CHANGED
@@ -21,6 +21,8 @@ const client = createNodeClient(nodeConfigFromEnvironment(process.env));
21
21
  const status = await client.getConnectionStatus();
22
22
  const devices = await client.listDevices();
23
23
  const connections = await client.getDevicesStatus();
24
+ await client.renameDevice("device-id", "Build server");
25
+ await client.removeDevice("old-device-id");
24
26
  const info = await client.describe("device-id");
25
27
  const result = await client.run("device-id", "exec", {
26
28
  command: "git",
@@ -48,6 +50,13 @@ Gateway connection. `connection` describes the caller connection to Gateway,
48
50
  not the online state of remote devices. `listDevices()` returns authorized
49
51
  devices without asserting that they are online.
50
52
 
53
+ `renameDevice(deviceId, name)` and `removeDevice(deviceId)` change the account's
54
+ device list in Cloud and resolve with no value. A failure throws
55
+ `DeviceActionError` with code `device_not_found`, `invalid_device_name`,
56
+ `invalid_device_session`, or `cloud_unavailable`. `removeDevice` revokes the
57
+ device first and throws `revocation_pending` while the Gateway has not confirmed
58
+ the revocation. The device stays listed as revoked until a later call deletes it.
59
+
51
60
  `runBinary(deviceId, action, args?, body?)` resolves to `{ response, body }`.
52
61
  It sends `body` as input bytes in a binary frame. For `exec`, the input is the
53
62
  program's stdin and the reply `body` is its raw stdout. Neither side is JSON or
@@ -203,7 +212,7 @@ where `expiresIn` is in seconds. It returns a `DeviceSession` after approval and
203
212
  rejects on denial, expiry, cancellation, or a terminal error. It opens no browser
204
213
  or callback listener. The callback receives neither the device code nor the access token.
205
214
 
206
- The host exposes `system.info` and `exec`, in text envelopes and in binary frames.
215
+ The host exposes `system.info`, `exec`, and the read-only `fs.list`, in text envelopes and in binary frames.
207
216
  It also accepts the internal file transfers that `copy()` uses. Programs run as the application's OS
208
217
  user. Connection loss terminates direct child processes on a best-effort basis.
209
218
  A local caller timeout does not cancel remote execution.
@@ -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/cloud.d.ts CHANGED
@@ -3,5 +3,5 @@ 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): Promise<unknown>;
6
+ export declare function cloudRequest(origin: string, path: string, token: string, method?: string, json?: unknown): Promise<unknown>;
7
7
  export declare function gatewayConfig(origin: string, token: string): Promise<string>;