@amritk/nish-x86_64-linux 0.41.0 → 0.44.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.
- package/bin/nish +0 -0
- package/docs/AI.md +282 -126
- package/package.json +2 -2
- package/runtime/core.d.ts +16 -0
- package/runtime/core.mjs +5 -0
- package/runtime/nish.d.ts +204 -33
- package/runtime/nish.h +19 -3
- package/runtime/nish.mjs +5 -1
- package/runtime/runtime-cross.c +15 -0
- package/runtime/runtime-net.c +876 -10
- package/runtime/runtime-region.c +21 -0
- package/runtime/runtime-sandbox.c +112 -15
- package/runtime/runtime-text.c +11 -0
- package/runtime/runtime-uring.c +533 -77
- package/runtime/runtime-wasm.c +3 -0
- package/runtime/runtime.c +474 -5
- package/runtime/sqlite/README.md +16 -3
- package/runtime/sqlite/nish-sqlite.c +940 -29
- package/scripts/build.sh +125 -29
- package/std/README.md +3 -3
- package/std/crypto/base64url.ts +102 -1
- package/std/crypto/scram.ts +142 -0
- package/std/crypto/sha1.ts +99 -41
- package/std/host/ring.ts +1 -1
- package/std/host/text.ts +1 -1
- package/std/net/fetch.ts +9 -1
- package/std/net/handler.ts +79 -15
- package/std/net/http-server.ts +2 -3
- package/std/net/http1-server.ts +294 -51
- package/std/net/http3-server.ts +26 -15
- package/std/net/http3.ts +2 -2
- package/std/net/oidc.ts +1107 -0
- package/std/net/postgres-async.ts +64 -33
- package/std/net/postgres.ts +65 -76
- package/std/net/quic-conn-ack.ts +57 -7
- package/std/net/quic-frame.ts +104 -2
- package/std/net/quic-listener.ts +9 -2
- package/std/net/quic.ts +16 -1
- package/std/net/serve.ts +10 -8
- package/std/net/websocket.ts +188 -49
- package/std/sqlite.ts +325 -0
- package/std/text.ts +80 -11
package/scripts/build.sh
CHANGED
|
@@ -94,6 +94,18 @@
|
|
|
94
94
|
# thread-local global, and ELF will not link that against a non-TLS definition,
|
|
95
95
|
# so a half-threaded build fails at the link rather than at run time.
|
|
96
96
|
#
|
|
97
|
+
# Debug arena: `--debug-arena` compiles the runtime with -DNISH_ARENA_DEBUG, so
|
|
98
|
+
# every arena block gets pages of its own, never reused, and a release turns
|
|
99
|
+
# them PROT_NONE: a stale reference past its scope faults at the read and the
|
|
100
|
+
# runtime names it (docs/security/runtime.md, "The debug arena"). The IR is the
|
|
101
|
+
# same either way; `nish --debug-arena` passes it through. Native profiles only.
|
|
102
|
+
#
|
|
103
|
+
# Compact-class range (WP48 stage 1): `--arena-range` compiles the runtime with
|
|
104
|
+
# -DNISH_ARENA_RANGE, which carves arena chunks of 2 MiB or less from one
|
|
105
|
+
# 15 GiB reservation (at [1 GiB, 16 GiB) on Linux) so a compact class's 32-bit
|
|
106
|
+
# reference can name them. There is no user flag: nish passes it when the
|
|
107
|
+
# program has a compact class (docs/wp48-ref32-classes.md). Native profiles only.
|
|
108
|
+
#
|
|
97
109
|
# Debug info (WP10): `-g` compiles every input with -g and skips the strip
|
|
98
110
|
# step of the speed/size/napi profiles, so the DWARF that `nish -g`
|
|
99
111
|
# put in the .ll (line table, variables) reaches the binary. `nish
|
|
@@ -113,11 +125,13 @@
|
|
|
113
125
|
# passes it through.
|
|
114
126
|
#
|
|
115
127
|
# SQLite: an input .ll that declares an `sqlite3_*` or `nishsqlite_*` function
|
|
116
|
-
# also compiles and links
|
|
117
|
-
# (runtime/sqlite/README.md)
|
|
118
|
-
#
|
|
119
|
-
#
|
|
120
|
-
#
|
|
128
|
+
# also compiles and links runtime/sqlite/nish-sqlite.c, the adapter, which
|
|
129
|
+
# includes sqlite3.c, the vendored amalgamation (runtime/sqlite/README.md), so
|
|
130
|
+
# it can call SQLite's internal B-tree functions (docs/sqlite-cursor.md): every
|
|
131
|
+
# *.c there but sqlite3.c is a unit. Any other program compiles none of it.
|
|
132
|
+
# The unit is compiled to native code at the profile's level, even where the
|
|
133
|
+
# profile compiles to LTO bitcode. The options are most of SQLite's recommended
|
|
134
|
+
# set (see the defaults below), with THREADSAFE=0 (=2 under --threads).
|
|
121
135
|
# NISH_SQLITE_CFLAGS is appended to them: its first line, split on whitespace
|
|
122
136
|
# with no quoting, and a relative -I in it names a directory below
|
|
123
137
|
# runtime/sqlite/, where each unit is compiled. A -D or -U in it for one of
|
|
@@ -138,7 +152,7 @@
|
|
|
138
152
|
# runtime.c input, after compiling every other input
|
|
139
153
|
# with its own $CC -c, all at once. The link line is
|
|
140
154
|
# the one the profile always uses.
|
|
141
|
-
# --sqlite-objects <dir> compile runtime/sqlite
|
|
155
|
+
# --sqlite-objects <dir> compile runtime/sqlite/'s units alone, into
|
|
142
156
|
# <dir>/<unit>.o, as a link of a program that calls
|
|
143
157
|
# SQLite would, and link nothing. Takes no inputs and
|
|
144
158
|
# no -o, and prints nothing on success.
|
|
@@ -151,6 +165,19 @@
|
|
|
151
165
|
# not, so the caller keeps every object it compiled
|
|
152
166
|
# (`nish run`'s module cache, src/build-cache.ts).
|
|
153
167
|
# The inputs' file names must differ.
|
|
168
|
+
# --link-lib <name> debug, speed and size only: link the C library
|
|
169
|
+
# <name> (-l<name>, after the inputs and before -lm);
|
|
170
|
+
# <name> is [A-Za-z0-9_][A-Za-z0-9_.+-]*, so it is
|
|
171
|
+
# never a flag. A package's `nish.link.libraries`
|
|
172
|
+
# (WP66 S7, docs/security/package-link.md).
|
|
173
|
+
# --link-source <file.c> debug, speed and size only: compile the C file, an
|
|
174
|
+
# absolute path, with the profile's flags and link
|
|
175
|
+
# it with the program. A package's `nish.link.sources`.
|
|
176
|
+
# --link-depends <file.c> debug, speed and size only: print, as a make rule
|
|
177
|
+
# (clang -M), the files it lists for the compile of
|
|
178
|
+
# that source with this profile's flags, and link
|
|
179
|
+
# nothing.
|
|
180
|
+
# `nish run` keys its cache on them.
|
|
154
181
|
#
|
|
155
182
|
# Works on Linux (clang + lld preferred, GNU ld tolerated) and macOS (Apple ld64
|
|
156
183
|
# or Homebrew llvm). Set CC to pick a compiler (default: clang on PATH).
|
|
@@ -162,6 +189,8 @@ inputs=()
|
|
|
162
189
|
pgo=() # -fprofile-generate / -fprofile-use=<file>
|
|
163
190
|
debug=0 # -g: keep DWARF (nish -g emits it in the IR; runtime.c gets it here)
|
|
164
191
|
threads=0 # --threads: -DNISH_THREADS, the thread-local arena (WP20 T0)
|
|
192
|
+
debug_arena=0 # --debug-arena: -DNISH_ARENA_DEBUG, the arena that traps a stale reference
|
|
193
|
+
arena_range=0 # --arena-range: -DNISH_ARENA_RANGE, the compact-class range (WP48)
|
|
165
194
|
objects_to="" # --runtime-objects <dir>: compile the runtime alone, into <dir>
|
|
166
195
|
objects_from="" # --runtime-from <dir>: link against the runtime compiled there
|
|
167
196
|
cpu="" # --cpu x86-64-v3: the one CPU level above the baseline (WP38 S2)
|
|
@@ -171,12 +200,17 @@ modules_at="" # --module-objects <dir>: each X.ll's obj
|
|
|
171
200
|
memory_mib="" # --memory <MiB>: wasm-host's fixed memory (WP50 stage 1)
|
|
172
201
|
wasm_opt="" # what the build line says of wasm-opt; set only by wasm-host
|
|
173
202
|
inline_to="" # --inline <file.mjs>: wasm-host's bytes as an ES module
|
|
203
|
+
link_libs=() # --link-lib <name>: -l<name> on the link line (WP66 S7)
|
|
204
|
+
link_sources=() # --link-source <file.c>: a package's own C, compiled into the link
|
|
205
|
+
link_depends="" # --link-depends <file.c>: print what its compile reads, then stop
|
|
174
206
|
while [ $# -gt 0 ]; do
|
|
175
207
|
case "$1" in
|
|
176
208
|
-o) out="$2"; shift 2 ;;
|
|
177
209
|
--profile) profile="$2"; shift 2 ;;
|
|
178
210
|
-g) debug=1; shift ;;
|
|
179
211
|
--threads) threads=1; shift ;;
|
|
212
|
+
--debug-arena) debug_arena=1; shift ;;
|
|
213
|
+
--arena-range) arena_range=1; shift ;;
|
|
180
214
|
--cpu)
|
|
181
215
|
[ -n "${2-}" ] || { echo "error: --cpu needs a level; the one taken is x86-64-v3" >&2; exit 2; }
|
|
182
216
|
cpu="$2"; shift 2 ;;
|
|
@@ -191,6 +225,21 @@ while [ $# -gt 0 ]; do
|
|
|
191
225
|
--inline)
|
|
192
226
|
[ -n "${2-}" ] || { echo "error: --inline needs a file to write" >&2; exit 2; }
|
|
193
227
|
inline_to="$2"; shift 2 ;;
|
|
228
|
+
--link-lib)
|
|
229
|
+
[[ "${2-}" =~ ^[A-Za-z0-9_][A-Za-z0-9_.+-]*$ ]] || { echo "error: --link-lib takes a library name of letters, digits, _ . + and -, not '${2-}'" >&2; exit 2; }
|
|
230
|
+
link_libs+=("-l$2"); shift 2 ;;
|
|
231
|
+
--link-source)
|
|
232
|
+
case "${2-}" in
|
|
233
|
+
/*.c) [ -f "$2" ] || { echo "error: --link-source: $2 is not a file" >&2; exit 2; } ;;
|
|
234
|
+
*) echo "error: --link-source takes the absolute path of a .c file, not '${2-}'" >&2; exit 2 ;;
|
|
235
|
+
esac
|
|
236
|
+
link_sources+=("$2"); shift 2 ;;
|
|
237
|
+
--link-depends)
|
|
238
|
+
case "${2-}" in
|
|
239
|
+
/*.c) [ -f "$2" ] || { echo "error: --link-depends: $2 is not a file" >&2; exit 2; } ;;
|
|
240
|
+
*) echo "error: --link-depends takes the absolute path of a .c file, not '${2-}'" >&2; exit 2 ;;
|
|
241
|
+
esac
|
|
242
|
+
link_depends="$2"; shift 2 ;;
|
|
194
243
|
--pgo-generate) pgo=(-fprofile-generate); shift ;;
|
|
195
244
|
--pgo-use)
|
|
196
245
|
[ -f "$2" ] || { echo "error: --pgo-use: profile '$2' not found (run the instrumented binary, then llvm-profdata merge)" >&2; exit 2; }
|
|
@@ -199,13 +248,24 @@ while [ $# -gt 0 ]; do
|
|
|
199
248
|
*) inputs+=("$1"); shift ;;
|
|
200
249
|
esac
|
|
201
250
|
done
|
|
202
|
-
[ ${#inputs[@]} -gt 0 ] || [ -n "$sqlite_to" ] || { echo "error: no input files" >&2; exit 2; }
|
|
251
|
+
[ ${#inputs[@]} -gt 0 ] || [ -n "$sqlite_to" ] || [ -n "$link_depends" ] || { echo "error: no input files" >&2; exit 2; }
|
|
203
252
|
if [ -n "$cpu" ]; then
|
|
253
|
+
[ "$cpu" != native ] || { echo "error: --cpu native is refused: under clang 18 the constant-time check (CT-16) refuses the assembly made for some CPUs native names (znver2 to znver4, sapphirerapids); --cpu takes x86-64-v3" >&2; exit 2; }
|
|
204
254
|
[ "$cpu" = x86-64-v3 ] || { echo "error: --cpu takes x86-64-v3, not '$cpu'" >&2; exit 2; }
|
|
205
255
|
case "$profile" in
|
|
206
256
|
wasm|wasm-host|wasi) echo "error: --cpu x86-64-v3 is an x86-64 level, so the $profile profile does not take it" >&2; exit 2 ;;
|
|
207
257
|
esac
|
|
208
258
|
fi
|
|
259
|
+
if [ "$debug_arena" = 1 ]; then
|
|
260
|
+
case "$profile" in
|
|
261
|
+
wasm|wasm-host|wasi|napi) echo "error: --debug-arena maps pages and catches SIGSEGV, so the $profile profile does not take it" >&2; exit 2 ;;
|
|
262
|
+
esac
|
|
263
|
+
fi
|
|
264
|
+
if [ "$arena_range" = 1 ]; then
|
|
265
|
+
case "$profile" in
|
|
266
|
+
wasm|wasm-host|wasi|napi) echo "error: --arena-range reserves a fixed address range, so the $profile profile does not take it" >&2; exit 2 ;;
|
|
267
|
+
esac
|
|
268
|
+
fi
|
|
209
269
|
if [ -n "$memory_mib" ] || [ -n "$inline_to" ]; then
|
|
210
270
|
[ "$profile" = wasm-host ] || { echo "error: --memory and --inline take the wasm-host profile, not '$profile'" >&2; exit 2; }
|
|
211
271
|
fi
|
|
@@ -271,7 +331,7 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
|
|
|
271
331
|
[ -z "$sqlite_to" ] || [ -z "$sqlite_from" ] || { echo "error: --sqlite-objects and --sqlite-from are two different builds" >&2; exit 2; }
|
|
272
332
|
[ -z "$sqlite_to" ] || [ -z "$objects_to$objects_from" ] || { echo "error: --sqlite-objects compiles runtime/sqlite/ alone, without --runtime-objects or --runtime-from" >&2; exit 2; }
|
|
273
333
|
fi
|
|
274
|
-
[ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
|
|
334
|
+
[ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || [ -n "$link_depends" ] || { echo "error: -o <out> is required" >&2; exit 2; }
|
|
275
335
|
|
|
276
336
|
# The runtime is eighteen translation units, and a caller names one: whoever passes
|
|
277
337
|
# <dir>/runtime.c gets <dir>/runtime-text.c, <dir>/runtime-os.c, <dir>/runtime-parallel.c,
|
|
@@ -311,8 +371,8 @@ done
|
|
|
311
371
|
|
|
312
372
|
# SQLite (runtime/sqlite/) is an optional unit, and the IR selects it. A module
|
|
313
373
|
# that declares a function of SQLite's C API (`sqlite3_*`) or of the adapter
|
|
314
|
-
# beside it (`nishsqlite_*`) gets
|
|
315
|
-
# linked. Any other program compiles none of it, so its link line and binary
|
|
374
|
+
# beside it (`nishsqlite_*`) gets runtime/sqlite/'s units (`sqlite_units`)
|
|
375
|
+
# compiled and linked. Any other program compiles none of it, so its link line and binary
|
|
316
376
|
# stay as they were. The test reads `declare` lines, and only before the first
|
|
317
377
|
# `"` on one, rather than any `@sqlite3_` in the file, because a string
|
|
318
378
|
# constant or a quoted name may hold one. It is one rule with `callsSqlite` in
|
|
@@ -519,6 +579,8 @@ if [ "$threads" = 1 ]; then
|
|
|
519
579
|
common+=(-DNISH_THREADS=1 -ftls-model=initial-exec -pthread)
|
|
520
580
|
tls=(-DNISH_THREADS=1 -ftls-model=initial-exec)
|
|
521
581
|
fi
|
|
582
|
+
if [ "$debug_arena" = 1 ]; then common+=(-DNISH_ARENA_DEBUG=1); fi
|
|
583
|
+
if [ "$arena_range" = 1 ]; then common+=(-DNISH_ARENA_RANGE=1); fi
|
|
522
584
|
|
|
523
585
|
# What the speed and size profiles compile every input with, beside `common`.
|
|
524
586
|
# One list per profile, because the runtime cache below compiles with exactly
|
|
@@ -540,6 +602,20 @@ case "$profile" in
|
|
|
540
602
|
-fno-asynchronous-unwind-tables -fno-unwind-tables ${elf[@]+"${elf[@]}"}) ;;
|
|
541
603
|
esac
|
|
542
604
|
|
|
605
|
+
# --link-depends: the files clang -M lists for a package source's compile,
|
|
606
|
+
# every header and every #included file of any name, with the flags the link
|
|
607
|
+
# line compiles that source with (`common` and the profile's `optimise`), so
|
|
608
|
+
# `nish run` keys those rather than guessing at them by name. clang -M does
|
|
609
|
+
# not list a file an assembler `.incbin` reads, nor a header that would shadow
|
|
610
|
+
# a listed one if it appeared later (docs/security/package-link.md, PL-6, PL-10).
|
|
611
|
+
if [ -n "$link_depends" ]; then
|
|
612
|
+
case "$profile" in
|
|
613
|
+
debug) exec "$CC" "${common[@]}" -Wno-unused-command-line-argument -M "$link_depends" ;;
|
|
614
|
+
speed|size) exec "$CC" "${common[@]}" "${optimise[@]}" -Wno-unused-command-line-argument -M "$link_depends" ;;
|
|
615
|
+
*) echo "error: --link-depends takes the debug, speed and size profiles, not '$profile'" >&2; exit 2 ;;
|
|
616
|
+
esac
|
|
617
|
+
fi
|
|
618
|
+
|
|
543
619
|
# The speed link splits full LTO's code generation into one partition per core,
|
|
544
620
|
# run in parallel: lld's --lto-partitions, after the whole program is optimised
|
|
545
621
|
# as one module, so inlining does not change. But a partition boundary promotes
|
|
@@ -646,29 +722,40 @@ for d in -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_DEFAULT_WAL_SYNCHR
|
|
|
646
722
|
done
|
|
647
723
|
sqlite_defs+=(${sqlite_extra[@]+"${sqlite_extra[@]}"})
|
|
648
724
|
|
|
649
|
-
#
|
|
650
|
-
#
|
|
651
|
-
#
|
|
652
|
-
#
|
|
653
|
-
#
|
|
654
|
-
#
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
725
|
+
# The units of runtime/sqlite/: every *.c but sqlite3.c, the amalgamation,
|
|
726
|
+
# which nish-sqlite.c compiles by including it. SQLite's B-tree and record
|
|
727
|
+
# functions are static there, and the cursor adapter calls them, so the two
|
|
728
|
+
# must be one translation unit (docs/sqlite-cursor.md, "The build decision").
|
|
729
|
+
# One name a line; callers read them with `while read`, so a name is never
|
|
730
|
+
# split on spaces.
|
|
731
|
+
sqlite_unit_names() {
|
|
732
|
+
local unit
|
|
733
|
+
for unit in "$sqlite_dir"/*.c; do
|
|
734
|
+
unit=${unit##*/}
|
|
735
|
+
[ "$unit" = sqlite3.c ] || printf '%s\n' "$unit"
|
|
736
|
+
done
|
|
737
|
+
}
|
|
738
|
+
# Compiles every unit of runtime/sqlite/ with the flags given, all at once,
|
|
739
|
+
# into $1/<unit>.o. Each unit is compiled from inside runtime/sqlite/ by its
|
|
740
|
+
# bare name, as the runtime is, so -g's DWARF names no directory the link was
|
|
741
|
+
# started in. Each is compiled to native code even where the profile compiles
|
|
742
|
+
# to LTO bitcode, because nish-sqlite.c holds the 9.6 MB amalgamation. As
|
|
743
|
+
# bitcode, every link of a program that uses it would generate its code
|
|
744
|
+
# again: measured on a program that opens a database and runs a query, that
|
|
745
|
+
# is 10.6 s a link at -O3, against 0.04 s for the native object. So `-flto`
|
|
746
|
+
# comes off.
|
|
659
747
|
sqlite_units() {
|
|
660
748
|
local to=$1 unit flag
|
|
661
749
|
local -a flags
|
|
662
750
|
shift
|
|
663
|
-
|
|
664
|
-
unit=${unit##*/}
|
|
751
|
+
while IFS= read -r unit; do
|
|
665
752
|
flags=()
|
|
666
753
|
for flag in "$@"; do
|
|
667
|
-
case "$
|
|
754
|
+
case "$flag" in -flto) ;; *) flags+=("$flag") ;; esac
|
|
668
755
|
done
|
|
669
756
|
(cd -- "$sqlite_dir" && exec "$CC" "${flags[@]}" "${sqlite_defs[@]}" -I. -c "$unit" -o "$to/${unit%.c}.o") &
|
|
670
757
|
pids+=("$!")
|
|
671
|
-
done
|
|
758
|
+
done < <(sqlite_unit_names)
|
|
672
759
|
join_jobs || { echo "error: runtime/sqlite/ did not compile" >&2; exit 1; }
|
|
673
760
|
}
|
|
674
761
|
# Adds the objects of runtime/sqlite/ to this link, in the order of the units.
|
|
@@ -684,11 +771,10 @@ sqlite_objects() {
|
|
|
684
771
|
mkdir -p -- "$from"
|
|
685
772
|
sqlite_units "$from" "$@"
|
|
686
773
|
fi
|
|
687
|
-
|
|
688
|
-
unit=${unit##*/}
|
|
774
|
+
while IFS= read -r unit; do
|
|
689
775
|
[ -f "$from/${unit%.c}.o" ] || { echo "error: --sqlite-from: $from/${unit%.c}.o is missing" >&2; exit 2; }
|
|
690
776
|
inputs+=("$from/${unit%.c}.o")
|
|
691
|
-
done
|
|
777
|
+
done < <(sqlite_unit_names)
|
|
692
778
|
}
|
|
693
779
|
|
|
694
780
|
if [ -n "$sqlite_to" ]; then
|
|
@@ -770,12 +856,22 @@ fi
|
|
|
770
856
|
# why Linux never noticed. `pgo`, `elf`, `strip_flag` and `libs` are all empty on
|
|
771
857
|
# ordinary builds, so please do not simplify these back.
|
|
772
858
|
case "$profile" in debug|speed|size) sqlite_objects "${compile[@]}" ;; esac
|
|
859
|
+
# A package's own C sources join the inputs here, after the runtime's halves
|
|
860
|
+
# and SQLite were decided from the IR alone, so a source can neither stand in
|
|
861
|
+
# for runtime.c nor be taken for one of its siblings. clang compiles each by
|
|
862
|
+
# its .c name on the one link line, with the profile's flags.
|
|
863
|
+
if [ ${#link_libs[@]} -gt 0 ] || [ ${#link_sources[@]} -gt 0 ]; then
|
|
864
|
+
case "$profile" in
|
|
865
|
+
debug|speed|size) inputs+=(${link_sources[@]+"${link_sources[@]}"}) ;;
|
|
866
|
+
*) echo "error: --link-lib and --link-source take the debug, speed and size profiles, not '$profile'" >&2; exit 2 ;;
|
|
867
|
+
esac
|
|
868
|
+
fi
|
|
773
869
|
case "$profile" in
|
|
774
870
|
debug)
|
|
775
|
-
"$CC" "${common[@]}" "${inputs[@]}" -lm -o "$out" ;;
|
|
871
|
+
"$CC" "${common[@]}" "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} -lm -o "$out" ;;
|
|
776
872
|
speed|size)
|
|
777
873
|
"$CC" "${common[@]}" "${optimise[@]}" ${lto_parts[@]+"${lto_parts[@]}"} \
|
|
778
|
-
"${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" -lm -o "$out" ;;
|
|
874
|
+
"${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} -lm -o "$out" ;;
|
|
779
875
|
wasm|wasm-host)
|
|
780
876
|
# A region's chunks come from malloc, and the freestanding wasm runtime
|
|
781
877
|
# (runtime-wasm.c) has none, so IR that makes or enters one is refused here
|
package/std/README.md
CHANGED
|
@@ -113,8 +113,8 @@ is listed in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.m
|
|
|
113
113
|
| [`crypto/ct.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ct.ts) | `timingSafeEqual(a, b)`, which reads every byte whatever it holds, and `timingSafeEqualAt(a, aOff, b, bOff, len)` over two windows, which answers `false` for a window outside its array. Two lengths that differ answer `false` at once, because a length is public, and so does an array longer than 2^31 − 1 bytes | — |
|
|
114
114
|
| [`crypto/bcrypt.ts`](https://github.com/amritk/nish/blob/main/std/crypto/bcrypt.ts) | `bcryptHash(password, salt, cost)`, the 60-character `$2b$` hash of a `Secret<u8[]>` password under a 16-byte salt and a cost of 4 to 31, and `bcryptVerify(password, hash)`, which reads `$2a$`, `$2b$` and `$2y$` hashes, refuses `$2x$`, and compares in constant time. The first 72 bytes of a password count, up to its first NUL, as under libxcrypt's `crypt_r` (where other implementations differ: [the interoperability table](../docs/security/crypto-bcrypt.md#interoperability)); the Blowfish state is wiped before either returns. `bcryptHash4(p0, p1, p2, p3, salts, cost)` and `bcryptVerify4(p0, p1, p2, p3, hashes)` do up to four at once, interleaved (four in the time of about 1.2 single hashes on one core), each lane the single path's answer; verify groups lanes by cost, and a malformed lane makes the whole call an `Err` naming it. `BCRYPT_MAX_PASSWORD`, `BCRYPT_HASH_LENGTH`, `BCRYPT_SALT_SIZE`, `BCRYPT_MIN_COST`, `BCRYPT_MAX_COST`. A `std/threads` task may call all four ([BCRYPT-9](../docs/security/crypto-bcrypt.md#findings)) | OpenBSD `bcrypt(3)`; crypt_blowfish 1.3 for `$2a$` and `$2y$` |
|
|
115
115
|
| [`crypto/bcrypt-batch.ts`](https://github.com/amritk/nish/blob/main/std/crypto/bcrypt-batch.ts) | `bcryptBatcher({ width, holdNanos, cores, cost })`, a login batcher: `verify(password, hash, now)` and `hash(password, salt, now)` queue a request and answer its ticket, `waitNanos(now)` says when a run is due (a full batch, or the oldest request held `holdNanos`), and `run(now)` sends up to `width × cores` requests as `bcryptVerifyN` / `bcryptHashN` batches on one `std/threads` task per core and answers a `BcryptAnswer` (`ticket`, `ok`, `hash`, `error`) for each. It keeps and wipes its own copy of each password; a damaged stored hash answers its `Err` on its own row ([the record](../docs/security/crypto-bcrypt.md#the-login-batcher)) | — |
|
|
116
|
-
| [`crypto/base64url.ts`](https://github.com/amritk/nish/blob/main/std/crypto/base64url.ts) | `base64urlEncode(data)` and `base64urlDecode(text)`, unpadded; `base64StdPadEncode(data)` and `base64StdPadDecode(text)`, the padded standard alphabet that SCRAM and PEM use, constant-time in both directions. These are not `nish/base64`, which encodes only, is not constant-time and is for pixels; the names differ because std modules share the program's one namespace. Decoding is strict, so every byte string has one spelling. `base64urlDecode` answers `null` for any `=`, a character outside the alphabet, a length of 1 mod 4 or nonzero unused low bits; `base64StdPadDecode` requires the padding, answering `null` unless the text is whole four-character groups with `=` only as the last one or two characters, every other character in the alphabet and the unused bits zero. Both refuse a text longer than 2^31 − 1 bytes, and `base64urlEncode` panics on such an array | RFC 4648 §4, §5, §10 (`tests/link/std_base64_padded`) |
|
|
117
|
-
| [`crypto/sha1.ts`](https://github.com/amritk/nish/blob/main/std/crypto/sha1.ts) | `sha1(data)`, a fresh 20-byte digest, and `SHA1_SIZE` and `SHA1_BLOCK`. **Not for security**: SHA-1 is broken for collisions, and it is here only because RFC 6455 §4.2.2's `Sec-WebSocket-Accept` is defined on it (`nish/net/websocket` is its importer). One-shot only; it panics on an array longer than 2^31 − 1 bytes. It came after the #363 audit and has no record in `docs/security/` | FIPS 180-4 §6.1 |
|
|
116
|
+
| [`crypto/base64url.ts`](https://github.com/amritk/nish/blob/main/std/crypto/base64url.ts) | `base64urlEncode(data)` and `base64urlDecode(text)`, unpadded; `base64StdPadEncode(data)` and `base64StdPadDecode(text)`, the padded standard alphabet that SCRAM and PEM use, with the buffer forms `base64StdPadEncodeInto(data, start, length, out, at)` and `base64StdPadDecodedLength(text, start, length)` that allocate nothing, constant-time in both directions. These are not `nish/base64`, which encodes only, is not constant-time and is for pixels; the names differ because std modules share the program's one namespace. Decoding is strict, so every byte string has one spelling. `base64urlDecode` answers `null` for any `=`, a character outside the alphabet, a length of 1 mod 4 or nonzero unused low bits; `base64StdPadDecode` requires the padding, answering `null` unless the text is whole four-character groups with `=` only as the last one or two characters, every other character in the alphabet and the unused bits zero. Both refuse a text longer than 2^31 − 1 bytes, and `base64urlEncode` panics on such an array | RFC 4648 §4, §5, §10 (`tests/link/std_base64_padded`) |
|
|
117
|
+
| [`crypto/sha1.ts`](https://github.com/amritk/nish/blob/main/std/crypto/sha1.ts) | `sha1(data)`, a fresh 20-byte digest, `Sha1`, whose `digestInto(data, start, length, out, at)` hashes a slice into a caller's buffer and allocates nothing after it is built, and `SHA1_SIZE` and `SHA1_BLOCK`. **Not for security**: SHA-1 is broken for collisions, and it is here only because RFC 6455 §4.2.2's `Sec-WebSocket-Accept` is defined on it (`nish/net/websocket` is its importer). One-shot only, not streaming; it panics on an array longer than 2^31 − 1 bytes. It came after the #363 audit and has no record in `docs/security/` | FIPS 180-4 §6.1 |
|
|
118
118
|
| [`crypto/x25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x25519.ts) | `x25519(scalar, u)`, the shared secret as a `Secret<u8[]>`, and `x25519Base(scalar)`, the public key, each from a `Secret<u8[]>` scalar, on ten 25.5-bit limbs in `i64`. Either answers `null` unless its arguments are `X25519_SIZE` (32) bytes; the scalar is clamped on a copy, which is wiped | RFC 7748 §5.2, §6.1, Wycheproof `x25519_test` |
|
|
119
119
|
| [`crypto/ed25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ed25519.ts) | `ed25519PublicKey(seed)`, the 32-byte public key, `ed25519Sign(seed, msg)`, the 64-byte signature `R \|\| S`, each from a `Secret<u8[]>` seed of `ED25519_SEED_SIZE` (32) bytes or `null`, and `ed25519Verify(pub, msg, sig)`. Signing is deterministic and constant time; the seed's hash, the nonce and every intermediate the scalar reaches are wiped. Verify is cofactorless, refuses an S of L or more and a key that does not decode, and is variable time, since its inputs are public. Sign and verify panic on a message longer than 2^31 − 1 bytes. It reuses `crypto/x25519.ts`'s field arithmetic | RFC 8032 §5.1, §7.1 |
|
|
120
120
|
| [`crypto/chacha20poly1305.ts`](https://github.com/amritk/nish/blob/main/std/crypto/chacha20poly1305.ts) | `chacha20Poly1305Seal(key, nonce, aad, plaintext)`, which answers the ciphertext followed by the 16-byte tag, and `chacha20Poly1305Open`, which checks the whole tag before it decrypts anything and answers `null` for a message that does not authenticate. Beneath them `chacha20Block`, `chacha20`, `chacha20QuarterRound`, `poly1305` and `poly1305KeyGen`, and `chacha20HeaderMask`, QUIC's 5-byte header-protection mask. Every input of the wrong length answers `null`. What a call derives from the key — the ChaCha20 state, the keystream, the Poly1305 key, `r` and accumulator, and on open the tag it compared — is wiped with `wipe`'s volatile stores before the call returns, the refusal path included. Natively, on x86-64 with AVX2 or on AArch64, the compiler sends the keystream of a message of 256 bytes or more to the runtime's kernel instead (`runtime/runtime-chacha20.c`), and `NISH_CHACHA20=soft` pins the Nish code | RFC 8439 §2, RFC 9001 §5.4.4, Wycheproof `chacha20_poly1305` (all 325 cases) |
|
|
@@ -257,7 +257,7 @@ reads one, and it still takes its randomness as an argument.
|
|
|
257
257
|
| [`net/fetch.ts`](https://github.com/amritk/nish/blob/main/std/net/fetch.ts) | A blocking HTTP/1.1 client for command-line programs: `fetchSync(request, options)` looks the host up, connects, sends an `HttpRequest` (`method`, `url`, `header(name, value)`, `body`) and answers an `HttpResponse` (`status`, `reason`, `url`, `header(name)`) once its head is in, its body read through `body.read` or `body.readAll(limit)`; null on a failure. `FetchSyncClient(options)` does the same and keeps one connection alive between fetches, sending an idempotent request once more when a kept connection turns out to be gone, and says why a fetch failed in `error` (an `HTTP_E_*` code, `httpErrorName`) and `errorText`. `HttpOptions` bounds every wait (`connectTimeoutMs`, `readTimeoutMs`, `totalTimeoutMs`) and every body (`maxBodyBytes`), follows redirects only when asked (`followRedirects`, `maxRedirects`, `crossOriginRedirects`, never https to http, credentials dropped across origins), and reads `http_proxy`, `https_proxy` and `no_proxy` when `useEnvProxy` is set (`HTTP_PROXY` ignored under CGI; https through `CONNECT`). Every byte goes through `nish/net/http1-client-codec`. Native only. Record: [`docs/security/fetch.md`](../docs/security/fetch.md) | RFC 9110 §9.2.2 and §15.4, RFC 9112; a loopback server and proxy in the test itself: keep-alive, retries, redirects, proxies, timeouts and body caps (`tests/link/net_http_fetch`) |
|
|
258
258
|
| [`net/outbound.ts`](https://github.com/amritk/nish/blob/main/std/net/outbound.ts) | The policy for fetching URLs your program did not choose, set as `HttpOptions.outbound`: `OutboundPolicy` reaches only public addresses (no loopback, private, link-local, CGNAT, metadata or other special-purpose range, IPv4-mapped, NAT64 and 6to4 forms judged as the IPv4 address they carry), checked on the resolved address the client then connects to, so DNS rebinding cannot move it; every redirect hop is checked again, the proxy is not used, and redirects, total time and body size are capped. `permit(cidr)` lets a trusted prefix through, `allowHost(name)` limits the names a URL or hop may carry (`HTTP_E_BLOCKED` before the lookup). Native only. Record: [`docs/security/outbound.md`](../docs/security/outbound.md) | RFC 6890, RFC 4291, RFC 6052, RFC 3056 and the IANA special-purpose address registries; every range at its edges and a loopback server fetched with and without a policy (`tests/link/net_outbound`) |
|
|
259
259
|
| [`net/tls/ticket.ts`](https://github.com/amritk/nish/blob/main/std/net/tls/ticket.ts) | Session tickets a server seals for itself (RFC 8446 §4.6.1): `tlsTicketSeal` and `tlsTicketOpen` seal a `TlsTicketState` (suite, issue time, lifetime, chain start, server name, resumption PSK) under ChaCha20-Poly1305 with a borrowed `Secret<u8[]>` key, as key id ‖ nonce ‖ ciphertext ‖ tag, and wipe the plaintext on every path. `TlsTicketKeyInfo`, `tlsTicketKeyDraw` and `tlsTicketKeyDue` are a key's public record, its draw and when to replace it: a key seals for 12 h of awake time and 2^30 tickets, and opens for 14 h. `TlsTicketStrikes` is the bounded strike register (§8.1) that makes a ticket single-use, failing closed when full | `tests/link/net_tls_ticket`: every bound at its instant and 1 ns past it, a flipped bit in each region, three key rotations, replay and a full register |
|
|
260
|
-
| [`net/websocket.ts`](https://github.com/amritk/nish/blob/main/std/net/websocket.ts) | `WsDecoder(expectMasked, maxMessage)`, the same `feed` and `next()` over WebSocket frames: `WS_MESSAGE` (fragments joined, text checked as UTF-8 fragment by fragment), `WS_PING`, `WS_PONG`, and the final `WS_CLOSE` and `WS_ERROR`, whose `closeCode` is the 1002, 1007 or 1009 to close with. `websocketFrame` encodes a frame with the mask key the caller supplies (`websocketWriteFrame` into a caller's buffer, `websocketFrameSize` its length), `reset()` readies a decoder for the next connection, `websocketClosePayload` a close frame's code and reason, and `websocketIsUtf8` checks a window. The handshake is `websocketRequestKey(parser)` over an `Http1Parser`'s head, `websocketAcceptKey`, `websocketKeyIsValid`, `websocketOfferedProtocols` and `websocketUpgradeResponse`, the 101. The client's side is `websocketClientKey(nonce)` (a 16-byte nonce the caller draws; the module draws no randomness), `websocketUpgradeRequest(host, target, key, protocols)` and `websocketCheckResponse(parser, key, offered)` over an `Http1ResponseParser` told `expectUpgrade()`, answering a `WsHandshake` (`error`, a `WS_HS_*` code, and `protocol`) | RFC 6455 §1.3's accept key, the §5.7 example frames byte for byte, §5.5's control-frame rules, §7.4's close codes |
|
|
260
|
+
| [`net/websocket.ts`](https://github.com/amritk/nish/blob/main/std/net/websocket.ts) | `WsDecoder(expectMasked, maxMessage)`, the same `feed` and `next()` over WebSocket frames: `WS_MESSAGE` (fragments joined, text checked as UTF-8 fragment by fragment), `WS_PING`, `WS_PONG`, and the final `WS_CLOSE` and `WS_ERROR`, whose `closeCode` is the 1002, 1007 or 1009 to close with. `websocketFrame` encodes a frame with the mask key the caller supplies (`websocketWriteFrame` into a caller's buffer, `websocketFrameSize` its length), `reset()` readies a decoder for the next connection, `websocketClosePayload` a close frame's code and reason, and `websocketIsUtf8` checks a window. The handshake is `websocketRequestKey(parser)` over an `Http1Parser`'s head, `websocketAcceptKey`, `websocketKeyIsValid`, `websocketOfferedProtocols` and `websocketUpgradeResponse`, the 101; `WsAcceptKey`, `websocketRequestKeyField` and `websocketWriteUpgradeResponse`, the same accept written into storage a server keeps, so a connection's later handshakes allocate nothing. The client's side is `websocketClientKey(nonce)` (a 16-byte nonce the caller draws; the module draws no randomness), `websocketUpgradeRequest(host, target, key, protocols)` and `websocketCheckResponse(parser, key, offered)` over an `Http1ResponseParser` told `expectUpgrade()`, answering a `WsHandshake` (`error`, a `WS_HS_*` code, and `protocol`) | RFC 6455 §1.3's accept key, the §5.7 example frames byte for byte, §5.5's control-frame rules, §7.4's close codes |
|
|
261
261
|
| [`net/http1-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-server.ts) | The server side of HTTP/1.1: `Http1Connection`, sans-IO, drives an `Http1Parser` — `feed`, then `next()` answers `H1_REQUEST` (the parser's head), `H1_BODY` (at most `chunkSize` bytes, either framing), `H1_END`, `H1_WRITE` (a held-back write may go again), `H1_WS_MESSAGE`, `H1_WS_CLOSE` or the final `H1_ERROR`; the program answers with `respond(status, names, values, bodyLength)`, `write` and `end`, or `acceptWebSocket(protocol)` and then `sendFrame` and `closeWebSocket`. Keep-alive and pipelining one exchange at a time, a response with a length or chunked (unframed to an HTTP/1.0 client), `Connection` and the framing decided by the server, every parser refusal answered with its status and a close, pings and closes answered on a WebSocket. Two slot pools for a program that owns its loop: `Http1Server` on plain TCP and `Http1TlsServer` on `nish/net/tls-tcp` with ALPN `http/1.1` or none (`accept`, `readable` / `writable`, `next(slot)`, `flush(slot)`, `close`, `expire(now)` for the idle timeout and the deadline for a whole head, `headTimeout`, against a client that trickles its head). Both build a slot's connection on the first accept into it rather than at start-up. `Http1Server` reads a socket until a short read rather than until it would block, takes a free slot off a stack of released slots or the next never-used one rather than scanning for one, and answers `rearm(slot, wants)`, whether the interest changed and needs a `pollModify` at all: a keep-alive request is one `recv` and one `send`. The slots borrow their output from one `Http1OutputPool` while they write and give it back once sent, so a pool's memory follows the connections the socket is holding back, not its size: an idle slot holds no output buffer. Every final response carries a `Date` from `HttpDate`, which reads `Date.now()` and formats at most once a second, shared by a pool's slots; `pin(unixMs)` fixes it for a test, and a program's own `date` field replaces it. Every cap is an `Http1Config` number fixed at start-up, and a warmed slot allocates nothing per request (`docs/security/http1-codec.md`). Native only, as `nish:net` is | RFC 9112 §6, §7, §9; RFC 9110 §9.3.2, §15; RFC 6455 §4.2, §5.5. Nish clients over loopback against both carriers, requests cut at every byte, 2 MiB bodies each way, pipelining, a WebSocket echo, the arena flat over two hundred requests, the date formatted once a second, and every refusal (`tests/link/net_http1_server`); `curl` against its `serve` mode |
|
|
262
262
|
| [`net/url.ts`](https://github.com/amritk/nish/blob/main/std/net/url.ts) | The request target's path and query, read in place: `urlQueryStart` finds the `?`, `UrlPathSegments` splits a path on the raw `/` and `UrlQuery` yields a query's pairs as offsets, both reusable by `reset`; `percentDecode` and `percentDecodePathSegment` decode a window into the caller's array and answer the length or a `URL_DECODE_ERR_*` code, `percentDecodeErrorAt` answers the offset an error is at, and `urlQueryFind` finds a key. Decoding is strict by default (a malformed escape and `%00` are refused); `URL_DECODE_FORM`, `URL_DECODE_LENIENT` and `URL_DECODE_ALLOW_NUL` together decode valid UTF-8 as `URLSearchParams` does. A query yields at most `UrlQueryLimits.maxPairs` pairs (100 by default) and then answers `URL_QUERY_ERR_PAIRS`. The byte API allocates nothing; `urlDecode` and `urlQueryGet` answer strings and refuse what is not UTF-8. Whole URLs: `urlParse` splits an absolute URL into a `Url` (`scheme`, `hasAuthority`, `username`, `password`, `host`, `port`, `path`, `query`, `fragment`, each still percent-encoded, the scheme and host lower-cased), `urlResolve(base, ref)` resolves a reference against one, `urlSerialize` writes one back, and `urlDefaultPort` and `urlOrigin` answer the port and the origin a client connects to. Both refuse with null what two readers could take for different hosts: a byte outside printable ASCII, a backslash, a malformed `%`, a second `@`, a non-unreserved host byte, a numeric host that is not strict dotted-decimal IPv4, an IPv6 zone, a port past 65535. Records: [`docs/security/url.md`](../docs/security/url.md) | RFC 3986 §2.1 and §3.3, the WHATWG URL Standard's percent-decode and `application/x-www-form-urlencoded` parser; `decodeURIComponent` and `URLSearchParams` on 3,000 seeded inputs; RFC 3986 §3 and §5.2, every §5.4 example, 57 refusals and 4,000 seeded round trips in both number modes (`tests/link/net_url_parse`) |
|
|
263
263
|
| [`net/http-fields.ts`](https://github.com/amritk/nish/blob/main/std/net/http-fields.ts) | The header model HTTP/2 and HTTP/3 share, version-neutral: `HttpFields` reads a decoded section with `readRequest(names, values, extendedConnect)`, `readResponse` or `readTrailers` into `method`, `scheme`, `authority`, `path`, `protocol`, `status`, the regular fields in order (`get(name)`) and `contentLength`, answering `HTTP_FIELDS_OK` or the first refusal: a name that is empty, not a token or not lowercase; a value with NUL, CR or LF or whitespace at an end; a connection-specific field (`te` but `trailers` included); a pseudo-header unknown, repeated, after a regular field, forbidden by the shape or missing; a pseudo-header value of the wrong syntax; a `host` that disagrees with `:authority`; a bad or disagreeing `content-length`. `:protocol` (RFC 8441) is read only where the caller enabled extended CONNECT. `httpFieldNameValid`, `httpFieldValueValid`, `httpFieldConnectionSpecific` and `httpFieldsCheckOutgoing` check one name, one value or a section a program sends. `httpDateWrite(out, at, seconds)` writes a second since 1970 as the IMF-fixdate a `Date` field holds (`HTTP_DATE_SIZE` bytes, to 9999), reading no clock, so it compiles for wasm32 | RFC 9110 §5, RFC 9113 §8.2–§8.5, RFC 9114 §4.2–§4.3, RFC 8441 §4; every refusal in `tests/link/net_http_fields`; RFC 9110 §5.6.7, every day from 1970 to 2399 (`tests/link/net_http_date`) |
|
package/std/crypto/base64url.ts
CHANGED
|
@@ -13,7 +13,10 @@
|
|
|
13
13
|
*
|
|
14
14
|
* The module also holds RFC 4648 §4 standard base64 — `+` and `/`, padded with
|
|
15
15
|
* `=` — as `base64StdPadEncode` and `base64StdPadDecode`, for PEM
|
|
16
|
-
* (`nish/crypto/x509`) and SCRAM (`nish/net/postgres`)
|
|
16
|
+
* (`nish/crypto/x509`) and SCRAM (`nish/net/postgres`), and as
|
|
17
|
+
* `base64StdPadEncodeInto` and `base64StdPadDecodedLength`, which read and
|
|
18
|
+
* write a caller's buffer and allocate nothing, for the WebSocket handshake
|
|
19
|
+
* (`nish/net/websocket`). It is as strict and as
|
|
17
20
|
* constant-time as the URL alphabet, by the same masks, and it refuses a `=`
|
|
18
21
|
* anywhere but the last one or two characters of a text whose length is a
|
|
19
22
|
* multiple of four. They are not `nish/base64`'s `base64Encode`, which encodes
|
|
@@ -283,6 +286,104 @@ export const base64StdPadEncode = (data: u8[]): string => {
|
|
|
283
286
|
return parts.join("")
|
|
284
287
|
}
|
|
285
288
|
|
|
289
|
+
/**
|
|
290
|
+
* `base64StdPadEncode` of `data[start .. start + length)`, written into `out`
|
|
291
|
+
* from `at` as the bytes of its characters, allocating nothing: the WebSocket
|
|
292
|
+
* accept key that a server writes for every handshake (RFC 6455 §4.2.2). A
|
|
293
|
+
* range outside `data`, or text that does not fit in `out` from `at`, panics.
|
|
294
|
+
*
|
|
295
|
+
* @param data The buffer holding the bytes to encode; it is read, not changed.
|
|
296
|
+
* @param start Where in `data` the bytes start.
|
|
297
|
+
* @param length How many bytes to encode.
|
|
298
|
+
* @param out The buffer the text is written into.
|
|
299
|
+
* @param at Where in `out` the text starts.
|
|
300
|
+
* @returns The index in `out` just past the text, `at + 4 × ceil(length / 3)`.
|
|
301
|
+
*/
|
|
302
|
+
export const base64StdPadEncodeInto = (data: u8[], start: i32, length: i32, out: u8[], at: i32): i32 => {
|
|
303
|
+
if (data.length > 2147483647 || out.length > 2147483647) {
|
|
304
|
+
panic("base64StdPadEncodeInto: a buffer longer than 2^31 - 1 bytes")
|
|
305
|
+
}
|
|
306
|
+
if (start < 0 || length < 0 || start > toI32(data.length) - length || length > 1610612733) {
|
|
307
|
+
panic("base64StdPadEncodeInto: bytes outside their buffer")
|
|
308
|
+
}
|
|
309
|
+
const end: i32 = at + ((length + 2) / 3) * 4
|
|
310
|
+
if (at < 0 || at > toI32(out.length) || end > toI32(out.length)) {
|
|
311
|
+
panic("base64StdPadEncodeInto: text that does not fit its buffer")
|
|
312
|
+
}
|
|
313
|
+
let j: i32 = at
|
|
314
|
+
let acc: i32 = 0
|
|
315
|
+
let bits: u32 = 0
|
|
316
|
+
for (let k: i32 = start; k < start + length; k++) {
|
|
317
|
+
if (k >= 0 && k < toI32(data.length)) {
|
|
318
|
+
acc = ((acc << 8) | toI32(data[k])) & 0xfff
|
|
319
|
+
}
|
|
320
|
+
bits += 8
|
|
321
|
+
while (bits >= 6) {
|
|
322
|
+
bits -= 6
|
|
323
|
+
if (j >= 0 && j < toI32(out.length)) {
|
|
324
|
+
out[j] = toU8(base64StdPadCharOf((acc >> toI32(bits)) & 63))
|
|
325
|
+
}
|
|
326
|
+
j++
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (bits > 0) {
|
|
330
|
+
out[j] = toU8(base64StdPadCharOf((acc << toI32(6 - bits)) & 63))
|
|
331
|
+
j++
|
|
332
|
+
}
|
|
333
|
+
while (j < end) {
|
|
334
|
+
out[j] = 61
|
|
335
|
+
j++
|
|
336
|
+
}
|
|
337
|
+
return end
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* How many bytes the padded standard base64 in `text[start .. start + length)`
|
|
342
|
+
* decodes to, or -1 unless it is their one canonical spelling, by
|
|
343
|
+
* `base64StdPadDecode`'s rules and its masks; nothing is decoded or allocated.
|
|
344
|
+
* A WebSocket server checks a handshake's `Sec-WebSocket-Key` this way, where
|
|
345
|
+
* it lies in the request (RFC 6455 §4.2.1, item 5). A range outside `text`
|
|
346
|
+
* panics.
|
|
347
|
+
*
|
|
348
|
+
* @param text The buffer holding the text, one character a byte.
|
|
349
|
+
* @param start Where in `text` the base64 starts.
|
|
350
|
+
* @param length How many characters it is.
|
|
351
|
+
* @returns The decoded length, or -1 when the text is not canonical.
|
|
352
|
+
*/
|
|
353
|
+
export const base64StdPadDecodedLength = (text: u8[], start: i32, length: i32): i32 => {
|
|
354
|
+
if (text.length > 2147483647) {
|
|
355
|
+
panic("base64StdPadDecodedLength: a buffer longer than 2^31 - 1 bytes")
|
|
356
|
+
}
|
|
357
|
+
if (start < 0 || length < 0 || start > toI32(text.length) - length) {
|
|
358
|
+
panic("base64StdPadDecodedLength: text outside its buffer")
|
|
359
|
+
}
|
|
360
|
+
if ((length & 3) !== 0) {
|
|
361
|
+
return -1
|
|
362
|
+
}
|
|
363
|
+
let pad: i32 = 0
|
|
364
|
+
if (length > 0 && toI32(text[start + length - 1]) === 61) {
|
|
365
|
+
pad = toI32(text[start + length - 2]) === 61 ? 2 : 1
|
|
366
|
+
}
|
|
367
|
+
const chars: i32 = length - pad
|
|
368
|
+
let bad: i32 = 0
|
|
369
|
+
let acc: i32 = 0
|
|
370
|
+
let bits: i32 = 0
|
|
371
|
+
for (let k: i32 = 0; k < chars; k++) {
|
|
372
|
+
const v: i32 = base64StdPadSextetOf(toI32(text[start + k]))
|
|
373
|
+
bad = bad | (v >> 31)
|
|
374
|
+
acc = ((acc << 6) | (v & 63)) & 0xfff
|
|
375
|
+
bits += 6
|
|
376
|
+
if (bits >= 8) {
|
|
377
|
+
bits -= 8
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
bad = bad | (acc & ((1 << bits) - 1))
|
|
381
|
+
if (bad !== 0) {
|
|
382
|
+
return -1
|
|
383
|
+
}
|
|
384
|
+
return (length >> 2) * 3 - pad
|
|
385
|
+
}
|
|
386
|
+
|
|
286
387
|
/**
|
|
287
388
|
* The bytes of padded standard base64 `text`, or `null` unless it is the one
|
|
288
389
|
* canonical spelling of them: a whole number of four-character groups, `=`
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `nish/crypto/scram` — the arithmetic of a SCRAM-SHA-256 client, as RFC 5802
|
|
3
|
+
* §3 defines it with SHA-256 for `H` and `HMAC` (RFC 7677 §3):
|
|
4
|
+
*
|
|
5
|
+
* SaltedPassword := Hi(Normalize(password), salt, i)
|
|
6
|
+
* ClientKey := HMAC(SaltedPassword, "Client Key")
|
|
7
|
+
* StoredKey := H(ClientKey)
|
|
8
|
+
* ClientSignature := HMAC(StoredKey, AuthMessage)
|
|
9
|
+
* ClientProof := ClientKey XOR ClientSignature
|
|
10
|
+
* ServerKey := HMAC(SaltedPassword, "Server Key")
|
|
11
|
+
* ServerSignature := HMAC(ServerKey, AuthMessage)
|
|
12
|
+
*
|
|
13
|
+
* import { scramSha256ClientProof, scramSha256SaltedPassword, scramSha256ServerSignature } from "nish/crypto/scram";
|
|
14
|
+
*
|
|
15
|
+
* const salted: Secret<u8[]> | null = scramSha256SaltedPassword(password, salt, 4096);
|
|
16
|
+
* if (salted !== null) {
|
|
17
|
+
* const proof: u8[] = scramSha256ClientProof(salted, authMessage);
|
|
18
|
+
* const expected: u8[] = scramSha256ServerSignature(salted, authMessage);
|
|
19
|
+
* wipe(salted);
|
|
20
|
+
* }
|
|
21
|
+
*
|
|
22
|
+
* The module holds none of SCRAM's messages: the caller builds AuthMessage,
|
|
23
|
+
* decodes the server's salt and encodes the proof, so that a driver keeps its
|
|
24
|
+
* own wire format and this file stays a pure function of its inputs, which a
|
|
25
|
+
* contract (`specs/scram-sha256.md`) can hold to the RFC's printed exchange.
|
|
26
|
+
* `Normalize` (SASLprep) is the caller's too: the password arrives as the
|
|
27
|
+
* bytes the caller decided to send.
|
|
28
|
+
*
|
|
29
|
+
* SaltedPassword, ClientKey and ServerKey each let whoever holds them log in
|
|
30
|
+
* as the user, so SaltedPassword is taken and given as a `Secret`, and
|
|
31
|
+
* ClientKey, StoredKey, ClientSignature and ServerKey are wiped before each
|
|
32
|
+
* function returns. ClientProof and ServerSignature cross the wire in the
|
|
33
|
+
* clear and are plain bytes. A caller compares the server's signature with
|
|
34
|
+
* `timingSafeEqual` (`nish/crypto/ct`), and caps the iteration count before
|
|
35
|
+
* it calls: `i=` is the server's to choose and Hi runs that many HMACs.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { hmacSha256, pbkdf2HmacSha256 } from "nish/crypto/hmac"
|
|
39
|
+
import { Sha256 } from "nish/crypto/sha256"
|
|
40
|
+
import { Secret, exposeWith, wipe } from "nish:secret"
|
|
41
|
+
|
|
42
|
+
/** The bytes of an ASCII literal, for the two HMAC labels. */
|
|
43
|
+
const scramAscii = (text: string): u8[] => {
|
|
44
|
+
const n: i32 = toI32(text.length)
|
|
45
|
+
const out: u8[] = []
|
|
46
|
+
for (let i: i32 = 0; i < n; i++) {
|
|
47
|
+
out.push(toU8(text.charCodeAt(i)))
|
|
48
|
+
}
|
|
49
|
+
return out
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* SHA-256 of `data` through a hasher of its own, whose state, block and
|
|
54
|
+
* schedule are wiped before it returns: the one-shot `sha256` leaves the last
|
|
55
|
+
* block of its input in a hasher nothing wipes, and here the input is
|
|
56
|
+
* ClientKey.
|
|
57
|
+
*/
|
|
58
|
+
const scramSha256Wiped = (data: u8[]): u8[] => {
|
|
59
|
+
const h = new Sha256()
|
|
60
|
+
h.update(data, toI32(0), toI32(data.length))
|
|
61
|
+
const digest: u8[] = h.digest()
|
|
62
|
+
wipe(h.state)
|
|
63
|
+
wipe(h.block)
|
|
64
|
+
wipe(h.schedule)
|
|
65
|
+
h.fill = 0
|
|
66
|
+
h.total = 0
|
|
67
|
+
h.finished = true
|
|
68
|
+
return digest
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** ClientKey XOR HMAC(H(ClientKey), AuthMessage), with every key on the way wiped. */
|
|
72
|
+
const scramClientProofExposed = (salted: u8[], authMessage: u8[]): u8[] => {
|
|
73
|
+
const clientKey: u8[] = hmacSha256(salted, scramAscii("Client Key"))
|
|
74
|
+
const storedKey: u8[] = scramSha256Wiped(clientKey)
|
|
75
|
+
const clientSignature: u8[] = hmacSha256(storedKey, authMessage)
|
|
76
|
+
if (clientKey.length < 32 || clientSignature.length < 32) {
|
|
77
|
+
panic("nish/crypto/scram: an HMAC-SHA-256 shorter than 32 bytes")
|
|
78
|
+
}
|
|
79
|
+
const proof: u8[] = new Array<u8>(32)
|
|
80
|
+
for (let i: i32 = 0; i < 32; i++) {
|
|
81
|
+
proof[i] = clientKey[i] ^ clientSignature[i]
|
|
82
|
+
}
|
|
83
|
+
wipe(clientKey)
|
|
84
|
+
wipe(storedKey)
|
|
85
|
+
wipe(clientSignature)
|
|
86
|
+
return proof
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** HMAC(HMAC(SaltedPassword, "Server Key"), AuthMessage), with ServerKey wiped. */
|
|
90
|
+
const scramServerSignatureExposed = (salted: u8[], authMessage: u8[]): u8[] => {
|
|
91
|
+
const serverKey: u8[] = hmacSha256(salted, scramAscii("Server Key"))
|
|
92
|
+
const signature: u8[] = hmacSha256(serverKey, authMessage)
|
|
93
|
+
wipe(serverKey)
|
|
94
|
+
return signature
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* SaltedPassword, RFC 5802 §3's `Hi(password, salt, i)`: PBKDF2 with
|
|
99
|
+
* HMAC-SHA-256 and a 32-byte output (§2.2).
|
|
100
|
+
*
|
|
101
|
+
* The time is linear in `iterations` and nothing here bounds it, so a caller
|
|
102
|
+
* taking the count from a server caps it first.
|
|
103
|
+
*
|
|
104
|
+
* @param password The password, already normalized as the caller sends it;
|
|
105
|
+
* read only inside `exposeWith`, and still the caller's to wipe.
|
|
106
|
+
* @param salt The salt the server sent, decoded from base64.
|
|
107
|
+
* @param iterations The server's iteration count `i`; below 1 answers `null`.
|
|
108
|
+
* @returns SaltedPassword, which the caller wipes, or `null` when it cannot be
|
|
109
|
+
* computed.
|
|
110
|
+
*/
|
|
111
|
+
export const scramSha256SaltedPassword = (
|
|
112
|
+
password: Secret<u8[]>,
|
|
113
|
+
salt: u8[],
|
|
114
|
+
iterations: i32
|
|
115
|
+
): Secret<u8[]> | null => pbkdf2HmacSha256(password, salt, iterations, 32)
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* ClientProof, the `p=` of the client-final message (RFC 5802 §3). ClientKey,
|
|
119
|
+
* StoredKey and ClientSignature are wiped before it returns.
|
|
120
|
+
*
|
|
121
|
+
* @param saltedPassword SaltedPassword from `scramSha256SaltedPassword`, read
|
|
122
|
+
* only inside `exposeWith`; still the caller's to wipe.
|
|
123
|
+
* @param authMessage The client-first message without its GS2 header, the
|
|
124
|
+
* server-first message and the client-final message without its proof,
|
|
125
|
+
* joined by commas.
|
|
126
|
+
* @returns The 32-byte proof, which is sent in the clear.
|
|
127
|
+
*/
|
|
128
|
+
export const scramSha256ClientProof = (saltedPassword: Secret<u8[]>, authMessage: u8[]): u8[] =>
|
|
129
|
+
exposeWith(saltedPassword, authMessage, scramClientProofExposed)
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* ServerSignature, what the server's `v=` must equal (RFC 5802 §3). ServerKey
|
|
133
|
+
* is wiped before it returns. Compare it to the server's with
|
|
134
|
+
* `timingSafeEqual`.
|
|
135
|
+
*
|
|
136
|
+
* @param saltedPassword SaltedPassword from `scramSha256SaltedPassword`, read
|
|
137
|
+
* only inside `exposeWith`; still the caller's to wipe.
|
|
138
|
+
* @param authMessage The same AuthMessage the proof was computed over.
|
|
139
|
+
* @returns The 32-byte signature the server should send.
|
|
140
|
+
*/
|
|
141
|
+
export const scramSha256ServerSignature = (saltedPassword: Secret<u8[]>, authMessage: u8[]): u8[] =>
|
|
142
|
+
exposeWith(saltedPassword, authMessage, scramServerSignatureExposed)
|