nish 0.36.0 → 0.37.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 (88) hide show
  1. package/docs/AI.md +43 -4
  2. package/docs/INSTALL.md +67 -58
  3. package/package.json +9 -5
  4. package/runtime/async.d.mts +2 -0
  5. package/runtime/async.mjs +7 -0
  6. package/runtime/nish.d.ts +736 -499
  7. package/runtime/nish.h +25 -0
  8. package/runtime/page.d.ts +53 -0
  9. package/runtime/page.mjs +146 -0
  10. package/runtime/runtime-async.c +557 -0
  11. package/runtime/runtime-wasm.c +63 -7
  12. package/scripts/build.sh +147 -5
  13. package/scripts/fuzz.sh +1 -0
  14. package/scripts/undocumented.txt +14 -0
  15. package/std/README.md +107 -82
  16. package/std/bytes.ts +23 -19
  17. package/std/compress/checksum.ts +1 -1
  18. package/std/crypto/aes.ts +48 -43
  19. package/std/crypto/base64url.ts +7 -5
  20. package/std/crypto/bcrypt-batch.ts +13 -13
  21. package/std/crypto/bcrypt.ts +33 -27
  22. package/std/crypto/chacha20poly1305.ts +16 -14
  23. package/std/crypto/ed25519.ts +19 -16
  24. package/std/crypto/hmac.ts +7 -6
  25. package/std/crypto/jwt.ts +23 -20
  26. package/std/crypto/p256.ts +63 -56
  27. package/std/crypto/p384.ts +23 -20
  28. package/std/crypto/pki.ts +18 -15
  29. package/std/crypto/rsa.ts +23 -19
  30. package/std/crypto/x25519.ts +11 -10
  31. package/std/crypto/x509.ts +69 -62
  32. package/std/host/ring.ts +124 -0
  33. package/std/json-equal.ts +12 -11
  34. package/std/json-number.ts +12 -12
  35. package/std/json-tokenizer.ts +26 -22
  36. package/std/json-typed.ts +92 -78
  37. package/std/json-value.ts +38 -33
  38. package/std/json.ts +32 -28
  39. package/std/net/fetch.ts +1117 -230
  40. package/std/net/handler.ts +18 -0
  41. package/std/net/hpack.ts +29 -26
  42. package/std/net/http-compress.ts +27 -21
  43. package/std/net/http1-client-codec.ts +29 -25
  44. package/std/net/http1-codec.ts +44 -87
  45. package/std/net/http1-server.ts +66 -54
  46. package/std/net/http2-frame.ts +17 -16
  47. package/std/net/http2-tls.ts +17 -15
  48. package/std/net/http2.ts +67 -54
  49. package/std/net/http3-frame.ts +11 -10
  50. package/std/net/http3-server.ts +36 -35
  51. package/std/net/http3.ts +70 -58
  52. package/std/net/postgres.ts +178 -160
  53. package/std/net/prefork.ts +38 -34
  54. package/std/net/qpack.ts +15 -14
  55. package/std/net/quic-conn-ack.ts +1 -0
  56. package/std/net/quic-conn-cid.ts +11 -0
  57. package/std/net/quic-conn-params.ts +41 -14
  58. package/std/net/quic-datagram.ts +7 -0
  59. package/std/net/quic-frame.ts +48 -12
  60. package/std/net/quic-listener.ts +61 -44
  61. package/std/net/quic-packet.ts +71 -52
  62. package/std/net/quic-recovery.ts +59 -21
  63. package/std/net/quic-stream.ts +83 -55
  64. package/std/net/quic.ts +204 -152
  65. package/std/net/tls/client.ts +1 -0
  66. package/std/net/tls/codec.ts +81 -12
  67. package/std/net/tls/record-client.ts +30 -18
  68. package/std/net/tls/record-server.ts +74 -46
  69. package/std/net/tls/record.ts +33 -24
  70. package/std/net/tls/ticket.ts +2 -0
  71. package/std/net/tls/verify.ts +8 -7
  72. package/std/net/tls-tcp.ts +58 -50
  73. package/std/net/tls.ts +55 -43
  74. package/std/net/url.ts +12 -9
  75. package/std/net/websocket.ts +23 -19
  76. package/std/net/webtransport.ts +24 -18
  77. package/std/random.ts +8 -6
  78. package/std/regex.ts +70 -59
  79. package/std/sync/ring.ts +24 -21
  80. package/std/sync/shm.ts +9 -7
  81. package/std/term-io.ts +17 -14
  82. package/std/term-probe.ts +11 -10
  83. package/std/term-rate.ts +71 -61
  84. package/std/term.ts +73 -59
  85. package/std/text.ts +11 -10
  86. package/std/threads.ts +19 -15
  87. package/std/yaml-json.ts +17 -15
  88. package/std/yaml-write.ts +21 -14
package/scripts/build.sh CHANGED
@@ -20,7 +20,9 @@
20
20
  # <dir>/runtime-bytes.c, the byte-class runs of `nish/bytes`,
21
21
  # <dir>/runtime-sandbox.c, the confinement `--sandbox` applies,
22
22
  # <dir>/runtime-shm.c, the shared-memory regions of `nish/sync/shm`, and
23
- # <dir>/runtime-region.c, the arenas a program makes and frees one at a time. Each of those
23
+ # <dir>/runtime-region.c, the arenas a program makes and frees one at a time, and,
24
+ # only for a program whose IR declares one of its functions,
25
+ # <dir>/runtime-async.c, the executor `spawn` and `nish:async`'s waits park tasks on. Each of those
24
26
  # files says why they are compiled and measured apart.
