@amritk/nish-x86_64-linux 0.38.0 → 0.40.1

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 (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
@@ -73,16 +73,32 @@
73
73
  * **Errors.** A connection that is refused, reset, closed or past its connect
74
74
  * timeout fails every query on it with `PG_CARRIER_FAILED`, `failure` the
75
75
  * connection's `PG_ERR_*` and `socketError` the socket's negative errno
76
- * (`-110` for the timeout, 0 when the server closed cleanly). A plain query
76
+ * (`-110` for the timeout, 0 when the server closed cleanly; under TLS, see
77
+ * below). A plain query
77
78
  * the server refuses answers `PG_CARRIER_ERROR`, then `PG_CARRIER_FAILED`
78
79
  * with `failure` `PG_ERR_NONE`; a batched query the server refuses answers
79
80
  * only `PG_CARRIER_FAILED` with `failure` `PG_ERR_NONE`.
80
81
  * Programming errors (a cap out of range, an unknown batcher id, `send()`
81
82
  * with no build open) panic.
82
83
  *
83
- * `tests/link/std_postgres_carrier` runs one against a loopback backend;
84
- * `tests/postgres/carrier.ts` against a live server. Caps and findings:
85
- * `docs/security/postgres.md`.
84
+ * **TLS.** With `PgConfig.tls` set to `PG_TLS_REQUIRE` or `PG_TLS_VERIFY_FULL`,
85
+ * each connection opens with an SSLRequest and reads exactly the one byte of
86
+ * its answer, so nothing the server sends in the clear reaches the protocol:
87
+ * after `N` nothing more is read, and after `S` the next bytes are the
88
+ * handshake's, so anything else fails it. `S` goes on to a TLS 1.3 handshake
89
+ * (`nish/net/tls/record-client`) driven on the same loop without blocking, the
90
+ * StartupMessage held until it is done; any other answer fails the connection
91
+ * with `PG_ERR_TLS`. Under `PG_TLS_VERIFY_FULL` the server's chain is checked
92
+ * with `nish/net/tls/verify` against `PgConfig.tlsRootsPath` (or the system's
93
+ * store) and its name against `tlsServerName` (or the target's host);
94
+ * `PG_TLS_REQUIRE` encrypts without checking who answered. A refused
95
+ * certificate or failed handshake is `PG_ERR_TLS` with `socketError` the TLS
96
+ * alert (positive); a refused SSLRequest has `socketError` 0. TLS needs a TCP
97
+ * target.
98
+ *
99
+ * `tests/link/std_postgres_carrier` runs one against a loopback backend,
100
+ * `tests/link/std_postgres_tls` one over TLS; `tests/postgres/carrier.ts`
101
+ * against a live server. Caps and findings: `docs/security/postgres.md`.
86
102
  *
87
103
  * Written for this module; not ported from another implementation.
88
104
  */
@@ -103,10 +119,14 @@ import {
103
119
  PG_READY,
104
120
  PG_ROW,
105
121
  PG_TARGET_OK,
122
+ PG_TLS_DISABLE,
123
+ PG_TLS_VERIFY_FULL,
106
124
  PgBatcher,
125
+ PgConfig,
107
126
  PgConnection,
108
127
  PgPool,
109
128
  PgTarget,
129
+ pgSslRequest,
110
130
  } from "nish/net/postgres"
111
131
  import {
112
132
  connectResult,
@@ -122,7 +142,13 @@ import {
122
142
  tcpConnect,
123
143
  unixConnect,
124
144
  } from "nish:net"
125
- import { monotonicNanos } from "nish:process"
145
+ import { monotonicNanos, wallClockNanos } from "nish:process"
146
+ import { PkiRoots, pkiLoadRoots, pkiLoadSystemRoots } from "nish/crypto/pki-roots"
147
+ import { TlsClient, TlsClientConfig } from "nish/net/tls/client"
148
+ import { TLS_GROUP_SECP256R1, TLS_GROUP_X25519 } from "nish/net/tls/codec"
149
+ import { TLS_RECORD_AUTH, TlsRecordClient } from "nish/net/tls/record-client"
150
+ import { TLS_RECORD_STATE_FAILED, TLS_RECORD_STATE_OPEN } from "nish/net/tls/record-server"
151
+ import { TlsClientTrust, tlsClientTrust, tlsClientVerdict } from "nish/net/tls/verify"
126
152
 
127
153
  /** The client nonce a SCRAM exchange starts with, as `PgPool.connect` takes it. */
128
154
  const PG_CARRIER_NONCE_BYTES: i32 = 18
@@ -163,6 +189,22 @@ const PG_CARRIER_DISPATCH: i32 = 2
163
189
  const PG_CARRIER_FLUSH: i32 = 3
164
190
  /** `pgCarrierDispatch`: look again, something is owed. */
165
191
  const PG_CARRIER_AGAIN_PASS: i32 = -1
192
+ /** A slot's TLS phase: none, the connection is cleartext. */
193
+ const PG_CARRIER_TLS_OFF: i32 = 0
194
+ /** A slot's TLS phase: the SSLRequest is being sent, or its answer awaited. */
195
+ const PG_CARRIER_TLS_ASK: i32 = 1
196
+ /** A slot's TLS phase: the server said `S`; the handshake is under way. */
197
+ const PG_CARRIER_TLS_HANDSHAKE: i32 = 2
198
+ /** A slot's TLS phase: the handshake is done; the protocol runs inside it. */
199
+ const PG_CARRIER_TLS_OPEN: i32 = 3
200
+ /** The bytes of key material a TLS client starts from: its random, an x25519 and a P-256 private key. */
201
+ const PG_CARRIER_TLS_KEY_BYTES: i32 = 32
202
+ /** The most ciphertext read from a socket at once: one largest record and its header. */
203
+ const PG_CARRIER_TLS_READ_BYTES: i32 = 16645
204
+ /** A zero that stays `i32` under `--number-mode f64`: no bytes, no offset, no alert. */
205
+ const PG_CARRIER_ZERO: i32 = 0
206
+ /** The byte a server answers an SSLRequest with to go on with TLS. */
207
+ const PG_CARRIER_TLS_YES: i32 = 83
166
208
 
167
209
  /**
168
210
  * The caps a `PgCarrier` is built with, all set before it starts: nothing
@@ -227,6 +269,18 @@ export class PgCarrier {
227
269
  private readonly made: boolean[]
228
270
  private readonly deadlines: i64[]
229
271
  private readonly errors: i32[]
272
+ // TLS (`PgConfig.tls`): the name checked and the roots it is checked
273
+ // against, each slot's phase (`PG_CARRIER_TLS_*`), its client, how much of
274
+ // the SSLRequest has gone out; the SSLRequest itself, the one byte its
275
+ // answer is read into, and the buffer ciphertext is read through.
276
+ private readonly tlsName: string
277
+ private readonly trust: TlsClientTrust | null
278
+ private readonly tlsPhase: i32[]
279
+ private readonly tlsConns: (TlsRecordClient | null)[]
280
+ private readonly tlsAsked: i32[]
281
+ private readonly sslRequest: u8[]
282
+ private readonly tlsAnswer: u8[]
283
+ private readonly tlsInput: u8[]
230
284
  // Each query's tag, request, pool ticket (-1 for a batched one), whether
231
285
  // the server failed it, and the stack of free ones.
232
286
  private readonly qTags: i32[]
@@ -256,6 +310,7 @@ export class PgCarrier {
256
310
  failure: i32 = 0
257
311
  /** Behind a `PG_CARRIER_FAILED` for a lost connection: the socket error that ended it (`-110` for a connect timeout), or 0. */
258
312
  socketError: i32 = 0
313
+ private readonly tlsMode: i32
259
314
  private readonly watchId: i32
260
315
  private readonly loop: i32
261
316
  private qFreeCount: i32 = 0
@@ -282,7 +337,9 @@ export class PgCarrier {
282
337
  /**
283
338
  * A carrier for `pool`'s connections to `target`, its descriptor watched on
284
339
  * `handler` as `limits.watch`. Panics on a cap or watch id out of range,
285
- * a target that failed or is not a numeric address, or a poll set the
340
+ * a target that failed or is not a numeric address, TLS asked for on a Unix
341
+ * socket, `PG_TLS_VERIFY_FULL` with no root certificate to read from
342
+ * `tlsRootsPath` (or the system's store), or a poll set the
286
343
  * system will not create. It allocates every table here and opens its poll
287
344
  * set, but connects nothing until the first `next()`.
288
345
  *
@@ -315,6 +372,16 @@ export class PgCarrier {
315
372
  if (!target.unix && netAddress(this.address, target.host, target.port) < 0) {
316
373
  panic("nish/net/postgres-carrier: a PgCarrier's TCP host must be a numeric address")
317
374
  }
375
+ const config: PgConfig = pool.settings()
376
+ this.tlsMode = config.tls
377
+ if (this.tlsMode !== PG_TLS_DISABLE && target.unix) {
378
+ panic("nish/net/postgres-carrier: PgConfig.tls asks for TLS on a Unix socket")
379
+ }
380
+ if (this.tlsMode !== PG_TLS_DISABLE) {
381
+ pool.carryTls()
382
+ }
383
+ this.tlsName = config.tlsServerName.length > 0 ? config.tlsServerName : target.host
384
+ this.trust = this.tlsMode === PG_TLS_VERIFY_FULL ? pgCarrierTrust(config.tlsRootsPath) : null
318
385
  this.pool = pool
319
386
  this.handler = handler
320
387
  this.watchId = limits.watch
@@ -330,6 +397,14 @@ export class PgCarrier {
330
397
  this.made = new Array<boolean>(size)
331
398
  this.deadlines = new Array<i64>(size)
332
399
  this.errors = new Array<i32>(size)
400
+ this.tlsPhase = new Array<i32>(size)
401
+ this.tlsConns = new Array<TlsRecordClient | null>(size)
402
+ this.tlsAsked = new Array<i32>(size)
403
+ this.sslRequest = pgSslRequest()
404
+ this.tlsAnswer = new Array<u8>(1)
405
+ this.tlsInput = new Array<u8>(
406
+ this.tlsMode !== PG_TLS_DISABLE ? PG_CARRIER_TLS_READ_BYTES : PG_CARRIER_ZERO
407
+ )
333
408
  for (let s: i32 = 0; s < size && s < toI32(this.fds.length); s++) {
334
409
  this.fds[s] = -1
335
410
  }
@@ -646,8 +721,15 @@ export class PgCarrier {
646
721
  const fd: i32 = this.fds[s]
647
722
  if (fd >= 0) {
648
723
  const conn: PgConnection = this.pool.connection(s)
649
- conn.terminate()
650
- this.flush(conn, fd)
724
+ const tls: TlsRecordClient | null = this.tlsConns[s]
725
+ if (this.tlsPhase[s] === PG_CARRIER_TLS_OFF || this.tlsPhase[s] === PG_CARRIER_TLS_OPEN) {
726
+ conn.terminate()
727
+ this.flushSlot(s, conn, fd)
728
+ }
729
+ if (tls !== null) {
730
+ tls.close()
731
+ this.flushTls(tls, fd)
732
+ }
651
733
  this.dropSocket(s, fd)
652
734
  }
653
735
  }
@@ -700,6 +782,12 @@ export class PgCarrier {
700
782
  }
701
783
  this.connected[s] = true
702
784
  }
785
+ if (this.tlsPhase[s] !== PG_CARRIER_TLS_OFF) {
786
+ if ((bits & PG_CARRIER_READ_BITS) !== 0) {
787
+ this.serviceTls(s, fd, conn)
788
+ }
789
+ return
790
+ }
703
791
  const room: i32 = conn.inputRoom()
704
792
  if ((bits & PG_CARRIER_READ_BITS) !== 0 && room > 0) {
705
793
  const got: i32 = netRead(fd, conn.inputBuffer(), conn.inputEnd(), room)
@@ -718,6 +806,123 @@ export class PgCarrier {
718
806
  this.deadlines[s] = 0
719
807
  }
720
808
 
809
+ // Reads slot `s`'s socket under TLS: the one byte answering the
810
+ // SSLRequest, else ciphertext for the record layer, whose plaintext is
811
+ // then moved into the connection's input.
812
+ private serviceTls(s: i32, fd: i32, conn: PgConnection): void {
813
+ if (this.tlsPhase[s] === PG_CARRIER_TLS_ASK) {
814
+ if (this.tlsAsked[s] < toI32(this.sslRequest.length)) {
815
+ // The answer is read only once the whole SSLRequest is out.
816
+ return
817
+ }
818
+ // Exactly one byte, so nothing the server sends in the clear around
819
+ // it reaches the backend parser (CVE-2021-23222): bytes after `N` are
820
+ // never read, and bytes after `S` go to the record layer as the start
821
+ // of the handshake, which a TLS server's ServerHello must be, so
822
+ // anything else fails it.
823
+ const got: i32 = netRead(fd, this.tlsAnswer, 0, 1)
824
+ if (got === PG_CARRIER_AGAIN) {
825
+ return
826
+ }
827
+ if (got <= 0) {
828
+ this.fail(s, got)
829
+ } else if (toI32(this.tlsAnswer[0]) !== PG_CARRIER_TLS_YES) {
830
+ this.failTls(s, PG_CARRIER_ZERO)
831
+ } else {
832
+ this.tlsConns[s] = pgCarrierTlsStart(this.tlsName)
833
+ this.tlsPhase[s] = PG_CARRIER_TLS_HANDSHAKE
834
+ }
835
+ return
836
+ }
837
+ const tls: TlsRecordClient | null = this.tlsConns[s]
838
+ if (tls === null) {
839
+ return
840
+ }
841
+ let room: i32 = tls.space()
842
+ if (room > toI32(this.tlsInput.length)) {
843
+ room = toI32(this.tlsInput.length)
844
+ }
845
+ if (room > 0) {
846
+ const got: i32 = netRead(fd, this.tlsInput, 0, room)
847
+ if (got > 0) {
848
+ tls.receive(this.tlsInput, PG_CARRIER_ZERO, got)
849
+ } else if (got === 0) {
850
+ tls.end()
851
+ } else if (got !== PG_CARRIER_AGAIN) {
852
+ tls.abort()
853
+ this.fail(s, got)
854
+ return
855
+ }
856
+ }
857
+ this.advanceTls(s, tls, conn)
858
+ }
859
+
860
+ // Gives slot `s`'s handshake the verdict it waits on, notes it open, and
861
+ // moves what plaintext `conn` has room for into its input: whether any
862
+ // moved, so that `next()` looks at the slot again.
863
+ private advanceTls(s: i32, tls: TlsRecordClient, conn: PgConnection): boolean {
864
+ if ((tls.interest() & TLS_RECORD_AUTH) !== 0) {
865
+ const trust: TlsClientTrust | null = this.trust
866
+ if (trust !== null) {
867
+ const verdict: i32 = tlsClientVerdict(tls.tls, trust, wallClockNanos() / toI64(1000000))
868
+ if (verdict !== 0) {
869
+ tls.reject(verdict)
870
+ } else {
871
+ tls.authenticate(true)
872
+ }
873
+ } else {
874
+ // PG_TLS_REQUIRE: encryption against a passive eavesdropper only,
875
+ // as libpq's `sslmode=require`; `docs/security/postgres.md` argues it.
876
+ tls.authenticate(true)
877
+ }
878
+ }
879
+ if (tls.state === TLS_RECORD_STATE_FAILED) {
880
+ this.failTls(s, tls.failure())
881
+ return false
882
+ }
883
+ if (this.tlsPhase[s] === PG_CARRIER_TLS_HANDSHAKE && tls.state === TLS_RECORD_STATE_OPEN) {
884
+ this.tlsPhase[s] = PG_CARRIER_TLS_OPEN
885
+ }
886
+ if (this.tlsPhase[s] !== PG_CARRIER_TLS_OPEN) {
887
+ return false
888
+ }
889
+ let moved: boolean = false
890
+ let room: i32 = conn.inputRoom()
891
+ while (room > 0) {
892
+ const got: i32 = tls.read(conn.inputBuffer(), conn.inputEnd(), room)
893
+ if (got > 0) {
894
+ conn.received(got)
895
+ moved = true
896
+ } else if (got === 0) {
897
+ // The server's close_notify: the stream ended cleanly.
898
+ this.fail(s, PG_CARRIER_ZERO)
899
+ return true
900
+ } else {
901
+ if (tls.state === TLS_RECORD_STATE_FAILED) {
902
+ this.failTls(s, tls.failure())
903
+ return true
904
+ }
905
+ return moved
906
+ }
907
+ room = conn.inputRoom()
908
+ }
909
+ return moved
910
+ }
911
+
912
+ // Fails slot `s` with `PG_ERR_TLS`: `alert` the TLS alert behind it, 0
913
+ // for a refused SSLRequest. One write sends the alert a refusal sealed,
914
+ // when the socket has room for it.
915
+ private failTls(s: i32, alert: i32): void {
916
+ this.pool.connection(s).tlsFailed()
917
+ this.errors[s] = alert
918
+ this.deadlines[s] = 0
919
+ const tls: TlsRecordClient | null = this.tlsConns[s]
920
+ const fd: i32 = this.fds[s]
921
+ if (tls !== null && fd >= 0) {
922
+ this.flushTls(tls, fd)
923
+ }
924
+ }
925
+
721
926
  // The events of every slot's connection, resuming at `at`.
722
927
  private slots(): i32 {
723
928
  while (this.at < toI32(this.made.length)) {
@@ -958,6 +1163,8 @@ export class PgCarrier {
958
1163
  this.interest[slot] = H1_WANT_WRITE
959
1164
  this.errors[slot] = 0
960
1165
  this.deadlines[slot] = deadline
1166
+ this.tlsPhase[slot] = this.tlsMode !== PG_TLS_DISABLE ? PG_CARRIER_TLS_ASK : PG_CARRIER_TLS_OFF
1167
+ this.tlsAsked[slot] = 0
961
1168
  const fd: i32 = this.unix ? unixConnect(this.path) : tcpConnect(this.address)
962
1169
  this.fds[slot] = fd
963
1170
  if (fd < 0) {
@@ -979,13 +1186,25 @@ export class PgCarrier {
979
1186
  if (conn.failure !== PG_ERR_NONE) {
980
1187
  continue
981
1188
  }
982
- const written: i32 = this.flush(conn, fd)
1189
+ const tls: TlsRecordClient | null = this.tlsConns[s]
1190
+ if (tls !== null && this.advanceTls(s, tls, conn)) {
1191
+ // Plaintext the record layer held, which no poll would report.
1192
+ failed = true
1193
+ }
1194
+ if (conn.failure !== PG_ERR_NONE) {
1195
+ failed = true
1196
+ continue
1197
+ }
1198
+ const written: i32 = this.flushSlot(s, conn, fd)
983
1199
  if (written < 0) {
1200
+ if (tls !== null) {
1201
+ tls.abort()
1202
+ }
984
1203
  this.fail(s, written)
985
1204
  failed = true
986
1205
  continue
987
1206
  }
988
- const wants: i32 = conn.outputEnd() > conn.outputStart() ? H1_WANT_READ | H1_WANT_WRITE : H1_WANT_READ
1207
+ const wants: i32 = this.pending(s, conn) ? H1_WANT_READ | H1_WANT_WRITE : H1_WANT_READ
989
1208
  if (wants !== this.interest[s]) {
990
1209
  pollModify(this.loop, fd, wants, s)
991
1210
  this.interest[s] = wants
@@ -994,6 +1213,83 @@ export class PgCarrier {
994
1213
  return failed
995
1214
  }
996
1215
 
1216
+ // Whether slot `s` has bytes for the socket that it has not taken.
1217
+ private pending(s: i32, conn: PgConnection): boolean {
1218
+ const phase: i32 = this.tlsPhase[s]
1219
+ if (phase === PG_CARRIER_TLS_ASK) {
1220
+ return this.tlsAsked[s] < toI32(this.sslRequest.length)
1221
+ }
1222
+ const tls: TlsRecordClient | null = this.tlsConns[s]
1223
+ if (tls !== null && tls.outputEnd > tls.outputStart) {
1224
+ return true
1225
+ }
1226
+ return (
1227
+ (phase === PG_CARRIER_TLS_OFF || phase === PG_CARRIER_TLS_OPEN) && conn.outputEnd() > conn.outputStart()
1228
+ )
1229
+ }
1230
+
1231
+ // Writes what slot `s` owes its socket, as its TLS phase has it: the
1232
+ // SSLRequest, the handshake, `conn`'s bytes sealed, or `conn`'s bytes as
1233
+ // they are. The socket error when it fails, else 0.
1234
+ private flushSlot(s: i32, conn: PgConnection, fd: i32): i32 {
1235
+ const phase: i32 = this.tlsPhase[s]
1236
+ if (phase === PG_CARRIER_TLS_OFF) {
1237
+ return this.flush(conn, fd)
1238
+ }
1239
+ if (phase === PG_CARRIER_TLS_ASK) {
1240
+ const request: u8[] = this.sslRequest
1241
+ while (this.tlsAsked[s] < toI32(request.length)) {
1242
+ const n: i32 = netWrite(fd, request, this.tlsAsked[s], toI32(request.length) - this.tlsAsked[s])
1243
+ if (n === PG_CARRIER_AGAIN) {
1244
+ return 0
1245
+ }
1246
+ if (n <= 0) {
1247
+ return n < 0 ? n : -1
1248
+ }
1249
+ this.tlsAsked[s] += n
1250
+ }
1251
+ return 0
1252
+ }
1253
+ const tls: TlsRecordClient | null = this.tlsConns[s]
1254
+ if (tls === null) {
1255
+ return 0
1256
+ }
1257
+ while (true) {
1258
+ const written: i32 = this.flushTls(tls, fd)
1259
+ if (written !== 0 || tls.outputEnd > tls.outputStart) {
1260
+ return written
1261
+ }
1262
+ if (phase !== PG_CARRIER_TLS_OPEN || conn.outputEnd() <= conn.outputStart()) {
1263
+ return 0
1264
+ }
1265
+ const sealed: i32 = tls.write(
1266
+ conn.outputBuffer(),
1267
+ conn.outputStart(),
1268
+ conn.outputEnd() - conn.outputStart()
1269
+ )
1270
+ if (sealed <= 0) {
1271
+ return 0
1272
+ }
1273
+ conn.sent(sealed)
1274
+ }
1275
+ }
1276
+
1277
+ // Writes the records `tls` has sealed until the socket takes no more; the
1278
+ // socket error when it fails, else 0.
1279
+ private flushTls(tls: TlsRecordClient, fd: i32): i32 {
1280
+ while (tls.outputEnd > tls.outputStart) {
1281
+ const n: i32 = netWrite(fd, tls.output, tls.outputStart, tls.outputEnd - tls.outputStart)
1282
+ if (n === PG_CARRIER_AGAIN) {
1283
+ return 0
1284
+ }
1285
+ if (n <= 0) {
1286
+ return n < 0 ? n : -1
1287
+ }
1288
+ tls.consume(n)
1289
+ }
1290
+ return 0
1291
+ }
1292
+
997
1293
  // Writes what `conn` queued until the socket takes no more; the socket
998
1294
  // error when it fails, else 0.
999
1295
  private flush(conn: PgConnection, fd: i32): i32 {
@@ -1026,6 +1322,11 @@ export class PgCarrier {
1026
1322
  pollRemove(this.loop, fd)
1027
1323
  netClose(fd)
1028
1324
  this.fds[s] = -1
1325
+ const tls: TlsRecordClient | null = this.tlsConns[s]
1326
+ if (tls !== null) {
1327
+ tls.wipe()
1328
+ this.tlsConns[s] = null
1329
+ }
1029
1330
  }
1030
1331
 
1031
1332
  // Answers query `q`'s final `event`; the query is freed on the next call.
@@ -1119,3 +1420,35 @@ export class PgCarrier {
1119
1420
  this.mapKeys[i] = -1
1120
1421
  }
1121
1422
  }
1423
+
1424
+ /**
1425
+ * The roots `PG_TLS_VERIFY_FULL` checks a server's chain against: the PEM
1426
+ * file at `path`, or the system's store when it is empty. Panics when no
1427
+ * root could be read, since no server could then be trusted.
1428
+ */
1429
+ const pgCarrierTrust = (path: string): TlsClientTrust => {
1430
+ const roots: PkiRoots = path.length > 0 ? pkiLoadRoots(path, [], []) : pkiLoadSystemRoots()
1431
+ if (toI32(roots.roots.length) === 0) {
1432
+ panic("nish/net/postgres-carrier: PG_TLS_VERIFY_FULL with no root certificate to read")
1433
+ }
1434
+ return tlsClientTrust(roots)
1435
+ }
1436
+
1437
+ /**
1438
+ * A TLS 1.3 client for `name`, offering ALPN `postgresql` as libpq does,
1439
+ * with fresh random and key shares; `TlsClient` copies the keys and zeroes
1440
+ * the arrays they came in. It offers secp256r1 beside x25519: a server
1441
+ * before PostgreSQL 18 accepts only `ssl_ecdh_curve`, prime256v1 unless
1442
+ * set, and asks for that share with a HelloRetryRequest.
1443
+ */
1444
+ const pgCarrierTlsStart = (name: string): TlsRecordClient => {
1445
+ const random: u8[] = new Array<u8>(PG_CARRIER_TLS_KEY_BYTES)
1446
+ const x25519: u8[] = new Array<u8>(PG_CARRIER_TLS_KEY_BYTES)
1447
+ const p256: u8[] = new Array<u8>(PG_CARRIER_TLS_KEY_BYTES)
1448
+ crypto.getRandomValues(random)
1449
+ crypto.getRandomValues(x25519)
1450
+ crypto.getRandomValues(p256)
1451
+ const config = new TlsClientConfig(name, ["postgresql"])
1452
+ config.groups = [TLS_GROUP_X25519, TLS_GROUP_SECP256R1]
1453
+ return new TlsRecordClient(new TlsClient(config, random, x25519, p256))
1454
+ }
@@ -124,8 +124,9 @@
124
124
  * of an exchange SCRAM began is refused.
125
125
  *
126
126
  * Cleartext and MD5 passwords, and SASL mechanisms other than SCRAM-SHA-256,
127
- * are refused: with no TLS here the first sends the password as it is, and the
128
- * second is a hash any eavesdropper can replay. The password's bytes are used
127
+ * are refused: the first sends the password as it is, and the second is a
128
+ * hash any eavesdropper can replay, over a connection that need not be
129
+ * encrypted (TLS is off unless `PgConfig.tls` asks for it). The password's bytes are used
129
130
  * as they are, without SASLprep (RFC 4013): an ASCII password works, and a
130
131
  * non-ASCII one works only when it is already in the form SASLprep would give
131
132
  * (PostgreSQL itself falls back to the raw bytes when it cannot prepare one).
@@ -248,6 +249,43 @@ export const PG_ERR_ENCODING: i32 = 8
248
249
  export const PG_ERR_CLOSED: i32 = 9
249
250
  /** The server's `DateStyle` is not ISO or its `TimeZone` is not UTC, the two the decoders read: at startup, or after a `SET`. */
250
251
  export const PG_ERR_SETTING: i32 = 10
252
+ /**
253
+ * TLS to the server failed, reported by the carrier (`tlsFailed()`): the
254
+ * server answered `N` to the SSLRequest while `PgConfig.tls` asks for TLS,
255
+ * its certificate was refused, or the handshake failed.
256
+ */
257
+ export const PG_ERR_TLS: i32 = 11
258
+
259
+ /** `PgConfig.tls`: no SSLRequest; the connection is cleartext. The default. */
260
+ export const PG_TLS_DISABLE: i32 = 0
261
+ /**
262
+ * `PgConfig.tls`: an SSLRequest first, and TLS 1.3 or nothing, the
263
+ * server's certificate not checked. Keeps a passive eavesdropper out; an
264
+ * active one who answers in the server's place is not.
265
+ */
266
+ export const PG_TLS_REQUIRE: i32 = 1
267
+ /**
268
+ * `PgConfig.tls`: an SSLRequest first, and TLS 1.3 or nothing, the
269
+ * server's chain checked against the trusted roots and its name against the
270
+ * host (libpq's `sslmode=verify-full`).
271
+ */
272
+ export const PG_TLS_VERIFY_FULL: i32 = 2
273
+ /** The SSLRequest's code, in place of a protocol version: 1234 in the high 16 bits, 5679 in the low. */
274
+ export const PG_SSL_REQUEST_CODE: i32 = 80877103
275
+
276
+ /**
277
+ * The 8-byte SSLRequest a client sends before its StartupMessage to ask for
278
+ * TLS: its length, 8, and `PG_SSL_REQUEST_CODE`, both big-endian. The server
279
+ * answers one byte, `S` to go on with a TLS handshake or `N` to refuse.
280
+ *
281
+ * @returns A new 8-byte array holding the message.
282
+ */
283
+ export const pgSslRequest = (): u8[] => {
284
+ const out: u8[] = new Array<u8>(8)
285
+ setI32BE(out, 0, 8)
286
+ setI32BE(out, 4, PG_SSL_REQUEST_CODE)
287
+ return out
288
+ }
251
289
 
252
290
  /** `PgArrayWalker.next()`: an element, at `start` for `length` bytes. */
253
291
  export const PG_ARRAY_ELEMENT: i32 = 0
@@ -349,6 +387,21 @@ export class PgConfig {
349
387
  * output cannot grow the buffer without bound.
350
388
  */
351
389
  maxOutput: i32 = 1048576
390
+ /**
391
+ * Read by the carrier only: `PG_TLS_DISABLE` (the default), `PG_TLS_REQUIRE`
392
+ * or `PG_TLS_VERIFY_FULL`. TLS needs a TCP target.
393
+ */
394
+ tls: i32 = 0
395
+ /**
396
+ * Read by the carrier only, under `PG_TLS_VERIFY_FULL`: a PEM file of the
397
+ * roots to trust; empty means the system's store.
398
+ */
399
+ tlsRootsPath: string = ""
400
+ /**
401
+ * Read by the carrier only: the name the server's certificate must carry,
402
+ * and the SNI sent; empty means the target's host.
403
+ */
404
+ tlsServerName: string = ""
352
405
  }
353
406
 
354
407
  /** A server's ErrorResponse or NoticeResponse: the fields a program acts on. */
@@ -465,7 +518,9 @@ const pgCheckConfig = (config: PgConfig): void => {
465
518
  config.maxColumns > 65535 ||
466
519
  config.minIterations < 1 ||
467
520
  config.maxIterations < config.minIterations ||
468
- config.maxIterations > PG_MAX_ITERATIONS
521
+ config.maxIterations > PG_MAX_ITERATIONS ||
522
+ config.tls < PG_TLS_DISABLE ||
523
+ config.tls > PG_TLS_VERIFY_FULL
469
524
  ) {
470
525
  panic("nish/net/postgres: a PgConfig cap out of range")
471
526
  }
@@ -1448,7 +1503,9 @@ export class PgConnection {
1448
1503
  * so the caller may wipe its own; `nonce` must be at least 18 bytes from a
1449
1504
  * cryptographic random source (`crypto.getRandomValues`), and is fixed only
1450
1505
  * in a test. Panics on a `PgConfig` that is a mistake (no user, a cap out
1451
- * of range, a NUL in a startup parameter) or a nonce shorter than 18 bytes.
1506
+ * of range, a NUL in a startup parameter), on one whose `tls` asks for TLS,
1507
+ * which only `PgCarrier` speaks, so a connection driven by hand never runs
1508
+ * in the clear when TLS was asked for, or on a nonce shorter than 18 bytes.
1452
1509
  * @param config The caps and startup parameters; kept, and read for the
1453
1510
  * connection's life, so do not change it afterwards.
1454
1511
  * @param password The role's password as UTF-8 bytes, without SASLprep;
@@ -1461,6 +1518,9 @@ export class PgConnection {
1461
1518
  panic("nish/net/postgres: the SCRAM nonce needs at least 18 random bytes")
1462
1519
  }
1463
1520
  pgCheckConfig(config)
1521
+ if (config.tls !== PG_TLS_DISABLE) {
1522
+ panic("nish/net/postgres: PgConfig.tls asks for TLS, which only PgCarrier speaks")
1523
+ }
1464
1524
  this.config = config
1465
1525
  this.text = new PgText()
1466
1526
  this.binary = new PgBinary()
@@ -1620,6 +1680,19 @@ export class PgConnection {
1620
1680
  return PG_FAILED
1621
1681
  }
1622
1682
 
1683
+ /**
1684
+ * Reports that TLS under the connection failed, or the server refused it:
1685
+ * unless it already has, the connection fails with `PG_ERR_TLS`, which
1686
+ * wipes the password.
1687
+ * @returns `PG_FAILED`, as every later `next()` does.
1688
+ */
1689
+ tlsFailed(): i32 {
1690
+ if (this.state !== PG_STATE_FAILED) {
1691
+ return this.fail(PG_ERR_TLS)
1692
+ }
1693
+ return PG_FAILED
1694
+ }
1695
+
1623
1696
  /**
1624
1697
  * Whether every byte of the connection's copy of the password is zero: true
1625
1698
  * once the proof is computed, the connection has failed or `dispose()` has
@@ -3359,6 +3432,9 @@ export class PgPool {
3359
3432
  readonly size: i32
3360
3433
 
3361
3434
  private readonly config: PgConfig
3435
+ // The cleartext copy of `config` a `PgCarrier` that runs TLS under the pool's
3436
+ // connections has them made with; null until one takes the pool.
3437
+ private carried: PgConfig | null = null
3362
3438
  private readonly password: PgPassword
3363
3439
  private readonly slots: PgPoolSlot[]
3364
3440
  private readonly queue: i32[]
@@ -3408,6 +3484,40 @@ export class PgPool {
3408
3484
  this.types = []
3409
3485
  }
3410
3486
 
3487
+ /**
3488
+ * The settings the pool's connections are made with, as given to the constructor.
3489
+ *
3490
+ * @returns The pool's `PgConfig`, not a copy.
3491
+ */
3492
+ settings(): PgConfig {
3493
+ return this.config
3494
+ }
3495
+
3496
+ /**
3497
+ * @internal Used by the `PgCarrier` constructor: marks the pool's connections
3498
+ * as carried over TLS, so `connect` makes them with a copy of the config
3499
+ * whose `tls` is `PG_TLS_DISABLE`; without it, a pool whose config asks for
3500
+ * TLS refuses to connect. A program that calls it by hand gets a pool in
3501
+ * the clear, as if it had set `tls` to `PG_TLS_DISABLE`.
3502
+ */
3503
+ carryTls(): void {
3504
+ const c: PgConfig = this.config
3505
+ const plain: PgConfig = new PgConfig()
3506
+ plain.user = c.user
3507
+ plain.database = c.database
3508
+ plain.applicationName = c.applicationName
3509
+ plain.options = c.options
3510
+ plain.maxMessage = c.maxMessage
3511
+ plain.maxInFlight = c.maxInFlight
3512
+ plain.pack = c.pack
3513
+ plain.inputSize = c.inputSize
3514
+ plain.maxColumns = c.maxColumns
3515
+ plain.minIterations = c.minIterations
3516
+ plain.maxIterations = c.maxIterations
3517
+ plain.maxOutput = c.maxOutput
3518
+ this.carried = plain
3519
+ }
3520
+
3411
3521
  /**
3412
3522
  * Registers a statement for every connection to prepare before its first
3413
3523
  * request. False when a connection has been made already, `name` or `sql`
@@ -3588,8 +3698,9 @@ export class PgPool {
3588
3698
  /**
3589
3699
  * Makes the wanted `slot`'s connection, `nonce` as `PgConnection` takes it:
3590
3700
  * send its output once the socket is connected, and if the socket fails,
3591
- * call `connection(slot).closed()`. Panics when `slot` is not wanted or the
3592
- * pool is disposed.
3701
+ * call `connection(slot).closed()`. Panics when `slot` is not wanted, the
3702
+ * pool is disposed, or its `PgConfig.tls` asks for TLS and no `PgCarrier`
3703
+ * drives the pool: only the carrier speaks TLS.
3593
3704
  *
3594
3705
  * @param slot The slot `wanted()` answered.
3595
3706
  * @param nonce At least 18 fresh random bytes for the SCRAM client nonce, as the
@@ -3602,8 +3713,12 @@ export class PgPool {
3602
3713
  if (this.password.gone) {
3603
3714
  panic("nish/net/postgres: PgPool.connect after dispose")
3604
3715
  }
3716
+ const carried: PgConfig | null = this.carried
3717
+ if (this.config.tls !== PG_TLS_DISABLE && carried === null) {
3718
+ panic("nish/net/postgres: PgConfig.tls asks for TLS, which only PgCarrier speaks")
3719
+ }
3605
3720
  const s: PgPoolSlot = this.slots[slot]
3606
- s.conn = new PgConnection(this.config, this.password.bytes, nonce)
3721
+ s.conn = new PgConnection(carried !== null ? carried : this.config, this.password.bytes, nonce)
3607
3722
  s.state = PG_SLOT_STARTING
3608
3723
  s.queued = 0
3609
3724
  s.described = 0