nish 0.41.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +16 -4
  2. package/bin/nish-skills.js +233 -0
  3. package/docs/AI.md +282 -126
  4. package/llms.txt +4 -0
  5. package/package.json +14 -11
  6. package/runtime/core.d.ts +16 -0
  7. package/runtime/core.mjs +5 -0
  8. package/runtime/nish.d.ts +204 -33
  9. package/runtime/nish.h +19 -3
  10. package/runtime/nish.mjs +5 -1
  11. package/runtime/runtime-cross.c +15 -0
  12. package/runtime/runtime-net.c +876 -10
  13. package/runtime/runtime-region.c +21 -0
  14. package/runtime/runtime-sandbox.c +112 -15
  15. package/runtime/runtime-text.c +11 -0
  16. package/runtime/runtime-uring.c +533 -77
  17. package/runtime/runtime-wasm.c +3 -0
  18. package/runtime/runtime.c +474 -5
  19. package/runtime/sqlite/README.md +16 -3
  20. package/runtime/sqlite/nish-sqlite.c +940 -29
  21. package/scripts/build.sh +125 -29
  22. package/scripts/link-skills.mjs +1039 -0
  23. package/scripts/postinstall.mjs +43 -0
  24. package/skills/writing-nish/SKILL.md +144 -0
  25. package/std/README.md +3 -3
  26. package/std/crypto/base64url.ts +102 -1
  27. package/std/crypto/scram.ts +142 -0
  28. package/std/crypto/sha1.ts +99 -41
  29. package/std/host/ring.ts +1 -1
  30. package/std/host/text.ts +1 -1
  31. package/std/net/fetch.ts +9 -1
  32. package/std/net/handler.ts +79 -15
  33. package/std/net/http-server.ts +2 -3
  34. package/std/net/http1-server.ts +294 -51
  35. package/std/net/http3-server.ts +26 -15
  36. package/std/net/http3.ts +2 -2
  37. package/std/net/oidc.ts +1107 -0
  38. package/std/net/postgres-async.ts +64 -33
  39. package/std/net/postgres.ts +65 -76
  40. package/std/net/quic-conn-ack.ts +57 -7
  41. package/std/net/quic-frame.ts +104 -2
  42. package/std/net/quic-listener.ts +9 -2
  43. package/std/net/quic.ts +16 -1
  44. package/std/net/serve.ts +10 -8
  45. package/std/net/websocket.ts +188 -49
  46. package/std/sqlite.ts +325 -0
  47. package/std/text.ts +80 -11
@@ -44,6 +44,15 @@
44
44
  * correctly, not that it can still compile on a platform with no binary. A
45
45
  * postinstall that can break `npm ci` is a worse bug than the startup cost it
46
46
  * exists to remove.
