@amritk/nish-aarch64-linux 0.49.1 → 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 (107) hide show
  1. package/INSTALL.md +1 -1
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +237 -160
  4. package/package.json +1 -1
  5. package/runtime/gfx/nish-gfx.h +373 -61
  6. package/runtime/nish.d.ts +94 -11
  7. package/runtime/nish.h +5 -0
  8. package/runtime/runtime-host.c +21 -5
  9. package/std/README.md +14 -11
  10. package/std/base64.ts +74 -35
  11. package/std/bytes.ts +207 -97
  12. package/std/cli-args.ts +150 -107
  13. package/std/compress/checksum.ts +68 -10
  14. package/std/compress/deflate.ts +213 -115
  15. package/std/compress/gzip.ts +124 -49
  16. package/std/compress/zlib.ts +57 -15
  17. package/std/crypto/aes.ts +51 -9
  18. package/std/crypto/base64url.ts +93 -66
  19. package/std/crypto/bcrypt.ts +25 -21
  20. package/std/crypto/ed25519.ts +12 -10
  21. package/std/crypto/hkdf.ts +405 -283
  22. package/std/crypto/hmac.ts +484 -149
  23. package/std/crypto/jwt.ts +51 -40
  24. package/std/crypto/p256.ts +14 -19
  25. package/std/crypto/pki-roots.ts +35 -12
  26. package/std/crypto/pki.ts +43 -55
  27. package/std/crypto/rsa-sign.ts +1635 -0
  28. package/std/crypto/rsa.ts +26 -4
  29. package/std/crypto/sha256.ts +212 -90
  30. package/std/crypto/sha512.ts +135 -49
  31. package/std/crypto/x25519.ts +12 -11
  32. package/std/crypto/x509.ts +164 -40
  33. package/std/gpu/sys.ts +490 -0
  34. package/std/json-equal.ts +33 -18
  35. package/std/json-format.ts +39 -8
  36. package/std/json-number.ts +15 -3
  37. package/std/json-tokenizer.ts +4 -3
  38. package/std/json-typed.ts +12 -6
  39. package/std/json-value.ts +236 -119
  40. package/std/json.ts +81 -46
  41. package/std/net/buffer-pool.ts +25 -14
  42. package/std/net/dns-config.ts +18 -5
  43. package/std/net/dns-message.ts +60 -27
  44. package/std/net/dns-resolver.ts +35 -16
  45. package/std/net/dns.ts +3 -2
  46. package/std/net/fetch.ts +224 -61
  47. package/std/net/handler.ts +189 -88
  48. package/std/net/hpack.ts +216 -103
  49. package/std/net/http-compress.ts +104 -42
  50. package/std/net/http-fields.ts +327 -31
  51. package/std/net/http-server.ts +326 -24
  52. package/std/net/http1-client-codec.ts +159 -55
  53. package/std/net/http1-codec.ts +427 -237
  54. package/std/net/http1-server.ts +220 -38
  55. package/std/net/http2-cleartext.ts +10 -4
  56. package/std/net/http2-frame.ts +2 -2
  57. package/std/net/http2-tls.ts +3 -3
  58. package/std/net/http2.ts +69 -15
  59. package/std/net/http3-frame.ts +11 -14
  60. package/std/net/http3-server.ts +139 -60
  61. package/std/net/http3.ts +140 -79
  62. package/std/net/multipart.ts +592 -0
  63. package/std/net/outbound.ts +24 -8
  64. package/std/net/postgres-async.ts +97 -64
  65. package/std/net/postgres-carrier.ts +28 -4
  66. package/std/net/postgres.ts +166 -65
  67. package/std/net/prefork.ts +86 -5
  68. package/std/net/protobuf.ts +6 -2
  69. package/std/net/qpack.ts +147 -40
  70. package/std/net/quic-conn-ack.ts +27 -7
  71. package/std/net/quic-conn-cid.ts +13 -7
  72. package/std/net/quic-datagram.ts +6 -5
  73. package/std/net/quic-frame.ts +67 -23
  74. package/std/net/quic-listener.ts +61 -39
  75. package/std/net/quic-packet.ts +91 -50
  76. package/std/net/quic-recovery.ts +11 -9
  77. package/std/net/quic-stream.ts +36 -27
  78. package/std/net/quic.ts +84 -54
  79. package/std/net/router.ts +136 -24
  80. package/std/net/serve.ts +59 -5
  81. package/std/net/static.ts +86 -36
  82. package/std/net/tls/client.ts +81 -34
  83. package/std/net/tls/codec.ts +3 -4
  84. package/std/net/tls/record.ts +80 -35
  85. package/std/net/tls/schedule.ts +339 -149
  86. package/std/net/tls/ticket.ts +6 -5
  87. package/std/net/tls-tcp.ts +69 -30
  88. package/std/net/tls.ts +194 -50
  89. package/std/net/upstream.ts +83 -38
  90. package/std/net/url.ts +170 -94
  91. package/std/net/websocket.ts +19 -20
  92. package/std/net/webtransport.ts +123 -33
  93. package/std/raster.ts +12 -2
  94. package/std/regex.ts +600 -388
  95. package/std/sqlite.ts +37 -19
  96. package/std/sync/ring.ts +232 -115
  97. package/std/sync/shm.ts +11 -4
  98. package/std/temporal.ts +232 -133
  99. package/std/term-io.ts +12 -6
  100. package/std/term-pixels.ts +176 -24
  101. package/std/term-rate.ts +8 -3
  102. package/std/term.ts +4 -4
  103. package/std/text.ts +38 -16
  104. package/std/yaml-json.ts +238 -106
  105. package/std/yaml-lines.ts +47 -27
  106. package/std/yaml-write.ts +58 -24
  107. package/std/yaml.ts +808 -395
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * const pools = new QuicStreamPools(65536, 111, 64) // 64 connections of 100 + 3 + 8 slots
13
13
  * const streams = new QuicStreams(100, 3, 8, 65536, 1048576) // client bidi, client uni, own; bytes