25
27
  #
26
28
  # Profiles:
@@ -335,6 +337,34 @@ for i in ${inputs[@]+"${inputs[@]}"}; do
335
337
  *.c) if [ -n "$sqlite_dir" ] && [ "$(cd "$(dirname -- "$i")" && pwd -P)" = "$sqlite_dir" ]; then sqlite_wanted=0; break; fi ;;
336
338
  esac
337
339
  done
340
+ # The async executor (runtime-async.c) is selected by the IR the same way: a
341
+ # module that declares one of its `nish_async_*` functions -- every program
342
+ # that spawns, awaits a kernel wait or runs an async main does -- gets it
343
+ # compiled and linked beside runtime.c. Any other program links none of it, so
344
+ # its binary holds no `nish_async` symbol and its bytes stay as they were.
345
+ # `--runtime-objects` compiles it with the rest, so the runtime cache holds it,
346
+ # and `--runtime-from` links its object only when it is wanted. A caller that
347
+ # names it itself is left alone, as `halves` leaves a half.
348
+ async_wanted=0
349
+ if [ ${#lls[@]} -gt 0 ] && grep -Eq '^declare [^"]*@nish_async_' "${lls[@]}"; then
350
+ async_wanted=1
351
+ fi
352
+ if [ "$async_wanted" = 1 ]; then
353
+ for i in ${inputs[@]+"${inputs[@]}"}; do
354
+ case "$i" in
355
+ */runtime-async.c|runtime-async.c) async_wanted=0 ;;
356
+ esac
357
+ done
358
+ fi
359
+ if [ "$async_wanted" = 1 ] && [ -z "$objects_from" ]; then
360
+ for i in ${inputs[@]+"${inputs[@]}"}; do
361
+ case "$i" in
362
+ */runtime.c|runtime.c)
363
+ side="${i%runtime.c}runtime-async.c"
364
+ if [ -f "$side" ]; then inputs+=("$side"); fi ;;
365
+ esac
366
+ done
367
+ fi
338
368
  if [ "$sqlite_wanted" = 1 ] && [ -z "$sqlite_dir" ]; then
339
369
  echo "error: the module calls SQLite, and $(dirname "$0")/../runtime/sqlite/ is not there" >&2
340
370
  exit 2
@@ -656,7 +686,7 @@ if [ -n "$objects_to" ]; then
656
686
  # the file `runtime.c` in the runtime's own directory, whichever directory
657
687
  # the first link that compiled it was run in.
658
688
  runtime_dir=$(dirname -- "$runtime")
659
- for unit in runtime.c $halves; do
689
+ for unit in runtime.c $halves runtime-async.c; do
660
690
  (cd -- "$runtime_dir" && exec "$CC" "${compile[@]}" -c "$unit" -o "$objects_to/${unit%.c}.o") &
661
691
  pids+=("$!")
662
692
  done
@@ -694,6 +724,10 @@ if [ -n "$objects_from" ]; then
694
724
  for unit in runtime.c $halves; do
695
725
  objects+=("$objects_from/${unit%.c}.o")
696
726
  done
727
+ if [ "$async_wanted" = 1 ]; then
728
+ [ -f "$objects_from/runtime-async.o" ] || { echo "error: --runtime-from: $objects_from/runtime-async.o is missing" >&2; exit 2; }
729
+ objects+=("$objects_from/runtime-async.o")
730
+ fi
697
731
  inputs=("${objects[@]}")
698
732
  # clang runs dsymutil itself when one command compiles and links with -g on
699
733
  # macOS; a link of objects does not, so it is run here, while the program's
@@ -785,6 +819,31 @@ case "$profile" in
785
819
  *.ll) if grep -q '@nish_round_init' "$i"; then round_wanted=1; fi ;;
786
820
  esac
787
821
  done
822
+ # Under wasm-host a program whose loader guards panics (one with module
823
+ # storage or a host module: the compiler ends its IR with a
824
+ # `; nish.sites <count>` line) reports each panic through the page's
825
+ # `nish.panic` import, which runtime-wasm.c makes the call to when it is
826
+ # compiled with NISH_WASM_HOST. Any other program links the bytes it always
827
+ # did, with no import. IR with a tagged site links the runtime for the
828
+ # import, or the panic would stay the silent trap of an undefined weak
829
+ # stub; linked for that, it exports the arena entry points as any link of
830
+ # runtime-wasm.c does, since a guarded loader that moves an array marks
831
+ # and releases the arena around each call.
832
+ host_panics=0
833
+ if [ "$profile" = wasm-host ]; then
834
+ for i in ${inputs[@]+"${inputs[@]}"}; do
835
+ case "$i" in
836
+ *.ll) if grep -qE '^; nish\.sites [0-9]+$' "$i"; then host_panics=1; fi ;;
837
+ esac
838
+ done
839
+ fi
840
+ if [ "$host_panics" = 1 ] && [ "$wasm_named" = 0 ] && [ "$round_wanted" = 0 ]; then
841
+ for i in ${inputs[@]+"${inputs[@]}"}; do
842
+ case "$i" in
843
+ *.ll) if grep -qE '^[[:space:]]+call void @nish_panic[A-Za-z0-9_]*\(.*, !nish\.site !\{i32 ' "$i"; then round_wanted=1; fi ;;
844
+ esac
845
+ done
846
+ fi
788
847
  if [ "$round_wanted" = 1 ] && [ "$wasm_named" = 0 ]; then
