gitoriaLog in with ident

antcolony

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain3a4d0324antcolony#37: a too-long report gets up to 3 fix tries, finished work is never thrown away for lengthmremain/plugins/crypto/server.js

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

Branches

Latest commits

  • 3a4d0324antcolony#37: a too-long report gets up to 3 fix tries, finished work is never thrown away for lengthmre
  • a6af7883tracker: worker box sees calendar.worldapi.org (login to copy)mre
  • c613d26btemplates: bridges to external components (login.js for ident's selector) are allowed (creator 2026-09-27)mre
  • 9062978ctracker: worker box sees /media/STORAGE/projects/old-tracker read-only (tracker#2 source data)mre
  • 7f9660eeState of 2026-09-27, before the move to gitoriamre