@avatarsd-llc/libtracer-ws 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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @avatarsd-llc/libtracer-ws
2
+
3
+ WebSocket transport for [libtracer](https://github.com/avatarsd-llc/libtracer) —
4
+ an RFC 6455 frame codec plus a `TransportWs` client that carries libtracer TLV
5
+ frames over WebSocket. It is **wire-compatible with the C++
6
+ `tr::net::transport_ws`** (`core/include/libtracer/ws.hpp`,
7
+ `core/src/transport_ws.cpp`): a TS client interoperates with a C++ server and
8
+ vice versa.
9
+
10
+ A transport is a vertex behind a swappable seam
11
+ ([ADR-0027](../../../../docs/adr/0027-transport-and-connections-are-vertices.md)),
12
+ and WebSocket is the first reliable transport
13
+ ([ADR-0029](../../../../docs/adr/0029-websocket-first-transport-quic-deferred-per-link.md)).
14
+ The core (`@avatarsd-llc/libtracer`) is a `peerDependency`
15
+ ([ADR-0033](../../../../docs/adr/0033-npm-subpackage-monorepo.md)), so this
16
+ package never pulls a WebSocket dependency into a consumer that only needs the
17
+ in-process codec.
18
+
19
+ ## Two entry points
20
+
21
+ ```ts
22
+ // 1) The pure, socket-free RFC 6455 frame codec (cross-validated byte-for-byte
23
+ // against the C++ codec). Use it where you frame bytes yourself.
24
+ import { acceptKey, encodeClientFrame, decodeFrame, Opcode } from '@avatarsd-llc/libtracer-ws/ws';
25
+
26
+ // 2) The TransportWs client (delegates framing to the runtime's WebSocket).
27
+ import { TransportWs } from '@avatarsd-llc/libtracer-ws';
28
+ import { encode, TYPE } from '@avatarsd-llc/libtracer';
29
+ ```
30
+
31
+ ## Carrying a TLV
32
+
33
+ A libtracer TLV is carried as **one RFC 6455 BINARY frame** (opcode `0x2`),
34
+ exactly as the C++ transport does. The client masks its frames (RFC 6455 §5.1);
35
+ the server's frames are unmasked. `TransportWs.send()` puts the whole TLV on the
36
+ wire as a single BINARY frame, and `onFrame()` delivers each inbound frame's
37
+ payload.
38
+
39
+ ```ts
40
+ const transport = new TransportWs('ws://host:9000');
41
+ transport.onFrame((bytes) => {
42
+ /* bytes is one inbound TLV */
43
+ });
44
+ await transport.connect();
45
+ transport.send(encode({ type: TYPE.NAME, opt: { pl: false }, payload, children: [], trailer: null }));
46
+ ```
47
+
48
+ ### WebSocket implementation
49
+
50
+ Framing is delegated to the runtime's `WebSocket` — native in the browser and in
51
+ Node >= 22. On older Node, pass an implementation explicitly:
52
+
53
+ ```ts
54
+ import { WebSocket } from 'ws';
55
+ const transport = new TransportWs('ws://host:9000', { WebSocket });
56
+ ```
57
+
58
+ The hand-rolled codec at the `/ws` subpath is what guarantees cross-implementation
59
+ agreement and is available for environments without a `WebSocket`.
@@ -0,0 +1,5 @@
1
+ export declare const TRANSPORT: "ws";
2
+ export { Opcode, acceptKey, encodeFrame, encodeClientFrame, decodeFrame, sha1, base64, } from './ws.js';
3
+ export type { Frame } from './ws.js';
4
+ export { TransportWs } from './transport.js';
5
+ export type { FrameReceiver, WebSocketLike, WebSocketCtor, TransportWsOptions, } from './transport.js';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // @avatarsd-llc/libtracer-ws — WebSocket transport for libtracer (#54, ADR-0029).
4
+ //
5
+ // A transport is a vertex behind a swappable seam (ADR-0027); WebSocket is the
6
+ // first reliable transport (ADR-0029). This package carries libtracer TLV frames
7
+ // over RFC 6455 WebSocket, wire-compatible with the C++ `tr::net::transport_ws`.
8
+ //
9
+ // Two entry points:
10
+ // - the `ws` subpath: a pure, socket-free RFC 6455 frame codec (cross-validated
11
+ // byte-for-byte against the C++ codec); and
12
+ // - this barrel: the `TransportWs` client plus a re-export of the codec.
13
+ // The core (`@avatarsd-llc/libtracer`) is a peerDependency (ADR-0033).
14
+ export const TRANSPORT = 'ws';
15
+ export { Opcode, acceptKey, encodeFrame, encodeClientFrame, decodeFrame, sha1, base64, } from './ws.js';
16
+ export { TransportWs } from './transport.js';
@@ -0,0 +1,67 @@
1
+ /** A received libtracer frame: the unmasked payload of one inbound BINARY frame. */
2
+ export type FrameReceiver = (bytes: Uint8Array) => void;
3
+ /** The minimal WHATWG-WebSocket surface this transport relies on. */
4
+ export interface WebSocketLike {
5
+ binaryType: string;
6
+ send(data: Uint8Array): void;
7
+ close(code?: number, reason?: string): void;
8
+ onopen: ((ev: unknown) => void) | null;
9
+ onmessage: ((ev: {
10
+ data: unknown;
11
+ }) => void) | null;
12
+ onclose: ((ev: unknown) => void) | null;
13
+ onerror: ((ev: unknown) => void) | null;
14
+ }
15
+ /** Constructs a {@link WebSocketLike} for a `ws://` / `wss://` URL. */
16
+ export type WebSocketCtor = new (url: string) => WebSocketLike;
17
+ /** Options for {@link TransportWs}. */
18
+ export interface TransportWsOptions {
19
+ /**
20
+ * The WebSocket implementation to dial with. Defaults to the runtime global
21
+ * `WebSocket` (browser, Node >= 22). Pass the `ws` package's `WebSocket` when
22
+ * running on a Node without a global one.
23
+ */
24
+ WebSocket?: WebSocketCtor;
25
+ }
26
+ /**
27
+ * A WebSocket-backed libtracer transport client.
28
+ *
29
+ * Lifecycle: construct with a URL, `await connect()`, then `send()` TLV bytes and
30
+ * receive inbound TLV bytes via {@link onFrame}. Each `send()` emits exactly one
31
+ * BINARY WebSocket frame carrying the whole TLV, matching the C++ transport.
32
+ */
33
+ export declare class TransportWs {
34
+ private readonly url;
35
+ private readonly ctor;
36
+ private ws;
37
+ private receiver;
38
+ /**
39
+ * @param url The `ws://host:port` (or `wss://`) endpoint to dial.
40
+ * @param options Transport options; see {@link TransportWsOptions}.
41
+ */
42
+ constructor(url: string, options?: TransportWsOptions);
43
+ /**
44
+ * Register (or clear) the inbound-frame receiver. Mirrors the C++
45
+ * `transport_ws_client::set_receiver`. The callback is invoked once per inbound
46
+ * BINARY frame with that frame's payload bytes.
47
+ */
48
+ onFrame(receiver: FrameReceiver | null): void;
49
+ /** True once the underlying WebSocket has opened and not yet closed. */
50
+ get connected(): boolean;
51
+ /**
52
+ * Open the WebSocket and complete the RFC 6455 opening handshake.
53
+ *
54
+ * @param deadlineMs Reject if the socket has not opened within this many
55
+ * milliseconds (default 5000). Uses events, never a sleep.
56
+ * @returns A promise that resolves when the connection is open.
57
+ */
58
+ connect(deadlineMs?: number): Promise<void>;
59
+ /**
60
+ * Send one complete libtracer TLV as a single BINARY WebSocket frame. The
61
+ * underlying WebSocket applies the RFC 6455 client masking. Throws if not
62
+ * connected.
63
+ */
64
+ send(frame: Uint8Array): void;
65
+ /** Close the connection. Resolves once the socket has fully closed. */
66
+ close(): Promise<void>;
67
+ }
@@ -0,0 +1,133 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ /** Normalize an inbound WebSocket message payload to a `Uint8Array` of its bytes. */
4
+ function toBytes(data) {
5
+ if (data instanceof Uint8Array) {
6
+ // Copy out of the (possibly pooled) backing buffer so callers own their bytes.
7
+ return new Uint8Array(data);
8
+ }
9
+ if (data instanceof ArrayBuffer) {
10
+ return new Uint8Array(data.slice(0));
11
+ }
12
+ if (ArrayBuffer.isView(data)) {
13
+ const v = data;
14
+ return new Uint8Array(v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength));
15
+ }
16
+ return null; // text / unsupported payloads are ignored (BINARY-only transport)
17
+ }
18
+ /**
19
+ * A WebSocket-backed libtracer transport client.
20
+ *
21
+ * Lifecycle: construct with a URL, `await connect()`, then `send()` TLV bytes and
22
+ * receive inbound TLV bytes via {@link onFrame}. Each `send()` emits exactly one
23
+ * BINARY WebSocket frame carrying the whole TLV, matching the C++ transport.
24
+ */
25
+ export class TransportWs {
26
+ /**
27
+ * @param url The `ws://host:port` (or `wss://`) endpoint to dial.
28
+ * @param options Transport options; see {@link TransportWsOptions}.
29
+ */
30
+ constructor(url, options = {}) {
31
+ this.ws = null;
32
+ this.receiver = null;
33
+ const ctor = options.WebSocket ?? globalThis.WebSocket;
34
+ if (!ctor) {
35
+ throw new Error('No WebSocket implementation available: pass options.WebSocket (e.g. the `ws` package) ' +
36
+ 'or run on a runtime with a global WebSocket (browser / Node >= 22).');
37
+ }
38
+ this.url = url;
39
+ this.ctor = ctor;
40
+ }
41
+ /**
42
+ * Register (or clear) the inbound-frame receiver. Mirrors the C++
43
+ * `transport_ws_client::set_receiver`. The callback is invoked once per inbound
44
+ * BINARY frame with that frame's payload bytes.
45
+ */
46
+ onFrame(receiver) {
47
+ this.receiver = receiver;
48
+ }
49
+ /** True once the underlying WebSocket has opened and not yet closed. */
50
+ get connected() {
51
+ return this.ws !== null;
52
+ }
53
+ /**
54
+ * Open the WebSocket and complete the RFC 6455 opening handshake.
55
+ *
56
+ * @param deadlineMs Reject if the socket has not opened within this many
57
+ * milliseconds (default 5000). Uses events, never a sleep.
58
+ * @returns A promise that resolves when the connection is open.
59
+ */
60
+ connect(deadlineMs = 5000) {
61
+ return new Promise((resolve, reject) => {
62
+ let settled = false;
63
+ const ws = new this.ctor(this.url);
64
+ ws.binaryType = 'arraybuffer';
65
+ const timer = setTimeout(() => {
66
+ if (settled)
67
+ return;
68
+ settled = true;
69
+ try {
70
+ ws.close();
71
+ }
72
+ catch {
73
+ /* ignore */
74
+ }
75
+ reject(new Error(`TransportWs.connect timed out after ${deadlineMs}ms`));
76
+ }, deadlineMs);
77
+ ws.onopen = () => {
78
+ if (settled)
79
+ return;
80
+ settled = true;
81
+ clearTimeout(timer);
82
+ this.ws = ws;
83
+ resolve();
84
+ };
85
+ ws.onmessage = (ev) => {
86
+ const bytes = toBytes(ev.data);
87
+ if (bytes && this.receiver)
88
+ this.receiver(bytes);
89
+ };
90
+ ws.onerror = () => {
91
+ if (settled) {
92
+ return;
93
+ }
94
+ settled = true;
95
+ clearTimeout(timer);
96
+ reject(new Error('TransportWs.connect failed (WebSocket error)'));
97
+ };
98
+ ws.onclose = () => {
99
+ this.ws = null;
100
+ if (settled)
101
+ return;
102
+ settled = true;
103
+ clearTimeout(timer);
104
+ reject(new Error('TransportWs.connect closed before opening'));
105
+ };
106
+ });
107
+ }
108
+ /**
109
+ * Send one complete libtracer TLV as a single BINARY WebSocket frame. The
110
+ * underlying WebSocket applies the RFC 6455 client masking. Throws if not
111
+ * connected.
112
+ */
113
+ send(frame) {
114
+ if (!this.ws)
115
+ throw new Error('TransportWs.send called before connect()');
116
+ this.ws.send(frame);
117
+ }
118
+ /** Close the connection. Resolves once the socket has fully closed. */
119
+ close() {
120
+ return new Promise((resolve) => {
121
+ const ws = this.ws;
122
+ if (!ws) {
123
+ resolve();
124
+ return;
125
+ }
126
+ ws.onclose = () => {
127
+ this.ws = null;
128
+ resolve();
129
+ };
130
+ ws.close();
131
+ });
132
+ }
133
+ }
package/dist/ws.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ /** RFC 6455 frame opcodes (the subset libtracer cares about). */
2
+ export declare enum Opcode {
3
+ CONT = 0,
4
+ TEXT = 1,
5
+ BINARY = 2,
6
+ CLOSE = 8,
7
+ PING = 9,
8
+ PONG = 10
9
+ }
10
+ /** One decoded RFC 6455 data/control frame (payload already unmasked). */
11
+ export interface Frame {
12
+ /** Frame opcode. */
13
+ op: Opcode;
14
+ /** FIN bit (true = final fragment). */
15
+ fin: boolean;
16
+ /** Unmasked application payload. */
17
+ payload: Uint8Array;
18
+ }
19
+ /**
20
+ * Standard SHA-1 over an arbitrary byte array (RFC 3174 / FIPS 180-1). Returns
21
+ * the 20-byte digest. Used by {@link acceptKey} for the RFC 6455 opening
22
+ * handshake; SHA-1 is required there for protocol compatibility, not security.
23
+ */
24
+ export declare function sha1(data: Uint8Array): Uint8Array;
25
+ /** Standard base64 encoding (RFC 4648, with '=' padding). */
26
+ export declare function base64(data: Uint8Array): string;
27
+ /**
28
+ * Compute the RFC 6455 Sec-WebSocket-Accept value for a client key:
29
+ * `base64(sha1(clientKey + GUID))`. The server returns this in the 101 Switching
30
+ * Protocols response to prove it spoke RFC 6455.
31
+ *
32
+ * @param clientKey The raw Sec-WebSocket-Key header value sent by the client.
33
+ */
34
+ export declare function acceptKey(clientKey: string): string;
35
+ /**
36
+ * Encode one server->client RFC 6455 frame: FIN=1, given opcode, UNMASKED.
37
+ * Server frames MUST NOT be masked (RFC 6455 §5.1). The length uses the smallest
38
+ * legal encoding (7-bit, then 126 + 2-byte marker, then 127 + 8-byte marker).
39
+ */
40
+ export declare function encodeFrame(op: Opcode, payload: Uint8Array): Uint8Array;
41
+ /**
42
+ * Encode one client->server RFC 6455 frame: FIN=1, given opcode, MASKED.
43
+ * Client frames MUST be masked (RFC 6455 §5.1): the MASK bit is set, a 4-byte
44
+ * masking key is emitted big-endian after the length, and every payload byte is
45
+ * XOR'd with `maskKey[i % 4]`. `maskKey` is a 32-bit value whose 4 big-endian
46
+ * bytes form the RFC 6455 key; it need not be cryptographically strong, only
47
+ * varied.
48
+ */
49
+ export declare function encodeClientFrame(op: Opcode, payload: Uint8Array, maskKey: number): Uint8Array;
50
+ /**
51
+ * Decode exactly one RFC 6455 frame from the front of `buf`. Handles the FIN
52
+ * bit, opcode, the MASK bit with its 4-byte key (client->server frames are
53
+ * masked; the payload is unmasked here), and the 7 / 16 / 64-bit extended length
54
+ * encodings. Overflow-safe: a 64-bit over-long length on a short buffer yields
55
+ * need-more (`null`), never an out-of-bounds read.
56
+ *
57
+ * @returns `null` if `buf` does not yet hold a complete frame (need more bytes);
58
+ * otherwise the decoded frame and the number of bytes consumed.
59
+ */
60
+ export declare function decodeFrame(buf: Uint8Array): {
61
+ frame: Frame;
62
+ consumed: number;
63
+ } | null;
package/dist/ws.js ADDED
@@ -0,0 +1,276 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // RFC 6455 WebSocket frame codec — a pure-TS port of the C++ reference codec in
4
+ // core/include/libtracer/ws.hpp (`tr::net::ws`). It is socket-free and has no
5
+ // I/O; correctness is gated byte-for-byte against the same known vectors the C++
6
+ // codec is tested with (core/tests/ws_test.cpp). This is the cross-implementation
7
+ // agreement layer: a TS client framed by this codec interoperates with the C++
8
+ // `tr::net::transport_ws` server, and vice versa.
9
+ //
10
+ // Two concerns only, mirroring the C++ header:
11
+ // 1. the opening-handshake key derivation (SHA-1 + base64 -> Sec-WebSocket-Accept), and
12
+ // 2. the data-frame codec (decode one masked/unmasked frame; encode one
13
+ // server frame unmasked, or one client frame masked, FIN=1).
14
+ /** RFC 6455 frame opcodes (the subset libtracer cares about). */
15
+ export var Opcode;
16
+ (function (Opcode) {
17
+ Opcode[Opcode["CONT"] = 0] = "CONT";
18
+ Opcode[Opcode["TEXT"] = 1] = "TEXT";
19
+ Opcode[Opcode["BINARY"] = 2] = "BINARY";
20
+ Opcode[Opcode["CLOSE"] = 8] = "CLOSE";
21
+ Opcode[Opcode["PING"] = 9] = "PING";
22
+ Opcode[Opcode["PONG"] = 10] = "PONG";
23
+ })(Opcode || (Opcode = {}));
24
+ /* --------------------------------------------------------------- sha-1 --- */
25
+ function rotl32(v, n) {
26
+ return ((v << n) | (v >>> (32 - n))) >>> 0;
27
+ }
28
+ /**
29
+ * Standard SHA-1 over an arbitrary byte array (RFC 3174 / FIPS 180-1). Returns
30
+ * the 20-byte digest. Used by {@link acceptKey} for the RFC 6455 opening
31
+ * handshake; SHA-1 is required there for protocol compatibility, not security.
32
+ */
33
+ export function sha1(data) {
34
+ let h0 = 0x67452301;
35
+ let h1 = 0xefcdab89;
36
+ let h2 = 0x98badcfe;
37
+ let h3 = 0x10325476;
38
+ let h4 = 0xc3d2e1f0;
39
+ const bitLen = data.length * 8;
40
+ // Padded message: original bytes, 0x80, zero pad to 56 mod 64, then the 64-bit
41
+ // big-endian bit length.
42
+ const msg = Array.from(data);
43
+ msg.push(0x80);
44
+ while (msg.length % 64 !== 56)
45
+ msg.push(0x00);
46
+ // bitLen fits in 53 bits of a Number for any realistic handshake input.
47
+ const hi = Math.floor(bitLen / 0x100000000);
48
+ const lo = bitLen >>> 0;
49
+ for (let i = 7; i >= 0; i--) {
50
+ const v = i >= 4 ? hi : lo;
51
+ msg.push((v >>> ((i % 4) * 8)) & 0xff);
52
+ }
53
+ const w = new Uint32Array(80);
54
+ for (let chunk = 0; chunk < msg.length; chunk += 64) {
55
+ for (let i = 0; i < 16; i++) {
56
+ w[i] =
57
+ ((msg[chunk + i * 4 + 0] << 24) |
58
+ (msg[chunk + i * 4 + 1] << 16) |
59
+ (msg[chunk + i * 4 + 2] << 8) |
60
+ msg[chunk + i * 4 + 3]) >>>
61
+ 0;
62
+ }
63
+ for (let i = 16; i < 80; i++) {
64
+ w[i] = rotl32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
65
+ }
66
+ let a = h0;
67
+ let b = h1;
68
+ let c = h2;
69
+ let d = h3;
70
+ let e = h4;
71
+ for (let i = 0; i < 80; i++) {
72
+ let f = 0;
73
+ let k = 0;
74
+ if (i < 20) {
75
+ f = (b & c) | (~b & d);
76
+ k = 0x5a827999;
77
+ }
78
+ else if (i < 40) {
79
+ f = b ^ c ^ d;
80
+ k = 0x6ed9eba1;
81
+ }
82
+ else if (i < 60) {
83
+ f = (b & c) | (b & d) | (c & d);
84
+ k = 0x8f1bbcdc;
85
+ }
86
+ else {
87
+ f = b ^ c ^ d;
88
+ k = 0xca62c1d6;
89
+ }
90
+ const tmp = (rotl32(a, 5) + (f >>> 0) + e + k + w[i]) >>> 0;
91
+ e = d;
92
+ d = c;
93
+ c = rotl32(b, 30);
94
+ b = a;
95
+ a = tmp;
96
+ }
97
+ h0 = (h0 + a) >>> 0;
98
+ h1 = (h1 + b) >>> 0;
99
+ h2 = (h2 + c) >>> 0;
100
+ h3 = (h3 + d) >>> 0;
101
+ h4 = (h4 + e) >>> 0;
102
+ }
103
+ const out = new Uint8Array(20);
104
+ const hs = [h0, h1, h2, h3, h4];
105
+ for (let i = 0; i < 5; i++) {
106
+ out[i * 4 + 0] = (hs[i] >>> 24) & 0xff;
107
+ out[i * 4 + 1] = (hs[i] >>> 16) & 0xff;
108
+ out[i * 4 + 2] = (hs[i] >>> 8) & 0xff;
109
+ out[i * 4 + 3] = hs[i] & 0xff;
110
+ }
111
+ return out;
112
+ }
113
+ /* -------------------------------------------------------------- base64 --- */
114
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
115
+ /** Standard base64 encoding (RFC 4648, with '=' padding). */
116
+ export function base64(data) {
117
+ let out = '';
118
+ let i = 0;
119
+ for (; i + 3 <= data.length; i += 3) {
120
+ const n = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];
121
+ out += B64[(n >> 18) & 0x3f] + B64[(n >> 12) & 0x3f] + B64[(n >> 6) & 0x3f] + B64[n & 0x3f];
122
+ }
123
+ const rem = data.length - i;
124
+ if (rem === 1) {
125
+ const n = data[i] << 16;
126
+ out += B64[(n >> 18) & 0x3f] + B64[(n >> 12) & 0x3f] + '==';
127
+ }
128
+ else if (rem === 2) {
129
+ const n = (data[i] << 16) | (data[i + 1] << 8);
130
+ out += B64[(n >> 18) & 0x3f] + B64[(n >> 12) & 0x3f] + B64[(n >> 6) & 0x3f] + '=';
131
+ }
132
+ return out;
133
+ }
134
+ /* ----------------------------------------------------------- accept_key --- */
135
+ const ACCEPT_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
136
+ /**
137
+ * Compute the RFC 6455 Sec-WebSocket-Accept value for a client key:
138
+ * `base64(sha1(clientKey + GUID))`. The server returns this in the 101 Switching
139
+ * Protocols response to prove it spoke RFC 6455.
140
+ *
141
+ * @param clientKey The raw Sec-WebSocket-Key header value sent by the client.
142
+ */
143
+ export function acceptKey(clientKey) {
144
+ const combined = clientKey + ACCEPT_GUID;
145
+ const bytes = new Uint8Array(combined.length);
146
+ for (let i = 0; i < combined.length; i++)
147
+ bytes[i] = combined.charCodeAt(i) & 0xff;
148
+ return base64(sha1(bytes));
149
+ }
150
+ /* ------------------------------------------------------------- framing --- */
151
+ /**
152
+ * Encode one server->client RFC 6455 frame: FIN=1, given opcode, UNMASKED.
153
+ * Server frames MUST NOT be masked (RFC 6455 §5.1). The length uses the smallest
154
+ * legal encoding (7-bit, then 126 + 2-byte marker, then 127 + 8-byte marker).
155
+ */
156
+ export function encodeFrame(op, payload) {
157
+ const out = [];
158
+ out.push(0x80 | (op & 0x0f)); // FIN=1
159
+ const len = payload.length;
160
+ if (len < 126) {
161
+ out.push(len); // MASK=0
162
+ }
163
+ else if (len <= 0xffff) {
164
+ out.push(126);
165
+ out.push((len >> 8) & 0xff);
166
+ out.push(len & 0xff);
167
+ }
168
+ else {
169
+ out.push(127);
170
+ pushU64Be(out, len);
171
+ }
172
+ for (let i = 0; i < len; i++)
173
+ out.push(payload[i]);
174
+ return Uint8Array.from(out);
175
+ }
176
+ /**
177
+ * Encode one client->server RFC 6455 frame: FIN=1, given opcode, MASKED.
178
+ * Client frames MUST be masked (RFC 6455 §5.1): the MASK bit is set, a 4-byte
179
+ * masking key is emitted big-endian after the length, and every payload byte is
180
+ * XOR'd with `maskKey[i % 4]`. `maskKey` is a 32-bit value whose 4 big-endian
181
+ * bytes form the RFC 6455 key; it need not be cryptographically strong, only
182
+ * varied.
183
+ */
184
+ export function encodeClientFrame(op, payload, maskKey) {
185
+ const out = [];
186
+ out.push(0x80 | (op & 0x0f)); // FIN=1
187
+ const len = payload.length;
188
+ if (len < 126) {
189
+ out.push(0x80 | len); // MASK=1
190
+ }
191
+ else if (len <= 0xffff) {
192
+ out.push(0x80 | 126);
193
+ out.push((len >> 8) & 0xff);
194
+ out.push(len & 0xff);
195
+ }
196
+ else {
197
+ out.push(0x80 | 127);
198
+ pushU64Be(out, len);
199
+ }
200
+ const mk = [
201
+ (maskKey >>> 24) & 0xff,
202
+ (maskKey >>> 16) & 0xff,
203
+ (maskKey >>> 8) & 0xff,
204
+ maskKey & 0xff,
205
+ ];
206
+ for (const m of mk)
207
+ out.push(m);
208
+ for (let i = 0; i < len; i++)
209
+ out.push(payload[i] ^ mk[i % 4]);
210
+ return Uint8Array.from(out);
211
+ }
212
+ /**
213
+ * Decode exactly one RFC 6455 frame from the front of `buf`. Handles the FIN
214
+ * bit, opcode, the MASK bit with its 4-byte key (client->server frames are
215
+ * masked; the payload is unmasked here), and the 7 / 16 / 64-bit extended length
216
+ * encodings. Overflow-safe: a 64-bit over-long length on a short buffer yields
217
+ * need-more (`null`), never an out-of-bounds read.
218
+ *
219
+ * @returns `null` if `buf` does not yet hold a complete frame (need more bytes);
220
+ * otherwise the decoded frame and the number of bytes consumed.
221
+ */
222
+ export function decodeFrame(buf) {
223
+ if (buf.length < 2)
224
+ return null;
225
+ const b0 = buf[0];
226
+ const b1 = buf[1];
227
+ const fin = (b0 & 0x80) !== 0;
228
+ const op = (b0 & 0x0f);
229
+ const masked = (b1 & 0x80) !== 0;
230
+ let len = b1 & 0x7f;
231
+ let pos = 2;
232
+ if (len === 126) {
233
+ if (buf.length < pos + 2)
234
+ return null;
235
+ len = (buf[pos] << 8) | buf[pos + 1];
236
+ pos += 2;
237
+ }
238
+ else if (len === 127) {
239
+ if (buf.length < pos + 8)
240
+ return null;
241
+ // Accumulate as a Number; an over-long (e.g. ~2^64) length stays huge and
242
+ // fails the bounds check below rather than wrapping, so no OOB read occurs.
243
+ len = 0;
244
+ for (let i = 0; i < 8; i++)
245
+ len = len * 256 + buf[pos + i];
246
+ pos += 8;
247
+ }
248
+ const mask = [0, 0, 0, 0];
249
+ if (masked) {
250
+ if (buf.length < pos + 4)
251
+ return null;
252
+ for (let i = 0; i < 4; i++)
253
+ mask[i] = buf[pos + i];
254
+ pos += 4;
255
+ }
256
+ // Overflow-safe length check (mirrors the C++ `len > buf.size() - pos`).
257
+ if (len > buf.length - pos)
258
+ return null;
259
+ const payload = new Uint8Array(len);
260
+ for (let i = 0; i < len; i++) {
261
+ let byte = buf[pos + i];
262
+ if (masked)
263
+ byte ^= mask[i % 4];
264
+ payload[i] = byte;
265
+ }
266
+ return { frame: { op, fin, payload }, consumed: pos + len };
267
+ }
268
+ /** Append the 8 big-endian bytes of a (<= 2^53) length to `out`. */
269
+ function pushU64Be(out, len) {
270
+ const hi = Math.floor(len / 0x100000000);
271
+ const lo = len >>> 0;
272
+ for (let i = 7; i >= 0; i--) {
273
+ const v = i >= 4 ? hi : lo;
274
+ out.push((v >>> ((i % 4) * 8)) & 0xff);
275
+ }
276
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@avatarsd-llc/libtracer-ws",
3
+ "version": "0.1.0",
4
+ "description": "WebSocket transport for libtracer (ADR-0029) — an RFC 6455 frame codec plus a TransportWs client that carries libtracer TLV frames over WebSocket, wire-compatible with the C++ tr::net::transport_ws. The core (@avatarsd-llc/libtracer) is a peerDependency. See docs/adr/0033-npm-subpackage-monorepo.md.",
5
+ "author": "avatarsd LLC",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/avatarsd-llc/libtracer.git",
10
+ "directory": "bindings/typescript/packages/transport-ws"
11
+ },
12
+ "homepage": "https://github.com/avatarsd-llc/libtracer#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/avatarsd-llc/libtracer/issues"
15
+ },
16
+ "keywords": ["protocol", "iot", "graph", "tlv", "websocket", "transport", "rfc6455"],
17
+ "type": "module",
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "sideEffects": false,
22
+ "main": "dist/index.js",
23
+ "types": "dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./ws": {
30
+ "types": "./dist/ws.d.ts",
31
+ "default": "./dist/ws.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": ["dist", "README.md", "LICENSE"],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "peerDependencies": {
40
+ "@avatarsd-llc/libtracer": "^0.0.1"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc",
44
+ "test": "node --test test/*.test.mjs",
45
+ "prepublishOnly": "npm run build"
46
+ },
47
+ "devDependencies": {
48
+ "@avatarsd-llc/libtracer": "*",
49
+ "@types/node": "^20.0.0",
50
+ "@types/ws": "^8.5.0",
51
+ "typescript": "^5.4.0",
52
+ "ws": "^8.16.0"
53
+ }
54
+ }