789
848
  inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-wasm.c")
790
849
  fi
@@ -797,6 +856,83 @@ case "$profile" in
797
856
  -Wl,--no-entry -Wl,--export-all -Wl,--strip-all -Wl,--gc-sections \
798
857
  "${inputs[@]}" -o "$out"
799
858
  else
859
+ # Panic sites (WP50 stage 3). For a program whose loader guards panics
860
+ # the compiler tags each call of a runtime panic `!nish.site !{i32 N}`
861
+ # and lists the sites at the end of the module as
862
+ # `; nish.site N <kind> <path:line:col>` comments; code generation drops
863
+ # both, so `--profile wasm` links what it always did. Here each tagged
864
+ # call becomes its `_at` form taking the site as a first argument,
865
+ # numbered across the inputs, runtime-wasm.c (compiled with
866
+ # NISH_WASM_HOST) hands it to the page's `nish.panic` import, and the
867
+ # sites are written to `<out>.sites.json` for the loader. A program
868
+ # without the `; nish.sites` line has no tag, no import and no sidecar,
869
+ # and its build never touches `<out>.sites.json`; a guarded build
870
+ # removes the one an earlier build left before it writes its own.
871
+ host_define=()
872
+ host_inputs=("${inputs[@]}")
873
+ if [ "$host_panics" = 1 ]; then
874
+ rm -f "$out.sites.json"
875
+ host_define=(-DNISH_WASM_HOST)
876
+ make_work
877
+ sites_dir="$work/sites"
878
+ mkdir -p "$sites_dir"
879
+ sites_base=0
880
+ sites_json="$sites_dir/sites"
881
+ : > "$sites_json"
882
+ host_inputs=()
883
+ for i in "${inputs[@]}"; do
884
+ case "$i" in
885
+ *.ll)
886
+ rewritten="$sites_dir/${#host_inputs[@]}.ll"
887
+ awk -v base="$sites_base" -v list="$sites_json" '
888
+ # One tagged call: "call void @nish_panic<x>(<args>)<attrs>, !nish.site !{i32 N}<rest>".
889
+ # (`close` is a builtin, so the brace is `shut`.)
890
+ function untag(line, at, rest, shut, n, head, open, args) {
891
+ at = index(line, ", !nish.site !{i32 ")
892
+ rest = substr(line, at + 19)
893
+ shut = index(rest, "}")
894
+ n = substr(rest, 1, shut - 1) + base
895
+ head = substr(line, 1, at - 1)
896
+ open = index(head, "(")
897
+ args = substr(head, open + 1)
898
+ return substr(head, 1, open - 1) "_at(i32 " n (substr(args, 1, 1) == ")" ? "" : ", ") args substr(rest, shut + 1)
899
+ }
900
+ /^; nish\.site [0-9]+ / {
901
+ kind = $4
902
+ where = $0
903
+ sub(/^; nish\.site [0-9]+ [a-z]+ /, "", where)
904
+ gsub(/\\/, "\\\\", where)
905
+ gsub(/"/, "\\\"", where)
906
+ printf " { \"kind\": \"%s\", \"at\": \"%s\" }\n", kind, where >> list
907
+ count++
908
+ print
909
+ next
910
+ }
911
+ /^declare [a-z_ ]*void @nish_panic[a-z_]*\(/ {
912
+ print
913
+ open = index($0, "(")
914
+ print substr($0, 1, open - 1) "_at(i32" (substr($0, open + 1, 1) == ")" ? "" : ", ") substr($0, open + 1)
915
+ next
916
+ }
917
+ # Only a call line: a string constant may spell the tag in its bytes.
918
+ /^[ \t]+call void @nish_panic[A-Za-z0-9_]*\(.*, !nish\.site !\{i32 [0-9]+\}/ { print untag($0); next }
919
+ { print }
920
+ END { print count + 0 > (list ".count") }
921
+ ' "$i" > "$rewritten"
922
+ sites_base=$((sites_base + $(cat "$sites_json.count")))
923
+ host_inputs+=("$rewritten") ;;
924
+ *) host_inputs+=("$i") ;;
925
+ esac
926
+ done
927
+ {
928
+ printf '['
929
+ if [ -s "$sites_json" ]; then
930
+ printf '\n'
931
+ sed '$!s/$/,/' "$sites_json"
932
+ fi
933
+ printf ']\n'
934
+ } > "$out.sites.json"
935
+ fi
800
936
  # The export list. A module's exported functions are its `define` lines
801
937
  # with external linkage and default visibility: the compiler gives
802
938
  # everything else `internal` or `private`, and the other linkages are
@@ -811,7 +947,13 @@ case "$profile" in
811
947
  exports+=("-Wl,--export=$name")
812
948
  done < <(grep -E '^define ' "$i" \
813
949
  | grep -Ev '^define (internal|private|linkonce|linkonce_odr|weak|weak_odr|available_externally|extern_weak|common|hidden|protected) ' \
814
- | sed -nE 's/^[^@]*@"?([^"(]+)"?\(.*/\1/p') ;;
950
+ | sed -nE 's/^[^@]*@"?([^"(]+)"?\(.*/\1/p')
951
+ # Module storage (WP50 stage 3): each `@<name>.data` global is
952
+ # exported, and wasm-ld exports a data symbol as a global holding
953
+ # its address, which the loader reads into `layout.<name>.at`.
954
+ while IFS= read -r name; do
955
+ exports+=("-Wl,--export=$name")
956
+ done < <(sed -nE 's/^@"?([^" =]+\.data)"? = global .*/\1/p' "$i") ;;
815
957
  esac
