[ { "id": "f0e1a2b3c4d50001", "type": "tab", "label": "UP-SCALE records", "disabled": false, "info": "UPSCALE NODE-RED FLOW - UP-SCALES.COM RECORDS INTO A FILE AND YOUR LIMS (NODE-RED)\n\nA flow for Node-RED: 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 - checks them, writes each one as a JSON line into a file per type and day, calls the REST API of your LIMS (optional, with a field mapping), and only then answers the receipt {\"ack\",\"ref\"}. A record that is not stored gets no receipt: the scale (or the app) sends it again later.\n\n^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED!\n\nWEBHOOK EXPORT OF THE SCALE: https://up-scales.com/manual.html#WiFiWebhook\nLIMS / ELN FORWARDING OF THE APP: https://up-scales.com/manual.html#LimsForwarding\nALL EXAMPLES FOR YOUR IT: https://up-scales.com/hardware/integration-lims-webhook-api-examples.html#examples\n\n(C) Johann Anderson, 2025-2026 - http://farm23.es\n\nMIT License - Copyright (c) 2025-2026 Johann Anderson\nPermission is hereby granted, free of charge, to any person obtaining a copy of this\nsoftware and associated documentation files (the \"Software\"), to deal in the Software\nwithout restriction, including without limitation the rights to use, copy, modify,\nmerge, publish, distribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to the following\nconditions: The above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\nPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\nFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\nWHAT YOU NEED\n1. Node-RED 3.1 or newer (the function nodes load the Node.js module \"crypto\" - functionExternalModules on, the default).\n2. Menu -> Import -> this file -> Import. Double-click the flow tab -> Environment variables:\n UPSCALE_MODES \"1,3\" - 1 = token (the app, or the scale with \"Bearer token\"), 3 = sealed envelope (the scale). HMAC-signed (2) needs the exact bytes of the body, which the HTTP In node does not keep: choose the sealed envelope in the webhook box of the scale.\n UPSCALE_TOKENS mode 1: the token(s), comma separated\n UPSCALE_SECRET mode 3: the secret of the webhook box of the scale\n UPSCALE_FOLDER the folder for the JSON lines (created when missing)\n LIMS_URL the REST address of your LIMS (empty: no LIMS call); LIMS_TOKEN its token (Bearer)\n Change the mapping in the node \"map to the LIMS\" for your LIMS.\n3. Deploy. The address: http(s)://:1880/upscale (with httpNodeRoot in settings.js: below it).\n In the app: LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export: this address, security \"sealed envelope\", the same secret. Or Settings -> 🔗 LIMS / ELN FORWARDING: the https address + the token (browsers post only to https; the app also needs CORS: httpNodeCors: {origin: \"https://up-scales.com\", methods: \"GET,POST\"} in settings.js).\n4. The ids of the records and the last n per scale are kept in the flow context: in memory by default - set a file store (contextStorage in settings.js) to keep them over a restart.\n\nFor the hash chain check of the activity log and the LEGAL MODE store, the requests to the scale and the poll: upscale-receiver.py / .php / -node.js next to this file.\n", "env": [ { "name": "UPSCALE_MODES", "value": "1,3", "type": "str" }, { "name": "UPSCALE_TOKENS", "value": "CHANGE-ME-TOKEN", "type": "str" }, { "name": "UPSCALE_SECRET", "value": "CHANGE-ME-SECRET", "type": "str" }, { "name": "UPSCALE_FOLDER", "value": "/data/upscale", "type": "str" }, { "name": "LIMS_URL", "value": "", "type": "str" }, { "name": "LIMS_TOKEN", "value": "", "type": "str" } ] }, { "id": "f0e1a2b3c4d50002", "type": "comment", "z": "f0e1a2b3c4d50001", "name": "UP-SCALE: webhook of the scale + LIMS forwarding of the app -> file + LIMS -> receipt (MIT License - see the info of this tab)", "info": "UPSCALE NODE-RED FLOW - UP-SCALES.COM RECORDS INTO A FILE AND YOUR LIMS (NODE-RED)\n\nA flow for Node-RED: 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 - checks them, writes each one as a JSON line into a file per type and day, calls the REST API of your LIMS (optional, with a field mapping), and only then answers the receipt {\"ack\",\"ref\"}. A record that is not stored gets no receipt: the scale (or the app) sends it again later.\n\n^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED!\n\nWEBHOOK EXPORT OF THE SCALE: https://up-scales.com/manual.html#WiFiWebhook\nLIMS / ELN FORWARDING OF THE APP: https://up-scales.com/manual.html#LimsForwarding\nALL EXAMPLES FOR YOUR IT: https://up-scales.com/hardware/integration-lims-webhook-api-examples.html#examples\n\n(C) Johann Anderson, 2025-2026 - http://farm23.es\n\nMIT License - Copyright (c) 2025-2026 Johann Anderson\nPermission is hereby granted, free of charge, to any person obtaining a copy of this\nsoftware and associated documentation files (the \"Software\"), to deal in the Software\nwithout restriction, including without limitation the rights to use, copy, modify,\nmerge, publish, distribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to the following\nconditions: The above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\nPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\nFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\nWHAT YOU NEED\n1. Node-RED 3.1 or newer (the function nodes load the Node.js module \"crypto\" - functionExternalModules on, the default).\n2. Menu -> Import -> this file -> Import. Double-click the flow tab -> Environment variables:\n UPSCALE_MODES \"1,3\" - 1 = token (the app, or the scale with \"Bearer token\"), 3 = sealed envelope (the scale). HMAC-signed (2) needs the exact bytes of the body, which the HTTP In node does not keep: choose the sealed envelope in the webhook box of the scale.\n UPSCALE_TOKENS mode 1: the token(s), comma separated\n UPSCALE_SECRET mode 3: the secret of the webhook box of the scale\n UPSCALE_FOLDER the folder for the JSON lines (created when missing)\n LIMS_URL the REST address of your LIMS (empty: no LIMS call); LIMS_TOKEN its token (Bearer)\n Change the mapping in the node \"map to the LIMS\" for your LIMS.\n3. Deploy. The address: http(s)://:1880/upscale (with httpNodeRoot in settings.js: below it).\n In the app: LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export: this address, security \"sealed envelope\", the same secret. Or Settings -> 🔗 LIMS / ELN FORWARDING: the https address + the token (browsers post only to https; the app also needs CORS: httpNodeCors: {origin: \"https://up-scales.com\", methods: \"GET,POST\"} in settings.js).\n4. The ids of the records and the last n per scale are kept in the flow context: in memory by default - set a file store (contextStorage in settings.js) to keep them over a restart.\n\nFor the hash chain check of the activity log and the LEGAL MODE store, the requests to the scale and the poll: upscale-receiver.py / .php / -node.js next to this file.\n", "x": 420, "y": 40, "wires": [] }, { "id": "f0e1a2b3c4d50003", "type": "http in", "z": "f0e1a2b3c4d50001", "name": "POST /upscale", "url": "/upscale", "method": "post", "upload": false, "swaggerDoc": "", "x": 130, "y": 120, "wires": [ [ "f0e1a2b3c4d50004" ] ] }, { "id": "f0e1a2b3c4d50004", "type": "function", "z": "f0e1a2b3c4d50001", "name": "check (token / sealed)", "func": "// The request of the scale (webhook export) or of the app (LIMS / ELN forwarding): check it.\n// Output 1: a new record -> store it | output 2: the answer at once (refused, or a record that came twice).\n// Settings: the environment variables of this flow tab (double-click the tab -> Environment variables).\nconst MODES = String(env.get('UPSCALE_MODES') || '1,3').split(',').map(Number);\nconst TOKENS = String(env.get('UPSCALE_TOKENS') || '').split(',').map(s => s.trim()).filter(s => s && !s.startsWith('CHANGE-ME'));\nconst SECRET = String(env.get('UPSCALE_SECRET') || '');\nconst body = msg.payload, hdr = msg.req.headers;\nmsg.headers = {'Content-Type': 'application/json'};\nfunction refuse(code, text) {\n node.warn('refused ' + code + ': ' + text);\n msg.statusCode = code;\n msg.payload = JSON.stringify({error: text});\n return [null, msg];\n}\nlet mode = (body && typeof body === 'object' && body.schema === 'upscale.sealed/1') ? 3 : 1;\nif (hdr['x-upscale-signature']) {mode = 2;}\n// (HMAC-signed needs the exact bytes of the body - the HTTP In node keeps only the parsed JSON: use the sealed envelope or a token)\nif (!MODES.includes(mode) || mode === 2) {return refuse(401, 'mode ' + mode + ' not accepted here');}\nlet event = body, device = '', n = 0;\nif (mode === 1) {\n const auth = String(hdr['authorization'] || '');\n const given = auth.startsWith('Bearer ') ? auth.substring(7) : String(hdr['x-api-key'] || (msg.req.query || {}).token || '');\n const ok = TOKENS.some(t => t.length === given.length && crypto.timingSafeEqual(Buffer.from(t), Buffer.from(given)));\n if (!ok) {return refuse(401, 'mode 1: wrong or missing token');}\n} else {\n if (!SECRET || SECRET.startsWith('CHANGE-ME')) {return refuse(503, 'set UPSCALE_SECRET');}\n device = String(body.device || '');\n n = Number(body.n);\n if (!/^[0-9a-fA-F]{12}$/.test(device) || !Number.isInteger(n) || n < 1 || n > 0xFFFFFFFFFFFF) {return refuse(400, 'mode 3: device or n wrong');}\n // AES-256-GCM, key SHA-256(secret), nonce = the Device ID (6 bytes) + n (6 bytes, little endian); ct = cipher text + tag (16)\n const key = crypto.createHash('sha256').update(SECRET, 'utf8').digest();\n const nonce = Buffer.alloc(12);\n Buffer.from(device, 'hex').copy(nonce, 0);\n nonce.writeUIntLE(n, 6, 6);\n try {\n const ct = Buffer.from(String(body.ct || ''), 'base64');\n const d = crypto.createDecipheriv('aes-256-gcm', key, nonce);\n d.setAuthTag(ct.subarray(ct.length - 16));\n event = JSON.parse(Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]).toString('utf8'));\n } catch (e) {\n return refuse(401, 'mode 3: the envelope does not open');\n }\n // n only goes up, per scale (kept in the flow context - a file store keeps it over restarts: contextStorage in settings.js)\n const last = flow.get('upscale_last_n') || {};\n if (n <= (last[device.toLowerCase()] || 0)) {return refuse(409, 'mode 3: n ' + n + ' not higher than ' + last[device.toLowerCase()] + ' (replay)');}\n last[device.toLowerCase()] = n;\n flow.set('upscale_last_n', last);\n}\nif (!event || typeof event !== 'object' || typeof event.id !== 'string' || !event.id || !event.type) {return refuse(400, 'not a record');}\nmsg.upscale = {mode: mode, device: device, n: n, id: event.id};\nmsg.event = event;\n// a record that comes twice (same id, after a lost answer): acknowledged again, not stored again\nconst seen = flow.get('upscale_seen') || [];\nconst before = seen.find(s => s[0] === event.id);\nif (before) {\n msg.ref = before[1];\n return [null, null, msg];\n}\nconst type = String(event.type).toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'other';\nevent._rx = {at: new Date().toISOString(), mode: mode};\nmsg.filename = String(env.get('UPSCALE_FOLDER') || '/data/upscale') + '/' + type + '-' + new Date().toISOString().substring(0, 10) + '.jsonl';\nmsg.payload = JSON.stringify(event);\nreturn [msg, null, null];\n", "outputs": 3, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [ { "var": "crypto", "module": "crypto" } ], "x": 340, "y": 120, "wires": [ [ "f0e1a2b3c4d50005" ], [ "f0e1a2b3c4d5000a" ], [ "f0e1a2b3c4d50008" ] ] }, { "id": "f0e1a2b3c4d50005", "type": "file", "z": "f0e1a2b3c4d50001", "name": "append to -.jsonl", "filename": "filename", "filenameType": "msg", "appendNewline": true, "createDir": true, "overwriteFile": "false", "encoding": "utf8", "x": 590, "y": 100, "wires": [ [ "f0e1a2b3c4d50006" ] ] }, { "id": "f0e1a2b3c4d50006", "type": "function", "z": "f0e1a2b3c4d50001", "name": "map to the LIMS", "func": "// The stored record -> a call of the REST API of your LIMS (output 1), or straight to the answer (output 2: no LIMS set,\n// or a record type that is not for the LIMS). CHANGE THE MAPPING for your LIMS: \"LIMS field\": the value from the record.\nconst LIMS_URL = String(env.get('LIMS_URL') || '');\nconst e = msg.event, d = e.data || {};\nif (!LIMS_URL || ['ping', 'status', 'weight'].includes(e.type)) {return [null, msg];}\nmsg.url = LIMS_URL;\nmsg.method = 'POST';\nmsg.headers = {'Content-Type': 'application/json', 'Accept': 'application/json'};\nif (env.get('LIMS_TOKEN')) {msg.headers['Authorization'] = 'Bearer ' + env.get('LIMS_TOKEN');}\nmsg.payload = {\n sampleId: d.lot ?? null,\n test: d.name ?? d.request ?? e.type,\n result: d.grams ?? null,\n unit: d.unit || 'g',\n operator: d.user || e.user || '',\n measuredAt: d.time || e.sent_at || null,\n instrument: {id: e.device, name: e.scale || ''},\n type: e.type,\n externalId: e.id\n};\nreturn [msg, null];\n", "outputs": 2, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [ { "var": "crypto", "module": "crypto" } ], "x": 820, "y": 100, "wires": [ [ "f0e1a2b3c4d50007" ], [ "f0e1a2b3c4d50008" ] ] }, { "id": "f0e1a2b3c4d50007", "type": "http request", "z": "f0e1a2b3c4d50001", "name": "LIMS REST call", "method": "use", "ret": "obj", "paytoqs": "ignore", "url": "", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 1020, "y": 60, "wires": [ [ "f0e1a2b3c4d5000b" ] ] }, { "id": "f0e1a2b3c4d5000b", "type": "function", "z": "f0e1a2b3c4d50001", "name": "LIMS took it?", "func": "// The answer of the LIMS: 2xx -> its id as the receipt (output 1) | else: not taken (output 2 - the scale sends the record again later)\nif (msg.statusCode >= 200 && msg.statusCode < 300) {\n msg.ref = String((msg.payload && (msg.payload.id || msg.payload.resultId)) || '');\n return [msg, null];\n}\nnode.warn('the LIMS answered ' + msg.statusCode);\nmsg.statusCode = 503;\nmsg.headers = {'Content-Type': 'application/json'};\nmsg.payload = JSON.stringify({error: 'the LIMS did not take it'});\nreturn [null, msg];\n", "outputs": 2, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [ { "var": "crypto", "module": "crypto" } ], "x": 1210, "y": 60, "wires": [ [ "f0e1a2b3c4d50008" ], [ "f0e1a2b3c4d5000a" ] ] }, { "id": "f0e1a2b3c4d50008", "type": "function", "z": "f0e1a2b3c4d50001", "name": "receipt (sealed in mode 3)", "func": "// The receipt for the scale / the app: {\"ack\": \"\", \"ref\": \"\"} - only after the record was stored.\n// Sealed mode: the answer sealed with the nonce (Device ID XOR 0xFF) + n.\nconst u = msg.upscale;\nif (!msg.ref) {msg.ref = crypto.createHash('sha256').update(String(msg.payload)).digest('hex').substring(0, 16);}\n// (remember the id: a record that comes again is acknowledged with the same receipt - the last 2000 ids)\nconst seen = flow.get('upscale_seen') || [];\nif (!seen.find(s => s[0] === u.id)) {seen.push([u.id, msg.ref]); if (seen.length > 2000) {seen.shift();} flow.set('upscale_seen', seen);}\nlet out = JSON.stringify({ack: u.id, ref: String(msg.ref).substring(0, 36)});\nif (u.mode === 3) {\n const key = crypto.createHash('sha256').update(String(env.get('UPSCALE_SECRET')), 'utf8').digest();\n const nonce = Buffer.alloc(12);\n Buffer.from(u.device, 'hex').forEach((b, i) => {nonce[i] = b ^ 0xFF;});\n nonce.writeUIntLE(u.n, 6, 6);\n const c = crypto.createCipheriv('aes-256-gcm', key, nonce);\n const ct = Buffer.concat([c.update(out, 'utf8'), c.final(), c.getAuthTag()]);\n out = JSON.stringify({schema: 'upscale.sealed/1', n: u.n, ct: ct.toString('base64')});\n}\nmsg.statusCode = 200;\nmsg.headers = {'Content-Type': 'application/json'};\nmsg.payload = out;\nreturn msg;\n", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [ { "var": "crypto", "module": "crypto" } ], "x": 1240, "y": 160, "wires": [ [ "f0e1a2b3c4d5000a" ] ] }, { "id": "f0e1a2b3c4d5000a", "type": "http response", "z": "f0e1a2b3c4d50001", "name": "answer", "statusCode": "", "headers": {}, "x": 1450, "y": 200, "wires": [] }, { "id": "f0e1a2b3c4d5000c", "type": "catch", "z": "f0e1a2b3c4d50001", "name": "file or LIMS failed", "scope": [ "f0e1a2b3c4d50005", "f0e1a2b3c4d50007" ], "uncaught": false, "x": 600, "y": 240, "wires": [ [ "f0e1a2b3c4d5000d" ] ] }, { "id": "f0e1a2b3c4d5000d", "type": "function", "z": "f0e1a2b3c4d50001", "name": "no receipt (503)", "func": "// The file or the LIMS call failed: no receipt - the scale / the app sends the record again later.\nnode.warn('not stored: ' + (msg.error && msg.error.message));\nmsg.statusCode = 503;\nmsg.headers = {'Content-Type': 'application/json'};\nmsg.payload = JSON.stringify({error: 'not stored'});\nreturn msg;\n", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [ { "var": "crypto", "module": "crypto" } ], "x": 840, "y": 240, "wires": [ [ "f0e1a2b3c4d5000a" ] ] } ]