@amritk/nish-aarch64-linux 0.49.1 → 0.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/INSTALL.md +1 -1
- package/bin/nish +0 -0
- package/docs/AI.md +237 -160
- package/package.json +1 -1
- package/runtime/gfx/nish-gfx.h +373 -61
- package/runtime/nish.d.ts +94 -11
- package/runtime/nish.h +5 -0
- package/runtime/runtime-host.c +21 -5
- package/std/README.md +14 -11
- package/std/base64.ts +74 -35
- package/std/bytes.ts +207 -97
- package/std/cli-args.ts +150 -107
- package/std/compress/checksum.ts +68 -10
- package/std/compress/deflate.ts +213 -115
- package/std/compress/gzip.ts +124 -49
- package/std/compress/zlib.ts +57 -15
- package/std/crypto/aes.ts +51 -9
- package/std/crypto/base64url.ts +93 -66
- package/std/crypto/bcrypt.ts +25 -21
- package/std/crypto/ed25519.ts +12 -10
- package/std/crypto/hkdf.ts +405 -283
- package/std/crypto/hmac.ts +484 -149
- package/std/crypto/jwt.ts +51 -40
- package/std/crypto/p256.ts +14 -19
- package/std/crypto/pki-roots.ts +35 -12
- package/std/crypto/pki.ts +43 -55
- package/std/crypto/rsa-sign.ts +1635 -0
- package/std/crypto/rsa.ts +26 -4
- package/std/crypto/sha256.ts +212 -90
- package/std/crypto/sha512.ts +135 -49
- package/std/crypto/x25519.ts +12 -11
- package/std/crypto/x509.ts +164 -40
- package/std/gpu/sys.ts +490 -0
- package/std/json-equal.ts +33 -18
- package/std/json-format.ts +39 -8
- package/std/json-number.ts +15 -3
- package/std/json-tokenizer.ts +4 -3
- package/std/json-typed.ts +12 -6
- package/std/json-value.ts +236 -119
- package/std/json.ts +81 -46
- package/std/net/buffer-pool.ts +25 -14
- package/std/net/dns-config.ts +18 -5
- package/std/net/dns-message.ts +60 -27
- package/std/net/dns-resolver.ts +35 -16
- package/std/net/dns.ts +3 -2
- package/std/net/fetch.ts +224 -61
- package/std/net/handler.ts +189 -88
- package/std/net/hpack.ts +216 -103
- package/std/net/http-compress.ts +104 -42
- package/std/net/http-fields.ts +327 -31
- package/std/net/http-server.ts +326 -24
- package/std/net/http1-client-codec.ts +159 -55
- package/std/net/http1-codec.ts +427 -237
- package/std/net/http1-server.ts +220 -38
- package/std/net/http2-cleartext.ts +10 -4
- package/std/net/http2-frame.ts +2 -2
- package/std/net/http2-tls.ts +3 -3
- package/std/net/http2.ts +69 -15
- package/std/net/http3-frame.ts +11 -14
- package/std/net/http3-server.ts +139 -60
- package/std/net/http3.ts +140 -79
- package/std/net/multipart.ts +592 -0
- package/std/net/outbound.ts +24 -8
- package/std/net/postgres-async.ts +97 -64
- package/std/net/postgres-carrier.ts +28 -4
- package/std/net/postgres.ts +166 -65
- package/std/net/prefork.ts +86 -5
- package/std/net/protobuf.ts +6 -2
- package/std/net/qpack.ts +147 -40
- package/std/net/quic-conn-ack.ts +27 -7
- package/std/net/quic-conn-cid.ts +13 -7
- package/std/net/quic-datagram.ts +6 -5
- package/std/net/quic-frame.ts +67 -23
- package/std/net/quic-listener.ts +61 -39
- package/std/net/quic-packet.ts +91 -50
- package/std/net/quic-recovery.ts +11 -9
- package/std/net/quic-stream.ts +36 -27
- package/std/net/quic.ts +84 -54
- package/std/net/router.ts +136 -24
- package/std/net/serve.ts +59 -5
- package/std/net/static.ts +86 -36
- package/std/net/tls/client.ts +81 -34
- package/std/net/tls/codec.ts +3 -4
- package/std/net/tls/record.ts +80 -35
- package/std/net/tls/schedule.ts +339 -149
- package/std/net/tls/ticket.ts +6 -5
- package/std/net/tls-tcp.ts +69 -30
- package/std/net/tls.ts +194 -50
- package/std/net/upstream.ts +83 -38
- package/std/net/url.ts +170 -94
- package/std/net/websocket.ts +19 -20
- package/std/net/webtransport.ts +123 -33
- package/std/raster.ts +12 -2
- package/std/regex.ts +600 -388
- package/std/sqlite.ts +37 -19
- package/std/sync/ring.ts +232 -115
- package/std/sync/shm.ts +11 -4
- package/std/temporal.ts +232 -133
- package/std/term-io.ts +12 -6
- package/std/term-pixels.ts +176 -24
- package/std/term-rate.ts +8 -3
- package/std/term.ts +4 -4
- package/std/text.ts +38 -16
- package/std/yaml-json.ts +238 -106
- package/std/yaml-lines.ts +47 -27
- package/std/yaml-write.ts +58 -24
- package/std/yaml.ts +808 -395
package/runtime/nish.d.ts
CHANGED
|
@@ -241,15 +241,18 @@ declare function Err<T, E>(error: E): Result<T, E>;
|
|
|
241
241
|
* The disposable protocol `using` reads: declared here so that a program using
|
|
242
242
|
* `nish/threads`'s scope, a `Mutex`'s lock, `arena()` or a handle class needs
|
|
243
243
|
* no `"ESNext.Disposable"` in its `lib`. `nish` takes `using` only for a
|
|
244
|
-
* `scope()`, a `lock()`, an `arena()
|
|
245
|
-
* other `using` initialiser is refused.
|
|
246
|
-
*
|
|
247
|
-
* A handle class is a class
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
*
|
|
244
|
+
* `scope()`, a `lock()`, an `arena()`, or a handle class's `new` or factory
|
|
245
|
+
* call, and any other `using` initialiser is refused.
|
|
246
|
+
*
|
|
247
|
+
* A handle class is a class that owns one or more `readonly` fields, each a
|
|
248
|
+
* `CPtr`, an opaque `declare class`, a `HostHandle` or another handle class
|
|
249
|
+
* (each but a `HostHandle` perhaps `| null`). Its `[Symbol.dispose](): void`
|
|
250
|
+
* closes each native field, the last declared first, as `close(this.file);`
|
|
251
|
+
* or `const p = this.file; if (p !== null) { close(p); }` for a `declare
|
|
252
|
+
* function` `close` of one parameter.
|
|
253
|
+
* `using` of a handle class closes it at every exit of its block, once, in the
|
|
254
|
+
* reverse of the order the declarators opened; a panic and `process.exit` do
|
|
255
|
+
* not close.
|
|
253
256
|
* `--deny ffi` refuses that `using`. Any other class that declares
|
|
254
257
|
* `[Symbol.dispose]` is refused.
|
|
255
258
|
*
|
|
@@ -734,6 +737,26 @@ declare function geteuid(): i64;
|
|
|
734
737
|
*/
|
|
735
738
|
declare function isExecutableSync(path: string): boolean;
|
|
736
739
|
|
|
740
|
+
// ---- Misuse (`nish:panic`) ---------------------------------------------------
|
|
741
|
+
//
|
|
742
|
+
// Declared as a global, as the `nish:unsafe` functions below are, so `tsc`
|
|
743
|
+
// reads a program that names it, but `nish` refuses a call that is not
|
|
744
|
+
// imported from `nish:panic`: the import is the module's visible opt-in. The
|
|
745
|
+
// refusal reads `` `misuse` is a `nish:panic` name and is used only through an
|
|
746
|
+
// import of it ``. A user function of the same name, with no import, is the
|
|
747
|
+
// user's.
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* `message` and a newline to stderr, then exit 1, as `panic` does: called
|
|
751
|
+
* only through an import of `nish:panic`, where it is an allowed `misuse`
|
|
752
|
+
* site in the no-panic scope (`--deny-misuse` refuses it). Statement
|
|
753
|
+
* position, and it terminates control flow. Capability: none.
|
|
754
|
+
*
|
|
755
|
+
* @param message what the caller got wrong; a string the program fixes.
|
|
756
|
+
* @returns never: the program ends.
|
|
757
|
+
*/
|
|
758
|
+
declare function misuse(message: string): never;
|
|
759
|
+
|
|
737
760
|
// ---- Unsafe (`nish:unsafe`) --------------------------------------------------
|
|
738
761
|
//
|
|
739
762
|
// Declared as globals so `tsc` reads a program that imports them, as every
|
|
@@ -2488,7 +2511,7 @@ interface DateConstructor {
|
|
|
2488
2511
|
now(): number;
|
|
2489
2512
|
}
|
|
2490
2513
|
|
|
2491
|
-
/** The system's random source, with its one member. */
|
|
2514
|
+
/** The system's random source, with its one member and that member's answering twin. */
|
|
2492
2515
|
declare var crypto: {
|
|
2493
2516
|
/**
|
|
2494
2517
|
* Every byte of `bytes` from the kernel's CSPRNG (`getrandom(2)` on Linux,
|
|
@@ -2504,7 +2527,7 @@ declare var crypto: {
|
|
|
2504
2527
|
* panic, `crypto.getRandomValues: <n> bytes asked for, and one call fills at
|
|
2505
2528
|
* most 65536`, exit 1. A source that fails is a panic too; nothing weaker is
|
|
2506
2529
|
* ever substituted. It is the source for a key. `crypto` has no other member
|
|
2507
|
-
* (NL2403, for example `crypto.randomUUID`). Refused at compile time on
|
|
2530
|
+
* but its twin `tryGetRandomValues` (NL2403, for example `crypto.randomUUID`). Refused at compile time on
|
|
2508
2531
|
* wasm32 and the WASI profile (NL2404). Under Node the prelude fills a plain
|
|
2509
2532
|
* `u8[]` too and panics past 65,536 with the same words; without the prelude
|
|
2510
2533
|
* it takes only a typed array. Capability: entropy.
|
|
@@ -2512,6 +2535,21 @@ declare var crypto: {
|
|
|
2512
2535
|
* @param bytes the buffer filled.
|
|
2513
2536
|
*/
|
|
2514
2537
|
getRandomValues(bytes: u8[]): void;
|
|
2538
|
+
/**
|
|
2539
|
+
* `getRandomValues`'s twin for code built without `--allow-panics`: the same
|
|
2540
|
+
* fill from the same source under the same rules (a `u8[]` only, written,
|
|
2541
|
+
* refused on wasm32 and the WASI profile, capability entropy), but where
|
|
2542
|
+
* `getRandomValues` exits it answers `false`: more than 65,536 bytes, or a
|
|
2543
|
+
* source that fails, which may leave a prefix of `bytes` written. Nothing
|
|
2544
|
+
* weaker is ever substituted. An expression, so a caller can turn the
|
|
2545
|
+
* `false` into its own `Result`; it is no panic site. `--emit-ts` writes it
|
|
2546
|
+
* as a length test and the runtime's fill; the Node prelude that runs a
|
|
2547
|
+
* source file as TypeScript does not define it.
|
|
2548
|
+
*
|
|
2549
|
+
* @param bytes the buffer filled.
|
|
2550
|
+
* @returns `true` when every byte of `bytes` was filled, `false` otherwise.
|
|
2551
|
+
*/
|
|
2552
|
+
tryGetRandomValues(bytes: u8[]): boolean;
|
|
2515
2553
|
};
|
|
2516
2554
|
|
|
2517
2555
|
// ---- The builtin modules (`nish:`) ---------------------------------------------
|
|
@@ -3710,6 +3748,51 @@ declare module "nish:net" {
|
|
|
3710
3748
|
export function netRingState(): i32;
|
|
3711
3749
|
}
|
|
3712
3750
|
|
|
3751
|
+
/**
|
|
3752
|
+
* A panic the author states can never happen in a fixed program: one call to
|
|
3753
|
+
* `misuse(message)` from a module that imports it.
|
|
3754
|
+
*
|
|
3755
|
+
* import { misuse } from "nish:panic";
|
|
3756
|
+
*
|
|
3757
|
+
* export const pick = (mode: i32): i32 => {
|
|
3758
|
+
* if (mode === 0) return 10;
|
|
3759
|
+
* if (mode === 1) return 20;
|
|
3760
|
+
* misuse("pick: mode is 0 or 1");
|
|
3761
|
+
* };
|
|
3762
|
+
*
|
|
3763
|
+
* It lowers exactly like `panic`: the same message and newline to stderr, the
|
|
3764
|
+
* same exit 1. The difference is only in the no-panic scope. A `misuse` call is
|
|
3765
|
+
* a `misuse` site, which the default rule allows, as it allows `oom` and
|
|
3766
|
+
* `unchecked`: `--emit-panics` lists it with `allowed: true`, and a caller in
|
|
3767
|
+
* the scope raises neither NL2457 nor NL2458 for it. `--deny-misuse` refuses it
|
|
3768
|
+
* again, as an ordinary unproven site.
|
|
3769
|
+
*
|
|
3770
|
+
* It is for a panic only a wrong program reaches: a caller that passes a value
|
|
3771
|
+
* its documentation rules out, with the value fixed in the caller's own code.
|
|
3772
|
+
* A panic that input can reach, from a file, the network, the terminal or an
|
|
3773
|
+
* argument, stays proven away or becomes a `Result`. The global spelling is
|
|
3774
|
+
* refused: `misuse` is called only through an import of `nish:panic`, so each
|
|
3775
|
+
* module that uses it says so at its top.
|
|
3776
|
+
*
|
|
3777
|
+
* **Under Node.** `--emit-ts` writes the import as the runtime's `panic`, so the
|
|
3778
|
+
* emitted program ends the same way. `runtime/nish.mjs` does not answer
|
|
3779
|
+
* `nish:panic` yet, so a `.ts` file run directly under Node cannot import it.
|
|
3780
|
+
*
|
|
3781
|
+
* Rules: https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#nishpanic-a-panic-for-misuse
|
|
3782
|
+
*/
|
|
3783
|
+
declare module "nish:panic" {
|
|
3784
|
+
/**
|
|
3785
|
+
* `message` and a newline to stderr, then exit 1, as `panic` does, recorded
|
|
3786
|
+
* as an allowed `misuse` site rather than an unproven one. Statement
|
|
3787
|
+
* position, and it terminates control flow, so it is `never`. Capability:
|
|
3788
|
+
* none.
|
|
3789
|
+
*
|
|
3790
|
+
* @param message what the caller got wrong; a string the program fixes.
|
|
3791
|
+
* @returns never: the program ends.
|
|
3792
|
+
*/
|
|
3793
|
+
export function misuse(message: string): never;
|
|
3794
|
+
}
|
|
3795
|
+
|
|
3713
3796
|
/**
|
|
3714
3797
|
* Element access with no bounds check, signed arithmetic that wraps, a C
|
|
3715
3798
|
* string or struct read through a pointer nothing proves, and the errno a C
|
package/runtime/nish.h
CHANGED
|
@@ -781,6 +781,11 @@ double nish_date_now(void);
|
|
|
781
781
|
* bytes, the Web API's limit for one call, and a failing entropy source both
|
|
782
782
|
* print a message and exit 1; nothing weaker is ever substituted. */
|
|
783
783
|
void nish_random_fill(nish_array *bytes);
|
|
784
|
+
/* `crypto.tryGetRandomValues(bytes)`: the same fill from the same source, but
|
|
785
|
+
* where `nish_random_fill` exits it answers false (more than 65,536 bytes, or
|
|
786
|
+
* a failing source, which may leave a prefix written); true when every byte
|
|
787
|
+
* was filled. It never exits. */
|
|
788
|
+
bool nish_random_try_fill(nish_array *bytes);
|
|
784
789
|
/* `statMtimeSync(path)`: the modification time in milliseconds with its
|
|
785
790
|
* sub-millisecond fraction, computed as Node's `mtimeMs` is, or NaN when
|
|
786
791
|
* `stat` fails. Follows a symbolic link. */
|
package/runtime/runtime-host.c
CHANGED
|
@@ -73,25 +73,41 @@ static NISH_COLD void nish_entropy_fail(uint64_t asked) {
|
|
|
73
73
|
API's limit of 65,536 bytes a call is kept, so a program behaves the same
|
|
74
74
|
under Node. `getrandom` without flags blocks only until the pool is first
|
|
75
75
|
initialised at boot and can return short or be interrupted, so it loops;
|
|
76
|
-
`getentropy` fills at most 256 bytes a call and retries nothing itself.
|
|
77
|
-
|
|
76
|
+
`getentropy` fills at most 256 bytes a call and retries nothing itself.
|
|
77
|
+
The fill both builtins share: true when every byte of `bytes` came from the
|
|
78
|
+
source, false past the limit or when the source fails, which may leave a
|
|
79
|
+
prefix written. */
|
|
80
|
+
static bool nish_random_draw(nish_array *bytes) {
|
|
78
81
|
uint64_t n = bytes->len;
|
|
79
82
|
char *p = bytes->data;
|
|
80
|
-
if (n > 65536)
|
|
83
|
+
if (n > 65536) return false;
|
|
81
84
|
while (n > 0) {
|
|
82
85
|
#if defined(__linux__)
|
|
83
86
|
ssize_t got = getrandom(p, n, 0);
|
|
84
87
|
if (got < 0) {
|
|
85
88
|
if (errno == EINTR) continue;
|
|
86
|
-
|
|
89
|
+
return false;
|
|
87
90
|
}
|
|
88
91
|
#else
|
|
89
92
|
size_t got = n < 256 ? n : 256;
|
|
90
|
-
if (getentropy(p, got) != 0)
|
|
93
|
+
if (getentropy(p, got) != 0) return false;
|
|
91
94
|
#endif
|
|
92
95
|
p += got;
|
|
93
96
|
n -= (uint64_t)got;
|
|
94
97
|
}
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
void nish_random_fill(nish_array *bytes) {
|
|
102
|
+
if (!nish_random_draw(bytes)) nish_entropy_fail(bytes->len);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/* `crypto.tryGetRandomValues(bytes)`: the same fill, answering whether it
|
|
106
|
+
happened instead of exiting, so a program built without `--allow-panics`
|
|
107
|
+
can turn a failing source into its own error. Nothing weaker is tried
|
|
108
|
+
either: on false the bytes are not a key and the caller is told so. */
|
|
109
|
+
bool nish_random_try_fill(nish_array *bytes) {
|
|
110
|
+
return nish_random_draw(bytes);
|
|
95
111
|
}
|
|
96
112
|
|
|
97
113
|
/* `statMtimeSync(path)`: the modification time in milliseconds, with the
|
package/std/README.md
CHANGED
|
@@ -34,18 +34,18 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
34
34
|
| [`collections.ts`](https://github.com/amritk/nish/blob/main/std/collections.ts) | the global `Map<K, V>` and `Set<T>`: insertion-ordered tables whose buckets carry a hash fingerprint beside the entry index and whose entries keep their full hash, so every `get`, `set`, `add`, `has` and `delete` is one probe. `get` is not a method here: its `V | undefined` never crosses a call, so the compiler lowers it to `probe` and, where the key was found, `valueAt`. Nor are `keys()` and `values()`: an iterator is not a value, so a `for...of` over one is lowered to `walkOpen`, `walkNext`, `keyAt` or `valueAt`, and `walkClose`, and a count of live walks defers compaction until no loop is walking the table. A program never imports it: naming `Map` or `Set` loads it, and the compiler emits what a module uses of it into that module ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)). Its `hashKey`, `sameKey` and `storedKey` are lowered by the compiler per key type |
|
|
35
35
|
| [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)) |
|
|
36
36
|
| [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#byte-runs-skipblank-skipdigits-skipjsontext-skipjsonplain-and-copybytes-in-nishbytes)). The runs are variable-time. `tests/link/std_bytes*` are its programs |
|
|
37
|
-
| [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string, `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array
|
|
37
|
+
| [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string (`null` past 1,610,612,733 bytes), `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array, or an encoding that does not fit, answers -1 before a byte is written, as does `base64EncodeIfFits(src, off, len, dst, at)`. It indexes its alphabet by the sextet, so it is not constant-time: it is for pixels, not secrets. A strict decoder, and an encoder for key material, are `crypto/base64url.ts`'s `base64StdPadDecode` and `base64StdPadEncode` (`tests/link/std_base64`, `std_base64_f64`, `std_base64_if_fits`, `std_base64_negative_*`; the two modules in one program: `tests/link/std_base64_two_modules`; [guide](../docs/guide/using-nish/standard-library.md#nishbase64)) |
|
|
38
38
|
| [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin; `tryPlainDate`, `tryPlainDateFrom` and `PlainDate.tryAdd` answer the `RangeError`'s text as a `Result` `Err` (`tests/link/std_temporal_result`). There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
|
|
39
39
|
| [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, its wrapping add taken in `f64` on the state read as an unsigned count and its multiplies through `Math.imul`, so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
|
|
40
40
|
| [`cli.ts`](https://github.com/amritk/nish/blob/main/std/cli.ts) | a command-line tool's `--help`. `HelpMenu` builds it a line at a time — `header`, `usage`, `section`, `row(flag, placeholder, description)`, `note`, `value` — with descriptions lined up at the caller's columns, counted on the plain text, and answers it with `text()`. `Style` paints it in the basic ANSI colours, bold and faint, which the terminal's theme defines, or in bold and underline alone when `TERM` declares no colours; each role it paints (`heading`, `name`, `flag`, `meta`, `dim`) is a pair of SGR lists, `<role>Themed` and `<role>Mono`, a program may set. `Style` also paints any text: the sixteen colours (`red`, `brightBlack`, ...), their backgrounds (`bgRed`, `bgBrightRed`, ...), the attributes (`bold`, `faint`, `italic`, `underline`, `inverse`, `strikethrough`, which the failsafe keeps) and `sgr(text, codes)` for any parameter list, with the `SGR_` constants spelling the codes. `styleFor(fd, agent)` is the policy `nish --help` follows: plain unless the descriptor is a terminal, `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE`, `CLICOLOR` and `TERM=dumb` honoured, plain for an agent (`agentDriven`), forced colour always the theme's; it reads the environment and, for the terminal check, forks `/bin/sh` once, which runs `tput` by absolute path. `HelpMenu` and `Style` reach no capability. The compiler's own help is built with it through a relative import, so the module may use only what the last release compiles (`tests/link/std_cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli)) |
|
|
41
|
-
| [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle
|
|
41
|
+
| [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle. A declaration mistake panics nowhere: a call that answers a handle answers `NO_HANDLE`, the first mistake is kept for `declarationError()`, and `parse` then answers `PARSE_ERROR` with exit code 2 and the mistake as its message. `parse(argv, start)` walks the arguments once and answers a `ParseResult`: the reached command's id and path, each flag's value with its `source` (the command line, its default or unset), the positionals and what follows `--`, or the first error with a did-you-mean. `finish` prints help (laid out by `HelpMenu`), the version or the error and exits 0 or 2. `parse` reaches no capability (`tests/link/std_cli_args`, `examples/api-cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli-args)) |
|
|
42
42
|
| [`cli-flags.ts`](https://github.com/amritk/nish/blob/main/std/cli-flags.ts) | `nish/cli-flags`: a command line read against a declared table. `FlagTable` declares `string`, `number` (an `f64`), `boolean` (`--name` / `--no-name`) and `repeatable` flags and `command` paths of one or more words; `parse(args)` (or `parseFrom(process.argv, 1)`) answers a `ParsedFlags` with the longest matched `command`, the `positionals` and each flag by name (`str`, `num`, `bool`, `all`, `has`). `--name value`, `--name=value`, `--` and a lone `-` follow the GNU long-option grammar; there are no short options. A usage error (unknown flag, missing value, not a number, given twice, value on a boolean, unknown command) is carried as `code`, `message` and `argument`, and `exitUsage()` writes it to stderr and exits 2. `writeHelp(menu)` adds the table's rows to a `nish/cli` `HelpMenu`. Reaches `exit` only through `exitUsage` (`tests/link/std_cli_flags`, `std_cli_flags_bad_*`; [guide](../docs/guide/using-nish/standard-library.md#parsing-flags)) |
|
|
43
43
|
| [`sqlite.ts`](https://github.com/amritk/nish/blob/main/std/sqlite.ts) | SQLite, vendored in `runtime/sqlite/` and linked into a program that imports the module, through the C adapter `runtime/sqlite/nish-sqlite.c`. `openDatabase(path, flags)` answers a `Database`: `exec`, `begin` / `commit` / `rollback`, `prepare` into a `Statement`, `lastInsertRowid`, `changes` and `close`, which finalizes the connection's statements. A `Statement` binds (`bindI64`, `bindF64`, `bindNull`, `bindText`, `bindTextBytes`, `bindBlob`), steps, resets and reads columns (`columnType`, `columnI64`, `columnF64`, `columnBytes`, `columnText`, and `columnInto`, a copy into the caller's `u8[]`), so a row allocates nothing. Every failure is a `Result` of SQLite's extended code, and `error(code)` builds the `SqliteError` with its message. A handle is an `i32` into the adapter's thread-local tables, and one used after `close` or `finalize` answers `SQLITE_MISUSE`. Reaches `ffi`; links natively and under `--profile wasi` (`tests/link/std_sqlite*`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#sqlite-nishsqlite)) |
|
|
44
44
|
| [`release.ts`](https://github.com/amritk/nish/blob/main/std/release.ts) | `nish/release`: whether a newer release of a project on GitHub is out, and its `install.sh`. `releaseLatest(base, timeoutMs)` asks `<base>/releases/latest` once without following the redirect and answers the version only when it goes to exactly `<base>/releases/tag/v<version>`, else null; `releaseIsNewer`, `releaseCompare` and `releaseParseVersion` order semantic versions (a prerelease below its release, build metadata ignored, nothing that does not parse ever newer); `releaseValidVersion` is `install.sh`'s rule for a version that may go in a URL. `releaseCheckCached(base, current, path, maxAgeMs, timeoutMs)` keeps the answer in a file believed only when it is a regular file this user owns that nobody else can write, and refreshed when stale or dated in the future; `releaseFetchInstaller` writes a tag's `install.sh` to a file, never to a shell. https only, or http to loopback. The compiler's update notice and `nish upgrade` run on it ([`docs/security/release.md`](../docs/security/release.md); `tests/run.js` "nish/release"; [guide](../docs/guide/using-nish/standard-library.md#nishrelease)) |
|
|
45
45
|
| [`term.ts`](https://github.com/amritk/nish/blob/main/std/term.ts) | a terminal UI with no I/O of its own. `Screen` holds `width × height` cells (code point, 24-bit foreground and background, bold and inverse) for the frame being drawn and the frame last sent; `flush()` answers the string that turns one into the other — cursor moves and only the cells that changed, a style sent only where it differs — for the caller to `write`. A `Screen` made with `palette256` sends the nearest 256-colour index instead. `Canvas` draws pixels on a screen, two to a cell with the half block "▀" (`setPixel`, `fillRect`, `line`, `text`). The escapes (`enterAltScreen`, `hideCursor`, `clearScreen`, `beginSync`, …) are functions answering strings, and a `Screen` with `sync` set wraps each flush that changes anything in synchronized output (mode 2026). `FixedStep` is a fixed-step clock: `advance(nowMs)` answers the whole steps of `1000 / stepsPerSecond` ms since the last call, at most `maxSteps`, and `alpha()` the remainder, for logic at 240 Hz and drawing at 120. `KeyDecoder` turns raw-mode bytes into `KeyEvent`s (arrows as `ESC [` or `ESC O`, Enter, Space, Escape, Ctrl-C, characters), carries a sequence a read cut short into the next `feed`, and decides a lone ESC on a timeout the caller's clock measures. `feedEvents` and `pollEvents` read the same bytes as `TermEvent`s, whose `type` is an `EVENT_` constant: keys with `MOD_` bits and an `ACTION_` (legacy, modifyOtherKeys and the kitty keyboard protocol), SGR mouse reports in cells or pixels, bracketed paste, focus, and the terminal's replies to queries, which never come out as keys. `KeyState` tracks which keys are held, making up the releases a terminal without the kitty protocol never sends and turning Ctrl-C into `EVENT_QUIT`. The size, raw mode and the clock are the caller's, so the module reaches no capability and prints the same bytes under Node (`tests/link/std_term`, `std_term_f64`; [guide](../docs/guide/using-nish/standard-library.md#nishterm)) |
|
|
46
46
|
| [`term-probe.ts`](https://github.com/amritk/nish/blob/main/std/term-probe.ts) | what the terminal can do, asked once at start. `probeQueries(env)` is every query as one string — XTVERSION, DECRQM for synchronized output and pixel mouse, kitty's keyboard flags and a kitty graphics query, XTSMGRAPHICS, the cell and text-area sizes, a true-colour read-back, and DA1 last, wrapped for tmux's or screen's passthrough where only the outer terminal can answer. `TermProbe` takes the replies a read at a time (`feed`), holds back any key typed meanwhile (`heldEvents`), is `done()` once DA1 is answered or `timedOut(now)` after 250 ms, and `result()` reads the replies and a `TermEnv` (the `TERM`, `COLORTERM`, `TMUX`, `SSH_*`, `NO_COLOR` and `NISH_TERM_*` variables) into a `TermCaps`: colours, graphics backend, sync, kitty keyboard, cell size, pixel mouse, multiplexer. Pure: the environment, the bytes and the clock are the caller's (`tests/link/std_term_probe`; [guide](../docs/guide/using-nish/terminal.md#what-it-detects-and-what-it-falls-back-to)) |
|
|
47
47
|
| [`term-rate.ts`](https://github.com/amritk/nish/blob/main/std/term-rate.ts) | how fast the link to the terminal is, and the frame rate and detail a program keeps to under it. A `RateController` is told each frame sent (`frameSent(bytes, costNs, nowMs)`) and each acknowledgement — the answer to the DSR 5 query sent after a frame — (`ackReceived(nowMs)`), keeps running averages of the round trip, the bytes a second delivered and the cost of a frame, and answers `mayDraw(nowMs)` and a `RateDecision`: the frame interval, a resolution divisor, a backend cap and a palette, stepped down a tier when frames back up and up again when the link has room; `stats()` is the `TermStats` a program can show. Pure: no capability and no clock (`tests/link/std_term_rate`, `std_term_rate_f64`; [guide](../docs/guide/using-nish/terminal.md#how-the-frame-rate-adapts)) |
|
|
48
|
-
| [`term-pixels.ts`](https://github.com/amritk/nish/blob/main/std/term-pixels.ts) | a `Framebuffer` of `0xRRGGBB` pixels and the encoders that draw it with the backend the terminal has: `kittyFrame` (kitty graphics, one image id retransmitted each frame), `sixelFrame` (a fixed palette, optionally dithered), `drawHalfBlocks` onto a `Canvas` and `drawAscii` onto a `Screen`, each into the `PixelRect` `fitFramebuffer` letterboxes in the cells; `scaleFramebuffer` shrinks a frame by the controller's divisor. `PixelBytes` keeps the encoders' output and working arrays, so frame after frame allocates nothing. Pure (`tests/link/std_term_pixels`, `std_term_pixels_f64`; [guide](../docs/guide/using-nish/standard-library.md#nishterm-pixels)) |
|
|
48
|
+
| [`term-pixels.ts`](https://github.com/amritk/nish/blob/main/std/term-pixels.ts) | a `Framebuffer` of `0xRRGGBB` pixels, made and resized by `tryFramebuffer` and `tryResize` with an `Err` for a size the constructor and `resize` panic on, and the encoders that draw it with the backend the terminal has: `kittyFrame` (kitty graphics, one image id retransmitted each frame), `sixelFrame` (a fixed palette, optionally dithered), `drawHalfBlocks` onto a `Canvas` and `drawAscii` onto a `Screen`, each into the `PixelRect` `fitFramebuffer` letterboxes in the cells; `scaleFramebuffer` shrinks a frame by the controller's divisor. `PixelBytes` keeps the encoders' output and working arrays, so frame after frame allocates nothing. Pure (`tests/link/std_term_pixels`, `std_term_pixels_f64`, `std_term_pixels_try`; [guide](../docs/guide/using-nish/standard-library.md#nishterm-pixels)) |
|
|
49
49
|
| [`term-io.ts`](https://github.com/amritk/nish/blob/main/std/term-io.ts) | the term module that does the I/O. `runTerminal(options, state, update, render)` is a whole program loop: it opens the terminal, steps `update` at a fixed rate, calls `render` with a `Frame` (the `Screen`, the `Framebuffer`, the step `alpha`, `TermCaps` and `TermStats`) whenever the controller lets a frame go, and closes when `update` answers false or the user presses Ctrl-C. `openTerminal(options)` answers a `Terminal` for a program's own loop (`readEvents`, `present`, `stats`, `close`). Opening refuses a pipe, enters raw mode and the alternate screen, probes the terminal and turns on the kitty keyboard, mouse, paste and focus reports the options ask for, with the runtime's restore string set before each so a panic or signal leaves the terminal as it was; `present` sends the frame in the best backend the controller allows as one write and acknowledges it with DSR 5. Reaches `tty` (`tests/term-io/relay.mjs` drives it in a pseudo-terminal from `tests/run.js`'s `term-io` section; `tests/link/std_term_io_deny`; [guide](../docs/guide/using-nish/terminal.md)) |
|
|
50
50
|
| [`input.ts`](https://github.com/amritk/nish/blob/main/std/input.ts) | `nish/input`: what one fixed step reads from its player, for a program whose steps run the same behind a terminal, a page or a test. `StepInput` holds the step's `events` and the `KeyState` of which keys are down, which a host owns and points at what it read each step; `isDown(key, code)` reads a key. The events and the key state are `nish/term`'s. Pure: no capability, no I/O and no clock |
|
|
51
51
|
| [`raster.ts`](https://github.com/amritk/nish/blob/main/std/raster.ts) | `nish/raster`: drawing into a frame of `0xRRGGBB` pixels held as an `Int32Array` with its width and height, so the same draw fills a terminal's `Framebuffer` (`rasterFrame(fb.pixels)` lends its `i32[]`) and a wasm page's module storage with no copy. Colours (`rasterRgb`, `rasterMix`, `rasterAdd`, `rasterDim`, `rasterHue`, `rasterWeight`), a gradient, rectangles, anti-aliased discs, additive glows, 5×7 pixel text (`rasterText`, `rasterTextWidth`), a fading `RasterTrail` and a `RasterParticles` pool made once and stepped in place. Every shape clips to the frame and to the rows the array has. Pure: no capability, no I/O and no clock. `tests/link/std_raster` |
|
|
@@ -91,7 +91,8 @@ closed), so `length` is right in both number modes, and the one-shot functions
|
|
|
91
91
|
below refuse a longer input as each row says.
|
|
92
92
|
|
|
93
93
|
**Private keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`,
|
|
94
|
-
`crypto/ed25519.ts`, `crypto/
|
|
94
|
+
`crypto/ed25519.ts`, `crypto/rsa-sign.ts`, `crypto/x509.ts` and
|
|
95
|
+
`crypto/x509-random.ts` take and give
|
|
95
96
|
a private key as a `Secret<u8[]>` from
|
|
96
97
|
`nish:secret`, compute on it only inside `expose`, and wipe every intermediate
|
|
97
98
|
the key reaches before they return, with a store the optimiser may not remove
|
|
@@ -121,7 +122,8 @@ is listed in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.m
|
|
|
121
122
|
| [`crypto/aes.ts`](https://github.com/amritk/nish/blob/main/std/crypto/aes.ts) | AES-128 and AES-256, bitsliced four blocks at a time with the Boyar–Peralta S-box circuit, so no table is read; natively, on a CPU with AES-NI and PCLMULQDQ or the ARMv8 AES and PMULL instructions, the compiler sends the key schedule, the block, GCTR and GHASH to the runtime's kernels instead (`runtime/runtime-aes.c`), and `NISH_AES=soft` pins the bitsliced code: `aesKey(key)` expands a 16- or 32-byte key into an `AesKey` (or `aesKeyInto(key, out)` into one the caller holds, allocating nothing that outlives the call), then `aesEncryptBlock`, `aesGcmSeal` / `aesGcmOpen` (tag last, checked in full before anything is decrypted; any non-empty IV) and `aesHeaderMask`. AES-192 is out of scope, and a wrong length answers `null`, as does an `AesKey` not made by `aesKey`; one whose H is zero opens nothing. An `AesKey` holds its round keys in `roundKeys` and H in `h`, two `u64` words (high, low); `aesKeyWipe(key)` zeroes both with `wipe`'s volatile stores, the kernels' powers of H after the schedule included, and is how a holder drops a key. The bitsliced schedule's, block's and GCTR's working copies, the tag's E(K, J0) block, the tag open compared and J0 itself are wiped the same way before they are released | FIPS 197, SP 800-38D, RFC 9001 §5.4.3, Wycheproof `aes_gcm` (all 316 cases; the 103 AES-192 ones check that the key is refused) |
|
|
122
123
|
| [`crypto/p256.ts`](https://github.com/amritk/nish/blob/main/std/crypto/p256.ts) | ECDSA over P-256 with RFC 6979's deterministic nonces: `p256PublicKey(priv)` (65-byte uncompressed SEC1) from a `Secret<u8[]>` private key, `p256Sign` / `p256Verify` over a digest and `p256SignSha256` / `p256VerifySha256` over a message, and `p256SignSha256Into(scratch, priv, msg, off, len, out, at)`, the same signature written into the caller's window in a `P256SignScratch` made once, keeping nothing in the arena; a signature is `r` and `s`, 32 big-endian bytes each, not DER (`crypto/x509.ts`'s `x509DerSignatureRS` converts one). A malformed key, a point off the curve or an `r` or `s` out of range answers `null` or `false`, never a panic. ECDSA is malleable, and `p256Verify` accepts a high `s`: when `(r, s)` verifies, so does `(r, n − s)` | RFC 6979 A.2.5, Wycheproof `ecdsa_secp256r1_sha256`, `_sha256_p1363`, `_sha512` and `_sha512_p1363` |
|
|
123
124
|
| [`crypto/p384.ts`](https://github.com/amritk/nish/blob/main/std/crypto/p384.ts) | ECDSA verification over P-384: `p384Verify(pub, digest, sig)` over a digest from any hash (one longer than 48 bytes is truncated to its leftmost 384 bits) and `p384VerifySha384(pub, msg, sig)` over a message; the key is 97-byte uncompressed SEC1 and the signature `r` and `s`, 48 big-endian bytes each, not DER. It only verifies, so it holds no `Secret`. A malformed key, a point off the curve, an `r` or `s` out of range and a sum at the identity answer `false`, never a panic. ECDSA is malleable, and `p384Verify` accepts a high `s` | RFC 6979 A.2.6, Wycheproof `ecdsa_secp384r1_sha384`, `_sha384_p1363`, `_sha256`, `_sha512` and `_sha512_p1363` |
|
|
124
|
-
| [`crypto/rsa.ts`](https://github.com/amritk/nish/blob/main/std/crypto/rsa.ts) | RSA signature verification under a public key
|
|
125
|
+
| [`crypto/rsa.ts`](https://github.com/amritk/nish/blob/main/std/crypto/rsa.ts) | RSA signature verification under a public key (`crypto/rsa-sign.ts` signs): `rsaParsePublicKey(der)` reads a PKCS#1 `RSAPublicKey` (strict DER, a 1,024-to-8,192-bit modulus, an odd exponent from 3 below 2^32) into an `RsaPublicKey`, and `rsaVerifyPkcs1v15(key, hash, msg, sig)` and `rsaVerifyPss(key, hash, saltLen, msg, sig)` verify RSASSA-PKCS1-v1_5 and RSASSA-PSS (MGF1 with the same hash) over a message, the hash one of `RSA_HASH_SHA256`, `RSA_HASH_SHA384` and `RSA_HASH_SHA512`. A malformed key answers `null` and a bad signature `false`, never a panic. Public inputs only, so nothing is a `Secret` and the arithmetic is not constant-time (RSA-2) | RFC 8017 §8.2.2, §9.1.2, §9.2; Wycheproof `rsa_signature_*` and `rsa_pss_*` |
|
|
126
|
+
| [`crypto/rsa-sign.ts`](https://github.com/amritk/nish/blob/main/std/crypto/rsa-sign.ts) | RSA-PSS signing with SHA-256, for a TLS 1.3 server's CertificateVerify (`rsa_pss_rsae_sha256`): `rsaParsePrivateKey(der, start, end)` reads a PKCS#1 `RSAPrivateKey` (strict DER, two-prime, a 2,048-to-4,096-bit modulus of whole bytes, `e` odd from 3 below 2^32) into a `Secret<u8[]>` and refuses a key whose private exponent or CRT values do not sign under its modulus; `crypto/x509.ts`'s `x509ParseRsaPrivateKey` reads one from PKCS#1 or PKCS#8 PEM. `rsaSignPssSha256(priv, msg)` signs with MGF1-SHA-256 and a 32-byte salt derived from the key and the message, so the same message always gets the same signature; `rsaSignPssSha256Into(scratch, priv, msg, off, len, out, at)` writes it into the caller's window in an `RsaSignScratch` made once; `rsaSignPssSha256Salted` takes the salt; `rsaSignRaw` is the bare private operation. Each signature is checked under the public exponent before it is returned. A bad key or a failed check answers `null`, never a panic. The private operation is two fixed-window half exponentiations joined by Garner's formula (CRT), with the key's CRT values checked at load and no blinding, checked for secret-dependent branches and addresses by `ct_asm` (RSA-S1, RSA-S2) | RFC 8017 §8.1.1, §9.1.1, §A.1.2; the keys and ciphertexts of Wycheproof `rsa_pkcs1_2048`, `_3072` and `_4096` for the raw operation; PSS known answers each verified by OpenSSL |
|
|
125
127
|
| [`crypto/x509.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x509.ts) | DER, PEM and X.509 over P-256: `pemToDer` / `derToPem` (RFC 7468, padded standard base64, strict labels), `x509ParseP256PrivateKey` (SEC1 or PKCS#8, answering a `Secret<u8[]>`), `x509ParseCertificate` / `x509ParseChain` into an `X509Certificate`, `x509VerifySignature` (ecdsa-with-SHA256 under an issuer's key), `x509DerSignatureRS` (a DER ECDSA-Sig-Value as the `r || s` `crypto/p256.ts` takes), `x509MintSelfSigned`, the 1-to-14-day self-signed P-256 certificate WebTransport's `serverCertificateHashes` accepts, and `x509CertificateHash`, its SHA-256. DER is read strictly — non-minimal lengths and integers, indefinite lengths and trailing bytes answer `null`. `x509ParseCertificate` names the signature algorithm (`X509_SIG_*`: ECDSA with SHA-256 or SHA-384, RSA PKCS#1 v1.5 with SHA-1 to SHA-512, RSASSA-PSS with its hash and salt, Ed25519) and key type (`X509_KEY_*`: P-256, P-384, RSA, Ed25519), each in its one strict spelling, and decodes subjectAltName, basicConstraints, keyUsage, extKeyUsage, nameConstraints and the subject and authority key identifiers; a repeated or malformed extension refuses the certificate, and an unknown critical one sets `unknownCritical`. `x509NameEqual` and `x509NameIsPrefix` compare Names byte for byte, not by RFC 5280 §7.1. It parses and does not validate: there is no path validation, nothing applies the extensions to a chain, and no clock is consulted; `x509VerifySignature` checks only ecdsa-with-SHA256 under a P-256 key, and `x509DerSignatureRSWidth` reads a P-384 signature. `pemToDer` refuses a file in which any block, of any label, is malformed. `x509MintSelfSigned` refuses a common name that is not UTF-8 or holds a NUL, and its key and serial must come from `crypto.getRandomValues`, which the module cannot call itself without refusing wasm32: `crypto/x509-random.ts` draws them (X509-6) | X.690, RFC 5280, RFC 7468, RFC 5915, RFC 5208 / 5958, RFC 4055, RFC 8410; certificates checked against OpenSSL |
|
|
126
128
|
| [`crypto/x509-random.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x509-random.ts) | **Native only**: the key and serial `crypto/x509.ts`'s mint needs, drawn from `crypto.getRandomValues`, so a program that imports it does not compile for wasm32 and `crypto/x509.ts` imports nothing from it. `x509DrawP256Key()`, a `Secret<u8[]>` P-256 private key drawn again until it is a scalar in [1, n) (each refused draw wiped); `x509DrawSerial()`, twenty octets whose first is 0x40 to 0x7f, so a positive, non-zero, full-length serial; and `x509MintSelfSignedDrawn(priv, commonName, notBeforeMs, days)`, `x509MintSelfSigned` with a drawn serial | — |
|
|
127
129
|
| [`crypto/pki-roots.ts`](https://github.com/amritk/nish/blob/main/std/crypto/pki-roots.ts) | **Native only**: the trust anchors, read where OpenSSL and Go look. `pkiLoadSystemRoots()` gives a `PkiRoots` — `roots` (parsed `X509Certificate`s, no two with the same DER), `sources` (the files read) and `skipped` — from the file `SSL_CERT_FILE` and the `:`-separated directories `SSL_CERT_DIR` name when either is set and not empty, with no fallback, and otherwise from the first of `pkiSystemBundles()` (Go's six paths, in Go's order) that exists and `/etc/ssl/certs` (`PKI_SYSTEM_DIR`). `pkiLoadRoots(file, dirs, bundles)` and `pkiLoadRootsFor(certFile, certDir, dirs, bundles)` take the paths and the variables' values given. A directory gives its `*.pem`, `*.crt` and `xxxxxxxx.N` entries; only a regular file is read; a PEM block that is not a certificate `x509ParseCertificate` accepts, a file over `PKI_ROOTS_MAX_FILE_BYTES` and an entry past `PKI_ROOTS_MAX_FILES` or `PKI_ROOTS_MAX_ROOTS` count in `skipped` and are passed over. It does not read the macOS Keychain ([PKI-R7](../docs/security/crypto-pki.md#pki-r7-low-the-macos-keychain-is-not-read)) | — |
|
|
@@ -241,7 +243,7 @@ reads one, and it still takes its randomness as an argument.
|
|
|
241
243
|
| [`net/quic-conn-ack.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-conn-ack.ts) | `QuicAckRanges`: the packet numbers one space received, as at most 32 disjoint ranges, for duplicate detection (`record`, `contains`) and for the ACK frame written from them (`pushAck`, or `putAck` in place). Past 32 ranges the lowest is dropped and a floor raised over it, below which every packet number reads as already received | RFC 9000 §12.3, §13.2, §19.3 |
|
|
242
244
|
| [`net/quic-conn-cid.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-conn-cid.ts) | `QuicCidTable`: the connection IDs a connection issued (routed by `ownsLocal`, retired by the peer with `retireLocal`) and the ones its peer issued (`addPeer`, with Retire Prior To retiring older ones into `retirePending`, and `currentPeer` the one sent to). A reused sequence number, an ID under two sequence numbers and retiring the ID a packet was sent to are PROTOCOL_VIOLATION; more active IDs than advertised, or more owed retirements than twice that, CONNECTION_ID_LIMIT_ERROR. Its slots are fixed when it is made: an ID is copied into one, `addPeerAt` / `ownsLocalAt` / `retireLocal` read it from the packet in place, and `reset` empties the table for the next connection | RFC 9000 §5.1, §19.15, §19.16 |
|
|
243
245
|
| [`net/quic.ts`](https://github.com/amritk/nish/blob/main/std/net/quic.ts) | The server side of a QUIC connection: `new QuicConnection(config, entropy)`, `receive(datagram, now)`, `signatureInput()` / `sign(signature)`, `takeDatagram(now)` until `null`, `deadline()` / `handleTimer(now)` for its timers, and `readStream()` / `writeStream(id, data, fin)` once connected; `updateKeys()`, `close(code)` and `release()`; `acceptRetry(originalDcid, retryScid)` for a connection a Retry token opened; `quicStatelessResetToken(key, cid)`. TLS 1.3 runs over CRYPTO frames at the Initial, Handshake and 1-RTT levels (`TlsServer` with `quic` set), the keys of each level come from `nish/net/quic-packet` as the secrets appear and are discarded and wiped as RFC 9001 §4.9 says, transport parameters go both ways and the client's are checked, every ack-eliciting packet is acknowledged in its space, the client gets new connection IDs once the handshake is confirmed, PATH_CHALLENGE is answered, and an ack-eliciting Initial is padded to 1200 bytes and held to three times what the unvalidated client sent. A protocol violation closes the connection with the RFC's transport error, a TLS alert with CRYPTO_ERROR; a packet that cannot be used is dropped and counted. The idle timeout is the smaller of both sides' `max_idle_timeout`, at least three probe timeouts, and closes silently; key update runs both ways, the client's followed (at most `QUIC_CONN_MAX_KEY_UPDATES`, QUIC-4) and the server's started by `updateKeys()`, with the next read keys derived in advance and the previous kept a probe timeout for reordered packets; every connection ID carries the stateless reset token the configuration's static key gives it. Loss recovery is `nish/net/quic-recovery`'s: what a lost packet carried (CRYPTO, STREAM, HANDSHAKE_DONE and the connection-ID frames) is sent again, a probe timeout sends a probe (two datagrams in the Initial and Handshake spaces, `QUIC_CONN_HANDSHAKE_PROBES`, each with the oldest CRYPTO data not acknowledged), a client that shows it lacks the handshake flight (an Initial repeating CRYPTO data, an ack-eliciting Handshake packet) gets it again at once, up to `QUIC_CONN_EARLY_RESENDS` times a connection (QUIC-8), and NewReno's window holds back everything but ACKs and probes. Streams are `nish/net/quic-stream`'s, both ways and both kinds, through `nextStreamEvent()`, `openStream(bidirectional)`, `streamRead(id, buf, at, length)`, `streamWrite(id, buf, from, length, fin)`, `streamReset(id, code)` and `streamStopSending(id, code)`; RFC 9221's datagrams through `sendDatagram(buf, from, length)`, `readDatagram(buf, at, cap)` and `maxDatagramPayload()` when `config.maxDatagramFrameSize` offers them. Nothing is allocated per packet (QUIC-3): `receiveWindow(buf, off, len, now)` and `takeDatagramInto(out, at, now)` open and build packets in place inside an arena block, and `reset(entropy)` makes the connection a reusable slot for the next client. The AEAD limits of RFC 9001 §6.6 are kept: a 1-RTT write key under AES-GCM seals at most 2^23 packets, the server starting a key update at three quarters of that and closing with AEAD_LIMIT_REACHED at it if none can be made, and packets that fail to authenticate past the integrity limit (2^52 for AES-GCM, 2^36 for ChaCha20-Poly1305) close the connection the same way (QUIC-6). One Application Data packet number in every 128 to 1024 is skipped, and an ACK of a skipped one is PROTOCOL_VIOLATION, an optimistic ACK (RFC 9000 §21.4, QUIC-7) | RFC 9000 §10.1, §10.3.2, §21.4; RFC 9001 §4, §5.7, §6, §8; RFC 9221; a handshake and stream echo, and an update each way, against aioquic, recorded and replayed byte for byte |
|
|
244
|
-
| [`net/quic-listener.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-listener.ts) | What a QUIC server answers to a datagram no connection owns: `new QuicListener(config, entropy)` and `handleWindow(buf, at, len, address, now, answer)`, which reads the datagram `buf[at .. at + len)` in place and fills `answer`, a `QuicListenerAnswer` made once with `QUIC_LISTENER_ANSWER_SIZE` of room and refilled in it, so a datagram costs no arena memory whatever it is answered with (H3-3); `handle(datagram, address, now)` does the same over a whole array into an answer of its own. An answer's `kind` is `QUIC_LISTEN_DROP`, `_ACCEPT` (make a `QuicConnection`; after a Retry, `acceptRetry` it with the answer's IDs), or a `reply` to send: `_VERSION_NEGOTIATION` for another version in a full-sized datagram, `_RETRY` with an address-validation token when `config.retry` is set, `_INVALID_TOKEN` for a Retry token that is forged, moved, expired or for another ID, and `_STATELESS_RESET` for a short header to an ID the server has no connection for. A token is 128 bits of HMAC-SHA256 under `config.retryTokenKey` over its issue time, the original DCID, the new ID and the client's address and port, good for `config.retryTokenLifetime`. A reset ends in `quicStatelessResetToken` of the packet's ID, is always shorter than the datagram it answers and never under 21 bytes, and is rate limited. Its own unpredictable bytes come from an HMAC generator seeded once by the caller. `release()` wipes the seed, the generator, the scratch, the INVALID_TOKEN keys and the spare answer `handle` keeps, and `handle` and `handleWindow` answer nothing after it; its other methods still run, under the zeroed seed, and are the caller's not to call (QUIC-5). For the carrier's send loop, `quicListenerTakePaced(conn, now)` takes a connection's next datagram only when its pacer has the credit, and `quicListenerPaceTime(conn, now)` says when it will; `quicListenerTakeFlight(conn, now, buf, at, cap, flight)` writes a paced flight back to back for one GSO send, with the `UDP_SEGMENT` size in its `QuicFlight`, and `quicListenerReceiveSegments` hands a connection a GRO receive segment by segment, in place | RFC 9002 §7.7; RFC 9000 §5.2.2, §6, §8.1, §10.3, §17.2.1, §17.2.5; Version Negotiation, Retry, a stateless reset and the idle timeout against aioquic, recorded and replayed byte for byte |
|
|
246
|
+
| [`net/quic-listener.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-listener.ts) | What a QUIC server answers to a datagram no connection owns: `new QuicListener(config, entropy)` and `handleWindow(buf, at, len, address, now, answer)`, which reads the datagram `buf[at .. at + len)` in place (a window outside `buf` is dropped unread) and fills `answer`, a `QuicListenerAnswer` made once with `QUIC_LISTENER_ANSWER_SIZE` of room and refilled in it, so a datagram costs no arena memory whatever it is answered with (H3-3); `handle(datagram, address, now)` does the same over a whole array into an answer of its own. An answer's `kind` is `QUIC_LISTEN_DROP`, `_ACCEPT` (make a `QuicConnection`; after a Retry, `acceptRetry` it with the answer's IDs), or a `reply` to send: `_VERSION_NEGOTIATION` for another version in a full-sized datagram, `_RETRY` with an address-validation token when `config.retry` is set, `_INVALID_TOKEN` for a Retry token that is forged, moved, expired or for another ID, and `_STATELESS_RESET` for a short header to an ID the server has no connection for. A token is 128 bits of HMAC-SHA256 under `config.retryTokenKey` over its issue time, the original DCID, the new ID and the client's address and port, good for `config.retryTokenLifetime`. A reset ends in `quicStatelessResetToken` of the packet's ID, is always shorter than the datagram it answers and never under 21 bytes, and is rate limited. Its own unpredictable bytes come from an HMAC generator seeded once by the caller. `release()` wipes the seed, the generator, the scratch, the INVALID_TOKEN keys and the spare answer `handle` keeps, and `handle` and `handleWindow` answer nothing after it; its other methods still run, under the zeroed seed, and are the caller's not to call (QUIC-5). For the carrier's send loop, `quicListenerTakePaced(conn, now)` takes a connection's next datagram only when its pacer has the credit, and `quicListenerPaceTime(conn, now)` says when it will; `quicListenerTakeFlight(conn, now, buf, at, cap, flight)` writes a paced flight back to back for one GSO send, with the `UDP_SEGMENT` size in its `QuicFlight`, and `quicListenerReceiveSegments` hands a connection a GRO receive segment by segment, in place | RFC 9002 §7.7; RFC 9000 §5.2.2, §6, §8.1, §10.3, §17.2.1, §17.2.5; Version Negotiation, Retry, a stateless reset and the idle timeout against aioquic, recorded and replayed byte for byte |
|
|
245
247
|
| [`net/quic-recovery.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-recovery.ts) | QUIC loss detection and congestion control, sans-IO, for the server side: `QuicRecovery` holds one `QuicSentPackets` ring per packet number space (16 packets for Initial and Handshake, 128 for Application Data, fixed when it is made); `onPacketSent(space, pn, size, now)` records an ack-eliciting packet and answers its slot, `onAck(space, ranges, count, ackDelay, now)` reads an ACK frame's ranges and lists the slots it acknowledged and showed lost (`acked`, `lost`), `deadline(amplificationBlocked)` and `onTimeout(now, amplificationBlocked)` run the time-threshold loss timer and the probe timeout with its backoff, `discardSpace` drops a space whose keys are gone, `evictOldest` frees a slot for a probe. The RTT estimate (`latestRtt`, `smoothedRtt`, `rttVar`, `minRtt`, `probeTimeout()`), loss by packet threshold 3 and time threshold 9/8, NewReno (slow start, one halving per recovery period, congestion avoidance, the 2400-byte floor, persistent congestion) and a pacer at 5/4 of the window per smoothed RTT (`pacerDelay`, `onPaced`), all in integer milliseconds and bytes | RFC 9002 §5–7, Appendices A and B, worked by hand in `net_quic_recovery` |
|
|
246
248
|
| [`net/quic-stream.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-stream.ts) | QUIC streams, sans-IO, which `nish/net/quic` drives: `QuicStreams` holds one `QuicStream` slot per stream that may be open at once (the client's bidirectional and unidirectional limits and the server's own), each with a fixed receive and send buffer, found by ID through a hash index. The send and receive state machines of §3 (`QUIC_SEND_*`, `QUIC_RECV_*`), reassembly into the receive buffer, flow control per stream and for the connection both ways (MAX_STREAM_DATA and MAX_DATA raised as the application reads, STREAM_DATA_BLOCKED and DATA_BLOCKED once per limit), the stream limits (MAX_STREAMS raised as the client's streams finish, STREAMS_BLOCKED at the client's), STOP_SENDING answered with RESET_STREAM, and the refusals STREAM_STATE_ERROR, STREAM_LIMIT_ERROR, FLOW_CONTROL_ERROR and FINAL_SIZE_ERROR. The application's answers are `QUIC_STREAM_OK`, `QUIC_STREAM_END` and `QUIC_STREAM_ERR_*` | RFC 9000 §2–§4, §19.4–§19.14 |
|
|
247
249
|
| [`net/quic-datagram.ts`](https://github.com/amritk/nish/blob/main/std/net/quic-datagram.ts) | `QuicDatagramQueue`: a fixed ring of DATAGRAM payloads, one each way per connection, copied in (`push`) and out (`pop`, or `putFrame` as a DATAGRAM frame), refusing past a full ring and counting what it drops | RFC 9221 §5 |
|
|
@@ -251,7 +253,7 @@ reads one, and it still takes its randomness as an argument.
|
|
|
251
253
|
| [`net/dns-resolver.ts`](https://github.com/amritk/nish/blob/main/std/net/dns-resolver.ts) | The DNS stub resolver with no I/O of its own: `DnsResolver(config, hosts, maxLookups)` takes `start(name, port, now)` and answers a lookup's index, or `DNS_RESOLVE_BUSY` past `maxLookups` (at most 64). Each lookup asks A and AAAA at once; the caller sends what `nextOutgoing(out, to, meta, id)` gives (a datagram, a TCP connection or a close, with the caller's random ID), feeds what comes back to `receive` or `receiveStream`, calls `tick(now)` once `nextDeadlineNanos()` passes, and reads `result(lookup, out, ttls)`: the count of 18-byte addresses, A first, each with its TTL, or `DNS_RESOLVE_PENDING`, `NOT_FOUND`, `NO_ANSWER` or `CNAME`. Servers are tried in turn for `attempts` rounds of `timeout`; TC asks again over TCP (a reply over `DNS_TCP_MAX_REPLY`, 16 KiB, fails the server); a CNAME left unanswered is followed by a query of its own, at most 8 hops and never back to the start; the search list and `ndots` run as resolv.conf(5) says. `localhost`, an address literal and a hosts entry answer with no packet. A reply from another address or port, or with another ID or question, is dropped, counted (`droppedSource`, `droppedId`, `droppedQuestion`, `droppedMalformed`) and the query keeps waiting. It never imports `nish:net`, reads a clock or a file, and builds for `wasm32`; every buffer is made in the constructor | RFC 1035 §4.2 and §7.3; RFC 5452 (forgery resilience); RFC 7766 (DNS over TCP); resolv.conf(5); scripted packets for every drop, bound and error path (`tests/link/std_dns_resolver`) |
|
|
252
254
|
| [`net/dns.ts`](https://github.com/amritk/nish/blob/main/std/net/dns.ts) | `nish/net/dns-resolver` on `nish:net` sockets, on the caller's loop: `DnsClient(resolver, loop, tokenBase)` opens a new UDP socket on a kernel-chosen port for each try, or a TCP connection for a TCP one, under a token of its range (`owns`), draws each query ID from `crypto.getRandomValues`, and never waits: the program's `pollWait` hands it `ready(token, events, now)`, calls `tick(now)` and waits no longer than `timeoutMs(now, own)`. `resolveHost(name, timeoutMs, port, out, ttls)` reads `/etc/resolv.conf` and `/etc/hosts` and blocks on a loop of its own, for a CLI or start-up; `dnsLookupWith` does the same with a configuration given. | A Nish DNS server on loopback: UDP, TCP, TC, CNAME, the search list, a dead server, `attempts`, the hosts file and spoofed replies (`tests/link/std_dns`); the capability report (`std_dns_caps`); a flat arena over 2,000 lookups (`std_dns_soak`) |
|
|
253
255
|
| [`net/hpack.ts`](https://github.com/amritk/nish/blob/main/std/net/hpack.ts) | HPACK, HTTP/2's header compression: `HpackEncoder` and `HpackDecoder`, one per direction of a connection, each with its `HpackTable`; and beneath them the §5.1 integer (`hpackEncodeInteger` / `hpackDecodeInteger`), the §5.2 string (`hpackEncodeString` / `hpackDecodeString`) and Appendix B's Huffman code (`HpackHuffman`, `hpackHuffmanEncode`, `hpackHuffmanDecode`, `hpackHuffmanLength`). Names and values are `u8[]`. The encoder takes the representation and the Huffman choice per field, and sends a never-indexed field as a literal even when a table holds it. The decoder answers a negative `HPACK_ERR_*` code, and stays spent, for a truncated block, an integer past 2^31 - 1, an index of zero or out of range, bad Huffman padding, EOS, a size update above the SETTINGS limit, after a field or missing when a lowered limit requires one, and for a block that would copy more than `HPACK_COPY_FACTOR` times the larger of the table's size and the block's length into and out of the table (`HPACK_ERR_COPY_BUDGET`; `tableCopied` counts those octets); a header list past the caller's limit is decoded to the end, its excess dropped, and answered with `HPACK_LIST_TOO_LARGE`, which is not fatal. A window outside its buffer, a negative size or limit, and an integer prefix outside 1 to 8 bits are the program's mistakes and panic | RFC 7541 Appendix C (C.1–C.6, with the dynamic table after every step) and every code of Appendix B |
|
|
254
|
-
| [`net/qpack.ts`](https://github.com/amritk/nish/blob/main/std/net/qpack.ts) | QPACK, HTTP/3's field compression, with a dynamic table of capacity 0: `QpackEncoder` and `QpackDecoder`, one per connection. The encoder writes a field section that starts `00 00` (Required Insert Count 0, Base 0) with `beginSection`, then one field line per `encodeField(out, name, off, len, value, off, len, neverIndexed, huffman)`: an Indexed Field Line when the 99-entry static table holds the field, else a literal with the name by static index when it can, each string Huffman-coded when that is shorter and `huffman` is set, and a never-indexed field always a literal with the N bit. The decoder answers a section's fields as windows into its own `bytes` (`nameStart`, `nameLength`, `valueStart`, `valueLength`, `neverIndexed`, `count`), its arrays reused from section to section. It answers QPACK_DECOMPRESSION_FAILED, and stays spent, for a truncated section, an integer past 2^62 − 1, a non-zero Required Insert Count, a negative Base, any dynamic-table reference, a static index past 98 and bad Huffman; a section past `maxFieldSectionSize` answers `QPACK_SECTION_TOO_LARGE`, which is not fatal. `receiveEncoderStream` accepts Set Dynamic Table Capacity 0 and answers QPACK_ENCODER_STREAM_ERROR for any other capacity, Insert or Duplicate; the encoder's `receiveDecoderStream` accepts Stream Cancellations, split anywhere, and answers QPACK_DECODER_STREAM_ERROR for a Section Acknowledgment or Insert Count Increment; `reason` names the rule. `qpackPushStreamCancellation` is the one instruction it may send. The Huffman code is `nish/net/hpack`'s. A window outside its buffer
|
|
256
|
+
| [`net/qpack.ts`](https://github.com/amritk/nish/blob/main/std/net/qpack.ts) | QPACK, HTTP/3's field compression, with a dynamic table of capacity 0: `QpackEncoder` and `QpackDecoder`, one per connection. The encoder writes a field section that starts `00 00` (Required Insert Count 0, Base 0) with `beginSection`, then one field line per `encodeField(out, name, off, len, value, off, len, neverIndexed, huffman)`: an Indexed Field Line when the 99-entry static table holds the field, else a literal with the name by static index when it can, each string Huffman-coded when that is shorter and `huffman` is set, and a never-indexed field always a literal with the N bit. The decoder answers a section's fields as windows into its own `bytes` (`nameStart`, `nameLength`, `valueStart`, `valueLength`, `neverIndexed`, `count`), its arrays reused from section to section. It answers QPACK_DECOMPRESSION_FAILED, and stays spent, for a truncated section, an integer past 2^62 − 1, a non-zero Required Insert Count, a negative Base, any dynamic-table reference, a static index past 98 and bad Huffman; a section past `maxFieldSectionSize` answers `QPACK_SECTION_TOO_LARGE`, which is not fatal. `receiveEncoderStream` accepts Set Dynamic Table Capacity 0 and answers QPACK_ENCODER_STREAM_ERROR for any other capacity, Insert or Duplicate; the encoder's `receiveDecoderStream` accepts Stream Cancellations, split anywhere, and answers QPACK_DECODER_STREAM_ERROR for a Section Acknowledgment or Insert Count Increment; `reason` names the rule. `qpackPushStreamCancellation` is the one instruction it may send. The Huffman code is `nish/net/hpack`'s. A window outside its buffer and a stream ID outside 0 to 2^62 − 1 panic; a decoder made with a negative field-section limit refuses every section with `QPACK_REASON_LIMIT` | RFC 9204 Appendix B.1, every Appendix A entry by its index, B.2 to B.5's instructions refused, and a request matched byte for byte with pylsqpack's encoding |
|
|
255
257
|
| [`net/http1-codec.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-codec.ts) | `Http1Parser`, an incremental HTTP/1.1 request parser: `feed(buf, off, len)` any slice, then `next()` answers `HTTP1_NEED_MORE`, `HTTP1_HEAD` (`method`, `target`, `minor`, lowercased `names` beside `values`, `header(name)`, `contentLength` or `chunked`, `keepAlive`, `upgrade`), `HTTP1_BODY` (a window onto its buffer, de-chunked), `HTTP1_END`, or one of three final events: `HTTP1_UPGRADE` (`upgradeBytes()` and `declineUpgrade()`), `HTTP1_CLOSED` and `HTTP1_ERROR` with the `status` to answer. It refuses with 400 every request-smuggling shape — `Content-Length` with `Transfer-Encoding`, a repeated or non-digit `Content-Length`, an obs-fold, a bare LF, whitespace before a colon, a malformed chunk size or terminator — and with 413, 414, 431, 501 and 505 what those mean. The head is also kept as spans in a buffer reused from request to request (`head`, `spans`, `methodIs`, `targetIs`, `headerIndex`, `headerIs`, `upgradeIs`), so a parser with `keepText` off allocates nothing per request; `maxChunk` caps each `HTTP1_BODY`, and `restart()` readies it for the next connection. The writer is `http1ResponseHead(status, reason, names, values, bodyLength)`, which adds the framing field itself and refuses (`null`) a CR, LF or other control character anywhere a caller's string lands, and `http1Chunk` and `http1LastChunk` for a chunked body; `http1WriteResponseHead` and `http1WriteChunk` write the same bytes into a caller's buffer at an offset, answering `HTTP1_NO_ROOM` or `HTTP1_REFUSED`, and the first takes a date's bytes to send as a `Date` field on a final response, unless the caller's fields hold one | RFC 9112 §2–§7 and §9.3, RFC 9110 §5, §6.2, §7.2 and §7.8; a corpus fed at every split point (`tests/link/net_http1`) |
|
|
256
258
|
| [`net/http1-client-codec.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-client-codec.ts) | The client side of HTTP/1.1, sans-IO. The writer is `http1RequestHead(method, target, names, values, bodyLength)`, `Host` first and the framing field added for `bodyLength` (`Content-Length`, `HTTP1_CHUNKED` or `HTTP1_NO_BODY`), and `http1WriteRequestHead` into a caller's buffer, answering `HTTP1_NO_ROOM` or `HTTP1_REFUSED` with nothing written; it refuses a method that is not a token, a target that is not a form the method may send, a CR, LF or control byte in a value, not exactly one `Host`, the caller's own framing fields and a `Connection: upgrade`; `http1UpgradeRequestHead(method, target, names, values, upgrade)` writes `Upgrade` and `Connection: Upgrade` itself, with no body. `Http1ResponseParser(maxStatusLine, maxHeaderBytes, maxHeaders, maxBody, maxTrailerBytes)` is told what was asked (`expect(head, connect)`, then `expectUpgrade()` for a request that asked to switch protocols), fed any slice, and `next()` answers `HTTP1_INFORMATIONAL`, `HTTP1_HEAD` (`status`, `reason`, `minor`, lowercased `names` beside `values`, `header(name)`, `contentLength`), `HTTP1_BODY` (a window, de-chunked), `HTTP1_END` with `keepAlive()`, or the final `HTTP1_UPGRADE` (a 2xx to CONNECT or a 101 asked for, `tunnelBytes()`), `HTTP1_CLOSED` and `HTTP1_ERROR`; `finish()` reports the close that ends a body read until close, and anywhere else is `HTTP1_E_TRUNCATED`. Every smuggling shape is refused with its own `HTTP1_E_*` code, as is a 101 not asked for, more than `HTTP1_MAX_INFORMATIONAL` interim responses and a chunk-size line over `HTTP1_MAX_CHUNK_LINE`. Record: [`docs/security/http1-client-codec.md`](../docs/security/http1-client-codec.md) | RFC 9112 §4–§7 and §9.3, RFC 9110 §9.3.6 and §15.2; a corpus fed whole, cut at every byte and a byte at a time, every refusal and limit at its edge, and the server parser reading what the writer writes (`tests/link/net_http1_client`, `_f64`, `_feed_window`) |
|
|
257
259
|
| [`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`) |
|
|
@@ -260,15 +262,16 @@ reads one, and it still takes its randomness as an argument.
|
|
|
260
262
|
| [`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
263
|
| [`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
264
|
| [`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
|
-
| [`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`) |
|
|
265
|
+
| [`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. `mediaTypeParse(value, from, to)` reads a `Content-Type` into a `MediaType` (`type`, `subtype` and its parameters, names lowercased) and `mediaTypeParam` finds one; `formDataDispositionParse` reads a form part's `Content-Disposition`, keeping a backslash as the HTML form submission algorithm writes it. Each answers null for a parameter given twice in any case or a 17th (`docs/security/multipart.md`) | 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`); RFC 9110 §8.3.1 and every refusal in `tests/link/net_media_type` |
|
|
266
|
+
| [`net/multipart.ts`](https://github.com/amritk/nish/blob/main/std/net/multipart.ts) | `MultipartReader`, a `multipart/form-data` body read part by part in place: `next()` answers `MULTIPART_PART` with `name`, `filename` (as given, not a path), `contentType` and the data as `dataStart` and `dataLength` into the body, `MULTIPART_END` once the close delimiter is read, or a `MULTIPART_ERR_*` code it answers from then on: a bad boundary or window, a body cut short, a header line split by a lone CR or LF or folded, a second `Content-Disposition` or `Content-Type`, a disposition that is not `form-data` or has no `name`, and more parts, header lines or header octets than `MultipartLimits` allows (64, 16 and 8,192 by default). Copies no part's data and writes nothing to disk (`docs/security/multipart.md`) | RFC 7578 and RFC 2046 §5.1.1: six bodies Node's `FormData` wrote, every refusal code, every prefix of a body, and each cap at its limit and one past it (`tests/link/net_multipart_read`) |
|
|
264
267
|
| [`net/http2-frame.ts`](https://github.com/amritk/nish/blob/main/std/net/http2-frame.ts) | HTTP/2's frames, sans-IO and allocation-free: `http2ReadHeader` and `http2ParseFrame` read any frame of RFC 9113 §6 into a reused `Http2Frame` (its content left in the buffer as a window), answering 0 or the connection error — FRAME_SIZE_ERROR past the reader's SETTINGS_MAX_FRAME_SIZE or for a frame of the wrong length, PROTOCOL_ERROR for a frame on the wrong stream, padding as long as its frame, or a WINDOW_UPDATE of zero on the connection — with a stream error (`streamError`) for a PRIORITY of the wrong length, a self-dependency or a WINDOW_UPDATE of zero on a stream. `http2SettingCount`, `http2SettingId`, `http2SettingValue` and `http2SettingError` read and check SETTINGS. The writers, one per type (`http2WriteData` … `http2WriteContinuation`, `http2WriteSettingsAck`), write into the caller's buffer at an offset and answer -1 when a frame does not fit | Every type against frames built by hand from §4.1 and §6, both directions, and every refusal (`tests/link/net_http2_frame`) |
|
|
265
268
|
| [`net/http2.ts`](https://github.com/amritk/nish/blob/main/std/net/http2.ts) | `Http2Connection`, the server side of HTTP/2, sans-IO: `feed(buf, off, len)`, then `next()` answers `H2_REQUEST` (`stream`, `fields`), `H2_DATA` (a window onto the input), `H2_TRAILERS`, `H2_RESET`, `H2_WINDOW` (a send window opened), `H2_GOAWAY` or the final `H2_ERROR`; send `output[outputStart .. outputEnd)` and `consume`. `respond`, `writeData` (as far as both windows and the output allow), `writeTrailers`, `reset`, `goaway` and `restart`. The §5.1 stream state machine, connection and stream flow control with WINDOW_UPDATE both ways, SETTINGS and the acknowledgement, PING, header blocks across CONTINUATION decoded by `HpackDecoder`, a 431 past the header-list cap, extended CONNECT behind SETTINGS_ENABLE_CONNECT_PROTOCOL, and every connection and stream error of RFC 9113 as GOAWAY or RST_STREAM. Every final head carries one `date` field from the connection's `date` bytes, when it has them, straight after `:status` and never on a 1xx or trailers, unless the program's fields hold one (matched ASCII case-insensitively). Every cap is an `Http2Config` number fixed at start-up; DATA and every control frame allocate nothing ([H2-1](../docs/security/http2.md)) | RFC 9113 §3–§8, RFC 8441; requests, streamed responses, flow control stalling and resuming, concurrent streams and the date on every final head from a scripted client (`tests/link/net_http2`), and a negative for each error class (`tests/link/net_http2_errors`) |
|
|
266
269
|
| [`net/http2-tls.ts`](https://github.com/amritk/nish/blob/main/std/net/http2-tls.ts) | `Http2TlsServer`: HTTP/2 over `nish/net/tls-tcp` for a program that owns its loop — a pool of `Http2Connection`s beside the TLS slots, slot 0's built by the constructor and every other on the first accept into its slot, each reused with `restart`; `accept`, `readable` / `writable`, `signP256`, `next(slot)` for the slot's next event, `flush(slot)`, `close`. A slot whose ALPN did not choose `h2` is shut down with `close_notify` (RFC 9113 §3.2). Every slot's final responses carry the pool's one `HttpDate` (`date`, from `nish/net/http1-server`), refreshed at `connection(slot)` and `next(slot)` and formatted at most once a second; `date.pin(unixMs)` fixes it for a test. Native only, as `nish:net` is | A Nish TLS client over loopback (`tests/link/net_http2_tls`): ALPN, a GET, an echoed POST, a hundred DATA frames with the arena flat, the date with the arena flat while the pinned clock crosses seconds and shared by two slots, GOAWAY, and the pool; `curl --http2` against its `serve` mode |
|
|
267
270
|
| [`net/http2-cleartext.ts`](https://github.com/amritk/nish/blob/main/std/net/http2-cleartext.ts) | `Http2CleartextServer`: HTTP/2 over plain TCP with prior knowledge (h2c), a pool of `Http2Connection`s, one per accepted socket, for a program that owns its readiness loop — `nish/net/http2-tls`'s loop with a TCP socket in place of TLS, the same method names and interest bits (`H2C_WANT_READ`, `H2C_WANT_WRITE`, `H2C_DONE`), plus `expire(now)` for the preface deadline. Each slot checks the 24-byte preface byte by byte as it arrives and closes the socket, sending nothing, at the first byte that differs; until the preface is whole a slot holds no connection buffer. No `Upgrade: h2c` and no HTTP/1.1 fallback on the same port. No confidentiality and no integrity: serve it only behind a TLS-terminating proxy, on loopback or on a private network ([`docs/security/http2-cleartext.md`](../docs/security/http2-cleartext.md)) | RFC 9113 §3.3 (`tests/link/net_http2_cleartext`, and a refused configuration in `net_http2_cleartext_bad_slots` and `net_http2_cleartext_bad_timeout`) |
|
|
268
271
|
| [`net/http3-frame.ts`](https://github.com/amritk/nish/blob/main/std/net/http3-frame.ts) | HTTP/3's frames and stream types, sans-IO and allocation-free: `h3ReadFrameHeader` reads a type and a length (0 until both are in the window), `h3ReadSettings` a SETTINGS payload into a reused `Http3Settings` (the three identifiers it understands, and the first eight it does not, kept for an extension), `h3ReadIdPayload` a GOAWAY, MAX_PUSH_ID or CANCEL_PUSH; `h3PutFrameHeader`, `h3PutSettings`, `h3PutIdFrame` and `h3PutVarint` write in place. `h3ReservedHttp2Frame` names HTTP/2's reserved types, `h3Greased` the `0x1f * N + 0x21` ones, and the `H3_*` constants are RFC 9114's types, settings and error codes | RFC 9114 §6.2, §7, §8.1, against frames built by hand from §7's layouts (`tests/link/net_http3_frame`) |
|
|
269
|
-
| [`net/http3.ts`](https://github.com/amritk/nish/blob/main/std/net/http3.ts) | `Http3Connection`, the server side of HTTP/3 over a `QuicConnection`'s streams: `next()` answers `H3_REQUEST` (`stream`, `fields`), `H3_DATA` (a window onto `data`, at most `bodyChunk`), `H3_TRAILERS`, `H3_END`, `H3_RESET`, `H3_WRITABLE`, `H3_GOAWAY` or the final `H3_ERROR`; `respond`, `writeData` (takes what the send buffer has room for), `writeTrailers`, `reset` and `goaway` write. It opens its control stream with SETTINGS and its QPACK streams (capacity 0, through `nish/net/qpack`), checks every field section with `nish/net/http-fields`, answers a section past `maxFieldSectionSize` with a 431, sends one `date` field from the connection's `date` bytes on every final head (straight after `:status`, counted against the client's field-section limit, never on trailers) unless the program's fields hold one, and closes the connection with RFC 9114's code for each connection error. No server push. A warm connection allocates nothing per request (`docs/security/http3.md`) | RFC 9114 §4–§8 and RFC 9204 §4.2: a Nish client over QUIC, requests with bodies both ways, trailers, the date and its limit, GOAWAY, cancellation, every error code (`tests/link/net_http3`, `net_http3_errors`) |
|
|
270
|
-
| [`net/http3-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http3-server.ts) | `Http3Server`: HTTP/3 over QUIC on one UDP socket for a program that owns its loop — a pool of `QuicConnection` slots with an `Http3Connection` each, a slot's built on the first Initial accepted into it, slots 0 up, and reused, while the connection-ID index, the timer wheel and the rings are sized from the cap at start-up; a `QuicListener` in front; datagrams routed by a hashed index of every slot's connection IDs; `receive(now, key)`, `tick(now)`, `ready()` for the next slot with news, `flush(now)` sending paced GSO flights, `timeout(now)` from a timer wheel. A handshake that did not choose ALPN `h3` is closed with no_application_protocol (RFC 9114 §3.1); a slot done after GOAWAY is closed and freed. Every slot's final responses carry the server's one `HttpDate` (`date`), refreshed at `connection(slot)` and `ready()` and formatted at most once a second. `stop()` releases every connection and the listener and wipes the configuration's stateless reset and Retry token keys, which are the server's once handed in, and its last answer; the keys are zeroed in place, so a `QuicServerConfig` serves one server (QUIC-5). Native only, as `nish:net` is | A Nish client across loopback (`tests/link/net_http3_server`): requests, a paced 300 KB response, GOAWAY and the slot freed, ALPN, a full pool, the arena over connections through one slot while the pinned date moves a second on for each, one date formatted for two slots; every key read back as zero after `stop()` (`tests/link/net_quic_server_wipes`); aioquic and `curl --http3` against its `serve` mode |
|
|
271
|
-
| [`net/webtransport.ts`](https://github.com/amritk/nish/blob/main/std/net/webtransport.ts) | `WebTransport`, the server side of WebTransport over HTTP/3 as draft-ietf-webtrans-http3-02 has it and Chrome and `wtransport` 0.7 negotiate it, a layer over one `Http3Connection` whose `Http3Config.webtransportSessions` turns it on (extended CONNECT, SETTINGS_H3_DATAGRAM and the draft's two WebTransport settings): `next()` answers `WT_SESSION` (the program `accept`s or `refuse`s it), `WT_DATAGRAM`, `WT_STREAM`, `WT_STREAM_DATA`, `WT_STREAM_END`, `WT_STREAM_RESET`, `WT_STREAM_STOPPED`, `WT_WRITABLE`, `WT_DRAIN` and `WT_CLOSED`, and passes a plain request's `H3_*` events through; `sendDatagram` (the quarter stream ID, then the payload), `openStream`, `write`, `resetStream`, `stopSending`, `close` (CLOSE_WEBTRANSPORT_SESSION) and `drain`. Streams that arrive before their session wait, bounded; every cap is fixed at start-up, and a warm session allocates nothing per datagram or stream (`docs/security/webtransport.md`) | RFC 9220, RFC 9297 and draft-02: a Nish client over QUIC — sessions, datagrams at the size limits, streams both ways, close and drain from either side, every refusal — and one exchange recorded from a `wtransport` 0.7 client replayed byte for byte (`tests/link/net_webtransport`) |
|
|
272
|
+
| [`net/http3.ts`](https://github.com/amritk/nish/blob/main/std/net/http3.ts) | `Http3Connection`, the server side of HTTP/3 over a `QuicConnection`'s streams: `next()` answers `H3_REQUEST` (`stream`, `fields`), `H3_DATA` (a window onto `data`, at most `bodyChunk`), `H3_TRAILERS`, `H3_END`, `H3_RESET`, `H3_WRITABLE`, `H3_GOAWAY` or the final `H3_ERROR`; `respond`, `writeData` (takes what the send buffer has room for), `writeTrailers`, `reset` and `goaway` write. It opens its control stream with SETTINGS and its QPACK streams (capacity 0, through `nish/net/qpack`), checks every field section with `nish/net/http-fields`, answers a section past `maxFieldSectionSize` with a 431, sends one `date` field from the connection's `date` bytes on every final head (straight after `:status`, counted against the client's field-section limit, never on trailers) unless the program's fields hold one, and closes the connection with RFC 9114's code for each connection error. A configuration that breaks one of its caps fails the connection from the start with H3_INTERNAL_ERROR, `fault` naming the rule. No server push. A warm connection allocates nothing per request (`docs/security/http3.md`) | RFC 9114 §4–§8 and RFC 9204 §4.2: a Nish client over QUIC, requests with bodies both ways, trailers, the date and its limit, GOAWAY, cancellation, every error code (`tests/link/net_http3`, `net_http3_errors`) |
|
|
273
|
+
| [`net/http3-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http3-server.ts) | `Http3Server`: HTTP/3 over QUIC on one UDP socket for a program that owns its loop — a pool of `QuicConnection` slots with an `Http3Connection` each, a slot's built on the first Initial accepted into it, slots 0 up, and reused, while the connection-ID index, the timer wheel and the rings are sized from the cap at start-up; a `QuicListener` in front; datagrams routed by a hashed index of every slot's connection IDs; `receive(now, key)`, `tick(now)`, `ready()` for the next slot with news, `flush(now)` sending paced GSO flights, `timeout(now)` from a timer wheel. A handshake that did not choose ALPN `h3` is closed with no_application_protocol (RFC 9114 §3.1); a slot done after GOAWAY is closed and freed; an Initial that arrives while the entropy source fails (`crypto.tryGetRandomValues`) is dropped and counted in `starved`, its slot left free. Every slot's final responses carry the server's one `HttpDate` (`date`), refreshed at `connection(slot)` and `ready()` and formatted at most once a second. `stop()` releases every connection and the listener and wipes the configuration's stateless reset and Retry token keys, which are the server's once handed in, and its last answer; the keys are zeroed in place, so a `QuicServerConfig` serves one server (QUIC-5). `openHttp3Server` answers a slot count or timeout out of range as an `Err` where the constructor panics on either, at start-up. Native only, as `nish:net` is | A Nish client across loopback (`tests/link/net_http3_server`): requests, a paced 300 KB response, GOAWAY and the slot freed, ALPN, a full pool, the arena over connections through one slot while the pinned date moves a second on for each, one date formatted for two slots; every key read back as zero after `stop()` (`tests/link/net_quic_server_wipes`); aioquic and `curl --http3` against its `serve` mode |
|
|
274
|
+
| [`net/webtransport.ts`](https://github.com/amritk/nish/blob/main/std/net/webtransport.ts) | `WebTransport`, the server side of WebTransport over HTTP/3 as draft-ietf-webtrans-http3-02 has it and Chrome and `wtransport` 0.7 negotiate it, a layer over one `Http3Connection` whose `Http3Config.webtransportSessions` turns it on (extended CONNECT, SETTINGS_H3_DATAGRAM and the draft's two WebTransport settings): `next()` answers `WT_SESSION` (the program `accept`s or `refuse`s it), `WT_DATAGRAM`, `WT_STREAM`, `WT_STREAM_DATA`, `WT_STREAM_END`, `WT_STREAM_RESET`, `WT_STREAM_STOPPED`, `WT_WRITABLE`, `WT_DRAIN` and `WT_CLOSED`, and passes a plain request's `H3_*` events through; `sendDatagram` (the quarter stream ID, then the payload), `openStream`, `write`, `resetStream`, `stopSending`, `close` (CLOSE_WEBTRANSPORT_SESSION) and `drain`. Streams that arrive before their session wait, bounded; every cap is fixed at start-up and `openWebTransport` answers one out of range, or a connection with WebTransport off, as an `Err`, and a warm session allocates nothing per datagram or stream (`docs/security/webtransport.md`) | RFC 9220, RFC 9297 and draft-02: a Nish client over QUIC — sessions, datagrams at the size limits, streams both ways, close and drain from either side, every refusal — and one exchange recorded from a `wtransport` 0.7 client replayed byte for byte (`tests/link/net_webtransport`) |
|
|
272
275
|
| [`net/http-compress.ts`](https://github.com/amritk/nish/blob/main/std/net/http-compress.ts) | Content coding for HTTP responses: `httpAcceptEncoding(buf, start, end, offered)` reads an `Accept-Encoding` value (q-values, `*`, `identity`, `x-gzip`) into `HTTP_CODING_GZIP`, `HTTP_CODING_DEFLATE`, `HTTP_CODING_IDENTITY` or `HTTP_CODING_NONE`, allocating nothing; `HttpCompressor(level, minLength, maxLength)` gzips a body into its own buffer when it is worth it (-1 to send it as it is) and builds the response fields (`addFields`: `Content-Encoding: gzip` and, while `vary`, `Vary: Accept-Encoding`). It sends gzip only when it pays: `minLength`, `minSaving` bytes or `minSavingPercent`, and `segmentMode` (fewer TCP segments of `mss`, head included, than as it is); `decision` says why (`HTTP_COMPRESS_SENT`, `_NOT_ACCEPTED`, `_TOO_SMALL`, `_TOO_LARGE`, `_TOO_LITTLE_SAVED`, `_NO_FEWER_SEGMENTS`). Bodies up to `fixedLimit` use the fixed-Huffman encoder (`encoder`: `HTTP_ENCODER_AUTO`, `_FIXED`, `_LEVEL`). On HTTP/1.1, `Http1Connection.acceptEncoding()` and `respondEncoded(status, names, values, body, off, len, enc, coding)` answer a request in one call with the compressed `Content-Length`, or nothing at all (`H1_AGAIN`, `H1_INVALID`); `identity;q=0` is honoured. Opt-in; BREACH is the program's to avoid (`docs/security/compress.md`) | RFC 9110 §8.4 and §12.5.3: the negotiation table, and sans-IO responses gunzipped back (`tests/link/std_http_compress`) |
|
|
273
276
|
| [`net/router.ts`](https://github.com/amritk/nish/blob/main/std/net/router.ts) | `Router`, a method and path router that knows no carrier and allocates nothing per match: `add(method, pattern)` answers the route's index (0, 1, 2 in the order added) or a refusal — `ROUTER_BAD_PATTERN`, `ROUTER_BAD_METHOD`, `ROUTER_TOO_LONG`, `ROUTER_AMBIGUOUS` (`*` not last), `ROUTER_DUPLICATE` (the same shape and method, whatever the parameter names) or `ROUTER_FULL`, against `RouterLimits`; `match(method, mStart, mEnd, target, tStart, tEnd, params)` answers the index, `ROUTER_NOT_FOUND` or `ROUTER_METHOD_NOT_ALLOWED`, writing each `:name` and a final `*` as a `[start, end)` pair into the caller's `params` (`ROUTER_TOO_MANY_PARAMS` when it is short). Literal before parameter before `*`, segment by segment, backtracking; a lookup enters each node at most once. The query is left unparsed and nothing is decoded: `routerDecode` decodes one parameter (`ROUTER_BAD_ESCAPE`, `ROUTER_NO_ROOM`) (`docs/security/router.md`) | Every refusal code, precedence and backtracking, 405 against 404, `%2F` kept in one segment, the query, `*` and authority-form targets, a target deeper than any route, the lookup bound, params past storage, and the arena flat over matches (`tests/link/net_router`, `net_router_f64`, five `net_router_negative_*`) |
|
|
274
277
|
| [`net/handler.ts`](https://github.com/amritk/nish/blob/main/std/net/handler.ts) | `HttpHandler`, complete requests and their answers over the HTTP/1.1 carrier: it owns the readiness loop, routes each request through a `Router` at its head, gathers its body up to `HandlerLimits.http.maxBody` (1 MiB; past it the carrier answers 413), and hands it over whole. The program pulls — `wait(ms)`, `ready()`, `take()` — and switches on `req.route`; `HttpRequest` reads parameters, form-decoded query values and fields as ranges into its own buffers. Each request is answered once, now or in a later turn, by `send`, `sendFields`, `empty`, `json()` + `sendJson`, `problem` (RFC 9457), `refuse` (404, or 405 with `Allow`) or `start`/`write`/`end`; an answer whose connection closed first is `HANDLER_DROPPED` and reaches no later peer. `HEAD` takes a `GET` route. `watch`/`fired` add the program's own descriptors (`signalFd()`), and `drain` stops gracefully. Nothing is allocated per request once warm (`docs/security/handler.md`) | Routing, parameters and form-decoded queries, `HEAD`, 404 and 405 problems, chunked bodies in and out, the body cap at and one past it, pipelining order, late answers dropped across a reused slot, the arena and pool flat over two thousand requests, and the drain (`tests/link/net_handler`, and `net_http_app` over `examples/http-app`) |
|