816
958
  done
817
959
  if [ "$runtime_linked" = 1 ]; then
@@ -825,10 +967,10 @@ case "$profile" in
825
967
  bytes=$((memory_mib * 1048576))
826
968
  memory+=("-Wl,--initial-memory=$bytes" "-Wl,--max-memory=$bytes")
827
969
  fi
828
- "$CC" "${wasm_compile[@]}" \
970
+ "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
829
971
  ${tls[@]+"${tls[@]}"} \
830
972
  -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
831
- "${inputs[@]}" -o "$out"
973
+ "${host_inputs[@]}" -o "$out"
832
974
  # binaryen's size pass is optional: the module is complete without it.
833
975
  if command -v wasm-opt >/dev/null 2>&1; then
834
976
  wasm-opt -Oz --enable-bulk-memory "$out" -o "$out"
package/scripts/fuzz.sh CHANGED
@@ -60,6 +60,7 @@ RUNTIME_C=(
60
60
  runtime/runtime-sandbox.c
61
61
  runtime/runtime-shm.c
62
62
  runtime/runtime-region.c
63
+ runtime/runtime-async.c
63
64
  )
64
65
 
65
66
  SAN_FLAGS=(-g -O1 "-fsanitize=fuzzer,address,undefined" -fno-sanitize-recover=undefined)
@@ -0,0 +1,14 @@
1
+ # Public declarations of std/ and runtime/nish.d.ts that lack their documentation.
2
+ #
3
+ # This list only shrinks. `node scripts/gen-reference.mjs --check` fails on a gap
4
+ # it does not list and on a line that is no longer a gap: document the
5
+ # declaration and delete its line. `--update-baseline` rewrites the file and
6
+ # refuses to add a line; `--grow-baseline` adds them, only for a change to the rule.
7
+ # docs/README.md -> "The library reference" states the rule.
8
+ #
9
+ # module.Name.member the declaration has no doc comment
10
+ # module.Name#param:p parameter p has no @param
11
+ # module.Name#returns a return type other than void or never has no @returns
12
+
13
+ runtime/nish.HostHandle.__type.__nishHostKind
14
+ runtime/nish.nish.HostHandle.__type.__nishHostKind
package/std/README.md CHANGED
@@ -50,18 +50,21 @@ whatever program imports it, and subject to the same rules as `examples/` or
50
50
 
51
51
  ## `nish/crypto` — the primitives under TLS 1.3
52
52
 