14
- * streams.share(pools) // before any stream has borrowed
14
+ * streams.share(pools) // before any stream has borrowed; false on a size mismatch
15
15
  * streams.setPeerLimits(maxData, bidiLocal, bidiRemote, uni, maxStreamsBidi, maxStreamsUni)
16
16
  * streams.prime(packetLength) // per packet, before its frames: fills the reserve
17
17
  * const error: i64 = streams.onStream(frame.streamId, frame.offset, payload, frame.dataStart,
@@ -117,7 +117,8 @@ import {
117
117
  quicStreamOverhead,
118
118
  } from "nish/net/quic-frame"
119
119
  import { BufferPool } from "nish/net/buffer-pool"
120
- import { copyBytes } from "nish/bytes"
120
+ import { tryCopyBytes } from "nish/bytes"
121
+ import { wrappingAdd, wrappingSub } from "nish:unsafe"
121
122
 
122
123
  // ---- What the stream calls answer -----------------------------------------------
123
124
 
@@ -354,28 +355,28 @@ const quicStreamRingRun = (bits: u8[], size: i32, slot: i32, count: i32, on: boo
354
355
  /**
355
356
  * Copies `count` bytes of `src` from `from` into the ring `ring` at index `slot`, wrapping at its end: at most two slices.
356
357
  * Every caller passes `slot` from `QuicStream.at`, so below the ring's length, and a `count` of a ring at most:
357
- * `onStream` keeps a frame's last ring's worth, and `write` clamps to `room()`. So both slices are in range,
358
- * and `copyBytes` panicking on one that is not marks a broken invariant, not a byte to skip.
358
+ * `onStream` keeps a frame's last ring's worth, and `write` clamps to `room()`. So both slices are in range, and
359
+ * the `false` a slice out of range answers marks a broken invariant, which each caller turns into its internal error.
359
360
  */
360
- const quicStreamRingIn = (ring: u8[], slot: i32, src: u8[], from: i32, count: i32): void => {
361
+ const quicStreamRingIn = (ring: u8[], slot: i32, src: u8[], from: i32, count: i32): boolean => {
361
362
  const first: i32 = quicStreamFirstRun(toI32(ring.length), slot, count)
362
- copyBytes(ring, slot, src, from, first)
363
- if (count > first) {
364
- copyBytes(ring, 0, src, quicStreamAdd(from, first), quicStreamSub(count, first))
363
+ if (!tryCopyBytes(ring, slot, src, from, first)) {
364
+ return false
365
365
  }
366
+ return count <= first || tryCopyBytes(ring, 0, src, quicStreamAdd(from, first), quicStreamSub(count, first))
366
367
  }
367
368
 
368
369
  /**
369
370
  * Copies `count` bytes of the ring `ring` from index `slot`, wrapping at its end, into `dst` at `at`: at most two slices.
370
371
  * `read` passes a `count` of at most what is contiguous past `recvRead`, never more than a ring, so, as for
371
- * `quicStreamRingIn`, both slices are in range.
372
+ * `quicStreamRingIn`, both slices are in range, and `false` marks a broken invariant.
372
373
  */
373
- const quicStreamRingOut = (dst: u8[], at: i32, ring: u8[], slot: i32, count: i32): void => {
374
+ const quicStreamRingOut = (dst: u8[], at: i32, ring: u8[], slot: i32, count: i32): boolean => {
374
375
  const first: i32 = quicStreamFirstRun(toI32(ring.length), slot, count)
375
- copyBytes(dst, at, ring, slot, first)
376
- if (count > first) {
377
- copyBytes(dst, quicStreamAdd(at, first), ring, 0, quicStreamSub(count, first))
376
+ if (!tryCopyBytes(dst, at, ring, slot, first)) {
377
+ return false
378
378
  }
379
+ return count <= first || tryCopyBytes(dst, quicStreamAdd(at, first), ring, 0, quicStreamSub(count, first))
379
380
  }
380
381
 
381
382
  /** The bytes of a bitmap holding a bit for each of `bytes` bytes: `bytes` over 8, rounded up. */
@@ -408,16 +409,17 @@ const quicStreamZeros = (count: i32): i32[] => {
408
409
  }
409
410
 
410
411
  /** 2^63 − 1, the largest `i64`, which a sum past it is held at. */
411
- const quicStreamTop = (): i64 => toI64((toU64(1) << toU64(63)) - toU64(1))
412
+ const quicStreamTop = (): i64 => toI64(-1) >>> toI64(1)
412
413
 
413
414
  /**
414
415
  * `a + b`, held at 2^63 − 1 when the true sum is past it and at −2^63 when it is below. Stream
415
416
  * offsets, counts and limits are varints, below 2^62, so a held sum is one no peer can send:
416
- * a limit that is never reached. Taken in `u64`, whose `+` wraps, and read back as the `i64`
417
- * with the same bits, which is the true sum whenever that fits.
417
+ * a limit that is never reached. The wrap is how the overflow is seen, not an answer:
418
+ * `wrappingAdd` is the true sum whenever that fits, and its sign crosses only when it does
419
+ * not, which is held instead.
418
420
  */
419
421
  const quicStreamSum = (a: i64, b: i64): i64 => {
420
- const sum: i64 = toI64(toU64(a) + toU64(b))
422
+ const sum: i64 = wrappingAdd(a, b)
421
423
  if (a >= 0 && b >= 0 && sum < 0) {
422
424
  return quicStreamTop()
423
425
  }
@@ -429,7 +431,7 @@ const quicStreamSum = (a: i64, b: i64): i64 => {
429
431
 
430
432
  /** `a − b`, held at 2^63 − 1 / −2^63 where the true difference passes either, as `quicStreamSum` holds a sum. */
431
433
  const quicStreamLess = (a: i64, b: i64): i64 => {
432
- const diff: i64 = toI64(toU64(a) - toU64(b))
434
+ const diff: i64 = wrappingSub(a, b)
433
435
  if (a >= 0 && b < 0 && diff < 0) {
434
436
  return quicStreamTop()
435
437
  }
@@ -1152,19 +1154,20 @@ export class QuicStreams {
1152
1154
  /**
1153
1155
  * Borrows the stream buffers from `pools` from now on, in place of the
1154
1156
  * table's own: how a server's connections share one set. Call it before
1155
- * any stream has borrowed, or after `reset`. Panics when the pools' buffers
1156
- * are not `bufferSize` bytes.
1157
+ * any stream has borrowed, or after `reset`. Pools whose buffers are not
1158
+ * `bufferSize` bytes are refused: the table keeps the pools it had and
1159
+ * answers `false`.
1157
1160
  *
1158
1161
  * @param pools The pools to borrow from, kept by reference; usually shared with other connections.
1162
+ * @returns `true` when the table borrows from `pools` from now on, `false` when their buffer size differs.
1159
1163
  */
1160
- share(pools: QuicStreamPools): void {
1164
+ share(pools: QuicStreamPools): boolean {
1161
1165
  if (pools.data.size !== this.bufferSize) {
1162
- panic(
1163
- `QuicStreams: pools of ${pools.data.size}-byte buffers shared with streams of ${this.bufferSize} bytes`
1164
- )
1166
+ return false
1165
1167
  }
1166
1168
  this.giveBack()
1167
1169
  this.pools = pools
1170
+ return true
1168
1171
  }
1169
1172
 
1170
1173
  /**
@@ -1837,7 +1840,9 @@ export class QuicStreams {
1837
1840
  if (low >= 0 && low < high) {
1838
1841
  const slot: i32 = stream.at(quicStreamSum(offset, toI64(low)))
1839
1842
  // `from + low` is at most `from + length`, inside `buf`: exact.
1840
- quicStreamRingIn(stream.recvBuf, slot, buf, quicStreamAdd(from, low), high - low)
1843
+ if (!quicStreamRingIn(stream.recvBuf, slot, buf, quicStreamAdd(from, low), high - low)) {
1844
+ return QUIC_ERROR_INTERNAL
1845
+ }
1841
1846
  quicStreamMarkRing(stream.recvHave, size, slot, high - low, true)
1842
1847
  }
1843
1848
  if (contiguous < highest) {
@@ -2085,7 +2090,9 @@ export class QuicStreams {
2085
2090
  }
2086
2091
  // No buffer (length 0) is the one way this fails: a pool buffer is always `bufferSize` bytes.
2087
2092
  if (n > 0 && toI32(stream.sendBuf.length) === stream.size) {
2088
- quicStreamRingIn(stream.sendBuf, stream.at(stream.sendEnd), buf, from, n)
2093
+ if (!quicStreamRingIn(stream.sendBuf, stream.at(stream.sendEnd), buf, from, n)) {
2094
+ return QUIC_STREAM_ERR_UNKNOWN
2095
+ }
2089
2096
  }
2090
2097
  stream.sendEnd = quicStreamSum(stream.sendEnd, toI64(n))
2091
2098
  this.writtenTotal = quicStreamSum(this.writtenTotal, toI64(n))
@@ -2142,7 +2149,9 @@ export class QuicStreams {
2142
2149
  // With bytes owed, the buffer is held (the test above), and a held buffer is `bufferSize` bytes.
2143
2150
  if (n > 0 && size === stream.size) {
2144
2151
  const slot: i32 = stream.at(stream.recvRead)
2145
- quicStreamRingOut(buf, at, stream.recvBuf, slot, n)
2152
+ if (!quicStreamRingOut(buf, at, stream.recvBuf, slot, n)) {
2153
+ return QUIC_STREAM_ERR_UNKNOWN
2154
+ }
2146
2155
  quicStreamMarkRing(stream.recvHave, size, slot, n, false)
2147
2156
  }
2148
2157
  stream.recvRead = quicStreamSum(stream.recvRead, toI64(n))
package/std/net/quic.ts CHANGED
@@ -7,13 +7,14 @@
7
7
  * Sans-IO, like the rest of `nish/net`.
8
8
  *
9
9
  * import { QuicConnection, QuicServerConfig } from "nish/net/quic";
10
- * import { tlsSignEcdsaP256 } from "nish/net/tls";
10
+ * import { TlsKeySigner } from "nish/net/tls";
11
11
  *
12
+ * const signer = new TlsKeySigner(config.signatureScheme); // config: QuicServerConfig; P-256 or RSA-PSS
12
13
  * const conn = new QuicConnection(config, entropy); // entropy: QUIC_CONN_ENTROPY_SIZE random bytes
13
14
  * conn.receiveWindow(buf, off, len, now); // every datagram the client sends; now in ms
14
15
  * const input: u8[] | null = conn.signatureInput();
15
16
  * if (input !== null) {
16
- * const signature: u8[] | null = tlsSignEcdsaP256(key, input); // key: Secret<u8[]>
17
+ * const signature: u8[] | null = signer.sign(key, input); // key: Secret<u8[]>, the leaf's own key
17
18
  * if (signature !== null) { conn.sign(signature); }
18
19
  * }
19
20
  * let n: i32 = conn.takeDatagramInto(out, 0, now); // out: at least QUIC_CONN_DATAGRAM_SIZE bytes
@@ -361,6 +362,7 @@ import {
361
362
  } from "nish/net/tls"
362
363
  import { TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256 } from "nish/net/tls/schedule"
363
364
  import { Secret, expose, exposeWith, secret, wipe } from "nish:secret"
365
+ import { wrappingAdd } from "nish:unsafe"
364
366
 
365
367
  // ---- Sizes ----------------------------------------------------------------------
366
368
 
@@ -680,20 +682,38 @@ export interface QuicServerConfig {
680
682
  }
681
683
 
682
684
  /**
683
- * Panics, with the pair in the message, unless `config`'s worker fields are
684
- * both unset (`workerIndex` -1 and `workerCount` 0) or name a worker of a
685
- * steered group (0 <= k < N <= 255). `QuicListener` calls it when it is built,
686
- * before it reads a datagram, so an `Http3Server` panics through its listener.
685
+ * Why `config`'s worker fields are not a pair a server can run under, or ""
686
+ * when they are both unset (`workerIndex` -1 and `workerCount` 0) or name a
687
+ * worker of a steered group (0 <= k < N <= 255). A caller that ran it and
688
+ * left on a fault has made `quicWorkerCheck`'s check (the fault contract,
689
+ * `src/fault-contract.ts`).
687
690
  *
688
- * @param config The configuration whose `workerIndex` and `workerCount` are checked.
691
+ * @param config The configuration whose `workerIndex` and `workerCount` are read.
692
+ * @returns "" for a valid pair, else the message naming it.
689
693
  */
690
- export const quicWorkerCheck = (config: QuicServerConfig): void => {
694
+ export const quicWorkerFault = (config: QuicServerConfig): string => {
691
695
  const k: i32 = config.workerIndex
692
696
  const n: i32 = config.workerCount
693
697
  if ((k === -1 && n === 0) || (k >= 0 && k < n && n <= QUIC_WORKER_MAX)) {
694
- return
698
+ return ""
699
+ }
700
+ return `nish/net/quic: workerIndex ${k} and workerCount ${n}, not 0 <= k < n <= ${QUIC_WORKER_MAX}`
701
+ }
702
+
703
+ /**
704
+ * Panics, with the pair in the message, when `quicWorkerFault` finds one.
705
+ * `QuicListener` calls it when it is built, before it reads a datagram, so
706
+ * an `Http3Server` panics through its listener; a caller that ran
707
+ * `quicWorkerFault` on the same configuration and left on a fault has
708
+ * proved it cannot.
709
+ *
710
+ * @param config The configuration whose `workerIndex` and `workerCount` are checked.
711
+ */
712
+ export const quicWorkerCheck = (config: QuicServerConfig): void => {
713
+ const fault: string = quicWorkerFault(config)
714
+ if (fault.length > 0) {
715
+ panic(fault)
695
716
  }
696
- panic(`nish/net/quic: workerIndex ${k} and workerCount ${n}, not 0 <= k < n <= ${QUIC_WORKER_MAX}`)
697
717
  }
698
718
 
699
719
  /**
@@ -875,9 +895,9 @@ class QuicConnReassembly {
875
895
  for (let s: i32 = start; s < capacity && s - start < n; s += 1) {
876
896
  this.mark(s, false)
877
897
  }
878
- // Exact: `delivered` only moves past bytes that arrived, below 2^62 + the ring, and `n` is at
879
- // most the ring's size, so the sum is far below 2^63 and the u64 add cannot wrap.
880
- this.delivered = toI64(toU64(this.delivered) + toU64(n))
898
+ // `delivered` only moves past bytes that arrived, below 2^62 + the ring, and `n` is at most the
899
+ // ring's size, so the sum is far below 2^63 and `quicConnSum` never holds it at the cap.
900
+ this.delivered = quicConnSum(this.delivered, toI64(n))
881
901
  }
882
902
  }
883
903
 
@@ -1290,8 +1310,8 @@ class QuicConnSpace {
1290
1310
  // Never taken: a CRYPTO offset is a varint.
1291
1311
  return
1292
1312
  }
1293
- // Exact: `offset` is a varint, below 2^62, and `length` an `i32`, so the u64 sum cannot wrap.
1294
- const end: i64 = toI64(toU64(offset) + toU64(length))
1313
+ // `offset` is a varint, below 2^62, and `length` an `i32`, so the sum is exact.
1314
+ const end: i64 = quicConnSum(offset, toI64(length))
1295
1315
  if (this.cryptoResendLow < 0) {
1296
1316
  this.cryptoResendLow = offset
1297
1317
  this.cryptoResendHigh = end
@@ -1422,6 +1442,8 @@ export const quicStatelessResetToken = (key: u8[], cid: u8[]): u8[] => {
1422
1442
  * @param length The ID's length in bytes, at most 20: the caller's to keep, as nothing checks it.
1423
1443
  * @param out Where the 16-byte token goes; bytes that would fall past its end are not written.
1424
1444
  * @param outAt Where in `out` the token starts.
1445
+ * @returns `true` once the token is written; `false`, writing nothing, when
1446
+ * `cid[at .. at + length)` lies outside `cid`.
1425
1447
  */
1426
1448
  export const quicConnResetTokenInto = (
1427
1449
  mac: HmacSha256Scratch,
@@ -1431,12 +1453,17 @@ export const quicConnResetTokenInto = (
1431
1453
  length: i32,
1432
1454
  out: u8[],
1433
1455
  outAt: i32
1434
- ): void => {
1456
+ ): boolean => {
1435
1457
  using _scope = arena()
1436
1458
  const tag: u8[] = new Array<u8>(32)
1437
- mac.begin(key, QUIC_CONN_FROM, toI32(key.length))
1438
- mac.update(cid, at, length)
1439
- mac.finishInto(tag, QUIC_CONN_FROM)
1459
+ if (
1460
+ !mac.begin(key, QUIC_CONN_FROM, toI32(key.length)) ||
1461
+ !mac.update(cid, at, length) ||
1462
+ !mac.finishInto(tag, QUIC_CONN_FROM)
1463
+ ) {
1464
+ mac.wipe()
1465
+ return false
1466
+ }
1440
1467
  for (let k: i32 = 0; k < QUIC_RESET_TOKEN_SIZE && k < toI32(tag.length); k += 1) {
1441
1468
  const i: i32 = quicConnAt(outAt, k, toI32(out.length))
1442
1469
  if (i < 0 || i >= toI32(out.length)) {
@@ -1446,6 +1473,7 @@ export const quicConnResetTokenInto = (
1446
1473
  }
1447
1474
  secureZero(tag)
1448
1475
  mac.wipe()
1476
+ return true
1449
1477
  }
1450
1478
 
1451
1479
  /** `base + k` when it indexes an array of `length` elements, else -1; the sum is taken in `i64`, so it cannot overflow. */
@@ -1455,36 +1483,33 @@ const quicConnAt = (base: i32, k: i32, length: i32): i32 => {
1455
1483
  }
1456
1484
 
1457
1485
  /**
1458
- * A new array of `count` zero bytes: none for a count of 0 or less. A count
1459
- * that fits a `u16` is sized at once; a larger one is pushed byte by byte,
1460
- * so no `i32` length is computed for `new Array`.
1486
+ * A new array of `count` zero bytes: none for a count of 0 or less, or for
1487
+ * one past an `i32`, which no array can hold. One allocation, its length
1488
+ * proven by the guards.
1461
1489
  */
1462
1490
  const quicConnBytes = (count: i64): u8[] => {
1463
- if (count <= 0) {
1491
+ if (count <= 0 || count > 2147483647) {
1464
1492
  return []
1465
1493
  }
1466
- if (count <= 65535) {
1467
- return new Array<u8>(toU16(count))
1468
- }
1469
- const out: u8[] = []
1470
- while (toI64(out.length) < count) {
1471
- out.push(toU8(0))
1494
+ const n: i32 = toI32(count)
1495
+ if (n <= 0) {
1496
+ return []
1472
1497
  }
1473
- return out
1498
+ return new Array<u8>(n)
1474
1499
  }
1475
1500
 
1476
1501
  /**
1477
1502
  * `a + b`, stopping at the largest or smallest `i64` instead of wrapping. Its
1478
1503
  * callers add a span to a time in milliseconds or a datagram's size to a byte
1479
1504
  * count, which are never near either end, so the sum is exact on every path a
1480
- * connection takes. The add is done in `u64`, where it wraps to the same bits
1481
- * as an exact two's-complement sum, and a wrap shows as a sign the operands
1482
- * did not have.
1505
+ * connection takes. The add is a `wrappingAdd` because the wrap is how an
1506
+ * overflow is seen, as a sign the operands did not have; the answer is then
1507
+ * the cap, never the wrapped value.
1483
1508
  */
1484
1509
  const quicConnSum = (a: i64, b: i64): i64 => {
1485
- const sum: i64 = toI64(toU64(a) + toU64(b))
1510
+ const sum: i64 = wrappingAdd(a, b)
1486
1511
  if (a >= 0 && b >= 0 && sum < 0) {
1487
- return toI64((toU64(1) << toU64(63)) - toU64(1))
1512
+ return toI64(-1) >>> toI64(1)
1488
1513
  }
1489
1514
  if (a < 0 && b < 0 && sum >= 0) {
1490
1515
  return toI64(toU64(1) << toU64(63))
@@ -1511,11 +1536,14 @@ const quicConnRingAt = (index: i64, entries: i32): i32 => {
1511
1536
 
1512
1537
  /**
1513
1538
  * `received * 3 - sent`, what the anti-amplification limit (RFC 9000 §8.1)
1514
- * leaves a path. Byte counts are never near the ends of `i64`, so the
1515
- * arithmetic, done in `u64` where it wraps to the bits of the exact result,
1516
- * is exact.
1539
+ * leaves a path, each step held at the ends of `i64` by `quicConnSum`. Byte
1540
+ * counts are never near those ends, so the answer is exact on every path a
1541
+ * connection takes; a `sent` below 0, which no count holds, subtracts nothing.
1517
1542
  */
1518
- const quicConnThrice = (received: i64, sent: i64): i64 => toI64(toU64(received) * toU64(3) - toU64(sent))
1543
+ const quicConnThrice = (received: i64, sent: i64): i64 => {
1544
+ const tripled: i64 = quicConnSum(quicConnSum(received, received), received)
1545
+ return sent > 0 ? quicConnSum(tripled, 0 - sent) : tripled
1546
+ }
1519
1547
 
1520
1548
  /** Puts `from[at .. at + length)` in `to`, emptied first, in the room `to` already has. */
1521
1549
  const quicConnRefill = (to: u8[], from: u8[], at: i32, length: i32): void => {
@@ -3743,12 +3771,11 @@ export class QuicConnection {
3743
3771
  }
3744
3772
  let matched: boolean = false
3745
3773
  for (let m: i32 = 0; m < this.challengeCount; m += 1) {
3746
- // At most `challengesDrawn` challenges are kept, so the index, taken
3747
- // in `u64` where it is exact, is never negative.
3748
- const base: i32 = quicConnRingAt(
3749
- toI64(toU64(this.challengesDrawn) - toU64(1) - toU64(m)),
3750
- QUIC_CONN_CHALLENGES
3751
- )
3774
+ // At most `challengesDrawn` challenges are kept, so the index is never
3775
+ // negative; were it, `quicConnRingAt` answers -1 and the slot is skipped.
3776
+ const drawn: i64 = this.challengesDrawn
3777
+ const last: i64 = drawn >= 1 ? drawn - 1 : -1
3778
+ const base: i32 = quicConnRingAt(last >= 0 ? last - toI64(m) : -1, QUIC_CONN_CHALLENGES)
3752
3779
  if (base < 0) {
3753
3780
  continue
3754
3781
  }
@@ -3936,6 +3963,8 @@ export class QuicConnection {
3936
3963
  counter[k] = toU8(toI32((sequence >> (toI64(7 - k) * 8)) & 255))
3937
3964
  }
3938
3965
  const tag: u8[] = new Array<u8>(32)
3966
+ // Every window is a whole array (the seed, the 8-byte counter, the
3967
+ // 32-byte tag), so none of the three answers `false`.
3939
3968
  mac.begin(this.cidSeed, QUIC_CONN_FROM, toI32(this.cidSeed.length))
3940
3969
  mac.update(counter, QUIC_CONN_FROM, toI32(counter.length))
3941
3970
  mac.finishInto(tag, QUIC_CONN_FROM)
@@ -4490,9 +4519,11 @@ export class QuicConnection {
4490
4519
  using _scope = arena()
4491
4520
  n = this.buildProbe(out, at, size)
4492
4521
  }
4493
- // Both are byte counts far from the ends of `i64`, so the `u64`
4494
- // difference is exact.
4495
- this.probeBudget = toI64(toU64(this.probeBudget) - toU64(n))
4522
+ // Both are byte counts far from the ends of `i64`, so the difference is
4523
+ // exact; a negative `n`, no bytes built, spends nothing.
4524
+ if (n > 0) {
4525
+ this.probeBudget = quicConnSum(this.probeBudget, toI64(0 - n))
4526
+ }
4496
4527
  return n
4497
4528
  }
4498
4529
 
@@ -5037,9 +5068,8 @@ export class QuicConnection {
5037
5068
  */
5038
5069
  private beforeDatagram(): void {
5039
5070
  const limit: i64 = this.confidentialityLimit
5040
- // The limit is a positive count far from the ends of `i64`, so the
5041
- // `u64` difference is exact.
5042
- if (this.sealedUnderKey >= toI64(toU64(limit) - toU64(limit / 4))) {
5071
+ // The limit is a positive count, so three quarters of it is a proven difference.
5072
+ if (limit >= 0 && this.sealedUnderKey >= limit - limit / 4) {
5043
5073
  this.updateKeys()
5044
5074
  }
5045
5075
  const pn: i64 = this.application.nextPn
@@ -5248,11 +5278,11 @@ export class QuicConnection {
5248
5278
  if (low >= 0) {
5249
5279
  const high: i64 = space.cryptoResendHigh
5250
5280
  // A resend range is never empty while it is kept, so this is never taken.
5251
- if (high < low) {
5281
+ if (high < low || high < 0) {
5252
5282
  return at
5253
5283
  }
5254
- // `high` is at least `low`, so the `u64` difference is exact.
5255
- const want: i32 = toI32(toI64(toU64(high) - toU64(low)))
5284
+ // `high` is at least `low`, which is 0 or more, so the difference is exact.
5285
+ const want: i32 = toI32(high - low)
5256
5286
  const left: i32 = toI32(toI64(end) - toI64(at) - toI64(quicCryptoOverhead(low, want)))
5257
5287
  const n: i32 = left < want ? left : want
5258
5288
  if (n <= 0) {