@aide-family/dsh-remote 0.0.0-stage → 0.6.2
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/LICENSE +21 -0
- package/README.md +793 -2
- package/bin/dsh-remote-terminal +82 -0
- package/cordis.patch.yml +3 -0
- package/docs/TERMINAL_ACTIONS.md +39 -0
- package/docs/assets/host-audit.png +0 -0
- package/docs/assets/host-manager.png +0 -0
- package/docs/assets/live-terminal.png +0 -0
- package/docs/assets/remote-ops.png +0 -0
- package/docs/assets/remote-terminal.png +0 -0
- package/docs/icon.svg +11 -0
- package/lib/api-helpers.js +325 -0
- package/lib/api.js +715 -0
- package/lib/approval.js +238 -0
- package/lib/audit.js +224 -0
- package/lib/client.js +4919 -0
- package/lib/config.js +762 -0
- package/lib/connection-profile.js +65 -0
- package/lib/host-registry.js +703 -0
- package/lib/host-store.js +139 -0
- package/lib/hosts.js +442 -0
- package/lib/index.js +419 -0
- package/lib/live-stream.js +121 -0
- package/lib/live.js +245 -0
- package/lib/policy/argv.js +77 -0
- package/lib/policy/command-guard.js +404 -0
- package/lib/policy/docker.js +140 -0
- package/lib/policy/index.js +21 -0
- package/lib/policy/inspection.js +111 -0
- package/lib/policy/kubectl.js +128 -0
- package/lib/policy/shell-command.js +525 -0
- package/lib/policy/shell-wrappers.js +143 -0
- package/lib/policy/ssh.js +53 -0
- package/lib/policy/sudo.js +38 -0
- package/lib/policy/systemctl.js +22 -0
- package/lib/policy/types.js +12 -0
- package/lib/prompt.js +29 -0
- package/lib/render.js +442 -0
- package/lib/runtime-deps.js +50 -0
- package/lib/ssh/auth.js +256 -0
- package/lib/ssh/connection.js +504 -0
- package/lib/ssh/errors.js +209 -0
- package/lib/ssh/exec.js +394 -0
- package/lib/ssh/known-hosts.js +313 -0
- package/lib/ssh/pty.js +472 -0
- package/lib/ssh/sftp.js +589 -0
- package/lib/ssh/transport.js +801 -0
- package/lib/ssh-config.js +395 -0
- package/lib/terminal/bridge.cjs +305 -0
- package/lib/terminal/connection-login.js +188 -0
- package/lib/terminal/manager.js +656 -0
- package/lib/terminal/node-launcher.js +211 -0
- package/lib/terminal/pty-session.js +673 -0
- package/lib/terminal/relay-socket.js +605 -0
- package/lib/terminal/relay.js +905 -0
- package/lib/terminal/scrollback.js +588 -0
- package/lib/terminal/tools.js +532 -0
- package/lib/tools.js +751 -0
- package/package.json +90 -4
package/lib/approval.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Approval gate for dsh-remote.
|
|
3
|
+
*
|
|
4
|
+
* Risk is reviewed statically first (Crescent-style classifier), then the
|
|
5
|
+
* configured policy decides whether the action is allowed, denied, or handed to
|
|
6
|
+
* the DSH approval seam (`ctx.get("approval")`, the same one-shot, fail-closed
|
|
7
|
+
* seam the sandboxed bash tool uses).
|
|
8
|
+
*
|
|
9
|
+
* Policy modes (`config.policy`):
|
|
10
|
+
* - "auto" read-only actions run; anything mutating asks for approval
|
|
11
|
+
* - "always" every action asks for approval
|
|
12
|
+
* - "never" read-only actions run; anything mutating is denied outright
|
|
13
|
+
* (the headless / unattended stance)
|
|
14
|
+
*
|
|
15
|
+
* Independent hard denials, applied before policy:
|
|
16
|
+
* - a host matched by `readonlyHosts` forbids every mutating action
|
|
17
|
+
* - a command matched by `denyCommandPatterns` is always denied
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { classifyCommand, extractRiskVerb } from "./policy/index.js";
|
|
21
|
+
|
|
22
|
+
const MAX_REASON_SUBJECT = 300;
|
|
23
|
+
|
|
24
|
+
/** @typedef {{ level: "low" | "gray" | "high", verb: string }} RiskAssessment */
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Compile the configured deny patterns once, skipping invalid entries with a
|
|
28
|
+
* warning instead of failing the whole plugin.
|
|
29
|
+
*
|
|
30
|
+
* @param {string[] | undefined} patterns RegExp sources from config.
|
|
31
|
+
* @param {(message: string) => void} [warn] Warning sink.
|
|
32
|
+
* @returns {RegExp[]}
|
|
33
|
+
*/
|
|
34
|
+
export function compileDenyPatterns(patterns, warn) {
|
|
35
|
+
/** @type {RegExp[]} */
|
|
36
|
+
const compiled = [];
|
|
37
|
+
for (const source of patterns ?? []) {
|
|
38
|
+
const text = String(source ?? "").trim();
|
|
39
|
+
if (text.length === 0) continue;
|
|
40
|
+
try {
|
|
41
|
+
compiled.push(new RegExp(text));
|
|
42
|
+
} catch (error) {
|
|
43
|
+
warn?.(`dsh-remote: ignoring invalid denyCommandPatterns entry ${JSON.stringify(text)}: ${describe(error)}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return compiled;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Shorten a model-supplied command or path for an approval prompt without
|
|
51
|
+
* hiding which action is being approved.
|
|
52
|
+
*
|
|
53
|
+
* @param {string} subject Raw command/path.
|
|
54
|
+
* @returns {string}
|
|
55
|
+
*/
|
|
56
|
+
export function truncateSubject(subject) {
|
|
57
|
+
const text = String(subject ?? "").replaceAll(/\s+/gu, " ").trim();
|
|
58
|
+
return text.length <= MAX_REASON_SUBJECT ? text : `${text.slice(0, MAX_REASON_SUBJECT - 1)}…`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {unknown} error @returns {string} */
|
|
62
|
+
function describe(error) {
|
|
63
|
+
if (error instanceof Error) return error.message;
|
|
64
|
+
return String(error);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Create the approval gate used by every tool.
|
|
69
|
+
*
|
|
70
|
+
* @param {object} options
|
|
71
|
+
* @param {import("@deepseek-ai/cordis").Context} options.ctx Plugin context (for `ctx.get("approval")`).
|
|
72
|
+
* @param {object} options.config Normalized dsh-remote config.
|
|
73
|
+
* @param {{ info?: (m: string) => void, warn?: (m: string) => void }} [options.logger]
|
|
74
|
+
*/
|
|
75
|
+
export function createApprovalGate({ ctx, config, logger }) {
|
|
76
|
+
const denyPatterns = compileDenyPatterns(config.denyCommandPatterns, (message) => logger?.warn?.(message));
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Static review of one remote command.
|
|
80
|
+
*
|
|
81
|
+
* @param {string} command The shell line that would run on the remote host.
|
|
82
|
+
* @returns {RiskAssessment & { denied?: string }}
|
|
83
|
+
*/
|
|
84
|
+
function assessCommand(command) {
|
|
85
|
+
const text = String(command ?? "");
|
|
86
|
+
for (const pattern of denyPatterns) {
|
|
87
|
+
pattern.lastIndex = 0;
|
|
88
|
+
if (pattern.test(text)) {
|
|
89
|
+
return {
|
|
90
|
+
level: "high",
|
|
91
|
+
verb: extractRiskVerb(text),
|
|
92
|
+
denied: `command denied by denyCommandPatterns (${pattern.source})`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const { level, verb } = classifyCommand(text);
|
|
97
|
+
return { level, verb };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Build the human-facing reason shown in the approval prompt. It always names
|
|
102
|
+
* the action, the exact host, and the concrete subject.
|
|
103
|
+
*
|
|
104
|
+
* @param {object} options
|
|
105
|
+
* @param {"read" | "write" | "execute" | "transfer"} options.action
|
|
106
|
+
* @param {import("../lib/hosts.js").RemoteHost} options.host
|
|
107
|
+
* @param {string} options.subject Command or path being acted on.
|
|
108
|
+
* @param {string} [options.verb] Risk verb from the static classifier.
|
|
109
|
+
* @param {string} [options.description] Model-supplied short description.
|
|
110
|
+
* @returns {string}
|
|
111
|
+
*/
|
|
112
|
+
function buildReason({ action, host, subject, verb, description }) {
|
|
113
|
+
const target = formatHost(host);
|
|
114
|
+
// Name the configured alias as well as the connection target: the alias is
|
|
115
|
+
// what the user and the model recognise, the target proves where it lands.
|
|
116
|
+
const named = host.name !== undefined && host.name !== host.host ? `${host.name} (${target})` : target;
|
|
117
|
+
const label = actionLabel(action);
|
|
118
|
+
const risk = verb ? ` (risk: ${verb})` : "";
|
|
119
|
+
const why = description?.trim() ? ` — ${truncateSubject(description)}` : "";
|
|
120
|
+
return `Remote ${label} on ${named}${risk}: ${truncateSubject(subject)}${why}`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Decide one real action and, when required, ask the user through the DSH
|
|
125
|
+
* approval seam. Approval is fail-closed: a missing/failed answerer denies.
|
|
126
|
+
*
|
|
127
|
+
* @param {object} options
|
|
128
|
+
* @param {string} options.toolName Model-facing tool name (for the audit log).
|
|
129
|
+
* @param {import("@deepseek-ai/dsh-tools").ToolExecution} options.exec Tool execution carrying agent/callId/signal.
|
|
130
|
+
* @param {import("../lib/hosts.js").RemoteHost} options.host Target host.
|
|
131
|
+
* @param {"read" | "write" | "execute" | "transfer"} options.action Action category.
|
|
132
|
+
* @param {string} options.subject Exact command or path.
|
|
133
|
+
* @param {boolean} options.mutating Whether the static classifier proves the action changes remote state.
|
|
134
|
+
* @param {boolean} [options.unproven] The classifier could not prove the action read-only (gray).
|
|
135
|
+
* @param {string} [options.verb] Risk verb from {@link assessCommand}.
|
|
136
|
+
* @param {string} [options.description] Model-supplied short description.
|
|
137
|
+
* @param {boolean} [options.readonlyHost] Host is force-read-only.
|
|
138
|
+
* @returns {Promise<{ allowed: boolean, reason?: string, outcome?: string }>}
|
|
139
|
+
*/
|
|
140
|
+
async function authorize({ toolName, exec, host, action, subject, mutating, unproven = false, verb, description, readonlyHost }) {
|
|
141
|
+
const changesState = mutating === true;
|
|
142
|
+
const unprovenState = unproven === true;
|
|
143
|
+
// A read-only host accepts only actions the classifier proves read-only.
|
|
144
|
+
if (readonlyHost === true && (changesState || unprovenState)) {
|
|
145
|
+
return {
|
|
146
|
+
allowed: false,
|
|
147
|
+
reason: `Host ${host.name} is configured read-only; ${actionLabel(action)} is denied.`,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
if (!changesState && !unprovenState && config.policy !== "always") return { allowed: true };
|
|
151
|
+
if (config.policy === "never") {
|
|
152
|
+
return {
|
|
153
|
+
allowed: false,
|
|
154
|
+
reason: `Approval policy is "never": remote ${actionLabel(action)} on ${host.name} is denied.`,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
// "auto": only provably mutating commands ask; unproven commands run unless
|
|
158
|
+
// the deployment opts back into approval with unprovenCommands: "ask".
|
|
159
|
+
if (!changesState && unprovenState && config.unprovenCommands !== "ask") {
|
|
160
|
+
return { allowed: true };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const reason = buildReason({ action, host, subject, verb, description });
|
|
164
|
+
const approval = ctx?.get?.("approval");
|
|
165
|
+
if (approval === undefined || approval === null) {
|
|
166
|
+
return {
|
|
167
|
+
allowed: false,
|
|
168
|
+
outcome: "unavailable",
|
|
169
|
+
reason: `${reason} — denied because no approval answerer is mounted (fail closed).`,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let outcome;
|
|
174
|
+
try {
|
|
175
|
+
outcome = await approval.request({
|
|
176
|
+
agent: exec.agent,
|
|
177
|
+
toolName,
|
|
178
|
+
...(exec.callId === undefined ? {} : { callId: exec.callId }),
|
|
179
|
+
reason,
|
|
180
|
+
signal: exec.signal,
|
|
181
|
+
});
|
|
182
|
+
} catch (error) {
|
|
183
|
+
return {
|
|
184
|
+
allowed: false,
|
|
185
|
+
outcome: "unavailable",
|
|
186
|
+
reason: `${reason} — denied because the approval request failed: ${describe(error)}`,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (outcome === "allowed-once") return { allowed: true, outcome };
|
|
191
|
+
if (outcome === "rejected") {
|
|
192
|
+
return { allowed: false, outcome, reason: `${reason} — rejected by the user.` };
|
|
193
|
+
}
|
|
194
|
+
if (outcome === "cancelled") {
|
|
195
|
+
return { allowed: false, outcome, reason: `${reason} — the approval request was cancelled.` };
|
|
196
|
+
}
|
|
197
|
+
if (outcome === "unavailable") {
|
|
198
|
+
return {
|
|
199
|
+
allowed: false,
|
|
200
|
+
outcome,
|
|
201
|
+
reason: `${reason} — denied because no approval answerer is available (fail closed).`,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
allowed: false,
|
|
206
|
+
outcome: "unavailable",
|
|
207
|
+
reason: `${reason} — denied: unexpected approval outcome ${JSON.stringify(outcome)}.`,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return { assessCommand, authorize, buildReason };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* @param {import("../lib/hosts.js").RemoteHost} host
|
|
216
|
+
* @returns {string}
|
|
217
|
+
*/
|
|
218
|
+
export function formatHost(host) {
|
|
219
|
+
const user = host.username?.trim();
|
|
220
|
+
const target = `${host.host ?? host.name}${host.port && host.port !== 22 ? `:${host.port}` : ""}`;
|
|
221
|
+
return user ? `${user}@${target}` : target;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** @param {"read" | "write" | "execute" | "transfer"} action */
|
|
225
|
+
function actionLabel(action) {
|
|
226
|
+
switch (action) {
|
|
227
|
+
case "execute":
|
|
228
|
+
return "command execution";
|
|
229
|
+
case "read":
|
|
230
|
+
return "read";
|
|
231
|
+
case "write":
|
|
232
|
+
return "file write";
|
|
233
|
+
case "transfer":
|
|
234
|
+
return "file transfer";
|
|
235
|
+
default:
|
|
236
|
+
return "operation";
|
|
237
|
+
}
|
|
238
|
+
}
|
package/lib/audit.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded audit trail for remote operations.
|
|
3
|
+
*
|
|
4
|
+
* Every model-facing remote tool call is recorded in process memory (ring of
|
|
5
|
+
* `limit` newest entries) and appended to a JSONL file so the management page
|
|
6
|
+
* can show what the agent did and a later harness restart can still display the
|
|
7
|
+
* recent past. `list({ host, offset })` filters by exact host for the per-host
|
|
8
|
+
* audit dialog and `count({ host })` totals the matching entries. Recording and
|
|
9
|
+
* listing are synchronous; file I/O is queued, best-effort, and never throws
|
|
10
|
+
* into the tool path.
|
|
11
|
+
*
|
|
12
|
+
* Every entry keeps two detail fields (v0.5.1): `detail` (300-char one-line,
|
|
13
|
+
* for the table) and `detailFull` (the raw command/script/path, whitespace
|
|
14
|
+
* preserved, bounded to 16 384 chars) for the expand-row viewer and exports.
|
|
15
|
+
* `list()` omits `detailFull` unless called with `full: true`, and legacy JSONL
|
|
16
|
+
* entries written before v0.5.1 are backfilled from `detail`.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
20
|
+
import { dirname } from "node:path";
|
|
21
|
+
|
|
22
|
+
/** Default retained entries (process memory + page page size). */
|
|
23
|
+
export const DEFAULT_AUDIT_LIMIT = 500;
|
|
24
|
+
/** Upper bound for the raw, whitespace-preserving `detailFull` field. */
|
|
25
|
+
export const DETAIL_FULL_MAX = 16_384;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} [options]
|
|
29
|
+
* @param {number} [options.limit] Retained entries.
|
|
30
|
+
* @param {string} [options.filePath] JSONL persistence path; omit for memory-only.
|
|
31
|
+
* @param {{ warn?: (message: string) => void }} [options.logger]
|
|
32
|
+
*/
|
|
33
|
+
export function createAuditLog({ limit = DEFAULT_AUDIT_LIMIT, filePath, logger } = {}) {
|
|
34
|
+
const maxEntries = Number.isSafeInteger(limit) && limit > 0 ? limit : DEFAULT_AUDIT_LIMIT;
|
|
35
|
+
/** @type {any[]} newest first */
|
|
36
|
+
const entries = [];
|
|
37
|
+
let nextId = 1;
|
|
38
|
+
/** @type {Promise<void>} */
|
|
39
|
+
let queue = Promise.resolve();
|
|
40
|
+
let disposed = false;
|
|
41
|
+
|
|
42
|
+
const warn = (message) => {
|
|
43
|
+
try {
|
|
44
|
+
logger?.warn?.(message);
|
|
45
|
+
} catch {
|
|
46
|
+
// logging must never break the audit path
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
function record(input) {
|
|
51
|
+
const entry = {
|
|
52
|
+
id: nextId,
|
|
53
|
+
time: Date.now(),
|
|
54
|
+
tool: String(input.tool ?? ""),
|
|
55
|
+
host: String(input.host ?? "—"),
|
|
56
|
+
action: String(input.action ?? input.tool ?? ""),
|
|
57
|
+
risk: String(input.risk ?? ""),
|
|
58
|
+
outcome: input.outcome === "error" || input.outcome === "denied" ? input.outcome : "ok",
|
|
59
|
+
detail: boundDetail(input.detail),
|
|
60
|
+
detailFull: boundDetailFull(input.detail),
|
|
61
|
+
durationMs: Math.max(0, Math.round(Number(input.durationMs) || 0)),
|
|
62
|
+
};
|
|
63
|
+
nextId += 1;
|
|
64
|
+
entries.unshift(entry);
|
|
65
|
+
while (entries.length > maxEntries) entries.pop();
|
|
66
|
+
if (filePath !== undefined) {
|
|
67
|
+
// Synchronous append: the audit line must survive a headless process that
|
|
68
|
+
// exits immediately after its turn (the plugin's async teardown is not
|
|
69
|
+
// guaranteed to run before `process.exit`).
|
|
70
|
+
try {
|
|
71
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
72
|
+
appendFileSync(filePath, `${JSON.stringify(entry)}\n`, "utf8");
|
|
73
|
+
} catch (error) {
|
|
74
|
+
warn(`dsh-remote: audit append failed: ${messageOf(error)}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return entry;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* List audit entries, newest first.
|
|
82
|
+
*
|
|
83
|
+
* Backwards compatible: with no arguments it returns the newest `limit`
|
|
84
|
+
* entries as an array. `host` filters by exact `entry.host` equality (no
|
|
85
|
+
* globs) and `offset` pages through the matching entries.
|
|
86
|
+
*
|
|
87
|
+
* `full: true` includes the raw `detailFull` field; the default page stays
|
|
88
|
+
* lightweight (detailFull omitted) for the overview and the audit table.
|
|
89
|
+
*
|
|
90
|
+
* @param {{ limit?: number, offset?: number, host?: string, full?: boolean }} [options]
|
|
91
|
+
* @returns {any[]}
|
|
92
|
+
*/
|
|
93
|
+
function list({ limit: pageSize = 200, offset = 0, host, full } = {}) {
|
|
94
|
+
const size = Number.isSafeInteger(pageSize) && pageSize > 0 ? pageSize : 200;
|
|
95
|
+
const start = Number.isSafeInteger(offset) && offset > 0 ? offset : 0;
|
|
96
|
+
const hostFilter = typeof host === "string" && host.length > 0 ? host : undefined;
|
|
97
|
+
const matching =
|
|
98
|
+
hostFilter === undefined ? entries : entries.filter((entry) => entry.host === hostFilter);
|
|
99
|
+
const page = matching.slice(start, start + Math.min(size, maxEntries));
|
|
100
|
+
if (full === true) return page;
|
|
101
|
+
return page.map((entry) => {
|
|
102
|
+
const { detailFull, ...rest } = entry;
|
|
103
|
+
return rest;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Count audit entries, optionally for one exact host.
|
|
109
|
+
*
|
|
110
|
+
* @param {{ host?: string }} [options]
|
|
111
|
+
* @returns {number}
|
|
112
|
+
*/
|
|
113
|
+
function count({ host } = {}) {
|
|
114
|
+
const hostFilter = typeof host === "string" && host.length > 0 ? host : undefined;
|
|
115
|
+
if (hostFilter === undefined) return entries.length;
|
|
116
|
+
let total = 0;
|
|
117
|
+
for (const entry of entries) {
|
|
118
|
+
if (entry.host === hostFilter) total += 1;
|
|
119
|
+
}
|
|
120
|
+
return total;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function clear() {
|
|
124
|
+
entries.length = 0;
|
|
125
|
+
if (filePath !== undefined) {
|
|
126
|
+
try {
|
|
127
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
128
|
+
writeFileSync(filePath, "", "utf8");
|
|
129
|
+
} catch (error) {
|
|
130
|
+
warn(`dsh-remote: audit reset failed: ${messageOf(error)}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { cleared: true };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Load the retained tail from disk (best effort). */
|
|
137
|
+
async function load() {
|
|
138
|
+
if (filePath === undefined) return;
|
|
139
|
+
let text;
|
|
140
|
+
try {
|
|
141
|
+
text = readFileSync(filePath, "utf8");
|
|
142
|
+
} catch {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const lines = text.split("\n").filter((line) => line.trim().length > 0);
|
|
146
|
+
const tail = lines.slice(-maxEntries);
|
|
147
|
+
const parsed = [];
|
|
148
|
+
for (const line of tail) {
|
|
149
|
+
try {
|
|
150
|
+
const entry = JSON.parse(line);
|
|
151
|
+
if (entry !== null && typeof entry === "object" && Number.isFinite(entry.time)) {
|
|
152
|
+
// Legacy (pre-v0.5.1) lines have no detailFull; backfill from detail
|
|
153
|
+
// so the full viewer/export sees a string for every entry.
|
|
154
|
+
if (typeof entry.detailFull !== "string") entry.detailFull = boundDetailFull(entry.detail);
|
|
155
|
+
parsed.push(entry);
|
|
156
|
+
}
|
|
157
|
+
} catch {
|
|
158
|
+
// skip a torn line
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
entries.length = 0;
|
|
162
|
+
for (const entry of parsed.reverse()) entries.push(entry);
|
|
163
|
+
nextId = entries.reduce((max, entry) => Math.max(max, Number(entry.id) || 0), 0) + 1;
|
|
164
|
+
if (lines.length > maxEntries) {
|
|
165
|
+
// Bound the file so it cannot grow without limit across restarts.
|
|
166
|
+
try {
|
|
167
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
168
|
+
writeFileSync(filePath, parsed.map((entry) => JSON.stringify(entry)).reverse().join("\n") + "\n", "utf8");
|
|
169
|
+
} catch (error) {
|
|
170
|
+
warn(`dsh-remote: audit compaction failed: ${messageOf(error)}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Wait for pending file I/O (tests/disposal). */
|
|
176
|
+
async function flush() {
|
|
177
|
+
await queue;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function dispose() {
|
|
181
|
+
disposed = true;
|
|
182
|
+
await queue;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
record,
|
|
187
|
+
list,
|
|
188
|
+
count,
|
|
189
|
+
clear,
|
|
190
|
+
load,
|
|
191
|
+
flush,
|
|
192
|
+
dispose,
|
|
193
|
+
get size() {
|
|
194
|
+
return entries.length;
|
|
195
|
+
},
|
|
196
|
+
get isDisposed() {
|
|
197
|
+
return disposed;
|
|
198
|
+
},
|
|
199
|
+
filePath,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** @param {unknown} value @returns {string} */
|
|
204
|
+
export function boundDetail(value, max = 300) {
|
|
205
|
+
const text = String(value ?? "").replaceAll(/\s+/gu, " ").trim();
|
|
206
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Raw, whitespace-preserving detail for the full viewer and exports.
|
|
211
|
+
*
|
|
212
|
+
* @param {unknown} value
|
|
213
|
+
* @param {number} [max]
|
|
214
|
+
* @returns {string}
|
|
215
|
+
*/
|
|
216
|
+
export function boundDetailFull(value, max = DETAIL_FULL_MAX) {
|
|
217
|
+
const text = String(value ?? "");
|
|
218
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** @param {unknown} error @returns {string} */
|
|
222
|
+
function messageOf(error) {
|
|
223
|
+
return error instanceof Error ? error.message : String(error);
|
|
224
|
+
}
|