@amritk/nish-x86_64-linux 0.50.0 → 0.51.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.
Files changed (54) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +4 -1
  3. package/package.json +1 -1
  4. package/runtime/nish.d.ts +82 -2
  5. package/runtime/nish.h +5 -0
  6. package/runtime/runtime-host.c +21 -5
  7. package/std/README.md +7 -7
  8. package/std/base64.ts +61 -95
  9. package/std/bytes.ts +6 -4
  10. package/std/cli-args.ts +150 -107
  11. package/std/compress/checksum.ts +68 -10
  12. package/std/compress/deflate.ts +193 -100
  13. package/std/compress/gzip.ts +124 -49
  14. package/std/compress/zlib.ts +57 -15
  15. package/std/crypto/aes.ts +51 -9
  16. package/std/crypto/ed25519.ts +12 -10
  17. package/std/crypto/hkdf.ts +405 -283
  18. package/std/crypto/hmac.ts +483 -148
  19. package/std/crypto/jwt.ts +19 -21
  20. package/std/crypto/p256.ts +5 -7
  21. package/std/crypto/pki-roots.ts +28 -8
  22. package/std/crypto/rsa-sign.ts +5 -2
  23. package/std/crypto/sha256.ts +81 -26
  24. package/std/crypto/sha512.ts +135 -49
  25. package/std/json-value.ts +14 -15
  26. package/std/net/buffer-pool.ts +25 -14
  27. package/std/net/fetch.ts +108 -27
  28. package/std/net/handler.ts +11 -22
  29. package/std/net/hpack.ts +38 -19
  30. package/std/net/http-compress.ts +21 -12
  31. package/std/net/http-server.ts +9 -4
  32. package/std/net/http1-client-codec.ts +22 -15
  33. package/std/net/http1-codec.ts +37 -36
  34. package/std/net/http3-server.ts +127 -45
  35. package/std/net/http3.ts +99 -50
  36. package/std/net/postgres-async.ts +5 -10
  37. package/std/net/qpack.ts +83 -17
  38. package/std/net/quic-listener.ts +42 -27
  39. package/std/net/quic-packet.ts +91 -50
  40. package/std/net/quic-stream.ts +29 -22
  41. package/std/net/quic.ts +48 -23
  42. package/std/net/static.ts +5 -3
  43. package/std/net/tls/client.ts +81 -34
  44. package/std/net/tls/codec.ts +3 -4
  45. package/std/net/tls/record.ts +54 -22
  46. package/std/net/tls/schedule.ts +339 -149
  47. package/std/net/tls.ts +42 -12
  48. package/std/net/upstream.ts +18 -19
  49. package/std/net/url.ts +78 -21
  50. package/std/net/websocket.ts +3 -11
  51. package/std/net/webtransport.ts +95 -21
  52. package/std/raster.ts +12 -2
  53. package/std/term-pixels.ts +18 -2
  54. package/std/text.ts +5 -5
package/std/net/http3.ts CHANGED
@@ -408,11 +408,61 @@ export class Http3Config {
408
408
  resetBudget: i32 = 100
409
409
  }
410
410
 
