gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd702d76dd702d76dmd-editor look: root class md-empty (a host .empty rule hit it), rows = surface height, one phone toolbar row with 44 px targets; comment form rows 3; gate 360/0mred702d76d/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

  • d702d76dmd-editor look: root class md-empty (a host .empty rule hit it), rows = surface height, one phone toolbar row with 44 px targets; comment form rows 3; gate 360/0mre
  • 15be2ac0comments: attach (FilesUpload pick), onPost(text, files), files per comment; md-editor files=off; README, gate fixmre
  • 1f8d79d6comments (mission 009 WIP, tickets#27): attachments — attach="true" puts the form in FilesUpload pick mode, onPost(text, files), files per comment (thumbnails open full size, file rows, no url = no link); MdEditor files="off"; demo with attachments; gate m009 checks (WIP: 356/1)mre
  • 13389d67mission 008: report, LOG, STATUSmre
  • ab47e4a2files-upload (mission 008, #18 for hycon#46): pick-first-send-later mode — host-owned list (files + onChange), slot for the host's input area, Ctrl+V paste (both modes), thumbnails, name+size rows, ✕ remove, maxSize per file, Camera on touch screens, 44 px targets; demo /files-upload/pick; gate 343/0 (19 new, 18 fail on the old code)mre
  • 172e66bemission brief 008mre
  • 9db927dfpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 00a95329components (mission 007): re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ git-ignored), gate 324/0 old and new, real-data copy unchanged, report 007, same-output.mjs ports overridablemre
  • fe50766bmission brief 007mre
  • 2dce51b8components (mission 006) 4/4: docs (README comments + gate 324, STATUS, LOG), report reports/006-comments.mdmre
  • 9ec7273ecomponents layouts#2 (mission 006) 3/4: comments — each text is MdEditor readonly directly in its row (hl:web builds a composed child anew when a bound value changes, so the keyed one-row list was not needed); demo 'bob edits his comment elsewhere (a push)' + gate check that a text the host changes from outside is drawn anew; theme radii (var(--radius-small/large) with 5px/10px fallbacks: layouts' check-theme 0 problems with comments.hl copied in); README 'How it is built'; gate 324/0 (34 comments checks)mre
  • fd57c18bcomponents layouts#2 (mission 006) 2/3: comments block (components/comments, demo /comments) — pure Hybriel: '1 comment' / 'n comments', avatar initial, bubble with name, time, 'edited' (<details> with the earlier versions), the text drawn by MdEditor readonly (one-row list keyed by id + text, so an edit redraws), like ♥ n (aria-pressed), Edit / Delete (asks first) only where author == user, the form below in MdEditor (Comment button or Ctrl+Enter; a fresh editor after a post). Host passes comments + user and hands onPost / onEdit / onDelete / onLike (hybriel#87); demo keeps a mock thread from lib/comments.hl in the page, switches alice / bob / nobody. Home entry, routes, map line, README; base-look gate covers comments; 33 gate checks with real clicks / keysmre
  • 850a376bcomponents (mission 006) 1/3: MdEditor readonly = "true" — the Markdown shown formatted and nothing else (no toolbar, link form, file rows, placeholder, source view or switch; article contenteditable false, tabindex -1, role document; no field background or focus ring); the mount only loads the value. For the comments block, which draws every comment with the editor's own renderermre
  • ee9f1b57mission brief w6mre
  • fe691586components (mission 005) 4/4: docs (README components + gate 290, STATUS, LOG), report reports/005-fixes-16-17-5.mdmre
  • f1ebab53components #5 (mission 005) 3/4: file upload for several files (components/files-upload, demo /files-upload) — pure Hybriel, each file through emit server uploadFile (hybriel#94), drop or choose many, a row per file with live progress, one after the other in order, a drop during an upload waits, a file over uploadMax fails in its row and the next goes, 'n of m uploaded'; home entry, routes, map line, README; pagination keyboard focus ring #555 (Chrome painted its own orange one); docker-compose init: true (hybriel#156); gate 290/0 (17 #5 checks with real file drops, 1 #16 focus check)mre
  • 3b73ae5bcomponents #16 (mission 005) 2/4: Pagination tells the host the target page — the host hands onPage (hybriel#87: a function, not emit), called on every click that changes the page (pointer, Enter/Space, script click; Previous/Next/numbers/first/last; not … or the current page) with the target read from the clicked button's data-page before the rebuild; demo shows what the page was told; README Data out; 15 gate checks (14 fail on the old pagination)mre
  • 6b27c0f0components #17 (mission 005) 1/4: md-editor keeps backslash + r — parseInto dropped the two characters '\r' (C:\root -> C:oot) instead of a real carriage return; CR now decoded from JSON (String.fromCharCode does not parse in a member), real CRs also go from pasted plain text; 5 gate checks (3 fail on the old md-editor.hl)mre
  • 1a5dc327mission brief w5mre
  • a567b579components (mission 004) 3/3: docs (README Hybriel a832f73b + tables, STATUS, LOG), report reports/004-md-editor-tables.mdmre