53
- The first lanes of [WP34](https://github.com/amritk/nish/blob/main/docs/wp34-hosting-cs.md) §5: K1's hashes, MACs and
54
- key derivation, K2's and K3's AEADs, K4's key exchange, K5's signatures and
55
- K6's certificates, in
56
- pure Nish (decision S1), each module imported by its own specifier. Every one
57
- is written from its specification, with three exceptions that keep their
58
- upstream notice: `crypto/aes.ts`'s `ghashMul32` is adapted from BearSSL,
59
- `crypto/p256.ts`'s field and scalar arithmetic is ported from fiat-crypto and
60
- its nonce's safegcd inversion from libsecp256k1, and `crypto/p384.ts`'s field
61
- and scalar arithmetic is ported from fiat-crypto
62
- ([`THIRD_PARTY_NOTICES.md`](https://github.com/amritk/nish/blob/main/THIRD_PARTY_NOTICES.md)). Each reproduces its
63
- specification's published vectors in its `tests/link/crypto_*` programs. The
64
- performance gate compiles every module with no diagnostics under both
53
+ The first lanes of
54
+ [WP34](https://github.com/amritk/nish/blob/main/docs/wp34-hosting-cs.md) §5:
55
+ K1's hashes, MACs and key derivation, K2's and K3's AEADs, K4's key exchange,
56
+ K5's signatures and K6's certificates, in pure Nish (decision S1), each module
57
+ imported by its own specifier. Every one is written from its specification,
58
+ with three exceptions that keep their upstream notice: `crypto/aes.ts`'s
59
+ `ghashMul32` is adapted from BearSSL, `crypto/p256.ts`'s field and scalar
60
+ arithmetic is ported from fiat-crypto and its nonce's safegcd inversion from
61
+ libsecp256k1, and `crypto/p384.ts`'s field and scalar arithmetic is ported from
62
+ fiat-crypto
63
+ ([`THIRD_PARTY_NOTICES.md`](https://github.com/amritk/nish/blob/main/THIRD_PARTY_NOTICES.md)).
64
+ Each reproduces its specification's published vectors in its
65
+ `tests/link/crypto_*` programs.
66
+
67
+ The performance gate compiles every module with no diagnostics under both
65
68
  `--number-mode i32` and `f64`, and the hashes, HMAC, HKDF, X25519,
66
69
  ChaCha20-Poly1305, AES-GCM, P-256 and X.509 also run their vectors in `f64`
67
70
  (`crypto_*_f64`). SHA-1 is here too, for one non-security use (its row says
@@ -70,13 +73,17 @@ which), and does both.
70
73
  Every module here was security-audited (#363); the records are in
71
74
  [`docs/security/`](../docs/security/README.md), and how to report a
72
75
  vulnerability is in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.md). Two limits hold across the
73
- modules. **Lengths stop at 2^31 − 1.** No array built by `push` or `new Array`,
74
- no array or string the runtime makes (a file read, a concatenation, a
75
- template) and no string built by `join` can pass 2^31 − 1 elements or bytes
76
- (K1-6, CG-3, closed), so `length` is right in both number modes, and the
77
- one-shot functions below refuse a longer input as each row says. **Private
78
- keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`, `crypto/ed25519.ts`,
79
- `crypto/x509.ts` and `crypto/x509-random.ts` take and give a private key as a `Secret<u8[]>` from
76
+ modules.
77
+
78
+ **Lengths stop at 2^31 − 1.** No array built by `push` or `new Array`, no array
79
+ or string the runtime makes (a file read, a concatenation, a template) and no
80
+ string built by `join` can pass 2^31 − 1 elements or bytes (K1-6, CG-3,
81
+ closed), so `length` is right in both number modes, and the one-shot functions
82
+ below refuse a longer input as each row says.
83
+
84
+ **Private keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`,
85
+ `crypto/ed25519.ts`, `crypto/x509.ts` and `crypto/x509-random.ts` take and give
86
+ a private key as a `Secret<u8[]>` from
80
87
  `nish:secret`, compute on it only inside `expose`, and wipe every intermediate
81
88
  the key reaches before they return, with a store the optimiser may not remove
82
89
  (ECC-2, X509-7, closed); `crypto/hmac.ts` (`hmacSha256Secret` and its two
@@ -130,7 +137,9 @@ Three rules hold across the modules:
130
137
  255 steps, AES reads no table, P-256's comb and window read every entry of
131
138
  a table and keep one by mask, and base64url maps characters by arithmetic on range masks
132
139
  rather than a table. Every branch is on a length, a loop counter or a bit
133
- position. WP34 N6 checks that the machine code kept that shape:
140
+ position.
141
+
142
+ WP34 N6 checks that the machine code kept that shape:
134
143
  `tests/ct-asm.js` disassembles golden fixtures on x86-64 and aarch64 and
135
144
  refuses a branch, a call, a secret-addressed load, or a divide or square
136
145
  root of a secret (whose latency follows its operands) in them. It reads what
@@ -159,18 +168,19 @@ Three rules hold across the modules:
159
168
  - `tests/cases/ct_asm_aes`: one full bitsliced round, one GHASH multiply and
160
169
  the tag compare. Packing, the key schedule and the loops over blocks
161
170
  remain discipline.
162
- - `tests/cases/ct_asm_p256`: fiat's field multiply, square, add and
163
- subtract, its scalar multiply and its conditional move; the sixteen-entry
164
- table read by a secret digit; the complete doubling and addition; and one
165
- window step of the scalar multiplication (four doublings, the table read
166
- and an addition); and the fixed-base comb that multiplies G for a public
167
- key or a signature: its digit, the fifteen-entry read of the precomputed
168
- table, the mixed addition, the masked keep, and one whole comb step; and
169
- the nonce's safegcd inversion: thirty divsteps, held to the module's loop
170
- body, and both matrix updates. The check follows each call into the field
171
- functions. The 64-window and 4-row loops, the window's table build, the
172
- field inversion, safegcd's limb conversions, the encodings and
173
- RFC 6979's nonce derivation remain discipline.
171
+ - `tests/cases/ct_asm_p256`: fiat's field multiply, square, add and subtract,
172
+ its scalar multiply and its conditional move; the sixteen-entry table read
173
+ by a secret digit; the complete doubling and addition; and one window step
174
+ of the scalar multiplication (four doublings, the table read and an
175
+ addition); and the fixed-base comb that multiplies G for a public key or a
176
+ signature: its digit, the fifteen-entry read of the precomputed table, the
177
+ mixed addition, the masked keep, and one whole comb step; and the nonce's
178
+ safegcd inversion: thirty divsteps, held to the module's loop body, and
179
+ both matrix updates. The check follows each call into the field functions.
180
+
181
+ The 64-window and 4-row loops, the window's table build, the field
182
+ inversion, safegcd's limb conversions, the encodings and RFC 6979's nonce
183
+ derivation remain discipline.
174
184
 
175
185
  The SHA-2 hashes and HKDF are additions, rotations and xors that branch
176
186
  only on lengths, and are not in a fixture either; nor is `crypto/x509.ts`,
@@ -265,6 +275,7 @@ through both Finished messages) and `TLS_LEVEL_APPLICATION`. A carrier hands
265
275
  `receive` the bytes it got at a level, in any split, and sends what
266
276
  `takeOutput(level)` answers under that level's keys: TLS over TCP (T2) in
267
277
  records, QUIC (Q2) in CRYPTO frames of the matching packet number space.
278
+
268
279
  `writeKnown(level)` and `readKnown(level)` say when the server's and the
269
280
  client's traffic secret for the Handshake and Application levels is known
270
281
  (the Initial level has none); the secrets themselves are `Secret` fields of
@@ -272,7 +283,9 @@ client's traffic secret for the Handshake and Application levels is known
272
283
  `clientHandshake`, `serverApplication`, `clientApplication` and `exporter` —
273
284
  which a carrier reads only through `expose` (`installHeld` turns one into a
274
285
  record key), and `wipeSecret(TLS_SECRET_*)` zeroes one once the carrier has
275
- what it needs. The state says what is due: `TLS_STATE_WAIT_SIGNATURE` after the
286
+ what it needs.
287
+
288
+ The state says what is due: `TLS_STATE_WAIT_SIGNATURE` after the
276
289
  first flight is written, `TLS_STATE_WAIT_FINISHED` once it is signed,
277
290
  `TLS_STATE_CONNECTED` when the client's Finished verified, and
278
291
  `TLS_STATE_FAILED` with `alert` set after a refusal. Over QUIC, set `quic` in
@@ -283,7 +296,9 @@ ways (`clientTransportParameters` holds the client's).
283
296
  computed with, are `Secret`s wiped on every path, and `tlsSignEcdsaP256` takes
284
297
  its key as a `Secret`. The one-shot key-schedule functions of
285
298
  `nish/net/tls/schedule` and `tlsNextTrafficSecret` take and answer their
286
- secrets as `Secret<u8[]>`s, so a plain array there is a compile error. What `TlsServer` keeps for an open connection —
299
+ secrets as `Secret<u8[]>`s, so a plain array there is a compile error.
300
+
301
+ What `TlsServer` keeps for an open connection —
287
302
  the caller's ephemeral key, copied in by `restart`, and the handshake,
288
303
  traffic, exporter and resumption secrets — and the four traffic secrets
289
304
  `TlsRecordServer` keeps for KeyUpdate are `Secret` fields, readonly and read
@@ -293,6 +308,7 @@ zeroed once the carrier has what it needs from it and at every end of the
293
308
  connection (TLS-1 in
294
309
  [`docs/security/tls.md`](../docs/security/tls.md), the record that also lists
295
310
  what each refusal is and the test that pins it).
311
+
296
312
  `tests/link/net_tls_*` are the module's programs, each also run under
297
313
  `--number-mode f64`.
298
314
 
@@ -302,18 +318,20 @@ test or another transport. The program is the loop: there are no callbacks,
302
318
  so each call answers the slot's interest and the program re-arms the
303
319
  descriptor with `pollModify(loop, tls.fd(slot), wants & 3, slot)`, signs on
304
320
  `TLS_RECORD_SIGN`, reads on `TLS_RECORD_DATA` and calls `close(slot)` on
305
- `TLS_RECORD_DONE`. A slot's buffers — about 136 KB of resident memory, measured over a 400-slot pool, with the handshake's own state in them — are
306
- allocated once, on the first accept into the slot, and after its handshake a connection allocates nothing that
307
- outlives a record. The handshake keeps its state in the slot, which `accept`
308
- restarts, and a KeyUpdate installs its keys in place, so neither leaves
309
- anything in the arena (TLS-3); a connection still takes at most
310
- `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier
311
- has no clock, so
312
- closing quiet slots is the program's (TLS-4). On this path the record layer
313
- wipes `TlsServer`'s traffic and handshake secrets and the ephemeral key once
314
- it has what it needs from them, which narrows TLS-1.
315
- `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block
316
- of `tests/run.js` drives the carrier with openssl and Node's `https`.
321
+ `TLS_RECORD_DONE`.
322
+
323
+ A slot's buffers — about 136 KB of resident memory, measured over a 400-slot
324
+ pool, with the handshake's own state in them — are allocated once, on the first
325
+ accept into the slot, and after its handshake a connection allocates nothing
326
+ that outlives a record. The handshake keeps its state in the slot, which
327
+ `accept` restarts, and a KeyUpdate installs its keys in place, so neither
328
+ leaves anything in the arena (TLS-3); a connection still takes at most
329
+ `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier has
330
+ no clock, so closing quiet slots is the program's (TLS-4). On this path the
331
+ record layer wipes `TlsServer`'s traffic and handshake secrets and the
332
+ ephemeral key once it has what it needs from them, which narrows TLS-1.
333
+ `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block of
334
+ `tests/run.js` drives the carrier with openssl and Node's `https`.
317
335
 
318
336
  **How a server drives `QuicConnection`.** Keep one `QuicListener` for the
319
337
  server, with the same `QuicServerConfig` its connections use: two static keys
@@ -321,34 +339,37 @@ of `QUIC_CONN_STATIC_KEY_SIZE` bytes (the stateless reset key, which has to
321
339
  survive a restart to be any use, and the Retry token key) and whether to
322
340
  ask for Retry. `listener.release()` wipes the listener's seed and scratch
323
341
  when the server stops; the two keys are the caller's to wipe then, unless
324
- `Http3Server.stop` does it (QUIC-5). Route each datagram by
325
- its first packet's DCID: to the connection whose `ownsConnectionId` says it
326
- is its, and anything else to `listener.handle(datagram, address, now)`, which
327
- answers what to send back or says to make a connection — and must see nothing
328
- a live connection owns, or a stateless reset would end that connection.
329
- Make the connection when it says so, with `QUIC_CONN_ENTROPY_SIZE` bytes from
330
- `crypto.getRandomValues`: the TLS server random and x25519 key, the server's
331
- first connection ID and the seed its later IDs are derived from all come out
332
- of them, so a test injects fixed bytes and a recorded exchange replays byte
333
- for byte. Neither has a clock: `now` is the caller's monotonic time in
334
- milliseconds, and `deadline()` says when to call `handleTimer(now)` next.
335
- Hand the connection every datagram the client sends;
342
+ `Http3Server.stop` does it (QUIC-5).
343
+
344
+ Route each datagram by its first packet's DCID: to the connection whose
345
+ `ownsConnectionId` says it is its, and anything else to
346
+ `listener.handle(datagram, address, now)`, which answers what to send back or
347
+ says to make a connection — and must see nothing a live connection owns, or a
348
+ stateless reset would end that connection. Make the connection when it says so,
349
+ with `QUIC_CONN_ENTROPY_SIZE` bytes from `crypto.getRandomValues`: the TLS
350
+ server random and x25519 key, the server's first connection ID and the seed its
351
+ later IDs are derived from all come out of them, so a test injects fixed bytes
352
+ and a recorded exchange replays byte for byte. Neither has a clock: `now` is
353
+ the caller's monotonic time in milliseconds, and `deadline()` says when to call
354
+ `handleTimer(now)` next. Hand the connection every datagram the client sends;
336
355
  when `signatureInput()` answers bytes, sign them (`tlsSignEcdsaP256`) and hand
337
- the signature to `sign`; then send whatever `takeDatagram(now)` answers until it
338
- answers `null`, to the address the datagram came from. `ownsConnectionId`
339
- says whether a datagram's DCID is the connection's, which is how a server
340
- with many routes them. Stream data comes out of `readStream()` in order per
341
- stream, and `writeStream` queues a reply within the credit the client gave.
342
- `state` says where it is, and `error` why it closed. The keys of each level
343
- are wiped when the level is discarded, each key generation when an update
344
- replaces it, and the rest by `release()` or the idle timeout; what no wipe
345
- reaches is QUIC-2 in [`docs/security/quic.md`](../docs/security/quic.md).
356
+ the signature to `sign`; then send whatever `takeDatagram(now)` answers until
357
+ it answers `null`, to the address the datagram came from. `ownsConnectionId`
358
+ says whether a datagram's DCID is the connection's, which is how a server with
359
+ many routes them. Stream data comes out of `readStream()` in order per stream,
360
+ and `writeStream` queues a reply within the credit the client gave. `state`
361
+ says where it is, and `error` why it closed.
362
+
363
+ The keys of each level are wiped when the level is discarded, each key
364
+ generation when an update replaces it, and the rest by `release()` or the idle
365
+ timeout; what no wipe reaches is QUIC-2 in
366
+ [`docs/security/quic.md`](../docs/security/quic.md).
346
367
  `tests/link/net_quic_frame`, `net_quic_conn_parts`, `net_quic_conn`,
347
368
  `net_quic_conn_replay`, `net_quic_lifecycle` and `net_quic_lifecycle_replay`
348
369
  are its programs, each also run under `--number-mode f64`; the two replays
349
- send, over loopback from a Nish UDP client, exchanges recorded against
350
- aioquic by their `record.sh`: a handshake and echo, and Version Negotiation,
351
- Retry, key update both ways, the idle timeout and a stateless reset.
370
+ send, over loopback from a Nish UDP client, exchanges recorded against aioquic
371
+ by their `record.sh`: a handshake and echo, and Version Negotiation, Retry, key
372
+ update both ways, the idle timeout and a stateless reset.
352
373
 
353
374
  `net/http1-codec.ts`, `net/http1-server.ts` and `net/websocket.ts` run their checks
354
375
  again under `--number-mode f64` (`net_http1_f64`, `net_http1_server_f64`,
@@ -374,7 +395,9 @@ specifier works at any depth and from outside this repository.
374
395
  §2), so an import of a `std/` module is not a link against a built library: the
375
396
  module is compiled with the program that imports it, and the whole-program
376
397
  attribute pass sees through it exactly as it sees through the program's own
377
- functions. A `std/` function is inlined, specialised or dropped on the same
398
+ functions.
399
+
400
+ A `std/` function is inlined, specialised or dropped on the same
378
401
  terms as a local one — and a module you import but never call is dropped
379
402
  whole. Measured at the `speed` and `size` profiles, both of which link with
380
403
  `-flto -Wl,--gc-sections`: a program importing three `std/text` functions and
@@ -426,17 +449,18 @@ that are *not* this package.
426
449
 
427
450
  - **Spell the widths — and then convert what the builtins hand you.** `i32`,
428
451
  `i64`, `f64`, never `number`, so the module means the same thing under
429
- `--number-mode f64` as it does by default (`examples/arrays.ts` says that half
430
- for the same reason). It is necessary and **not sufficient**: `s.length`,
431
- `a.length` and `s.charCodeAt(i)` answer `number`, which *is* `f64` in that
432
- mode, so a module that declares every width of its own and still writes
433
- `let end: i32 = text.length` or `while (i < text.length)` does not compile
434
- there at all. Read each of those through `toI32` —
435
- `const length: i32 = toI32(text.length)`, once per function rather than once
436
- per iteration — and the module means one program in both modes. The default
437
- mode pays nothing for it, because `toI32` on an `i32` is identity.
438
- `tests/link/std_text_f64` is what keeps this from being prose;
439
- [`docs/wp26-stdlib.md`](https://github.com/amritk/nish/blob/main/docs/wp26-stdlib.md) §4 is the reasoning.
452
+ `--number-mode f64` as it does by default (`examples/arrays.ts` says that
453
+ half for the same reason). It is necessary and **not sufficient**:
454
+ `s.length`, `a.length` and `s.charCodeAt(i)` answer `number`, which *is*
455
+ `f64` in that mode, so a module that declares every width of its own and
456
+ still writes `let end: i32 = text.length` or `while (i < text.length)` does
457
+ not compile there at all. Read each of those through `toI32` — `const length:
458
+ i32 = toI32(text.length)`, once per function rather than once per iteration —
459
+ and the module means one program in both modes. The default mode pays nothing
460
+ for it, because `toI32` on an `i32` is identity. `tests/link/std_text_f64` is
461
+ what keeps this from being prose;
462
+ [`docs/wp26-stdlib.md`](https://github.com/amritk/nish/blob/main/docs/wp26-stdlib.md)
463
+ §4 is the reasoning.
440
464
  - **Name the private helpers as though they were exported.** A `std/` module
441
465
  belongs to package `nish`, so its symbols no longer collide with the
442
466
  importing program's (`tests/link/std_package_scope`), but every `std/` module
@@ -463,6 +487,7 @@ that are *not* this package.
463
487
  module into the corpus the stage1 oracles read
464
488
  ([`.claude/selfhost.md`](https://github.com/amritk/nish/blob/main/.claude/selfhost.md)): a `std/` module with no
465
489
  importer in `tests/link/` is compiled on no run.
490
+
466
491
  `testing.ts` has two, one per outcome — `tests/link/std_testing` (exit 0) and
467
492
  `tests/link/std_testing_fail` (exit 1, and the wording of every failure
468
493
  message) — and `text.ts` and `json.ts` have `tests/link/std_text` and
package/std/bytes.ts CHANGED
@@ -22,17 +22,20 @@
22
22
  * bytes are its IEEE 754 bits (`f64ToBits`). There is no `f32`: the language
23
23
  * has no bit cast for one.
24
24
  *
25
- * **Each access is an ordinary index**, so an offset whose bytes do not all lie in
26
- * the array panics `index`, naming the first byte that does not. A guard in
27
- * the caller does not yet remove these checks: in a loop guarded by
28
- * `off + 3 < b.length`, the checker proves an index it can see but not one
29
- * inside a call, and after `getU32LE` inlines, LLVM keeps the checks on
30
- * `off + 1` to `off + 3`, because the guard compares the length truncated to
31
- * `i32` and the checks compare it unsigned at 64 bits. A loop that needs them
32
- * gone indexes the bytes itself. `getU64BE`, and with it `getI64BE` and
33
- * `getF64BE`, is the exception: it checks the whole range once and reads the
34
- * eight bytes unchecked, which lowers to one load and a byte swap. An offset
35
- * outside the range still goes byte by byte, so it panics as the others do.
25
+ * **Each access is an ordinary index**, so an offset whose bytes do not all lie
26
+ * in the array panics `index`, naming the first byte that does not.
27
+ *
28
+ * A guard in the caller does not yet remove these checks: in a loop guarded by
29
+ * `off + 3 < b.length`, the checker proves an index it can see but not one
30
+ * inside a call, and after `getU32LE` inlines, LLVM keeps the checks on `off +
31
+ * 1` to `off + 3`, because the guard compares the length truncated to `i32` and
32
+ * the checks compare it unsigned at 64 bits. A loop that needs them gone
33
+ * indexes the bytes itself.
34
+ *
35
+ * `getU64BE`, and with it `getI64BE` and `getF64BE`, is the exception: it
36
+ * checks the whole range once and reads the eight bytes unchecked, which lowers
37
+ * to one load and a byte swap. An offset outside the range still goes byte by
38
+ * byte, so it panics as the others do.
36
39
  *
37
40
  * **The in-range answers are byte for byte those of the copies `std/` keeps for
38
41
  * itself**: `sha256LoadWord` (`std/crypto/sha256.ts`) for `getU32BE`,
@@ -456,14 +459,15 @@ export const skipDigits = (b: u8[], from: i32, to: i32): i32 => {
456
459
  /**
457
460
  * `skipBlank` for the bytes a JSON string holds as themselves: printable ASCII
458
461
  * other than `"` and `\`, and every well-formed UTF-8 sequence (RFC 3629 §4)
459
- * that ends before `to`. The run stops at the first quote, backslash or
460
- * control byte, and at the lead byte of a sequence that is malformed — an
461
- * overlong form, a surrogate, a code point past U+10FFFF, a stray continuation
462
- * byte — or cut short by `to`. So a whole JSON string body with no escape is
463
- * one call, and where it stops is the byte a decoder has to look at. Natively
464
- * the scan is `nish_bytes_skip_json_text`: blocks of ASCII 16 or 32 bytes at a
465
- * time, each multi-byte sequence a byte at a time. Variable-time, as
466
- * `skipBlank` is.
462
+ * that ends before `to`. The run stops at the first quote, backslash or control
463
+ * byte, and at the lead byte of a sequence that is malformed — an overlong
464
+ * form, a surrogate, a code point past U+10FFFF, a stray continuation byte — or
465
+ * cut short by `to`.
466
+ *
467
+ * So a whole JSON string body with no escape is one call, and where it stops is
468
+ * the byte a decoder has to look at. Natively the scan is
469
+ * `nish_bytes_skip_json_text`: blocks of ASCII 16 or 32 bytes at a time, each
470
+ * multi-byte sequence a byte at a time. Variable-time, as `skipBlank` is.
467
471
  *
468
472
  * @param b The bytes scanned; they are not changed.
469
473
  * @param from Where the scan starts, clamped into `[0, to]`.
@@ -9,7 +9,7 @@
9
9
  * let c: u32 = crc.update(toU32(0), body, 0, 100);
10
10
  * c = crc.update(c, body, 100, toI32(body.length) - 100); // the same as one call
11
11
  *
12
- * **Keep a `Crc32`.** A module has no global state, so CRC-32's tables live
12
+ * **Keep a `Crc32`.** A module's only state is zero-filled storage, so CRC-32's tables live
13
13
  * in a `Crc32` object: build one and keep it, because building it is 4,096
14
14
  * table entries (about ten microseconds) and an update of a 5 KB body is
15
15
  * under one. `crc32` is the one-off convenience that builds a table for one