nish 0.42.0 → 0.45.1

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 (125) hide show
  1. package/README.md +11 -5
  2. package/docs/AI.md +287 -129
  3. package/package.json +9 -9
  4. package/runtime/core/numbers.mjs +3 -1
  5. package/runtime/core/strings.mjs +90 -38
  6. package/runtime/core.d.ts +24 -0
  7. package/runtime/core.mjs +21 -0
  8. package/runtime/nish.d.ts +167 -24
  9. package/runtime/nish.mjs +7 -1
  10. package/runtime/runtime-cross.c +9 -0
  11. package/runtime/runtime-net.c +51 -13
  12. package/runtime/runtime-region.c +13 -0
  13. package/runtime/runtime-text.c +11 -0
  14. package/runtime/runtime-uring.c +83 -25
  15. package/runtime/runtime-wasm.c +3 -0
  16. package/runtime/runtime.c +329 -6
  17. package/runtime/sqlite/README.md +16 -3
  18. package/runtime/sqlite/nish-sqlite.c +940 -29
  19. package/scripts/build.sh +111 -29
  20. package/skills/writing-nish/SKILL.md +12 -4
  21. package/std/README.md +6 -6
  22. package/std/array.ts +10 -2
  23. package/std/bytes.ts +239 -26
  24. package/std/cli-args.ts +1072 -606
  25. package/std/cli-flags.ts +180 -98
  26. package/std/cli.ts +21 -13
  27. package/std/collections.ts +245 -127
  28. package/std/compress/checksum.ts +32 -37
  29. package/std/compress/deflate.ts +1102 -542
  30. package/std/compress/gzip.ts +290 -145
  31. package/std/compress/zlib.ts +57 -21
  32. package/std/crypto/aes.ts +153 -75
  33. package/std/crypto/base64url.ts +163 -39
  34. package/std/crypto/bcrypt-batch.ts +164 -90
  35. package/std/crypto/bcrypt.ts +185 -107
  36. package/std/crypto/chacha20poly1305.ts +84 -68
  37. package/std/crypto/ct.ts +9 -7
  38. package/std/crypto/ed25519.ts +64 -27
  39. package/std/crypto/hkdf.ts +105 -63
  40. package/std/crypto/hmac.ts +95 -89
  41. package/std/crypto/jwt.ts +248 -126
  42. package/std/crypto/p256.ts +758 -444
  43. package/std/crypto/p384.ts +20 -13
  44. package/std/crypto/pki-roots.ts +95 -38
  45. package/std/crypto/pki.ts +164 -60
  46. package/std/crypto/rsa.ts +266 -223
  47. package/std/crypto/scram.ts +141 -0
  48. package/std/crypto/sha1.ts +157 -57
  49. package/std/crypto/sha256.ts +502 -422
  50. package/std/crypto/sha512.ts +204 -135
  51. package/std/crypto/x509-random.ts +9 -3
  52. package/std/crypto/x509.ts +331 -171
  53. package/std/host/ring.ts +1 -1
  54. package/std/host/text.ts +1 -1
  55. package/std/json-equal.ts +35 -19
  56. package/std/json-format.ts +215 -108
  57. package/std/json-number.ts +126 -72
  58. package/std/json-pointer.ts +42 -13
  59. package/std/json-tokenizer.ts +498 -307
  60. package/std/json-typed.ts +115 -36
  61. package/std/json-value.ts +341 -152
  62. package/std/json.ts +300 -158
  63. package/std/net/buffer-pool.ts +17 -7
  64. package/std/net/dns-config.ts +427 -236
  65. package/std/net/dns-message.ts +114 -47
  66. package/std/net/dns-resolver.ts +736 -237
  67. package/std/net/dns.ts +205 -52
  68. package/std/net/fetch.ts +320 -184
  69. package/std/net/grpc.ts +948 -0
  70. package/std/net/handler.ts +1276 -218
  71. package/std/net/hpack.ts +395 -180
  72. package/std/net/http-compress.ts +502 -65
  73. package/std/net/http-fields.ts +85 -49
  74. package/std/net/http-server.ts +1764 -603
  75. package/std/net/http1-client-codec.ts +372 -161
  76. package/std/net/http1-codec.ts +665 -331
  77. package/std/net/http1-server.ts +881 -269
  78. package/std/net/http2-cleartext.ts +165 -95
  79. package/std/net/http2-frame.ts +232 -89
  80. package/std/net/http2-tls.ts +42 -12
  81. package/std/net/http2.ts +327 -101
  82. package/std/net/http3-frame.ts +68 -33
  83. package/std/net/http3-server.ts +672 -206
  84. package/std/net/http3.ts +669 -191
  85. package/std/net/oidc.ts +63 -24
  86. package/std/net/outbound.ts +207 -142
  87. package/std/net/postgres-async.ts +1223 -470
  88. package/std/net/postgres-carrier.ts +575 -372
  89. package/std/net/postgres.ts +1521 -632
  90. package/std/net/prefork.ts +254 -98
  91. package/std/net/protobuf.ts +1017 -0
  92. package/std/net/qpack.ts +143 -92
  93. package/std/net/quic-conn-ack.ts +104 -22
  94. package/std/net/quic-conn-cid.ts +66 -26
  95. package/std/net/quic-conn-params.ts +13 -7
  96. package/std/net/quic-datagram.ts +90 -27
  97. package/std/net/quic-frame.ts +324 -121
  98. package/std/net/quic-listener.ts +206 -91
  99. package/std/net/quic-packet.ts +289 -163
  100. package/std/net/quic-recovery.ts +279 -128
  101. package/std/net/quic-stream.ts +466 -167
  102. package/std/net/quic.ts +584 -258
  103. package/std/net/router.ts +450 -99
  104. package/std/net/serve.ts +661 -240
  105. package/std/net/static.ts +1458 -0
  106. package/std/net/tls/client.ts +140 -45
  107. package/std/net/tls/codec.ts +510 -260
  108. package/std/net/tls/record-client.ts +268 -76
  109. package/std/net/tls/record-server.ts +236 -79
  110. package/std/net/tls/record.ts +173 -47
  111. package/std/net/tls/schedule.ts +58 -39
  112. package/std/net/tls/ticket.ts +295 -103
  113. package/std/net/tls/verify.ts +1 -1
  114. package/std/net/tls-tcp.ts +218 -75
  115. package/std/net/tls.ts +260 -152
  116. package/std/net/upstream.ts +283 -86
  117. package/std/net/url.ts +277 -102
  118. package/std/net/websocket.ts +532 -209
  119. package/std/net/webtransport.ts +755 -436
  120. package/std/regex.ts +1659 -829
  121. package/std/sqlite.ts +325 -0
  122. package/std/sync/ring.ts +320 -156
  123. package/std/sync/shm.ts +53 -6
  124. package/std/text.ts +285 -135
  125. package/std/threads.ts +22 -2
@@ -9,7 +9,11 @@
9
9
  * writes the 101 that accepts it, with `Sec-WebSocket-Accept` from
10
10
  * `websocketAcceptKey` (§4.2.2): the base64 of the SHA-1 of the key and a
11
11
  * fixed GUID. `websocketOriginAllowed(parser, allowed)` is the opt-in check
12
- * of `Origin` a server makes first, against a page on another site. What `HTTP1_UPGRADE`'s `upgradeBytes()` answers is the first
12
+ * of `Origin` a server makes first, against a page on another site. A server
13
+ * that accepts handshake after handshake keeps a `WsAcceptKey` and writes the
14
+ * 101 into its output with `websocketRequestKeyField` and
15
+ * `websocketWriteUpgradeResponse`, allocating nothing per handshake, as
16
+ * `Http1Connection.acceptWebSocket` does. What `HTTP1_UPGRADE`'s `upgradeBytes()` answers is the first
13
17
  * input for the decoder.
14
18
  *
15
19
  * **The client's handshake** (§4.1). `websocketClientKey(nonce)` spells 16
@@ -70,14 +74,15 @@
70
74
  *
71
75
  * Written from RFC 6455, not ported from another implementation.
72
76
  */
73
- import { base64StdPadEncode, base64urlDecode } from "nish/crypto/base64url"
74
- import { sha1 } from "nish/crypto/sha1"
77
+ import { base64StdPadDecodedLength, base64StdPadEncode, base64StdPadEncodeInto } from "nish/crypto/base64url"
78
+ import { SHA1_SIZE, Sha1 } from "nish/crypto/sha1"
79
+ import { tryCopyBytes } from "nish/bytes"
75
80
  import {
76
- HTTP1_NO_BODY,
81
+ HTTP1_NO_ROOM,
82
+ HTTP1_REFUSED,
77
83
  Http1Parser,
78
84
  http1IsOws,
79
85
  http1IsToken,
80
- http1ResponseHead,
81
86
  http1SameWord,
82
87
  http1Text,
83
88
  } from "nish/net/http1-codec"
