@amritk/nish-aarch64-darwin 0.36.0 → 0.37.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 (87) hide show
  1. package/INSTALL.md +67 -58
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +43 -4
  4. package/package.json +1 -1
  5. package/runtime/async.d.mts +2 -0
  6. package/runtime/async.mjs +7 -0
  7. package/runtime/nish.d.ts +736 -499
  8. package/runtime/nish.h +25 -0
  9. package/runtime/page.d.ts +53 -0
  10. package/runtime/page.mjs +146 -0
  11. package/runtime/runtime-async.c +557 -0
  12. package/runtime/runtime-wasm.c +63 -7
  13. package/scripts/build.sh +147 -5
  14. package/std/README.md +107 -82
  15. package/std/bytes.ts +23 -19
  16. package/std/compress/checksum.ts +1 -1
  17. package/std/crypto/aes.ts +48 -43
  18. package/std/crypto/base64url.ts +7 -5
  19. package/std/crypto/bcrypt-batch.ts +13 -13
  20. package/std/crypto/bcrypt.ts +33 -27
  21. package/std/crypto/chacha20poly1305.ts +16 -14
  22. package/std/crypto/ed25519.ts +19 -16
  23. package/std/crypto/hmac.ts +7 -6
  24. package/std/crypto/jwt.ts +23 -20
  25. package/std/crypto/p256.ts +63 -56
  26. package/std/crypto/p384.ts +23 -20
  27. package/std/crypto/pki.ts +18 -15
  28. package/std/crypto/rsa.ts +23 -19
  29. package/std/crypto/x25519.ts +11 -10
  30. package/std/crypto/x509.ts +69 -62
  31. package/std/host/ring.ts +124 -0
  32. package/std/json-equal.ts +12 -11
  33. package/std/json-number.ts +12 -12
  34. package/std/json-tokenizer.ts +26 -22
  35. package/std/json-typed.ts +92 -78
  36. package/std/json-value.ts +38 -33
  37. package/std/json.ts +32 -28
  38. package/std/net/fetch.ts +1117 -230
  39. package/std/net/handler.ts +18 -0
  40. package/std/net/hpack.ts +29 -26
  41. package/std/net/http-compress.ts +27 -21
  42. package/std/net/http1-client-codec.ts +29 -25
  43. package/std/net/http1-codec.ts +44 -87
  44. package/std/net/http1-server.ts +66 -54
  45. package/std/net/http2-frame.ts +17 -16
  46. package/std/net/http2-tls.ts +17 -15
  47. package/std/net/http2.ts +67 -54
  48. package/std/net/http3-frame.ts +11 -10
  49. package/std/net/http3-server.ts +36 -35
  50. package/std/net/http3.ts +70 -58
  51. package/std/net/postgres.ts +178 -160
  52. package/std/net/prefork.ts +38 -34
  53. package/std/net/qpack.ts +15 -14
  54. package/std/net/quic-conn-ack.ts +1 -0
  55. package/std/net/quic-conn-cid.ts +11 -0
  56. package/std/net/quic-conn-params.ts +41 -14
  57. package/std/net/quic-datagram.ts +7 -0
  58. package/std/net/quic-frame.ts +48 -12
  59. package/std/net/quic-listener.ts +61 -44
  60. package/std/net/quic-packet.ts +71 -52
  61. package/std/net/quic-recovery.ts +59 -21
  62. package/std/net/quic-stream.ts +83 -55
  63. package/std/net/quic.ts +204 -152
  64. package/std/net/tls/client.ts +1 -0
  65. package/std/net/tls/codec.ts +81 -12
  66. package/std/net/tls/record-client.ts +30 -18
  67. package/std/net/tls/record-server.ts +74 -46
  68. package/std/net/tls/record.ts +33 -24
  69. package/std/net/tls/ticket.ts +2 -0
  70. package/std/net/tls/verify.ts +8 -7
  71. package/std/net/tls-tcp.ts +58 -50
  72. package/std/net/tls.ts +55 -43
  73. package/std/net/url.ts +12 -9
  74. package/std/net/websocket.ts +23 -19
  75. package/std/net/webtransport.ts +24 -18
  76. package/std/random.ts +8 -6
  77. package/std/regex.ts +70 -59
  78. package/std/sync/ring.ts +24 -21
  79. package/std/sync/shm.ts +9 -7
  80. package/std/term-io.ts +17 -14
  81. package/std/term-probe.ts +11 -10
  82. package/std/term-rate.ts +71 -61
  83. package/std/term.ts +73 -59
  84. package/std/text.ts +11 -10
  85. package/std/threads.ts +19 -15
  86. package/std/yaml-json.ts +17 -15
  87. package/std/yaml-write.ts +21 -14
@@ -24,27 +24,30 @@
24
24
  *