411
- /** Panics unless `value` lies in `[low, high]`: a cap out of range is the program's mistake. */
412
- const http3CheckCap = (what: string, value: i32, low: i32, high: i32): void => {
413
- if (value < low || value > high) {
414
- panic(`Http3Connection: ${what} of ${value}, outside ${low} to ${high}`)
415
- }
411
+ /** Why `value` is not in `[low, high]`, or "" when it is. */
412
+ const http3CapFault = (what: string, value: i64, low: i64, high: i64): string =>
413
+ value < low || value > high ? `Http3Connection: ${what} of ${value}, outside ${low} to ${high}` : ""
414
+
415
+ /**
416
+ * Why `config` over `quic` is not a connection this module can run, or ""
417
+ * when it is: the rules the `Http3Connection` constructor documents, the
418
+ * first broken one named.
419
+ */
420
+ const http3ConnectionFault = (config: Http3Config, quic: QuicConnection): string => {
421
+ // The most a section may be: half a buffer less a frame header. Widened
422
+ // from two `i32`s, so the difference cannot wrap.
423
+ const room: i64 = toI64(quic.streams.bufferSize / 2) - toI64(H3_HEAD)
424
+ const bidi: i64 = quic.streams.maxBidi
425
+ // A HEADERS frame is read once all of it is in the stream's buffer, and QUIC
426
+ // gives more credit only once half a buffer has been read, so the frame
427
+ // may be at most half a buffer, its header aside, or it could stall.
428
+ const caps: string[] = [
429
+ http3CapFault("maxFieldSectionSize", toI64(config.maxFieldSectionSize), toI64(1), room),
430
+ http3CapFault("the QUIC bidirectional stream limit", bidi, toI64(0), toI64(1024)),
431
+ http3CapFault("bodyChunk", toI64(config.bodyChunk), toI64(1), toI64(H3_MAX_CHUNK)),
432
+ http3CapFault("writeChunk", toI64(config.writeChunk), toI64(1), toI64(H3_MAX_CHUNK)),
433
+ http3CapFault("the QUIC unidirectional stream limit", quic.streams.maxUni, toI64(3), toI64(1024)),
434
+ http3CapFault("the QUIC local stream limit", quic.streams.localStreams, toI64(3), toI64(1024)),
435
+ http3CapFault(
436
+ "webtransportSessions",
437
+ toI64(config.webtransportSessions),
438
+ toI64(0),
439
+ toI64(H3_MAX_SESSIONS)
440
+ ),
441
+ http3CapFault("resetBudget", toI64(config.resetBudget), toI64(0), toI64(2147483647)),
442
+ http3CapFault("idleTimeout", toI64(config.idleTimeout), toI64(1), toI64(2147483647)),
443
+ http3CapFault("headTimeout", toI64(config.headTimeout), toI64(1), toI64(2147483647)),
444
+ ]
445
+ for (const fault of caps) {
446
+ if (fault.length > 0) {
447
+ return fault
448
+ }
449
+ }
450
+ // The connection's credit too: every request stream may hold a HEADERS
451
+ // frame not yet whole, and QUIC raises MAX_DATA once half the window is read.
452
+ // The window must hold `bidi` times `each`; dividing tests that with no product to overflow.
453
+ const each: i64 = toI64(2) * toI64(config.maxFieldSectionSize) + toI64(2) * toI64(H3_HEAD)
454
+ if (bidi > 0 && quic.streams.windowData / bidi < each) {
455
+ return `Http3Connection: a connection window of ${quic.streams.windowData}, under ${each} bytes for each of ${bidi} request streams' field sections`
456
+ }
457
+ // RFC 9297 §2.1.1: QUIC datagrams carry HTTP datagrams, which only WebTransport uses here.
458
+ const datagrams: boolean = quic.datagramsIn.capacity() > 0
459
+ if (config.webtransportSessions > 0 && !datagrams) {
460
+ return "Http3Connection: WebTransport needs QUIC datagrams, and the QUIC maxDatagramFrameSize is 0"
461
+ }
462
+ if (config.webtransportSessions === 0 && datagrams) {
463
+ return "Http3Connection: QUIC datagrams advertised with WebTransport off (webtransportSessions 0)"
464
+ }
465
+ return ""
416
466
  }
417
467
 
418
468
  /**
@@ -643,58 +693,41 @@ export class Http3Connection {
643
693
  private connect: boolean = false
644
694
  /** Whether WebTransport is on: `webtransportSessions` above 0. Fixed by the constructor. */
645
695
  webtransport: boolean = false
696
+ /**
697
+ * Why the configuration does not fit the QUIC connection, the rule it
698
+ * breaks, or "" when it fits. Fixed by the constructor; while it is set the
699
+ * connection is failed with H3_INTERNAL_ERROR, and `restart` fails it again.
700
+ */
701
+ fault: string = ""
646
702
 
647
703
  /**
648
704
  * A connection under `config` over `quic`, whose configuration must let a
649
705
  * HEADERS frame of `maxFieldSectionSize` fit half a stream's buffer, and
650
706
  * one on every request stream fit half the connection's window, and let
651
707
  * the client open the three unidirectional streams it needs and this side
652
- * open its own three (§6.2). Each QUIC stream limit is at most 1,024. A cap
653
- * out of range panics.
708
+ * open its own three (§6.2). Each QUIC stream limit is at most 1,024. A
709
+ * configuration that breaks one of these rules, a cap out of range, makes a
710
+ * connection that is failed from the start with H3_INTERNAL_ERROR, QUIC
711
+ * closing, and `fault` naming the rule.
654
712
  *
655
713
  * @param config The caps; kept, not copied, so it must not change after this call.
656
714
  * @param quic The server QUIC connection to run on, kept for this connection's life. Its stream caps
657
715
  * are checked as above, and it must take DATAGRAM frames exactly when `webtransportSessions` is above
658
- * 0, or this panics.
716
+ * 0, or the connection fails as above.
659
717
  */
660
718
  constructor(config: Http3Config, quic: QuicConnection) {
661
- const buffer: i32 = quic.streams.bufferSize
662
- // A HEADERS frame is read once all of it is in the stream's buffer, and QUIC
663
- // gives more credit only once half a buffer has been read, so the frame
664
- // may be at most half a buffer, its header aside, or it could stall.
665
- http3CheckCap("maxFieldSectionSize", config.maxFieldSectionSize, 1, buffer / 2 - H3_HEAD)
666
- // The connection's credit too: every request stream may hold a HEADERS
667
- // frame not yet whole, and QUIC raises MAX_DATA once half the window is read.
668
- // The window must hold `bidi` times `each`; dividing tests that with no product to overflow.
669
- const bidi: i64 = quic.streams.maxBidi
670
- http3CheckCap("the QUIC bidirectional stream limit", toI32(bidi), 0, 1024)
671
- const each: i64 = toI64(2) * toI64(config.maxFieldSectionSize) + toI64(2) * toI64(H3_HEAD)
672
- if (bidi > 0 && quic.streams.windowData / bidi < each) {
673
- panic(
674
- `Http3Connection: a connection window of ${quic.streams.windowData}, under ${each} bytes for each of ${bidi} request streams' field sections`
675
- )
676
- }
677
- http3CheckCap("bodyChunk", config.bodyChunk, 1, H3_MAX_CHUNK)
678
- http3CheckCap("writeChunk", config.writeChunk, 1, H3_MAX_CHUNK)
679
- http3CheckCap("the QUIC unidirectional stream limit", toI32(quic.streams.maxUni), 3, 1024)
680
- http3CheckCap("the QUIC local stream limit", toI32(quic.streams.localStreams), 3, 1024)
681
- http3CheckCap("webtransportSessions", config.webtransportSessions, 0, H3_MAX_SESSIONS)
682
- http3CheckCap("resetBudget", config.resetBudget, 0, 2147483647)
683
- http3CheckCap("idleTimeout", config.idleTimeout, 1, 2147483647)
684
- http3CheckCap("headTimeout", config.headTimeout, 1, 2147483647)
685
- // RFC 9297 §2.1.1: QUIC datagrams carry HTTP datagrams, which only WebTransport uses here.
686
- const datagrams: boolean = quic.datagramsIn.capacity() > 0
687
- if (config.webtransportSessions > 0 && !datagrams) {
688
- panic("Http3Connection: WebTransport needs QUIC datagrams, and the QUIC maxDatagramFrameSize is 0")
689
- }
690
- if (config.webtransportSessions === 0 && datagrams) {
691
- panic("Http3Connection: QUIC datagrams advertised with WebTransport off (webtransportSessions 0)")
692
- }
693
- this.webtransport = config.webtransportSessions > 0
719
+ const fault: string = http3ConnectionFault(config, quic)
720
+ const fits: boolean = fault.length === 0
721
+ this.fault = fault
722
+ // A configuration that does not fit fails the connection at once (below,
723
+ // and again on every `restart`), so it gets the smallest buffers instead.
724
+ const sectionSize: i32 = fits ? config.maxFieldSectionSize : H3_ONE
725
+ const bodyChunk: i32 = fits ? config.bodyChunk : H3_ONE
726
+ this.webtransport = fits && config.webtransportSessions > 0
694
727
  this.connect = config.extendedConnect || this.webtransport
695
728
  this.config = config
696
729
  this.quic = quic
697
- this.decoder = new QpackDecoder(config.maxFieldSectionSize)
730
+ this.decoder = new QpackDecoder(sectionSize)
698
731
  this.encoder = new QpackEncoder()
699
732
  this.fields = new HttpFields()
700
733
  this.peer = new Http3Settings()
@@ -702,8 +735,8 @@ export class Http3Connection {
702
735
  this.none = []
703
736
  this.data = this.none
704
737
  this.section = this.none
705
- this.dataPool = new BufferPool("Http3Connection.data", config.bodyChunk, 1)
706
- this.sectionPool = new BufferPool("Http3Connection.section", config.maxFieldSectionSize, 1)
738
+ this.dataPool = new BufferPool("Http3Connection.data", bodyChunk, 1)
739
+ this.sectionPool = new BufferPool("Http3Connection.section", sectionSize, 1)
707
740
  quicStreamGrowFree(this.dataPool.free, 1, this.none)
708
741
  quicStreamGrowFree(this.sectionPool.free, 1, this.none)
709
742
  this.control = new Array<u8>(H3_CONTROL_FRAME_MAX)
@@ -727,7 +760,7 @@ export class Http3Connection {
727
760
  H3_SETTINGS_QPACK_BLOCKED_STREAMS,
728
761
  H3_SETTINGS_MAX_FIELD_SECTION_SIZE,
729
762
  ]
730
- this.settingValues = [toI64(0), toI64(0), toI64(config.maxFieldSectionSize)]
763
+ this.settingValues = [toI64(0), toI64(0), toI64(sectionSize)]
731
764
  if (this.connect) {
732
765
  this.settingIds.push(H3_SETTINGS_ENABLE_CONNECT_PROTOCOL)
733
766
  this.settingValues.push(toI64(1))
@@ -742,8 +775,9 @@ export class Http3Connection {
742
775
  }
743
776
  // `QuicStreams` builds one slot per stream its three limits allow, each
744
777
  // checked above to be at most 1,024, so the table holds at most 3,072
745
- // and the `u16` holds it and every table below exactly.
746
- const n: u16 = toU16(quic.streams.slots.length)
778
+ // and the `u16` holds it and every table below exactly; a connection
779
+ // that does not fit tracks no stream.
780
+ const n: u16 = fits ? toU16(quic.streams.slots.length) : toU16(0)
747
781
  const bytes: u16 = toU16(toI32(n) * H3_HEAD)
748
782
  this.slotId = new Array<i64>(n)
749
783
  this.frameType = new Array<i64>(n)
@@ -824,6 +858,9 @@ export class Http3Connection {
824
858
  this.resetCredit = this.config.resetBudget
825
859
  this.settingsSeen = false
826
860
  this.resetByPeer = false
861
+ if (this.fault.length > 0) {
862
+ this.fail(H3_INTERNAL_ERROR)
863
+ }
827
864
  }
828
865
 
829
866
  // ---- The connection -----------------------------------------------------------
@@ -1363,7 +1400,9 @@ export class Http3Connection {
1363
1400
  const end: i32 = base + have
1364
1401
  const head: u8[] = this.head
1365
1402
  // Never: slot `k`'s H3_HEAD bytes lie inside `head`, which nothing resizes.
1403
+ // Were it taken, the connection fails, as `controlFrame`'s does.
1366
1404
  if (base < 0 || base > end || end > toI32(head.length)) {
1405
+ this.fail(H3_INTERNAL_ERROR)
1367
1406
  return H3_ZERO
1368
1407
  }
1369
1408
  if (h3ReadFrameHeader(this.header, head, base, end - base) > 0) {
@@ -1427,10 +1466,15 @@ export class Http3Connection {
1427
1466
  if (n < 0) {
1428
1467
  return this.fail(H3_CLOSED_CRITICAL_STREAM)
1429
1468
  }
1469
+ const data: u8[] = this.data
1470
+ if (n > toI32(data.length)) {
1471
+ return this.fail(H3_INTERNAL_ERROR) // never: `readData` reads at most the buffer it fills
1472
+ }
1473
+ const start: i32 = 0
1430
1474
  const result: i64 =
1431
1475
  phase === H3_PHASE_ENCODER
1432
- ? this.decoder.receiveEncoderStream(this.data, H3_ZERO, n)
1433
- : this.encoder.receiveDecoderStream(this.data, H3_ZERO, n)
1476
+ ? this.decoder.receiveEncoderStream(data, start, n)
1477
+ : this.encoder.receiveDecoderStream(data, start, n)
1434
1478
  if (result !== QPACK_OK) {
1435
1479
  return this.fail(result)
1436
1480
  }
@@ -2239,7 +2283,12 @@ export class Http3Connection {
2239
2283
  * checks it there.
2240
2284
  */
2241
2285
  private fieldSection(k: i32, id: i64, length: i32): i32 {
2242
- const result: i64 = this.decoder.decode(this.section, H3_ZERO, length)
2286
+ const section: u8[] = this.section
2287
+ if (length < 0 || length > toI32(section.length)) {
2288
+ return this.fail(H3_INTERNAL_ERROR) // never: `requestStep` passes a payload it holds whole in `section`
2289
+ }
2290
+ const start: i32 = 0
2291
+ const result: i64 = this.decoder.decode(section, start, length)
2243
2292
  if (k < 0 || k >= toI32(this.phase.length)) {
2244
2293
  return this.fail(H3_INTERNAL_ERROR) // never: `requestStep` holds a slot of the table, which nothing resizes
2245
2294
  }
@@ -2652,19 +2652,14 @@ const pgAsyncLabel = (out: u8[], name: i32): void => {
2652
2652
  }
2653
2653
 
2654
2654
  /**
2655
- * A zeroed byte array of `n` bytes, or an empty one for a negative `n`. Up to
2656
- * 64 KiB it is one `new Array` of a `u16` length, which needs no check; a
2657
- * longer one, the rare buffer for a message past that, is built by `push`.
2655
+ * A zeroed byte array of `n` bytes, or an empty one for a negative `n`: one
2656
+ * allocation, its length proven non-negative by the guard.
2658
2657
  */
2659
2658
  const pgAsyncZeroed = (n: i32): u8[] => {
2660
- if (n >= 0 && n <= 65535) {
2661
- return new Array<u8>(toU16(n))
2662
- }
2663
- const out: u8[] = []
2664
- while (toI32(out.length) < n) {
2665
- out.push(0)
2659
+ if (n < 0) {
2660
+ return []
2666
2661
  }
2667
- return out
2662
+ return new Array<u8>(n)
2668
2663
  }
2669
2664
 
2670
2665
  /** `s`'s UTF-8 bytes, or null when one is zero, which a C string in the protocol cannot hold. */
package/std/net/qpack.ts CHANGED
@@ -82,8 +82,8 @@
82
82
  import {
83
83
  HPACK_OK,
84
84
  HpackHuffman,
85
+ hpackHuffmanAppend,
85
86
  hpackHuffmanDecode,
86
- hpackHuffmanEncode,
87
87
  hpackHuffmanLength,
88
88
  } from "nish/net/hpack"
89
89
 
@@ -162,6 +162,12 @@ export const QPACK_REASON_ACKNOWLEDGMENT: i32 = 11
162
162
  /** An Insert Count Increment (§4.4.3). */
163
163
  export const QPACK_REASON_INCREMENT: i32 = 12
164
164
 
165
+ /**
166
+ * A `QpackDecoder` made with a negative `maxFieldSectionSize`, a limit no
167
+ * section can be held to: every `decode` refuses with it, before reading.
168
+ */
169
+ export const QPACK_REASON_LIMIT: i32 = 13
170
+
165
171
  /**
166
172
  * Where the instruction counters stop. A peer may send a legal one-byte
167
173
  * instruction as often as it likes, and an `i32` that overflows panics, so a
@@ -510,13 +516,23 @@ const qpackStaticValue = (index: i32): string => {
510
516
  return ""
511
517
  }
512
518
  }
513
- /** Panics unless `buf[off, off + len)` lies inside `buf`. */
519
+ /**
520
+ * Panics unless `buf[off, off + len)` lies inside `buf`. In the window contract's shape
521
+ * (`src/window-contract.ts`), so a caller that proved the window has proved this.
522
+ */
514
523
  const qpackCheckWindow = (where: string, buf: u8[], off: i32, len: i32): void => {
515
- if (off < 0 || len < 0 || toI64(off) + toI64(len) > toI64(buf.length)) {
516
- panic(`${where}: the window [${off}, ${off} + ${len}) is outside a buffer of ${buf.length} bytes`)
524
+ const size: i32 = toI32(buf.length)
525
+ if (off < 0 || len < 0 || off > size || len > size - off) {
526
+ panic(`${where}: the window [${off}, ${off} + ${len}) is outside a buffer of ${size} bytes`)
517
527
  }
518
528
  }
519
529
 
530
+ /** Whether `buf[off, off + len)` lies inside `buf`: the test `qpackCheckWindow` panics on. */
531
+ const qpackWindowFits = (buf: u8[], off: i32, len: i32): boolean => {
532
+ const size: i32 = toI32(buf.length)
533
+ return off >= 0 && len >= 0 && off <= size && len <= size - off
534
+ }
535
+
520
536
  /** Whether `buf[off, off + len)` spells `text`, which is ASCII. */
521
537
  const qpackSameText = (buf: u8[], off: i32, len: i32, text: string): boolean => {
522
538
  if (len !== toI32(text.length)) {
@@ -572,12 +588,36 @@ const qpackPushInteger = (out: u8[], flags: i32, max: i32, value: u64): void =>
572
588
  out.push(toU8(toI32(rest)))
573
589
  }
574
590
 
591
+ /**
592
+ * The bytes the string `src[off, off + len)` takes on the wire before its
593
+ * length prefix: its Huffman length when `huffman` is true and that is
594
+ * shorter, else `len`. The caller has checked the window.
595
+ */
596
+ const qpackStringLength = (h: HpackHuffman, src: u8[], off: i32, len: i32, huffman: boolean): i32 => {
597
+ // Never taken: `encodeLine` checked the window. Widened, so the sum of two
598
+ // `i32`s cannot wrap.
599
+ const stop: i64 = toI64(off) + toI64(len)
600
+ if (!huffman || off < 0 || len < 0 || stop > toI64(src.length)) {
601
+ return len
602
+ }
603
+ // At most the length, so the `i32` holds it exactly; `[off, end)` is the
604
+ // window, spelled so the bounds prover reads it.
605
+ const end: i32 = toI32(stop)
606
+ if (off > end || end > toI32(src.length)) {
607
+ return len
608
+ }
609
+ const coded: i32 = hpackHuffmanLength(h, src, off, end - off)
610
+ return coded < len ? coded : len
611
+ }
612
+
575
613
  /**
576
614
  * Appends `src[off, off + len)` as a §4.1.2 string literal: the Huffman
577
615
  * flag is the bit `huffmanBit`, the length an integer whose prefix is `max`
578
616
  * (every bit below the flag set), and `flags` the bits above.
579
- * When `huffman` is true the string is Huffman-coded if that makes it
580
- * shorter, and sent raw otherwise, as an empty string always is.
617
+ * `coded` is what `qpackStringLength` answered for the same window, read
618
+ * before anything was written: the string is Huffman-coded when it is less
619
+ * than `len`, and sent raw otherwise. It checks nothing and cannot panic, so
620
+ * it may follow a push to an array the window shares.
581
621
  */
582
622
  const qpackPushString = (
583
623
  h: HpackHuffman,
@@ -588,12 +628,11 @@ const qpackPushString = (
588
628
  src: u8[],
589
629
  off: i32,
590
630
  len: i32,
591
- huffman: boolean
631
+ coded: i32
592
632
  ): void => {
593
- const coded: i32 = huffman ? hpackHuffmanLength(h, src, off, len) : len
594
633
  if (coded < len) {
595
634
  qpackPushInteger(out, flags | huffmanBit, max, toU64(coded))
596
- hpackHuffmanEncode(h, src, off, len, out)
635
+ hpackHuffmanAppend(h, src, off, len, out)
597
636
  return
598
637
  }
599
638
  qpackPushInteger(out, flags, max, toU64(len))
@@ -743,7 +782,18 @@ const qpackReadString = (d: QpackDecoder, src: u8[], huffmanBit: i32, lengthMax:
743
782
  }
744
783
  // At most `end - start`, so the `i32` holds it exactly.
745
784
  const length: i32 = toI32(n)
746
- d.at = toI32(toI64(start) + toI64(length))
785
+ // `decode` checked `[at, end)` inside `src`, so a string inside it is too: never taken.
786
+ const stop: i64 = toI64(start) + toI64(length)
787
+ if (start < 0 || length < 0 || stop > toI64(src.length)) {
788
+ return QPACK_REASON_TRUNCATED
789
+ }
790
+ // At most the length, so the `i32` holds it exactly; `[start, end)` is the
791
+ // string, spelled so the bounds prover reads it.
792
+ const end: i32 = toI32(stop)
793
+ if (start > end || end > toI32(src.length)) {
794
+ return QPACK_REASON_TRUNCATED
795
+ }
796
+ d.at = end
747
797
  // `room` never passes the limit it starts at; one that did would be refused like a string past it.
748
798
  const room: i64 = d.room
749
799
  if (room < 0 || room > toI64(d.maxFieldSectionSize)) {
@@ -757,7 +807,11 @@ const qpackReadString = (d: QpackDecoder, src: u8[], huffmanBit: i32, lengthMax:
757
807
  }
758
808
  const before: i32 = toI32(d.bytes.length)
759
809
  if (huffman) {
760
- if (hpackHuffmanDecode(d.huffman, src, start, length, d.bytes) !== HPACK_OK) {
810
+ // `qpackHuffmanFits` only reads `src`, so it still holds `[start, end)`: never taken.
811
+ if (end > toI32(src.length)) {
812
+ return QPACK_REASON_TRUNCATED
813
+ }
814
+ if (hpackHuffmanDecode(d.huffman, src, start, end - start, d.bytes) !== HPACK_OK) {
761
815
  return QPACK_REASON_HUFFMAN
762
816
  }
763
817
  } else {
@@ -836,12 +890,10 @@ export class QpackDecoder {
836
890
  /**
837
891
  * Makes a decoder with no fields, no connection error and no capacity instructions counted.
838
892
  * @param maxFieldSectionSize The largest field section `decode` accepts, as RFC 9114 §4.2.2
839
- * counts it: each field's name and value in bytes plus 32. A negative limit panics.
893
+ * counts it: each field's name and value in bytes plus 32. A negative limit is kept, and every
894
+ * `decode` answers QPACK_DECOMPRESSION_FAILED for it with `QPACK_REASON_LIMIT`.
840
895
  */
841
896
  constructor(maxFieldSectionSize: i32) {
842
- if (maxFieldSectionSize < 0) {
843
- panic(`QpackDecoder: a field-section limit of ${maxFieldSectionSize}`)
844
- }
845
897
  this.huffman = new HpackHuffman()
846
898
  this.maxFieldSectionSize = maxFieldSectionSize
847
899
  this.failed = QPACK_OK
@@ -1006,6 +1058,9 @@ export class QpackDecoder {
1006
1058
  * each told apart by its first byte's pattern (§4.5.2 to §4.5.6).
1007
1059
  */
1008
1060
  private decodeLines(src: u8[]): i64 {
1061
+ if (this.maxFieldSectionSize < 0) {
1062
+ return this.refuse(QPACK_REASON_LIMIT)
1063
+ }
1009
1064
  const insertCount: i64 = qpackReadInteger(this, src, 255)
1010
1065
  if (insertCount < 0) {
1011
1066
  return this.refuseInteger(insertCount)
@@ -1251,13 +1306,24 @@ export class QpackEncoder {
1251
1306
  }
1252
1307
  }
1253
1308
  }
1309
+ // Never taken: `encodeField` checked both windows and `encodeWholeField`
1310
+ // passes whole arrays. Checked here, before the first byte goes out, so
1311
+ // a window outside its array writes no part of the field.
1312
+ if (!qpackWindowFits(name, nameOff, nameLen) || !qpackWindowFits(value, valueOff, valueLen)) {
1313
+ return
1314
+ }
1315
+ // Both lengths are read now: `out` may be `name` or `value`, and once a
1316
+ // byte is pushed the window facts no longer hold for the bounds prover.
1317
+ const nameCoded: i32 =
1318
+ nameIndex >= 0 ? 0 : qpackStringLength(this.huffman, name, nameOff, nameLen, huffman)
1319
+ const valueCoded: i32 = qpackStringLength(this.huffman, value, valueOff, valueLen, huffman)
1254
1320
  // `01 N 1` for a static name reference, `001 N` for a literal name.
1255
1321
  if (nameIndex >= 0) {
1256
1322
  qpackPushInteger(out, neverIndexed ? 112 : 80, 15, toU64(nameIndex))
1257
1323
  } else {
1258
- qpackPushString(this.huffman, out, neverIndexed ? 48 : 32, 8, 7, name, nameOff, nameLen, huffman)
1324
+ qpackPushString(this.huffman, out, neverIndexed ? 48 : 32, 8, 7, name, nameOff, nameLen, nameCoded)
1259
1325
  }
1260
- qpackPushString(this.huffman, out, 0, 128, 127, value, valueOff, valueLen, huffman)
1326
+ qpackPushString(this.huffman, out, 0, 128, 127, value, valueOff, valueLen, valueCoded)
1261
1327
  }
1262
1328
 
1263
1329
  /**
@@ -526,6 +526,8 @@ export class QuicListener {
526
526
  const mac: HmacSha256Scratch = this.kdf.sha256
527
527
  {
528
528
  using _scope = arena()
529
+ // The seed and the block are their sizes long and the pool is 32
530
+ // bytes, so none of the three answers `false`.
529
531
  mac.begin(this.seed, QUIC_LISTENER_FROM, QUIC_LISTENER_ENTROPY_SIZE)
530
532
  mac.update(this.block, QUIC_LISTENER_FROM, QUIC_LISTENER_BLOCK)
531
533
  mac.finishInto(this.pool, QUIC_LISTENER_FROM)
@@ -542,7 +544,7 @@ export class QuicListener {
542
544
  * whose arrays are refilled in their own room. Answers `answer.kind`. See
543
545
  * the module header for the rules; nothing a peer sends makes it panic,
544
546
  * and nothing it does keeps arena memory. A window outside `datagram` is
545
- * the caller's mistake, and panics.
547
+ * dropped unread, with no reply.
546
548
  *
547
549
  * @param datagram The array the datagram lies in; read, not kept.
548
550
  * @param at The index in `datagram` of its first byte.
@@ -555,17 +557,16 @@ export class QuicListener {
555
557
  * `QUIC_LISTEN_RETRY`, `QUIC_LISTEN_INVALID_TOKEN` or `QUIC_LISTEN_STATELESS_RESET`.
556
558
  */
557
559
  handleWindow(datagram: u8[], at: i32, len: i32, address: u8[], now: i64, answer: QuicListenerAnswer): i32 {
558
- // `[at, at + len)` inside `datagram`: `p256WindowFits`' test.
559
- if (at < 0 || len < 0 || at > toI32(datagram.length) - len) {
560
- panic(
561
- `QuicListener.handleWindow: the window [${at}, ${at} + ${len}) is outside a datagram of ${toI32(datagram.length)} bytes`
562
- )
563
- }
564
560
  answer.kind = QUIC_LISTEN_DROP
565
561
  answer.retried = false
566
562
  quicListenerResize(answer.reply, 0)
567
563
  quicListenerResize(answer.originalDcid, 0)
568
564
  quicListenerResize(answer.retryScid, 0)
565
+ // `[at, at + len)` inside `datagram`: `p256WindowFits`' test. Outside it,
566
+ // nothing is read and nothing is answered.
567
+ if (at < 0 || len < 0 || at > toI32(datagram.length) - len) {
568
+ return QUIC_LISTEN_DROP
569
+ }
569
570
  if (now > this.now) {
570
571
  this.now = now
571
572
  }
@@ -707,7 +708,8 @@ export class QuicListener {
707
708
  * (`scid[scidAt .. scidAt + scidLength)`) and its address, into `tag`:
708
709
  * what makes a token good for one address and one connection only. Its
709
710
  * first `QUIC_LISTENER_TOKEN_MAC_SIZE` bytes are the token's MAC; the
710
- * caller wipes `tag` once it has used them.
711
+ * caller wipes `tag` once it has used them. Answers `false`, writing
712
+ * nothing to `tag`, when a window lies outside its array.
711
713
  */
712
714
  private tokenMac(
713
715
  head: u8[],
@@ -717,24 +719,27 @@ export class QuicListener {
717
719
  scidAt: i32,
718
720
  scidLength: i32,
719
721
  address: u8[]
720
- ): void {
722
+ ): boolean {
721
723
  const mac: HmacSha256Scratch = this.kdf.sha256
722
724
  const lengths: u8[] = this.lengths
723
725
  const one: i32 = 1
724
726
  const four: i32 = 4
725
727
  quicListenerPutNumber(lengths, QUIC_LISTENER_FROM, toI64(scidLength), one)
726
728
  quicListenerPutNumber(lengths, one, toI64(toI32(address.length)), four)
729
+ let fed: boolean = false
727
730
  {
728
731
  using _scope = arena()
729
- mac.begin(this.config.retryTokenKey, QUIC_LISTENER_FROM, toI32(this.config.retryTokenKey.length))
730
- mac.update(head, headAt, headLength)
731
- mac.update(lengths, QUIC_LISTENER_FROM, one)
732
- mac.update(scid, scidAt, scidLength)
733
- mac.update(lengths, one, four)
734
- mac.update(address, QUIC_LISTENER_FROM, toI32(address.length))
735
- mac.finishInto(this.tag, QUIC_LISTENER_FROM)
732
+ fed =
733
+ mac.begin(this.config.retryTokenKey, QUIC_LISTENER_FROM, toI32(this.config.retryTokenKey.length)) &&
734
+ mac.update(head, headAt, headLength) &&
735
+ mac.update(lengths, QUIC_LISTENER_FROM, one) &&
736
+ mac.update(scid, scidAt, scidLength) &&
737
+ mac.update(lengths, one, four) &&
738
+ mac.update(address, QUIC_LISTENER_FROM, toI32(address.length))
739
+ fed = fed && mac.finishInto(this.tag, QUIC_LISTENER_FROM)
736
740
  }
737
741
  mac.wipe()
742
+ return fed
738
743
  }
739
744
 
740
745
  /**
@@ -766,7 +771,9 @@ export class QuicListener {
766
771
  if (head + QUIC_LISTENER_TOKEN_MAC_SIZE !== length) {
767
772
  return -1
768
773
  }
769
- this.tokenMac(datagram, tokenAt, head, datagram, header.dcidStart, header.dcidLength, address)
774
+ if (!this.tokenMac(datagram, tokenAt, head, datagram, header.dcidStart, header.dcidLength, address)) {
775
+ return -1
776
+ }
770
777
  const same: boolean = timingSafeEqualAt(
771
778
  this.tag,
772
779
  0,
@@ -823,7 +830,10 @@ export class QuicListener {
823
830
  quicListenerPutNumber(reply, tokenAt + 1, this.now, 8)
824
831
  quicListenerPutNumber(reply, tokenAt + QUIC_LISTENER_TOKEN_HEAD - 1, toI64(odcidLength), 1)
825
832
  quicPacketCopy(reply, tokenAt + QUIC_LISTENER_TOKEN_HEAD, datagram, header.dcidStart, odcidLength)
826
- this.tokenMac(reply, tokenAt, macAt - tokenAt, reply, retryScidAt, QUIC_CONN_CID_LENGTH, address)
833
+ if (!this.tokenMac(reply, tokenAt, macAt - tokenAt, reply, retryScidAt, QUIC_CONN_CID_LENGTH, address)) {
834
+ quicListenerResize(reply, 0)
835
+ return
836
+ }
827
837
  quicPacketCopy(reply, macAt, this.tag, 0, QUIC_LISTENER_TOKEN_MAC_SIZE)
828
838
  secureZero(this.tag)
829
839
  quicListenerPutNumber(reply, 0, toI64((this.randomByte() & 15) | 0xf0), 1)
@@ -1040,15 +1050,20 @@ export class QuicListener {
1040
1050
  if (reply.length > 0) {
1041
1051
  reply[0] = toU8((toI32(reply[0]) & 0x3f) | 0x40)
1042
1052
  }
1043
- quicConnResetTokenInto(
1044
- this.kdf.sha256,
1045
- this.config.statelessResetKey,
1046
- datagram,
1047
- dcidAt,
1048
- dcidLength,
1049
- reply,
1050
- tokenAt
1051
- )
1053
+ if (
1054
+ !quicConnResetTokenInto(
1055
+ this.kdf.sha256,
1056
+ this.config.statelessResetKey,
1057
+ datagram,
1058
+ dcidAt,
1059
+ dcidLength,
1060
+ reply,
1061
+ tokenAt
1062
+ )
1063
+ ) {
1064
+ quicListenerResize(reply, 0)
1065
+ return
1066
+ }
1052
1067
  answer.kind = QUIC_LISTEN_STATELESS_RESET
1053
1068
  }
1054
1069
  }