@@ -174,6 +179,35 @@ const websocketIsKnownOpcode = (opcode: i32): boolean =>
174
179
  */
175
180
  const WS_CONTINUE: i32 = -1
176
181
 
182
+ /**
183
+ * `a + b`, worked in `i64` and held to `i32`. Every caller adds an offset
184
+ * and a length that lie inside one array, so the sum is an index into it or
185
+ * just past it and always fits.
186
+ */
187
+ const websocketAdd = (a: i32, b: i32): i32 => toI32(toI64(a) + toI64(b))
188
+
189
+ /** `a - b`, worked as `websocketAdd` is, for offsets inside one array. */
190
+ const websocketSub = (a: i32, b: i32): i32 => toI32(toI64(a) - toI64(b))
191
+
192
+ /**
193
+ * A zeroed array of `n` bytes, or of none when `n` is below zero. Up to
194
+ * 65535 bytes is one allocation; past that the array grows a byte at a time
195
+ * from a 65535-byte start, which an `i32` length cannot make fail.
196
+ */
197
+ const websocketBytes = (n: i32): u8[] => {
198
+ if (n < 0) {
199
+ return []
200
+ }
201
+ if (n <= 65535) {
202
+ return new Array<u8>(toU16(n))
203
+ }
204
+ const out: u8[] = new Array<u8>(65535)
205
+ for (let k: i32 = 65535; k < n; k += 1) {
206
+ out.push(0)
207
+ }
208
+ return out
209
+ }
210
+
177
211
  /**
178
212
  * Runs `buf[off .. off + len)` through the check `state` holds. Answers false
179
213
  * at the first byte that cannot continue well-formed UTF-8 (RFC 3629 §4: no
@@ -185,7 +219,8 @@ const websocketUtf8Run = (state: WsUtf8, buf: u8[], off: i32, len: i32): boolean
185
219
  let need: i32 = state.need
186
220
  let lo: i32 = state.lo
187
221
  let hi: i32 = state.hi
188
- for (let k: i32 = off; k >= 0 && k < off + len && k < toI32(buf.length); k += 1) {
222
+ const stop: i64 = toI64(off) + toI64(len)
223
+ for (let k: i32 = off; k >= 0 && toI64(k) < stop && k < toI32(buf.length); k += 1) {
189
224
  const b: i32 = toI32(buf[k])
190
225
  if (need > 0) {
191
226
  if (b < lo || b > hi) {
@@ -323,22 +358,12 @@ export class WsDecoder {
323
358
  if (this.state !== WS_S_FRAMES) {
324
359
  return
325
360
  }
326
- websocketReserve(this, len)
327
- const buf: u8[] = this.buf
328
- const at: i32 = this.end
329
- // A whole array is one `set`; `set` takes no window of its source.
330
- if (off === 0 && len === size) {
331
- buf.set(data, at)
332
- this.end = at + len
361
+ // More than 2^31 - 1 bytes waiting is more than any message.
362
+ if (!websocketReserve(this, len) || !tryCopyBytes(this.buf, this.end, data, off, len)) {
363
+ websocketFail(this, WS_CLOSE_TOO_BIG, "more than 2^31 - 1 bytes of input waiting")
333
364
  return
334
365
  }
335
- for (let k: i32 = 0; k < len; k += 1) {
336
- const to: i32 = at + k
337
- if (to >= 0 && to < toI32(buf.length)) {
338
- buf[to] = data[off + k]
339
- }
340
- }
341
- this.end = at + len
366
+ this.end = websocketAdd(this.end, len)
342
367
  }
343
368
 
344
369
  /**
@@ -370,29 +395,48 @@ export class WsDecoder {
370
395
  }
371
396
  }
372
397
 
373
- /** Makes room for `len` more input bytes at `d.end`, moving the live bytes down first. */
374
- const websocketReserve = (d: WsDecoder, len: i32): void => {
398
+ /**
399
+ * Makes room for `len` more input bytes at `d.end`, moving the live bytes
400
+ * down first. Answers false, changing nothing, when the live bytes and `len`
401
+ * together pass 2^31 - 1.
402
+ */
403
+ const websocketReserve = (d: WsDecoder, len: i32): boolean => {
375
404
  const old: u8[] = d.buf
376
405
  const capacity: i32 = toI32(old.length)
377
- if (len <= capacity - d.end) {
378
- return
406
+ const start: i32 = d.start
407
+ const end: i32 = d.end
408
+ if (len < 0 || start < 0 || end < 0 || end < start) {
409
+ return false
379
410
  }
380
- const live: i32 = d.end - d.start
411
+ if (len <= capacity - end) {
412
+ return true
413
+ }
414
+ const live: i32 = end - start
415
+ if (toI64(len) > toI64(2147483647) - toI64(live)) {
416
+ return false
417
+ }
418
+ const need: i32 = websocketAdd(live, len)
419
+ // Room enough moves the live bytes down in place; otherwise the buffer
420
+ // at least doubles.
381
421
  let size: i32 = capacity
382
- while (size - live < len) {
383
- if (size > 1073741823) {
384
- panic("WsDecoder: more than 2^31 - 1 bytes buffered")
422
+ if (need > capacity) {
423
+ if (capacity > 1073741823) {
424
+ size = 2147483647
425
+ } else {
426
+ size = capacity * 2
427
+ }
428
+ if (size < need) {
429
+ size = need
385
430
  }
386
- size = size * 2
387
431
  }
388
- const buf: u8[] = size === capacity ? old : new Array<u8>(size)
389
- const from: i32 = d.start
390
- for (let k: i32 = 0; k < live && k < toI32(buf.length); k += 1) {
391
- buf[k] = old[from + k]
432
+ const buf: u8[] = size === capacity ? old : websocketBytes(size)
433
+ if (!tryCopyBytes(buf, 0, old, start, live)) {
434
+ return false
392
435
  }
393
436
  d.buf = buf
394
437
  d.start = 0
395
438
  d.end = live
439
+ return true
396
440
  }
397
441
 
398
442
  /** Refuses the input; the connection is to be closed with `code`. Answers `WS_ERROR`. */
@@ -409,6 +453,7 @@ const websocketFail = (d: WsDecoder, code: i32, reason: string): i32 => {
409
453
  * unmasking it with the key at `buf[maskAt .. maskAt + 4)` when `masked`
410
454
  * (§5.3: byte i is XORed with key byte i mod 4). `phase` is how far into the
411
455
  * payload `from` is, so a payload can be unmasked a piece at a time.
456
+ * Answers false, writing nothing, when a window lies outside its array.
412
457
  */
413
458
  const websocketUnmaskInto = (
414
459
  buf: u8[],
@@ -419,24 +464,37 @@ const websocketUnmaskInto = (
419
464
  phase: i32,
420
465
  to: u8[],
421
466
  at: i32
422
- ): void => {
467
+ ): boolean => {
468
+ if (!masked) {
469
+ return tryCopyBytes(to, at, buf, from, len)
470
+ }
471
+ const bufLength: i32 = toI32(buf.length)
472
+ const toLength: i32 = toI32(to.length)
473
+ if (len < 0 || from < 0 || at < 0 || from > bufLength - len || at > toLength - len) {
474
+ return false
475
+ }
476
+ if (maskAt < 0 || maskAt >= bufLength - 3) {
477
+ return false
478
+ }
423
479
  // The four key bytes in one word, high byte first, rotated a byte left
424
480
  // after each payload byte, so its top byte is always key byte k mod 4.
425
- let key: u32 = 0
426
- if (masked) {
427
- key =
428
- (toU32(buf[maskAt]) << 24) |
429
- (toU32(buf[maskAt + 1]) << 16) |
430
- (toU32(buf[maskAt + 2]) << 8) |
431
- toU32(buf[maskAt + 3])
432
- }
481
+ let key: u32 =
482
+ (toU32(buf[maskAt]) << 24) |
483
+ (toU32(buf[maskAt + 1]) << 16) |
484
+ (toU32(buf[maskAt + 2]) << 8) |
485
+ toU32(buf[maskAt + 3])
433
486
  for (let r: i32 = 0; r < (phase & 3); r += 1) {
434
487
  key = (key << 8) | (key >>> 24)
435
488
  }
436
- for (let k: i32 = 0; k < len; k += 1) {
437
- to[at + k] = buf[from + k] ^ toU8(key >>> 24)
489
+ let s: i32 = from
490
+ let t: i32 = at
491
+ for (let k: i32 = 0; k < len && s >= 0 && s < bufLength && t >= 0 && t < toLength; k += 1) {
492
+ to[t] = buf[s] ^ toU8(key >>> 24)
438
493
  key = (key << 8) | (key >>> 24)
494
+ s += 1
495
+ t += 1
439
496
  }
497
+ return true
440
498
  }
441
499
 
442
500
  /**
@@ -445,18 +503,20 @@ const websocketUnmaskInto = (
445
503
  */
446
504
  const websocketMessageRoom = (d: WsDecoder, need: i32): void => {
447
505
  const old: u8[] = d.message
448
- let size: i32 = toI32(old.length)
449
- if (need <= size) {
506
+ const oldLength: i32 = toI32(old.length)
507
+ if (need <= oldLength) {
450
508
  return
451
509
  }
452
- while (size < need) {
453
- size = size > 1073741823 ? 2147483647 : size * 2
510
+ let size: i64 = toI64(oldLength) * toI64(2)
511
+ if (size < toI64(need)) {
512
+ size = toI64(need)
454
513
  }
455
- const grown: u8[] = new Array<u8>(size)
456
- const live: i32 = d.messageLen + d.frameChecked
457
- for (let k: i32 = 0; k < live && k < toI32(grown.length) && k < toI32(old.length); k += 1) {
458
- grown[k] = old[k]
514
+ if (size > toI64(2147483647)) {
515
+ size = toI64(2147483647)
459
516
  }
517
+ const grown: u8[] = websocketBytes(toI32(size))
518
+ const live: i32 = websocketAdd(d.messageLen, d.frameChecked)
519
+ tryCopyBytes(grown, 0, old, 0, live < oldLength ? live : oldLength)
460
520
  d.message = grown
461
521
  }
462
522
 
@@ -476,6 +536,10 @@ const websocketReadClose = (d: WsDecoder, len: i32): i32 => {
476
536
  if (len === 1) {
477
537
  return websocketFail(d, WS_CLOSE_PROTOCOL_ERROR, "a close frame with a one-byte payload")
478
538
  }
539
+ // `control` holds 125 bytes and the frame's payload was copied into it.
540
+ if (len < 2 || toI32(payload.length) < 2) {
541
+ return websocketFail(d, WS_CLOSE_INTERNAL_ERROR, "a close frame payload that was not kept")
542
+ }
479
543
  const code: i32 = (toI32(payload[0]) << 8) | toI32(payload[1])
480
544
  if (!websocketIsSendableCode(code)) {
481
545
  return websocketFail(d, WS_CLOSE_PROTOCOL_ERROR, "a close status code that may not be sent")
@@ -503,8 +567,13 @@ const websocketReadClose = (d: WsDecoder, len: i32): i32 => {
503
567
  const websocketFrameEvent = (d: WsDecoder): i32 => {
504
568
  const buf: u8[] = d.buf
505
569
  const at: i32 = d.start
506
- const ready: i32 = d.end - at
507
- if (ready < 2 || at < 0 || at + 1 >= toI32(buf.length)) {
570
+ const end: i32 = d.end
571
+ const bufLength: i32 = toI32(buf.length)
572
+ if (at < 0 || end < 0 || end < at || end > bufLength || at >= bufLength - 1) {
573
+ return WS_NEED_MORE
574
+ }
575
+ const ready: i32 = end - at
576
+ if (ready < 2) {
508
577
  return WS_NEED_MORE
509
578
  }
510
579
  const b0: i32 = toI32(buf[at])
@@ -520,10 +589,16 @@ const websocketFrameEvent = (d: WsDecoder): i32 => {
520
589
  } else if (short === 127) {
521
590
  extended = 8
522
591
  }
523
- const headerLength: i32 = 2 + extended + (masked ? 4 : 0)
592
+ let keyLength: i32 = 0
593
+ if (masked) {
594
+ keyLength = 4
595
+ }
596
+ const headerLength: i32 = 2 + extended + keyLength
524
597
  if (ready < headerLength) {
525
598
  return WS_NEED_MORE
526
599
  }
600
+ // What of the payload has arrived; at least zero, past the guard above.
601
+ const body: i32 = ready - headerLength
527
602
  if ((b0 & 0x70) !== 0) {
528
603
  return websocketFail(d, WS_CLOSE_PROTOCOL_ERROR, "a reserved bit set with no extension negotiated")
529
604
  }
@@ -539,22 +614,27 @@ const websocketFrameEvent = (d: WsDecoder): i32 => {
539
614
  )
540
615
  }
541
616
  // The payload length (§5.2), held to `i32` and refused before it is used.
617
+ // `ready` covers the header, so its bytes lie inside `buf`; the checks on
618
+ // `at` say so in the form the index proofs read.
542
619
  let length: i32 = short
543
620
  if (extended === 2) {
621
+ if (at >= bufLength - 3) {
622
+ return WS_NEED_MORE
623
+ }
544
624
  length = (toI32(buf[at + 2]) << 8) | toI32(buf[at + 3])
545
625
  if (length < 126) {
546
626
  return websocketFail(d, WS_CLOSE_PROTOCOL_ERROR, "a 16-bit length under 126")
547
627
  }
548
628
  } else if (extended === 8) {
629
+ if (at >= bufLength - 9) {
630
+ return WS_NEED_MORE
631
+ }
549
632
  if ((toI32(buf[at + 2]) & 0x80) !== 0) {
550
633
  return websocketFail(d, WS_CLOSE_PROTOCOL_ERROR, "a 64-bit length with its top bit set")
551
634
  }
552
635
  // Anything in the high four bytes, or a top bit in the low four, is more
553
636
  // than an `i32` holds and so more than any `maxMessage`.
554
- let high: i32 = 0
555
- for (let k: i32 = 2; k < 6; k += 1) {
556
- high = high | toI32(buf[at + k])
557
- }
637
+ const high: i32 = toI32(buf[at + 2]) | toI32(buf[at + 3]) | toI32(buf[at + 4]) | toI32(buf[at + 5])
558
638
  if (high !== 0 || (toI32(buf[at + 6]) & 0x80) !== 0) {
559
639
  return websocketFail(d, WS_CLOSE_TOO_BIG, "a frame longer than 2^31 - 1 bytes")
560
640
  }
@@ -578,19 +658,19 @@ const websocketFrameEvent = (d: WsDecoder): i32 => {
578
658
  if (opcode !== WS_OP_CONTINUATION && d.messageOpcode !== 0) {
579
659
  return websocketFail(d, WS_CLOSE_PROTOCOL_ERROR, "a new message before the last one ended")
580
660
  }
581
- if (length > d.maxMessage - d.messageLen) {
661
+ if (toI64(length) > toI64(d.maxMessage) - toI64(d.messageLen)) {
582
662
  return websocketFail(d, WS_CLOSE_TOO_BIG, "a message longer than the limit")
583
663
  }
584
664
  }
585
- const payloadAt: i32 = at + headerLength
586
- const maskAt: i32 = payloadAt - 4
665
+ const payloadAt: i32 = websocketAdd(at, headerLength)
666
+ const maskAt: i32 = websocketAdd(at, headerLength - 4)
587
667
  const text: boolean =
588
668
  opcode === WS_OP_TEXT || (opcode === WS_OP_CONTINUATION && d.messageOpcode === WS_OP_TEXT)
589
669
  if (text) {
590
670
  // A text frame is unmasked and checked as its bytes arrive, so a byte
591
671
  // that cannot continue UTF-8 fails the connection at once (§8.1), not
592
672
  // when the frame or the message ends.
593
- const arrived: i32 = ready - headerLength < length ? ready - headerLength : length
673
+ const arrived: i32 = body < length ? body : length
594
674
  const from: i32 = d.messageLen
595
675
  const done: i32 = d.frameChecked
596
676
  if (done === 0 && opcode === WS_OP_TEXT) {
@@ -601,22 +681,39 @@ const websocketFrameEvent = (d: WsDecoder): i32 => {
601
681
  if (arrived > done) {
602
682
  // Room for the bytes that have arrived, not the length the header
603
683
  // declares: a peer that declares much and sends little costs little.
604
- websocketMessageRoom(d, from + arrived)
605
- websocketUnmaskInto(buf, payloadAt + done, arrived - done, masked, maskAt, done, d.message, from + done)
684
+ const fresh: i32 = websocketSub(arrived, done)
685
+ const freshAt: i32 = websocketAdd(from, done)
686
+ websocketMessageRoom(d, websocketAdd(from, arrived))
687
+ if (
688
+ !websocketUnmaskInto(
689
+ buf,
690
+ websocketAdd(payloadAt, done),
691
+ fresh,
692
+ masked,
693
+ maskAt,
694
+ done,
695
+ d.message,
696
+ freshAt
697
+ )
698
+ ) {
699
+ return websocketFail(d, WS_CLOSE_INTERNAL_ERROR, "a frame outside the decoder's buffers")
700
+ }
606
701
  d.frameChecked = arrived
607
- if (!websocketUtf8Run(d.utf8, d.message, from + done, arrived - done)) {
702
+ if (!websocketUtf8Run(d.utf8, d.message, freshAt, fresh)) {
608
703
  return websocketFail(d, WS_CLOSE_INVALID_DATA, "a text message that is not UTF-8")
609
704
  }
610
705
  }
611
706
  }
612
- if (ready - headerLength < length) {
707
+ if (body < length) {
613
708
  return WS_NEED_MORE
614
709
  }
615
710
  // The whole frame is here: take it out of the input.
616
- d.start = payloadAt + length
711
+ d.start = websocketAdd(payloadAt, length)
617
712
  d.frameChecked = 0
618
713
  if (control) {
619
- websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, 0, d.control, 0)
714
+ if (!websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, 0, d.control, 0)) {
715
+ return websocketFail(d, WS_CLOSE_INTERNAL_ERROR, "a frame outside the decoder's buffers")
716
+ }
620
717
  d.opcode = opcode
621
718
  d.data = d.control
622
719
  d.dataLen = length
@@ -629,12 +726,15 @@ const websocketFrameEvent = (d: WsDecoder): i32 => {
629
726
  d.messageOpcode = opcode
630
727
  }
631
728
  const from: i32 = d.messageLen
729
+ const total: i32 = websocketAdd(from, length)
632
730
  if (!text) {
633
731
  // A text frame's payload is already in `message`, unmasked and checked.
634
- websocketMessageRoom(d, from + length)
635
- websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, 0, d.message, from)
732
+ websocketMessageRoom(d, total)
733
+ if (!websocketUnmaskInto(buf, payloadAt, length, masked, maskAt, 0, d.message, from)) {
734
+ return websocketFail(d, WS_CLOSE_INTERNAL_ERROR, "a frame outside the decoder's buffers")
735
+ }
636
736
  }
637
- d.messageLen = from + length
737
+ d.messageLen = total
638
738
  if (!fin) {
639
739
  return WS_CONTINUE
640
740
  }
@@ -678,16 +778,28 @@ export const WS_REFUSED: i32 = -2
678
778
  *
679
779
  * @param len The payload's length in bytes, at least 0.
680
780
  * @param masked Whether the frame carries a 4-byte mask key, as every frame a client sends does.
681
- * @returns The frame's size in bytes: 2 to 14 bytes of header, then `len`.
781
+ * @returns The frame's size in bytes: 2 to 14 bytes of header, then `len`; `WS_REFUSED` for a negative `len` or one past 2^31 - 15, whose frame `websocketWriteFrame` refuses.
682
782
  */
683
783
  export const websocketFrameSize = (len: i32, masked: boolean): i32 => {
684
- let extended: i32 = 8
784
+ if (len < 0 || len > WS_MAX_FRAME_PAYLOAD) {
785
+ return WS_REFUSED
786
+ }
787
+ return websocketAdd(websocketHeaderLength(len, masked), len)
788
+ }
789
+
790
+ /** A frame's header length for a payload of `len` bytes, 0 to `WS_MAX_FRAME_PAYLOAD`: 2 to 14. */
791
+ const websocketHeaderLength = (len: i32, masked: boolean): i32 => {
792
+ let key: i32 = 0
793
+ if (masked) {
794
+ key = 4
795
+ }
685
796
  if (len < 126) {
686
- extended = 0
687
- } else if (len < 65536) {
688
- extended = 2
797
+ return 2 + key
689
798
  }
690
- return 2 + extended + (masked ? 4 : 0) + len
799
+ if (len < 65536) {
800
+ return 4 + key
801
+ }
802
+ return 10 + key
691
803
  }
692
804
 
693
805
  /**
@@ -698,12 +810,12 @@ export const websocketFrameSize = (len: i32, masked: boolean): i32 => {
698
810
  * shortest of its three forms.
699
811
  *
700
812
  * Answers where the frame ends, `WS_NO_ROOM` when it does not fit, or
701
- * `WS_REFUSED` for an opcode RFC 6455 does not define, a control frame that is
702
- * not FIN or is longer than 125 bytes, and a mask that is not 4 bytes; on
703
- * either refusal `out` is untouched. A window outside `payload` panics, and so
704
- * does a payload longer than 2^31 - 15 bytes. A text frame's payload is not
705
- * checked here, because a fragment may end inside a character;
706
- * `websocketIsUtf8` checks a whole message.
813
+ * `WS_REFUSED` for a window outside `payload`, a payload longer than
814
+ * 2^31 - 15 bytes, an opcode RFC 6455 does not define, a control frame that
815
+ * is not FIN or is longer than 125 bytes, and a mask that is not 4 bytes; on
816
+ * either refusal `out` is untouched. A text frame's payload is not checked
817
+ * here, because a fragment may end inside a character; `websocketIsUtf8`
818
+ * checks a whole message.
707
819
  *
708
820
  * @param out The buffer the frame is written into.
709
821
  * @param at The index in `out` the frame starts at; one outside `out` answers `WS_NO_ROOM`.
@@ -726,8 +838,8 @@ export const websocketWriteFrame = (
726
838
  mask: u8[] | null
727
839
  ): i32 => {
728
840
  const size: i32 = toI32(payload.length)
729
- if (off < 0 || len < 0 || off > size || len > size - off) {
730
- panic("websocketWriteFrame: the window is outside the buffer")
841
+ if (off < 0 || len < 0 || off > size || len > size - off || len > WS_MAX_FRAME_PAYLOAD) {
842
+ return WS_REFUSED
731
843
  }
732
844
  if (!websocketIsKnownOpcode(opcode)) {
733
845
  return WS_REFUSED
@@ -739,60 +851,69 @@ export const websocketWriteFrame = (
739
851
  if (mask !== null && toI32(mask.length) !== 4) {
740
852
  return WS_REFUSED
741
853
  }
742
- if (len > WS_MAX_FRAME_PAYLOAD) {
743
- panic("websocketWriteFrame: a frame longer than 2^31 - 1 bytes")
744
- }
745
- const frameSize: i32 = websocketFrameSize(len, mask !== null)
854
+ const headerLength: i32 = websocketHeaderLength(len, mask !== null)
746
855
  const outLength: i32 = toI32(out.length)
747
- if (at < 0 || at > outLength || frameSize > outLength - at) {
856
+ if (at < 0 || at > outLength || toI64(headerLength) + toI64(len) > toI64(outLength) - toI64(at)) {
748
857
  return WS_NO_ROOM
749
858
  }
859
+ const finBit: i32 = fin ? 0x80 : 0
860
+ const maskBit: i32 = mask === null ? 0 : 0x80
861
+ // The room check covers the header; each form's own check on `at` says so
862
+ // in the form the index proofs read.
750
863
  let extended: i32 = 8
751
864
  if (len < 126) {
752
865
  extended = 0
866
+ if (at >= outLength - 1) {
867
+ return WS_NO_ROOM
868
+ }
869
+ out[at] = toU8(finBit | opcode)
870
+ out[at + 1] = toU8(maskBit | len)
753
871
  } else if (len < 65536) {
754
872
  extended = 2
755
- }
756
- const headerLength: i32 = frameSize - len
757
- const finBit: i32 = fin ? 0x80 : 0
758
- out[at] = toU8(finBit | opcode)
759
- const maskBit: i32 = mask === null ? 0 : 0x80
760
- if (extended === 0) {
761
- out[at + 1] = toU8(maskBit | len)
762
- } else if (extended === 2) {
873
+ if (at >= outLength - 3) {
874
+ return WS_NO_ROOM
875
+ }
876
+ out[at] = toU8(finBit | opcode)
763
877
  out[at + 1] = toU8(maskBit | 126)
764
878
  out[at + 2] = toU8(len >> 8)
765
879
  out[at + 3] = toU8(len)
766
880
  } else {
881
+ if (at >= outLength - 9) {
882
+ return WS_NO_ROOM
883
+ }
884
+ out[at] = toU8(finBit | opcode)
767
885
  out[at + 1] = toU8(maskBit | 127)
768
886
  // The top four bytes are zero: `len` is an `i32`.
769
- for (let k: i32 = 2; k < 6; k += 1) {
770
- out[at + k] = 0
771
- }
887
+ out[at + 2] = 0
888
+ out[at + 3] = 0
889
+ out[at + 4] = 0
890
+ out[at + 5] = 0
772
891
  out[at + 6] = toU8(len >> 24)
773
892
  out[at + 7] = toU8(len >> 16)
774
893
  out[at + 8] = toU8(len >> 8)
775
894
  out[at + 9] = toU8(len)
776
895
  }
777
- const payloadAt: i32 = at + headerLength
778
- for (let k: i32 = 0; k < len && payloadAt + k < outLength; k += 1) {
779
- out[payloadAt + k] = payload[off + k]
896
+ const payloadAt: i32 = websocketAdd(at, headerLength)
897
+ if (!tryCopyBytes(out, payloadAt, payload, off, len)) {
898
+ return WS_NO_ROOM
780
899
  }
781
900
  if (mask !== null) {
782
- const keyAt: i32 = at + 2 + extended
783
- for (let k: i32 = 0; k < 4 && k < toI32(mask.length); k += 1) {
784
- out[keyAt + k] = mask[k]
785
- }
901
+ const keyAt: i32 = websocketAdd(at, 2 + extended)
786
902
  // Masking and unmasking are the same XOR, so the copied payload goes
787
903
  // through the decoder's own loop, reading the key just written.
788
- websocketUnmaskInto(out, payloadAt, len, true, keyAt, 0, out, payloadAt)
904
+ if (
905
+ !tryCopyBytes(out, keyAt, mask, 0, 4) ||
906
+ !websocketUnmaskInto(out, payloadAt, len, true, keyAt, 0, out, payloadAt)
907
+ ) {
908
+ return WS_NO_ROOM
909
+ }
789
910
  }
790
- return payloadAt + len
911
+ return websocketAdd(payloadAt, len)
791
912
  }
792
913
 
793
914
  /**
794
915
  * One frame, as `websocketWriteFrame` writes it, in an array of its own; the
795
- * same refusals answer `null`. A window outside `payload` panics.
916
+ * same refusals, a window outside `payload` among them, answer `null`.
796
917
  *
797
918
  * @param fin Whether this is the message's last frame; a control frame must set it.
798
919
  * @param opcode The frame's opcode, such as `WS_OP_TEXT` or `WS_OP_PING`.
@@ -811,13 +932,10 @@ export const websocketFrame = (
811
932
  mask: u8[] | null
812
933
  ): u8[] | null => {
813
934
  const size: i32 = toI32(payload.length)
814
- if (off < 0 || len < 0 || off > size || len > size - off) {
815
- panic("websocketFrame: the window is outside the buffer")
816
- }
817
- if (len > WS_MAX_FRAME_PAYLOAD) {
818
- panic("websocketFrame: a frame longer than 2^31 - 1 bytes")
935
+ if (off < 0 || len < 0 || off > size || len > size - off || len > WS_MAX_FRAME_PAYLOAD) {
936
+ return null
819
937
  }
820
- const out: u8[] = new Array<u8>(websocketFrameSize(len, mask !== null))
938
+ const out: u8[] = websocketBytes(websocketFrameSize(len, mask !== null))
821
939
  const at: i32 = 0
822
940
  return websocketWriteFrame(out, at, fin, opcode, payload, off, len, mask) < 0 ? null : out
823
941
  }
@@ -837,12 +955,9 @@ export const websocketClosePayload = (code: i32, reason: string): u8[] | null =>
837
955
  if (!websocketIsSendableCode(code) || n > WS_MAX_CONTROL - 2) {
838
956
  return null
839
957
  }
840
- const out: u8[] = new Array<u8>(n + 2)
841
- const outLength: i32 = toI32(out.length)
842
- out[0] = toU8(code >> 8)
843
- out[1] = toU8(code)
844
- for (let k: i32 = 0; k < n && k + 2 < outLength; k += 1) {
845
- out[k + 2] = toU8(reason.charCodeAt(k))
958
+ const out: u8[] = [toU8(code >> 8), toU8(code)]
959
+ for (let k: i32 = 0; k < n; k += 1) {
960
+ out.push(toU8(reason.charCodeAt(k)))
846
961
  }
847
962
  const reasonStart: i32 = 2
848
963
  if (!websocketIsUtf8(out, reasonStart, n)) {
@@ -856,7 +971,7 @@ export const websocketClosePayload = (code: i32, reason: string): u8[] | null =>
856
971
  /** The bytes of `text`, as the language holds a string. */
857
972
  const websocketBytesOf = (text: string): u8[] => {
858
973
  const n: i32 = toI32(text.length)
859
- const out: u8[] = new Array<u8>(n)
974
+ const out: u8[] = websocketBytes(n)
860
975
  const outLength: i32 = toI32(out.length)
861
976
  for (let k: i32 = 0; k < outLength && k < n; k += 1) {
862
977
  out[k] = toU8(text.charCodeAt(k))
@@ -864,23 +979,87 @@ const websocketBytesOf = (text: string): u8[] => {
864
979
  return out
865
980
  }
866
981
 
982
+ /** The length of a valid `Sec-WebSocket-Key`: 16 bytes in padded base64. */
983
+ /** Zero as an `i32`, for offsets under `--number-mode f64`. */
984
+ const WS_ZERO: i32 = 0
985
+
986
+ const WS_KEY_LENGTH: i32 = 24
987
+ /** The length of `Sec-WebSocket-Accept`: 20 bytes of SHA-1 in padded base64. */
988
+ const WS_ACCEPT_LENGTH: i32 = 28
989
+
867
990
  /**
868
- * `text` with one byte replaced by another throughout: how a base64url
869
- * spelling becomes standard base64 (`-` and `_` for `+` and `/`) and back.
991
+ * Whether `text[start .. end)` is a valid `Sec-WebSocket-Key` (§4.2.1 item 5):
992
+ * 24 characters of padded standard base64 that decode to 16 bytes in their
993
+ * one canonical spelling, read where they lie and allocating nothing.
870
994
  */
871
- const websocketSwapBytes = (text: string, from1: i32, to1: i32, from2: i32, to2: i32): string => {
872
- const parts: string[] = []
873
- const n: i32 = toI32(text.length)
874
- for (let k: i32 = 0; k < n; k += 1) {
875
- let c: i32 = toI32(text.charCodeAt(k))
876
- if (c === from1) {
877
- c = to1
878
- } else if (c === from2) {
879
- c = to2
995
+ const websocketKeySpanIsValid = (text: u8[], start: i32, end: i32): boolean =>
996
+ start >= 0 &&
997
+ end >= 0 &&
998
+ end <= toI32(text.length) &&
999
+ end - start === WS_KEY_LENGTH &&
1000
+ base64StdPadDecodedLength(text, start, WS_KEY_LENGTH) === 16
1001
+
1002
+ /**
1003
+ * The accept key of one handshake after another, in storage the caller keeps:
1004
+ * a server builds one per connection and computes every handshake's
1005
+ * `Sec-WebSocket-Accept` into it, allocating nothing after it is built (the
1006
+ * fix for H1-3 in `docs/security/http1-codec.md`).
1007
+ *
1008
+ * const accept = new WsAcceptKey();
1009
+ * if (accept.compute(p.head, start, end)) {
1010
+ * // accept.value[0 .. 28) is the field's value
1011
+ * }
1012
+ */
1013
+ export class WsAcceptKey {
1014
+ /** The hasher, its state kept from one handshake to the next. */
1015
+ hasher: Sha1
1016
+ /** The key followed by `WS_GUID`: what is hashed (§4.2.2 item 5.4). */
1017
+ input: u8[]
1018
+ /** The SHA-1 of `input`. */
1019
+ digest: u8[]
1020
+ /** The accept value's 28 characters, one a byte, once `compute` answers true. */
1021
+ value: u8[]
1022
+
1023
+ /** Storage for one accept value, its hasher and buffers allocated. */
1024
+ constructor() {
1025
+ this.hasher = new Sha1()
1026
+ const text: string = WS_GUID
1027
+ const guid: i32 = toI32(text.length)
1028
+ // The 24-character key and the 36-character GUID.
1029
+ const input: u8[] = new Array<u8>(60)
1030
+ const inputLength: i32 = toI32(input.length)
1031
+ let t: i32 = WS_KEY_LENGTH
1032
+ for (let k: i32 = 0; k < guid && t >= 0 && t < inputLength; k += 1) {
1033
+ input[t] = toU8(text.charCodeAt(k))
1034
+ t += 1
1035
+ }
1036
+ this.input = input
1037
+ this.digest = new Array<u8>(SHA1_SIZE)
1038
+ this.value = new Array<u8>(WS_ACCEPT_LENGTH)
1039
+ }
1040
+
1041
+ /**
1042
+ * Computes into `value` the accept value of the key in `text[start .. end)`
1043
+ * (§4.2.2 item 5.4), when that is a valid key.
1044
+ *
1045
+ * @param text The buffer holding the client's key, one character a byte, such as an `Http1Parser`'s `head`.
1046
+ * @param start Where in `text` the key starts.
1047
+ * @param end Where in `text` it ends.
1048
+ * @returns True with `value` written, or false, `value` unchanged, when the key is not valid.
1049
+ */
1050
+ compute(text: u8[], start: i32, end: i32): boolean {
1051
+ if (!websocketKeySpanIsValid(text, start, end)) {
1052
+ return false
1053
+ }
1054
+ const input: u8[] = this.input
1055
+ // A valid key is 24 bytes inside `text`, so the copy fits.
1056
+ if (!tryCopyBytes(input, WS_ZERO, text, start, WS_KEY_LENGTH)) {
1057
+ return false
880
1058
  }
881
- parts.push(String.fromCharCode(c))
1059
+ this.hasher.digestInto(input, WS_ZERO, toI32(input.length), this.digest, WS_ZERO)
1060
+ base64StdPadEncodeInto(this.digest, WS_ZERO, SHA1_SIZE, this.value, WS_ZERO)
1061
+ return true
882
1062
  }
883
- return parts.join("")
884
1063
  }
885
1064
 
886
1065
  /**
@@ -890,8 +1069,14 @@ const websocketSwapBytes = (text: string, from1: i32, to1: i32, from2: i32, to2:
890
1069
  * @param key The key as the client sent it; it is not checked here, so check it with `websocketKeyIsValid` first.
891
1070
  * @returns The 28-character accept value.
892
1071
  */
893
- export const websocketAcceptKey = (key: string): string =>
894
- base64StdPadEncode(sha1(websocketBytesOf(`${key}${WS_GUID}`)))
1072
+ export const websocketAcceptKey = (key: string): string => {
1073
+ const input: u8[] = websocketBytesOf(`${key}${WS_GUID}`)
1074
+ const digest: u8[] = new Array<u8>(SHA1_SIZE)
1075
+ new Sha1().digestInto(input, WS_ZERO, toI32(input.length), digest, WS_ZERO)
1076
+ const text: u8[] = new Array<u8>(WS_ACCEPT_LENGTH)
1077
+ base64StdPadEncodeInto(digest, WS_ZERO, SHA1_SIZE, text, WS_ZERO)
1078
+ return http1Text(text, 0, WS_ACCEPT_LENGTH, false)
1079
+ }
895
1080
 
896
1081
  /**
897
1082
  * Whether `key` is a valid `Sec-WebSocket-Key` (§4.2.1 item 5): padded
@@ -902,65 +1087,163 @@ export const websocketAcceptKey = (key: string): string =>
902
1087
  * @returns True for a 24-character key ending in `==` whose other characters decode to 16 bytes.
903
1088
  */
904
1089
  export const websocketKeyIsValid = (key: string): boolean => {
905
- if (toI32(key.length) !== 24 || !key.endsWith("==")) {
1090
+ if (toI32(key.length) !== WS_KEY_LENGTH) {
906
1091
  return false
907
1092
  }
908
- const body: string = key.substring(0, 22)
909
- // A `-` or `_` is not standard base64, so it may not survive the swap as
910
- // if it were; `=` inside the body is refused by the decoder.
911
- if (toI32(body.indexOf("-")) >= 0 || toI32(body.indexOf("_")) >= 0) {
912
- return false
1093
+ const bytes: u8[] = websocketBytesOf(key)
1094
+ return websocketKeySpanIsValid(bytes, 0, WS_KEY_LENGTH)
1095
+ }
1096
+
1097
+ /**
1098
+ * Which field of the head `p` has just read holds the client's key, when that
1099
+ * head is a valid opening handshake (§4.2.1): a GET in HTTP/1.1, asking to
1100
+ * upgrade to `websocket` (alone, in any case), at version 13, with a valid
1101
+ * first `Sec-WebSocket-Key`. Otherwise -1. Nothing is allocated: the key is
1102
+ * `p.head[p.spans[4 * i + 2] .. p.spans[4 * i + 3])`, for `WsAcceptKey`.
1103
+ *
1104
+ * @param p The server's parser, at the `HTTP1_HEAD` of the request.
1105
+ * @returns The key's field index, or -1 when the request is not a valid handshake.
1106
+ */
1107
+ export const websocketRequestKeyField = (p: Http1Parser): i32 => {
1108
+ if (!p.methodIs("GET") || p.minor !== 1 || !p.upgradeIs("websocket")) {
1109
+ return -1
913
1110
  }
914
- const bytes: u8[] | null = base64urlDecode(websocketSwapBytes(body, 43, 45, 47, 95))
915
- return bytes !== null && toI32(bytes.length) === 16
1111
+ if (!p.headerIs("sec-websocket-version", "13")) {
1112
+ return -1
1113
+ }
1114
+ const i: i32 = p.headerIndex("sec-websocket-key")
1115
+ const spans: i32[] = p.spans
1116
+ const at: i32 = websocketValueAt(spans, i)
1117
+ if (at < 0 || at >= toI32(spans.length) - 1 || !websocketKeySpanIsValid(p.head, spans[at], spans[at + 1])) {
1118
+ return -1
1119
+ }
1120
+ return i
916
1121
  }
917
1122
 
918
1123
  /**
919
1124
  * The client's key when the head `p` has just read is a valid opening
920
- * handshake (§4.2.1): a GET in HTTP/1.1, asking to upgrade to `websocket`
921
- * (alone, in any case), at version 13, with a valid key. Otherwise `null`, and
922
- * the server answers 400 (or 426 with `Sec-WebSocket-Version: 13` when only the
923
- * version is wrong, §4.4).
1125
+ * handshake (§4.2.1), as `websocketRequestKeyField` judges it. Otherwise
1126
+ * `null`, and the server answers 400 (or 426 with `Sec-WebSocket-Version: 13`
1127
+ * when only the version is wrong, §4.4).
924
1128
  *
925
1129
  * @param p The server's parser, at the `HTTP1_HEAD` of the request.
926
1130
  * @returns The `Sec-WebSocket-Key` to pass to `websocketUpgradeResponse`, or null when the request is not a valid handshake.
927
1131
  */
928
1132
  export const websocketRequestKey = (p: Http1Parser): string | null => {
929
- if (!p.methodIs("GET") || p.minor !== 1 || !p.upgradeIs("websocket")) {
1133
+ const spans: i32[] = p.spans
1134
+ const at: i32 = websocketValueAt(spans, websocketRequestKeyField(p))
1135
+ if (at < 0 || at >= toI32(spans.length) - 1) {
930
1136
  return null
931
1137
  }
932
- if (!p.headerIs("sec-websocket-version", "13")) {
933
- return null
1138
+ return http1Text(p.head, spans[at], spans[at + 1], false)
1139
+ }
1140
+
1141
+ /**
1142
+ * Where field `i`'s value span starts in `spans` (four entries a field: the
1143
+ * name's start and end, then the value's), or -1 when `i` is not a field
1144
+ * `spans` holds; `spans[at]` and `spans[at + 1]` are then the value's ends.
1145
+ */
1146
+ const websocketValueAt = (spans: i32[], i: i32): i32 => {
1147
+ if (i < 0 || i > 536870910) {
1148
+ return -1
934
1149
  }
935
- const key: string | null = p.header("sec-websocket-key")
936
- if (key === null || !websocketKeyIsValid(key)) {
937
- return null
1150
+ const at: i32 = 4 * i + 2
1151
+ if (at >= toI32(spans.length) - 1) {
1152
+ return -1
1153
+ }
1154
+ return at
1155
+ }
1156
+
1157
+ /** Writes `text` into `out` from `at`; the caller has checked it fits. */
1158
+ const websocketPutText = (out: u8[], at: i32, text: string): i32 => {
1159
+ const n: i32 = toI32(text.length)
1160
+ const outLength: i32 = toI32(out.length)
1161
+ let j: i32 = at
1162
+ for (let k: i32 = 0; k < n && j >= 0 && j < outLength; k += 1) {
1163
+ out[j] = toU8(text.charCodeAt(k))
1164
+ j += 1
938
1165
  }
939
- return key
1166
+ return j
1167
+ }
1168
+
1169
+ /** The 101's status line and its first two fields, which never change. */
1170
+ const WS_SWITCHING: string =
1171
+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "
1172
+
1173
+ /**
1174
+ * Writes the server's 101 response to an opening handshake (§4.2.2) into
1175
+ * `out` from `at`, allocating nothing: `Upgrade`, `Connection`,
1176
+ * `Sec-WebSocket-Accept` with the 28 bytes `accept` holds, and
1177
+ * `Sec-WebSocket-Protocol` when `protocol` is not empty. The bytes are those
1178
+ * of `websocketUpgradeResponse`.
1179
+ *
1180
+ * @param out The buffer the head is written into.
1181
+ * @param at Where in `out` it starts.
1182
+ * @param accept The accept value, its 28 characters one a byte: a `WsAcceptKey`'s `value`.
1183
+ * @param protocol The subprotocol the server chose from `websocketOfferedProtocols`, or "" for none.
1184
+ * @returns The index just past the head, `HTTP1_REFUSED` when `protocol` is not a token or `accept` is not 28 bytes, or `HTTP1_NO_ROOM` when the head does not fit, `out` unchanged either way.
1185
+ */
1186
+ export const websocketWriteUpgradeResponse = (out: u8[], at: i32, accept: u8[], protocol: string): i32 => {
1187
+ const p: i32 = toI32(protocol.length)
1188
+ if (p < 0 || p > 65536) {
1189
+ return HTTP1_REFUSED
1190
+ }
1191
+ if (toI32(accept.length) !== WS_ACCEPT_LENGTH || (p > 0 && !http1IsToken(protocol))) {
1192
+ return HTTP1_REFUSED
1193
+ }
1194
+ const fixed: i32 = toI32(WS_SWITCHING.length)
1195
+ let named: i32 = 0
1196
+ if (p > 0) {
1197
+ named = 26 + p
1198
+ }
1199
+ const length: i32 = websocketAdd(fixed, named + WS_ACCEPT_LENGTH + 4)
1200
+ if (at < 0 || toI64(at) + toI64(length) > toI64(toI32(out.length))) {
1201
+ return HTTP1_NO_ROOM
1202
+ }
1203
+ let j: i32 = websocketPutText(out, at, WS_SWITCHING)
1204
+ if (!tryCopyBytes(out, j, accept, WS_ZERO, WS_ACCEPT_LENGTH)) {
1205
+ return HTTP1_NO_ROOM
1206
+ }
1207
+ j = websocketPutText(out, websocketAdd(j, WS_ACCEPT_LENGTH), "\r\n")
1208
+ if (p > 0) {
1209
+ j = websocketPutText(out, j, "Sec-WebSocket-Protocol: ")
1210
+ j = websocketPutText(out, j, protocol)
1211
+ j = websocketPutText(out, j, "\r\n")
1212
+ }
1213
+ return websocketPutText(out, j, "\r\n")
940
1214
  }
941
1215
 
942
1216
  /**
943
1217
  * The server's 101 response to an opening handshake (§4.2.2): `Upgrade`,
944
1218
  * `Connection`, `Sec-WebSocket-Accept`, and `Sec-WebSocket-Protocol` when
945
1219
  * `protocol` is not empty (the caller picks it from the client's list).
946
- * Answers `null` for an invalid key or a protocol that is not a token.
1220
+ * Answers `null` for an invalid key or a protocol that is not a token. A
1221
+ * server answering handshake after handshake writes the same bytes with
1222
+ * `WsAcceptKey` and `websocketWriteUpgradeResponse` instead, allocating
1223
+ * nothing.
947
1224
  *
948
1225
  * @param key The client's `Sec-WebSocket-Key`, as `websocketRequestKey` gave it.
949
1226
  * @param protocol The subprotocol the server chose from `websocketOfferedProtocols`, or "" for none.
950
1227
  * @returns The whole response head, ending in the empty line, or null when refused.
951
1228
  */
952
1229
  export const websocketUpgradeResponse = (key: string, protocol: string): u8[] | null => {
953
- if (!websocketKeyIsValid(key)) {
1230
+ const bytes: u8[] = websocketBytesOf(key)
1231
+ const accept = new WsAcceptKey()
1232
+ if (!accept.compute(bytes, WS_ZERO, toI32(bytes.length))) {
954
1233
  return null
955
1234
  }
956
- const names: string[] = ["Upgrade", "Connection", "Sec-WebSocket-Accept"]
957
- const values: string[] = ["websocket", "Upgrade", websocketAcceptKey(key)]
958
- if (toI32(protocol.length) > 0) {
959
- names.push("Sec-WebSocket-Protocol")
960
- values.push(protocol)
1235
+ const out: u8[] = websocketBytes(
1236
+ websocketAdd(websocketAdd(toI32(WS_SWITCHING.length), WS_ACCEPT_LENGTH + 30), toI32(protocol.length))
1237
+ )
1238
+ const end: i32 = websocketWriteUpgradeResponse(out, WS_ZERO, accept.value, protocol)
1239
+ if (end < 0) {
1240
+ return null
1241
+ }
1242
+ const head: u8[] = websocketBytes(end)
1243
+ for (let k: i32 = 0; k < toI32(head.length) && k < toI32(out.length); k++) {
1244
+ head[k] = out[k]
961
1245
  }
962
- const switching: i32 = 101
963
- return http1ResponseHead(switching, "Switching Protocols", names, values, HTTP1_NO_BODY)
1246
+ return head
964
1247
  }
965
1248
 
966
1249
  /**
@@ -978,9 +1261,15 @@ export const websocketOfferedProtocols = (p: Http1Parser): string[] | null => {
978
1261
  const out: string[] = []
979
1262
  const head: u8[] = p.head
980
1263
  const spans: i32[] = p.spans
981
- for (let i: i32 = 0; i < p.headerCount && 4 * i + 3 < toI32(spans.length); i += 1) {
982
- if (websocketSpanIs(head, spans[4 * i], spans[4 * i + 1], "sec-websocket-protocol")) {
983
- websocketListInto(head, spans[4 * i + 2], spans[4 * i + 3], out)
1264
+ // `s` steps through the four spans of each field in turn.
1265
+ let s: i32 = 0
1266
+ for (let i: i32 = 0; i < p.headerCount && s >= 0 && s < toI32(spans.length) - 3; i += 1) {
1267
+ const valueStart: i32 = spans[s + 2]
1268
+ const valueEnd: i32 = spans[s + 3]
1269
+ const offers: boolean = websocketSpanIs(head, spans[s], spans[s + 1], "sec-websocket-protocol")
1270
+ s += 4
1271
+ if (offers) {
1272
+ websocketListInto(head, valueStart, valueEnd, out)
984
1273
  }
985
1274
  }
986
1275
  for (let k: i32 = 0; k < toI32(out.length); k += 1) {
@@ -1014,20 +1303,24 @@ export const websocketOfferedProtocols = (p: Http1Parser): string[] | null => {
1014
1303
  export const websocketOriginAllowed = (p: Http1Parser, allowed: string[]): boolean => {
1015
1304
  const head: u8[] = p.head
1016
1305
  const spans: i32[] = p.spans
1306
+ // `s` steps through the four spans of each field in turn; `found` is where
1307
+ // the `Origin` field's spans start.
1017
1308
  let found: i32 = -1
1018
- for (let i: i32 = 0; i < p.headerCount && 4 * i + 3 < toI32(spans.length); i += 1) {
1019
- if (websocketSpanIs(head, spans[4 * i], spans[4 * i + 1], "origin")) {
1309
+ let s: i32 = 0
1310
+ for (let i: i32 = 0; i < p.headerCount && s >= 0 && s < toI32(spans.length) - 3; i += 1) {
1311
+ if (websocketSpanIs(head, spans[s], spans[s + 1], "origin")) {
1020
1312
  if (found >= 0) {
1021
1313
  return false
1022
1314
  }
1023
- found = i
1315
+ found = s
1024
1316
  }
1317
+ s += 4
1025
1318
  }
1026
- if (found < 0) {
1319
+ if (found < 0 || found >= toI32(spans.length) - 3) {
1027
1320
  return false
1028
1321
  }
1029
1322
  for (let k: i32 = 0; k < toI32(allowed.length); k += 1) {
1030
- if (websocketSpanFolds(head, spans[4 * found + 2], spans[4 * found + 3], allowed[k])) {
1323
+ if (websocketSpanFolds(head, spans[found + 2], spans[found + 3], allowed[k])) {
1031
1324
  return true
1032
1325
  }
1033
1326
  }
@@ -1040,11 +1333,11 @@ export const websocketOriginAllowed = (p: Http1Parser, allowed: string[]): boole
1040
1333
  */
1041
1334
  const websocketSpanFolds = (bytes: u8[], a: i32, b: i32, text: string): boolean => {
1042
1335
  const n: i32 = toI32(text.length)
1043
- if (a < 0 || b - a !== n || b > toI32(bytes.length)) {
1336
+ if (a < 0 || b < 0 || b - a !== n || b > toI32(bytes.length)) {
1044
1337
  return false
1045
1338
  }
1339
+ let at: i32 = a
1046
1340
  for (let k: i32 = 0; k < n; k += 1) {
1047
- const at: i32 = a + k
1048
1341
  if (at < 0 || at >= toI32(bytes.length) || k >= toI32(text.length)) {
1049
1342
  return false
1050
1343
  }
@@ -1059,6 +1352,7 @@ const websocketSpanFolds = (bytes: u8[], a: i32, b: i32, text: string): boolean
1059
1352
  if (c !== w) {
1060
1353
  return false
1061
1354
  }
1355
+ at += 1
1062
1356
  }
1063
1357
  return true
1064
1358
  }
@@ -1066,11 +1360,11 @@ const websocketSpanFolds = (bytes: u8[], a: i32, b: i32, text: string): boolean
1066
1360
  /** Whether `bytes[a .. b)` is `word`, which is lower case, in any ASCII case. Allocates nothing. */
1067
1361
  const websocketSpanIs = (bytes: u8[], a: i32, b: i32, word: string): boolean => {
1068
1362
  const n: i32 = toI32(word.length)
1069
- if (a < 0 || b - a !== n || b > toI32(bytes.length)) {
1363
+ if (a < 0 || b < 0 || b - a !== n || b > toI32(bytes.length)) {
1070
1364
  return false
1071
1365
  }
1366
+ let at: i32 = a
1072
1367
  for (let k: i32 = 0; k < n; k += 1) {
1073
- const at: i32 = a + k
1074
1368
  if (at < 0 || at >= toI32(bytes.length) || k >= toI32(word.length)) {
1075
1369
  return false
1076
1370
  }
@@ -1081,6 +1375,7 @@ const websocketSpanIs = (bytes: u8[], a: i32, b: i32, word: string): boolean =>
1081
1375
  if (c !== toI32(word.charCodeAt(k))) {
1082
1376
  return false
1083
1377
  }
1378
+ at += 1
1084
1379
  }
1085
1380
  return true
1086
1381
  }
@@ -1090,49 +1385,71 @@ const websocketSpanIs = (bytes: u8[], a: i32, b: i32, word: string): boolean =>
1090
1385
  * (RFC 9110 §5.6.1) to `out`, each trimmed of OWS, the empty ones dropped.
1091
1386
  */
1092
1387
  const websocketListInto = (bytes: u8[], from: i32, to: i32, out: string[]): void => {
1093
- if (from < 0 || to > toI32(bytes.length)) {
1388
+ const n: i32 = toI32(bytes.length)
1389
+ if (from < 0 || to > n) {
1094
1390
  return
1095
1391
  }
1096
1392
  let start: i32 = from
1097
- for (let k: i32 = from; k <= to; k += 1) {
1098
- if (k === to || (k >= 0 && k < toI32(bytes.length) && toI32(bytes[k]) === 44)) {
1099
- let a: i32 = start
1100
- let b: i32 = k
1101
- while (a < b && a >= 0 && a < toI32(bytes.length) && http1IsOws(toI32(bytes[a]))) {
1102
- a += 1
1103
- }
1104
- while (b > a && b - 1 >= 0 && b - 1 < toI32(bytes.length) && http1IsOws(toI32(bytes[b - 1]))) {
1105
- b -= 1
1106
- }
1107
- if (b > a) {
1108
- out.push(http1Text(bytes, a, b, false))
1109
- }
1393
+ for (let k: i32 = from; k >= 0 && k < to && k < toI32(bytes.length); k += 1) {
1394
+ if (toI32(bytes[k]) === 44) {
1395
+ websocketElementInto(bytes, start, k, out)
1110
1396
  start = k + 1
1111
1397
  }
1112
1398
  }
1399
+ websocketElementInto(bytes, start, to, out)
1400
+ }
1401
+
1402
+ /** Appends `bytes[a .. b)`, trimmed of OWS, to `out` unless it is empty. */
1403
+ const websocketElementInto = (bytes: u8[], a: i32, b: i32, out: string[]): void => {
1404
+ const n: i32 = toI32(bytes.length)
1405
+ let x: i32 = a
1406
+ let y: i32 = b
1407
+ while (x < y && x >= 0 && x < n && http1IsOws(toI32(bytes[x]))) {
1408
+ x += 1
1409
+ }
1410
+ while (y > x && y > 0 && y <= n) {
1411
+ const c: i32 = y - 1
1412
+ if (c < 0 || c >= n || !http1IsOws(toI32(bytes[c]))) {
1413
+ break
1414
+ }
1415
+ y = c
1416
+ }
1417
+ if (y > x) {
1418
+ out.push(http1Text(bytes, x, y, false))
1419
+ }
1113
1420
  }
1114
1421
 
1115
1422
  /** Whether the comma-separated list `value` (RFC 9110 §5.6.1) has an element that is `word`, which is lower case, in any ASCII case. */
1116
1423
  const websocketListHas = (value: string, word: string): boolean => {
1117
1424
  const n: i32 = toI32(value.length)
1118
1425
  let start: i32 = 0
1119
- for (let k: i32 = 0; k <= n; k += 1) {
1120
- if (k === n || (k >= 0 && k < n && toI32(value.charCodeAt(k)) === 44)) {
1121
- let a: i32 = start
1122
- let b: i32 = k
1123
- while (a < b && a >= 0 && a < n && http1IsOws(toI32(value.charCodeAt(a)))) {
1124
- a += 1
1125
- }
1126
- while (b > a && b - 1 >= 0 && b - 1 < n && http1IsOws(toI32(value.charCodeAt(b - 1)))) {
1127
- b -= 1
1128
- }
1129
- if (http1SameWord(value, a, b, word)) {
1426
+ for (let k: i32 = 0; k >= 0 && k < n; k += 1) {
1427
+ if (toI32(value.charCodeAt(k)) === 44) {
1428
+ if (websocketElementIs(value, start, k, word)) {
1130
1429
  return true
1131
1430
  }
1132
1431
  start = k + 1
1133
1432
  }
1134
1433
  }
1135
- return false
1434
+ return websocketElementIs(value, start, n, word)
1435
+ }
1436
+
1437
+ /** Whether `value[a .. b)`, trimmed of OWS, is `word` in any ASCII case. */
1438
+ const websocketElementIs = (value: string, a: i32, b: i32, word: string): boolean => {
1439
+ const n: i32 = toI32(value.length)
1440
+ let x: i32 = a
1441
+ let y: i32 = b
1442
+ while (x < y && x >= 0 && x < n && http1IsOws(toI32(value.charCodeAt(x)))) {
1443
+ x += 1
1444
+ }
1445
+ while (y > x && y > 0 && y <= n) {
1446
+ const c: i32 = y - 1
1447
+ if (c < 0 || c >= n || !http1IsOws(toI32(value.charCodeAt(c)))) {
1448
+ break
1449
+ }
1450
+ y = c
1451
+ }
1452
+ return http1SameWord(value, x, y, word)
1136
1453
  }
1137
1454
 
1138
1455
  /**
@@ -1285,19 +1602,25 @@ export const websocketCheckResponse = (
1285
1602
  const name: string = names[i]
1286
1603
  const value: string = values[i]
1287
1604
  if (name === "upgrade") {
1288
- upgrades += 1
1605
+ if (upgrades < 2) {
1606
+ upgrades += 1
1607
+ }
1289
1608
  upgradeOk = http1SameWord(value, 0, toI32(value.length), "websocket")
1290
1609
  } else if (name === "connection") {
1291
1610
  if (websocketListHas(value, "upgrade")) {
1292
1611
  connection = true
1293
1612
  }
1294
1613
  } else if (name === "sec-websocket-accept") {
1295
- accepts += 1
1614
+ if (accepts < 2) {
1615
+ accepts += 1
1616
+ }
1296
1617
  acceptOk = toI32(expected.length) > 0 && value === expected
1297
1618
  } else if (name === "sec-websocket-extensions") {
1298
1619
  extensions = true
1299
1620
  } else if (name === "sec-websocket-protocol") {
1300
- protocols += 1
1621
+ if (protocols < 2) {
1622
+ protocols += 1
1623
+ }
1301
1624
  protocol = value
1302
1625
  }
1303
1626
  }