47
+ *
48
+ * **Its second half points at the package's agent skills**, and links none:
49
+ * a skill can grant an agent tools, so it is linked only when the user accepts
50
+ * it, by running `npx nish-skills` (`bin/nish-skills.js`, whose rules are
51
+ * `scripts/link-skills.mjs`'s). Postinstall writes nothing under `.claude/`; it
52
+ * prints one line saying so, and only for a local install into the project
53
+ * `INIT_CWD` names -- not for `-g`, not for npx's cache, not with
54
+ * `NISH_NO_SKILLS` set. It imports the linker for `projectOf` alone, a read,
55
+ * and like the first half it only reports a failure, never raises one.
47
56
  */
48
57
  import fs from "node:fs"
49
58
  import path from "node:path"
@@ -133,9 +142,43 @@ const swap = async () => {
133
142
  return `bin/nish now execs the native compiler in ${name}`
134
143
  }
135
144
 
145
+ /** The line that points the user at `nish-skills`, when every guard passes. */
146
+ const skills = async () => {
147
+ if (fs.existsSync(path.join(root, "src", "compile.ts"))) {
148
+ return "a checkout, so there are no skills to review"
149
+ }
150
+ if (process.env.npm_config_global === "true") {
151
+ return "a global install has no project to link skills into"
152
+ }
153
+ if ((process.env.NISH_NO_SKILLS ?? "") !== "") {
154
+ return "NISH_NO_SKILLS is set, so skills are not mentioned"
155
+ }
156
+ const initCwd = process.env.INIT_CWD ?? ""
157
+ if (initCwd === "") {
158
+ return "INIT_CWD is not set, so there is no project to link skills into"
159
+ }
160
+ const linker = path.join(root, "scripts", "link-skills.mjs")
161
+ if (!fs.existsSync(linker)) {
162
+ return "scripts/link-skills.mjs is missing, so there are no skills to review"
163
+ }
164
+ const { projectOf } = await import(pathToFileURL(linker).href)
165
+ if (projectOf(initCwd, root) === null) {
166
+ return "not installed in INIT_CWD's project, so there are no skills to review"
167
+ }
168
+ return "run 'npx nish-skills' to review and link the agent skills of installed Nish packages"
169
+ }
170
+
136
171
  try {
137
172
  console.log(`nish: ${await swap()}`)
138
173
  } catch (err) {
139
174
  // Deliberately not an error: the shim is still there and still works.
140
175
  console.log(`nish: keeping the node launcher (${err instanceof Error ? err.message : String(err)})`)
141
176
  }
177
+
178
+ // Its own try, so either half failing leaves the other intact; nothing about
179
+ // skills is ever a reason to fail the install.
180
+ try {
181
+ console.log(`nish: ${await skills()}`)
182
+ } catch (err) {
183
+ console.log(`nish: skills not checked (${err instanceof Error ? err.message : String(err)})`)
184
+ }
@@ -0,0 +1,144 @@
1
+ ---
2
+ name: writing-nish
3
+ description: Write a program in Nish, the strictly static subset of TypeScript that compiles ahead of time to native code through LLVM, and get it accepted by the `nish` compiler. Use when asked to write, port, fix or explain a `.ts` program meant for `nish`, when `nish` rejects a program with an `NL` diagnostic code, or when a TypeScript habit (truthiness, `throw`, `any`, casts, `reduce`, callbacks in variables) needs its Nish replacement.
4
+ ---
5
+
6
+ # Writing Nish
7
+
8
+ Nish programs are legal TypeScript syntax, and with `runtime/nish.d.ts` on the
9
+ include path they type-check under `tsc --strict`. That is the trap: **your
10
+ TypeScript instincts produce programs that `tsc` accepts and `nish` rejects.**
11
+ The subset is much smaller than it looks.
12
+
13
+ This skill is the short form. The whole language, stated as rules for a model,
14
+ is the rules card,
15
+ [`docs/AI.md`](https://github.com/amritk/nish/blob/main/docs/AI.md); the
16
+ normative reference is
17
+ [`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md).
18
+ Where this page and those disagree, they win.
19
+
20
+ ## The loop: compile, read the code, fix
21
+
22
+ Do not reason about whether a program is legal. Ask the compiler; it is fast
23
+ and it is the only authority. Install it with `npm install -g nish`.
24
+
25
+ ```bash
26
+ nish program.ts --json # one JSON object per diagnostic, on stdout
27
+ nish --fix program.ts # apply every machine-applicable fix, in place, then report the rest
28
+ nish run program.ts a b # build into a cache, then run it with `a b`
29
+ nish program.ts --link prog # build a native binary (needs clang)
30
+ nish --help # every flag
31
+ ```
32
+
33
+ - **Key on `code`, never on `message`.** `NL2249` means the same rule next
34
+ release; the prose may change.
35
+ - A warning (`"performance"`, `"portability"`, `"deprecation"`) never changes
36
+ the exit code.
37
+ - Exit codes: `0` ok, `1` the program was rejected, `2` usage, `3` the C
38
+ toolchain is unusable, `70` a bug in `nish` worth reporting.
39
+ - `nish --fix` rewrites files with no backup: run it on a committed tree.
40
+ - A build is refused (NL2457, NL2458) where your code could panic and the
41
+ compiler cannot prove it will not: an index, a sum, a division. Add the guard
42
+ the message names. Never reach for `--allow-panics`, a `nish:unsafe` import
43
+ or a guard that proves nothing (one whose `else` returns a made-up value the
44
+ caller cannot tell from a real one) to make the error go away.
45
+ - When it compiles, check the native build against the TypeScript reading:
46
+ `nish program.ts --emit-ts out/` then `node out/entry.ts`. Both must print
47
+ the same and exit the same.
48
+
49
+ ## The shape of a program
50
+
51
+ <!-- nish:ok -->
52
+ ```ts
53
+ const gcd = (a: i32, b: i32): i32 => {
54
+ let x = a;
55
+ let y = b;
56
+ while (y > 0) {
57
+ const t = y;
58
+ y = x % y;
59
+ x = t;
60
+ }
61
+ return x;
62
+ };
63
+
64
+ export const main = (): i32 => {
65
+ console.log(`gcd = ${gcd(1071, 462)}`);
66
+ return 0;
67
+ };
68
+ ```
69
+
70
+ Top-level `const` arrows, an exported `main` returning the exit code, explicit
71
+ types everywhere, a template literal instead of `String(n)`. A module holds only
72
+ declarations at the top level: functions, `class`, `interface`, module `const`s,
73
+ `type` aliases, `enum`s (numeric or string) and `import`s.
74
+
75
+ ## Failure is a `Result`
76
+
77
+ There is no `throw`, no `try` and no unwinding. A function that can fail says
78
+ so in its return type.
79
+
80
+ <!-- nish:ok -->
81
+ ```ts
82
+ const half = (n: i32): Result<i32, string> => {
83
+ if (n % 2 !== 0) {
84
+ return Err("odd");
85
+ }
86
+ return Ok(n / 2);
87
+ };
88
+
89
+ export const main = (): i32 => {
90
+ const outcome = half(7);
91
+ if (outcome.isErr()) {
92
+ console.error(outcome.error);
93
+ return 1;
94
+ }
95
+ console.log(`${outcome.value}`);
96
+ return 0;
97
+ };
98
+ ```
99
+
100
+ `r.orReturn()` propagates an error like Rust's `?`. `panic(m)` ends the process.
101
+
102
+ ## What you must unlearn
103
+
104
+ | Your reflex | Write instead |
105
+ | --- | --- |
106
+ | `if (xs.length)`, `!s.length` (no truthiness) | `if (xs.length !== 0)`, `s.length === 0` |
107
+ | `x == y` | `x === y` |
108
+ | `throw`, `try` / `catch` | `return Err(m)`, `isErr()`, or `panic(m)` |
109
+ | `any`, `unknown`, `undefined` | name the real type; `T \| null` for absence |
110
+ | `x as T`, `x!`, `typeof`, `instanceof` | there are no casts and no runtime types |
111
+ | `xs.reduce`, `.forEach`, `.find` | a `for` loop; `map`, `filter`, `some`, `every`, `findIndex`, `slice` work |
112
+ | `s.split()`, `s.trim()`, `s.toUpperCase()` | index bytes with `charCodeAt` / `substring` |
113
+ | `String(n)`, `n.toString()` | `` `${n}` `` |
114
+ | a callback in a variable or field | there are no function values; pass an arrow straight to a function-typed parameter |
115
+ | `class B extends A`, `static`, getters | repeat the fields and `implements` an interface; module `const`s and plain methods |
116
+ | `A \| B` of anything but tagged variants | a discriminated union, a tag field first in each variant |
117
+ | top-level `let`, top-level code | a module `const`, or a local inside `main` |
118
+ | destructuring, optional parameters, spread arguments | one name per binding; `n: i32 = 1` for a default |
119
+ | `import fs from "fs"`, `export default` | `readFileSync` is a global (or `nish:fs`); a named `export const` |
120
+ | `let v = m.get(k)` on a `Map` | `m.get(k) ?? 0`, or narrow with `!== undefined` first |
121
+ | `JSON.parse`, `RegExp`, `Promise`, `new Date()` | `nish/json-typed`, `nish/regex`, `await` at the call, `Date.now()` |
122
+
123
+ The most common rejection, NL2188:
124
+
125
+ <!-- nish:err-body NL2188 -->
126
+ ```ts
127
+ const xs = [1, 2, 3];
128
+ if (xs.length) {
129
+ console.log("non-empty");
130
+ }
131
+ ```
132
+
133
+ ## Before you say it compiles
134
+
135
+ 1. Did you **run the compiler**? Nothing else counts.
136
+ 2. Is every condition a `boolean`?
137
+ 3. Is every method you call a real builtin? The list is in
138
+ [the rules card](https://github.com/amritk/nish/blob/main/docs/AI.md#the-builtins-in-full).
139
+ 4. Is every parameter, return type, field and module constant annotated, and
140
+ does every numeric width match exactly (no `i32` meeting `i64`)?
141
+ 5. Is every `Result` read, and every `.value` behind an `isOk()`?
142
+ 6. Is every nullable narrowed with `!== null` before it is touched?
143
+ 7. Does it reach only what you meant? `nish run --capabilities file.ts` lists
144
+ the files, network, processes and C calls it can reach.
package/std/README.md CHANGED
@@ -113,8 +113,8 @@ is listed in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.m
113
113
  | [`crypto/ct.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ct.ts) | `timingSafeEqual(a, b)`, which reads every byte whatever it holds, and `timingSafeEqualAt(a, aOff, b, bOff, len)` over two windows, which answers `false` for a window outside its array. Two lengths that differ answer `false` at once, because a length is public, and so does an array longer than 2^31 − 1 bytes | — |
114
114
  | [`crypto/bcrypt.ts`](https://github.com/amritk/nish/blob/main/std/crypto/bcrypt.ts) | `bcryptHash(password, salt, cost)`, the 60-character `$2b$` hash of a `Secret<u8[]>` password under a 16-byte salt and a cost of 4 to 31, and `bcryptVerify(password, hash)`, which reads `$2a$`, `$2b$` and `$2y$` hashes, refuses `$2x$`, and compares in constant time. The first 72 bytes of a password count, up to its first NUL, as under libxcrypt's `crypt_r` (where other implementations differ: [the interoperability table](../docs/security/crypto-bcrypt.md#interoperability)); the Blowfish state is wiped before either returns. `bcryptHash4(p0, p1, p2, p3, salts, cost)` and `bcryptVerify4(p0, p1, p2, p3, hashes)` do up to four at once, interleaved (four in the time of about 1.2 single hashes on one core), each lane the single path's answer; verify groups lanes by cost, and a malformed lane makes the whole call an `Err` naming it. `BCRYPT_MAX_PASSWORD`, `BCRYPT_HASH_LENGTH`, `BCRYPT_SALT_SIZE`, `BCRYPT_MIN_COST`, `BCRYPT_MAX_COST`. A `std/threads` task may call all four ([BCRYPT-9](../docs/security/crypto-bcrypt.md#findings)) | OpenBSD `bcrypt(3)`; crypt_blowfish 1.3 for `$2a$` and `$2y$` |
115
115
  | [`crypto/bcrypt-batch.ts`](https://github.com/amritk/nish/blob/main/std/crypto/bcrypt-batch.ts) | `bcryptBatcher({ width, holdNanos, cores, cost })`, a login batcher: `verify(password, hash, now)` and `hash(password, salt, now)` queue a request and answer its ticket, `waitNanos(now)` says when a run is due (a full batch, or the oldest request held `holdNanos`), and `run(now)` sends up to `width × cores` requests as `bcryptVerifyN` / `bcryptHashN` batches on one `std/threads` task per core and answers a `BcryptAnswer` (`ticket`, `ok`, `hash`, `error`) for each. It keeps and wipes its own copy of each password; a damaged stored hash answers its `Err` on its own row ([the record](../docs/security/crypto-bcrypt.md#the-login-batcher)) | — |
116
- | [`crypto/base64url.ts`](https://github.com/amritk/nish/blob/main/std/crypto/base64url.ts) | `base64urlEncode(data)` and `base64urlDecode(text)`, unpadded; `base64StdPadEncode(data)` and `base64StdPadDecode(text)`, the padded standard alphabet that SCRAM and PEM use, constant-time in both directions. These are not `nish/base64`, which encodes only, is not constant-time and is for pixels; the names differ because std modules share the program's one namespace. Decoding is strict, so every byte string has one spelling. `base64urlDecode` answers `null` for any `=`, a character outside the alphabet, a length of 1 mod 4 or nonzero unused low bits; `base64StdPadDecode` requires the padding, answering `null` unless the text is whole four-character groups with `=` only as the last one or two characters, every other character in the alphabet and the unused bits zero. Both refuse a text longer than 2^31 − 1 bytes, and `base64urlEncode` panics on such an array | RFC 4648 §4, §5, §10 (`tests/link/std_base64_padded`) |
117
- | [`crypto/sha1.ts`](https://github.com/amritk/nish/blob/main/std/crypto/sha1.ts) | `sha1(data)`, a fresh 20-byte digest, and `SHA1_SIZE` and `SHA1_BLOCK`. **Not for security**: SHA-1 is broken for collisions, and it is here only because RFC 6455 §4.2.2's `Sec-WebSocket-Accept` is defined on it (`nish/net/websocket` is its importer). One-shot only; it panics on an array longer than 2^31 − 1 bytes. It came after the #363 audit and has no record in `docs/security/` | FIPS 180-4 §6.1 |
116
+ | [`crypto/base64url.ts`](https://github.com/amritk/nish/blob/main/std/crypto/base64url.ts) | `base64urlEncode(data)` and `base64urlDecode(text)`, unpadded; `base64StdPadEncode(data)` and `base64StdPadDecode(text)`, the padded standard alphabet that SCRAM and PEM use, with the buffer forms `base64StdPadEncodeInto(data, start, length, out, at)` and `base64StdPadDecodedLength(text, start, length)` that allocate nothing, constant-time in both directions. These are not `nish/base64`, which encodes only, is not constant-time and is for pixels; the names differ because std modules share the program's one namespace. Decoding is strict, so every byte string has one spelling. `base64urlDecode` answers `null` for any `=`, a character outside the alphabet, a length of 1 mod 4 or nonzero unused low bits; `base64StdPadDecode` requires the padding, answering `null` unless the text is whole four-character groups with `=` only as the last one or two characters, every other character in the alphabet and the unused bits zero. Both refuse a text longer than 2^31 − 1 bytes, and `base64urlEncode` panics on such an array | RFC 4648 §4, §5, §10 (`tests/link/std_base64_padded`) |
117
+ | [`crypto/sha1.ts`](https://github.com/amritk/nish/blob/main/std/crypto/sha1.ts) | `sha1(data)`, a fresh 20-byte digest, `Sha1`, whose `digestInto(data, start, length, out, at)` hashes a slice into a caller's buffer and allocates nothing after it is built, and `SHA1_SIZE` and `SHA1_BLOCK`. **Not for security**: SHA-1 is broken for collisions, and it is here only because RFC 6455 §4.2.2's `Sec-WebSocket-Accept` is defined on it (`nish/net/websocket` is its importer). One-shot only, not streaming; it panics on an array longer than 2^31 − 1 bytes. It came after the #363 audit and has no record in `docs/security/` | FIPS 180-4 §6.1 |
118
118
  | [`crypto/x25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x25519.ts) | `x25519(scalar, u)`, the shared secret as a `Secret<u8[]>`, and `x25519Base(scalar)`, the public key, each from a `Secret<u8[]>` scalar, on ten 25.5-bit limbs in `i64`. Either answers `null` unless its arguments are `X25519_SIZE` (32) bytes; the scalar is clamped on a copy, which is wiped | RFC 7748 §5.2, §6.1, Wycheproof `x25519_test` |
119
119
  | [`crypto/ed25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ed25519.ts) | `ed25519PublicKey(seed)`, the 32-byte public key, `ed25519Sign(seed, msg)`, the 64-byte signature `R \|\| S`, each from a `Secret<u8[]>` seed of `ED25519_SEED_SIZE` (32) bytes or `null`, and `ed25519Verify(pub, msg, sig)`. Signing is deterministic and constant time; the seed's hash, the nonce and every intermediate the scalar reaches are wiped. Verify is cofactorless, refuses an S of L or more and a key that does not decode, and is variable time, since its inputs are public. Sign and verify panic on a message longer than 2^31 − 1 bytes. It reuses `crypto/x25519.ts`'s field arithmetic | RFC 8032 §5.1, §7.1 |
120
120
  | [`crypto/chacha20poly1305.ts`](https://github.com/amritk/nish/blob/main/std/crypto/chacha20poly1305.ts) | `chacha20Poly1305Seal(key, nonce, aad, plaintext)`, which answers the ciphertext followed by the 16-byte tag, and `chacha20Poly1305Open`, which checks the whole tag before it decrypts anything and answers `null` for a message that does not authenticate. Beneath them `chacha20Block`, `chacha20`, `chacha20QuarterRound`, `poly1305` and `poly1305KeyGen`, and `chacha20HeaderMask`, QUIC's 5-byte header-protection mask. Every input of the wrong length answers `null`. What a call derives from the key — the ChaCha20 state, the keystream, the Poly1305 key, `r` and accumulator, and on open the tag it compared — is wiped with `wipe`'s volatile stores before the call returns, the refusal path included. Natively, on x86-64 with AVX2 or on AArch64, the compiler sends the keystream of a message of 256 bytes or more to the runtime's kernel instead (`runtime/runtime-chacha20.c`), and `NISH_CHACHA20=soft` pins the Nish code | RFC 8439 §2, RFC 9001 §5.4.4, Wycheproof `chacha20_poly1305` (all 325 cases) |
@@ -257,7 +257,7 @@ reads one, and it still takes its randomness as an argument.
257
257
  | [`net/fetch.ts`](https://github.com/amritk/nish/blob/main/std/net/fetch.ts) | A blocking HTTP/1.1 client for command-line programs: `fetchSync(request, options)` looks the host up, connects, sends an `HttpRequest` (`method`, `url`, `header(name, value)`, `body`) and answers an `HttpResponse` (`status`, `reason`, `url`, `header(name)`) once its head is in, its body read through `body.read` or `body.readAll(limit)`; null on a failure. `FetchSyncClient(options)` does the same and keeps one connection alive between fetches, sending an idempotent request once more when a kept connection turns out to be gone, and says why a fetch failed in `error` (an `HTTP_E_*` code, `httpErrorName`) and `errorText`. `HttpOptions` bounds every wait (`connectTimeoutMs`, `readTimeoutMs`, `totalTimeoutMs`) and every body (`maxBodyBytes`), follows redirects only when asked (`followRedirects`, `maxRedirects`, `crossOriginRedirects`, never https to http, credentials dropped across origins), and reads `http_proxy`, `https_proxy` and `no_proxy` when `useEnvProxy` is set (`HTTP_PROXY` ignored under CGI; https through `CONNECT`). Every byte goes through `nish/net/http1-client-codec`. Native only. Record: [`docs/security/fetch.md`](../docs/security/fetch.md) | RFC 9110 §9.2.2 and §15.4, RFC 9112; a loopback server and proxy in the test itself: keep-alive, retries, redirects, proxies, timeouts and body caps (`tests/link/net_http_fetch`) |
258
258
  | [`net/outbound.ts`](https://github.com/amritk/nish/blob/main/std/net/outbound.ts) | The policy for fetching URLs your program did not choose, set as `HttpOptions.outbound`: `OutboundPolicy` reaches only public addresses (no loopback, private, link-local, CGNAT, metadata or other special-purpose range, IPv4-mapped, NAT64 and 6to4 forms judged as the IPv4 address they carry), checked on the resolved address the client then connects to, so DNS rebinding cannot move it; every redirect hop is checked again, the proxy is not used, and redirects, total time and body size are capped. `permit(cidr)` lets a trusted prefix through, `allowHost(name)` limits the names a URL or hop may carry (`HTTP_E_BLOCKED` before the lookup). Native only. Record: [`docs/security/outbound.md`](../docs/security/outbound.md) | RFC 6890, RFC 4291, RFC 6052, RFC 3056 and the IANA special-purpose address registries; every range at its edges and a loopback server fetched with and without a policy (`tests/link/net_outbound`) |
259
259
  | [`net/tls/ticket.ts`](https://github.com/amritk/nish/blob/main/std/net/tls/ticket.ts) | Session tickets a server seals for itself (RFC 8446 §4.6.1): `tlsTicketSeal` and `tlsTicketOpen` seal a `TlsTicketState` (suite, issue time, lifetime, chain start, server name, resumption PSK) under ChaCha20-Poly1305 with a borrowed `Secret<u8[]>` key, as key id ‖ nonce ‖ ciphertext ‖ tag, and wipe the plaintext on every path. `TlsTicketKeyInfo`, `tlsTicketKeyDraw` and `tlsTicketKeyDue` are a key's public record, its draw and when to replace it: a key seals for 12 h of awake time and 2^30 tickets, and opens for 14 h. `TlsTicketStrikes` is the bounded strike register (§8.1) that makes a ticket single-use, failing closed when full | `tests/link/net_tls_ticket`: every bound at its instant and 1 ns past it, a flipped bit in each region, three key rotations, replay and a full register |
260
- | [`net/websocket.ts`](https://github.com/amritk/nish/blob/main/std/net/websocket.ts) | `WsDecoder(expectMasked, maxMessage)`, the same `feed` and `next()` over WebSocket frames: `WS_MESSAGE` (fragments joined, text checked as UTF-8 fragment by fragment), `WS_PING`, `WS_PONG`, and the final `WS_CLOSE` and `WS_ERROR`, whose `closeCode` is the 1002, 1007 or 1009 to close with. `websocketFrame` encodes a frame with the mask key the caller supplies (`websocketWriteFrame` into a caller's buffer, `websocketFrameSize` its length), `reset()` readies a decoder for the next connection, `websocketClosePayload` a close frame's code and reason, and `websocketIsUtf8` checks a window. The handshake is `websocketRequestKey(parser)` over an `Http1Parser`'s head, `websocketAcceptKey`, `websocketKeyIsValid`, `websocketOfferedProtocols` and `websocketUpgradeResponse`, the 101. The client's side is `websocketClientKey(nonce)` (a 16-byte nonce the caller draws; the module draws no randomness), `websocketUpgradeRequest(host, target, key, protocols)` and `websocketCheckResponse(parser, key, offered)` over an `Http1ResponseParser` told `expectUpgrade()`, answering a `WsHandshake` (`error`, a `WS_HS_*` code, and `protocol`) | RFC 6455 §1.3's accept key, the §5.7 example frames byte for byte, §5.5's control-frame rules, §7.4's close codes |
260
+ | [`net/websocket.ts`](https://github.com/amritk/nish/blob/main/std/net/websocket.ts) | `WsDecoder(expectMasked, maxMessage)`, the same `feed` and `next()` over WebSocket frames: `WS_MESSAGE` (fragments joined, text checked as UTF-8 fragment by fragment), `WS_PING`, `WS_PONG`, and the final `WS_CLOSE` and `WS_ERROR`, whose `closeCode` is the 1002, 1007 or 1009 to close with. `websocketFrame` encodes a frame with the mask key the caller supplies (`websocketWriteFrame` into a caller's buffer, `websocketFrameSize` its length), `reset()` readies a decoder for the next connection, `websocketClosePayload` a close frame's code and reason, and `websocketIsUtf8` checks a window. The handshake is `websocketRequestKey(parser)` over an `Http1Parser`'s head, `websocketAcceptKey`, `websocketKeyIsValid`, `websocketOfferedProtocols` and `websocketUpgradeResponse`, the 101; `WsAcceptKey`, `websocketRequestKeyField` and `websocketWriteUpgradeResponse`, the same accept written into storage a server keeps, so a connection's later handshakes allocate nothing. The client's side is `websocketClientKey(nonce)` (a 16-byte nonce the caller draws; the module draws no randomness), `websocketUpgradeRequest(host, target, key, protocols)` and `websocketCheckResponse(parser, key, offered)` over an `Http1ResponseParser` told `expectUpgrade()`, answering a `WsHandshake` (`error`, a `WS_HS_*` code, and `protocol`) | RFC 6455 §1.3's accept key, the §5.7 example frames byte for byte, §5.5's control-frame rules, §7.4's close codes |
261
261
  | [`net/http1-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-server.ts) | The server side of HTTP/1.1: `Http1Connection`, sans-IO, drives an `Http1Parser` — `feed`, then `next()` answers `H1_REQUEST` (the parser's head), `H1_BODY` (at most `chunkSize` bytes, either framing), `H1_END`, `H1_WRITE` (a held-back write may go again), `H1_WS_MESSAGE`, `H1_WS_CLOSE` or the final `H1_ERROR`; the program answers with `respond(status, names, values, bodyLength)`, `write` and `end`, or `acceptWebSocket(protocol)` and then `sendFrame` and `closeWebSocket`. Keep-alive and pipelining one exchange at a time, a response with a length or chunked (unframed to an HTTP/1.0 client), `Connection` and the framing decided by the server, every parser refusal answered with its status and a close, pings and closes answered on a WebSocket. Two slot pools for a program that owns its loop: `Http1Server` on plain TCP and `Http1TlsServer` on `nish/net/tls-tcp` with ALPN `http/1.1` or none (`accept`, `readable` / `writable`, `next(slot)`, `flush(slot)`, `close`, `expire(now)` for the idle timeout and the deadline for a whole head, `headTimeout`, against a client that trickles its head). Both build a slot's connection on the first accept into it rather than at start-up. `Http1Server` reads a socket until a short read rather than until it would block, takes a free slot off a stack of released slots or the next never-used one rather than scanning for one, and answers `rearm(slot, wants)`, whether the interest changed and needs a `pollModify` at all: a keep-alive request is one `recv` and one `send`. The slots borrow their output from one `Http1OutputPool` while they write and give it back once sent, so a pool's memory follows the connections the socket is holding back, not its size: an idle slot holds no output buffer. Every final response carries a `Date` from `HttpDate`, which reads `Date.now()` and formats at most once a second, shared by a pool's slots; `pin(unixMs)` fixes it for a test, and a program's own `date` field replaces it. Every cap is an `Http1Config` number fixed at start-up, and a warmed slot allocates nothing per request (`docs/security/http1-codec.md`). Native only, as `nish:net` is | RFC 9112 §6, §7, §9; RFC 9110 §9.3.2, §15; RFC 6455 §4.2, §5.5. Nish clients over loopback against both carriers, requests cut at every byte, 2 MiB bodies each way, pipelining, a WebSocket echo, the arena flat over two hundred requests, the date formatted once a second, and every refusal (`tests/link/net_http1_server`); `curl` against its `serve` mode |
262
262
  | [`net/url.ts`](https://github.com/amritk/nish/blob/main/std/net/url.ts) | The request target's path and query, read in place: `urlQueryStart` finds the `?`, `UrlPathSegments` splits a path on the raw `/` and `UrlQuery` yields a query's pairs as offsets, both reusable by `reset`; `percentDecode` and `percentDecodePathSegment` decode a window into the caller's array and answer the length or a `URL_DECODE_ERR_*` code, `percentDecodeErrorAt` answers the offset an error is at, and `urlQueryFind` finds a key. Decoding is strict by default (a malformed escape and `%00` are refused); `URL_DECODE_FORM`, `URL_DECODE_LENIENT` and `URL_DECODE_ALLOW_NUL` together decode valid UTF-8 as `URLSearchParams` does. A query yields at most `UrlQueryLimits.maxPairs` pairs (100 by default) and then answers `URL_QUERY_ERR_PAIRS`. The byte API allocates nothing; `urlDecode` and `urlQueryGet` answer strings and refuse what is not UTF-8. Whole URLs: `urlParse` splits an absolute URL into a `Url` (`scheme`, `hasAuthority`, `username`, `password`, `host`, `port`, `path`, `query`, `fragment`, each still percent-encoded, the scheme and host lower-cased), `urlResolve(base, ref)` resolves a reference against one, `urlSerialize` writes one back, and `urlDefaultPort` and `urlOrigin` answer the port and the origin a client connects to. Both refuse with null what two readers could take for different hosts: a byte outside printable ASCII, a backslash, a malformed `%`, a second `@`, a non-unreserved host byte, a numeric host that is not strict dotted-decimal IPv4, an IPv6 zone, a port past 65535. Records: [`docs/security/url.md`](../docs/security/url.md) | RFC 3986 §2.1 and §3.3, the WHATWG URL Standard's percent-decode and `application/x-www-form-urlencoded` parser; `decodeURIComponent` and `URLSearchParams` on 3,000 seeded inputs; RFC 3986 §3 and §5.2, every §5.4 example, 57 refusals and 4,000 seeded round trips in both number modes (`tests/link/net_url_parse`) |
263
263
  | [`net/http-fields.ts`](https://github.com/amritk/nish/blob/main/std/net/http-fields.ts) | The header model HTTP/2 and HTTP/3 share, version-neutral: `HttpFields` reads a decoded section with `readRequest(names, values, extendedConnect)`, `readResponse` or `readTrailers` into `method`, `scheme`, `authority`, `path`, `protocol`, `status`, the regular fields in order (`get(name)`) and `contentLength`, answering `HTTP_FIELDS_OK` or the first refusal: a name that is empty, not a token or not lowercase; a value with NUL, CR or LF or whitespace at an end; a connection-specific field (`te` but `trailers` included); a pseudo-header unknown, repeated, after a regular field, forbidden by the shape or missing; a pseudo-header value of the wrong syntax; a `host` that disagrees with `:authority`; a bad or disagreeing `content-length`. `:protocol` (RFC 8441) is read only where the caller enabled extended CONNECT. `httpFieldNameValid`, `httpFieldValueValid`, `httpFieldConnectionSpecific` and `httpFieldsCheckOutgoing` check one name, one value or a section a program sends. `httpDateWrite(out, at, seconds)` writes a second since 1970 as the IMF-fixdate a `Date` field holds (`HTTP_DATE_SIZE` bytes, to 9999), reading no clock, so it compiles for wasm32 | RFC 9110 §5, RFC 9113 §8.2–§8.5, RFC 9114 §4.2–§4.3, RFC 8441 §4; every refusal in `tests/link/net_http_fields`; RFC 9110 §5.6.7, every day from 1970 to 2399 (`tests/link/net_http_date`) |
@@ -13,7 +13,10 @@
13
13
  *
14
14
  * The module also holds RFC 4648 §4 standard base64 — `+` and `/`, padded with
15
15
  * `=` — as `base64StdPadEncode` and `base64StdPadDecode`, for PEM
16
- * (`nish/crypto/x509`) and SCRAM (`nish/net/postgres`). It is as strict and as
16
+ * (`nish/crypto/x509`) and SCRAM (`nish/net/postgres`), and as
17
+ * `base64StdPadEncodeInto` and `base64StdPadDecodedLength`, which read and
18
+ * write a caller's buffer and allocate nothing, for the WebSocket handshake
19
+ * (`nish/net/websocket`). It is as strict and as
17
20
  * constant-time as the URL alphabet, by the same masks, and it refuses a `=`
18
21
  * anywhere but the last one or two characters of a text whose length is a
19
22
  * multiple of four. They are not `nish/base64`'s `base64Encode`, which encodes
@@ -283,6 +286,104 @@ export const base64StdPadEncode = (data: u8[]): string => {
283
286
  return parts.join("")
284
287
  }
285
288
 
289
+ /**
290
+ * `base64StdPadEncode` of `data[start .. start + length)`, written into `out`
291
+ * from `at` as the bytes of its characters, allocating nothing: the WebSocket
292
+ * accept key that a server writes for every handshake (RFC 6455 §4.2.2). A
293
+ * range outside `data`, or text that does not fit in `out` from `at`, panics.
294
+ *
295
+ * @param data The buffer holding the bytes to encode; it is read, not changed.
296
+ * @param start Where in `data` the bytes start.
297
+ * @param length How many bytes to encode.
298
+ * @param out The buffer the text is written into.
299
+ * @param at Where in `out` the text starts.
300
+ * @returns The index in `out` just past the text, `at + 4 × ceil(length / 3)`.
301
+ */
302
+ export const base64StdPadEncodeInto = (data: u8[], start: i32, length: i32, out: u8[], at: i32): i32 => {
303
+ if (data.length > 2147483647 || out.length > 2147483647) {
304
+ panic("base64StdPadEncodeInto: a buffer longer than 2^31 - 1 bytes")
305
+ }
306
+ if (start < 0 || length < 0 || start > toI32(data.length) - length || length > 1610612733) {
307
+ panic("base64StdPadEncodeInto: bytes outside their buffer")
308
+ }
309
+ const end: i32 = at + ((length + 2) / 3) * 4
310
+ if (at < 0 || at > toI32(out.length) || end > toI32(out.length)) {
311
+ panic("base64StdPadEncodeInto: text that does not fit its buffer")
312
+ }
313
+ let j: i32 = at
314
+ let acc: i32 = 0
315
+ let bits: u32 = 0
316
+ for (let k: i32 = start; k < start + length; k++) {
317
+ if (k >= 0 && k < toI32(data.length)) {
318
+ acc = ((acc << 8) | toI32(data[k])) & 0xfff
319
+ }
320
+ bits += 8
321
+ while (bits >= 6) {
322
+ bits -= 6
323
+ if (j >= 0 && j < toI32(out.length)) {
324
+ out[j] = toU8(base64StdPadCharOf((acc >> toI32(bits)) & 63))
325
+ }
326
+ j++
327
+ }
328
+ }
329
+ if (bits > 0) {
330
+ out[j] = toU8(base64StdPadCharOf((acc << toI32(6 - bits)) & 63))
331
+ j++
332
+ }
333
+ while (j < end) {
334
+ out[j] = 61
335
+ j++
336
+ }
337
+ return end
338
+ }
339
+
340
+ /**
341
+ * How many bytes the padded standard base64 in `text[start .. start + length)`
342
+ * decodes to, or -1 unless it is their one canonical spelling, by
343
+ * `base64StdPadDecode`'s rules and its masks; nothing is decoded or allocated.
344
+ * A WebSocket server checks a handshake's `Sec-WebSocket-Key` this way, where
345
+ * it lies in the request (RFC 6455 §4.2.1, item 5). A range outside `text`
346
+ * panics.
347
+ *
348
+ * @param text The buffer holding the text, one character a byte.
349
+ * @param start Where in `text` the base64 starts.
350
+ * @param length How many characters it is.
351
+ * @returns The decoded length, or -1 when the text is not canonical.
352
+ */
353
+ export const base64StdPadDecodedLength = (text: u8[], start: i32, length: i32): i32 => {
354
+ if (text.length > 2147483647) {
355
+ panic("base64StdPadDecodedLength: a buffer longer than 2^31 - 1 bytes")
356
+ }
357
+ if (start < 0 || length < 0 || start > toI32(text.length) - length) {
358
+ panic("base64StdPadDecodedLength: text outside its buffer")
359
+ }
360
+ if ((length & 3) !== 0) {
361
+ return -1
362
+ }
363
+ let pad: i32 = 0
364
+ if (length > 0 && toI32(text[start + length - 1]) === 61) {
365
+ pad = toI32(text[start + length - 2]) === 61 ? 2 : 1
366
+ }
367
+ const chars: i32 = length - pad
368
+ let bad: i32 = 0
369
+ let acc: i32 = 0
370
+ let bits: i32 = 0
371
+ for (let k: i32 = 0; k < chars; k++) {
372
+ const v: i32 = base64StdPadSextetOf(toI32(text[start + k]))
373
+ bad = bad | (v >> 31)
374
+ acc = ((acc << 6) | (v & 63)) & 0xfff
375
+ bits += 6
376
+ if (bits >= 8) {
377
+ bits -= 8
378
+ }
379
+ }
380
+ bad = bad | (acc & ((1 << bits) - 1))
381
+ if (bad !== 0) {
382
+ return -1
383
+ }
384
+ return (length >> 2) * 3 - pad
385
+ }
386
+
286
387
  /**
287
388
  * The bytes of padded standard base64 `text`, or `null` unless it is the one
288
389
  * canonical spelling of them: a whole number of four-character groups, `=`
@@ -0,0 +1,142 @@
1
+ /**
2
+ * `nish/crypto/scram` — the arithmetic of a SCRAM-SHA-256 client, as RFC 5802
3
+ * §3 defines it with SHA-256 for `H` and `HMAC` (RFC 7677 §3):
4
+ *
5
+ * SaltedPassword := Hi(Normalize(password), salt, i)
6
+ * ClientKey := HMAC(SaltedPassword, "Client Key")
7
+ * StoredKey := H(ClientKey)
8
+ * ClientSignature := HMAC(StoredKey, AuthMessage)
9
+ * ClientProof := ClientKey XOR ClientSignature
10
+ * ServerKey := HMAC(SaltedPassword, "Server Key")
11
+ * ServerSignature := HMAC(ServerKey, AuthMessage)
12
+ *
13
+ * import { scramSha256ClientProof, scramSha256SaltedPassword, scramSha256ServerSignature } from "nish/crypto/scram";
14
+ *
15
+ * const salted: Secret<u8[]> | null = scramSha256SaltedPassword(password, salt, 4096);
16
+ * if (salted !== null) {
17
+ * const proof: u8[] = scramSha256ClientProof(salted, authMessage);
18
+ * const expected: u8[] = scramSha256ServerSignature(salted, authMessage);
19
+ * wipe(salted);
20
+ * }
21
+ *
22
+ * The module holds none of SCRAM's messages: the caller builds AuthMessage,
23
+ * decodes the server's salt and encodes the proof, so that a driver keeps its
24
+ * own wire format and this file stays a pure function of its inputs, which a
25
+ * contract (`specs/scram-sha256.md`) can hold to the RFC's printed exchange.
26
+ * `Normalize` (SASLprep) is the caller's too: the password arrives as the
27
+ * bytes the caller decided to send.
28
+ *
29
+ * SaltedPassword, ClientKey and ServerKey each let whoever holds them log in
30
+ * as the user, so SaltedPassword is taken and given as a `Secret`, and
31
+ * ClientKey, StoredKey, ClientSignature and ServerKey are wiped before each
32
+ * function returns. ClientProof and ServerSignature cross the wire in the
33
+ * clear and are plain bytes. A caller compares the server's signature with
34
+ * `timingSafeEqual` (`nish/crypto/ct`), and caps the iteration count before
35
+ * it calls: `i=` is the server's to choose and Hi runs that many HMACs.
36
+ */
37
+
38
+ import { hmacSha256, pbkdf2HmacSha256 } from "nish/crypto/hmac"
39
+ import { Sha256 } from "nish/crypto/sha256"
40
+ import { Secret, exposeWith, wipe } from "nish:secret"
41
+
42
+ /** The bytes of an ASCII literal, for the two HMAC labels. */
43
+ const scramAscii = (text: string): u8[] => {
44
+ const n: i32 = toI32(text.length)
45
+ const out: u8[] = []
46
+ for (let i: i32 = 0; i < n; i++) {
47
+ out.push(toU8(text.charCodeAt(i)))
48
+ }
49
+ return out
50
+ }
51
+
52
+ /**
53
+ * SHA-256 of `data` through a hasher of its own, whose state, block and
54
+ * schedule are wiped before it returns: the one-shot `sha256` leaves the last
55
+ * block of its input in a hasher nothing wipes, and here the input is
56
+ * ClientKey.
57
+ */
58
+ const scramSha256Wiped = (data: u8[]): u8[] => {
59
+ const h = new Sha256()
60
+ h.update(data, toI32(0), toI32(data.length))
61
+ const digest: u8[] = h.digest()
62
+ wipe(h.state)
63
+ wipe(h.block)
64
+ wipe(h.schedule)
65
+ h.fill = 0
66
+ h.total = 0
67
+ h.finished = true
68
+ return digest
69
+ }
70
+
71
+ /** ClientKey XOR HMAC(H(ClientKey), AuthMessage), with every key on the way wiped. */
72
+ const scramClientProofExposed = (salted: u8[], authMessage: u8[]): u8[] => {
73
+ const clientKey: u8[] = hmacSha256(salted, scramAscii("Client Key"))
74
+ const storedKey: u8[] = scramSha256Wiped(clientKey)
75
+ const clientSignature: u8[] = hmacSha256(storedKey, authMessage)
76
+ if (clientKey.length < 32 || clientSignature.length < 32) {
77
+ panic("nish/crypto/scram: an HMAC-SHA-256 shorter than 32 bytes")
78
+ }
79
+ const proof: u8[] = new Array<u8>(32)
80
+ for (let i: i32 = 0; i < 32; i++) {
81
+ proof[i] = clientKey[i] ^ clientSignature[i]
82
+ }
83
+ wipe(clientKey)
84
+ wipe(storedKey)
85
+ wipe(clientSignature)
86
+ return proof
87
+ }
88
+
89
+ /** HMAC(HMAC(SaltedPassword, "Server Key"), AuthMessage), with ServerKey wiped. */
90
+ const scramServerSignatureExposed = (salted: u8[], authMessage: u8[]): u8[] => {
91
+ const serverKey: u8[] = hmacSha256(salted, scramAscii("Server Key"))
92
+ const signature: u8[] = hmacSha256(serverKey, authMessage)
93
+ wipe(serverKey)
94
+ return signature
95
+ }
96
+
97
+ /**
98
+ * SaltedPassword, RFC 5802 §3's `Hi(password, salt, i)`: PBKDF2 with
99
+ * HMAC-SHA-256 and a 32-byte output (§2.2).
100
+ *
101
+ * The time is linear in `iterations` and nothing here bounds it, so a caller
102
+ * taking the count from a server caps it first.
103
+ *
104
+ * @param password The password, already normalized as the caller sends it;
105
+ * read only inside `exposeWith`, and still the caller's to wipe.
106
+ * @param salt The salt the server sent, decoded from base64.
107
+ * @param iterations The server's iteration count `i`; below 1 answers `null`.
108
+ * @returns SaltedPassword, which the caller wipes, or `null` when it cannot be
109
+ * computed.
110
+ */
111
+ export const scramSha256SaltedPassword = (
112
+ password: Secret<u8[]>,
113
+ salt: u8[],
114
+ iterations: i32
115
+ ): Secret<u8[]> | null => pbkdf2HmacSha256(password, salt, iterations, 32)
116
+
117
+ /**
118
+ * ClientProof, the `p=` of the client-final message (RFC 5802 §3). ClientKey,
119
+ * StoredKey and ClientSignature are wiped before it returns.
120
+ *
121
+ * @param saltedPassword SaltedPassword from `scramSha256SaltedPassword`, read
122
+ * only inside `exposeWith`; still the caller's to wipe.
123
+ * @param authMessage The client-first message without its GS2 header, the
124
+ * server-first message and the client-final message without its proof,
125
+ * joined by commas.
126
+ * @returns The 32-byte proof, which is sent in the clear.
127
+ */
128
+ export const scramSha256ClientProof = (saltedPassword: Secret<u8[]>, authMessage: u8[]): u8[] =>
129
+ exposeWith(saltedPassword, authMessage, scramClientProofExposed)
130
+
131
+ /**
132
+ * ServerSignature, what the server's `v=` must equal (RFC 5802 §3). ServerKey
133
+ * is wiped before it returns. Compare it to the server's with
134
+ * `timingSafeEqual`.
135
+ *
136
+ * @param saltedPassword SaltedPassword from `scramSha256SaltedPassword`, read
137
+ * only inside `exposeWith`; still the caller's to wipe.
138
+ * @param authMessage The same AuthMessage the proof was computed over.
139
+ * @returns The 32-byte signature the server should send.
140
+ */
141
+ export const scramSha256ServerSignature = (saltedPassword: Secret<u8[]>, authMessage: u8[]): u8[] =>
142
+ exposeWith(saltedPassword, authMessage, scramServerSignatureExposed)