gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/crypto/server.js

15.6 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. // base64urlEncode / base64urlDecode, p256Generate, p256PublicKey, es256Sign, es256Verify,
  13. // ecdhSharedSecret, hkdfExtract, hkdfExpand, hkdf, aes128gcmEncrypt, aes128gcmDecrypt
  14. // → the Web Push primitives (ticket #173), same Bytes shapes as server.hl
  15. //
  16. // The PHC STRING FORMAT, the strictness of the parser, the cost knob and its cap,
  17. // and the salt/output lengths are identical on both engines — a `$scrypt$` string
  18. // written by either one verifies on the other, byte for byte, because RFC 7914 is
  19. // RFC 7914 whether it is reached through Node's crypto or through libcrypto's
  20. // EVP_PBE_scrypt.
  21. //
  22. // THE ONE DIFFERENCE, stated rather than hidden: Node has no argon2 of any kind,
  23. // so this engine hashes with scrypt where the native plugin prefers argon2id on a
  24. // host whose libcrypto has it. `parsePhc` still reads argon2id strings here — the
  25. // format is just a string — but `verify` on one THROWS instead of answering
  26. // `false`, because "I cannot compute this algorithm" is not "wrong password".
  27. import {
  28. createHash, randomBytes as nodeRandomBytes, scryptSync, timingSafeEqual as nodeTimingSafeEqual, createECDH, createHmac, createPrivateKey,
  29. createPublicKey, sign as nodeSign, verify as nodeVerify, createCipheriv, createDecipheriv,
  30. } from 'node:crypto';
  31. // Bytes are the runtime's: this file is copied to hl-modules/crypto.js, beside hl-runtime.js.
  32. import { hlMakeBytes, hlIsBytes } from '../hl-runtime.js';
  33. // The cost knob: base-2 log of the working memory in KiB. Same numbers as the
  34. // native plugin — 15 is 32 MiB (scrypt N = 2^15, r = 8, p = 1 is 128·N·r bytes).
  35. const COST_DEFAULT = 15;
  36. const COST_MIN = 10; // 1 MiB
  37. const COST_MAX = 17; // 128 MiB — see the note in crypto.zig; the two engines
  38. // must cap at the same number or a string one of them
  39. // wrote would be out of range for the other.
  40. const SALT_LEN = 16;
  41. const HASH_LEN = 32;
  42. // The floor a stored string must clear to be READ at all — see decodePhc().
  43. const MIN_SALT_LEN = 8;
  44. const MIN_HASH_LEN = 16;
  45. const SCRYPT_R = 8;
  46. const SCRYPT_P = 1;
  47. // Node refuses a derivation whose 128·N·r exceeds maxmem, default 32 MiB — which
  48. // the DEFAULT cost sits exactly on. Raised past the cost cap so the cap is the
  49. // only thing that limits anything.
  50. const SCRYPT_MAXMEM = 2 * 1024 * 1024 * 1024;
  51. const B64_CHARS = /^[A-Za-z0-9+/]+$/;
  52. function b64(buf) {
  53. return buf.toString('base64').replace(/=+$/, '');
  54. }
  55. // Deliberately strict, to match the Zig decoder, and BOTH halves of that are
  56. // load-bearing:
  57. // • Node's base64 reader silently skips characters outside the alphabet, so a
  58. // string with junk in it would parse rather than be refused;
  59. // • it also drops NON-CANONICAL TRAILING BITS. A 32-byte hash is 43 base64
  60. // characters, whose last character carries only two significant bits — so
  61. // "…L8E" and "…L8F" decode to the SAME 32 bytes and, before this check,
  62. // editing the last character of a stored hash did not change what it
  63. // verified against. Zig's decoder refuses that outright; re-encoding is how
  64. // this engine reaches the same answer.
  65. function unb64(text) {
  66. if (!B64_CHARS.test(text)) return null;
  67. const buf = Buffer.from(text, 'base64');
  68. if (buf.length === 0) return null;
  69. if (b64(buf) !== text) return null;
  70. return buf;
  71. }
  72. function paramValue(field, key) {
  73. for (const pair of field.split(',')) {
  74. const eq = pair.indexOf('=');
  75. if (eq < 0) continue;
  76. if (pair.slice(0, eq) !== key) continue;
  77. const raw = pair.slice(eq + 1);
  78. if (!/^[0-9]+$/.test(raw)) return null;
  79. const n = Number(raw);
  80. return Number.isSafeInteger(n) ? n : null;
  81. }
  82. return null;
  83. }
  84. /** Strict PHC decode. Any deviation at all is null — that is what makes a
  85. * tampered string fail rather than half-parse into something comparable.
  86. *
  87. * Including the LENGTH FLOOR: a KDF derives as many bytes as it is asked for,
  88. * so a stored string whose hash field had been cut down to eight base64
  89. * characters derived six bytes and compared six bytes — and six bytes of a
  90. * correct derivation match. Truncating the stored value was a way to make a
  91. * wrong password verify until this check existed (both engines had it). */
  92. function decodePhc(stored) {
  93. if (typeof stored !== 'string' || stored.length < 2 || stored[0] !== '$') return null;
  94. const parts = stored.slice(1).split('$');
  95. if (parts.length > 8) return null;
  96. if (parts[0] === 'argon2id') {
  97. if (parts.length !== 5) return null;
  98. if (!parts[1].startsWith('v=') || !/^[0-9]+$/.test(parts[1].slice(2))) return null;
  99. const version = Number(parts[1].slice(2));
  100. const m = paramValue(parts[2], 'm');
  101. const t = paramValue(parts[2], 't');
  102. const p = paramValue(parts[2], 'p');
  103. if (m === null || t === null || p === null) return null;
  104. const salt = unb64(parts[3]);
  105. const hash = unb64(parts[4]);
  106. if (!salt || !hash) return null;
  107. if (salt.length < MIN_SALT_LEN || hash.length < MIN_HASH_LEN) return null;
  108. return { kdf: 'argon2id', version, m, t, p, salt, hash };
  109. }
  110. if (parts[0] === 'scrypt') {
  111. if (parts.length !== 4) return null;
  112. const ln = paramValue(parts[1], 'ln');
  113. const r = paramValue(parts[1], 'r');
  114. const p = paramValue(parts[1], 'p');
  115. if (ln === null || r === null || p === null) return null;
  116. const salt = unb64(parts[2]);
  117. const hash = unb64(parts[3]);
  118. if (!salt || !hash) return null;
  119. if (salt.length < MIN_SALT_LEN || hash.length < MIN_HASH_LEN) return null;
  120. return { kdf: 'scrypt', version: null, ln, r, p, salt, hash };
  121. }
  122. return null;
  123. }
  124. function clampCost(value) {
  125. if (typeof value !== 'number' || Number.isNaN(value)) return COST_DEFAULT;
  126. return Math.trunc(Math.max(COST_MIN, Math.min(COST_MAX, value)));
  127. }
  128. export function hash(password, options) {
  129. if (typeof password !== 'string') throw new Error('hl:crypto hash() expects a string password');
  130. const opts = options && typeof options === 'object' ? options : {};
  131. const cost = clampCost(opts.cost);
  132. const want = typeof opts.kdf === 'string' ? opts.kdf : 'scrypt';
  133. if (want === 'argon2id') {
  134. throw new Error('hl:crypto hash(): this engine has no argon2id — Node ships no argon2');
  135. }
  136. if (want !== 'scrypt') {
  137. throw new Error('hl:crypto hash(): unknown kdf — expected "argon2id" or "scrypt"');
  138. }
  139. const salt = nodeRandomBytes(SALT_LEN);
  140. const derived = scryptSync(password, salt, HASH_LEN, {
  141. N: 2 ** cost, r: SCRYPT_R, p: SCRYPT_P, maxmem: SCRYPT_MAXMEM,
  142. });
  143. return `$scrypt$ln=${cost},r=${SCRYPT_R},p=${SCRYPT_P}$${b64(salt)}$${b64(derived)}`;
  144. }
  145. export function verify(password, stored) {
  146. if (typeof password !== 'string') return false;
  147. const phc = decodePhc(stored);
  148. if (phc === null) return false;
  149. if (phc.hash.length === 0 || phc.hash.length > 64) return false;
  150. if (phc.kdf === 'argon2id') {
  151. throw new Error('hl:crypto verify(): stored password is argon2id and this engine has none — Node ships no argon2');
  152. }
  153. if (phc.ln === 0 || phc.ln > 30 || phc.r === 0 || phc.p === 0) return false;
  154. let computed;
  155. try {
  156. computed = scryptSync(password, phc.salt, phc.hash.length, {
  157. N: 2 ** phc.ln, r: phc.r, p: phc.p, maxmem: SCRYPT_MAXMEM,
  158. });
  159. } catch {
  160. // A stored string asking for more memory than this host will give is not a
  161. // wrong password, but it is also not something to crash a login over.
  162. return false;
  163. }
  164. return nodeTimingSafeEqual(computed, phc.hash);
  165. }
  166. export function timingSafeEqual(a, b) {
  167. const bytes = (value) => hlIsBytes(value) ? Buffer.from(value._d)
  168. : typeof value === 'string' ? Buffer.from(value, 'utf8') : null;
  169. const left = bytes(a);
  170. const right = bytes(b);
  171. if (left === null || right === null || left.length !== right.length) return false;
  172. return nodeTimingSafeEqual(left, right);
  173. }
  174. export function parsePhc(stored) {
  175. const phc = decodePhc(stored);
  176. if (phc === null) return null;
  177. const params = phc.kdf === 'argon2id'
  178. ? { m: phc.m, t: phc.t, p: phc.p }
  179. : { ln: phc.ln, r: phc.r, p: phc.p };
  180. return {
  181. kdf: phc.kdf,
  182. version: phc.version,
  183. params,
  184. saltLen: phc.salt.length,
  185. hashLen: phc.hash.length,
  186. };
  187. }
  188. export function kdf() {
  189. return 'scrypt';
  190. }
  191. export function sha256(data) {
  192. if (typeof data !== 'string') throw new Error('hl:crypto sha256() expects a string');
  193. return createHash('sha256').update(data, 'utf8').digest('hex');
  194. }
  195. export function randomBytes(n, encoding) {
  196. if (typeof n !== 'number' || !(n >= 1) || n > 1024) {
  197. throw new Error('hl:crypto randomBytes(): count must be between 1 and 1024');
  198. }
  199. const buf = nodeRandomBytes(Math.trunc(n));
  200. const enc = typeof encoding === 'string' ? encoding : 'hex';
  201. if (enc === 'hex') return buf.toString('hex');
  202. if (enc === 'base64') return buf.toString('base64');
  203. throw new Error('hl:crypto randomBytes(): encoding must be "hex" or "base64"');
  204. }
  205. // Base64, standard alphabet (ticket #90) — the rules are crypto.zig's: encoding
  206. // pads; decoding takes padded or unpadded text and answers null for anything an
  207. // encoder would not have written. Node's own decoder skips what it does not
  208. // understand, so the text is checked first and the result re-encoded after.
  209. export function toBase64(data) {
  210. if (hlIsBytes(data)) return Buffer.from(data._d).toString('base64');
  211. if (typeof data !== 'string') throw new Error('hl:crypto toBase64() expects a String or a Bytes');
  212. return Buffer.from(data, 'utf8').toString('base64');
  213. }
  214. export function fromBase64(text) {
  215. if (typeof text !== 'string') throw new Error('hl:crypto fromBase64() expects a String');
  216. let core = text;
  217. if (core.length % 4 === 0) core = core.replace(/={1,2}$/, '');
  218. if (core.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(core)) return null;
  219. const buf = Buffer.from(core, 'base64');
  220. if (buf.toString('base64').replace(/=+$/, '') !== core) return null;
  221. return hlMakeBytes(new Uint8Array(buf));
  222. }
  223. // ── Web Push primitives (ticket #173) ───────────────────────────────────────
  224. // Same shapes as server.hl: Bytes in, Bytes out, null for what cannot be answered.
  225. const toU8 = (b, what, len) => {
  226. if (!hlIsBytes(b)) throw new Error(`hl:crypto ${what} expects a Bytes`);
  227. if (len !== undefined && b._d.length !== len) throw new Error(`hl:crypto ${what} expects ${len} bytes`);
  228. return Buffer.from(b._d);
  229. };
  230. const mk = (buf) => hlMakeBytes(new Uint8Array(buf));
  231. export function base64urlEncode(data) {
  232. if (hlIsBytes(data)) return Buffer.from(data._d).toString('base64url');
  233. if (typeof data !== 'string') throw new Error('hl:crypto base64urlEncode() expects a String or a Bytes');
  234. return Buffer.from(data, 'utf8').toString('base64url');
  235. }
  236. export function base64urlDecode(text) {
  237. if (typeof text !== 'string') throw new Error('hl:crypto base64urlDecode() expects a String');
  238. let core = text;
  239. let pad = 0;
  240. while (pad < 2 && core.endsWith('=')) { core = core.slice(0, -1); pad++; }
  241. if (pad > 0 && (core.length + pad) % 4 !== 0) return null;
  242. if (core.length % 4 === 1 || !/^[A-Za-z0-9_-]*$/.test(core)) return null;
  243. const buf = Buffer.from(core, 'base64url');
  244. if (buf.toString('base64url') !== core) return null;
  245. return mk(buf);
  246. }
  247. // A P-256 private scalar as a node KeyObject (JWK carries d, x, y)
  248. function privKey(d) {
  249. const ecdh = createECDH('prime256v1');
  250. ecdh.setPrivateKey(d);
  251. const pub = ecdh.getPublicKey();
  252. return createPrivateKey({
  253. key: { kty: 'EC', crv: 'P-256', d: d.toString('base64url'),
  254. x: pub.subarray(1, 33).toString('base64url'), y: pub.subarray(33).toString('base64url') },
  255. format: 'jwk',
  256. });
  257. }
  258. function pubKey(point) {
  259. return createPublicKey({
  260. key: { kty: 'EC', crv: 'P-256', x: point.subarray(1, 33).toString('base64url'), y: point.subarray(33).toString('base64url') },
  261. format: 'jwk',
  262. });
  263. }
  264. export function p256Generate() {
  265. const ecdh = createECDH('prime256v1');
  266. ecdh.generateKeys();
  267. // Node returns the scalar in its shortest form: 31 bytes when the top byte is 0 (1 in 256). Bytes 32 is the contract.
  268. const raw = ecdh.getPrivateKey();
  269. const priv = raw.length === 32 ? raw : Buffer.concat([Buffer.alloc(32 - raw.length), raw]);
  270. return { privateKey: mk(priv), publicKey: mk(ecdh.getPublicKey()) };
  271. }
  272. export function p256PublicKey(privateKey) {
  273. const d = toU8(privateKey, 'p256PublicKey()', 32);
  274. try {
  275. const ecdh = createECDH('prime256v1');
  276. ecdh.setPrivateKey(d);
  277. return mk(ecdh.getPublicKey());
  278. } catch { return null; }
  279. }
  280. export function es256Sign(privateKey, message) {
  281. const d = toU8(privateKey, 'es256Sign()', 32);
  282. let key;
  283. try { key = privKey(d); } catch { throw new Error('hl:crypto es256Sign(): invalid private key'); }
  284. return mk(nodeSign('sha256', toU8(message, 'es256Sign()'), { key, dsaEncoding: 'ieee-p1363' }));
  285. }
  286. export function es256Verify(publicKey, message, signature) {
  287. const pk = toU8(publicKey, 'es256Verify()');
  288. const sig = toU8(signature, 'es256Verify()');
  289. if (pk.length !== 65 || pk[0] !== 4 || sig.length !== 64) return false;
  290. try {
  291. return nodeVerify('sha256', toU8(message, 'es256Verify()'), { key: pubKey(pk), dsaEncoding: 'ieee-p1363' }, sig);
  292. } catch { return false; }
  293. }
  294. export function ecdhSharedSecret(privateKey, peerPublicKey) {
  295. const d = toU8(privateKey, 'ecdhSharedSecret()', 32);
  296. const peer = toU8(peerPublicKey, 'ecdhSharedSecret()');
  297. if (peer.length !== 65) return null;
  298. try {
  299. const ecdh = createECDH('prime256v1');
  300. ecdh.setPrivateKey(d);
  301. return mk(ecdh.computeSecret(peer));
  302. } catch { return null; }
  303. }
  304. export function hkdfExtract(salt, ikm) {
  305. // RFC 5869 §2.2: PRK = HMAC-SHA256(salt, ikm); an empty salt is HashLen zero bytes
  306. const key = toU8(salt, 'hkdfExtract()');
  307. return mk(createHmac('sha256', key).update(toU8(ikm, 'hkdfExtract()')).digest());
  308. }
  309. export function hkdfExpand(prk, info, length) {
  310. if (!(length >= 1) || length > 255 * 32 || length !== Math.trunc(length)) {
  311. throw new Error('hl:crypto hkdfExpand(): length must be 1..8160');
  312. }
  313. // hkdfSync with the PRK as ikm and an empty salt would extract again; do the expand by hand
  314. const k = toU8(prk, 'hkdfExpand()', 32);
  315. const inf = toU8(info, 'hkdfExpand()');
  316. const out = [];
  317. let t = Buffer.alloc(0);
  318. for (let i = 1; Buffer.concat(out).length < length; i++) {
  319. t = createHmac('sha256', k).update(Buffer.concat([t, inf, Buffer.from([i])])).digest();
  320. out.push(t);
  321. }
  322. return mk(Buffer.concat(out).subarray(0, length));
  323. }
  324. export function hkdf(salt, ikm, info, length) {
  325. return hkdfExpand(hkdfExtract(salt, ikm), info, length);
  326. }
  327. export function aes128gcmEncrypt(key, nonce, plaintext, aad) {
  328. const c = createCipheriv('aes-128-gcm', toU8(key, 'aes128gcmEncrypt()', 16), toU8(nonce, 'aes128gcmEncrypt()', 12));
  329. if (aad != null) c.setAAD(toU8(aad, 'aes128gcmEncrypt()'));
  330. const ct = Buffer.concat([c.update(toU8(plaintext, 'aes128gcmEncrypt()')), c.final()]);
  331. return mk(Buffer.concat([ct, c.getAuthTag()]));
  332. }
  333. export function aes128gcmDecrypt(key, nonce, ciphertext, aad) {
  334. const k = toU8(key, 'aes128gcmDecrypt()', 16);
  335. const n = toU8(nonce, 'aes128gcmDecrypt()', 12);
  336. const ct = toU8(ciphertext, 'aes128gcmDecrypt()');
  337. if (ct.length < 16) return null;
  338. try {
  339. const d = createDecipheriv('aes-128-gcm', k, n);
  340. if (aad != null) d.setAAD(toU8(aad, 'aes128gcmDecrypt()'));
  341. d.setAuthTag(ct.subarray(ct.length - 16));
  342. return mk(Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]));
  343. } catch { return null; }
  344. }

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre