/* ---------------------------------- UPSCALE RECEIVER ---------------------------------- ---------------- UP-SCALES.COM WEBHOOK + LIMS FORWARDING RECEIVER (NODE.JS) ------------ ---------------------------------------------------------------------------------------- A RECEIVER FOR YOUR OWN SERVER: IT TAKES THE RECORDS OF YOUR UP↑SCALE SCALES - FROM THE WEBHOOK EXPORT OF THE SCALE (THE SCALE POSTS BY ITSELF IN ITS WIFI NETWORK) AND FROM THE LIMS / ELN FORWARDING OF THE APP (THE BROWSER POSTS) - AND KEEPS THEM AS JSON LINES. ---------------------------------------------------------------------------------------- ^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! ---------------------------------------------------------------------------------------- WEBHOOK EXPORT: https://up-scales.com/manual.html#WiFiWebhook LIMS / ELN FORWARDING OF THE APP: https://up-scales.com/manual.html#LimsForwarding ALL EXAMPLES FOR YOUR IT: https://up-scales.com/hardware/integration-lims-webhook-api-examples.html#examples ---------------------------------------------------------------------------------------- (C) Johann Anderson, 2025-2026 http://farm23.es ---------------------------------------------------------------------------------------- MIT License - Copyright (c) 2025-2026 Johann Anderson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------------------- This script will: Check every request with one of the three security modes of the scale: 1 https + a token (Bearer, X-API-Key or ?token=) - also the mode of the app 2 HMAC-signed (X-Upscale-Time / -Nonce / -Signature) - it signs its answer 3 sealed envelope (AES-256-GCM) - it seals its answer and refuses a replayed n Answer the preflight of the browser (CORS, OPTIONS) for the app. Drop an event that comes twice (same "id") - and still acknowledge it. The same id with other content: CONFLICT (in chain.log + receiver.log, kept as well). Store every event as one JSON line: /events//.jsonl Check the hash chains of "activity", "legal" and "sales" events, per scale: every entry against the one before AND the one after it - also an entry that fills a gap later. Check every seal of the scale by itself (event "sealed", and the seal inside a sealed JSON / HTML file the app sends): the ECDSA signature of the scale, its certificate with the public UP-SCALE licence keys (key confirmed by UP-SCALE), the Device ID. A scale without a certificate: its first key is noted, a changed key is reported. Check the chain checkpoints (seal kind 4: the scale signs the head of its activity log and of its sales log; kind 5: of the LEGAL MODE store) against the entries here: "SIGNED up to N" = every entry up to N that links to it is covered by the signature of the scale. Pair a sale or a print of the balance that has a LEGAL MODE number ("UP-000123", RS-232 dongles) with its LEGAL MODE entry: the sale id, the grams / the value and the time must be the same (linked, MISMATCH, waiting, entry missing). Answer {"ack": "", "ref": ""} - and requests for the scale. Answer "stored" as an archive receiver: {"stored": {"type": "activity" | "legal", "upto": N, "chain": ""}} - N = the newest entry up to which every entry is written to the disk in one chain this script recomputed itself. The scale (and the app with "free only what the receiver confirmed as saved") may then reuse the space of those entries. Keeping these files safe (backup) is your job. Answer the idle poll of the scale (GET ?device=...&poll=1, sealed: &n=..&t=..). ---------------------------------------------------------------------------------------- 1st: What you need: ---------------------------------------------------------------------------------------- 1.) Node.js 18 or newer - no packages (node:http, node:https, node:crypto, node:fs). 2.) https for mode 1 and for the app (browsers only post from the app to https): put it behind your web server (nginx / Apache as a proxy to this port), or give it a certificate itself: UPSCALE_CERT=/path/cert.pem UPSCALE_KEY=/path/key.pem Modes 2 and 3 also work on plain http in your own network. 3.) Your settings (environment variables, or change the defaults below): UPSCALE_PORT the port (default 8080) UPSCALE_MODES the modes this receiver takes, e.g. "1,2,3" or "3" UPSCALE_TOKENS mode 1: the token(s), comma separated (the scale's secret with the credential "Bearer token" / "X-API-Key" / "token in the address", and the token of the app's LIMS forwarding) UPSCALE_SECRET modes 2 + 3: the secret you typed into the webhook card UPSCALE_DATA the folder for the events and the state files UPSCALE_STORED "0" = no "stored" answers (the scale and the app then free their entries as without this receiver) 4.) In the app: LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export: http(s)://:/, the same security mode and the secret. Or Settings -> 🔗 LIMS / ELN FORWARDING: the https address and the token (mode 1). UPSCALE_SECRET=my-secret UPSCALE_MODES=2,3 node upscale-receiver-node.js ---------------------------------------------------------------------------------------- What you get in the data folder: ---------------------------------------------------------------------------------------- events//.jsonl every event as it came, one line each, with "_rx" added: at (time received), mode, chain (ok, filled, broken, gap, first, same, conflict, no raw), seal (certified = key confirmed by UP-SCALE, same_key, first_key, key_changed, bad + seal_why), checkpoint ({"activity": "signed" | "waiting" | "differs", "sales": ..., "legal": ...} | "not checked" for a seal that is not good), file (match, differs, no seal, not matched), pair (linked, MISMATCH , waiting, entry missing), conflict (a repeated id with other content: the receipt of the first one); the day is the UTC day chain.log one line per checked entry and seal: OK, FILLED, BROKEN, GAP, FIRST, AGAIN, CONFLICT, NOT CHECKED, SEAL OK / BAD / KEY CHANGED, CHECKPOINT WAITING / DIFFERS / not checked, SIGNED up to N (dropped), PAIR UP-n linked / MISMATCH / WAITING / entry missing receiver.log refused requests (wrong token, signature, replay), CONFLICT (a repeated id with other content) requests/.json (you write it) requests for that scale, see below state/ chain/-/ every entry with its H (in files of 256 entries) + runs.json (the numbers here), checkpoints/.json (the newest signed one per kind, the waiting ones), seal-keys/ .json (the key of the scale), pairs/ .json (the sales / prints waiting for their LEGAL MODE entry, the entries waiting for their sale), the last n per scale (mode 3), one marker per event id (receipt + content digest), stored-marks.json (the "stored" answer per scale + kind: number + H) Check the whole folder again later, offline: python3 upscale-verify.py ---------------------------------------------------------------------------------------- */ 'use strict'; const http = require('node:http'), https = require('node:https'), crypto = require('node:crypto'), fs = require('node:fs'), path = require('node:path'); // ---------- your settings ---------- const PORT = Number(process.env.UPSCALE_PORT || 8080); const MODES = (process.env.UPSCALE_MODES || '1,2,3').split(',').map(Number); const TOKENS = (process.env.UPSCALE_TOKENS || 'CHANGE-ME-TOKEN').split(',').map((t) => t.trim()).filter(Boolean); const SECRET = process.env.UPSCALE_SECRET || 'CHANGE-ME-SECRET'; const DATA = (process.env.UPSCALE_DATA || path.join(__dirname, 'upscale-data')).replace(/\/+$/, ''); // the app's address (the offline app - the single file - sends the origin "null": add 'null' only if you use it) const ORIGINS = ['https://up-scales.com']; const MAX_BODY = 20 * 1024 * 1024; // (the app can send a sealed report file as base64) const STORED = process.env.UPSCALE_STORED !== '0'; // answer "stored" (the archive receiver) // the secret of a scale (modes 2 + 3). Several scales with their own secrets: // const secrets = {'a1b2c3d4e5f6': 'secret of scale 1', '0a1b2c3d4e5f': 'secret of scale 2'}; // return secrets[device.toLowerCase()] || ''; function secret_for(device) { return SECRET; } // requests for the scale, sent with the answer to an event of the scale or to its idle poll (max. 4 per answer). // This example takes them from /requests/.json (a JSON list you or another program writes), e.g. // [{"get":"weight","id":"w1"}, {"get":"status"}, {"get":"things","from":0}, // {"get":"activity","since":1200}, {"get":"legal","since":1}, {"get":"sales","day":"2026-11-27"}, // {"do":"tare","id":"t1"}, {"do":"zero"}, {"do":"log","text":"batch 42 started"}] // "get": the scale answers with an event "reply" (request, id, ok, the values or error); "since" / "day": the records // come again as normal events. "do": only when "remote actions" is switched on at the scale - refused in LEGAL MODE, // every action goes into the scale's activity log. A request that was handed out is gone from the file: if the // answer is lost on the way, write it again. // Or fixed ones: return [{get: 'weight', id: 'w1'}]; function requests_for(device) { const file = path.join(DATA, 'requests', device.replace(/[^A-Za-z0-9_-]/g, '') + '.json'); if(!fs.existsSync(file)) {return [];} let list = null; try {list = JSON.parse(fs.readFileSync(file, 'utf8'));} catch(e) {} if(!Array.isArray(list) || !list.length) {fs.unlinkSync(file); return [];} const rest = list.slice(4); if(rest.length) {fs.writeFileSync(file, JSON.stringify(rest));} else {fs.unlinkSync(file);} return list.slice(0, 4); } function not_set(s) {return !s || s.startsWith('CHANGE-ME');} function utc_now() {return new Date().toISOString().replace(/\.\d+Z$/, 'Z');} function log_line(name, text) {fs.appendFileSync(path.join(DATA, name), utc_now() + ' ' + text + '\n');} function json_file(file) { try {const j = JSON.parse(fs.readFileSync(file, 'utf8')); return (j && typeof j == 'object' && !Array.isArray(j)) ? j : {};} catch(e) {return {};} } function write_json(file, obj) {fs.writeFileSync(file + '.tmp', JSON.stringify(obj)); fs.renameSync(file + '.tmp', file);} function same(a, b) { const x = Buffer.from(String(a)), y = Buffer.from(String(b)); return x.length == y.length && crypto.timingSafeEqual(x, y); } const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest(); const hex64 = (v) => typeof v == 'string' && /^[0-9a-fA-F]{64}$/.test(v); // the 12-byte AES-GCM nonce: the 6 bytes of the Device ID (XOR 0xFF for the answer) + n as 6 bytes little-endian function seal_nonce(device, n, answer) { const b = Buffer.alloc(12); Buffer.from(device, 'hex').copy(b, 0); if(answer) {for(let i = 0; i < 6; i++) {b[i] ^= 0xFF;}} b.writeUIntLE(n, 6, 6); return b; } // ---------- the hash chains of "activity", "legal" and "sales" ---------- // activity: H = SHA-256(H before | seq as uint32 little-endian | the entry, 16 bytes); H before seq 0 = 32 zero bytes // legal: H = SHA-256(H before | the entry, 48 bytes); H before number 1 = 32 zero bytes // sales: chain = the first 8 bytes of SHA-256(chain before | the record without its last 8 bytes | its alibi bytes, if any), the chain // is the last 8 bytes of the record itself; before seq 1 = 8 zero bytes // The scale sends "raw" and "alibi_raw" as base64 and "chain" (H after the entry) as hex; the app sends them as hex ("h"). // bytes from a text: the scale sends base64, the app hex (size: the length it must have, 0 = any) function hex_or_b64(v, src, size) { v = String(v || ''); const isHex = v.length % 2 == 0 && /^[0-9a-fA-F]*$/.test(v); if(isHex && (size ? v.length == 2 * size : src != 'scale')) {return Buffer.from(v, 'hex');} return (v.length % 4 == 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(v)) ? Buffer.from(v, 'base64') : Buffer.alloc(0); } // a number of a chain entry or a seal field: an integer 0...4294967295 (a JSON number or a text of digits) | null function entry_number(v) { if(typeof v == 'string' && /^[0-9]{1,10}$/.test(v)) {v = Number(v);} return (typeof v == 'number' && Number.isInteger(v) && v >= 0 && v <= 4294967295) ? v : null; } function is_map(v) {return !!v && typeof v == 'object' && !Array.isArray(v);} // the parts of an activity / legal / sales entry: {dev, type, num, raw, rawok, h (H after it, '' none), hb (H before it: the app at the // start of a piece, '' none), alibi, no_alibi} | null: not such an event | a string: why not. The number: an integer 0...4294967295, else // the event is no chain entry ('no number') function entry_parts(ev) { const type = ev.type, d = ev.data; if((type != 'activity' && type != 'legal' && type != 'sales') || !is_map(d)) {return null;} const src = ev.src; const num = entry_number(d.seq ?? d.number ?? d.no); if(num === null) {return 'no number';} const hlen = type == 'sales' ? 16 : 64; const isH = (v) => typeof v == 'string' && v.length == hlen && /^[0-9a-fA-F]+$/.test(v); let h = isH(d.chain) ? d.chain.toLowerCase() : (isH(d.h) ? d.h.toLowerCase() : ''); const hb = isH(d.hb) ? d.hb.toLowerCase() : ''; let raw, rawok, alibi = Buffer.alloc(0), no_alibi = false; if(type == 'sales') { raw = hex_or_b64(d.raw, src, 0); rawok = raw.length > 8; if(rawok) {h = raw.subarray(raw.length - 8).toString('hex');} // (the chain is part of the record) alibi = hex_or_b64(d.alibi_raw, src, 0); no_alibi = !alibi.length && !!d.alibi; // (an alibi number without its bytes: the link can't be computed) } else { const size = type == 'activity' ? 16 : 48; raw = hex_or_b64(d.raw, src, size); rawok = raw.length == size; } return {dev: String(ev.device || d.device || '').toLowerCase(), type: type, num: num, raw: raw, rawok: rawok, h: h, hb: hb, alibi: alibi, no_alibi: no_alibi}; } function chain_link(type, before, num, raw, alibi) { if(type == 'sales') {return sha256(Buffer.concat([Buffer.from(before, 'hex'), raw.subarray(0, raw.length - 8), alibi || Buffer.alloc(0)])).toString('hex').slice(0, 16);} const seq = Buffer.alloc(4); seq.writeUInt32LE(num >>> 0); return sha256(Buffer.concat([Buffer.from(before, 'hex'), type == 'activity' ? seq : Buffer.alloc(0), raw])).toString('hex'); } // the H before the first entry of a chain ('' = not the first one) function chain_start(type, num) { if((type == 'activity' && num == 0) || (type == 'legal' && num == 1)) {return '00'.repeat(32);} if(type == 'sales' && num == 1) {return '00'.repeat(8);} return ''; } function same_hex(a, b) {return !!a && !!b && same(String(a).toLowerCase(), String(b).toLowerCase());} const CHUNK = 256; // entries per state file function dev_name(dev) {return String(dev).toLowerCase().replace(/[^0-9a-z]/g, '');} // The chain state per scale + kind (activity, legal, sales), read when needed and written after the event is on the disk: // state/chain/-/.json = {"": {"h": H after it, "r": the raw entry (hex), "b": the H before // it the entry was linked with ('' = not linked yet), "a": the alibi bytes of a sale (hex), "n": 1 = a sale kept without its alibi // bytes (not linked), "x": 1 = BROKEN link}} // state/chain/-/runs.json = {"runs": [[first, last], ...]} - the numbers kept // state/checkpoints/.json = {"signed": {"": the newest checkpoint whose H matched: upto, h, from (the lowest entry covered // by its signature), log_seq, time, seal, at}, "waiting": {"": [checkpoints whose entry is not here yet]}} // state/seal-keys/.json = {"pk": the public key of the scale, "certified": true | false, "at"} (the first key seen, or the key // confirmed by UP-SCALE) class Chains { constructor() {this.files = {}; this.dirty = new Set(); this.snap = {};} path(...parts) {return path.join(DATA, 'state', ...parts);} file(p, watch) { if(!(p in this.files)) { this.files[p] = json_file(p); if(watch) {this.snap[p] = JSON.stringify(this.files[p]);} } return this.files[p]; } changed(p) {this.dirty.add(p);} keys(dev) {return this.file(this.path('seal-keys', dev_name(dev) + '.json'), true);} cps(dev) { const c = this.file(this.path('checkpoints', dev_name(dev) + '.json'), true); for(const k of ['signed', 'waiting']) {if(!is_map(c[k])) {c[k] = {};}} return c; } pairs(dev) { const c = this.file(this.path('pairs', dev_name(dev) + '.json'), true); for(const k of ['need_entry', 'need_sale']) {if(!is_map(c[k])) {c[k] = {};}} return c; } folder(dev, type) {return path.join('chain', dev_name(dev) + '-' + type);} chunk(dev, type, num) {return this.path(this.folder(dev, type), String(Math.floor(num / CHUNK)).padStart(8, '0') + '.json');} get(dev, type, num) { if(num < 0) {return null;} const e = this.file(this.chunk(dev, type, num))[String(num)]; return is_map(e) ? e : null; } put(dev, type, num, e) { const p = this.chunk(dev, type, num); this.file(p)[String(num)] = e; this.changed(p); const rp = this.path(this.folder(dev, type), 'runs.json'); const runs = this.runs(dev, type).concat([[num, num]]).sort((x, y) => x[0] - y[0] || x[1] - y[1]); const merged = []; for(const [a, b] of runs) { if(merged.length && a <= merged[merged.length - 1][1] + 1) {merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], b);} else {merged.push([a, b]);} } this.file(rp).runs = merged; this.changed(rp); } runs(dev, type) { const r = this.file(this.path(this.folder(dev, type), 'runs.json')).runs; return Array.isArray(r) ? r.filter((x) => Array.isArray(x) && x.length == 2 && Number.isInteger(x[0]) && Number.isInteger(x[1])).map((x) => [x[0], x[1]]) : []; } // the newest number kept below num | the oldest above it (null: none) below(dev, type, num) { let best = null; for(const [a, b] of this.runs(dev, type)) {if(a < num) {best = Math.min(b, num - 1);}} return best; } above(dev, type, num) { for(const [a, b] of this.runs(dev, type)) {if(b > num) {return Math.max(a, num + 1);}} return null; } flush() { for(const p of Object.keys(this.snap)) {if(JSON.stringify(this.files[p]) != this.snap[p]) {this.dirty.add(p);}} for(const p of [...this.dirty].sort()) {fs.mkdirSync(path.dirname(p), {recursive: true}); write_json(p, this.files[p]);} this.dirty = new Set(); } } function ask_text(type, a) {return type != 'sales' ? ' (ask for them: {"get":"' + type + '","since":' + a + '})' : '';} // does entry num (kept: e) follow the H h? -> true | false | null (not known: no raw entry, a sale without its alibi bytes) function follows_from(type, h, num, e) { if(e.r && !e.n) {return same_hex(chain_link(type, h, num, Buffer.from(e.r, 'hex'), Buffer.from(e.a || '', 'hex')), e.h);} if(e.b) {return same_hex(e.b, h);} return null; } const BROKEN_TEXT = 'BROKEN - the entry or the one before it is not what the chain says'; // the hash chain of "activity", "legal" and "sales" (entry_parts): every entry is kept with its H, so it is checked against the entry // before it AND the one after it - also when it fills a gap later. A kept H is never replaced by another one, except an entry without // raw whose H the entry after it does not follow, by a raw entry that links to both neighbours. -> the state: ok | filled | broken | gap | // first | same | conflict | no raw | no number | '' (not a chain event) function chain_check(ev, ch) { const p = entry_parts(ev); if(p === null || typeof p == 'string') {return p || '';} const dev = p.dev, type = p.type, num = p.num, raw = p.raw; const rawok = p.rawok && !p.no_alibi; const what = dev + ' ' + type + ' ' + num; const prev = ch.get(dev, type, num - 1); const start = chain_start(type, num); const before = prev ? prev.h : (start || p.hb); const calc = (before && rawok) ? chain_link(type, before, num, raw, p.alibi) : ''; const new_h = (calc && (!p.h || same_hex(calc, p.h))) ? calc : p.h; const old = ch.get(dev, type, num); let note = '', e = null, broken = ''; if(old && old.r) { if(p.rawok && old.r == raw.toString('hex')) { if(p.alibi.length && old.n) { // (the alibi bytes of a sale kept without them: its own chain bytes must come out of them) if(calc && !same_hex(calc, old.h)) { log_line('chain.log', what + ' CONFLICT - these alibi bytes do not give the chain of the record here'); return 'conflict'; } e = Object.assign({}, old, {a: p.alibi.toString('hex'), b: calc ? before : ''}); delete e.n; note = 'alibi bytes added - '; } else if(p.alibi.length && (old.a || '') != p.alibi.toString('hex')) { log_line('chain.log', what + ' CONFLICT - the same record with other alibi bytes is here already'); return 'conflict'; } else { log_line('chain.log', what + ' AGAIN - the same entry is here already'); return 'same'; } } else if(!p.rawok && (!p.h || same_hex(p.h, old.h))) { log_line('chain.log', what + ' AGAIN - the same entry is here already'); return 'same'; } else { log_line('chain.log', what + ' CONFLICT - another entry with this number is here already (the first one stays the checked one)'); return 'conflict'; } } else if(old) { // (an entry kept with its H only) if(!new_h || same_hex(new_h, old.h)) { if(!p.rawok) { log_line('chain.log', what + ' AGAIN - the same entry is here already'); return 'same'; } e = Object.assign({}, old, {r: raw.toString('hex'), b: (calc && same_hex(calc, old.h)) ? before : ''}); if(p.alibi.length) {e.a = p.alibi.toString('hex');} if(p.no_alibi) {e.n = 1;} if(calc && !same_hex(calc, old.h)) { broken = BROKEN_TEXT; e.x = 1; } else if(e.b) { delete e.x; } } else { const nxt = ch.get(dev, type, num + 1); if(!(calc && same_hex(calc, new_h) && (prev || start) && nxt && follows_from(type, calc, num + 1, nxt))) { log_line('chain.log', what + ' CONFLICT - another H for this number is here already (the first one stays the checked one)'); return 'conflict'; } note = 'CONFLICT - replaces an entry without raw that had another H - '; } } if(e === null) { e = {h: new_h, r: p.rawok ? raw.toString('hex') : '', b: (calc && same_hex(calc, new_h)) ? before : ''}; if(p.alibi.length) {e.a = p.alibi.toString('hex');} if(p.no_alibi) {e.n = 1;} if(calc && !same_hex(calc, new_h)) { broken = BROKEN_TEXT; e.x = 1; } } if(!e.h) { log_line('chain.log', what + ' NOT CHECKED - no raw entry and no chain H'); return 'no raw'; } ch.put(dev, type, num, e); // the entry after it (it came first: this one fills a gap) const nxt = ch.get(dev, type, num + 1); let follows = null, unchecked = false; if(nxt) { follows = follows_from(type, e.h, num + 1, nxt); if(follows) { if(nxt.x || (nxt.r && !nxt.n && nxt.b != e.h)) { delete nxt.x; nxt.b = e.h; ch.put(dev, type, num + 1, nxt); } } else if(follows === false && !p.rawok) { unchecked = true; // (an entry without raw does not make the one after it broken) } else if(follows === false) { nxt.x = 1; ch.put(dev, type, num + 1, nxt); if(!broken) {broken = 'BROKEN - entry ' + (num + 1) + ' does not follow this one';} } } const linked = !!e.b && !!(prev || start); const lo = ch.below(dev, type, num), hi = ch.above(dev, type, num); const missing = []; if(lo !== null && lo < num - 1) {missing.push([lo + 1, num - 1]);} if(hi !== null && hi > num + 1) {missing.push([num + 1, hi - 1]);} let state, text; if(broken) { state = 'broken'; text = broken; } else if(!rawok) { state = 'no raw'; text = 'NOT CHECKED - ' + (p.no_alibi ? 'no alibi bytes ("alibi_raw")' : 'no raw entry') + ': H noted'; } else if(hi !== null) { const parts = (linked ? [start ? 'starts the chain' : 'links to ' + (num - 1)] : []).concat(follows ? [(num + 1) + ' follows it'] : []); state = 'filled'; text = 'FILLED - ' + (parts.length ? parts.join(' and ') : 'not linked yet'); } else if(linked) { state = 'ok'; text = 'OK'; } else if(lo !== null) { state = 'gap'; text = 'GAP -'; } else { state = 'first'; text = 'FIRST - H noted' + (e.b ? ' (checked with the H before it, "hb")' : ''); } if(unchecked) {text += ' - ' + (num + 1) + ' not checked against an entry without raw';} if(missing.length && (state == 'filled' || state == 'gap' || state == 'broken')) { const ranges = missing.map(([a, b]) => a == b ? String(a) : a + '...' + b).join(', '); text += (state == 'gap' ? ' ' + ranges + ' missing' : ' - still missing: ' + ranges) + ask_text(type, missing[0][0]); } if(note.startsWith('CONFLICT')) {state = 'conflict';} log_line('chain.log', what + ' ' + note + text); checkpoint_after(ch, dev, type, num); return state; } // ---------- the seals of the scale (ECDSA P-256) ---------- // seal = payload (80 bytes) + the signature of the scale over SHA-256(payload) (64 bytes, raw r | s); payload: [0] 1 | [1] kind: 1 report, // 2 file, 3 signature, 4 chain checkpoint, 5 LEGAL MODE store | [2-7] Device ID | [8-11] the seq of its own activity log entry | [12-15] // time (epoch) | [16-19] number (kind 1 / 3: the report, kind 4: N = the newest activity seq covered, kind 5: the newest legal number) // | [20] user | [21] meaning (kind 3) / how (kind 4: 0 an app asked, 1 the webhook export) | [22-41] user name (kinds 1-3) // | kind 4: [22-25] S = the newest sales seq (0: none), [26-33] the sales chain after S | [42-73] SHA-256 of the document (kind 4: the // activity H after N, kind 5: the legal H after the newest number) | [74-77] kind 4 / 5: the oldest entry still kept on the scale // certificate = payload (80 bytes) + the signature of the UP-SCALE licence key over SHA-256(payload); payload: [0] the licence key id // (1 | 2) | [1] edition (1 ENTERPRISE) | [2-7] Device ID | [8-11] certificate number | [12-15] made | [16-79] the public key of the scale const LICENCE_KEYS_REAL = {1: '04aaf58d81d222eacd3d696a5d6cd48e6169303c7677d29f2c8319ca1961fa0598e04759ffbac18c01525542c9bcb1c9dc8fd091442bfcaa96688c9ed85f466f6b', 2: '0459765607ee8d42b4ed481b72285684a5c0063cbcf17adc02320a57957f30bc308186c7f60c9a5bc9f1b7adbeeec8543362396ea2c199147036ada9d925bd6941'}; // (tests only: UPSCALE_TEST_LICENCE_KEY=<130 hex: 04 | x | y> takes the place of both keys - never on a real receiver) const TEST_KEY = /^04[0-9a-fA-F]{128}$/.test(process.env.UPSCALE_TEST_LICENCE_KEY || '') ? process.env.UPSCALE_TEST_LICENCE_KEY.toLowerCase() : ''; const LICENCE_KEYS = TEST_KEY ? {1: TEST_KEY, 2: TEST_KEY} : LICENCE_KEYS_REAL; const SEAL_KINDS = {1: 'report', 2: 'file', 3: 'signature', 4: 'chain_checkpoint', 5: 'legal_store'}; const SEAL_GOOD = ['certified', 'same_key', 'first_key']; // (only a seal with one of these is taken as a checkpoint) // ECDSA P-256 over SHA-256(data), pk = x | y (64 bytes), sig = r | s (64 bytes) -> true | false function ecdsa_ok(pk, data, sig) { try { const key = crypto.createPublicKey({key: {kty: 'EC', crv: 'P-256', x: pk.subarray(0, 32).toString('base64url'), y: pk.subarray(32, 64).toString('base64url')}, format: 'jwk'}); return crypto.verify('sha256', data, {key: key, dsaEncoding: 'ieee-p1363'}, sig); } catch(e) { return false; } } function unhex(v) { v = typeof v == 'string' ? v : ''; return (v.length % 2 == 0 && /^[0-9a-fA-F]*$/.test(v)) ? Buffer.from(v, 'hex') : Buffer.alloc(0); } function seal_parse(seal) { if(seal.length != 144 || seal[0] != 1) {return null;} const u32 = (at) => seal.readUInt32LE(at); return {kind: seal[1], device: seal.subarray(2, 8).toString('hex'), seq: u32(8), time: u32(12), number: u32(16), user: seal[20], how: seal[21], sales_upto: u32(22), sales_chain: seal.subarray(26, 34).toString('hex'), hash: seal.subarray(42, 74).toString('hex'), oldest: u32(74)}; } // a seal with its certificate (or the public key that came with it) -> {res, why, p, cert_id}. res: certified (key confirmed by UP-SCALE) // | same_key | first_key (no certificate, noted now) | key_changed (no certificate, another key than the noted one) | bad. The key per // scale (ch.keys): the first one seen, replaced by a key confirmed by UP-SCALE - then the checkpoints taken from seals without a // certificate of another key are dropped function seal_verify(seal, cert, pk, ch) { const p = seal_parse(seal); if(!p) {return {res: 'bad', why: ['format'], p: null, cert_id: ''};} const why = []; let certified = false, cert_id = ''; if(pk.length == 65 && pk[0] == 4) {pk = pk.subarray(1);} if(cert.length) { if(cert.length != 144 || !LICENCE_KEYS[cert[0]]) { why.push('cert_format'); } else { cert_id = cert.subarray(80, 84).toString('hex').toUpperCase(); if(!ecdsa_ok(Buffer.from(LICENCE_KEYS[cert[0]], 'hex').subarray(1), cert.subarray(0, 80), cert.subarray(80))) {why.push('cert_bad');} else if(cert[1] != 1 || cert.subarray(2, 8).toString('hex') != p.device) {why.push('cert_other');} certified = why.length == 0; pk = cert.subarray(16, 80); } } if(pk.length != 64) {return {res: 'bad', why: why.concat(['nokey']), p: p, cert_id: cert_id};} if(!ecdsa_ok(pk, seal.subarray(0, 80), seal.subarray(80))) {why.push('signature');} if(why.length) {return {res: 'bad', why: why, p: p, cert_id: cert_id};} const dev = p.device, pin = ch.keys(dev), hex = pk.toString('hex'); if(certified) { if(pin.pk != hex) { if(pin.pk) { log_line('chain.log', dev + ' SEAL KEY CHANGED - a new key, confirmed by UP-SCALE (certificate ' + cert_id + '): noted'); if(!pin.certified) {drop_uncertified(ch, dev);} } for(const k of Object.keys(pin)) {delete pin[k];} Object.assign(pin, {pk: hex, certified: true, at: utc_now()}); } else if(!pin.certified) { pin.certified = true; } return {res: 'certified', why: [], p: p, cert_id: cert_id}; } if(!pin.pk) { Object.assign(pin, {pk: hex, certified: false, at: utc_now()}); return {res: 'first_key', why: [], p: p, cert_id: cert_id}; } return {res: pin.pk == hex ? 'same_key' : 'key_changed', why: [], p: p, cert_id: cert_id}; } // a key confirmed by UP-SCALE replaced a key without a certificate: the checkpoints of seals without a certificate go function drop_uncertified(ch, dev) { const cps = ch.cps(dev); for(const type of Object.keys(cps.signed).sort()) { const cp = cps.signed[type]; if(cp.seal != 'certified') { delete cps.signed[type]; log_line('chain.log', dev + ' ' + type + ' SIGNED up to ' + cp.upto + ' dropped - its seal had no certificate and another key than the one confirmed by UP-SCALE'); } } for(const type of Object.keys(cps.waiting).sort()) {cps.waiting[type] = (cps.waiting[type] || []).filter((w) => w.seal == 'certified');} } const SEAL_TEXT = {certified: 'OK - key confirmed by UP-SCALE (certificate %s)', same_key: 'OK - the same key as before (no certificate)', first_key: 'OK - the first key of this scale, noted (no certificate: later seals show "the same key")', key_changed: 'KEY CHANGED !!! - signed with another key than the noted one, and no certificate', bad: 'BAD - %s'}; function seal_line(dev, what, r) { log_line('chain.log', dev + ' SEAL ' + what + ' ' + SEAL_TEXT[r.res].replace('%s', r.res == 'certified' ? r.cert_id : r.why.join(', '))); } // the lowest entry covered from entry top downward: each entry linked with its H before, each H before = the H of the entry before it // (null: top itself is not linked) function covered_down(ch, dev, type, top) { let low = null, k = top; for(;;) { const e = ch.get(dev, type, k); if(!e || !e.b || e.x) {return low;} low = k; if(chain_start(type, k)) {return low;} const p = ch.get(dev, type, k - 1); if(!p || !same_hex(p.h, e.b)) {return low;} k--; } } // a signed chain head (seal kind 4: activity + sales, kind 5: legal; only a seal of SEAL_GOOD) against the entries kept -> signed | differs // | waiting (entry upto is not here yet). A checkpoint without a certificate never takes the place of one with it function checkpoint(ch, dev, type, upto, h, info) { const cps = ch.cps(dev), what = dev + ' ' + type; const e = ch.get(dev, type, upto); if(!e) { const waiting = (cps.waiting[type] || []).filter((w) => w.upto != upto).concat([Object.assign({}, info, {upto: upto, h: h})]); cps.waiting[type] = waiting.sort((x, y) => (x.log_seq || 0) - (y.log_seq || 0) || (x.upto || 0) - (y.upto || 0)).slice(-8); log_line('chain.log', what + ' CHECKPOINT ' + upto + ' WAITING - entry ' + upto + ' is not here yet'); return 'waiting'; } if(!same_hex(e.h, h)) { log_line('chain.log', what + ' CHECKPOINT ' + upto + ' DIFFERS - BROKEN: the scale signed another H after ' + upto + ' than the entries here'); return 'differs'; } const low = covered_down(ch, dev, type, upto); const cur = cps.signed[type]; const newCert = info.seal == 'certified', curCert = !!cur && cur.seal == 'certified'; if(!cur || (newCert && !curCert) || (newCert == curCert && upto >= (cur.upto || 0))) {cps.signed[type] = Object.assign({}, info, {upto: upto, h: h, from: low !== null ? low : upto + 1, at: utc_now()});} log_line('chain.log', what + ' SIGNED up to ' + upto + ' (' + (low !== null ? low + '...' + upto + ' covered by the signature' : 'not linked yet: nothing covered') + ')'); return 'signed'; } // after entry num was kept: a waiting checkpoint for it, and a signed checkpoint whose covered range now reaches further down (only while // the entry it signed still has the signed H) function checkpoint_after(ch, dev, type, num) { const cps = ch.cps(dev); for(const w of (cps.waiting[type] || []).filter((x) => x.upto == num)) { cps.waiting[type] = cps.waiting[type].filter((x) => x.upto != num); const info = Object.assign({}, w); delete info.upto; delete info.h; checkpoint(ch, dev, type, num, w.h, info); } const cp = cps.signed[type]; if(cp && cp.from - 2 <= num && num < cp.from) { const top = ch.get(dev, type, cp.upto); if(!top || !same_hex(top.h, cp.h)) { log_line('chain.log', dev + ' ' + type + ' CHECKPOINT ' + cp.upto + ' DIFFERS - the entry here has another H than the signed one'); return; } const low = covered_down(ch, dev, type, Math.min(cp.from, cp.upto)); if(low !== null && low < cp.from) { cp.from = low; log_line('chain.log', dev + ' ' + type + ' SIGNED up to ' + cp.upto + ' - covers ' + low + '...' + cp.upto + ' now'); } } } // a 'sealed' event: the seal checked by itself (signature, certificate, device), kind 4 / 5 against the chains -> fields for _rx function seal_event(ev, ch) { const d = ev.data, dev = String(ev.device || '').toLowerCase(); if(!is_map(d)) {return {};} const r = seal_verify(unhex(d.seal), unhex(d.cert), unhex(d.pk), ch), p = r.p; const rx = {}; if(p) { if(dev && dev != 'unknown' && p.device != dev) {r.why.push('device');} for(const [k, v] of [['kind', p.kind], ['log_seq', p.seq], ['number', p.number]]) {if(k in d && entry_number(d[k]) !== v) {r.why.push(k);}} if([1, 2, 3].includes(p.kind) && typeof d.sha256 == 'string' && /^[0-9a-fA-F]{64}$/.test(d.sha256) && d.sha256.toLowerCase() != p.hash) {r.why.push('hash');} if(r.why.length) {r.res = 'bad';} } seal_line(dev || '?', p ? (SEAL_KINDS[p.kind] || 'kind ' + p.kind) + ' log ' + p.seq : '?', r); rx.seal = r.res; if(r.why.length) {rx.seal_why = r.why.join(',');} if(p && (p.kind == 4 || p.kind == 5)) { const heads = p.kind == 4 ? [['activity', p.number, p.hash]].concat(p.sales_upto ? [['sales', p.sales_upto, p.sales_chain]] : []) : [['legal', p.number, p.hash]]; if(SEAL_GOOD.includes(r.res)) { const info = {log_seq: p.seq, time: p.time, seal: r.res}; if(p.kind == 5) {info.oldest = p.oldest;} rx.checkpoint = {}; for(const [type, upto, h] of heads) {rx.checkpoint[type] = checkpoint(ch, p.device, type, upto, h, info);} } else { for(const [type, upto] of heads) {log_line('chain.log', p.device + ' ' + type + ' CHECKPOINT ' + upto + ' not checked - the seal is ' + r.res);} rx.checkpoint = 'not checked'; } } return rx; } // a sealed file of the app (event 'sealed_file', a 'programs' report file) with its bytes ("content_base64"): the seal inside the file // against the file - a JSON file (its last field "seal") or an HTML report (
). -> fields for _rx function file_seal(ev, ch) { const d = ev.data; if(!is_map(d) || !d.content_base64) {return {};} let text; try {text = new TextDecoder('utf-8', {fatal: true}).decode(Buffer.from(String(d.content_base64), 'base64'));} catch(e) {return {file: 'not matched'};} const m = /,\n "seal": (\{[^\n]*\})\n\}\s*$/.exec(text); const tag = /
]*)>[\s\S]*?<\/div>/.exec(text); let seal, cert, pk, plain; if(m) { let field; try {field = JSON.parse(m[1]);} catch(e) {return {file: 'no seal'};} if(!is_map(field)) {return {file: 'no seal'};} [seal, cert, pk] = ['seal', 'cert', 'pk'].map((k) => String(field[k] || '')); plain = text.slice(0, m.index) + '\n}'; } else if(tag) { const attr = (k) => {const a = new RegExp('data-' + k + '="([0-9a-f]*)"').exec(tag[1]); return a ? a[1] : '';}; [seal, cert, pk] = [attr('seal'), attr('cert'), attr('pk')]; const code = /[0-9a-f]{16}<\/span>/.exec(text); const block = /
[\s\S]*?<\/div>/.exec(text); plain = text; if(code) {plain = plain.replace(code[0], () => '0000000000000000');} if(block) {plain = plain.replace(block[0], () => '
');} plain = plain.replace(tag[0], () => '
'); } else { return {file: 'no seal'}; } if(!seal) {return {file: 'no seal'};} const r = seal_verify(unhex(seal), unhex(cert), unhex(pk), ch), p = r.p; const dev = String(ev.device || '').toLowerCase(); const match = !!p && sha256(Buffer.from(plain, 'utf8')).toString('hex') == p.hash; if(p && !match) {r.why.push('hash');} if(p && dev && dev != 'unknown' && p.device != dev) {r.why.push('device');} if(r.why.length) {r.res = 'bad';} seal_line(dev || '?', 'in file ' + (d.file || '?'), r); const rx = {file: match ? 'match' : 'differs', seal: r.res}; if(r.why.length) {rx.seal_why = r.why.join(',');} return rx; } // ---------- PAIR CHECK: a sale / a print of the balance <-> its LEGAL MODE entry (RS-232 dongles in LEGAL MODE) ---------- // sales record (76 bytes, the "raw" of a sales event): [0-3] sale id | [4-6] seconds of the day | [11-14] grams (float) | [40-43] seq // | [65-66] minutes east of UTC (int16, 0x7FFF: not known) | [68-75] its chain; its alibi bytes "UP-000123" = the number of its entry // (other alibi texts: the balance's own number - not checked here) // LEGAL MODE entry (48 bytes): [0-3] number | [4-7] time (epoch) | [8] kind (1 sale, 8 print of the balance) | [40-43] the value used // (float g: the same float as the grams of the sale / the value of the print) | [44-47] kind 1: the sale id // print event: data.legal "UP-000123", raw = its activity entry: [0-3] time, [8-11] the value (float g) // state/pairs/.json = {"need_entry": {"": a sale / print whose entry is not here yet}, "need_sale": {"": the // sale id of an entry of kind 1 whose sale is not here yet}} (each at most PAIR_KEEP, the newest numbers stay) const PAIR_SALE_S = 300; // the time of the sale (the clock of the app) against the time of the entry (the clock of the scale) const PAIR_PRINT_S = 10; // the time of the print line against the entry (both the clock of the scale) const PAIR_KEEP = 1000; function legal_no(text) { const m = typeof text == 'string' ? /^UP-([0-9]{1,10})$/.exec(text) : null; return m ? entry_number(m[1]) : null; } // the epoch of a sale: its day ("YYYY-MM-DD"), the seconds of the day, minutes east of UTC (as sales_local_epoch of the scale) function day_epoch(day, secs, tz) { const m = typeof day == 'string' ? /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(day) : null; if(!m) {return null;} let y = Number(m[1]); const mo = Number(m[2]), d = Number(m[3]); if(mo <= 2) {y--;} const era = Math.floor(y / 400), yoe = y - era * 400; const doy = Math.floor((153 * (mo + (mo > 2 ? -3 : 9)) + 2) / 5) + d - 1; const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy; return (era * 146097 + doe - 719468) * 86400 + secs - tz * 60; } // the pair data of a sales event (its record with a LEGAL MODE alibi) or a print event -> object | null function pair_info(ev, p) { const d = ev.data; if(p && typeof p == 'object' && p.type == 'sales') { const raw = p.raw; const n = legal_no(p.alibi.length ? p.alibi.toString('latin1') : d.alibi); if(raw.length != 76 || n === null) {return null;} const tz = raw.readInt16LE(65); const secs = raw[4] | (raw[5] << 8) | (raw[6] << 16); return {what: 'sale', num: p.num, n: n, ref: raw.readUInt32LE(0), v: raw.subarray(11, 15).toString('hex'), time: tz != 0x7FFF ? day_epoch(d.day, secs, tz) : null}; } if(ev.type == 'print' && is_map(d)) { const n = legal_no(d.legal), raw = hex_or_b64(d.raw, ev.src, 16); if(n === null || raw.length != 16) {return null;} return {what: 'print', num: entry_number(d.seq), n: n, v: raw.subarray(8, 12).toString('hex'), time: raw.readUInt32LE(0)}; } return null; } // a sale / print against its entry -> [the fields that differ, a note] function pair_compare(info, raw) { const sale = info.what == 'sale', why = []; if(raw[8] != (sale ? 1 : 8)) {why.push('kind');} if(sale && raw.readUInt32LE(44) != info.ref) {why.push('sale_id');} const a = raw.readFloatLE(40), b = Buffer.from(info.v, 'hex').readFloatLE(0); if(!(a == b || (sale && b == 0 && a <= 0))) {why.push(sale ? 'grams' : 'value');} // (a sale books 0 for a value below 0) if(info.time === null || info.time === undefined) {return [why, ' (time not compared)'];} if(Math.abs(raw.readUInt32LE(4) - info.time) > (sale ? PAIR_SALE_S : PAIR_PRINT_S)) {why.push('time');} return [why, '']; } function keep_newest(m) { const keys = Object.keys(m).sort((x, y) => Number(x) - Number(y)); for(const k of keys.slice(0, Math.max(0, keys.length - PAIR_KEEP))) {delete m[k];} } // a sale / print with its LEGAL MODE number against the entry kept -> linked | MISMATCH | waiting | entry missing function pair_check(ch, dev, info) { const pairs = ch.pairs(dev), n = info.n; const what = dev + ' ' + (info.what == 'sale' ? 'sales' : 'print') + ' ' + info.num + ' PAIR UP-' + String(n).padStart(6, '0'); const e = ch.get(dev, 'legal', n); if(e && e.r && !e.x) { delete pairs.need_entry[String(n)]; if(info.what == 'sale') {delete pairs.need_sale[String(n)];} const [why, note] = pair_compare(info, Buffer.from(e.r, 'hex')); if(why.length) { log_line('chain.log', what + ' MISMATCH ' + why.join(',') + ' - the entry says something else than the ' + info.what); return 'MISMATCH ' + why.join(','); } log_line('chain.log', what + ' linked' + note); return 'linked' + note; } const legal = ch.cps(dev).signed.legal, oldest = legal ? legal.oldest : undefined; if((e && e.x) || (!e && Number.isInteger(oldest) && n < oldest)) { log_line('chain.log', what + ' entry missing - ' + (e ? 'the entry is BROKEN in the chain' : 'below the oldest entry kept on the scale')); return 'entry missing'; } pairs.need_entry[String(n)] = info; keep_newest(pairs.need_entry); log_line('chain.log', what + ' WAITING - entry ' + n + ' is not here yet'); return 'waiting'; } // a LEGAL MODE entry just kept: the sale / print waiting for it, or (kind 1) wait for its sale -> the result for _rx | '' function pair_legal(ch, dev, num) { const e = ch.get(dev, 'legal', num); if(!e || !e.r || e.x) {return '';} const pairs = ch.pairs(dev); const info = pairs.need_entry[String(num)]; if(info) {return pair_check(ch, dev, info);} const raw = Buffer.from(e.r, 'hex'); if(raw[8] == 1) { const ref = raw.readUInt32LE(44); pairs.need_sale[String(num)] = ref; keep_newest(pairs.need_sale); log_line('chain.log', dev + ' legal ' + num + ' PAIR WAITING - its sale (id ' + ref + ') is not here yet'); return 'waiting'; } return ''; } // ---------- a repeated id: the same content? ---------- // the event as one fixed text (keys sorted, numbers in one form) - the same in the three receivers function canon(v) { if(Array.isArray(v)) {return '[' + v.map(canon).join(',') + ']';} if(v === null || v === undefined) {return 'null';} if(typeof v == 'object') {return '{' + Object.keys(v).sort().map((k) => JSON.stringify(k) + ':' + canon(v[k])).join(',') + '}';} if(typeof v == 'boolean') {return v ? 'true' : 'false';} if(typeof v == 'number') { if(!isFinite(v)) {return 'null';} if(Number.isInteger(v) && Math.abs(v) < 1e15) {return String(v);} const m = v.toExponential(16).split('e'); return m[0] + 'e' + parseInt(m[1], 10); } return JSON.stringify(String(v)); } // what a repeated id is compared by: a chain entry by its raw bytes (a sale without its alibi bytes too: its chain bytes bind them), a seal // by the seal, any other event by its content without sent_at, env and _rx (the scale and the app send the same record with other fields // around it) function content_digest(ev) { const p = entry_parts(ev); if(p && typeof p == 'object' && p.rawok) {return sha256(Buffer.concat([Buffer.from(p.type + '|' + p.num + '|'), p.raw])).toString('hex');} const d = ev.data; if(ev.type == 'sealed' && is_map(d) && unhex(d.seal).length == 144) {return sha256(Buffer.concat([Buffer.from('sealed|'), unhex(d.seal)])).toString('hex');} const rest = {}; for(const k of Object.keys(ev)) {if(k != 'sent_at' && k != 'env' && k != '_rx') {rest[k] = ev[k];}} return sha256(Buffer.from(canon(rest), 'utf8')).toString('hex'); } // THE ARCHIVE RECEIVER ("stored"): per scale + kind the newest entry up to which every entry is on the disk in ONE chain this script // recomputed itself - marks[key] = {num, h} (base: only the first entry of a run is known, its H came with it, nothing is recomputed yet). // fresh: the entry was written now (false: it was on the disk already - the scale sends again). Only an entry with raw and with the chain // H of the sender ("chain" / "h") or the H before it ("hb") moves the mark. The run goes on with the next number (also a resend of one that // is on the disk); the next number whose chain H is not the recomputed one, or a new entry further back, starts a new run; a gap stops it // until the missing entries come (ask for them: {"get":"legal","since":...}). The first entry of a log (activity 0, legal 1) links to the // zero start. Activity + legal only. function stored_step(ev, marks, fresh) { const p = entry_parts(ev); if(p === null || typeof p == 'string' || p.type == 'sales') {return null;} const key = p.dev + ':' + p.type, m = marks[key], hb = p.hb || chain_start(p.type, p.num); if(!p.rawok || !(p.h || hb)) {return m || null;} if(m && p.num == m.num + 1 && (!hb || same_hex(hb, m.h))) { const calc = chain_link(p.type, m.h, p.num, p.raw); marks[key] = (!p.h || same(calc, p.h)) ? {num: p.num, h: calc} : {num: p.num, h: p.h, base: true}; } else if(fresh && (!m || p.num <= m.num + 1)) { const calc = hb ? chain_link(p.type, hb, p.num, p.raw) : ''; if(calc && (!p.h || same(calc, p.h))) {marks[key] = {num: p.num, h: calc};} else if(p.h) {marks[key] = {num: p.num, h: p.h, base: true};} } return marks[key] || null; } // the event as one line into events//.jsonl (on the disk before the answer) -> the line function store_line(type, event) { const line = JSON.stringify(event); fs.mkdirSync(path.join(DATA, 'events', type), {recursive: true}); try { const fd = fs.openSync(path.join(DATA, 'events', type, utc_now().slice(0, 10) + '.jsonl'), 'a'); try {fs.writeSync(fd, line + '\n'); fs.fsyncSync(fd);} finally {fs.closeSync(fd);} } catch(e) {throw new Refused(500, 'could not store');} return line; } class Refused extends Error { constructor(code, text, log = true) {super(text); this.code = code; this.text = text; this.log = log;} } // one request: everything is synchronous - node runs one at a time, the state files need no lock function processRequest(req, raw) { const url = new URL(req.url, 'http://x'), q = url.searchParams; const isPoll = req.method == 'GET'; const hdr = (k) => String(req.headers[k.toLowerCase()] || ''); if(isPoll && q.get('poll') !== '1') {throw new Refused(405, 'GET only for the poll', false);} let body = null; // (a number that does not fit a double - 1e400 - makes the body no event, as in the other receivers) if(!isPoll) {try {body = JSON.parse(raw.toString('utf8'), (k, v) => {if(typeof v == 'number' && !isFinite(v)) {throw new Error('number');} return v;});} catch(e) {}} // which mode: the form of the request says it (the mode must be one you accept - each has its own secret) let mode = 1; if(hdr('X-Upscale-Signature')) {mode = 2;} else if(isPoll ? q.has('n') : (body && body.schema === 'upscale.sealed/1')) {mode = 3;} if(!MODES.includes(mode)) {throw new Refused(401, 'mode ' + mode + ' not accepted here', false);} // (not set up yet: refused without writing anything) if(mode == 1 && TOKENS.every(not_set)) {throw new Refused(503, 'set UPSCALE_TOKENS', false);} const device = isPoll ? String(q.get('device') || '') : String((body && body.device) || ''); if(mode != 1 && not_set(secret_for(device))) {throw new Refused(503, 'set UPSCALE_SECRET', false);} for(const sub of ['', 'events', 'state', 'requests']) {fs.mkdirSync(path.join(DATA, sub), {recursive: true});} let event = null, nonce = '', n = 0; if(mode == 1) { // the token: Authorization: Bearer, X-API-Key or ?token= (the app's "receiver without CORS" mode, the scale's // "token in the address"). Basic or a header of your own: check hdr('Authorization') / hdr('Your-Header') here. const auth = hdr('Authorization'); const given = auth.startsWith('Bearer ') ? auth.slice(7) : (hdr('X-API-Key') || String(q.get('token') || '')); if(!TOKENS.some((t) => !not_set(t) && same(t, given))) {throw new Refused(401, 'mode 1: wrong or missing token');} event = body; } else if(mode == 2) { // signature over: time "." nonce "." body (the poll: an empty body) nonce = hdr('X-Upscale-Nonce'); const want = 'sha256=' + crypto.createHmac('sha256', secret_for(device)).update(hdr('X-Upscale-Time') + '.' + nonce + '.').update(raw).digest('hex'); if(!same(want, hdr('X-Upscale-Signature'))) {throw new Refused(401, 'mode 2: signature wrong');} // (a replayed signed request repeats an event id you have: it is dropped below. A time window is possible too - // Math.abs(Date.now() / 1000 - Number(hdr('X-Upscale-Time'))) < 300 - but only when the clock of the scale is set.) event = body; } else { n = isPoll ? q.get('n') : body.n; if(!/^[0-9a-fA-F]{12}$/.test(device) || !/^[0-9]{1,15}$/.test(String(n)) || Number(n) < 1 || Number(n) > 0xFFFFFFFFFFFF) {throw new Refused(400, 'mode 3: device or n wrong');} n = Number(n); // (up to 2^48: exact in a JS Number, which holds integers up to 2^53) const key = sha256(secret_for(device)); if(isPoll) { // the poll carries t = the AES-256-GCM tag of an EMPTY text with the nonce of n: checked before n counts const c = crypto.createCipheriv('aes-256-gcm', key, seal_nonce(device, n, false), {authTagLength: 16}); c.update(Buffer.alloc(0)); c.final(); if(!same(c.getAuthTag().toString('hex'), String(q.get('t') || '').toLowerCase())) {throw new Refused(401, 'mode 3: poll tag t wrong or missing');} } else { let plain; try { const bin = Buffer.from(String(body.ct || ''), 'base64'); if(bin.length <= 16) {throw new Error('short');} const d = crypto.createDecipheriv('aes-256-gcm', key, seal_nonce(device, n, false), {authTagLength: 16}); d.setAuthTag(bin.subarray(bin.length - 16)); plain = Buffer.concat([d.update(bin.subarray(0, bin.length - 16)), d.final()]).toString('utf8'); } catch(e) { throw new Refused(401, 'mode 3: the envelope does not open'); } try {event = JSON.parse(plain);} catch(e) {event = null;} } // replay check (only after the seal or the poll tag was checked): n only goes up. Kept per scale in state/last-n.json. const lastFile = path.join(DATA, 'state', 'last-n.json'); const last = json_file(lastFile), dev = device.toLowerCase(); if(n <= (last[dev] || 0)) {throw new Refused(409, 'mode 3: n ' + n + ' not higher than ' + (last[dev] || 0) + ' (replay)');} last[dev] = n; write_json(lastFile, last); } // ---------- store the event ---------- let answer = {}, status = 200; // (modes 2 + 3: the scale counts a 4xx for one event toward its "skipped after 5 refusals" only when the answer is signed / // sealed - so a refusal of a bad event goes out like a 2xx below; the 401 / 409 refusals above need no signature) const bad = !isPoll && (!event || typeof event != 'object' || typeof event.id != 'string' || !event.id || !event.type); if(bad) { if(mode == 1) {throw new Refused(400, 'not an event');} log_line('receiver.log', '400 not an event (' + String(req.socket.remoteAddress).replace(/^::ffff:/, '') + ')'); answer = {error: 'not an event'}; status = 400; } else if(!isPoll) { const type = String(event.type).toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'other'; // a doubled id (after a lost answer, a power cut ...): not stored again, but acknowledged again with its receipt - unless its // content differs (CONFLICT: kept as well, for the check). (live weight: every one has its own time id and is never sent again - // no marker for it) const hid = sha256(event.id).toString('hex'); const marker = path.join(DATA, 'state', 'seen', type, hid.slice(0, 2), hid); let ref, fresh = false; if(type != 'weight' && fs.existsSync(marker)) { const seen = fs.readFileSync(marker, 'utf8').split('\n'); ref = seen[0].trim(); const was = (seen[1] || '').trim(); if(was && !same(was, content_digest(event))) { const text = 'CONFLICT ' + event.id + ' - came again with other content (the first one: ' + ref + ')'; log_line('chain.log', text); log_line('receiver.log', text + ' (' + String(req.socket.remoteAddress).replace(/^::ffff:/, '') + ')'); event._rx = {at: utc_now(), mode: mode, conflict: ref}; store_line(type, event); fresh = true; // (this one is on the disk too: it may start a new "stored" run) } } else { // the checks: the chains (activity, legal, sales), the seals, the checkpoints - the state files are written after the event // (only the files of this scale + kind are read) const ch = new Chains(); const rx = {at: utc_now(), mode: mode, chain: chain_check(event, ch)}; // the pair check: a sale / print with its LEGAL MODE number <-> the entry const p = entry_parts(event); const kept = ['ok', 'filled', 'gap', 'first', 'broken', 'no raw'].includes(rx.chain); let pair = ''; if((kept && type == 'sales') || type == 'print') { const info = pair_info(event, p); if(info) {pair = pair_check(ch, (p && typeof p == 'object') ? p.dev : String(event.device || '').toLowerCase(), info);} } else if(kept && type == 'legal') { pair = pair_legal(ch, p.dev, p.num); } if(pair) {rx.pair = pair;} if(type == 'sealed') {Object.assign(rx, seal_event(event, ch));} else if(type == 'sealed_file' || type == 'programs') {Object.assign(rx, file_seal(event, ch));} event._rx = rx; // (no 2xx without a stored event: the scale sends it again; on the disk before "stored" may name it) const line = store_line(type, event); fresh = true; ch.flush(); // your receipt (max. 36 characters): here the day + the start of the SHA-256 of the stored line ref = utc_now().slice(0, 10).replace(/-/g, '') + '-' + sha256(line).toString('hex').slice(0, 16); if(type != 'weight') { fs.mkdirSync(path.dirname(marker), {recursive: true}); fs.writeFileSync(marker, ref + '\n' + content_digest(event)); } } answer.ack = event.id; answer.ref = ref; // the archive receiver: what is on the disk in one recomputed chain (activity / legal events of the scale and of the app) if(STORED) { const marksFile = path.join(DATA, 'state', 'stored-marks.json'); const marks = json_file(marksFile), was = JSON.stringify(marks); const m = stored_step(event, marks, fresh); if(JSON.stringify(marks) != was) {write_json(marksFile, marks);} if(m && !m.base) {answer.stored = {type: type, upto: m.num, chain: m.h};} } } // requests only to the scale (the app ignores them): its events have "src":"scale", modes 2 + 3 and the poll are the scale if(!bad && (isPoll || mode != 1 || event.src === 'scale')) { const list = requests_for(device); if(list.length) {answer.requests = list;} } // ---------- the answer: signed (mode 2) or sealed (mode 3) ---------- let out = JSON.stringify(answer); const headers = {}; if(mode == 2) { const t = String(Math.floor(Date.now() / 1000)); headers['X-Upscale-Time'] = t; headers['X-Upscale-Nonce'] = nonce; headers['X-Upscale-Signature'] = 'sha256=' + crypto.createHmac('sha256', secret_for(device)).update(t + '.' + nonce + '.' + out).digest('hex'); } else if(mode == 3) { const c = crypto.createCipheriv('aes-256-gcm', sha256(secret_for(device)), seal_nonce(device, n, true)); const ct = Buffer.concat([c.update(out, 'utf8'), c.final(), c.getAuthTag()]); out = JSON.stringify({schema: 'upscale.sealed/1', n: n, ct: ct.toString('base64')}); } return [status, out, headers]; } function handler(req, res) { const origin = String(req.headers.origin || ''); const cors = { 'Access-Control-Allow-Origin': ORIGINS.includes(origin) ? origin : ORIGINS[0], 'Vary': 'Origin', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', 'Access-Control-Allow-Private-Network': 'true'}; if(req.method == 'OPTIONS') {res.writeHead(204, cors); res.end(); return;} if(req.method != 'POST' && req.method != 'GET') {res.writeHead(405, cors); res.end(); return;} const chunks = []; let size = 0; req.on('data', (c) => { size += c.length; if(size > MAX_BODY) {res.writeHead(413, cors); res.end(); req.destroy(); return;} chunks.push(c); }); req.on('end', () => { if(res.writableEnded) {return;} let code, out, headers; try { [code, out, headers] = processRequest(req, Buffer.concat(chunks)); } catch(e) { const refused = e instanceof Refused; code = refused ? e.code : 500; out = refused ? JSON.stringify({error: e.text}) : ''; headers = {}; if(!refused || e.log) {try {log_line('receiver.log', code + ' ' + (refused ? e.text : String(e)) + ' (' + String(req.socket.remoteAddress).replace(/^::ffff:/, '') + ')');} catch(e2) {}} } res.writeHead(code, Object.assign({}, cors, headers, {'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(out)})); res.end(out); }); } const server = process.env.UPSCALE_CERT ? https.createServer({cert: fs.readFileSync(process.env.UPSCALE_CERT), key: fs.readFileSync(process.env.UPSCALE_KEY)}, handler) : http.createServer(handler); if(TEST_KEY) {console.error('NOTE: UPSCALE_TEST_LICENCE_KEY is set - a TEST licence key, not for a real receiver');} server.listen(PORT, () => { console.log('UP-SCALE receiver on ' + (process.env.UPSCALE_CERT ? 'https' : 'http') + '://0.0.0.0:' + PORT + ' - modes ' + MODES.join(',') + ' - data in ' + DATA); });