@amritk/nish-aarch64-linux 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
package/std/crypto/aes.ts CHANGED
@@ -40,49 +40,53 @@
40
40
  * `q[0..7]`, word `b` holding bit `b` of all 64 bytes. Inside a word, block `k`
41
41
  * owns the 16 bits from `16k`, and in those the byte in row `r` and column `c`
42
42
  * of the AES state is bit `4r + c`: each row is one nibble. That makes the two
43
- * permutations cheap. ShiftRows turns row `r` by `r` columns, which is a
44
- * rotation of nibble `r` by `r` bits; MixColumns needs each byte's neighbour
45
- * in the next row of its column, which is the word rotated by four bits inside
46
- * each 16-bit lane. Getting 64 bytes in and out of that layout is an 8 × 8
47
- * bit-matrix transpose per byte lane (`aesTranspose`, three rounds of masked
48
- * swaps between words) after placing each byte in the word and slot the
49
- * transpose will carry to its bit (`aesPack`, `aesUnpack`).
43
+ * permutations cheap.
44
+ *
45
+ * ShiftRows turns row `r` by `r` columns, which is a rotation of nibble `r` by
46
+ * `r` bits; MixColumns needs each byte's neighbour in the next row of its
47
+ * column, which is the word rotated by four bits inside each 16-bit lane.
48
+ * Getting 64 bytes in and out of that layout is an 8 × 8 bit-matrix transpose
49
+ * per byte lane (`aesTranspose`, three rounds of masked swaps between words)
50
+ * after placing each byte in the word and slot the transpose will carry to its
51
+ * bit (`aesPack`, `aesUnpack`).
50
52
  *
51
53
  * **Constant time.** No table is read anywhere, key schedule included: the
52
- * S-box is the circuit, and `SubWord` in the key schedule runs the same
53
- * circuit on a four-byte state. No branch or index depends on a key, a
54
- * plaintext, a tag or H: every `if` and every loop bound is on a length, a
55
- * block number or the round count. GHASH multiplies with no table and no
56
- * data-dependent shift, and `aesGcmOpen` computes the whole tag and compares
57
- * it with `aesGcmTagMask` — a difference ORed into one word and handed to
58
- * `ctEq` — before it decrypts or returns anything. What `tests/ct-asm.js`
59
- * verifies by disassembly on x86-64 and aarch64 is one full round
60
- * (`aesBitslicedRound`: S-box circuit, ShiftRows, MixColumns, AddRoundKey),
61
- * one GHASH multiply (`ghashMultiply`) and the tag compare
62
- * (`aesGcmTagMask`). A golden case compiles to one module and cannot import
63
- * this one, so `tests/cases/ct_asm_aes` holds a verbatim copy of those three
64
- * and the helpers they call, and `tests/link/crypto_aes` checks that the copy
65
- * and this module agree on generated inputs, so neither can drift from the
66
- * other unnoticed. Everything around them — packing bytes, the key schedule,
67
- * the loops over blocks — is the discipline above and not a verified
68
- * property.
54
+ * S-box is the circuit, and `SubWord` in the key schedule runs the same circuit
55
+ * on a four-byte state. No branch or index depends on a key, a plaintext, a tag
56
+ * or H: every `if` and every loop bound is on a length, a block number or the
57
+ * round count.
58
+ *
59
+ * GHASH multiplies with no table and no data-dependent shift, and `aesGcmOpen`
60
+ * computes the whole tag and compares it with `aesGcmTagMask` — a difference
61
+ * ORed into one word and handed to `ctEq` — before it decrypts or returns
62
+ * anything. What `tests/ct-asm.js` verifies by disassembly on x86-64 and
63
+ * aarch64 is one full round (`aesBitslicedRound`: S-box circuit, ShiftRows,
64
+ * MixColumns, AddRoundKey), one GHASH multiply (`ghashMultiply`) and the tag
65
+ * compare (`aesGcmTagMask`).
66
+ *
67
+ * A golden case compiles to one module and cannot import this one, so
68
+ * `tests/cases/ct_asm_aes` holds a verbatim copy of those three and the helpers
69
+ * they call, and `tests/link/crypto_aes` checks that the copy and this module
70
+ * agree on generated inputs, so neither can drift from the other unnoticed.
71
+ * Everything around them — packing bytes, the key schedule, the loops over
72
+ * blocks — is the discipline above and not a verified property.
69
73
  *
70
74
  * **The seams.** Four private functions do nearly all of the cipher's work,
71
75
  * each called from exactly one place: `aesScheduleInto` (the key schedule),
72
76
  * `aesBlockInto` (one block), `aesCtrInto` (GCTR over a run of bytes) and
73
77
  * `ghashBlocksInto` (GHASH over a run of bytes). Each takes the arrays its
74
- * caller passes, writes into them and allocates nothing the caller needs
75
- * back, and its one caller checks every precondition it names first. That is
76
- * what lets the compiler, natively, put each of those four calls behind a
77
- * branch on the runtime's `nish_aes_hw` (`src/kernels.ts`, lowered in
78
- * `src/emit.ts`): on a CPU with AES-NI and PCLMULQDQ, or the ARMv8 AES and
79
- * PMULL instructions, the call goes to a kernel in `runtime/runtime-aes.c`
80
- * that does no bounds checks of its own; on any other CPU, under
81
- * `NISH_AES=soft`, on wasm32 and under Node, the body here runs (WP38 S5,
82
- * `docs/wp38-simd.md`). The bodies are the bitsliced code, and keep their
83
- * own defensive checks. The kernel keeps its own layout in a key's
84
- * `roundKeys`, which a process only ever reads under the one answer
85
- * `nish_aes_hw` gives it.
78
+ * caller passes, writes into them and allocates nothing the caller needs back,
79
+ * and its one caller checks every precondition it names first.
80
+ *
81
+ * That is what lets the compiler, natively, put each of those four calls behind
82
+ * a branch on the runtime's `nish_aes_hw` (`src/kernels.ts`, lowered in
83
+ * `src/emit.ts`): on a CPU with AES-NI and PCLMULQDQ, or the ARMv8 AES and
84
+ * PMULL instructions, the call goes to a kernel in `runtime/runtime-aes.c` that
85
+ * does no bounds checks of its own; on any other CPU, under `NISH_AES=soft`, on
86
+ * wasm32 and under Node, the body here runs (WP38 S5, `docs/wp38-simd.md`). The
87
+ * bodies are the bitsliced code, and keep their own defensive checks. The
88
+ * kernel keeps its own layout in a key's `roundKeys`, which a process only ever
89
+ * reads under the one answer `nish_aes_hw` gives it.
86
90
  *
87
91
  * What runs outside the seams, and so on the bitsliced code whichever way
88
92
  * they go: `ghashLengths`, the last GHASH block of every tag, and so the end
