@browsercore/quic 0.1.3

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.
Files changed (55) hide show
  1. package/.github/workflows/ci.yml +17 -0
  2. package/.github/workflows/publish.yml +49 -0
  3. package/CODING_STANDARDS.md +205 -0
  4. package/LICENSE +21 -0
  5. package/dist/connection.d.ts +104 -0
  6. package/dist/connection.d.ts.map +1 -0
  7. package/dist/connection.js +334 -0
  8. package/dist/connection.js.map +1 -0
  9. package/dist/errors.d.ts +98 -0
  10. package/dist/errors.d.ts.map +1 -0
  11. package/dist/errors.js +130 -0
  12. package/dist/errors.js.map +1 -0
  13. package/dist/frame/frame.d.ts +22 -0
  14. package/dist/frame/frame.d.ts.map +1 -0
  15. package/dist/frame/frame.js +365 -0
  16. package/dist/frame/frame.js.map +1 -0
  17. package/dist/frame/varint.d.ts +32 -0
  18. package/dist/frame/varint.d.ts.map +1 -0
  19. package/dist/frame/varint.js +119 -0
  20. package/dist/frame/varint.js.map +1 -0
  21. package/dist/index.d.ts +20 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +19 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/packet/packet.d.ts +71 -0
  26. package/dist/packet/packet.d.ts.map +1 -0
  27. package/dist/packet/packet.js +150 -0
  28. package/dist/packet/packet.js.map +1 -0
  29. package/dist/stream/stream.d.ts +66 -0
  30. package/dist/stream/stream.d.ts.map +1 -0
  31. package/dist/stream/stream.js +617 -0
  32. package/dist/stream/stream.js.map +1 -0
  33. package/dist/types.d.ts +344 -0
  34. package/dist/types.d.ts.map +1 -0
  35. package/dist/types.js +127 -0
  36. package/dist/types.js.map +1 -0
  37. package/dist/utils.d.ts +16 -0
  38. package/dist/utils.d.ts.map +1 -0
  39. package/dist/utils.js +36 -0
  40. package/dist/utils.js.map +1 -0
  41. package/package.json +43 -0
  42. package/src/connection.ts +374 -0
  43. package/src/errors.ts +153 -0
  44. package/src/frame/frame.ts +423 -0
  45. package/src/frame/varint.ts +124 -0
  46. package/src/index.ts +70 -0
  47. package/src/packet/packet.ts +210 -0
  48. package/src/stream/stream.ts +746 -0
  49. package/src/types.ts +441 -0
  50. package/src/utils.ts +38 -0
  51. package/tests/connection.test.ts +106 -0
  52. package/tests/fake-transport.ts +107 -0
  53. package/tests/stream.test.ts +152 -0
  54. package/tests/wire.test.ts +342 -0
  55. package/tsconfig.json +30 -0
