@masstensor/diagnose 0.0.0-stage → 0.1.0
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 +80 -2
- package/deploy/Caddyfile +3 -0
- package/deploy/ecosystem.config.cjs +1 -0
- package/deploy/start-relay.sh +4 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +82 -0
- package/dist/crypto.d.ts +25 -0
- package/dist/crypto.js +60 -0
- package/dist/engine.d.ts +19 -0
- package/dist/engine.js +145 -0
- package/dist/executor.d.ts +18 -0
- package/dist/executor.js +203 -0
- package/dist/mcp.d.ts +1 -0
- package/dist/mcp.js +36 -0
- package/dist/operator.d.ts +21 -0
- package/dist/operator.js +68 -0
- package/dist/peer.d.ts +51 -0
- package/dist/peer.js +253 -0
- package/dist/relay-main.d.ts +2 -0
- package/dist/relay-main.js +6 -0
- package/dist/relay.d.ts +15 -0
- package/dist/relay.js +176 -0
- package/dist/schema.d.ts +102 -0
- package/dist/schema.js +28 -0
- package/dist/util.d.ts +11 -0
- package/dist/util.js +46 -0
- package/npm-shrinkwrap.json +2229 -0
- package/package.json +46 -4
- package/src/cli.ts +57 -0
- package/src/crypto.ts +54 -0
- package/src/engine.ts +87 -0
- package/src/executor.ts +129 -0
- package/src/mcp.ts +25 -0
- package/src/operator.ts +45 -0
- package/src/peer.ts +174 -0
- package/src/relay-main.ts +5 -0
- package/src/relay.ts +97 -0
- package/src/schema.ts +44 -0
- package/src/util.ts +39 -0
- package/src/vendor.d.ts +22 -0
- package/test/CACOPHONY-LICENSE +24 -0
- package/test/cli.test.ts +33 -0
- package/test/mcp.test.ts +29 -0
- package/test/noise-vector.json +40 -0
- package/test/probe.test.ts +131 -0
- package/test/serial.test.ts +24 -0
- package/test/vector.test.ts +32 -0
- package/tsconfig.json +8 -0
package/dist/relay.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { createReadStream, statSync } from 'node:fs';
|
|
3
|
+
import { WebSocket, WebSocketServer } from 'ws';
|
|
4
|
+
import { MAX_FRAME } from './schema.js';
|
|
5
|
+
const control = (ws, type, extra = {}) => { if (ws.readyState === WebSocket.OPEN)
|
|
6
|
+
ws.send(JSON.stringify({ type, ...extra })); };
|
|
7
|
+
export function createRelay(options = {}) {
|
|
8
|
+
const rooms = new Map();
|
|
9
|
+
const clients = new Map();
|
|
10
|
+
const connectionsByIp = new Map();
|
|
11
|
+
const server = http.createServer((req, res) => {
|
|
12
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
13
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
14
|
+
if (req.method === 'GET' && req.url === '/healthz') {
|
|
15
|
+
res.setHeader('Content-Type', 'application/json');
|
|
16
|
+
res.end('{"ok":true,"protocol":1}');
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (req.method === 'GET' && req.url === '/downloads/diagnose-0.1.0.tgz' && options.downloadPath) {
|
|
20
|
+
try {
|
|
21
|
+
const size = statSync(options.downloadPath).size;
|
|
22
|
+
res.setHeader('Content-Type', 'application/octet-stream');
|
|
23
|
+
res.setHeader('Content-Length', size);
|
|
24
|
+
createReadStream(options.downloadPath).on('error', () => res.destroy()).pipe(res);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
res.writeHead(404);
|
|
28
|
+
res.end();
|
|
29
|
+
}
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
33
|
+
res.writeHead(req.url === '/' ? 200 : 404);
|
|
34
|
+
res.end(req.url === '/' ? 'Diagnose blind relay v1. User-approved, end-to-end encrypted diagnostics.\n' : 'Not found\n');
|
|
35
|
+
});
|
|
36
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME, perMessageDeflate: false });
|
|
37
|
+
server.on('upgrade', (req, socket, head) => {
|
|
38
|
+
if (req.url !== '/v1/connect' || clients.size >= 400) {
|
|
39
|
+
socket.destroy();
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
|
|
43
|
+
});
|
|
44
|
+
wss.on('connection', (ws, req) => {
|
|
45
|
+
const direct = req.socket.remoteAddress ?? 'unknown';
|
|
46
|
+
const ip = ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(direct) ? String(req.headers['x-forwarded-for'] ?? direct).split(',')[0].trim() : direct;
|
|
47
|
+
if ((connectionsByIp.get(ip) ?? 0) >= 30) {
|
|
48
|
+
ws.close(1008, 'Connection limit');
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
connectionsByIp.set(ip, (connectionsByIp.get(ip) ?? 0) + 1);
|
|
52
|
+
const state = { ip, alive: true };
|
|
53
|
+
clients.set(ws, state);
|
|
54
|
+
const registration = setTimeout(() => { if (!state.role)
|
|
55
|
+
ws.close(1008, 'Registration timeout'); }, 5000);
|
|
56
|
+
ws.on('pong', () => { state.alive = true; });
|
|
57
|
+
ws.on('error', () => ws.terminate());
|
|
58
|
+
ws.on('message', (raw, binary) => {
|
|
59
|
+
try {
|
|
60
|
+
const bytes = Buffer.from(raw);
|
|
61
|
+
if (!state.role) {
|
|
62
|
+
if (binary || bytes.length > 256)
|
|
63
|
+
throw new Error();
|
|
64
|
+
const msg = JSON.parse(bytes.toString());
|
|
65
|
+
if (msg.version !== 1 || !/^[A-Za-z0-9_-]{16}$/.test(msg.room) || !['host', 'join'].includes(msg.role))
|
|
66
|
+
throw new Error();
|
|
67
|
+
if (msg.role === 'host') {
|
|
68
|
+
if (rooms.has(msg.room) || rooms.size >= (options.maxRooms ?? 100))
|
|
69
|
+
throw new Error();
|
|
70
|
+
rooms.set(msg.room, { host: ws, locked: false, attempts: 0, expires: Date.now() + (options.invitationMs ?? 600000), frames: 0, window: Date.now() });
|
|
71
|
+
state.role = 'host';
|
|
72
|
+
state.room = msg.room;
|
|
73
|
+
control(ws, 'registered');
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
const room = rooms.get(msg.room);
|
|
77
|
+
if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now())
|
|
78
|
+
throw new Error();
|
|
79
|
+
state.role = 'join';
|
|
80
|
+
state.room = msg.room;
|
|
81
|
+
room.peer = ws;
|
|
82
|
+
room.attempts++;
|
|
83
|
+
control(room.host, 'peer');
|
|
84
|
+
control(ws, 'joined');
|
|
85
|
+
}
|
|
86
|
+
clearTimeout(registration);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const room = rooms.get(state.room);
|
|
90
|
+
if (!room)
|
|
91
|
+
throw new Error();
|
|
92
|
+
if (binary) {
|
|
93
|
+
if (Date.now() - room.window > 1000) {
|
|
94
|
+
room.window = Date.now();
|
|
95
|
+
room.frames = 0;
|
|
96
|
+
}
|
|
97
|
+
if (++room.frames > 250 || bytes.length > MAX_FRAME)
|
|
98
|
+
throw new Error();
|
|
99
|
+
const target = state.role === 'host' ? room.peer : room.host;
|
|
100
|
+
if (!target || target.readyState !== WebSocket.OPEN || target.bufferedAmount > 1024 * 1024)
|
|
101
|
+
throw new Error();
|
|
102
|
+
let buffered = 0;
|
|
103
|
+
for (const client of clients.keys())
|
|
104
|
+
buffered += client.bufferedAmount;
|
|
105
|
+
if (buffered > 64 * 1024 * 1024)
|
|
106
|
+
throw new Error();
|
|
107
|
+
options.observeCiphertext?.(bytes);
|
|
108
|
+
target.send(bytes, { binary: true });
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (bytes.length > 128 || state.role !== 'host')
|
|
112
|
+
throw new Error();
|
|
113
|
+
const msg = JSON.parse(bytes.toString());
|
|
114
|
+
if (msg.type === 'lock') {
|
|
115
|
+
room.locked = true;
|
|
116
|
+
room.expires = Date.now() + (options.sessionMs ?? 3600000);
|
|
117
|
+
}
|
|
118
|
+
else if (msg.type === 'reject' && !room.locked) {
|
|
119
|
+
const peer = room.peer;
|
|
120
|
+
room.peer = undefined;
|
|
121
|
+
peer?.close(1008, 'Pairing rejected');
|
|
122
|
+
}
|
|
123
|
+
else
|
|
124
|
+
throw new Error();
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
ws.close(1008, 'Protocol rejected');
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
ws.on('close', () => {
|
|
131
|
+
clearTimeout(registration);
|
|
132
|
+
clients.delete(ws);
|
|
133
|
+
const count = (connectionsByIp.get(ip) ?? 1) - 1;
|
|
134
|
+
if (count > 0)
|
|
135
|
+
connectionsByIp.set(ip, count);
|
|
136
|
+
else
|
|
137
|
+
connectionsByIp.delete(ip);
|
|
138
|
+
const room = rooms.get(state.room);
|
|
139
|
+
if (!room)
|
|
140
|
+
return;
|
|
141
|
+
if (state.role === 'host') {
|
|
142
|
+
rooms.delete(state.room);
|
|
143
|
+
room.peer?.close(1000, 'Session ended');
|
|
144
|
+
}
|
|
145
|
+
else if (room.peer === ws) {
|
|
146
|
+
room.peer = undefined;
|
|
147
|
+
control(room.host, 'peer-left');
|
|
148
|
+
if (room.locked)
|
|
149
|
+
room.host.close(1000, 'Peer disconnected');
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
const sweep = setInterval(() => {
|
|
154
|
+
for (const [id, room] of rooms)
|
|
155
|
+
if (room.expires < Date.now()) {
|
|
156
|
+
rooms.delete(id);
|
|
157
|
+
room.host.close(1000, 'Session expired');
|
|
158
|
+
room.peer?.close(1000, 'Session expired');
|
|
159
|
+
}
|
|
160
|
+
for (const [ws, state] of clients) {
|
|
161
|
+
if (!state.alive)
|
|
162
|
+
ws.terminate();
|
|
163
|
+
else {
|
|
164
|
+
state.alive = false;
|
|
165
|
+
ws.ping();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}, 10000);
|
|
169
|
+
sweep.unref();
|
|
170
|
+
return {
|
|
171
|
+
server,
|
|
172
|
+
async listen() { await new Promise((resolve, reject) => { server.once('error', reject); server.listen(options.port ?? 8792, options.host ?? '127.0.0.1', () => { server.off('error', reject); resolve(); }); }); return server.address().port; },
|
|
173
|
+
async close() { clearInterval(sweep); for (const ws of wss.clients)
|
|
174
|
+
ws.terminate(); await new Promise(resolve => wss.close(() => resolve())); await new Promise(resolve => server.close(() => resolve())); },
|
|
175
|
+
};
|
|
176
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const MAX_FRAME: number;
|
|
3
|
+
export declare const CHUNK_SIZE: number;
|
|
4
|
+
export declare const MAX_OUTPUT: number;
|
|
5
|
+
export declare const taskSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
6
|
+
id: z.ZodString;
|
|
7
|
+
reason: z.ZodString;
|
|
8
|
+
operation: z.ZodLiteral<"system.inspect">;
|
|
9
|
+
arguments: z.ZodObject<{}, z.core.$strict>;
|
|
10
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
11
|
+
id: z.ZodString;
|
|
12
|
+
reason: z.ZodString;
|
|
13
|
+
operation: z.ZodLiteral<"file.read">;
|
|
14
|
+
arguments: z.ZodObject<{
|
|
15
|
+
path: z.ZodString;
|
|
16
|
+
offset: z.ZodDefault<z.ZodNumber>;
|
|
17
|
+
length: z.ZodDefault<z.ZodNumber>;
|
|
18
|
+
}, z.core.$strict>;
|
|
19
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
20
|
+
id: z.ZodString;
|
|
21
|
+
reason: z.ZodString;
|
|
22
|
+
operation: z.ZodLiteral<"file.write">;
|
|
23
|
+
arguments: z.ZodObject<{
|
|
24
|
+
path: z.ZodString;
|
|
25
|
+
content: z.ZodString;
|
|
26
|
+
expectedSha256: z.ZodOptional<z.ZodString>;
|
|
27
|
+
}, z.core.$strict>;
|
|
28
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
29
|
+
id: z.ZodString;
|
|
30
|
+
reason: z.ZodString;
|
|
31
|
+
operation: z.ZodLiteral<"process.run">;
|
|
32
|
+
arguments: z.ZodObject<{
|
|
33
|
+
executable: z.ZodString;
|
|
34
|
+
args: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
35
|
+
cwd: z.ZodOptional<z.ZodString>;
|
|
36
|
+
timeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
37
|
+
}, z.core.$strict>;
|
|
38
|
+
}, z.core.$strict>, ...z.ZodObject<{
|
|
39
|
+
id: z.ZodString;
|
|
40
|
+
reason: z.ZodString;
|
|
41
|
+
operation: z.ZodLiteral<"serial.capture" | "serial.exchange">;
|
|
42
|
+
arguments: z.ZodObject<{
|
|
43
|
+
path: z.ZodString;
|
|
44
|
+
baudRate: z.ZodDefault<z.ZodNumber>;
|
|
45
|
+
durationMs: z.ZodDefault<z.ZodNumber>;
|
|
46
|
+
dataHex: z.ZodOptional<z.ZodString>;
|
|
47
|
+
}, z.core.$strict>;
|
|
48
|
+
}, z.core.$strict>[]], "operation">;
|
|
49
|
+
export type Task = z.infer<typeof taskSchema>;
|
|
50
|
+
export type TaskInput = {
|
|
51
|
+
operation: Task['operation'];
|
|
52
|
+
arguments: Record<string, unknown>;
|
|
53
|
+
reason: string;
|
|
54
|
+
};
|
|
55
|
+
export type ApprovalStage = 'execute' | 'send';
|
|
56
|
+
export type Approval = {
|
|
57
|
+
stage: ApprovalStage;
|
|
58
|
+
task: Task;
|
|
59
|
+
digest: string;
|
|
60
|
+
preview: string;
|
|
61
|
+
bytes?: number;
|
|
62
|
+
signal?: AbortSignal;
|
|
63
|
+
};
|
|
64
|
+
export type ApprovalHandler = (request: Approval) => Promise<boolean>;
|
|
65
|
+
export type Result = {
|
|
66
|
+
status: 'ok' | 'error' | 'denied' | 'cancelled' | 'duplicate';
|
|
67
|
+
data?: unknown;
|
|
68
|
+
error?: string;
|
|
69
|
+
exitCode?: number | null;
|
|
70
|
+
truncated?: boolean;
|
|
71
|
+
};
|
|
72
|
+
export type WireMessage = {
|
|
73
|
+
type: 'session.accepted';
|
|
74
|
+
label: string;
|
|
75
|
+
fingerprint: string;
|
|
76
|
+
} | {
|
|
77
|
+
type: 'session.closed';
|
|
78
|
+
reason: string;
|
|
79
|
+
} | {
|
|
80
|
+
type: 'task.request';
|
|
81
|
+
task: Task;
|
|
82
|
+
} | {
|
|
83
|
+
type: 'task.started';
|
|
84
|
+
id: string;
|
|
85
|
+
digest: string;
|
|
86
|
+
} | {
|
|
87
|
+
type: 'task.output';
|
|
88
|
+
id: string;
|
|
89
|
+
stream: string;
|
|
90
|
+
chunk: string;
|
|
91
|
+
index: number;
|
|
92
|
+
} | {
|
|
93
|
+
type: 'task.result';
|
|
94
|
+
id: string;
|
|
95
|
+
result: Result;
|
|
96
|
+
} | {
|
|
97
|
+
type: 'task.cancel';
|
|
98
|
+
id: string;
|
|
99
|
+
} | {
|
|
100
|
+
type: 'ping' | 'pong';
|
|
101
|
+
};
|
|
102
|
+
export declare function parseMessage(value: unknown): WireMessage;
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const MAX_FRAME = 64 * 1024;
|
|
3
|
+
export const CHUNK_SIZE = 12 * 1024;
|
|
4
|
+
export const MAX_OUTPUT = 10 * 1024 * 1024;
|
|
5
|
+
const path = z.string().min(1).max(4096);
|
|
6
|
+
const common = { id: z.string().uuid(), reason: z.string().min(1).max(1000) };
|
|
7
|
+
export const taskSchema = z.discriminatedUnion('operation', [
|
|
8
|
+
z.object({ ...common, operation: z.literal('system.inspect'), arguments: z.object({}).strict() }).strict(),
|
|
9
|
+
z.object({ ...common, operation: z.literal('file.read'), arguments: z.object({ path, offset: z.number().int().min(0).default(0), length: z.number().int().min(1).max(1024 * 1024).default(65536) }).strict() }).strict(),
|
|
10
|
+
z.object({ ...common, operation: z.literal('file.write'), arguments: z.object({ path, content: z.string().max(1024 * 1024), expectedSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict() }).strict(),
|
|
11
|
+
z.object({ ...common, operation: z.literal('process.run'), arguments: z.object({ executable: path, args: z.array(z.string().max(65536)).max(128).default([]), cwd: path.optional(), timeoutMs: z.number().int().min(100).max(300000).default(60000) }).strict() }).strict(),
|
|
12
|
+
...['serial.capture', 'serial.exchange'].map(operation => z.object({ ...common, operation: z.literal(operation), arguments: z.object({ path, baudRate: z.number().int().min(300).max(3000000).default(115200), durationMs: z.number().int().min(100).max(300000).default(20000), dataHex: z.string().regex(/^(?:[a-fA-F0-9]{2})*$/).max(65536).optional() }).strict() }).strict()),
|
|
13
|
+
]);
|
|
14
|
+
export function parseMessage(value) {
|
|
15
|
+
const basic = z.object({ type: z.string() }).passthrough().parse(value);
|
|
16
|
+
switch (basic.type) {
|
|
17
|
+
case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task) };
|
|
18
|
+
case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
|
|
19
|
+
case 'ping':
|
|
20
|
+
case 'pong': return { type: basic.type };
|
|
21
|
+
case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100) }).strict().parse(value);
|
|
22
|
+
case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
|
|
23
|
+
case 'task.started': return z.object({ type: z.literal('task.started'), id: z.string().uuid(), digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict().parse(value);
|
|
24
|
+
case 'task.output': return z.object({ type: z.literal('task.output'), id: z.string().uuid(), stream: z.string().max(20), chunk: z.string().max(CHUNK_SIZE * 2), index: z.number().int().min(0) }).strict().parse(value);
|
|
25
|
+
case 'task.result': return z.object({ type: z.literal('task.result'), id: z.string().uuid(), result: z.object({ status: z.enum(['ok', 'error', 'denied', 'cancelled', 'duplicate']), data: z.unknown().optional(), error: z.string().max(2000).optional(), exitCode: z.number().int().nullable().optional(), truncated: z.boolean().optional() }).strict() }).strict().parse(value);
|
|
26
|
+
default: throw new Error('Unsupported message type');
|
|
27
|
+
}
|
|
28
|
+
}
|
package/dist/util.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare function safeText(text: string): string;
|
|
2
|
+
export declare function redact(text: string): string;
|
|
3
|
+
export declare function canonical(value: unknown): string;
|
|
4
|
+
export declare const digest: (value: unknown) => string;
|
|
5
|
+
export declare const sha256: (bytes: Buffer) => string;
|
|
6
|
+
export declare function inside(root: string, path: string): boolean;
|
|
7
|
+
export declare class Audit {
|
|
8
|
+
readonly path: string;
|
|
9
|
+
constructor(path?: string);
|
|
10
|
+
record(event: string, details: Record<string, unknown>): void;
|
|
11
|
+
}
|
package/dist/util.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { appendFileSync, mkdirSync, openSync, closeSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { dirname, resolve, relative, isAbsolute } from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
export function safeText(text) {
|
|
6
|
+
return text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
|
7
|
+
}
|
|
8
|
+
export function redact(text) {
|
|
9
|
+
return safeText(text)
|
|
10
|
+
.replace(/("?(?:password|passwd|pswd|secret|token|session|authorization|api[_-]?key)"?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\r\n]+)/gi, '$1[REDACTED]')
|
|
11
|
+
.replace(/\bD1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}\b/g, '[PAIRING CODE]')
|
|
12
|
+
.replace(/\b[a-f0-9]{32,}\b/gi, '[REDACTED]')
|
|
13
|
+
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[PRIVATE KEY]');
|
|
14
|
+
}
|
|
15
|
+
export function canonical(value) {
|
|
16
|
+
if (Array.isArray(value))
|
|
17
|
+
return `[${value.map(canonical).join(',')}]`;
|
|
18
|
+
if (value !== null && typeof value === 'object')
|
|
19
|
+
return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
|
|
20
|
+
return JSON.stringify(value);
|
|
21
|
+
}
|
|
22
|
+
export const digest = (value) => createHash('sha256').update(canonical(value)).digest('hex');
|
|
23
|
+
export const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
24
|
+
export function inside(root, path) {
|
|
25
|
+
try {
|
|
26
|
+
const diff = relative(realpathSync(root), realpathSync(path));
|
|
27
|
+
return diff === '' || (!diff.startsWith('..') && !isAbsolute(diff));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export class Audit {
|
|
34
|
+
path;
|
|
35
|
+
constructor(path = resolve(os.homedir(), '.diagnose', `audit-${Date.now()}.jsonl`)) {
|
|
36
|
+
this.path = path;
|
|
37
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
38
|
+
const fd = openSync(path, 'ax', 0o600);
|
|
39
|
+
closeSync(fd);
|
|
40
|
+
this.record('session.created', {});
|
|
41
|
+
}
|
|
42
|
+
record(event, details) {
|
|
43
|
+
// No command text, payload, credentials, or file contents are persisted by default.
|
|
44
|
+
appendFileSync(this.path, JSON.stringify({ at: new Date().toISOString(), event, ...details }) + '\n', { mode: 0o600, flush: true });
|
|
45
|
+
}
|
|
46
|
+
}
|