gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit06b078e306b078e3tracker mission 028 (code order) 3/5 project.hl is the map: config, routes, wiring and a feature → file index (914 → 258 lines); the background jobs (daily sync run, backfills, details repair, credits job, merge, short ids, collection seed) moved unchanged into lib/jobs.hl (a class: their state is reassigned every step, a static cannot be; one instance made after the server), the login callback into lib/users.hl, poster/photo serving into lib/images.hl, the /shows/<slug> rule into lib/shows.hl showsMovedPath; route handlers are thin wrappers; gates 342/0, 32/0, 52/0, real-copy pages identicalmre06b078e3/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

  • 06b078e3tracker mission 028 (code order) 3/5 project.hl is the map: config, routes, wiring and a feature → file index (914 → 258 lines); the background jobs (daily sync run, backfills, details repair, credits job, merge, short ids, collection seed) moved unchanged into lib/jobs.hl (a class: their state is reassigned every step, a static cannot be; one instance made after the server), the login callback into lib/users.hl, poster/photo serving into lib/images.hl, the /shows/<slug> rule into lib/shows.hl showsMovedPath; route handlers are thin wrappers; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
  • 94716fd2tracker mission 028 (code order) 2/5 util + topics: lib/util.hl holds envOr, storageDir, postersDir, profilesDir, newId, hexDigits, todayStr, dateOr, textOr, hasId, listOr, firstOf, sortDesc once (were copied into up to 5 files); tmdbsync.hl split into tmdb.hl (TMDB/TVmaze requests), sync.hl (one title's sync), sync-helpers.hl, backfill.hl; details.hl split into details.hl, credits.hl, credits-helpers.hl (isIncomplete to shows.hl); search-helpers.hl (words, query, ranking, slugs); collections.hl (the TMDB collection seed, out of franchises.hl); deltasync.hl renamed dailysync.hl; no behaviour change: gates 342/0, 32/0, 52/0, real-copy pages identicalmre
  • 186079b0tracker mission 028 (code order) 1/5 move: every root .hl except project.hl into lib/ (styles.hl into components/), import paths only; gates 342/0, 32/0, 52/0; real-copy pages identicalmre
  • 4f47f181tracker: report 027mre
  • dc1d4be4tracker mission 027: Hybriel master 06617221 vendored (plugin allocator fixes 3a781359 + 413f60e4); real copy RSS through first-start jobs + 400 loads flat ~2.55 GB (190aa11d 2.3 -> 5.6 GB), page times <= 1.1x; gates 342/0, 32/0, 52/0mre
  • 84e1b3e1tracker: reports 025 + 026mre
  • dc40d859tracker#31 (mission 026): duplicate titles merged — the 68 type+tmdbId pairs held by 157 records were the old tracker's (all migrated); merge.hl repair job (own clock, before the TMDB jobs) keeps one keeper per title (follows/watches > old short id > oldest), moves follows, watches, seasons, cast, credits, timelines, tombstones the rest (mergedInto, never deleted), slugs + short ids 301 to the keeper; stray seasons merged into their listed twin (Reacher S3 watches) or linked when watched; search import re-checks before its put; deploy.sh waits up to 90 s for 200; real copy 68 -> 0 dup ids, az5b2 follows/watches equal; gates 342/0, 32/0, 52/0mre
  • 2667da05tracker#30 (mission 025): /my/ pages from slim cached title cards, episode rows and watch sets (after the jobs /my/series 1.8 s -> 0.06 s, /my/unwatched 4.1 -> 0.18 s); timeline page shows its name once; franchise widget under the poster/title; movies with TV leftovers (First Contact) go through the details repair; tools/count-tmdb-ids.hl; gates 327/0, 52/0, 32/0mre
  • 3909810dantcolony#40: mission references in README/STATUS/docs point to the moved missionsmre
  • e63b1d28antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 1cda451dtracker: Hybriel master 190aa11d (#127 both shapes, GC correctness fc838894) — conductor adopts despite /my/series 2.4x after jobs (memory 8.0 → 1.7 GB boot); see reports/071mre
  • c1fa2f2etracker (mission 071): Hybriel master 190aa11d measured on the real copy vs the live binary 8590df63 — NOT adopted (after the first-start jobs /my/series 2.4x slower, /series 1.6x, RSS swings 7.4-12.2 GB; fresh it is flat at 1.7-2.2 GB and /my/unwatched faster), vendor stays 8efba065, candidate kept in .scratch/w071/vendor-190aa11d; tests/kinds.mjs: collection seed off (its TMDB request broke check 1 in 1 of 4 runs); tests/realdata-071.sh + realdata-071-bench.mjs + tools/realdata-071-table.py; README + STATUS (numbers, how to repeat); gates 325/0, 32/0, 50/0mre
  • 8081350atracker docs (mission 070): README (summary, Config HL_GC_BYTES — kept at Hybriel's default, the 256 MiB setting is taken out of docker-compose.yml again: the jobs grew to 12+ GB with it too, see STATUS), Test (three gates), Deploy (first start ~50 min: kinds then seed, restart once after collections done, memory numbers), Vendored Hybriel 8efba065 + #48 audit, Files; STATUS mission 070 entry (merges, migrated counts, lambda audit, gates, RSS old vs new, how to repeat, open points); docs/kinds.md + docs/franchises.md job order; tests/realdata-070-*.sh, tools/count-migrated.hl, tools/ref-params.py, tools/lambda-audit.pymre
  • 1ad19c8ctracker: re-vendor Hybriel master 8efba065 (#126 GC by bytes, #48 lambda parameters copy) (mission 070): bin/hybriel sha256 50361e95…, plugins core crypto data fetch fs http http1 mpackdb proc smtp time web; lambda audit: 13 lambdas change a passed record/list (11 through a local alias), no caller relies on it — unchanged; 319 read-only lambda parameters get & (no copy per call: /my/schedule 2.35 → 0.46 s, /my/unwatched 13.7 → 5.7 s on the real copy); /my/unwatched one merge sort instead of n² inserts; docker-compose HL_GC_BYTES=268435456; deploy.sh runs kinds.mjs + franchises.mjs too (default ports 8700–8710); tests/realdata-070.mjs; gates browser 325/0, kinds 32/0, franchises 50/0mre
  • 46b21389tracker (mission 070, conductor): the sync never destroys migrated data — the one-time summary step MOVES a copied summary to migratedSummary (marker summaries-moved.txt) instead of clearing it; a migrated record's first title/genres/homepage/tagline TMDB replaces → migratedTitle/migratedGenres/migratedHomepage/migratedTagline, a migrated season's/episode's title/summary → migratedTitle/migratedSummary (set once); tests/peek-shows.hl prints them; gate 325/0mre
  • 749019b0Merge t19 (tracker#19 franchises + timelines) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs/faketmdb.mjs, both sides kept; franchise/timeline pages get #20's typed heading (Franchise | …, Timeline | …), their title links via titlePath (/movies|/series|/shows); the collection seed waits for repair, kinds and credits too; franchises.mjs URLs + 2 new checks; gates browser 323/0, kinds 32/0, franchises 50/0mre
  • daf49feaMerge t20 (tracker#20 typed headings + #21 series/shows split) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/search.hl/components/search.hl/browser.mjs/faketmdb.mjs, both sides kept; clock order backfill → repair → kinds → credits; withDetailsFields stores tmdbType + kind; gates: browser.mjs URLs → /series|/movies, typed h1 selectors; kinds.mjs repair/credits off, fixture name = seed name; browser 323/0, kinds 32/0mre
  • 20e09d89Merge t18 (tracker#18 delta sync) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs, both sides kept; pageShowOf summary = summaryOfmre
  • f83571c3tracker#18 (mission 067): daily sync by change lists — TMDB /tv|movie/changes (since the stored day, paged) + TVmaze /updates/shows → only our changed titles (followed: full step, unfollowed: light step — changed seasons, no TVmaze), full walk on first run / gap > 14 days / failed list; show record refreshed (title, tmdbSummary, tagline, status, genres …; renamed titles re-indexed); summary = the creator's own text (page: summary > tmdbSummary > tvmazeSummary), one-time clear of copied summaries (9,647 on the live copy); gate 261, tests/realdata-018*.mjs, README + STATUSmre
  • 1ed5457etracker#20 + #21 (mission 068): typed headings "<Type> | <name>" in type colours; TV titles split into Series (/series) and Shows (/shows) by TMDB type + Reality/Talk/News genres — kind stored by sync/import/adult backfill + new kind backfill (resumes), /movies/<slug>, /shows/<slug> of a series/movie → 301, /my/series + /my/shows, home 5 tiles + 3 rows, search/filmography labels; gates kinds 32 + browser 266, tests/realdata-068.mjs, tools/count-kinds.hl, docs/kinds.md, README + STATUSmre