@@ -0,0 +1,17 @@
1
+ name: CI
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ branches: [main]
7
+ jobs:
8
+ build-and-test:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: actions/setup-node@v4
13
+ with:
14
+ node-version: 24
15
+ - run: npm install
16
+ - run: npm test
17
+ - run: npm run build
@@ -0,0 +1,49 @@
1
+ name: Publish
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ jobs:
6
+ publish:
7
+ runs-on: ubuntu-latest
8
+ permissions:
9
+ contents: write
10
+ id-token: write
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ with:
14
+ fetch-depth: 0
15
+ fetch-tags: true
16
+ token: ${{ secrets.GITHUB_TOKEN }}
17
+ - uses: actions/setup-node@v4
18
+ with:
19
+ node-version: 24
20
+ registry-url: https://registry.npmjs.org
21
+ - run: npm install
22
+ - run: npm run build
23
+ - run: npm test
24
+ - name: Publish to npm if version is new
25
+ run: |
26
+ VERSION=$(node -p "require('./package.json').version")
27
+ NAME=$(node -p "require('./package.json').name")
28
+ if npm view "$NAME@$VERSION" version >/dev/null 2>&1; then
29
+ echo "$NAME@$VERSION already on npm — skipping publish"
30
+ else
31
+ npm publish --access public
32
+ fi
33
+ env:
34
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
35
+ - name: Create git tag and GitHub Release
36
+ env:
37
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
38
+ run: |
39
+ VERSION=$(node -p "require('./package.json').version")
40
+ TAG="v$VERSION"
41
+ if git rev-parse "$TAG" >/dev/null 2>&1; then
42
+ echo "tag $TAG already exists — skipping release"
43
+ exit 0
44
+ fi
45
+ git config user.name "github-actions[bot]"
46
+ git config user.email "github-actions[bot]@users.noreply.github.com"
47
+ git tag "$TAG"
48
+ git push origin "$TAG"
49
+ gh release create "$TAG" --title "$TAG" --generate-notes
@@ -0,0 +1,205 @@
1
+ # TypeScript Coding Standards
2
+
3
+ These rules are the standard for this codebase and **every** sub-package. Every PR,
4
+ every AI-generated snippet, and every hand-written file follows them. They exist so
5
+ the intended behavior lives in the types — never in tribal knowledge or hidden assumptions.
6
+
7
+ > Design for AI modification: before committing, ask *"Could another developer or an
8
+ > LLM understand the intended behavior without asking me?"* If not — add types, split
9
+ > functions, clarify states, rename.
10
+
11
+ ---
12
+
13
+ ## 1. Strict compiler — never relax it
14
+
15
+ Every `tsconfig.json` inherits `tsconfig.base.json`, which carries:
16
+
17
+ ```json
18
+ {
19
+ "strict": true,
20
+ "noUncheckedIndexedAccess": true,
21
+ "exactOptionalPropertyTypes": true
22
+ }
23
+ ```
24
+
25
+ - `noUncheckedIndexedAccess` → `arr[i]` is `T | undefined`.
26
+ - `exactOptionalPropertyTypes` → `?` means absent-or-present, not present-and-undefined.
27
+
28
+ Ambiguity creates bugs and forces LLMs to guess. **Never** override these to `false`
29
+ in a sub-package to dodge an error. Fix the error instead.
30
+
31
+ ## 2. Every important data structure has a type
32
+
33
+ If data crosses a module boundary, it has an explicit type. No anonymous object
34
+ literals escaping a function.
35
+
36
+ ```ts
37
+ // Bad
38
+ const frame = { type: 0x1, streamId: 3, data: buf };
39
+
40
+ // Good
41
+ interface HeadersFrame {
42
+ readonly type: FrameType.HEADERS;
43
+ readonly streamId: StreamId;
44
+ readonly data: Uint8Array;
45
+ }
46
+ ```
47
+
48
+ ## 3. Never `any`
49
+
50
+ Unknown external data is `unknown`, then validated. `any` is a build failure.
51
+
52
+ ```ts
53
+ function parseFrame(raw: Uint8Array): Frame {
54
+ const unknown = decodeUnknown(raw); // unknown
55
+ return FrameSchema.parse(unknown); // validated → typed
56
+ }
57
+ ```
58
+
59
+ ## 4. Interfaces for domain objects, type aliases for states/constraints
60
+
61
+ - Interfaces for real entities (`TlsConnection`, `Http2Stream`, `Cookie`).
62
+ - Type aliases for states/constraints (`RunStatus`, `CipherSuite`).
63
+ - If values come from a known set, encode the set — never bare `string`.
64
+
65
+ ## 5. Model states explicitly — make invalid states unrepresentable
66
+
67
+ No "state via nullable-field combos." Use discriminated unions.
68
+
69
+ ```ts
70
+ // Bad — allows { state: "open", error: "failed" }
71
+ interface Connection {
72
+ state: string;
73
+ stream?: Stream;
74
+ error?: string;
75
+ }
76
+
77
+ // Good
78
+ type ConnectionState =
79
+ | { readonly state: "connecting" }
80
+ | { readonly state: "open"; readonly stream: Stream }
81
+ | { readonly state: "closed"; readonly reason: CloseReason };
82
+ ```
83
+
84
+ ## 6. Discriminated unions for every workflow/state
85
+
86
+ The compiler + LLM reason about every case.
87
+
88
+ ## 7. Functions declare input AND output types
89
+
90
+ Public functions always define both sides — no inference-only signatures on exported APIs.
91
+
92
+ ## 8. One function = one decision
93
+
94
+ No `processHandshake()` that validates + persists + schedules + notifies. Split:
95
+ `validate…`, `decodeStep`, `actuate`, `recordStep`.
96
+
97
+ ## 9. No hidden behavior
98
+
99
+ A function named `updateSettings` does not also flush a log. Every side effect is its
100
+ own named call.
101
+
102
+ ## 10. Name things explicitly
103
+
104
+ `cipherSuite`, `observedRank`, `clientHello` — never `data`, `result`, `obj`.
105
+ The name is the documentation.
106
+
107
+ ## 11. Prefer immutable data + `readonly`
108
+
109
+ ```ts
110
+ const next = { ...prev, cipherSuite } as const;
111
+ interface Connection { readonly id: ConnectionId; }
112
+ ```
113
+
114
+ No in-place mutation of shared state. `const` over `let`.
115
+
116
+ ## 12. Validate external data immediately
117
+
118
+ Everything from outside the boundary is `unknown`: sockets, files, captures, configs.
119
+ Use **Zod** at every boundary:
120
+
121
+ ```ts
122
+ const frame = FrameSchema.parse(raw); // never `raw as Frame`
123
+ ```
124
+
125
+ ## 13. Types are contracts, not documentation
126
+
127
+ ```ts
128
+ // Bad // user id
129
+ // id: string;
130
+ // Good
131
+ type UserId = string & { __brand: "UserId" };
132
+ ```
133
+
134
+ ## 14. Branded/opaque ID types — load-bearing
135
+
136
+ Don't use bare `number`/`string` for IDs. This kills the "pass an X where a Y belongs"
137
+ class of bug. The project uses these brands (defined per-package, see `types.ts`):
138
+
139
+ ```ts
140
+ type ConnectionId = string & { __brand: "ConnectionId" };
141
+ type StreamId = number & { __brand: "StreamId" };
142
+ type SessionId = string & { __brand: "SessionId" };
143
+ ```
144
+
145
+ ## 15. Exhaustive switches
146
+
147
+ Every `switch` over a union hits `default: assertNever(x)`. Adding a state forces every
148
+ handler to compile-error until handled.
149
+
150
+ ```ts
151
+ function assertNever(x: never): never {
152
+ throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
153
+ }
154
+ ```
155
+
156
+ ## 16. Explicit, typed errors
157
+
158
+ ```ts
159
+ // Bad
160
+ throw new Error("handshake failed");
161
+ // Good
162
+ throw new TlsHandshakeError("server_hello_parse", cause);
163
+ ```
164
+
165
+ Errors are part of the API. Define them in each package's `errors.ts`.
166
+
167
+ ## 17. No magic strings
168
+
169
+ `if (event === Event.COLD_START)` or a string-literal union — never bare `"cold_start"`.
170
+
171
+ ## 18. Clear dependency boundaries
172
+
173
+ Domain (pure protocol logic) knows nothing of AWS / HTTP / DDB / sockets. Infrastructure
174
+ adapts. The protocol state machines stay I/O-free so they're unit-testable.
175
+
176
+ **Within this repo**, the dependency graph flows upward only — never sideways or downward:
177
+
178
+ ```
179
+ @browsercore/fetch
180
+ └─ @browsercore/http2 @browsercore/http1 @browsercore/cookies @browsercore/profiles
181
+ └─ @browsercore/tls
182
+ └─ @browsercore/crypto @browsercore/transport
183
+ └─ node:net / node:crypto
184
+ ```
185
+
186
+ A package may only import from packages *below* it in this graph.
187
+
188
+ ## 19. Documentation: why, not what
189
+
190
+ Comments explain *why* ("crawl past our position so the competitor snapshot covers the
191
+ neighborhood"), never *what* the code obviously does. Priority: Types > Names > Structure >
192
+ Comments.
193
+
194
+ ## 20. API contracts in one place
195
+
196
+ Domain types live in each package's `types.ts`; wire schemas in `schemas.ts`. One source
197
+ of truth, never duplicated shapes.
198
+
199
+ ---
200
+
201
+ ## The Golden Rule
202
+
203
+ Every piece of important information exists as one of: **a type, a function signature,
204
+ an explicit state model, a schema validation, or clear naming.** Never rely on tribal
205
+ knowledge or hidden assumptions.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jens Verneuer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
@@ -0,0 +1,104 @@
1
+ /**
2
+ * QUIC connection lifecycle + datagram read loop (RFC 9000 §5, §12).
3
+ *
4
+ * Wires packet header parsing/serialization, the frame layer, and the stream
5
+ * manager over an injected {@link DatagramTransport} (UDP). The connection owns
6
+ * the read loop: it turns inbound datagrams into frames, dispatches each to the
7
+ * stream manager, and drains pending stream sends back into outbound packets.
8
+ *
9
+ * Honest limitations:
10
+ * - The TLS 1.3 handshake and packet protection (header protection + AEAD
11
+ * payload encryption) are out of scope. `connectQuic()` returns a connection
12
+ * that moves *unprotected* frames over the transport directly — enough to
13
+ * drive the data plane and to be tested with a fake datagram transport. A
14
+ * production build layers protection + the handshake on top of this.
15
+ * - No congestion controller, no connection migration, no PATH_CHALLENGE /
16
+ * PATH_RESPONSE beyond frame relay, and no liveness PING.
17
+ *
18
+ * Concurrency model: the read loop is a single async task pulling datagrams from
19
+ * the transport. Outbound frames are produced synchronously by the stream
20
+ * manager and packed into packets; writes resolve once bytes are buffered.
21
+ */
22
+ import type { EventEmitter } from "node:events";
23
+ import type { ConnectionId, QuicConnection, QuicFrame, QuicOptions, QuicStream } from "./types.js";
24
+ import { type StreamManager } from "./stream/stream.js";
25
+ /**
26
+ * Concrete QUIC connection. The public surface matches the fixed
27
+ * `QuicConnection` interface; internal state is kept on the instance.
28
+ */
29
+ export declare class QuicConnectionImpl implements QuicConnection {
30
+ readonly id: string;
31
+ /** The underlying datagram (UDP) transport. */
32
+ private readonly transport;
33
+ /** The peer's UDP address. */
34
+ private readonly peer;
35
+ /** Stream manager (also an EventEmitter for connection-level signals). */
36
+ private readonly manager;
37
+ /** Our current destination connection id (the one we put on outbound packets). */
38
+ private readonly dcid;
39
+ /** Set once the connection begins graceful shutdown. */
40
+ private closing;
41
+ /** Set once the connection is fully torn down. */
42
+ private closed;
43
+ /** Buffered outbound frames waiting to be packed into the next packet. */
44
+ private readonly outboundFrames;
45
+ constructor(id: string, options: QuicOptions, manager: StreamManager & EventEmitter, dcid: ConnectionId);
46
+ openBidirectionalStream(): Promise<QuicStream>;
47
+ acceptBidirectionalStream(): Promise<QuicStream>;
48
+ openUnidirectionalStream(): Promise<QuicStream>;
49
+ acceptUnidirectionalStream(): Promise<QuicStream>;
50
+ close(errorCode: bigint, reason: string): Promise<void>;
51
+ /**
52
+ * Enqueue a frame for the next outbound packet. Control frames from the
53
+ * stream manager flow through here so they are serialized + sent by the
54
+ * connection's packetizer.
55
+ */
56
+ sendFrame(frame: QuicFrame): void;
57
+ /**
58
+ * Pack all buffered outbound frames into a short-header packet and send it.
59
+ * Splits into multiple datagrams if the payload exceeds MAX_DATAGRAM_PAYLOAD.
60
+ */
61
+ private _flush;
62
+ /** Serialize frames into a single byte buffer (no packet header). */
63
+ private _packFrames;
64
+ /** Wrap a serialized payload in a short (1-RTT) header + packet number. */
65
+ private _wrapPacket;
66
+ /**
67
+ * Start the datagram read loop. Must be called once after construction.
68
+ * Runs until the transport closes or the connection tears down.
69
+ */
70
+ startReadLoop(): void;
71
+ private _onPeerClose;
72
+ /** Parse a single datagram into frames and dispatch them. */
73
+ private _dispatchDatagram;
74
+ /** Pull the DCID / version from a parsed header into connection state. */
75
+ private _applyHeader;
76
+ /**
77
+ * Build a pull-based byte reader over a fixed buffer. `readFrames` consumes
78
+ * bytes incrementally; this yields slices until the buffer is exhausted.
79
+ */
80
+ private _byteStreamReader;
81
+ /** Route a decoded frame: data-plane frames to the manager, the rest here. */
82
+ private _handleFrame;
83
+ /** Run `fn`, then flush any outbound frames it produced to the peer. */
84
+ private _withOutbound;
85
+ /** Main read loop: pull datagrams, dispatch, drain sends. */
86
+ private _readLoop;
87
+ /** Emit STREAM frames for streams with queued data, then flush. */
88
+ private _drainSends;
89
+ /** Tear down the connection on a fatal transport / parse error. */
90
+ private _handleFatal;
91
+ /** Mark closed and release the transport. */
92
+ private _teardown;
93
+ private _ensureOpen;
94
+ }
95
+ /**
96
+ * Establish a QUIC connection over an existing datagram transport.
97
+ *
98
+ * Creates the stream manager and the read loop. Because the TLS handshake and
99
+ * packet protection are out of scope, this returns a connection that moves
100
+ * unprotected frames — the data plane is fully functional and testable with a
101
+ * fake datagram transport.
102
+ */
103
+ export declare function connectQuic(options: QuicOptions): Promise<QuicConnection>;
104
+ //# sourceMappingURL=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