@amritk/nish-aarch64-linux 0.37.0 → 0.39.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 (73) hide show
  1. package/INSTALL.md +28 -16
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +380 -47
  4. package/package.json +1 -1
  5. package/runtime/core/arrays.d.ts +4 -0
  6. package/runtime/core/arrays.mjs +33 -0
  7. package/runtime/core/host.d.ts +11 -0
  8. package/runtime/core/host.mjs +35 -0
  9. package/runtime/nish.d.ts +645 -66
  10. package/runtime/nish.h +101 -15
  11. package/runtime/nish.mjs +69 -6
  12. package/runtime/node.mjs +117 -0
  13. package/runtime/runtime-aes.c +12 -4
  14. package/runtime/runtime-async.c +267 -51
  15. package/runtime/runtime-checksum.c +207 -15
  16. package/runtime/runtime-cross.c +2 -1
  17. package/runtime/runtime-net.c +32 -3
  18. package/runtime/runtime-os.c +174 -27
  19. package/runtime/runtime-region.c +170 -8
  20. package/runtime/runtime-sandbox.c +377 -17
  21. package/runtime/runtime-sha256.c +11 -4
  22. package/runtime/runtime-text.c +1068 -0
  23. package/runtime/runtime-wasm.c +18 -3
  24. package/runtime/runtime.c +55 -961
  25. package/runtime/vite.mjs +48 -11
  26. package/scripts/build.sh +113 -36
  27. package/std/LICENSE-fdlibm +8 -0
  28. package/std/README.md +7 -4
  29. package/std/array.ts +266 -0
  30. package/std/compress/checksum.ts +13 -0
  31. package/std/compress/deflate.ts +0 -2
  32. package/std/crypto/p256.ts +247 -74
  33. package/std/crypto/p384.ts +3 -1
  34. package/std/crypto/pki.ts +35 -9
  35. package/std/crypto/x25519.ts +153 -64
  36. package/std/crypto/x509.ts +113 -10
  37. package/std/host/text.ts +86 -0
  38. package/std/json-tokenizer.ts +20 -0
  39. package/std/json-typed.ts +217 -8
  40. package/std/math.ts +743 -41
  41. package/std/net/dns-resolver.ts +46 -6
  42. package/std/net/dns.ts +50 -13
  43. package/std/net/fetch.ts +691 -129
  44. package/std/net/handler.ts +142 -16
  45. package/std/net/http-compress.ts +17 -9
  46. package/std/net/http-fields.ts +19 -4
  47. package/std/net/http1-codec.ts +517 -154
  48. package/std/net/http1-server.ts +508 -25
  49. package/std/net/http2-cleartext.ts +526 -0
  50. package/std/net/http2-tls.ts +48 -0
  51. package/std/net/http2.ts +84 -0
  52. package/std/net/postgres-async.ts +2223 -0
  53. package/std/net/postgres-carrier.ts +343 -10
  54. package/std/net/postgres.ts +129 -11
  55. package/std/net/prefork.ts +195 -11
  56. package/std/net/quic-datagram.ts +30 -0
  57. package/std/net/quic-listener.ts +38 -12
  58. package/std/net/quic-packet.ts +19 -6
  59. package/std/net/quic-recovery.ts +134 -19
  60. package/std/net/quic-stream.ts +174 -36
  61. package/std/net/quic.ts +418 -18
  62. package/std/net/router.ts +39 -17
  63. package/std/net/serve.ts +867 -0
  64. package/std/net/tls/codec.ts +110 -32
  65. package/std/net/tls/record-server.ts +37 -7
  66. package/std/net/tls-tcp.ts +56 -1
  67. package/std/net/tls.ts +196 -50
  68. package/std/net/websocket.ts +55 -18
  69. package/std/net/webtransport.ts +179 -1
  70. package/std/regex.ts +69 -47
  71. package/std/region.ts +62 -11
  72. package/std/secret.ts +26 -59
  73. package/std/text.ts +464 -5
@@ -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
+ }