@brud/daemon 0.0.0-stage → 0.0.1
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 +201 -0
- package/README.md +67 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +88 -0
- package/dist/client/DaemonClient.d.ts +55 -0
- package/dist/client/DaemonClient.js +383 -0
- package/dist/client/connectToDaemon.d.ts +19 -0
- package/dist/client/connectToDaemon.js +131 -0
- package/dist/client/errors.d.ts +74 -0
- package/dist/client/errors.js +104 -0
- package/dist/client/identity.d.ts +3 -0
- package/dist/client/identity.js +7 -0
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.js +23 -0
- package/dist/client/socket.d.ts +9 -0
- package/dist/client/socket.js +101 -0
- package/dist/client/spawn.d.ts +7 -0
- package/dist/client/spawn.js +171 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +29 -0
- package/dist/instanceRegistry.d.ts +130 -0
- package/dist/instanceRegistry.js +332 -0
- package/dist/lifecycle/endpoint.d.ts +19 -0
- package/dist/lifecycle/endpoint.js +124 -0
- package/dist/lifecycle/idle.d.ts +28 -0
- package/dist/lifecycle/idle.js +69 -0
- package/dist/lifecycle/index.d.ts +4 -0
- package/dist/lifecycle/index.js +21 -0
- package/dist/lifecycle/lock.d.ts +28 -0
- package/dist/lifecycle/lock.js +155 -0
- package/dist/lifecycle/shutdown.d.ts +39 -0
- package/dist/lifecycle/shutdown.js +115 -0
- package/dist/operatorConfig.d.ts +36 -0
- package/dist/operatorConfig.js +92 -0
- package/dist/security/channel.d.ts +113 -0
- package/dist/security/channel.js +448 -0
- package/dist/security/noise.d.ts +64 -0
- package/dist/security/noise.js +313 -0
- package/dist/security/ownership.d.ts +36 -0
- package/dist/security/ownership.js +86 -0
- package/dist/security/peerCredentials.d.ts +104 -0
- package/dist/security/peerCredentials.js +244 -0
- package/dist/server/Connection.d.ts +70 -0
- package/dist/server/Connection.js +412 -0
- package/dist/server/DaemonServer.d.ts +77 -0
- package/dist/server/DaemonServer.js +396 -0
- package/dist/server/createDaemon.d.ts +52 -0
- package/dist/server/createDaemon.js +165 -0
- package/dist/server/dispatch.d.ts +52 -0
- package/dist/server/dispatch.js +291 -0
- package/dist/server/framing.d.ts +63 -0
- package/dist/server/framing.js +196 -0
- package/dist/server/handshake.d.ts +22 -0
- package/dist/server/handshake.js +94 -0
- package/dist/server/protocolValidation.d.ts +47 -0
- package/dist/server/protocolValidation.js +366 -0
- package/dist/server/wireErrors.d.ts +5 -0
- package/dist/server/wireErrors.js +190 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +6 -0
- package/package.json +55 -4
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.RequestDispatcher = void 0;
|
|
37
|
+
const Protocol = __importStar(require("@brud/protocol"));
|
|
38
|
+
const instanceRegistry_js_1 = require("../instanceRegistry.js");
|
|
39
|
+
const handshake_js_1 = require("./handshake.js");
|
|
40
|
+
const wireErrors_js_1 = require("./wireErrors.js");
|
|
41
|
+
const DaemonVersion = __importStar(require("../version.js"));
|
|
42
|
+
/** Caller id the daemon presents to the kernel when opening a host session. */
|
|
43
|
+
const HOST_CALLER_ID = 'brud.host.daemon';
|
|
44
|
+
class MethodError extends Error {
|
|
45
|
+
rpcCode;
|
|
46
|
+
details;
|
|
47
|
+
constructor(rpcCode, message, details) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = 'MethodError';
|
|
50
|
+
this.rpcCode = rpcCode;
|
|
51
|
+
this.details = details;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function asParams(value) {
|
|
55
|
+
if (value === undefined) {
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
59
|
+
throw new MethodError(Protocol.INVALID_PARAMS, 'Params must be an object');
|
|
60
|
+
}
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
function requireString(params, key) {
|
|
64
|
+
const value = params[key];
|
|
65
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
66
|
+
throw new MethodError(Protocol.INVALID_PARAMS, `${key} must be a non-empty string`, { field: key });
|
|
67
|
+
}
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
function optionalString(params, key) {
|
|
71
|
+
const value = params[key];
|
|
72
|
+
if (value === undefined) {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
if (typeof value !== 'string') {
|
|
76
|
+
throw new MethodError(Protocol.INVALID_PARAMS, `${key} must be a string`, { field: key });
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
function optionalBoolean(params, key) {
|
|
81
|
+
const value = params[key];
|
|
82
|
+
if (value !== undefined && typeof value !== 'boolean') {
|
|
83
|
+
throw new MethodError(Protocol.INVALID_PARAMS, `${key} must be a boolean`, { field: key });
|
|
84
|
+
}
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
/** Plain JSON copy: nothing but data crosses the wire. */
|
|
88
|
+
function toJson(value) {
|
|
89
|
+
return JSON.parse(JSON.stringify(value ?? null));
|
|
90
|
+
}
|
|
91
|
+
function describe(instance) {
|
|
92
|
+
return {
|
|
93
|
+
instanceId: instance.id,
|
|
94
|
+
state: instance.state,
|
|
95
|
+
clientCount: instance.clients.size,
|
|
96
|
+
lastUsedAt: instance.lastUsedAt.toISOString(),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Routes daemon RPC. The dispatcher knows the kernel and nothing above it:
|
|
101
|
+
* remote work is Brud syntax handed to the Router inside a host session whose
|
|
102
|
+
* capabilities the operator assigned to the authenticated principal.
|
|
103
|
+
*/
|
|
104
|
+
class RequestDispatcher {
|
|
105
|
+
registry;
|
|
106
|
+
connectValidator = new handshake_js_1.ConnectValidator();
|
|
107
|
+
serverName;
|
|
108
|
+
serverVersion;
|
|
109
|
+
startedAt = Date.now();
|
|
110
|
+
constructor(options) {
|
|
111
|
+
this.registry = options.registry;
|
|
112
|
+
this.serverName = options.serverName ?? DaemonVersion.DAEMON_SERVER_NAME;
|
|
113
|
+
this.serverVersion = options.serverVersion ?? DaemonVersion.DAEMON_SERVER_VERSION;
|
|
114
|
+
}
|
|
115
|
+
/** Detaches a closed connection from every kernel it used. */
|
|
116
|
+
connectionClosed(connectionId) {
|
|
117
|
+
this.registry.detachClient(connectionId);
|
|
118
|
+
}
|
|
119
|
+
async dispatch(request, session, options = {}) {
|
|
120
|
+
try {
|
|
121
|
+
return await this.route(request, session, options);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error instanceof MethodError) {
|
|
125
|
+
return (0, wireErrors_js_1.createRpcErrorResponse)(request.id, error.rpcCode, error.message, error.details);
|
|
126
|
+
}
|
|
127
|
+
if (error instanceof instanceRegistry_js_1.KernelInstanceNotFoundError) {
|
|
128
|
+
return (0, wireErrors_js_1.createRpcErrorResponse)(request.id, Protocol.INVALID_PARAMS, error.message, {
|
|
129
|
+
errorCode: error.code,
|
|
130
|
+
instanceId: error.instanceId,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
if (error instanceof instanceRegistry_js_1.BootOptionNotAllowedError) {
|
|
134
|
+
return (0, wireErrors_js_1.createRpcErrorResponse)(request.id, Protocol.INVALID_PARAMS, error.message, {
|
|
135
|
+
errorCode: error.code,
|
|
136
|
+
field: error.field,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return (0, wireErrors_js_1.toRpcErrorResponse)(request.id, error);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async route(request, session, options) {
|
|
143
|
+
if (request.method === Protocol.DAEMON_CONNECT) {
|
|
144
|
+
return success(request.id, this.connect(request.params, session));
|
|
145
|
+
}
|
|
146
|
+
if (!session.handshaken) {
|
|
147
|
+
throw new MethodError(Protocol.HANDSHAKE_REQUIRED, `Method "${request.method}" requires a completed daemon handshake`, { method: request.method });
|
|
148
|
+
}
|
|
149
|
+
const params = asParams(request.params);
|
|
150
|
+
switch (request.method) {
|
|
151
|
+
case Protocol.DAEMON_PING:
|
|
152
|
+
return success(request.id, this.ping(params, session));
|
|
153
|
+
case Protocol.DAEMON_INFO:
|
|
154
|
+
return success(request.id, this.info(session));
|
|
155
|
+
case Protocol.KERNEL_REQUIREMENTS:
|
|
156
|
+
return success(request.id, await this.requirements());
|
|
157
|
+
case Protocol.KERNEL_BOOT:
|
|
158
|
+
return success(request.id, await this.boot(params, session));
|
|
159
|
+
case Protocol.KERNEL_ATTACH:
|
|
160
|
+
return success(request.id, this.attach(params, session));
|
|
161
|
+
case Protocol.KERNEL_LIST:
|
|
162
|
+
return success(request.id, this.list(session));
|
|
163
|
+
case Protocol.KERNEL_STATUS:
|
|
164
|
+
return success(request.id, this.status(params, session));
|
|
165
|
+
case Protocol.KERNEL_DISPOSE:
|
|
166
|
+
return success(request.id, await this.dispose(params, session));
|
|
167
|
+
case Protocol.KERNEL_KINDS:
|
|
168
|
+
return success(request.id, await this.kinds(params, session));
|
|
169
|
+
case Protocol.KERNEL_ROUTE:
|
|
170
|
+
return success(request.id, await this.routeText(params, session, options.signal));
|
|
171
|
+
default:
|
|
172
|
+
throw new MethodError(Protocol.METHOD_NOT_FOUND, `Unknown method "${request.method}"`, { method: request.method });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
connect(value, session) {
|
|
176
|
+
if (session.handshaken) {
|
|
177
|
+
throw new MethodError(Protocol.ALREADY_HANDSHAKEN, 'This connection has already completed the daemon handshake');
|
|
178
|
+
}
|
|
179
|
+
const outcome = this.connectValidator.validate(value);
|
|
180
|
+
if (!outcome.ok) {
|
|
181
|
+
throw new MethodError(outcome.code, outcome.message, outcome.data);
|
|
182
|
+
}
|
|
183
|
+
const tier = session.tier;
|
|
184
|
+
if (tier === undefined) {
|
|
185
|
+
throw new MethodError(Protocol.INTERNAL_ERROR, 'The connection has no authenticated principal');
|
|
186
|
+
}
|
|
187
|
+
session.markHandshaken();
|
|
188
|
+
return {
|
|
189
|
+
connectionId: session.connectionId,
|
|
190
|
+
protocolVersion: Protocol.DAEMON_PROTOCOL_VERSION,
|
|
191
|
+
tier,
|
|
192
|
+
capabilities: {
|
|
193
|
+
protocolVersion: Protocol.DAEMON_PROTOCOL_VERSION,
|
|
194
|
+
methods: [...Protocol.DAEMON_METHODS, ...Protocol.KERNEL_METHODS, ...Protocol.REQUEST_METHODS],
|
|
195
|
+
},
|
|
196
|
+
server: { name: this.serverName, version: this.serverVersion, pid: process.pid },
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
ping(params, session) {
|
|
200
|
+
const nonce = optionalString(params, 'nonce');
|
|
201
|
+
return {
|
|
202
|
+
connectionId: session.connectionId,
|
|
203
|
+
timestamp: Date.now(),
|
|
204
|
+
...(nonce === undefined ? {} : { nonce }),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
info(session) {
|
|
208
|
+
return {
|
|
209
|
+
connectionId: session.connectionId,
|
|
210
|
+
name: this.serverName,
|
|
211
|
+
version: this.serverVersion,
|
|
212
|
+
protocolVersion: Protocol.DAEMON_PROTOCOL_VERSION,
|
|
213
|
+
pid: process.pid,
|
|
214
|
+
uptimeMs: Date.now() - this.startedAt,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
async requirements() {
|
|
218
|
+
const fields = await this.registry.requirements();
|
|
219
|
+
const settable = this.registry.clientSettableFields;
|
|
220
|
+
return { fields: fields.map((field) => ({ ...field, clientSettable: settable.includes(field.name) })) };
|
|
221
|
+
}
|
|
222
|
+
async boot(params, session) {
|
|
223
|
+
const options = params.options ?? {};
|
|
224
|
+
if (typeof options !== 'object' || options === null || Array.isArray(options)) {
|
|
225
|
+
throw new MethodError(Protocol.INVALID_PARAMS, 'options must be an object', { field: 'options' });
|
|
226
|
+
}
|
|
227
|
+
const { instance, reused } = await this.registry.boot(toJson(options), session.connectionId);
|
|
228
|
+
return { instance: describe(instance), reused, pruned: toJson(instance.pruned) };
|
|
229
|
+
}
|
|
230
|
+
attach(params, session) {
|
|
231
|
+
return { instance: describe(this.registry.attach(requireString(params, 'instanceId'), session.connectionId)) };
|
|
232
|
+
}
|
|
233
|
+
list(session) {
|
|
234
|
+
return { instances: this.registry.listFor(session.connectionId).map(describe) };
|
|
235
|
+
}
|
|
236
|
+
status(params, session) {
|
|
237
|
+
const instanceId = requireString(params, 'instanceId');
|
|
238
|
+
try {
|
|
239
|
+
return { instance: describe(this.registry.forClient(instanceId, session.connectionId)) };
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
if (error instanceof instanceRegistry_js_1.KernelInstanceNotFoundError) {
|
|
243
|
+
return { instance: null };
|
|
244
|
+
}
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
async dispose(params, session) {
|
|
249
|
+
const instance = this.registry.forClient(requireString(params, 'instanceId'), session.connectionId);
|
|
250
|
+
return { disposed: await this.registry.dispose(instance.id) };
|
|
251
|
+
}
|
|
252
|
+
/** Runs `operation` against the Router inside the session's host call. */
|
|
253
|
+
async inHostSession(kernel, session, operation) {
|
|
254
|
+
const kernelModule = await (0, instanceRegistry_js_1.loadKernelModule)();
|
|
255
|
+
const capabilities = this.registry.capabilitiesFor(session.tier ?? 'ai');
|
|
256
|
+
return kernel.runHostCall({ capabilities }, async () => {
|
|
257
|
+
const registry = kernel.requestAccess({ callerId: HOST_CALLER_ID, tier: 'core', options: {} }, kernelModule.ExposedApiRegistryToken);
|
|
258
|
+
const syntax = registry.resolve('syntax.route');
|
|
259
|
+
if (syntax === null) {
|
|
260
|
+
throw new MethodError(Protocol.INTERNAL_ERROR, 'The kernel has no Router (syntax.route@1)');
|
|
261
|
+
}
|
|
262
|
+
return operation(syntax);
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
async kinds(params, session) {
|
|
266
|
+
const instance = this.registry.forClient(requireString(params, 'instanceId'), session.connectionId);
|
|
267
|
+
return { kinds: toJson(await this.inHostSession(instance.kernel, session, (syntax) => syntax.kinds())) };
|
|
268
|
+
}
|
|
269
|
+
async routeText(params, session, signal) {
|
|
270
|
+
const instance = this.registry.forClient(requireString(params, 'instanceId'), session.connectionId);
|
|
271
|
+
const text = requireString(params, 'text');
|
|
272
|
+
const stopOnFailure = optionalBoolean(params, 'stopOnFailure');
|
|
273
|
+
const dryRun = optionalBoolean(params, 'dryRun');
|
|
274
|
+
const maxOperations = params.maxOperations;
|
|
275
|
+
if (maxOperations !== undefined && (typeof maxOperations !== 'number' || !Number.isInteger(maxOperations) || maxOperations < 1)) {
|
|
276
|
+
throw new MethodError(Protocol.INVALID_PARAMS, 'maxOperations must be a positive integer', { field: 'maxOperations' });
|
|
277
|
+
}
|
|
278
|
+
const result = await this.inHostSession(instance.kernel, session, (syntax) => syntax.route(text, {
|
|
279
|
+
...(signal === undefined ? {} : { signal }),
|
|
280
|
+
...(stopOnFailure === undefined ? {} : { stopOnFailure }),
|
|
281
|
+
...(dryRun === undefined ? {} : { dryRun }),
|
|
282
|
+
...(maxOperations === undefined ? {} : { maxOperations }),
|
|
283
|
+
}));
|
|
284
|
+
return toJson(result);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
exports.RequestDispatcher = RequestDispatcher;
|
|
288
|
+
function success(id, result) {
|
|
289
|
+
return { jsonrpc: '2.0', id, result };
|
|
290
|
+
}
|
|
291
|
+
//# sourceMappingURL=dispatch.js.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import * as Protocol from '@brud/protocol';
|
|
3
|
+
/**
|
|
4
|
+
* Hard ceiling for one raw newline-delimited frame, measured on the bytes that
|
|
5
|
+
* arrive from the socket before any JSON parsing happens.
|
|
6
|
+
*
|
|
7
|
+
* 8 MiB is deliberately smaller than the kernel mutation governor so a large
|
|
8
|
+
* payload is rejected at the transport boundary instead of being materialized
|
|
9
|
+
* as a JavaScript object first.
|
|
10
|
+
*/
|
|
11
|
+
export declare const MAX_FRAME_BYTES: number;
|
|
12
|
+
export declare const FRAME_DELIMITER_BYTE = 10;
|
|
13
|
+
export type FrameErrorCode = 'FRAME_OVERSIZE' | 'FRAME_INVALID_JSON';
|
|
14
|
+
export declare class FrameError extends Error {
|
|
15
|
+
readonly code: FrameErrorCode;
|
|
16
|
+
readonly rpcCode: Protocol.RpcErrorCode;
|
|
17
|
+
constructor(code: FrameErrorCode, message: string);
|
|
18
|
+
}
|
|
19
|
+
/** One decoded frame, or the parse failure that belongs to it. */
|
|
20
|
+
export type FrameResult = {
|
|
21
|
+
readonly ok: true;
|
|
22
|
+
readonly message: unknown;
|
|
23
|
+
} | {
|
|
24
|
+
readonly ok: false;
|
|
25
|
+
readonly error: FrameError;
|
|
26
|
+
readonly frameId: Protocol.JsonRpcId;
|
|
27
|
+
};
|
|
28
|
+
export declare class FrameDecoder {
|
|
29
|
+
private buffer;
|
|
30
|
+
/**
|
|
31
|
+
* Push surface: decodes every complete frame and throws the first
|
|
32
|
+
* frame error after the chunk has been consumed.
|
|
33
|
+
*
|
|
34
|
+
* The daemon server uses {@link pushFrames} so one malformed frame cannot
|
|
35
|
+
* discard valid peers. This method remains for client-side consumers and
|
|
36
|
+
* frame tests that treat a bad frame as fatal.
|
|
37
|
+
*/
|
|
38
|
+
push(chunk: Buffer): unknown[];
|
|
39
|
+
/**
|
|
40
|
+
* Decodes every complete NDJSON frame in `chunk`.
|
|
41
|
+
*
|
|
42
|
+
* Only a complete frame (one terminated by `\n`) is ever handed to
|
|
43
|
+
* `JSON.parse`. A malformed complete frame becomes a per-frame failure that
|
|
44
|
+
* names the frame id when the raw bytes expose one; the decoder then keeps
|
|
45
|
+
* scanning the same chunk so valid frames that follow are still delivered.
|
|
46
|
+
*
|
|
47
|
+
* An oversize frame is a frame-length violation: it throws
|
|
48
|
+
* {@link FrameError} `FRAME_OVERSIZE` after clearing the buffer, which lets
|
|
49
|
+
* the connection reject the payload and close.
|
|
50
|
+
*/
|
|
51
|
+
pushFrames(chunk: Buffer): FrameResult[];
|
|
52
|
+
reset(): void;
|
|
53
|
+
get pendingBytes(): number;
|
|
54
|
+
private decodeFrame;
|
|
55
|
+
}
|
|
56
|
+
export declare function encodeFrame(message: unknown): Buffer;
|
|
57
|
+
export declare class NdjsonFramingStream {
|
|
58
|
+
private readonly decoder;
|
|
59
|
+
push(chunk: Buffer): unknown[];
|
|
60
|
+
pushFrames(chunk: Buffer): FrameResult[];
|
|
61
|
+
encode(message: unknown): Buffer;
|
|
62
|
+
reset(): void;
|
|
63
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.NdjsonFramingStream = exports.FrameDecoder = exports.FrameError = exports.FRAME_DELIMITER_BYTE = exports.MAX_FRAME_BYTES = void 0;
|
|
37
|
+
exports.encodeFrame = encodeFrame;
|
|
38
|
+
const node_buffer_1 = require("node:buffer");
|
|
39
|
+
const Protocol = __importStar(require("@brud/protocol"));
|
|
40
|
+
/**
|
|
41
|
+
* Hard ceiling for one raw newline-delimited frame, measured on the bytes that
|
|
42
|
+
* arrive from the socket before any JSON parsing happens.
|
|
43
|
+
*
|
|
44
|
+
* 8 MiB is deliberately smaller than the kernel mutation governor so a large
|
|
45
|
+
* payload is rejected at the transport boundary instead of being materialized
|
|
46
|
+
* as a JavaScript object first.
|
|
47
|
+
*/
|
|
48
|
+
exports.MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
49
|
+
exports.FRAME_DELIMITER_BYTE = 0x0a;
|
|
50
|
+
const RPC_CODE_BY_FRAME_ERROR = {
|
|
51
|
+
FRAME_OVERSIZE: Protocol.INVALID_REQUEST,
|
|
52
|
+
FRAME_INVALID_JSON: Protocol.PARSE_ERROR,
|
|
53
|
+
};
|
|
54
|
+
const OVERSIZE_MESSAGE = `Payload too large: frame exceeds the ${exports.MAX_FRAME_BYTES} byte limit`;
|
|
55
|
+
class FrameError extends Error {
|
|
56
|
+
code;
|
|
57
|
+
rpcCode;
|
|
58
|
+
constructor(code, message) {
|
|
59
|
+
super(message);
|
|
60
|
+
this.name = 'FrameError';
|
|
61
|
+
this.code = code;
|
|
62
|
+
this.rpcCode = RPC_CODE_BY_FRAME_ERROR[code];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exports.FrameError = FrameError;
|
|
66
|
+
function extractFrameId(frame) {
|
|
67
|
+
const match = /"id"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|null)/u.exec(frame);
|
|
68
|
+
if (match === null) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
const raw = match[1];
|
|
72
|
+
if (raw === 'null') {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const value = JSON.parse(raw);
|
|
77
|
+
return typeof value === 'string' || typeof value === 'number' ? value : null;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
class FrameDecoder {
|
|
84
|
+
buffer = node_buffer_1.Buffer.alloc(0);
|
|
85
|
+
/**
|
|
86
|
+
* Push surface: decodes every complete frame and throws the first
|
|
87
|
+
* frame error after the chunk has been consumed.
|
|
88
|
+
*
|
|
89
|
+
* The daemon server uses {@link pushFrames} so one malformed frame cannot
|
|
90
|
+
* discard valid peers. This method remains for client-side consumers and
|
|
91
|
+
* frame tests that treat a bad frame as fatal.
|
|
92
|
+
*/
|
|
93
|
+
push(chunk) {
|
|
94
|
+
const results = this.pushFrames(chunk);
|
|
95
|
+
const messages = [];
|
|
96
|
+
for (const result of results) {
|
|
97
|
+
if (!result.ok) {
|
|
98
|
+
throw result.error;
|
|
99
|
+
}
|
|
100
|
+
messages.push(result.message);
|
|
101
|
+
}
|
|
102
|
+
return messages;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Decodes every complete NDJSON frame in `chunk`.
|
|
106
|
+
*
|
|
107
|
+
* Only a complete frame (one terminated by `\n`) is ever handed to
|
|
108
|
+
* `JSON.parse`. A malformed complete frame becomes a per-frame failure that
|
|
109
|
+
* names the frame id when the raw bytes expose one; the decoder then keeps
|
|
110
|
+
* scanning the same chunk so valid frames that follow are still delivered.
|
|
111
|
+
*
|
|
112
|
+
* An oversize frame is a frame-length violation: it throws
|
|
113
|
+
* {@link FrameError} `FRAME_OVERSIZE` after clearing the buffer, which lets
|
|
114
|
+
* the connection reject the payload and close.
|
|
115
|
+
*/
|
|
116
|
+
pushFrames(chunk) {
|
|
117
|
+
if (chunk.length === 0) {
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
const combined = this.buffer.length === 0 ? chunk : node_buffer_1.Buffer.concat([this.buffer, chunk]);
|
|
121
|
+
const results = [];
|
|
122
|
+
let offset = 0;
|
|
123
|
+
try {
|
|
124
|
+
for (;;) {
|
|
125
|
+
const newlineIndex = combined.indexOf(exports.FRAME_DELIMITER_BYTE, offset);
|
|
126
|
+
if (newlineIndex === -1) {
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
const frameLength = newlineIndex - offset;
|
|
130
|
+
if (frameLength > exports.MAX_FRAME_BYTES) {
|
|
131
|
+
throw new FrameError('FRAME_OVERSIZE', OVERSIZE_MESSAGE);
|
|
132
|
+
}
|
|
133
|
+
const frame = combined.subarray(offset, newlineIndex);
|
|
134
|
+
offset = newlineIndex + 1;
|
|
135
|
+
if (frame.length === 0) {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
results.push(this.decodeFrame(frame));
|
|
139
|
+
}
|
|
140
|
+
const remaining = combined.subarray(offset);
|
|
141
|
+
this.buffer = remaining.length === 0 ? node_buffer_1.Buffer.alloc(0) : node_buffer_1.Buffer.from(remaining);
|
|
142
|
+
if (this.buffer.length > exports.MAX_FRAME_BYTES) {
|
|
143
|
+
throw new FrameError('FRAME_OVERSIZE', OVERSIZE_MESSAGE);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
this.buffer = node_buffer_1.Buffer.alloc(0);
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
return results;
|
|
151
|
+
}
|
|
152
|
+
reset() {
|
|
153
|
+
this.buffer = node_buffer_1.Buffer.alloc(0);
|
|
154
|
+
}
|
|
155
|
+
get pendingBytes() {
|
|
156
|
+
return this.buffer.length;
|
|
157
|
+
}
|
|
158
|
+
decodeFrame(frame) {
|
|
159
|
+
const text = frame.toString('utf8');
|
|
160
|
+
try {
|
|
161
|
+
return { ok: true, message: JSON.parse(text) };
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return {
|
|
165
|
+
ok: false,
|
|
166
|
+
error: new FrameError('FRAME_INVALID_JSON', 'Frame is not valid JSON'),
|
|
167
|
+
frameId: extractFrameId(text),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
exports.FrameDecoder = FrameDecoder;
|
|
173
|
+
function encodeFrame(message) {
|
|
174
|
+
const frame = node_buffer_1.Buffer.from(`${JSON.stringify(message)}\n`, 'utf8');
|
|
175
|
+
if (frame.length - 1 > exports.MAX_FRAME_BYTES) {
|
|
176
|
+
throw new FrameError('FRAME_OVERSIZE', OVERSIZE_MESSAGE);
|
|
177
|
+
}
|
|
178
|
+
return frame;
|
|
179
|
+
}
|
|
180
|
+
class NdjsonFramingStream {
|
|
181
|
+
decoder = new FrameDecoder();
|
|
182
|
+
push(chunk) {
|
|
183
|
+
return this.decoder.push(chunk);
|
|
184
|
+
}
|
|
185
|
+
pushFrames(chunk) {
|
|
186
|
+
return this.decoder.pushFrames(chunk);
|
|
187
|
+
}
|
|
188
|
+
encode(message) {
|
|
189
|
+
return encodeFrame(message);
|
|
190
|
+
}
|
|
191
|
+
reset() {
|
|
192
|
+
this.decoder.reset();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
exports.NdjsonFramingStream = NdjsonFramingStream;
|
|
196
|
+
//# sourceMappingURL=framing.js.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { DaemonConnectParams, RpcErrorCode, RpcErrorDetails } from '@brud/protocol';
|
|
2
|
+
export interface HandshakeFailure {
|
|
3
|
+
readonly ok: false;
|
|
4
|
+
readonly code: RpcErrorCode;
|
|
5
|
+
readonly message: string;
|
|
6
|
+
readonly data?: RpcErrorDetails;
|
|
7
|
+
}
|
|
8
|
+
export interface ConnectSuccess {
|
|
9
|
+
readonly ok: true;
|
|
10
|
+
readonly params: DaemonConnectParams;
|
|
11
|
+
}
|
|
12
|
+
export type ConnectOutcome = ConnectSuccess | HandshakeFailure;
|
|
13
|
+
/**
|
|
14
|
+
* Validates the post-handshake `daemon.connect` payload.
|
|
15
|
+
*
|
|
16
|
+
* Identity, principal, and scope were authenticated by the Noise session
|
|
17
|
+
* before this method ran. This validator only checks the protocol version and
|
|
18
|
+
* the optional presentation fields; it never accepts a token, tier, or scope.
|
|
19
|
+
*/
|
|
20
|
+
export declare class ConnectValidator {
|
|
21
|
+
validate(value: unknown): ConnectOutcome;
|
|
22
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.ConnectValidator = void 0;
|
|
37
|
+
const Protocol = __importStar(require("@brud/protocol"));
|
|
38
|
+
function isRecord(value) {
|
|
39
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
40
|
+
}
|
|
41
|
+
function failure(code, message, data) {
|
|
42
|
+
return data === undefined ? { ok: false, code, message } : { ok: false, code, message, data };
|
|
43
|
+
}
|
|
44
|
+
function parseClientIdentity(value) {
|
|
45
|
+
if (!isRecord(value)) {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
const name = value.name;
|
|
49
|
+
const version = value.version;
|
|
50
|
+
if (typeof name !== 'string' || typeof version !== 'string') {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
return { name, version };
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Validates the post-handshake `daemon.connect` payload.
|
|
57
|
+
*
|
|
58
|
+
* Identity, principal, and scope were authenticated by the Noise session
|
|
59
|
+
* before this method ran. This validator only checks the protocol version and
|
|
60
|
+
* the optional presentation fields; it never accepts a token, tier, or scope.
|
|
61
|
+
*/
|
|
62
|
+
class ConnectValidator {
|
|
63
|
+
validate(value) {
|
|
64
|
+
if (!isRecord(value)) {
|
|
65
|
+
return failure(Protocol.INVALID_PARAMS, 'daemon.connect requires a params object');
|
|
66
|
+
}
|
|
67
|
+
const protocolVersion = value.protocolVersion;
|
|
68
|
+
if (typeof protocolVersion !== 'string') {
|
|
69
|
+
return failure(Protocol.INVALID_PARAMS, 'protocolVersion must be a string');
|
|
70
|
+
}
|
|
71
|
+
if (protocolVersion !== Protocol.DAEMON_PROTOCOL_VERSION) {
|
|
72
|
+
return failure(Protocol.PROTOCOL_VERSION_MISMATCH, 'Unsupported daemon protocol version', {
|
|
73
|
+
expected: Protocol.DAEMON_PROTOCOL_VERSION,
|
|
74
|
+
actual: protocolVersion,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const clientInfo = parseClientIdentity(value.clientInfo);
|
|
78
|
+
const client = parseClientIdentity(value.client);
|
|
79
|
+
const capabilities = Array.isArray(value.capabilities)
|
|
80
|
+
? value.capabilities.filter((entry) => typeof entry === 'string')
|
|
81
|
+
: undefined;
|
|
82
|
+
return {
|
|
83
|
+
ok: true,
|
|
84
|
+
params: {
|
|
85
|
+
protocolVersion,
|
|
86
|
+
...(client === undefined ? {} : { client }),
|
|
87
|
+
...(clientInfo === undefined ? {} : { clientInfo }),
|
|
88
|
+
...(capabilities === undefined ? {} : { capabilities }),
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
exports.ConnectValidator = ConnectValidator;
|
|
94
|
+
//# sourceMappingURL=handshake.js.map
|