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
@@ -15,7 +15,9 @@
15
15
  * const digest: u8[] = sha1(message); // 20 bytes
16
16
  *
17
17
  * One shot only, because a handshake key is a few dozen bytes: there is no
18
- * streaming hasher to keep in step with `Sha256`'s.
18
+ * streaming hasher to keep in step with `Sha256`'s. A caller that hashes again
19
+ * and again keeps a `Sha1` and calls `digestInto`, which writes into its
20
+ * buffer and allocates nothing.
19
21
  *
20
22
  * Every word is a `u32`, whose arithmetic wraps, so the additions modulo 2^32
21
23
  * are plain `+`. The only branches are on lengths, loop counters and the round
@@ -39,8 +41,8 @@ const sha1LoadWord = (buf: u8[], at: i32): u32 =>
39
41
 
40
42
  /**
41
43
  * Folds the 64-byte block at `src[at .. at + 64)` into `h`: FIPS 180-4
42
- * §6.1.2, steps 1 to 4. `w` is the 80-word schedule, allocated once per call
43
- * to `sha1` rather than once per block.
44
+ * §6.1.2, steps 1 to 4. `w` is the 80-word schedule, held by the `Sha1`
45
+ * hasher rather than allocated once per block.
44
46
  */
45
47
  const sha1Compress = (h: u32[], w: u32[], src: u8[], at: i32): void => {
46
48
  // Written as the condition the body runs under, the shape that proves the
@@ -95,7 +97,98 @@ const sha1Compress = (h: u32[], w: u32[], src: u8[], at: i32): void => {
95
97
  }
96
98
 
97
99
  /**
98
- * The SHA-1 digest of all of `data`, as a fresh 20-byte array.
100
+ * A SHA-1 hasher that keeps its working state, so that a caller hashing again
101
+ * and again (a server answering WebSocket handshakes) allocates once, when it
102
+ * builds one, and never after: `digestInto` writes into the caller's buffer.
103
+ * It holds no secret, so nothing in it is wiped.
104
+ *
105
+ * const hasher = new Sha1();
106
+ * hasher.digestInto(message, 0, message.length, digest, 0); // digest[0 .. 20)
107
+ */
108
+ export class Sha1 {
109
+ /** The chaining value H of FIPS 180-4 §6.1.2, five words. */
110
+ h: u32[]
111
+ /** The 80-word message schedule, reused for every block. */
112
+ w: u32[]
113
+ /** The last one or two blocks: the message's tail and its padding (§5.1.1). */
114
+ last: u8[]
115
+
116
+ /** A hasher with its buffers allocated, ready for `digestInto`. */
117
+ constructor() {
118
+ this.h = new Array<u32>(5)
119
+ this.w = new Array<u32>(80)
120
+ this.last = new Array<u8>(2 * SHA1_BLOCK)
121
+ }
122
+
123
+ /**
124
+ * Writes the SHA-1 digest of `data[start .. start + length)` into
125
+ * `out[at .. at + 20)`, allocating nothing. A range outside `data` or `out`
126
+ * panics, as does a message longer than 2^31 - 1 bytes.
127
+ *
128
+ * @param data The buffer holding the message; it is read, not changed.
129
+ * @param start Where in `data` the message starts.
130
+ * @param length How many bytes of `data` the message is.
131
+ * @param out The buffer the 20-byte digest is written into.
132
+ * @param at Where in `out` the digest starts.
133
+ */
134
+ digestInto(data: u8[], start: i32, length: i32, out: u8[], at: i32): void {
135
+ if (data.length > 2147483647 || out.length > 2147483647) {
136
+ panic("sha1: a buffer longer than 2^31 - 1 bytes")
137
+ }
138
+ if (start < 0 || length < 0 || start > toI32(data.length) - length) {
139
+ panic("sha1: a message outside its buffer")
140
+ }
141
+ if (at < 0 || at > toI32(out.length) - SHA1_SIZE) {
142
+ panic("sha1: a digest outside its buffer")
143
+ }
144
+ const h: u32[] = this.h
145
+ const w: u32[] = this.w
146
+ const last: u8[] = this.last
147
+ if (toI32(h.length) < 5) {
148
+ panic("sha1: a hasher without its state")
149
+ }
150
+ // H^(0) of FIPS 180-4 §5.3.1.
151
+ h[0] = 0x67452301
152
+ h[1] = 0xefcdab89
153
+ h[2] = 0x98badcfe
154
+ h[3] = 0x10325476
155
+ h[4] = 0xc3d2e1f0
156
+ // Whole blocks straight from `data`, then the tail and its padding (§5.1.1)
157
+ // in one or two blocks of `last`.
158
+ const whole: i32 = length - (length % SHA1_BLOCK)
159
+ for (let off: i32 = 0; off < whole; off += SHA1_BLOCK) {
160
+ sha1Compress(h, w, data, start + off)
161
+ }
162
+ const tail: i32 = length - whole
163
+ const lastLength: i32 = tail < SHA1_BLOCK - 8 ? SHA1_BLOCK : 2 * SHA1_BLOCK
164
+ const room: i32 = toI32(last.length)
165
+ if (lastLength > room) {
166
+ panic("sha1: a hasher without its state")
167
+ }
168
+ for (let k: i32 = 0; k < lastLength && k < room; k += 1) {
169
+ last[k] = k < tail ? data[start + whole + k] : 0
170
+ }
171
+ last[tail] = 0x80
172
+ const bits: u64 = toU64(toI64(length)) << 3
173
+ for (let i: i32 = 0; i < 8; i += 1) {
174
+ last[lastLength - 1 - i] = toU8(bits >>> toU64(8 * i))
175
+ }
176
+ for (let off: i32 = 0; off < lastLength; off += SHA1_BLOCK) {
177
+ sha1Compress(h, w, last, off)
178
+ }
179
+ for (let i: i32 = 0; i < 5; i += 1) {
180
+ const word: u32 = h[i]
181
+ out[at + 4 * i] = toU8(word >>> 24)
182
+ out[at + 4 * i + 1] = toU8(word >>> 16)
183
+ out[at + 4 * i + 2] = toU8(word >>> 8)
184
+ out[at + 4 * i + 3] = toU8(word)
185
+ }
186
+ }
187
+ }
188
+
189
+ /**
190
+ * The SHA-1 digest of all of `data`, as a fresh 20-byte array: `Sha1`'s
191
+ * `digestInto` over the whole of it, with a hasher of its own.
99
192
  *
100
193
  * An array longer than 2^31 - 1 bytes panics, for the reason `sha256` gives:
101
194
  * under `--number-mode f64`, `toI32` of a longer length saturates, and the
@@ -108,43 +201,8 @@ export const sha1 = (data: u8[]): u8[] => {
108
201
  if (data.length > 2147483647) {
109
202
  panic("sha1: a message longer than 2^31 - 1 bytes")
110
203
  }
111
- const n: i32 = toI32(data.length)
112
- // H^(0) of FIPS 180-4 §5.3.1.
113
- const h: u32[] = new Array<u32>(5)
114
- h[0] = 0x67452301
115
- h[1] = 0xefcdab89
116
- h[2] = 0x98badcfe
117
- h[3] = 0x10325476
118
- h[4] = 0xc3d2e1f0
119
- const w: u32[] = new Array<u32>(80)
120
- // Whole blocks straight from `data`, then the tail and its padding (§5.1.1)
121
- // in one or two blocks of their own.
122
- const whole: i32 = n - (n % SHA1_BLOCK)
123
- for (let at: i32 = 0; at < whole; at += SHA1_BLOCK) {
124
- sha1Compress(h, w, data, at)
125
- }
126
- const tail: i32 = n - whole
127
- const tailBlocks: i32 = tail < SHA1_BLOCK - 8 ? 1 : 2
128
- const last: u8[] = new Array<u8>(tailBlocks * SHA1_BLOCK)
129
- const lastLength: i32 = toI32(last.length)
130
- for (let k: i32 = 0; k < tail && k < lastLength; k += 1) {
131
- last[k] = data[whole + k]
132
- }
133
- last[tail] = 0x80
134
- const bits: u64 = toU64(toI64(n)) << 3
135
- for (let i: i32 = 0; i < 8; i += 1) {
136
- last[lastLength - 1 - i] = toU8(bits >>> toU64(8 * i))
137
- }
138
- for (let at: i32 = 0; at < lastLength; at += SHA1_BLOCK) {
139
- sha1Compress(h, w, last, at)
140
- }
141
204
  const out: u8[] = new Array<u8>(SHA1_SIZE)
142
- for (let i: i32 = 0; i < 5; i += 1) {
143
- const word: u32 = h[i]
144
- out[4 * i] = toU8(word >>> 24)
145
- out[4 * i + 1] = toU8(word >>> 16)
146
- out[4 * i + 2] = toU8(word >>> 8)
147
- out[4 * i + 3] = toU8(word)
148
- }
205
+ const zero: i32 = 0
206
+ new Sha1().digestInto(data, zero, toI32(data.length), out, zero)
149
207
  return out
150
208
  }
package/std/host/ring.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * const INPUT = new Int32Array(2 + 64); // head, tail, then 64 slots
12
12
  *
13
- * export function tick(): void {
13
+ * export const tick = (): void => {
14
14
  * while (ringSize(INPUT) > 0) {
15
15
  * steer(ringShift(INPUT));
16
16
  * }
package/std/host/text.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * export const OUTBOX = new Array<u8>(256);
14
14
  *
15
15
  * // The page: n = new TextEncoder().encodeInto(text, views.INBOX).written
16
- * export function echo(n: i32): i32 {
16
+ * export const echo = (n: i32): i32 => {
17
17
  * const text = textRead(INBOX, n);
18
18
  * if (text === null) return -1;
19
19
  * return textWriteInt(OUTBOX, textWrite(OUTBOX, 0, text), toI64(n));
package/std/net/fetch.ts CHANGED
@@ -492,6 +492,8 @@ export class FetchSyncClient {
492
492
  private rbuf: u8[]
493
493
  /** Where TLS application data is read before the parser takes it; empty until the first https connection. */
494
494
  private plain: u8[]
495
+ /** Where a redirect's body is read and thrown away; empty until the first redirect that has one. */
496
+ private sink: u8[]
495
497
  /** The fetch's end in monotonic nanoseconds; `HTTP_CLIENT_NEVER` for none. */
496
498
  private deadline: i64 = 0
497
499
  /** The last failure's `HTTP_E_*` code; `HTTP_E_NONE` after a fetch that answered. */
@@ -530,6 +532,7 @@ export class FetchSyncClient {
530
532
  this.ready = new Array<i32>(8)
531
533
  this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
532
534
  this.plain = []
535
+ this.sink = []
533
536
  const proxies: string[] = httpClientEnvProxies(options)
534
537
  this.httpProxy = proxies[0]
535
538
  this.httpsProxy = proxies[1]
@@ -1192,9 +1195,14 @@ export class FetchSyncClient {
1192
1195
  /**
1193
1196
  * Reads past a redirect's body so the connection can carry the next
1194
1197
  * request; a body too long to be worth reading, or any failure, closes it.
1198
+ * The sink is the client's, kept for the next hop: one built per call would
1199
+ * stay in the caller's memory for every redirect the fetch follows.
1195
1200
  */
1196
1201
  private drain(): void {
1197
- const sink: u8[] = new Array<u8>(HTTP_CLIENT_DRAIN_CHUNK)
1202
+ if (toI32(this.sink.length) === 0) {
1203
+ this.sink = new Array<u8>(HTTP_CLIENT_DRAIN_CHUNK)
1204
+ }
1205
+ const sink: u8[] = this.sink
1198
1206
  let left: i32 = HTTP_CLIENT_DRAIN_BYTES
1199
1207
  while (this.bodyOpen && left > 0) {
1200
1208
  const n: i32 = this.readBody(this.generation, sink, HTTP_CLIENT_ZERO, HTTP_CLIENT_DRAIN_CHUNK)
@@ -105,7 +105,15 @@ import {
105
105
  routerDecode,
106
106
  } from "nish/net/router"
107
107
  import { URL_DECODE_ALLOW_NUL, URL_DECODE_ERR_SPACE, URL_DECODE_FORM, percentDecode } from "nish/net/url"
108
- import { pollAdd, pollCreate, pollModify, pollRemove, pollWait } from "nish:net"
108
+ import {
109
+ NET_LISTEN_RING,
110
+ pollAdd,
111
+ pollCreate,
112
+ pollModify,
113
+ pollRemove,
114
+ pollWait,
115
+ tcpListenFlags,
116
+ } from "nish:net"
109
117
 
110
118
  /** An answer sent, or queued to be sent. */
111
119
  export const HANDLER_SENT: i32 = 0
@@ -142,7 +150,10 @@ const HANDLER_ONE_MIB: i32 = 1048576
142
150
  /** `tcpAccept`: none is waiting (EAGAIN), or the one that was left before it was taken (ECONNABORTED). */
143
151
  const HANDLER_ACCEPT_NONE: i32 = -11
144
152
  const HANDLER_ACCEPT_ABORTED: i32 = -103
145
- /** How long the listener rests after an accept fails for want of descriptors or memory: 100 ms. */
153
+ /**
154
+ * How long, at most, the listener rests after an accept fails for want of
155
+ * descriptors, ring slots or memory: 100 ms, or until a connection closes.
156
+ */
146
157
  const HANDLER_ACCEPT_REST: i64 = 100000000
147
158
  /** How often, at most, `wait` looks for a body past `bodyTimeout`: a second, in nanoseconds. */
148
159
  const HANDLER_BODY_SWEEP: i64 = 1000000000
@@ -160,8 +171,21 @@ const HANDLER_TOOK_THREE: i32 = 768
160
171
  export class HandlerLimits {
161
172
  /** The carrier's caps and timeouts; `http.maxBody` is the body cap, past which a request is answered 413. */
162
173
  http: Http1Config
163
- /** The most connections at once. */
174
+ /**
175
+ * The most connections at once. It is the handler's own cap, not
176
+ * `RLIMIT_NOFILE`: with `ring` set the connections live in io_uring slots
177
+ * and may outnumber the descriptor limit. Past it a connection is accepted
178
+ * and closed at once.
179
+ */
164
180
  slots: i32 = 256
181
+ /**
182
+ * Whether `listen` opens its listener with `NET_LISTEN_RING`, so each
183
+ * connection is accepted into an io_uring slot rather than a descriptor.
184
+ * Off by default. Where the kernel refuses rings, the listener serves
185
+ * descriptors and `netRingState` says why. A connection is then a slot
186
+ * handle, which `sendFd` and a C library through `nish:ffi` cannot take.
187
+ */
188
+ ring: boolean = false
165
189
  /**
166
190
  * Bytes in the JSON scratch buffer: the largest body `json` and `problem`
167
191
  * can write. A value past it makes `sendJson` answer 500. At least 256.
@@ -188,6 +212,19 @@ export class HandlerLimits {
188
212
  this.http = new Http1Config()
189
213
  this.http.maxBody = HANDLER_ONE_MIB
190
214
  }
215
+
216
+ /**
217
+ * Opens a TCP listener for an `HttpHandler` with these limits:
218
+ * `tcpListenFlags` with `flags`, plus `NET_LISTEN_RING` when `ring` is set.
219
+ * @param host the address to bind, such as "0.0.0.0"
220
+ * @param port the port to bind, or 0 for one the kernel picks
221
+ * @param backlog the kernel's queue of connections not yet accepted
222
+ * @param flags `tcpListenFlags`' other bits: 1 for `SO_REUSEPORT`, 2 for `TCP_NODELAY`
223
+ * @returns the listener, or a negative errno
224
+ */
225
+ listen(host: string, port: i32, backlog: i32, flags: i32): i32 {
226
+ return tcpListenFlags(host, port, backlog, this.ring ? flags | NET_LISTEN_RING : flags)
227
+ }
191
228
  }
192
229
 
193
230
  /**
@@ -523,9 +560,10 @@ export class HttpHandler {
523
560
  private problemType: u8[]
524
561
  private noFields: u8[][]
525
562
  /**
526
- * When an accept failed for want of a resource (EMFILE, ENFILE, ENOMEM):
527
- * the listener is out of the loop until then, which it would otherwise wake
528
- * every turn while its connection waits. 0 while it is in the loop.
563
+ * When an accept failed for want of a resource (EMFILE for descriptors,
564
+ * ENFILE for ring slots, ENOMEM): the listener is out of the loop until
565
+ * then, or until a connection closes (`forget`), which it would otherwise
566
+ * wake every turn while its connection waits. 0 while it is in the loop.
529
567
  */
530
568
  private acceptRestUntil: i64 = 0
531
569
  /** `bodyTimeout` in nanoseconds. */
@@ -559,7 +597,9 @@ export class HttpHandler {
559
597
  * A handler over `listener`, a listening socket the program made
560
598
  * (`tcpListen`, or `tcpListenFlags` with SO_REUSEPORT for a worker of
561
599
  * `nish/net/prefork`), routing through `router`, whose routes are added
562
- * before the first `wait`.
600
+ * before the first `wait`. `limits.ring` acts only through the listener:
601
+ * open it with `limits.listen`, since a listener from `tcpListen` stays on
602
+ * descriptors whatever `ring` says.
563
603
  * @param limits the caps and timeouts. `slots`, `jsonBytes`, `maxEvents`
564
604
  * and `bodyTimeout` are read once here, so changing them later has no
565
605
  * effect; `http` is kept by the carrier, which reads its timeouts and
@@ -652,10 +692,7 @@ export class HttpHandler {
652
692
  this.watchedFired[id] = false
653
693
  }
654
694
  if (this.acceptRestUntil > 0 && monotonicNanos() >= this.acceptRestUntil) {
655
- this.acceptRestUntil = 0
656
- if (!this.draining) {
657
- pollAdd(this.loop, this.listener, H1_WANT_READ, HANDLER_LISTENER)
658
- }
695
+ this.endAcceptRest()
659
696
  }
660
697
  let timeout: i32 = timeoutMs
661
698
  if (this.acceptRestUntil > 0 && !this.draining) {
@@ -733,7 +770,7 @@ export class HttpHandler {
733
770
  this.open[s] &&
734
771
  this.server.holds(s) &&
735
772
  this.current[s] === -1 &&
736
- !this.server.connection(s).wantsWrite()
773
+ (this.server.resting(s) || !this.server.connection(s).wantsWrite())
737
774
  ) {
738
775
  this.closeSlot(s)
739
776
  } else if (this.open[s] && this.server.holds(s)) {
@@ -759,8 +796,9 @@ export class HttpHandler {
759
796
  slot = this.server.accept()
760
797
  }
761
798
  if (slot !== HANDLER_ACCEPT_NONE) {
762
- // Out of descriptors or memory: the connection stays in the backlog
763
- // and the listener stays readable, so rest it rather than spin.
799
+ // Out of descriptors (-24), ring slots (-23) or memory: the connection
800
+ // stays in the backlog and the listener stays readable, so rest it
801
+ // rather than spin, until a close frees one or the rest ends.
764
802
  pollRemove(this.loop, this.listener)
765
803
  this.acceptRestUntil = monotonicNanos() + HANDLER_ACCEPT_REST
766
804
  }
@@ -1088,8 +1126,22 @@ export class HttpHandler {
1088
1126
  this.forget(slot)
1089
1127
  }
1090
1128
 
1091
- /** The bookkeeping of a slot the carrier has closed. */
1129
+ /** Ends the listener's rest: it is back in the loop unless the handler is draining. */
1130
+ private endAcceptRest(): void {
1131
+ this.acceptRestUntil = 0
1132
+ if (!this.draining) {
1133
+ pollAdd(this.loop, this.listener, H1_WANT_READ, HANDLER_LISTENER)
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * The bookkeeping of a slot the carrier has closed. Its descriptor or ring
1139
+ * slot is free again, so a listener resting for want of one comes back.
1140
+ */
1092
1141
  private forget(slot: i32): void {
1142
+ if (this.acceptRestUntil > 0 && !this.draining) {
1143
+ this.endAcceptRest()
1144
+ }
1093
1145
  this.open[slot] = false
1094
1146
  this.slotGen[slot] = this.slotGen[slot] + 1
1095
1147
  const at: i32 = this.current[slot]
@@ -1191,6 +1243,18 @@ export class HttpHandler {
1191
1243
  return this.server.busy()
1192
1244
  }
1193
1245
 
1246
+ /**
1247
+ * Whether the listener is resting: an accept failed for want of a resource
1248
+ * (EMFILE for descriptors, ENFILE for ring slots, ENOMEM), so the handler
1249
+ * takes no connection until one closes or the 100 ms rest ends. During
1250
+ * `drain()` a close does not end the rest, so it stays true until the
1251
+ * 100 ms pass.
1252
+ * @returns true while the listener is out of the loop for such a rest
1253
+ */
1254
+ resting(): boolean {
1255
+ return this.acceptRestUntil > 0
1256
+ }
1257
+
1194
1258
  // ---- Responses ------------------------------------------------------------------
1195
1259
 
1196
1260
  /**
@@ -1271,11 +1271,10 @@ export class HttpServer {
1271
1271
  if (h1 !== null) {
1272
1272
  for (let s: i32 = 0; s < toI32(this.h1Open.length); s++) {
1273
1273
  if (this.h1Open[s] && h1.holds(s)) {
1274
- const conn: Http1Connection = h1.connection(s)
1275
- if (this.h1Current[s] === -1 && !conn.wantsWrite()) {
1274
+ if (this.h1Current[s] === -1 && (h1.resting(s) || !h1.connection(s).wantsWrite())) {
1276
1275
  this.h1Close(h1, s)
1277
1276
  } else {
1278
- conn.closeAfter = true
1277
+ h1.connection(s).closeAfter = true
1279
1278
  }
1280
1279
  }
1281
1280
  }