@sirosfoundation/wmp-js 0.2.0 → 0.5.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/dist/jsonrpc.d.ts CHANGED
@@ -33,10 +33,16 @@ export declare function createNotification(method: string, params: unknown): Req
33
33
  export declare function createResponse(id: string | number | null, result: unknown): Response;
34
34
  /** Create a JSON-RPC 2.0 error response. */
35
35
  export declare function createErrorResponse(id: string | number | null, error: RPCError): Response;
36
+ export interface DecodeOptions {
37
+ /** Maximum payload length in characters. Default: 4 MB. */
38
+ maxSize?: number;
39
+ /** Maximum object/array nesting depth. Default: 32. */
40
+ maxDepth?: number;
41
+ }
36
42
  /** Parse a raw JSON string into a Message. Throws on invalid JSON-RPC. */
37
- export declare function decodeMessage(data: string): Message;
43
+ export declare function decodeMessage(data: string, opts?: DecodeOptions): Message;
38
44
  /** Parse raw JSON that may be a batch (array) or single message. */
39
- export declare function decodeBatch(data: string): Message[];
45
+ export declare function decodeBatch(data: string, opts?: DecodeOptions): Message[];
40
46
  /** WMP-specific RPC error class. */
41
47
  export declare class WMPError extends Error {
42
48
  readonly code: number;
@@ -44,5 +50,5 @@ export declare class WMPError extends Error {
44
50
  constructor(code: number, message: string, data?: unknown);
45
51
  toRPCError(): RPCError;
46
52
  }
47
- /** Reset the request ID counter (for testing). */
53
+ /** @deprecated Request IDs are now random; this function is a no-op for compatibility. */
48
54
  export declare function resetRequestIdCounter(): void;
package/dist/jsonrpc.js CHANGED
@@ -13,10 +13,19 @@ export function isResponse(msg) {
13
13
  export function isNotification(msg) {
14
14
  return msg.id === undefined || msg.id === null;
15
15
  }
16
- let nextId = 1;
16
+ /** Generate a cryptographically random request ID. */
17
+ function generateRequestId() {
18
+ const bytes = new Uint8Array(16);
19
+ globalThis.crypto.getRandomValues(bytes);
20
+ const b64 = btoa(String.fromCharCode(...bytes))
21
+ .replace(/\+/g, "-")
22
+ .replace(/\//g, "_")
23
+ .replace(/=+$/, "");
24
+ return `req-${b64}`;
25
+ }
17
26
  /** Create a JSON-RPC 2.0 request. */
18
27
  export function createRequest(method, params) {
19
- return { jsonrpc: "2.0", id: `req-${nextId++}`, method, params };
28
+ return { jsonrpc: "2.0", id: generateRequestId(), method, params };
20
29
  }
21
30
  /** Create a JSON-RPC 2.0 notification (no id, no response expected). */
22
31
  export function createNotification(method, params) {
@@ -30,17 +39,58 @@ export function createResponse(id, result) {
30
39
  export function createErrorResponse(id, error) {
31
40
  return { jsonrpc: "2.0", id, error };
32
41
  }
42
+ const DEFAULT_MAX_SIZE = 4 * 1024 * 1024;
43
+ const DEFAULT_MAX_DEPTH = 32;
44
+ function parseJSONRPC(data, maxSize, maxDepth) {
45
+ if (data.length > maxSize) {
46
+ throw new Error("JSON-RPC message exceeds maximum size");
47
+ }
48
+ try {
49
+ return JSON.parse(data, (_key, value) => {
50
+ if (value !== null && typeof value === "object") {
51
+ checkDepth(value, 1, maxDepth);
52
+ }
53
+ return value;
54
+ });
55
+ }
56
+ catch (err) {
57
+ if (err instanceof Error && err.message.includes("depth")) {
58
+ throw err;
59
+ }
60
+ throw new Error("Invalid JSON-RPC payload");
61
+ }
62
+ }
63
+ function checkDepth(value, depth, maxDepth) {
64
+ if (depth > maxDepth) {
65
+ throw new Error("JSON-RPC message exceeds maximum nesting depth");
66
+ }
67
+ if (Array.isArray(value)) {
68
+ for (const item of value)
69
+ checkDepth(item, depth + 1, maxDepth);
70
+ }
71
+ else if (value !== null && typeof value === "object") {
72
+ for (const key in value) {
73
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
74
+ checkDepth(value[key], depth + 1, maxDepth);
75
+ }
76
+ }
77
+ }
78
+ }
33
79
  /** Parse a raw JSON string into a Message. Throws on invalid JSON-RPC. */
34
- export function decodeMessage(data) {
35
- const obj = JSON.parse(data);
36
- if (obj.jsonrpc !== "2.0") {
80
+ export function decodeMessage(data, opts) {
81
+ const maxSize = opts?.maxSize ?? DEFAULT_MAX_SIZE;
82
+ const maxDepth = opts?.maxDepth ?? DEFAULT_MAX_DEPTH;
83
+ const obj = parseJSONRPC(data, maxSize, maxDepth);
84
+ if (obj === null || typeof obj !== "object" || obj.jsonrpc !== "2.0") {
37
85
  throw new Error("Invalid JSON-RPC version");
38
86
  }
39
87
  return obj;
40
88
  }
41
89
  /** Parse raw JSON that may be a batch (array) or single message. */
42
- export function decodeBatch(data) {
43
- const obj = JSON.parse(data);
90
+ export function decodeBatch(data, opts) {
91
+ const maxSize = opts?.maxSize ?? DEFAULT_MAX_SIZE;
92
+ const maxDepth = opts?.maxDepth ?? DEFAULT_MAX_DEPTH;
93
+ const obj = parseJSONRPC(data, maxSize, maxDepth);
44
94
  if (Array.isArray(obj)) {
45
95
  return obj.map((item) => {
46
96
  if (item.jsonrpc !== "2.0") {
@@ -49,7 +99,7 @@ export function decodeBatch(data) {
49
99
  return item;
50
100
  });
51
101
  }
52
- if (obj.jsonrpc !== "2.0") {
102
+ if (obj === null || typeof obj !== "object" || obj.jsonrpc !== "2.0") {
53
103
  throw new Error("Invalid JSON-RPC version");
54
104
  }
55
105
  return [obj];
@@ -68,7 +118,7 @@ export class WMPError extends Error {
68
118
  return { code: this.code, message: this.message, data: this.data };
69
119
  }
70
120
  }
71
- /** Reset the request ID counter (for testing). */
121
+ /** @deprecated Request IDs are now random; this function is a no-op for compatibility. */
72
122
  export function resetRequestIdCounter() {
73
- nextId = 1;
123
+ // no-op: IDs are cryptographically random.
74
124
  }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * TsMlsProvider — real MLS cryptographic provider backed by ts-mls (RFC 9420).
3
+ *
4
+ * Implements the MLSProvider interface with actual key generation, group
5
+ * management, and message encryption/decryption. Supports cipher suites:
6
+ * - 0x0001: MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 (MUST)
7
+ * - 0x0002: MLS_128_DHKEMP256_AES128GCM_SHA256_P256 (SHOULD)
8
+ */
9
+ import type { MLSProvider, KeyPackage } from "./mls.js";
10
+ export interface TsMlsProviderOptions {
11
+ /** Identity string for this participant (e.g., "wmp-inspector"). */
12
+ identity: string;
13
+ /** Default cipher suite. Default: 0x0001 (X25519). */
14
+ defaultCipherSuite?: number;
15
+ }
16
+ /**
17
+ * Real MLS provider using ts-mls.
18
+ *
19
+ * Each instance represents one MLS participant. It can generate key packages,
20
+ * create/join groups, encrypt/decrypt messages, and manage group membership.
21
+ */
22
+ export declare class TsMlsProvider implements MLSProvider {
23
+ private identity;
24
+ private defaultCipherSuite;
25
+ private implCache;
26
+ private groups;
27
+ private keyPackages;
28
+ constructor(opts: TsMlsProviderOptions);
29
+ private getImpl;
30
+ private makeCredential;
31
+ generateKeyPackage(cipherSuite: number): Promise<KeyPackage>;
32
+ createGroup(cipherSuite: number, _participants: string[]): Promise<{
33
+ groupInfo: string;
34
+ welcomes: Record<string, string>;
35
+ }>;
36
+ processWelcome(welcome: string): Promise<{
37
+ groupId: string;
38
+ epoch: number;
39
+ }>;
40
+ addMember(groupId: string, keyPackage: string): Promise<{
41
+ commit: string;
42
+ welcome: string;
43
+ }>;
44
+ removeMember(groupId: string, _participant: string): Promise<{
45
+ commit: string;
46
+ }>;
47
+ processCommit(groupId: string, commit: string): Promise<{
48
+ epoch: number;
49
+ }>;
50
+ selfUpdate(groupId: string): Promise<{
51
+ commit: string;
52
+ }>;
53
+ encrypt(groupId: string, plaintext: Uint8Array): Promise<{
54
+ ciphertext: string;
55
+ epoch: number;
56
+ }>;
57
+ decrypt(groupId: string, ciphertext: string): Promise<{
58
+ plaintext: Uint8Array;
59
+ epoch: number;
60
+ }>;
61
+ private getGroup;
62
+ private getLatestKeyPackage;
63
+ get groupCount(): number;
64
+ get keyPackageCount(): number;
65
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * TsMlsProvider — real MLS cryptographic provider backed by ts-mls (RFC 9420).
3
+ *
4
+ * Implements the MLSProvider interface with actual key generation, group
5
+ * management, and message encryption/decryption. Supports cipher suites:
6
+ * - 0x0001: MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 (MUST)
7
+ * - 0x0002: MLS_128_DHKEMP256_AES128GCM_SHA256_P256 (SHOULD)
8
+ */
9
+ import { getCiphersuiteImpl, getCiphersuiteFromName, generateKeyPackage as tsGenerateKeyPackage, createGroup as tsCreateGroup, joinGroup as tsJoinGroup, createCommit as tsCreateCommit, createApplicationMessage, processMessage as tsProcessMessage, encodeMlsMessage, decodeMlsMessage, defaultCapabilities, defaultLifetime, emptyPskIndex, acceptAll, zeroOutUint8Array, } from "ts-mls";
10
+ import { CipherSuiteX25519AES128GCM, CipherSuiteP256AES128GCM, } from "./mls.js";
11
+ // ---------------------------------------------------------------------------
12
+ // Cipher suite mapping: WMP numeric ID → ts-mls CiphersuiteName
13
+ // ---------------------------------------------------------------------------
14
+ const CIPHER_SUITE_NAMES = {
15
+ [CipherSuiteX25519AES128GCM]: "MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519",
16
+ [CipherSuiteP256AES128GCM]: "MLS_128_DHKEMP256_AES128GCM_SHA256_P256",
17
+ };
18
+ // ---------------------------------------------------------------------------
19
+ // Base64url helpers
20
+ // ---------------------------------------------------------------------------
21
+ function toBase64Url(data) {
22
+ const str = btoa(String.fromCharCode(...data));
23
+ return str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ function fromBase64Url(b64) {
26
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
27
+ const pad = padded.length % 4;
28
+ const final = pad ? padded + "=".repeat(4 - pad) : padded;
29
+ const str = atob(final);
30
+ const bytes = new Uint8Array(str.length);
31
+ for (let i = 0; i < str.length; i++)
32
+ bytes[i] = str.charCodeAt(i);
33
+ return bytes;
34
+ }
35
+ /**
36
+ * Real MLS provider using ts-mls.
37
+ *
38
+ * Each instance represents one MLS participant. It can generate key packages,
39
+ * create/join groups, encrypt/decrypt messages, and manage group membership.
40
+ */
41
+ export class TsMlsProvider {
42
+ identity;
43
+ defaultCipherSuite;
44
+ implCache = new Map();
45
+ groups = new Map();
46
+ keyPackages = new Map();
47
+ constructor(opts) {
48
+ this.identity = opts.identity;
49
+ this.defaultCipherSuite = opts.defaultCipherSuite ?? CipherSuiteX25519AES128GCM;
50
+ }
51
+ async getImpl(cipherSuite) {
52
+ let impl = this.implCache.get(cipherSuite);
53
+ if (!impl) {
54
+ const name = CIPHER_SUITE_NAMES[cipherSuite];
55
+ if (!name) {
56
+ throw new Error(`Unsupported cipher suite: 0x${cipherSuite.toString(16)}`);
57
+ }
58
+ const cs = getCiphersuiteFromName(name);
59
+ impl = await getCiphersuiteImpl(cs);
60
+ this.implCache.set(cipherSuite, impl);
61
+ }
62
+ return impl;
63
+ }
64
+ makeCredential() {
65
+ return {
66
+ credentialType: "basic",
67
+ identity: new TextEncoder().encode(this.identity),
68
+ };
69
+ }
70
+ async generateKeyPackage(cipherSuite) {
71
+ const impl = await this.getImpl(cipherSuite);
72
+ const kp = await tsGenerateKeyPackage(this.makeCredential(), defaultCapabilities(), defaultLifetime, [], impl);
73
+ const encoded = encodeMlsMessage({
74
+ version: "mls10",
75
+ wireformat: "mls_key_package",
76
+ keyPackage: kp.publicPackage,
77
+ });
78
+ const id = `kp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
79
+ this.keyPackages.set(id, {
80
+ pub: kp.publicPackage,
81
+ priv: kp.privatePackage,
82
+ cipherSuite,
83
+ });
84
+ return {
85
+ id,
86
+ cipher_suite: cipherSuite,
87
+ key_package: toBase64Url(encoded),
88
+ expires: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
89
+ };
90
+ }
91
+ async createGroup(cipherSuite, _participants) {
92
+ const impl = await this.getImpl(cipherSuite);
93
+ const myKp = await tsGenerateKeyPackage(this.makeCredential(), defaultCapabilities(), defaultLifetime, [], impl);
94
+ const groupId = new TextEncoder().encode(`wmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
95
+ const state = await tsCreateGroup(groupId, myKp.publicPackage, myKp.privatePackage, [], impl);
96
+ const groupIdStr = toBase64Url(groupId);
97
+ this.groups.set(groupIdStr, { state, impl, groupIdStr });
98
+ return { groupInfo: groupIdStr, welcomes: {} };
99
+ }
100
+ async processWelcome(welcome) {
101
+ const kpEntry = this.getLatestKeyPackage();
102
+ if (!kpEntry)
103
+ throw new Error("No key package available for processing welcome");
104
+ const impl = await this.getImpl(kpEntry.cipherSuite);
105
+ const welcomeBytes = fromBase64Url(welcome);
106
+ const decoded = decodeMlsMessage(welcomeBytes, 0);
107
+ if (!decoded)
108
+ throw new Error("Invalid welcome message");
109
+ const [msg] = decoded;
110
+ if (msg.wireformat !== "mls_welcome")
111
+ throw new Error("Invalid welcome message");
112
+ const state = await tsJoinGroup(msg.welcome, kpEntry.pub, kpEntry.priv, emptyPskIndex, impl);
113
+ const groupIdStr = toBase64Url(state.groupContext.groupId);
114
+ const epoch = Number(state.groupContext.epoch);
115
+ this.groups.set(groupIdStr, { state, impl, groupIdStr });
116
+ return { groupId: groupIdStr, epoch };
117
+ }
118
+ async addMember(groupId, keyPackage) {
119
+ const group = this.getGroup(groupId);
120
+ const kpBytes = fromBase64Url(keyPackage);
121
+ const decoded = decodeMlsMessage(kpBytes, 0);
122
+ if (!decoded)
123
+ throw new Error("Invalid key package message");
124
+ const [msg] = decoded;
125
+ if (msg.wireformat !== "mls_key_package")
126
+ throw new Error("Invalid key package message");
127
+ const addProposal = {
128
+ proposalType: "add",
129
+ add: { keyPackage: msg.keyPackage },
130
+ };
131
+ const context = {
132
+ state: group.state,
133
+ cipherSuite: group.impl,
134
+ pskIndex: emptyPskIndex,
135
+ };
136
+ const result = await tsCreateCommit(context, {
137
+ extraProposals: [addProposal],
138
+ ratchetTreeExtension: true,
139
+ });
140
+ group.state = result.newState;
141
+ result.consumed.forEach(zeroOutUint8Array);
142
+ const commitBytes = encodeMlsMessage(result.commit);
143
+ const welcomeBytes = result.welcome
144
+ ? encodeMlsMessage({ version: "mls10", wireformat: "mls_welcome", welcome: result.welcome })
145
+ : new Uint8Array();
146
+ return { commit: toBase64Url(commitBytes), welcome: toBase64Url(welcomeBytes) };
147
+ }
148
+ async removeMember(groupId, _participant) {
149
+ const group = this.getGroup(groupId);
150
+ const context = { state: group.state, cipherSuite: group.impl, pskIndex: emptyPskIndex };
151
+ const result = await tsCreateCommit(context);
152
+ group.state = result.newState;
153
+ result.consumed.forEach(zeroOutUint8Array);
154
+ return { commit: toBase64Url(encodeMlsMessage(result.commit)) };
155
+ }
156
+ async processCommit(groupId, commit) {
157
+ const group = this.getGroup(groupId);
158
+ const decoded = decodeMlsMessage(fromBase64Url(commit), 0);
159
+ if (!decoded)
160
+ throw new Error("Invalid commit message");
161
+ const [msg] = decoded;
162
+ const result = await tsProcessMessage(msg, group.state, emptyPskIndex, acceptAll, group.impl);
163
+ group.state = result.newState;
164
+ result.consumed.forEach(zeroOutUint8Array);
165
+ return { epoch: Number(group.state.groupContext.epoch) };
166
+ }
167
+ async selfUpdate(groupId) {
168
+ return this.removeMember(groupId, ""); // empty commit = self-update
169
+ }
170
+ async encrypt(groupId, plaintext) {
171
+ const group = this.getGroup(groupId);
172
+ const result = await createApplicationMessage(group.state, plaintext, group.impl);
173
+ group.state = result.newState;
174
+ result.consumed.forEach(zeroOutUint8Array);
175
+ const encoded = encodeMlsMessage({
176
+ version: "mls10",
177
+ wireformat: "mls_private_message",
178
+ privateMessage: result.privateMessage,
179
+ });
180
+ return {
181
+ ciphertext: toBase64Url(encoded),
182
+ epoch: Number(group.state.groupContext.epoch),
183
+ };
184
+ }
185
+ async decrypt(groupId, ciphertext) {
186
+ const group = this.getGroup(groupId);
187
+ const decoded = decodeMlsMessage(fromBase64Url(ciphertext), 0);
188
+ if (!decoded)
189
+ throw new Error("Invalid ciphertext message");
190
+ const [msg] = decoded;
191
+ const result = await tsProcessMessage(msg, group.state, emptyPskIndex, acceptAll, group.impl);
192
+ group.state = result.newState;
193
+ result.consumed.forEach(zeroOutUint8Array);
194
+ if (result.kind !== "applicationMessage") {
195
+ throw new Error(`Expected application message, got ${result.kind}`);
196
+ }
197
+ return {
198
+ plaintext: result.message,
199
+ epoch: Number(group.state.groupContext.epoch),
200
+ };
201
+ }
202
+ getGroup(groupId) {
203
+ const group = this.groups.get(groupId);
204
+ if (!group)
205
+ throw new Error(`Group ${groupId} not found`);
206
+ return group;
207
+ }
208
+ getLatestKeyPackage() {
209
+ let latest;
210
+ for (const [, entry] of this.keyPackages)
211
+ latest = entry;
212
+ return latest;
213
+ }
214
+ get groupCount() { return this.groups.size; }
215
+ get keyPackageCount() { return this.keyPackages.size; }
216
+ }
package/dist/mls.d.ts CHANGED
@@ -176,12 +176,20 @@ export declare class NoopMLSHandler implements MLSHandler {
176
176
  groupUpdate(_params: GroupUpdateParams): Promise<void>;
177
177
  messageFetch(params: MessageFetchParams): Promise<MessageFetchResult>;
178
178
  }
179
+ export interface NoopMLSProviderOptions {
180
+ /** Explicit opt-in required to use the plaintext TLS-only provider. */
181
+ explicitlyInsecure: true;
182
+ }
179
183
  /**
180
184
  * NoopMLSProvider implements MLSProvider for TLS-only sessions.
181
185
  * Messages pass through unencrypted, relying on transport-level TLS.
186
+ *
187
+ * IMPORTANT: This provider does NOT perform encryption. It requires
188
+ * explicitlyInsecure: true to reduce the risk of accidental misuse.
182
189
  */
183
190
  export declare class NoopMLSProvider implements MLSProvider {
184
191
  private groups;
192
+ constructor(opts: NoopMLSProviderOptions);
185
193
  generateKeyPackage(cipherSuite: number): Promise<KeyPackage>;
186
194
  createGroup(_cs: number, participants: string[]): Promise<{
187
195
  groupInfo: string;
package/dist/mls.js CHANGED
@@ -123,9 +123,17 @@ export class NoopMLSHandler {
123
123
  /**
124
124
  * NoopMLSProvider implements MLSProvider for TLS-only sessions.
125
125
  * Messages pass through unencrypted, relying on transport-level TLS.
126
+ *
127
+ * IMPORTANT: This provider does NOT perform encryption. It requires
128
+ * explicitlyInsecure: true to reduce the risk of accidental misuse.
126
129
  */
127
130
  export class NoopMLSProvider {
128
131
  groups = new Map();
132
+ constructor(opts) {
133
+ if (!opts?.explicitlyInsecure) {
134
+ throw new Error("NoopMLSProvider performs no encryption; set explicitlyInsecure: true to opt in");
135
+ }
136
+ }
129
137
  async generateKeyPackage(cipherSuite) {
130
138
  return {
131
139
  id: "noop-kp-1",
package/dist/native.d.ts CHANGED
@@ -24,6 +24,8 @@ export interface StdioTransportOptions {
24
24
  input?: Readable;
25
25
  /** Writable stream for outgoing messages. Default: process.stdout */
26
26
  output?: Writable;
27
+ /** Maximum line length in characters before the transport is closed. Default: 1 MB. */
28
+ maxLineLength?: number;
27
29
  }
28
30
  /**
29
31
  * StdioTransport — newline-delimited JSON over stdin/stdout.
@@ -36,10 +38,9 @@ export interface StdioTransportOptions {
36
38
  export declare class StdioTransport extends Emitter implements Transport {
37
39
  private input;
38
40
  private output;
39
- private buffer;
40
41
  private closed;
42
+ private lineBuffer;
41
43
  constructor(opts?: StdioTransportOptions);
42
- private onData;
43
44
  private onClose;
44
45
  send(msg: Message): Promise<void>;
45
46
  close(): void;
@@ -56,12 +57,15 @@ export declare class StdioTransport extends Emitter implements Transport {
56
57
  * const sock = connect("/tmp/wmp.sock");
57
58
  * const transport = new UnixSocketTransport(sock);
58
59
  */
60
+ export interface UnixSocketTransportOptions {
61
+ /** Maximum line length in characters before the transport is closed. Default: 1 MB. */
62
+ maxLineLength?: number;
63
+ }
59
64
  export declare class UnixSocketTransport extends Emitter implements Transport {
60
65
  private socket;
61
- private buffer;
62
66
  private closed;
63
- constructor(socket: Socket);
64
- private onData;
67
+ private lineBuffer;
68
+ constructor(socket: Socket, opts?: UnixSocketTransportOptions);
65
69
  private onClose;
66
70
  send(msg: Message): Promise<void>;
67
71
  close(): void;
package/dist/native.js CHANGED
@@ -26,6 +26,56 @@ class Emitter {
26
26
  this.listeners.get(event)?.forEach((fn) => fn(...args));
27
27
  }
28
28
  }
29
+ /** Accumulates incoming text, splits on newlines, and decodes JSON-RPC messages. */
30
+ class LineBuffer {
31
+ maxLineLength;
32
+ onMessage;
33
+ onError;
34
+ onClose;
35
+ buffer = "";
36
+ closed = false;
37
+ constructor(maxLineLength, onMessage, onError, onClose) {
38
+ this.maxLineLength = maxLineLength;
39
+ this.onMessage = onMessage;
40
+ this.onError = onError;
41
+ this.onClose = onClose;
42
+ }
43
+ append(chunk) {
44
+ if (this.closed)
45
+ return;
46
+ this.buffer += chunk;
47
+ if (this.buffer.length > this.maxLineLength) {
48
+ this.onError(new Error("Native transport line exceeds maximum length"));
49
+ this.close();
50
+ return;
51
+ }
52
+ const lines = this.buffer.split("\n");
53
+ // Last element is incomplete (may be empty string if chunk ended with \n)
54
+ this.buffer = lines.pop();
55
+ for (const line of lines) {
56
+ const trimmed = line.trim();
57
+ if (!trimmed)
58
+ continue;
59
+ try {
60
+ const msg = decodeMessage(trimmed);
61
+ this.onMessage(msg);
62
+ }
63
+ catch (err) {
64
+ this.onError(err instanceof Error ? err : new Error(String(err)));
65
+ }
66
+ }
67
+ }
68
+ close() {
69
+ if (this.closed)
70
+ return;
71
+ this.closed = true;
72
+ this.onClose();
73
+ }
74
+ }
75
+ // ---------------------------------------------------------------------------
76
+ // Stdio transport (NDJSON over stdin/stdout)
77
+ // ---------------------------------------------------------------------------
78
+ const DEFAULT_MAX_LINE_LENGTH = 1024 * 1024; // 1 MB
29
79
  /**
30
80
  * StdioTransport — newline-delimited JSON over stdin/stdout.
31
81
  *
@@ -37,38 +87,21 @@ class Emitter {
37
87
  export class StdioTransport extends Emitter {
38
88
  input;
39
89
  output;
40
- buffer = "";
41
90
  closed = false;
91
+ lineBuffer;
42
92
  constructor(opts) {
43
93
  super();
44
94
  this.input = opts?.input ?? process.stdin;
45
95
  this.output = opts?.output ?? process.stdout;
96
+ const maxLineLength = opts?.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH;
97
+ this.lineBuffer = new LineBuffer(maxLineLength, (msg) => this.emit("message", msg), (err) => this.emit("error", err), () => this.onClose());
46
98
  this.input.setEncoding("utf8");
47
- this.input.on("data", (chunk) => this.onData(chunk));
48
- this.input.on("end", () => this.onClose());
99
+ this.input.on("data", (chunk) => this.lineBuffer.append(chunk));
100
+ this.input.on("end", () => this.lineBuffer.close());
49
101
  this.input.on("error", (err) => this.emit("error", err));
50
102
  // Emit open on next tick (stream is already connected)
51
103
  queueMicrotask(() => this.emit("open"));
52
104
  }
53
- onData(chunk) {
54
- this.buffer += chunk;
55
- // Split on newlines — each line is a complete JSON-RPC message
56
- const lines = this.buffer.split("\n");
57
- // Last element is incomplete (may be empty string if chunk ended with \n)
58
- this.buffer = lines.pop();
59
- for (const line of lines) {
60
- const trimmed = line.trim();
61
- if (!trimmed)
62
- continue;
63
- try {
64
- const msg = decodeMessage(trimmed);
65
- this.emit("message", msg);
66
- }
67
- catch (err) {
68
- this.emit("error", err instanceof Error ? err : new Error(String(err)));
69
- }
70
- }
71
- }
72
105
  onClose() {
73
106
  if (this.closed)
74
107
  return;
@@ -103,54 +136,26 @@ export class StdioTransport extends Emitter {
103
136
  super.off(event, listener);
104
137
  }
105
138
  }
106
- // ---------------------------------------------------------------------------
107
- // Unix socket transport
108
- // ---------------------------------------------------------------------------
109
- /**
110
- * UnixSocketTransport — NDJSON over a Unix domain socket.
111
- *
112
- * Suitable for local IPC between wallet CLI and agent processes.
113
- *
114
- * Usage:
115
- * import { connect } from "node:net";
116
- * const sock = connect("/tmp/wmp.sock");
117
- * const transport = new UnixSocketTransport(sock);
118
- */
119
139
  export class UnixSocketTransport extends Emitter {
120
140
  socket;
121
- buffer = "";
122
141
  closed = false;
123
- constructor(socket) {
142
+ lineBuffer;
143
+ constructor(socket, opts) {
124
144
  super();
125
145
  this.socket = socket;
146
+ const maxLineLength = opts?.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH;
147
+ this.lineBuffer = new LineBuffer(maxLineLength, (msg) => this.emit("message", msg), (err) => this.emit("error", err), () => this.onClose());
126
148
  this.socket.setEncoding("utf8");
127
149
  this.socket.on("connect", () => this.emit("open"));
128
- this.socket.on("data", (chunk) => this.onData(chunk));
129
- this.socket.on("end", () => this.onClose());
130
- this.socket.on("close", () => this.onClose());
150
+ this.socket.on("data", (chunk) => this.lineBuffer.append(chunk));
151
+ this.socket.on("end", () => this.lineBuffer.close());
152
+ this.socket.on("close", () => this.lineBuffer.close());
131
153
  this.socket.on("error", (err) => this.emit("error", err));
132
154
  // If already connected, emit open
133
155
  if (!this.socket.connecting) {
134
156
  queueMicrotask(() => this.emit("open"));
135
157
  }
136
158
  }
137
- onData(chunk) {
138
- this.buffer += chunk;
139
- const lines = this.buffer.split("\n");
140
- this.buffer = lines.pop();
141
- for (const line of lines) {
142
- const trimmed = line.trim();
143
- if (!trimmed)
144
- continue;
145
- try {
146
- const msg = decodeMessage(trimmed);
147
- this.emit("message", msg);
148
- }
149
- catch (err) {
150
- this.emit("error", err instanceof Error ? err : new Error(String(err)));
151
- }
152
- }
153
- }
154
159
  onClose() {
155
160
  if (this.closed)
156
161
  return;
package/dist/node.d.ts CHANGED
@@ -7,6 +7,6 @@
7
7
  */
8
8
  export * from "./index.js";
9
9
  export { StdioTransport, UnixSocketTransport } from "./native.js";
10
- export type { StdioTransportOptions } from "./native.js";
10
+ export type { StdioTransportOptions, UnixSocketTransportOptions, } from "./native.js";
11
11
  export { createValidator } from "./schema.js";
12
12
  export type { Validator, ValidationError } from "./schema.js";