25
25
  * Ported from fiat-crypto (https://github.com/mit-plv/fiat-crypto), fiat-c/src/p384_32.c and fiat-c/src/p384_scalar_32.c. Copyright (c) 2015-2020 the fiat-crypto authors (see the AUTHORS file). Used under the MIT licence; see std/crypto/LICENSE-fiat-crypto-p384.
26
26
  *
27
- * **What is ported and what is not.** The `p384Fiat*` functions are
28
- * fiat-crypto's generated, formally verified Montgomery arithmetic on twelve
29
- * `u32` limbs with `u64` products — `mul`, `add`, `sub`, `selectznz`,
30
- * `nonzero` and `set_one` mod p, and `mul` and `set_one` mod n — statement for
31
- * statement, with fiat's variable names, translated the way
32
- * `nish/crypto/p256` translates P-256's: C's out-pointers become a `u64`
33
- * answer, each of fiat's `addcarryx`, `subborrowx` and `mulx` helpers here
34
- * answering its two outputs packed, the first in the low 32 bits and the
35
- * second above them, and the caller declaring only the halves fiat goes on to
36
- * read; and each function opens with a length guard, so that the literal
37
- * indices after it compile with no bounds check. fiat's 64-bit `p384_64.c`
38
- * needs a 128-bit product, which Nish has not got, so the 32-bit files are the
39
- * ones ported. fiat's `square` is not: a square is a `mul` of an element by
40
- * itself, which costs verification a little time and saves this file 2,500
41
- * lines. The scalar functions use the field's four helpers, which fiat
42
- * generates identically for both. Everything else in this file — the curve,
43
- * the encodings, the inversions and ECDSA — is written for this module from
44
- * the documents it names.
27
+ * **What is ported and what is not.**
45
28
  *
46
- * **The curve** is `y^2 = x^3 - 3x + b` over GF(p), p = 2^384 - 2^128 - 2^96
47
- * + 2^32 - 1, with the base point G and its order n from SEC 2 §2.5.1 (FIPS
29
+ * The `p384Fiat*` functions are fiat-crypto's generated, formally verified
30
+ * Montgomery arithmetic on twelve `u32` limbs with `u64` products — `mul`,
31
+ * `add`, `sub`, `selectznz`, `nonzero` and `set_one` mod p, and `mul` and
32
+ * `set_one` mod n — statement for statement, with fiat's variable names,
33
+ * translated the way `nish/crypto/p256` translates P-256's:
34
+ * - C's out-pointers become a `u64` answer, each of fiat's `addcarryx`,
35
+ * `subborrowx` and `mulx` helpers here answering its two outputs packed, the
36
+ * first in the low 32 bits and the second above them, and the caller
37
+ * declaring only the halves fiat goes on to read;
38
+ * - and each function opens with a length guard, so that the literal indices
39
+ * after it compile with no bounds check.
40
+ *
41
+ * fiat's 64-bit `p384_64.c` needs a 128-bit product, which Nish has not got, so
42
+ * the 32-bit files are the ones ported. fiat's `square` is not: a square is a
43
+ * `mul` of an element by itself, which costs verification a little time and
44
+ * saves this file 2,500 lines. The scalar functions use the field's four
45
+ * helpers, which fiat generates identically for both. Everything else in this
46
+ * file — the curve, the encodings, the inversions and ECDSA — is written for
47
+ * this module from the documents it names.
48
+ *
49
+ * **The curve** is `y^2 = x^3 - 3x + b` over GF(p),
50
+ * p = 2^384 - 2^128 - 2^96 + 2^32 - 1, with the base point G and its order n from SEC 2 §2.5.1 (FIPS
48
51
  * 186-4 §D.1.2.4). Points are projective (X : Y : Z), Z = 0 the identity, and
49
52
  * are added and doubled with the complete formulas of J. Renes, C. Costello and
50
53
  * L. Batina, "Complete addition formulas for prime order elliptic curves"
package/std/crypto/pki.ts CHANGED
@@ -30,22 +30,25 @@
30
30
  * and subtrees of a certificate, the certificates of a path, the signatures
31
31
  * checked and the name comparisons made by one call.
32
32
  *
33
- * The chain's first certificate is the leaf; the rest are a pool, in any
34
- * order and possibly with extras, as servers send them. A path is searched
35
- * for depth first from the leaf: an issuer is a root of the store, tried
36
- * first, or a pool certificate, whose subject is the child's issuer Name byte
37
- * for byte, and whose subjectKeyIdentifier, when both it and the child's
33
+ * The chain's first certificate is the leaf; the rest are a pool, in any order
34
+ * and possibly with extras, as servers send them. A path is searched for depth
35
+ * first from the leaf: an issuer is a root of the store, tried first, or a pool
36
+ * certificate, whose subject is the child's issuer Name byte for byte, and
37
+ * whose subjectKeyIdentifier, when both it and the child's
38
38
  * authorityKeyIdentifier are present, is that identifier. A certificate is
39
- * never twice in a path. A path ends at a root, whose own signature is not
40
- * read, but whose validity, critical extensions, basicConstraints,
41
- * extKeyUsage, name constraints and key identifiers are checked as an
42
- * intermediate's are, as x509-limbo's cases ask. Every check of an issuer is
43
- * made as it is added, against the certificates below it, so a refusal ends
44
- * that branch at once; the leaf's profile (CA/Browser Forum Baseline
45
- * Requirements §7.1) is checked once a path is found. When no path is
46
- * accepted, the reason is that of the attempt that got nearest a root: one
47
- * that reached a root beats any that did not, a longer one a shorter, and the
48
- * first found a later one of the same length.
39
+ * never twice in a path.
40
+ *
41
+ * A path ends at a root, whose own signature is not read, but whose validity,
42
+ * critical extensions, basicConstraints, extKeyUsage, name constraints and key
43
+ * identifiers are checked as an intermediate's are, as x509-limbo's cases ask.
44
+ * Every check of an issuer is made as it is added, against the certificates
45
+ * below it, so a refusal ends that branch at once; the leaf's profile
46
+ * (CA/Browser Forum Baseline Requirements §7.1) is checked once a path is
47
+ * found.
48
+ *
49
+ * When no path is accepted, the reason is that of the attempt that got nearest
50
+ * a root: one that reached a root beats any that did not, a longer one a
51
+ * shorter, and the first found a later one of the same length.
49
52
  *
50
53
  * Revocation (CRLs, OCSP, Certificate Transparency), certificate policies,
51
54
  * RFC 5280 §7.1's Name folding and an extension's criticality are not
package/std/crypto/rsa.ts CHANGED
@@ -27,14 +27,16 @@
27
27
  * **Verification** answers `false`, never a panic, for an unknown hash id, a
28
28
  * signature that is not exactly as long as the modulus or is not below it, a
29
29
  * negative salt length, and any encoding that is not exactly the one RFC 8017
30
- * defines. PKCS#1 v1.5 builds the whole encoded message it expects, `00 01 FF
31
- * … FF 00 DigestInfo`, and compares it with what the signature opens to, so no
30
+ * defines. PKCS#1 v1.5 builds the whole encoded message it expects, `00 01 FF …
31
+ * FF 00 DigestInfo`, and compares it with what the signature opens to, so no
32
32
  * part of the opened block is parsed (Bleichenbacher's 2006 forgery against a
33
- * parser that skipped trailing bytes). The DigestInfo carries the NULL
34
- * parameters RFC 8017 §9.2 note 1 prints; the form without them, which the
35
- * RFC lets a verifier accept, is refused. PSS is RFC 8017 §8.1.2 and §9.1.2
36
- * step by step, with MGF1 over the same hash as the message, the leftmost
37
- * bits of the masked block checked to be zero and the 0x01 separator checked.
33
+ * parser that skipped trailing bytes).
34
+ *
35
+ * The DigestInfo carries the NULL parameters RFC 8017 §9.2 note 1 prints; the
36
+ * form without them, which the RFC lets a verifier accept, is refused. PSS is
37
+ * RFC 8017 §8.1.2 and §9.1.2 step by step, with MGF1 over the same hash as the
38
+ * message, the leftmost bits of the masked block checked to be zero and the
39
+ * 0x01 separator checked.
38
40
  *
39
41
  * **Variable time, on purpose.** A public key, a signature and a message are
40
42
  * all public, so nothing here has a secret to leak: the exponentiation
@@ -42,19 +44,21 @@
42
44
  * the encodings are compared with an early exit. That is why this module does
43
45
  * not use `nish:secret` or `nish/crypto/ct`.
44
46
  *
45
- * **The arithmetic** is written for this module from the textbook. Numbers
46
- * are little-endian `u32` limbs, products are taken in `u64`, and modular
47
+ * **The arithmetic** is written for this module from the textbook. Numbers are
48
+ * little-endian `u32` limbs, products are taken in `u64`, and modular
47
49
  * multiplication is Montgomery's (P. L. Montgomery, "Modular multiplication
48
50
  * without trial division", Math. Comp. 44, 1985) in the coarsely integrated
49
- * operand scanning form of Ç. K. Koç, T. Acar and B. S. Kaliski, "Analyzing
50
- * and comparing Montgomery multiplication algorithms" (IEEE Micro, 1996), the
51
- * same algorithm as A. Menezes, P. van Oorschot and S. Vanstone, *Handbook of
51
+ * operand scanning form of Ç. K. Koç, T. Acar and B. S. Kaliski, "Analyzing and
52
+ * comparing Montgomery multiplication algorithms" (IEEE Micro, 1996), the same
53
+ * algorithm as A. Menezes, P. van Oorschot and S. Vanstone, *Handbook of
52
54
  * Applied Cryptography* (1996), Algorithm 14.36, with one conditional
53
- * subtraction at the end. The exponent is applied left to right by square
54
- * and multiply (HAC Algorithm 14.79's binary special case). The closest
55
- * upstream is BearSSL's `i31` code (`br_i31_montymul`, `br_i31_modpow`), and
56
- * nothing here follows it: BearSSL keeps 31-bit words and a constant-time
57
- * structure, this keeps 32-bit words and branches freely.
55
+ * subtraction at the end.
56
+ *
57
+ * The exponent is applied left to right by square and multiply (HAC Algorithm
58
+ * 14.79's binary special case). The closest upstream is BearSSL's `i31` code
59
+ * (`br_i31_montymul`, `br_i31_modpow`), and nothing here follows it: BearSSL
60
+ * keeps 31-bit words and a constant-time structure, this keeps 32-bit words and
61
+ * branches freely.
58
62
  *
59
63
  * Private names carry the `rsa` prefix because a `std/` module's private
60
64
  * functions share the importing program's flat symbol namespace
@@ -343,8 +347,8 @@ const rsaSubInPlace = (a: u32[], n: u32[], count: i32): void => {
343
347
  * Acar and Kaliski's CIOS. `t` is scratch of `count + 2` limbs. Each row adds
344
348
  * `a b[i]` into `t`, then the multiple `m n` of the modulus that clears the
345
349
  * low limb, and shifts down a limb; `t` stays below 2n, and one subtraction
346
- * of `n` brings it below `n`. Every sum is at most (2^32 - 1) + (2^32 - 1)^2
347
- * + (2^32 - 1) = 2^64 - 1, so a `u64` holds it.
350
+ * of `n` brings it below `n`. Every sum is
351
+ * at most (2^32 - 1) + (2^32 - 1)^2 + (2^32 - 1) = 2^64 - 1, so a `u64` holds it.
348
352
  */
349
353
  const rsaMontMul = (out: u32[], a: u32[], b: u32[], n: u32[], n0inv: u32, t: u32[], count: i32): void => {
350
354
  if (
@@ -58,16 +58,17 @@
58
58
  * `f25519Square`, `f25519MulA24`, `f25519Add`, `f25519Sub`, `f25519Swap` and
59
59
  * one pass of `x25519Ladder`'s loop, and the check reads each one's `clang -O2`
60
60
  * machine code for x86-64 and aarch64 and finds no branch and no load or store
61
- * at an address the scalar bit or a limb reaches. They are copies because the
62
- * check refuses every branch, loop back-edges included, and this module's own
63
- * functions keep their loops and the early `return`s below; the copies drop the
64
- * guards and write `f25519Mul`'s outer loop out a row at a time, and the
65
- * fixture's `main` holds them to the same RFC 7748 vectors as this module. A
66
- * change to one of those functions belongs in that fixture too. What stays
67
- * discipline rather than proof is the rest: the loops around the step,
68
- * `f25519Decode`, `f25519Encode` and `f25519Invert`, whose branches are all on
69
- * public positions. Weekly, `tests/ct-timing.js` times the fixture's functions
70
- * on real x86-64 and aarch64 hardware as well.
61
+ * at an address the scalar bit or a limb reaches.
62
+ *
63
+ * They are copies because the check refuses every branch, loop back-edges
64
+ * included, and this module's own functions keep their loops and the early
65
+ * `return`s below; the copies drop the guards and write `f25519Mul`'s outer
66
+ * loop out a row at a time, and the fixture's `main` holds them to the same RFC
67
+ * 7748 vectors as this module. A change to one of those functions belongs in
68
+ * that fixture too. What stays discipline rather than proof is the rest: the
69
+ * loops around the step, `f25519Decode`, `f25519Encode` and `f25519Invert`,
70
+ * whose branches are all on public positions. Weekly, `tests/ct-timing.js`
71
+ * times the fixture's functions on real x86-64 and aarch64 hardware as well.
71
72
  *
72
73
  * **Loop bounds are literals.** A field element is always ten limbs and an
73
74
  * encoding always 32 bytes, and each function that indexes one opens with an
@@ -29,17 +29,18 @@
29
29
  * must be definite and minimal (no `0x80`, no long form below 128, no leading
30
30
  * zero length octet), an INTEGER must be minimal in two's complement, a tag
31
31
  * must fit in one octet, every element must end inside its parent, and a
32
- * certificate must end where its outer SEQUENCE does. Anything else answers
33
- * `null`, never a panic. The reader takes the version, serial, algorithms,
34
- * the issuer and subject Names (their RDNs checked, their bytes kept whole),
35
- * validity, the subject public key and the signature, checks the order of what
36
- * follows the key (`[1]`, `[2]`, `[3]`), and decodes the extensions a path
37
- * validator needs: subjectAltName, basicConstraints, keyUsage, extKeyUsage,
38
- * nameConstraints and the two key identifiers. A duplicate or malformed one
39
- * refuses the certificate, and any other critical one sets `unknownCritical`.
40
- * It parses and does not validate: applying these to a chain is RFC 5280 §6
41
- * path validation, which `nish/crypto/pki`'s `pkiVerifyServer` does. The mint
42
- * writes two extensions of its own (below).
32
+ * certificate must end where its outer SEQUENCE does.
33
+ *
34
+ * Anything else answers `null`, never a panic. The reader takes the version,
35
+ * serial, algorithms, the issuer and subject Names (their RDNs checked, their
36
+ * bytes kept whole), validity, the subject public key and the signature, checks
37
+ * the order of what follows the key (`[1]`, `[2]`, `[3]`), and decodes the
38
+ * extensions a path validator needs: subjectAltName, basicConstraints,
39
+ * keyUsage, extKeyUsage, nameConstraints and the two key identifiers. A
40
+ * duplicate or malformed one refuses the certificate, and any other critical
41
+ * one sets `unknownCritical`. It parses and does not validate: applying these
42
+ * to a chain is RFC 5280 §6 path validation, which `nish/crypto/pki`'s
43
+ * `pkiVerifyServer` does. The mint writes two extensions of its own (below).
43
44
  *
44
45
  * **PEM is RFC 7468's strict grammar**, with standard base64 (`+` and `/`,
45
46
  * padded with `=`), not `base64url`: 64 characters a line and a shorter last
@@ -52,44 +53,47 @@
52
53
  * `serverCertificateHashes` accepts (W3C WebTransport, "custom certificate
53
54
  * requirements"): X.509 v3, an ECDSA P-256 key signed with ecdsa-with-SHA256,
54
55
  * and a validity period of at most fourteen days — `notAfter - notBefore`,
55
- * which is what Chromium compares, so `days` is 1 to 14. Subject and issuer
56
- * are the same single common name, as a UTF8String. It carries **two
57
- * extensions, both critical and both constant**: basicConstraints with cA
58
- * FALSE and keyUsage with digitalSignature alone. The W3C text requires no
59
- * extension, but Chromium does: the verifier behind `serverCertificateHashes`,
60
- * quiche's `WebTransportFingerprintProofVerifier`, parses the certificate
61
- * with `CertificateView::ParseSingleCertificate` before it compares the hash,
62
- * and that answers null when `[3] extensions` is absent
63
- * (`quiche/quic/core/crypto/certificate_view.cc:395`, at the quiche revision
64
- * 62826931 Chromium 141 pins), so the handshake fails with
65
- * CERTIFICATE_VERIFY_FAILED. It also holds every extension to `SEQUENCE {
66
- * OID, BOOLEAN OPTIONAL, OCTET STRING }` (`:413`–`:432`) and reads
67
- * subjectAltName only when one is present (`:434`), so no name is needed
68
- * there. The two chosen say what the certificate is, an end entity whose key
69
- * only signs handshakes, so a verifier that does build a path need not fall
70
- * back on its defaults; OpenSSL verifies it as its own trust anchor
71
- * (`tests/link/crypto_x509`'s header has the commands; X509-9 in
72
- * docs/security/crypto-x509.md). The key, the serial and the time are
73
- * parameters so the golden certificate is deterministic; a caller passes
74
- * `Date.now()` and, for the key and the serial, bytes from
75
- * `crypto.getRandomValues`. This module does not draw them itself,
76
- * because a call to the operating system would stop it compiling for wasm32;
77
- * `nish/crypto/x509-random`, which this module does not import, draws both
78
- * for a native program (X509-6).
56
+ * which is what Chromium compares, so `days` is 1 to 14. Subject and issuer are
57
+ * the same single common name, as a UTF8String. It carries **two extensions,
58
+ * both critical and both constant**: basicConstraints with cA FALSE and
59
+ * keyUsage with digitalSignature alone.
60
+ *
61
+ * The W3C text requires no extension, but Chromium does: the verifier behind
62
+ * `serverCertificateHashes`, quiche's `WebTransportFingerprintProofVerifier`,
63
+ * parses the certificate with `CertificateView::ParseSingleCertificate` before
64
+ * it compares the hash, and that answers null when `[3] extensions` is absent
65
+ * (`quiche/quic/core/crypto/certificate_view.cc:395`, at the quiche revision
66
+ * 62826931 Chromium 141 pins), so the handshake fails with
67
+ * CERTIFICATE_VERIFY_FAILED. It also holds every extension to `SEQUENCE { OID,
68
+ * BOOLEAN OPTIONAL, OCTET STRING }` (`:413`–`:432`) and reads subjectAltName
69
+ * only when one is present (`:434`), so no name is needed there.
70
+ *
71
+ * The two chosen say what the certificate is, an end entity whose key only
72
+ * signs handshakes, so a verifier that does build a path need not fall back on
73
+ * its defaults; OpenSSL verifies it as its own trust anchor
74
+ * (`tests/link/crypto_x509`'s header has the commands; X509-9 in
75
+ * docs/security/crypto-x509.md). The key, the serial and the time are
76
+ * parameters so the golden certificate is deterministic; a caller passes
77
+ * `Date.now()` and, for the key and the serial, bytes from
78
+ * `crypto.getRandomValues`. This module does not draw them itself, because a
79
+ * call to the operating system would stop it compiling for wasm32;
80
+ * `nish/crypto/x509-random`, which this module does not import, draws both for
81
+ * a native program (X509-6).
79
82
  *
80
83
  * **Constant time.** A private key is the one secret that passes through here:
81
84
  * it is base64-decoded from PEM, lifted out of its DER, and handed to
82
85
  * `nish/crypto/p256`. Base64 is `nish/crypto/base64url`'s `base64StdPadDecode`,
83
86
  * which maps a character to its sextet by arithmetic on range masks and folds a
84
87
  * bad character into one word read after the whole text, so neither a branch
85
- * nor a table index depends on the key's bytes. PEM's framing is found by comparing
86
- * the start of each line with the fixed `-----BEGIN ` and `-----END `, which no
87
- * base64 character matches, so those comparisons end on a line's first byte
88
- * whatever the key is. The DER reader branches on tags and
89
- * lengths, which are the key's public framing, and copies its 32 octets with a
90
- * fixed loop. Signing is `p256SignSha256`, and checking a key against the
91
- * public key stored beside it compares public values. None of this is under
92
- * the disassembly check; it is discipline.
88
+ * nor a table index depends on the key's bytes.
89
+ *
90
+ * PEM's framing is found by comparing the start of each line with the fixed
91
+ * `-----BEGIN ` and `-----END `, which no base64 character matches, so those
92
+ * comparisons end on a line's first byte whatever the key is. The DER reader
93
+ * branches on tags and lengths, which are the key's public framing, and copies
94
+ * its 32 octets with a fixed loop. Signing is `p256SignSha256`, and checking a
95
+ * key against the public key stored beside it compares public values. None of
96
+ * this is under the disassembly check; it is discipline.
93
97
  *
94
98
  * **The private key is a `Secret`** (`nish:secret`, docs/LANGUAGE.md
95
99
  * "Secrets"). `x509ParseP256PrivateKey` answers one and `x509MintSelfSigned`
@@ -2016,17 +2020,19 @@ const x509ReadExtensions = (der: u8[], e: X509DerElement, out: X509Certificate):
2016
2020
  }
2017
2021
 
2018
2022
  /**
2019
- * `der` read as one Certificate (RFC 5280 §4.1), or `null` unless it is
2020
- * exactly one in DER: `SEQUENCE { tbsCertificate, signatureAlgorithm,
2021
- * signatureValue }`, where tbsCertificate holds an explicit version of v2 or
2022
- * v3 or none (DER omits v1, the default), a minimal serial, an algorithm equal
2023
- * to the outer one byte for byte (§4.1.1.2), issuer and subject Names, a
2024
- * Validity of two valid times, a SubjectPublicKeyInfo whose key is whole
2025
- * octets, then only the optional `[1]` and `[2]` unique identifiers (v2 and
2026
- * v3) and `[3]` extensions (v3), in that order. Issuer and subject must be
2027
- * sound Names. The signature algorithm is named in `sigAlg` (with `pssHash`
2028
- * and `pssSaltLen` for RSA-PSS) and the key in `keyType`; `p256` and
2029
- * `ecdsaSha256` say whether they are the ones `x509VerifySignature` checks.
2023
+ * `der` read as one Certificate (RFC 5280 §4.1), or `null` unless it is exactly
2024
+ * one in DER: `SEQUENCE { tbsCertificate, signatureAlgorithm, signatureValue
2025
+ * }`, where tbsCertificate holds an explicit version of v2 or v3 or none (DER
2026
+ * omits v1, the default), a minimal serial, an algorithm equal to the outer one
2027
+ * byte for byte (§4.1.1.2), issuer and subject Names, a Validity of two valid
2028
+ * times, a SubjectPublicKeyInfo whose key is whole octets, then only the
2029
+ * optional `[1]` and `[2]` unique identifiers (v2 and v3) and `[3]` extensions
2030
+ * (v3), in that order.
2031
+ *
2032
+ * Issuer and subject must be sound Names. The signature algorithm is named in
2033
+ * `sigAlg` (with `pssHash` and `pssSaltLen` for RSA-PSS) and the key in
2034
+ * `keyType`; `p256` and `ecdsaSha256` say whether they are the ones
2035
+ * `x509VerifySignature` checks.
2030
2036
  *
2031
2037
  * Extensions are read: subjectAltName, basicConstraints, keyUsage,
2032
2038
  * extKeyUsage, nameConstraints and the two key identifiers are decoded into
@@ -2261,14 +2267,15 @@ const x509MintExtensions = (): u8[] => [
2261
2267
  * and issuer `CN=commonName`, valid from `notBeforeMs` (milliseconds since
2262
2268
  * 1970, rounded down to the second) for exactly `days` days, serial number
2263
2269
  * `serial`, carrying `x509MintExtensions`' basicConstraints and keyUsage, and
2264
- * signed with ecdsa-with-SHA256 — see the module comment for why Chromium
2265
- * needs an extension at all. `null` when `days` is below 1 or above
2266
- * `X509_MAX_DAYS`, `notBeforeMs` is negative or the validity would end after
2267
- * 9999, `commonName` is empty, longer than 64 bytes, not UTF-8 or holds a NUL
2268
- * (it is written as a UTF8String), `priv` is not a P-256 private key, or
2269
- * `serial` — big-endian, leading zeros ignored — is zero or
2270
- * needs more than `X509_MAX_SERIAL` octets as a positive INTEGER (clear the top
2271
- * bit of 20 random bytes, or use fewer).
2270
+ * signed with ecdsa-with-SHA256 — see the module comment for why Chromium needs
2271
+ * an extension at all.
2272
+ *
2273
+ * `null` when `days` is below 1 or above `X509_MAX_DAYS`, `notBeforeMs` is
2274
+ * negative or the validity would end after 9999, `commonName` is empty, longer
2275
+ * than 64 bytes, not UTF-8 or holds a NUL (it is written as a UTF8String),
2276
+ * `priv` is not a P-256 private key, or `serial` — big-endian, leading zeros
2277
+ * ignored — is zero or needs more than `X509_MAX_SERIAL` octets as a positive
2278
+ * INTEGER (clear the top bit of 20 random bytes, or use fewer).
2272
2279
  *
2273
2280
  * @param priv The 32-byte P-256 private scalar, big-endian; read, and left for the caller to wipe.
2274
2281
  * @param commonName The subject's and issuer's common name, 1 to 64 bytes of UTF-8 without a NUL.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * `nish/host/ring` — a single-producer, single-consumer ring of `i32` words
3
+ * over module storage, shared by a wasm module and the page that drives it
4
+ * (`docs/wp50-wasm-host.md` §11).
5
+ *
6
+ * The ring is an `Int32Array` the program declares as module storage, so the
7
+ * page reaches the same words through the `Layout` the loader hands it:
8
+ *
9
+ * import { ringShift, ringSize } from "nish/host/ring";
10
+ *
11
+ * const INPUT = new Int32Array(2 + 64); // head, tail, then 64 slots
12
+ *
13
+ * export function tick(): void {
14
+ * while (ringSize(INPUT) > 0) {
15
+ * steer(ringShift(INPUT));
16
+ * }
17
+ * }
18
+ *
19
+ * Word 0 is the **head** and word 1 the **tail**, each a count of words taken
20
+ * and put kept modulo twice the capacity (the length less two), so neither
21
+ * overflows and `tail - head` (modulo the same) is the number waiting: 0 is
22
+ * empty and the capacity is full. Slot `count % capacity` holds the word put
23
+ * at that count. One side only advances the tail and the other only the head:
24
+ * that is the whole protocol, and it needs no atomics because the page and the
25
+ * module run on one thread and never at once. `nish/page`'s `ringOver` is the
26
+ * page's half, over the same layout and arithmetic.
27
+ *
28
+ * A zero-filled ring (what module storage starts as) is empty. A ring whose
29
+ * counts a buggy page wrote out of protocol is still never read out of
30
+ * bounds: each count is reduced modulo twice the capacity before it is used,
31
+ * and a size past the capacity reads as full, so `ringPush` refuses and
32
+ * `ringShift` takes words until the counts agree again.
33
+ */
34
+
35
+ /** Head, tail: the two words in front of the slots. */
36
+ const RING_HEADER: i32 = 2
37
+
38
+ /**
39
+ * The number of slots, the ring's length less its header.
40
+ *
41
+ * @param ring - the ring's storage: head, tail, then its slots
42
+ * @returns the slot count, or 0 for a ring too short to have one
43
+ */
44
+ export const ringCapacity = (ring: Int32Array): i32 => {
45
+ const length: i32 = toI32(ring.length)
46
+ return length > RING_HEADER ? length - RING_HEADER : 0
47
+ }
48
+
49
+ /** `count` brought into `[0, 2 * capacity)`, whatever a page wrote there. */
50
+ const ringCount = (count: i32, capacity: i32): i32 => {
51
+ const m: i32 = capacity * 2
52
+ const r: i32 = count % m
53
+ return r < 0 ? r + m : r
54
+ }
55
+
56
+ /**
57
+ * The number of words put and not yet taken.
58
+ *
59
+ * @param ring - the ring's storage: head, tail, then its slots
60
+ * @returns the words waiting, at most the capacity
61
+ */
62
+ export const ringSize = (ring: Int32Array): i32 => {
63
+ const capacity: i32 = ringCapacity(ring)
64
+ if (capacity === 0) {
65
+ return 0
66
+ }
67
+ const size: i32 = ringCount(ringCount(ring[1], capacity) - ringCount(ring[0], capacity), capacity)
68
+ return size > capacity ? capacity : size
69
+ }
70
+
71
+ /**
72
+ * The number of words `ringPush` would still take.
73
+ *
74
+ * @param ring - the ring's storage: head, tail, then its slots
75
+ * @returns the free slots
76
+ */
77
+ export const ringFree = (ring: Int32Array): i32 => ringCapacity(ring) - ringSize(ring)
78
+
79
+ /**
80
+ * Puts `word` at the tail, or changes nothing when the ring is full.
81
+ *
82
+ * @param ring - the ring's storage: head, tail, then its slots
83
+ * @param word - the word to put
84
+ * @returns true when the word was put, false when the ring was full
85
+ */
86
+ export const ringPush = (ring: Int32Array, word: i32): boolean => {
87
+ const capacity: i32 = ringCapacity(ring)
88
+ if (capacity === 0 || ringSize(ring) >= capacity) {
89
+ return false
90
+ }
91
+ const tail: i32 = ringCount(ring[1], capacity)
92
+ ring[RING_HEADER + (tail % capacity)] = word
93
+ ring[1] = ringCount(tail + 1, capacity)
94
+ return true
95
+ }
96
+
97
+ /**
98
+ * Takes the word at the head. On an empty ring it answers 0 and changes
99
+ * nothing, so a caller that cannot tell 0 from empty asks `ringSize` first.
100
+ *
101
+ * @param ring - the ring's storage: head, tail, then its slots
102
+ * @returns the word taken, or 0 on an empty ring
103
+ */
104
+ export const ringShift = (ring: Int32Array): i32 => {
105
+ const capacity: i32 = ringCapacity(ring)
106
+ if (capacity === 0 || ringSize(ring) === 0) {
107
+ return 0
108
+ }
109
+ const head: i32 = ringCount(ring[0], capacity)
110
+ const word: i32 = ring[RING_HEADER + (head % capacity)]
111
+ ring[0] = ringCount(head + 1, capacity)
112
+ return word
113
+ }
114
+
115
+ /**
116
+ * Empties the ring: the head catches up with the tail, and the slots keep their stale words.
117
+ *
118
+ * @param ring - the ring's storage: head, tail, then its slots
119
+ */
120
+ export const ringClear = (ring: Int32Array): void => {
121
+ if (toI32(ring.length) >= RING_HEADER) {
122
+ ring[0] = ring[1]
123
+ }
124
+ }
package/std/json-equal.ts CHANGED
@@ -25,17 +25,18 @@
25
25
  * built with `push` and `set` deeper than any parser allows compares as well
26
26
  * as a flat one, and nothing recurses.
27
27
  *
28
- * **What a call costs.** `jsonEqual` stops at the first difference. Up to
29
- * there it is linear in the values' size, except that each pair of objects
30
- * reads every key (one string each) and sorts them, `n log n` for `n`
31
- * members; it also allocates one string per string value, its stack, and
32
- * whatever `jsonNumberCompare` allocates per number pair. `jsonEqualCanonical`
33
- * builds the canonical text, about the size of the value written as JSON,
34
- * and sorts keys the same way. `jsonEqualHash` is FNV-1a of that text's
35
- * units: its bytes natively, its code units under Node. Every order and
36
- * length below is in those units too.
37
- * `jsonEqualFirstDuplicate` makes the canonical text of every element up to
38
- * the first repeat and keeps them in a `Map`.
28
+ * **What a call costs.** `jsonEqual` stops at the first difference. Up to there
29
+ * it is linear in the values' size, except that each pair of objects reads
30
+ * every key (one string each) and sorts them, `n log n` for `n` members; it
31
+ * also allocates one string per string value, its stack, and whatever
32
+ * `jsonNumberCompare` allocates per number pair. `jsonEqualCanonical` builds
33
+ * the canonical text, about the size of the value written as JSON, and sorts
34
+ * keys the same way. `jsonEqualHash` is FNV-1a of that text's units: its bytes
35
+ * natively, its code units under Node.
36
+ *
37
+ * Every order and length below is in those units too. `jsonEqualFirstDuplicate`
38
+ * makes the canonical text of every element up to the first repeat and keeps
39
+ * them in a `Map`.
39
40
  *
40
41
  * **The hash is not keyed.** FNV-1a (public domain) is the same in every
41
42
  * process, so an attacker can make many values that share a hash, and a
@@ -19,18 +19,18 @@
19
19
  * grammar exactly (what `JsonDocument.numberText` answers); anything else is
20
20
  * `JSON_NUMBER_ERR_SYNTAX`.
21
21
  *
22
- * **What a call costs.** `jsonNumberCompare` reads each text once and
23
- * allocates two records of a few fields, nothing in proportion to the text:
24
- * time is linear in the texts' lengths. `jsonNumberCanonical` allocates the
25
- * string it answers, at most the text's length plus an exponent.
26
- * `jsonNumberMultipleOf` divides the value's digits, followed by as many
27
- * zeros as its exponent is above the divisor's (the gap), by the divisor's
28
- * digits: one step per digit of that dividend when the divisor has at most 18
29
- * significant digits, and one per digit of the dividend per digit of the
30
- * divisor otherwise, which then also allocates the remainder, one byte per
31
- * divisor digit. A step of that long division is a shift, up to ten
32
- * comparisons and up to nine subtractions of a byte each, so about twenty
33
- * byte operations.
22
+ * **What a call costs.** `jsonNumberCompare` reads each text once and allocates
23
+ * two records of a few fields, nothing in proportion to the text: time is
24
+ * linear in the texts' lengths. `jsonNumberCanonical` allocates the string it
25
+ * answers, at most the text's length plus an exponent.
26
+ *
27
+ * `jsonNumberMultipleOf` divides the value's digits, followed by as many zeros
28
+ * as its exponent is above the divisor's (the gap), by the divisor's digits:
29
+ * one step per digit of that dividend when the divisor has at most 18
30
+ * significant digits, and one per digit of the dividend per digit of the
31
+ * divisor otherwise, which then also allocates the remainder, one byte per
32
+ * divisor digit. A step of that long division is a shift, up to ten comparisons
33
+ * and up to nine subtractions of a byte each, so about twenty byte operations.
34
34
  *
35
35
  * **The bounds are stated.** An exponent is at most `JSON_NUMBER_MAX_EXPONENT`
36
36
  * in size, which keeps every exponent sum far inside `i64`, and past