gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf83d9c0df83d9c0dtickets (mission 016): report reports/016-comments-block.md, LOG, STATUS, README gate countmref83d9c0d/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

  • f83d9c0dtickets (mission 016): report reports/016-comments-block.md, LOG, STATUS, README gate countmre
  • eef80f55tickets (mission 016): comments through the shared Comments block (layouts#2) — edit (author, earlier versions kept), delete (author, asks; leaves one line in the history), like (members, toggle) on the server (lib/comments.hl, append-only tables), faces + API …/comments/:comment/{edit,delete,like}, push commentChanged; every run of comments is a block in place in the history; Markdown fields on the Hybriel MdEditor (shared/md-editor.js retired: it took over the block's <md-editor>); blocks copied verbatim from components.hybriel 9db927d (tools/sync-components.sh); gates browser 351/0 (old 326/0), events 52/0 (old 52/0)mre
  • eb7aeeb9mission brief 016mre
  • e4c34759paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 26efb23freport w6-events (events test)mre
  • c6bfab04mission 015: re-vendor Hybriel 0f396652 (static build), reportmre
  • b7ec5981mission brief 015mre
  • 5dc68731docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 8a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre
  • 6309ca81mission brief 014mre
  • c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre
  • a30b5d12mission brief (w13)mre
  • b50a6f93w9 (tickets): re-vendor hybriel 9f912f3b (#146 emit in a lib static, #147) — the 12 live-push emits in lib/api.hl compile as they are; cold start (#148): tests wait TICKETS_COLD_MS for every start, deploy.sh gates browser + events and waits up to 120 s for the URL, container /tmp tmpfs + hybriel-cache volume; events-client stops at EVENTS_MAX inside a chunk; connect.mjs ports by env. bin/hybriel sha256 7421907868ac07d8a7d08296b083c6f8b20407d0e099ce4bebbf7ae053d9060a. Gates (8720–8739): browser 315/0 (+ all-cold 315/0), events 48/0 cold, connect 60/0, short-id 19/0; real-data copy old 0e8a41c vs new: 2,425 reads + 72 writes identical after masking ?v hashes, offline at, route order; event stream on the copy delivers. Not deployed.mre
  • 43be6578w9: re-vendor hybriel master edfd400a; event stream imports sseStart/sseSend/sseAlive from hl:http1 (hybriel#144), useTransport gone; tools/import.hl plain declarations. BLOCKED: hybriel-native refuses `emit client` in a static (lib/api.hl) — the server does not compile on edfd400a, gates fail at start; scratch copy without those emits: events 48/0, gate 254 ok up to the first live pushmre
  • 0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre
  • bb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmre
  • 7538b034mission 011 (ticket #25 web part): short page URLs /<slug> and /<slug>/<number>; /projects/<slug>, /projects/<slug>/<n>, /projects/<slug>/tickets/<n> and /tickets/<ref> answer 301 (current slug); slug pages moved behind hl:web's own routes after construction (they answered /__hl/* and /components/*.hl); reserved slugs refused; API paths unchanged. gate 293/0, connect 60/0, live-data copy 187/0, API old vs new: only page links differmre
  • 0369106emission 010 (code order) 4/4: README file map + import order + 'Same output' test, STATUS (entry, lessons, how to verify), LOG, report; tests/realdata-baseline.mjs + realdata-compare*.py (a cleanup answers the same on live data), tests/letcount.pymre
  • a75e0279mission 010 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (456 lets → plain declarations; Hybriel refuses a plain declaration inside a loop on its 2nd pass). gate 249/0, connect 60/0, real-data reads identical, a 50-step write sequence (API + faces) identical to the old codemre
  • e9d5c618mission 010 (code order) 2/4: one lib/ file per topic — store.hl split into projects / tickets (+ relations) / events / tickets-helpers, util.hl shared helpers (env, storage dir, URLs, sorts, Vienna time), the function routes out of project.hl into lib/api.hl (thin; auth/filters/Accept in api-helpers.hl), invite + member-removal logic out of the faces/routes into invites.hl / tickets.hl; project.hl is the map. /login/callback gets req + the session store by reference. gate 249/0, connect 60/0, real-data reads identicalmre