@@ -756,13 +760,14 @@ export const aesKey = (key: u8[]): AesKey | null => {
756
760
  * arena scope may be put around; this stores numbers only, so a caller that
757
761
  * keeps one `AesKey` per connection installs every key inside a `using a =
758
762
  * arena()` block and leaves the arena where it was. The schedule and H are
759
- * secret: the caller hands `out` to `aesKeyWipe` when it is done with the
760
- * key. The schedule is written straight into `out.roundKeys`, and the
761
- * working copies the bitsliced schedule and the block H passes through are
762
- * wiped with `wipe`'s volatile stores before they are released. On a CPU
763
- * that runs the runtime's kernels (the seams, in the module docs) those
764
- * copies are the kernels' own, in `runtime/runtime-aes.c`, and what they
765
- * leave in vector registers no wipe here reaches.
763
+ * secret: the caller hands `out` to `aesKeyWipe` when it is done with the key.
764
+ *
765
+ * The schedule is written straight into `out.roundKeys`, and the working copies
766
+ * the bitsliced schedule and the block H passes through are wiped with `wipe`'s
767
+ * volatile stores before they are released. On a CPU that runs the runtime's
768
+ * kernels (the seams, in the module docs) those copies are the kernels' own, in
769
+ * `runtime/runtime-aes.c`, and what they leave in vector registers no wipe here
770
+ * reaches.
766
771
  *
767
772
  * `aesKey` makes its key through this, so this is the one call of
768
773
  * `aesScheduleInto`, and the checks its contract needs are made here.
@@ -31,11 +31,13 @@
31
31
  * **Neither direction indexes or branches on the data.** What is encoded here
32
32
  * is usually a key, a nonce or a MAC, and a lookup table indexed by a secret
33
33
  * sextet leaves its trace in the cache. So a sextet becomes a character, and a
34
- * character a sextet, by arithmetic on range masks: `(lo - 1 - c) & (c - hi - 1)`
35
- * is negative exactly when `lo <= c <= hi`, and an arithmetic shift by 31 turns
36
- * that sign into an all-ones or all-zeros mask. A malformed character is not
37
- * refused where it is found either: the verdict is ORed into one word and read
38
- * once, after the whole text. The text's length is public and is tested first.
34
+ * character a sextet, by arithmetic on range masks: `(lo - 1 - c) & (c - hi -
35
+ * 1)` is negative exactly when `lo <= c <= hi`, and an arithmetic shift by 31
36
+ * turns that sign into an all-ones or all-zeros mask.
37
+ *
38
+ * A malformed character is not refused where it is found either: the verdict is
39
+ * ORed into one word and read once, after the whole text. The text's length is
40
+ * public and is tested first.
39
41
  *
40
42
  * Private helpers share the importing program's flat symbol namespace
41
43
  * (`docs/wp26-stdlib.md` §3e), which is why each one carries the module's name.
@@ -22,19 +22,19 @@
22
22
  * itself; this module holds them until there are enough, or until a short
23
23
  * window has passed.
24
24
  *
25
- * **When a batch is sent.** `run(now)` sends work when the queue holds at
26
- * least `width` requests, or when the oldest has waited `holdNanos`; a hold
27
- * of 0 sends whatever is queued at every `run`. It takes at most
28
- * `width × cores` requests a run, the oldest first, and spreads them evenly
29
- * over `min(cores, taken)` tasks, each running its share as one batch, so a
30
- * run takes about one batch's time and the event loop gets control back
31
- * between runs. Spreading rather than filling is deliberate: while a run is
32
- * going nothing else can use the free cores, and a batch of two on each of
33
- * three cores ends sooner than one of six on one. Under load the requests
34
- * that arrive during a run fill the next one, so the batches fill on their
35
- * own; at light load each request runs alone on a core, as a task per login
36
- * would. `waitNanos(now)` says how long the loop may sleep before a `run` is
37
- * due.
25
+ * **When a batch is sent.** `run(now)` sends work when the queue holds at least
26
+ * `width` requests, or when the oldest has waited `holdNanos`; a hold of 0
27
+ * sends whatever is queued at every `run`. It takes at most `width × cores`
28
+ * requests a run, the oldest first, and spreads them evenly over `min(cores,
29
+ * taken)` tasks, each running its share as one batch, so a run takes about one
30
+ * batch's time and the event loop gets control back between runs.
31
+ *
32
+ * Spreading rather than filling is deliberate: while a run is going nothing
33
+ * else can use the free cores, and a batch of two on each of three cores ends
34
+ * sooner than one of six on one. Under load the requests that arrive during a
35
+ * run fill the next one, so the batches fill on their own; at light load each
36
+ * request runs alone on a core, as a task per login would. `waitNanos(now)`
37
+ * says how long the loop may sleep before a `run` is due.
38
38
  *
39
39
  * **`run` blocks.** It opens a scope, runs the shares, one on the calling
40
40
  * thread, and returns once every share has finished: about one batch, 60–95
@@ -18,13 +18,15 @@
18
18
  * passwords (lane 0 always, a null lane skipped) and run their Blowfish
19
19
  * encryptions interleaved in one loop, so one core does the work of several
20
20
  * hashes in well under the time of as many; each result is the single path's,
21
- * byte for byte. `bcryptVerifyN` groups lanes by the cost their hash names,
22
- * and a malformed hash in any lane is an `Err` for the whole call, naming the
23
- * lane, before anything is hashed. `bcryptHash4` and `bcryptVerify4` are the
24
- * same for up to four. Which width is fastest depends on the core (how many
25
- * loads it issues a cycle, how much L1 the states fill), so `bcryptCalibrate`
26
- * measures it: it times widths one to six at cost 4 on throwaway passwords
27
- * and answers the one with the least time per hash. Call it once, at startup.
21
+ * byte for byte. `bcryptVerifyN` groups lanes by the cost their hash names, and
22
+ * a malformed hash in any lane is an `Err` for the whole call, naming the lane,
23
+ * before anything is hashed. `bcryptHash4` and `bcryptVerify4` are the same for
24
+ * up to four.
25
+ *
26
+ * Which width is fastest depends on the core (how many loads it issues a cycle,
27
+ * how much L1 the states fill), so `bcryptCalibrate` measures it: it times
28
+ * widths one to six at cost 4 on throwaway passwords and answers the one with
29
+ * the least time per hash. Call it once, at startup.
28
30
  *
29
31
  * **The password is a `Secret<u8[]>`** (`nish:secret`). The key schedule and
30
32
  * the 2^cost rounds run inside `exposeWith`; the Blowfish state (the P-array
@@ -40,14 +42,17 @@
40
42
  * repeated until 72 bytes are taken: a password longer than 72 bytes hashes as
41
43
  * its first 72, and bytes after an embedded NUL are not read, as under
42
44
  * `crypt_r`; docs/security/crypto-bcrypt.md says why a longer password is cut
43
- * rather than refused. Bytes above 127 are unsigned, as `$2b$` and
44
- * `$2y$` define them. A `$2a$` hash gets crypt_blowfish's countermeasure for
45
- * the old sign-extension bug: when an 8-bit byte was sign-extended into a key
46
- * word and yet the buggy and the correct key came out equal, one bit of the
47
- * first P word is flipped, as crypt_blowfish flips it, so the `$2a$` digest of
48
- * such a password (`\xff\xff\xa3`) is not its `$2y$` one. It takes an 8-bit
49
- * byte after the first byte of a key word with only 0xff bytes before it, every
50
- * such byte in all 18 words being so placed, which UTF-8 never holds. `$2x$` (the bug itself) is refused.
45
+ * rather than refused. Bytes above 127 are unsigned, as `$2b$` and `$2y$`
46
+ * define them.
47
+ *
48
+ * A `$2a$` hash gets crypt_blowfish's countermeasure for the old sign-extension
49
+ * bug: when an 8-bit byte was sign-extended into a key word and yet the buggy
50
+ * and the correct key came out equal, one bit of the first P word is flipped,
51
+ * as crypt_blowfish flips it, so the `$2a$` digest of such a password
52
+ * (`\xff\xff\xa3`) is not its `$2y$` one. It takes an 8-bit byte after the
53
+ * first byte of a key word with only 0xff bytes before it, every such byte in
54
+ * all 18 words being so placed, which UTF-8 never holds. `$2x$` (the bug
55
+ * itself) is refused.
51
56
  *
52
57
  * **Errors are `Err`s.** A salt that is not 16 bytes, a cost outside 4–31, or
53
58
  * a hash string that is not one (the wrong length, an unknown prefix, a cost
@@ -70,18 +75,19 @@
70
75
  * milliseconds of one core; a server runs it off its event loop, on a task
71
76
  * (docs/guide/using-nish/password-hashing.md).
72
77
  *
73
- * The algorithm is Provos and Mazières's ("A Future-Adaptable Password
74
- * Scheme", USENIX 1999). The code is adapted from Solar Designer's
75
- * crypt_blowfish 1.3, which carries the notice below, and the 1042 initial
76
- * words, the hexadecimal digits of π, are its `BF_init_state`. Closest
77
- * upstream for each part: `bcryptInitState` is `BF_init_state`;
78
- * `bcryptEncrypt` and the rounds in `bcryptBody` are `BF_ENCRYPT`/`BF_ROUND`;
79
- * `bcryptBody` is `BF_body`; `bcryptSetKey` is `BF_set_key`; `bcryptDecodeSalt`
80
- * and `bcryptEncode` are `BF_decode` and `BF_encode`; `bcryptExposed` is the
81
- * part of `BF_crypt` after the setting is parsed, and `bcryptParse` that
82
- * parse. The state is one flat `u32[]` with P first (words 0–17) and the
83
- * S-boxes after (18–1041), so the body walks it in one pass, and every S-box
84
- * index is an `i32` masked to 0–255, which the checker proves in bounds
78
+ * The algorithm is Provos and Mazières's ("A Future-Adaptable Password Scheme",
79
+ * USENIX 1999). The code is adapted from Solar Designer's crypt_blowfish 1.3,
80
+ * which carries the notice below, and the 1042 initial words, the hexadecimal
81
+ * digits of π, are its `BF_init_state`. Closest upstream for each part:
82
+ * `bcryptInitState` is `BF_init_state`; `bcryptEncrypt` and the rounds in
83
+ * `bcryptBody` are `BF_ENCRYPT`/`BF_ROUND`; `bcryptBody` is `BF_body`;
84
+ * `bcryptSetKey` is `BF_set_key`; `bcryptDecodeSalt` and `bcryptEncode` are
85
+ * `BF_decode` and `BF_encode`; `bcryptExposed` is the part of `BF_crypt` after
86
+ * the setting is parsed, and `bcryptParse` that parse.
87
+ *
88
+ * The state is one flat `u32[]` with P first (words 0–17) and the S-boxes after
89
+ * (18–1041), so the body walks it in one pass, and every S-box index is an
90
+ * `i32` masked to 0–255, which the checker proves in bounds
85
91
  * (`BCRYPT_STATE_WORDS`). The magic-string encryption, the parsing and the
86
92
  * alphabet are separate functions so a several-lane kernel can share them.
87
93
  *
@@ -37,25 +37,27 @@
37
37
  * makes the arithmetic fit: a limb product is below 2^56, five of them sum
38
38
  * below 2^58, and 2^130 = 5 (mod p) folds the top of a product back into the
39
39
  * bottom as a multiply by five.
40
- * `poly1305Block` says why each sum fits. The reduction is by carries and
41
- * masks, and the final reduction into `[0, p)` picks between `h` and `h - p`
42
- * with `ctSelect` on a mask made from a borrow, never with a comparison.
40
+ *
41
+ * `poly1305Block` says why each sum fits. The reduction is by carries and
42
+ * masks, and the final reduction into `[0, p)` picks between `h` and `h - p`
43
+ * with `ctSelect` on a mask made from a borrow, never with a comparison.
43
44
  *
44
45
  * **Constant time.** Nothing branches on, or indexes by, a key, a keystream
45
46
  * word, the accumulator or a tag. Every `if` and every loop bound is on a
46
47
  * length, an offset or a block number, all of which the peer already knows.
47
48
  * `chacha20Poly1305Open` computes the tag over the received ciphertext and
48
- * compares all sixteen bytes by ORing their differences into one word before
49
- * it decrypts anything, and a mismatch is decided on that one word. Verified by
50
- * disassembly (`tests/cases/ct_asm_chacha20poly1305`, read by
51
- * `tests/ct-asm.js` for x86-64 and aarch64): the key clamp, one Poly1305 block
52
- * (the load, the multiply and the partial reduction), the final reduction and
53
- * the addition of `s`, and the tag compare, each straight-line with no
54
- * secret-addressed load. The fixture holds copies of those four functions,
55
- * because the check reads one compiled module; `tests/link/crypto_chacha20poly1305`
56
- * holds the copies to these originals. The ChaCha20 rounds and the loops that
57
- * drive both halves are discipline, not proof: the check refuses a loop's own
58
- * back-edge, so it cannot read them.
49
+ * compares all sixteen bytes by ORing their differences into one word before it
50
+ * decrypts anything, and a mismatch is decided on that one word.
51
+ *
52
+ * Verified by disassembly (`tests/cases/ct_asm_chacha20poly1305`, read by
53
+ * `tests/ct-asm.js` for x86-64 and aarch64): the key clamp, one Poly1305 block
54
+ * (the load, the multiply and the partial reduction), the final reduction and
55
+ * the addition of `s`, and the tag compare, each straight-line with no
56
+ * secret-addressed load. The fixture holds copies of those four functions,
57
+ * because the check reads one compiled module;
58
+ * `tests/link/crypto_chacha20poly1305` holds the copies to these originals. The
59
+ * ChaCha20 rounds and the loops that drive both halves are discipline, not
60
+ * proof: the check refuses a loop's own back-edge, so it cannot read them.
59
61
  *
60
62
  * Private names carry the `chacha20` / `poly1305` prefix because a `std/`
61
63
  * module's private functions share the importing program's flat symbol
@@ -37,20 +37,21 @@
37
37
  * is carried first, and so is every cached coordinate. The field functions
38
38
  * state their own bounds (`nish/crypto/x25519`).
39
39
  *
40
- * **Constant time, by construction.** Signing and the public key multiply
41
- * the base point by a secret scalar, and that multiplication branches on and
40
+ * **Constant time, by construction.** Signing and the public key multiply the
41
+ * base point by a secret scalar, and that multiplication branches on and
42
42
  * indexes by nothing the scalar reaches. The scalar is recoded into 64 signed
43
43
  * radix-16 digits in [-8, 8]; each step doubles four times and adds the table
44
- * entry for the digit, which is chosen by reading all eight entries and
45
- * keeping one under a mask, and negated with a masked swap and a masked
46
- * select. The digit arithmetic and the masks use `f25519Add64`, `f25519Sub64`
47
- * and `f25519Mul64`, because signed overflow is undefined and a checked
48
- * operation branches. The reductions mod L run a fixed 512 steps of a
49
- * shift and a masked conditional subtraction over 32-bit limbs in `u64`,
50
- * whose subtraction wraps. Every `if` and every loop bound is on a public
51
- * quantity: a digit position, a limb number, a bit position or a length.
52
- * This is discipline, checked by reading, not by a disassembly fixture as
53
- * `f25519Mul` and the X25519 ladder are (ECC-5, docs/security/crypto-ecc.md).
44
+ * entry for the digit, which is chosen by reading all eight entries and keeping
45
+ * one under a mask, and negated with a masked swap and a masked select.
46
+ *
47
+ * The digit arithmetic and the masks use `f25519Add64`, `f25519Sub64` and
48
+ * `f25519Mul64`, because signed overflow is undefined and a checked operation
49
+ * branches. The reductions mod L run a fixed 512 steps of a shift and a masked
50
+ * conditional subtraction over 32-bit limbs in `u64`, whose subtraction wraps.
51
+ * Every `if` and every loop bound is on a public quantity: a digit position, a
52
+ * limb number, a bit position or a length. This is discipline, checked by
53
+ * reading, not by a disassembly fixture as `f25519Mul` and the X25519 ladder
54
+ * are (ECC-5, docs/security/crypto-ecc.md).
54
55
  *
55
56
  * **Verification is variable time.** Every value `ed25519Verify` handles is
56
57
  * public — the key, the message and the signature — so it may branch on them:
@@ -62,10 +63,12 @@
62
63
  * below p or that is not on the curve, and an x of zero with the sign bit set
63
64
  * are all refused (§5.1.3). R is not decoded: [S]B - [k]A is encoded and
64
65
  * compared with R's bytes, and since the encoding is canonical, an R that is
65
- * not the canonical encoding of a point never matches. A public key of small
66
- * order is not refused, as RFC 8032 does not ask it to be: under such a key,
67
- * some signatures verify for messages its owner never signed, so a protocol
68
- * that needs a signature to bind one key checks the key itself.
66
+ * not the canonical encoding of a point never matches.
67
+ *
68
+ * A public key of small order is not refused, as RFC 8032 does not ask it to
69
+ * be: under such a key, some signatures verify for messages its owner never
70
+ * signed, so a protocol that needs a signature to bind one key checks the key
71
+ * itself.
69
72
  *
70
73
  * **The seed is a `Secret`** (`nish:secret`, docs/LANGUAGE.md "Secrets").
71
74
  * `ed25519PublicKey` and `ed25519Sign` take the 32-byte seed as a
@@ -934,13 +934,14 @@ const pbkdf2HmacSha256Exposed = (password: u8[], request: Pbkdf2Request): u8[] |
934
934
  * Bad input answers `null` and never panics: an iteration count or a length
935
935
  * below 1, or a password or salt longer than 2^31 - 1 bytes. The password is
936
936
  * read only inside `exposeWith`, and every U_j, every T_i, both keyed hashers
937
- * and the working one are wiped before the key is answered; the digests on
938
- * the way are wiped in the call that made them. The time taken depends on
937
+ * and the working one are wiped before the key is answered; the digests on the
938
+ * way are wiped in the call that made them. The time taken depends on
939
939
  * `iterations`, `dkLen` and the password's length past a block, all of which
940
- * RFC 8018 treats as public, and on nothing of the password's bytes. The time
941
- * is linear in `iterations` and nothing here bounds it, so a caller that takes
942
- * the count from an untrusted peer (a SCRAM server's `i=`) must cap it first:
943
- * 2^31 - 1 rounds is about 2^32 compressions.
940
+ * RFC 8018 treats as public, and on nothing of the password's bytes.
941
+ *
942
+ * The time is linear in `iterations` and nothing here bounds it, so a caller
943
+ * that takes the count from an untrusted peer (a SCRAM server's `i=`) must cap
944
+ * it first: 2^31 - 1 rounds is about 2^32 compressions.
944
945
  *
945
946
  * @param password The password P, read only inside `exposeWith`; the caller
946
947
  * still owns and wipes it.
package/std/crypto/jwt.ts CHANGED
@@ -27,14 +27,15 @@
27
27
  *
28
28
  * **The key decides the algorithm, never the token.** A `JwtKey` is made for
29
29
  * one algorithm, and a token verifies only when its header's `alg` is that
30
- * algorithm's name, spelled exactly. `none` names no key, so a token that
31
- * says it is unsigned is refused like any other mismatch (`JWT_ERR_ALG`); an
32
- * `HS256` header in front of an RSA key is refused before any MAC is taken,
33
- * so an RSA public key can never be used as an HMAC secret (RFC 8725 §2.1,
34
- * §3.1). The header must hold `alg` exactly once, as a string; `typ` and `kid`
35
- * at most once, as strings; and no `crit` and no `b64` (RFC 7515 §4.1.11,
36
- * RFC 7797), since this verifier understands no extension and a header that
37
- * names one must be refused. Other header members are skipped.
30
+ * algorithm's name, spelled exactly. `none` names no key, so a token that says
31
+ * it is unsigned is refused like any other mismatch (`JWT_ERR_ALG`); an `HS256`
32
+ * header in front of an RSA key is refused before any MAC is taken, so an RSA
33
+ * public key can never be used as an HMAC secret (RFC 8725 §2.1, §3.1).
34
+ *
35
+ * The header must hold `alg` exactly once, as a string; `typ` and `kid` at most
36
+ * once, as strings; and no `crit` and no `b64` (RFC 7515 §4.1.11, RFC 7797),
37
+ * since this verifier understands no extension and a header that names one must
38
+ * be refused. Other header members are skipped.
38
39
  *
39
40
  * **Nothing in the payload is read before the signature holds.** The verifier
40
41
  * reads the header, decodes the signature and checks it, and only then decodes
@@ -1360,18 +1361,20 @@ export class JwtVerifier {
1360
1361
 
1361
1362
  /**
1362
1363
  * Verifies the token `src[off .. off + len)` under `key` and checks its
1363
- * claims at `now` (seconds since 1970): `JWT_OK`, or the first
1364
- * `JWT_ERR_*` that applies, in this order: the window (`JWT_ERR_SIZE`);
1365
- * the three parts and the header's base64url (`JWT_ERR_FORMAT`); the
1366
- * header's members in the order written (`JWT_ERR_HEADER`, `JWT_ERR_ALG`),
1367
- * then a missing `alg` and, when the verifier names a `typ`, a missing or
1368
- * other one; signature text too long for any signature
1369
- * (`JWT_ERR_SIGNATURE`); the signature's base64url (`JWT_ERR_FORMAT`); its
1370
- * length, the key's fit and the signature itself (`JWT_ERR_SIGNATURE`); the
1371
- * payload's base64url (`JWT_ERR_FORMAT`); the payload's members in the
1372
- * order written and, while `requireExp` is set (the default), a missing
1373
- * `exp` (`JWT_ERR_CLAIMS`); and then `exp`,
1374
- * `nbf`, `iat`, `iss`, `aud` and `sub`, in that order.
1364
+ * claims at `now` (seconds since 1970): `JWT_OK`, or the first `JWT_ERR_*`
1365
+ * that applies, in this order:
1366
+ * - the window (`JWT_ERR_SIZE`);
1367
+ * - the three parts and the header's base64url (`JWT_ERR_FORMAT`);
1368
+ * - the header's members in the order written (`JWT_ERR_HEADER`,
1369
+ * `JWT_ERR_ALG`), then a missing `alg` and, when the verifier names a
1370
+ * `typ`, a missing or other one;
1371
+ * - signature text too long for any signature (`JWT_ERR_SIGNATURE`);
1372
+ * - the signature's base64url (`JWT_ERR_FORMAT`);
1373
+ * - its length, the key's fit and the signature itself (`JWT_ERR_SIGNATURE`);
1374
+ * - the payload's base64url (`JWT_ERR_FORMAT`);
1375
+ * - the payload's members in the order written and, while `requireExp` is set
1376
+ * (the default), a missing `exp` (`JWT_ERR_CLAIMS`);
1377
+ * - and then `exp`, `nbf`, `iat`, `iss`, `aud` and `sub`, in that order.
1375
1378
  *
1376
1379
  * @param key The key to verify with; it alone decides the algorithm, and a
1377
1380
  * wiped one verifies nothing.
@@ -30,27 +30,29 @@
30
30
  *
31
31
  * **What is ported and what is not.** The `p256Fiat*` functions are
32
32
  * fiat-crypto's generated, formally verified Montgomery arithmetic on eight
33
- * `u32` limbs with `u64` products — `mul`, `square`, `add`, `sub`,
34
- * `selectznz`, `nonzero` and `set_one` mod p, and `mul`, `add` and `set_one`
35
- * mod n — statement for statement, with fiat's variable names. Three things
36
- * change in the translation and nothing else does. C's out-pointers become a
37
- * `u64` answer: each of fiat's `addcarryx`, `subborrowx` and `mulx` helpers
38
- * here answers its two outputs packed, the first in the low 32 bits and the
39
- * second above them, and the caller splits them, declaring only the halves
40
- * fiat goes on to read. And each function opens with
41
- * a length guard, so that the literal indices after it compile with no bounds
42
- * check. And `square` reads its input's eight limbs into locals first, which
43
- * changes no arithmetic; it kept the input's pointer from being spilled in a
44
- * way the aarch64 disassembly check once misread (#334). The
45
- * scalar functions use the field's four helpers, which fiat generates
46
- * identically for both. The nonce's inverse, `p256ScalarInverse`, is
47
- * libsecp256k1's 32-bit safegcd (`modinv32`), function for function; the
48
- * section that holds it says what changes. Everything else in this file — the
49
- * curve, the encodings, the other inversions and ECDSA — is written for this
50
- * module from the documents it names.
33
+ * `u32` limbs with `u64` products — `mul`, `square`, `add`, `sub`, `selectznz`,
34
+ * `nonzero` and `set_one` mod p, and `mul`, `add` and `set_one` mod n —
35
+ * statement for statement, with fiat's variable names. Three things change in
36
+ * the translation and nothing else does.
51
37
  *
52
- * **The curve** is `y^2 = x^3 - 3x + b` over GF(p), p = 2^256 - 2^224 + 2^192
53
- * + 2^96 - 1, with the base point G and its order n from SEC 2 §2.4.2 (FIPS
38
+ * C's out-pointers become a `u64` answer: each of fiat's `addcarryx`,
39
+ * `subborrowx` and `mulx` helpers here answers its two outputs packed, the
40
+ * first in the low 32 bits and the second above them, and the caller splits
41
+ * them, declaring only the halves fiat goes on to read. And each function opens
42
+ * with a length guard, so that the literal indices after it compile with no
43
+ * bounds check.
44
+ *
45
+ * And `square` reads its input's eight limbs into locals first, which changes
46
+ * no arithmetic; it kept the input's pointer from being spilled in a way the
47
+ * aarch64 disassembly check once misread (#334). The scalar functions use the
48
+ * field's four helpers, which fiat generates identically for both. The nonce's
49
+ * inverse, `p256ScalarInverse`, is libsecp256k1's 32-bit safegcd (`modinv32`),
50
+ * function for function; the section that holds it says what changes.
51
+ * Everything else in this file — the curve, the encodings, the other inversions
52
+ * and ECDSA — is written for this module from the documents it names.
53
+ *
54
+ * **The curve** is `y^2 = x^3 - 3x + b` over GF(p),
55
+ * p = 2^256 - 2^224 + 2^192 + 2^96 - 1, with the base point G and its order n from SEC 2 §2.4.2 (FIPS
54
56
  * 186-4 §D.1.2.3). Points are projective (X : Y : Z), Z = 0 the identity, and
55
57
  * are added and doubled with the complete formulas of J. Renes, C. Costello and
56
58
  * L. Batina, "Complete addition formulas for prime order elliptic curves"
@@ -64,44 +66,49 @@
64
66
  * sums of a tooth's multiples of G, one per 4-bit offset, as affine points in
65
67
  * the Montgomery domain (`p256BaseTable`, 15 KiB, written by
66
68
  * `scripts/gen-p256-table.mjs`). Four rows of 16 mixed additions with a
67
- * doubling between rows replace the 256 doublings and 64 additions of a
68
- * window, whatever the scalar. Each addition reads all fifteen entries of its
69
- * sub-table and keeps one with fiat's conditional move, steered by `ctEq` on
70
- * the digit; a zero digit keeps none, and the sum is then discarded by the
71
- * same conditional move rather than skipped, so neither a branch nor an
72
- * address depends on the scalar. `p256ScalarMult`, a fixed 4-bit window over
73
- * sixteen multiples of a point, is what verification multiplies G and the
74
- * received key by, and the reference the comb is held to bit for bit
75
- * (`tests/link/crypto_p256_agree`). The signer inverts the nonce by
76
- * Bernstein and Yang's safegcd, `p256ScalarInverse`: twenty batches of thirty
77
- * divsteps, each a fixed run of masks and adds, whatever the scalar, so its
78
- * loops count constants and no branch or address follows the nonce; Fermat's
79
- * `p256ScalarInvert` is the reference it is held to bit for bit
80
- * (`tests/link/crypto_p256_inverse`) and what verification still uses. The
81
- * other inversions raise to the public exponents p - 2 and n - 2, so their
82
- * branches follow a constant. The
83
- * branches that remain are on public facts: a length, a limb or bit position,
84
- * whether a received key or signature is in range, and — once in about 2^32
85
- * signatures — RFC 6979's retry when a candidate nonce is not below n.
69
+ * doubling between rows replace the 256 doublings and 64 additions of a window,
70
+ * whatever the scalar.
71
+ *
72
+ * Each addition reads all fifteen entries of its sub-table and keeps one with
73
+ * fiat's conditional move, steered by `ctEq` on the digit; a zero digit keeps
74
+ * none, and the sum is then discarded by the same conditional move rather than
75
+ * skipped, so neither a branch nor an address depends on the scalar.
76
+ * `p256ScalarMult`, a fixed 4-bit window over sixteen multiples of a point, is
77
+ * what verification multiplies G and the received key by, and the reference the
78
+ * comb is held to bit for bit (`tests/link/crypto_p256_agree`).
79
+ *
80
+ * The signer inverts the nonce by Bernstein and Yang's safegcd,
81
+ * `p256ScalarInverse`: twenty batches of thirty divsteps, each a fixed run of
82
+ * masks and adds, whatever the scalar, so its loops count constants and no
83
+ * branch or address follows the nonce; Fermat's `p256ScalarInvert` is the
84
+ * reference it is held to bit for bit (`tests/link/crypto_p256_inverse`) and
85
+ * what verification still uses. The other inversions raise to the public
86
+ * exponents p - 2 and n - 2, so their branches follow a constant.
87
+ *
88
+ * The branches that remain are on public facts: a length, a limb or bit
89
+ * position, whether a received key or signature is in range, and — once in
90
+ * about 2^32 signatures — RFC 6979's retry when a candidate nonce is not below
91
+ * n.
86
92
  *
87
93
  * **What is verified by disassembly and what is discipline.**
88
- * `tests/cases/ct_asm_p256` holds copies of fiat's field multiply, square, add
89
- * and subtract, its scalar multiply and its conditional move, the table read
90
- * by a secret digit, the complete doubling and addition, one window step of
91
- * `p256ScalarMult`, the comb's digit, entry read, mixed addition,
92
- * conditional keep and one whole comb step, and safegcd's thirty divsteps and
93
- * its two matrix updates, to the check of
94
- * `tests/ct-asm.js`, which refuses any branch, call it cannot follow or
95
- * secret-indexed access in them on x86-64 and aarch64, following each call
96
- * into the field functions. The copies of the point functions take coordinate
97
- * arrays rather than points, the table reads' loops are written out there and
98
- * their offsets computed with wrapping arithmetic, as that fixture's header
99
- * says; its `main` runs RFC 6979 A.2.5 through them, by the window and by the
100
- * comb, and three inverses through the safegcd copies. The 64-window and 4-row
101
- * loops, the table build, the inversions (safegcd's twenty-batch loop, its
102
- * conversions, normalisation and limb loops among them), the encodings and the
103
- * nonce derivation are constant time by construction rather than by that
104
- * proof.
94
+ *
95
+ * `tests/cases/ct_asm_p256` holds copies of fiat's field multiply, square, add
96
+ * and subtract, its scalar multiply and its conditional move, the table read by
97
+ * a secret digit, the complete doubling and addition, one window step of
98
+ * `p256ScalarMult`, the comb's digit, entry read, mixed addition, conditional
99
+ * keep and one whole comb step, and safegcd's thirty divsteps and its two
100
+ * matrix updates, to the check of `tests/ct-asm.js`, which refuses any branch,
101
+ * call it cannot follow or secret-indexed access in them on x86-64 and aarch64,
102
+ * following each call into the field functions.
103
+ *
104
+ * The copies of the point functions take coordinate arrays rather than points,
105
+ * the table reads' loops are written out there and their offsets computed with
106
+ * wrapping arithmetic, as that fixture's header says; its `main` runs RFC 6979
107
+ * A.2.5 through them, by the window and by the comb, and three inverses through
108
+ * the safegcd copies. The 64-window and 4-row loops, the table build, the
109
+ * inversions (safegcd's twenty-batch loop, its conversions, normalisation and
110
+ * limb loops among them), the encodings and the nonce derivation are constant
111
+ * time by construction rather than by that proof.
105
112
  *
106
113
  * Verification multiplies only public values, by `p256ScalarMult` alone.
107
114
  *