gitoriaLog in with ident

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7bd0337c7bd0337ccalendar: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gates 78/0 + 18/0mre7bd0337c/plugins/crypto/server.js

9.4 KB

  1. // hl:crypto — passwords first. JS transpiler twin of plugins/crypto/crypto.zig.
  2. //
  3. // Parity contract with the native plugin:
  4. // hash(password, options) → a PHC string, freshly salted every call
  5. // verify(password, stored) → boolean, timing-safe comparison
  6. // parsePhc(stored) → the stored string described, or null
  7. // kdf() → the algorithm THIS engine hashes with
  8. // sha256(data) → 64 lowercase hex characters
  9. // randomBytes(n, encoding) → "hex" (default) or "base64"
  10. // toBase64(data) → base64 of a String's UTF-8 or of a Bytes (ticket #90)
  11. // fromBase64(text) → a Bytes, or null when text is not base64
  12. //
  13. // The PHC STRING FORMAT, the strictness of the parser, the cost knob and its cap,
  14. // and the salt/output lengths are identical on both engines — a `$scrypt$` string
  15. // written by either one verifies on the other, byte for byte, because RFC 7914 is
  16. // RFC 7914 whether it is reached through Node's crypto or through libcrypto's
  17. // EVP_PBE_scrypt.
  18. //
  19. // THE ONE DIFFERENCE, stated rather than hidden: Node has no argon2 of any kind,
  20. // so this engine hashes with scrypt where the native plugin prefers argon2id on a
  21. // host whose libcrypto has it. `parsePhc` still reads argon2id strings here — the
  22. // format is just a string — but `verify` on one THROWS instead of answering
  23. // `false`, because "I cannot compute this algorithm" is not "wrong password".
  24. import { createHash, randomBytes as nodeRandomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
  25. // Bytes are the runtime's: this file is copied to hl-modules/crypto.js, beside hl-runtime.js.
  26. import { hlMakeBytes, hlIsBytes } from '../hl-runtime.js';
  27. // The cost knob: base-2 log of the working memory in KiB. Same numbers as the
  28. // native plugin — 15 is 32 MiB (scrypt N = 2^15, r = 8, p = 1 is 128·N·r bytes).
  29. const COST_DEFAULT = 15;
  30. const COST_MIN = 10; // 1 MiB
  31. const COST_MAX = 17; // 128 MiB — see the note in crypto.zig; the two engines
  32. // must cap at the same number or a string one of them
  33. // wrote would be out of range for the other.
  34. const SALT_LEN = 16;
  35. const HASH_LEN = 32;
  36. // The floor a stored string must clear to be READ at all — see decodePhc().
  37. const MIN_SALT_LEN = 8;
  38. const MIN_HASH_LEN = 16;
  39. const SCRYPT_R = 8;
  40. const SCRYPT_P = 1;
  41. // Node refuses a derivation whose 128·N·r exceeds maxmem, default 32 MiB — which
  42. // the DEFAULT cost sits exactly on. Raised past the cost cap so the cap is the
  43. // only thing that limits anything.
  44. const SCRYPT_MAXMEM = 2 * 1024 * 1024 * 1024;
  45. const B64_CHARS = /^[A-Za-z0-9+/]+$/;
  46. function b64(buf) {
  47. return buf.toString('base64').replace(/=+$/, '');
  48. }
  49. // Deliberately strict, to match the Zig decoder, and BOTH halves of that are
  50. // load-bearing:
  51. // • Node's base64 reader silently skips characters outside the alphabet, so a
  52. // string with junk in it would parse rather than be refused;
  53. // • it also drops NON-CANONICAL TRAILING BITS. A 32-byte hash is 43 base64
  54. // characters, whose last character carries only two significant bits — so
  55. // "…L8E" and "…L8F" decode to the SAME 32 bytes and, before this check,
  56. // editing the last character of a stored hash did not change what it
  57. // verified against. Zig's decoder refuses that outright; re-encoding is how
  58. // this engine reaches the same answer.
  59. function unb64(text) {
  60. if (!B64_CHARS.test(text)) return null;
  61. const buf = Buffer.from(text, 'base64');
  62. if (buf.length === 0) return null;
  63. if (b64(buf) !== text) return null;
  64. return buf;
  65. }
  66. function paramValue(field, key) {
  67. for (const pair of field.split(',')) {
  68. const eq = pair.indexOf('=');
  69. if (eq < 0) continue;
  70. if (pair.slice(0, eq) !== key) continue;
  71. const raw = pair.slice(eq + 1);
  72. if (!/^[0-9]+$/.test(raw)) return null;
  73. const n = Number(raw);
  74. return Number.isSafeInteger(n) ? n : null;
  75. }
  76. return null;
  77. }
  78. /** Strict PHC decode. Any deviation at all is null — that is what makes a
  79. * tampered string fail rather than half-parse into something comparable.
  80. *
  81. * Including the LENGTH FLOOR: a KDF derives as many bytes as it is asked for,
  82. * so a stored string whose hash field had been cut down to eight base64
  83. * characters derived six bytes and compared six bytes — and six bytes of a
  84. * correct derivation match. Truncating the stored value was a way to make a
  85. * wrong password verify until this check existed (both engines had it). */
  86. function decodePhc(stored) {
  87. if (typeof stored !== 'string' || stored.length < 2 || stored[0] !== '$') return null;
  88. const parts = stored.slice(1).split('$');
  89. if (parts.length > 8) return null;
  90. if (parts[0] === 'argon2id') {
  91. if (parts.length !== 5) return null;
  92. if (!parts[1].startsWith('v=') || !/^[0-9]+$/.test(parts[1].slice(2))) return null;
  93. const version = Number(parts[1].slice(2));
  94. const m = paramValue(parts[2], 'm');
  95. const t = paramValue(parts[2], 't');
  96. const p = paramValue(parts[2], 'p');
  97. if (m === null || t === null || p === null) return null;
  98. const salt = unb64(parts[3]);
  99. const hash = unb64(parts[4]);
  100. if (!salt || !hash) return null;
  101. if (salt.length < MIN_SALT_LEN || hash.length < MIN_HASH_LEN) return null;
  102. return { kdf: 'argon2id', version, m, t, p, salt, hash };
  103. }
  104. if (parts[0] === 'scrypt') {
  105. if (parts.length !== 4) return null;
  106. const ln = paramValue(parts[1], 'ln');
  107. const r = paramValue(parts[1], 'r');
  108. const p = paramValue(parts[1], 'p');
  109. if (ln === null || r === null || p === null) return null;
  110. const salt = unb64(parts[2]);
  111. const hash = unb64(parts[3]);
  112. if (!salt || !hash) return null;
  113. if (salt.length < MIN_SALT_LEN || hash.length < MIN_HASH_LEN) return null;
  114. return { kdf: 'scrypt', version: null, ln, r, p, salt, hash };
  115. }
  116. return null;
  117. }
  118. function clampCost(value) {
  119. if (typeof value !== 'number' || Number.isNaN(value)) return COST_DEFAULT;
  120. return Math.trunc(Math.max(COST_MIN, Math.min(COST_MAX, value)));
  121. }
  122. export function hash(password, options) {
  123. if (typeof password !== 'string') throw new Error('hl:crypto hash() expects a string password');
  124. const opts = options && typeof options === 'object' ? options : {};
  125. const cost = clampCost(opts.cost);
  126. const want = typeof opts.kdf === 'string' ? opts.kdf : 'scrypt';
  127. if (want === 'argon2id') {
  128. throw new Error('hl:crypto hash(): this engine has no argon2id — Node ships no argon2');
  129. }
  130. if (want !== 'scrypt') {
  131. throw new Error('hl:crypto hash(): unknown kdf — expected "argon2id" or "scrypt"');
  132. }
  133. const salt = nodeRandomBytes(SALT_LEN);
  134. const derived = scryptSync(password, salt, HASH_LEN, {
  135. N: 2 ** cost, r: SCRYPT_R, p: SCRYPT_P, maxmem: SCRYPT_MAXMEM,
  136. });
  137. return `$scrypt$ln=${cost},r=${SCRYPT_R},p=${SCRYPT_P}$${b64(salt)}$${b64(derived)}`;
  138. }
  139. export function verify(password, stored) {
  140. if (typeof password !== 'string') return false;
  141. const phc = decodePhc(stored);
  142. if (phc === null) return false;
  143. if (phc.hash.length === 0 || phc.hash.length > 64) return false;
  144. if (phc.kdf === 'argon2id') {
  145. throw new Error('hl:crypto verify(): stored password is argon2id and this engine has none — Node ships no argon2');
  146. }
  147. if (phc.ln === 0 || phc.ln > 30 || phc.r === 0 || phc.p === 0) return false;
  148. let computed;
  149. try {
  150. computed = scryptSync(password, phc.salt, phc.hash.length, {
  151. N: 2 ** phc.ln, r: phc.r, p: phc.p, maxmem: SCRYPT_MAXMEM,
  152. });
  153. } catch {
  154. // A stored string asking for more memory than this host will give is not a
  155. // wrong password, but it is also not something to crash a login over.
  156. return false;
  157. }
  158. return timingSafeEqual(computed, phc.hash);
  159. }
  160. export function parsePhc(stored) {
  161. const phc = decodePhc(stored);
  162. if (phc === null) return null;
  163. const params = phc.kdf === 'argon2id'
  164. ? { m: phc.m, t: phc.t, p: phc.p }
  165. : { ln: phc.ln, r: phc.r, p: phc.p };
  166. return {
  167. kdf: phc.kdf,
  168. version: phc.version,
  169. params,
  170. saltLen: phc.salt.length,
  171. hashLen: phc.hash.length,
  172. };
  173. }
  174. export function kdf() {
  175. return 'scrypt';
  176. }
  177. export function sha256(data) {
  178. if (typeof data !== 'string') throw new Error('hl:crypto sha256() expects a string');
  179. return createHash('sha256').update(data, 'utf8').digest('hex');
  180. }
  181. export function randomBytes(n, encoding) {
  182. if (typeof n !== 'number' || !(n >= 1) || n > 1024) {
  183. throw new Error('hl:crypto randomBytes(): count must be between 1 and 1024');
  184. }
  185. const buf = nodeRandomBytes(Math.trunc(n));
  186. const enc = typeof encoding === 'string' ? encoding : 'hex';
  187. if (enc === 'hex') return buf.toString('hex');
  188. if (enc === 'base64') return buf.toString('base64');
  189. throw new Error('hl:crypto randomBytes(): encoding must be "hex" or "base64"');
  190. }
  191. // Base64, standard alphabet (ticket #90) — the rules are crypto.zig's: encoding
  192. // pads; decoding takes padded or unpadded text and answers null for anything an
  193. // encoder would not have written. Node's own decoder skips what it does not
  194. // understand, so the text is checked first and the result re-encoded after.
  195. export function toBase64(data) {
  196. if (hlIsBytes(data)) return Buffer.from(data._d).toString('base64');
  197. if (typeof data !== 'string') throw new Error('hl:crypto toBase64() expects a String or a Bytes');
  198. return Buffer.from(data, 'utf8').toString('base64');
  199. }
  200. export function fromBase64(text) {
  201. if (typeof text !== 'string') throw new Error('hl:crypto fromBase64() expects a String');
  202. let core = text;
  203. if (core.length % 4 === 0) core = core.replace(/={1,2}$/, '');
  204. if (core.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(core)) return null;
  205. const buf = Buffer.from(core, 'base64');
  206. if (buf.toString('base64').replace(/=+$/, '') !== core) return null;
  207. return hlMakeBytes(new Uint8Array(buf));
  208. }

Branches

Latest commits

  • 7bd0337ccalendar: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gates 78/0 + 18/0mre
  • ff41310ccalendar: Hybriel master 8efba065 (#126 memory, #48 lambda copy; audit: no & needed)mre
  • 14ba08c7antcolony#40: mission references point to the moved missionsmre
  • 99c73346antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 76edaa62calendar: Hybriel master ff51cf46 (re-vendor round, static workaround removed)mre
  • 90a3fc2cdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 6722b72ddeploy.sh: never send .git or .gitignore to Byrodinmre
  • be099807State of 2026-09-27, before the move to gitoriamre