{ "name": "UP-SCALE records to the LIMS", "nodes": [ { "parameters": { "content": "## UPSCALE N8N WORKFLOW - UP-SCALES.COM RECORDS INTO YOUR LIMS (N8N)\n\nA workflow for n8n: 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, hands each one to the REST API of your LIMS (with a field mapping), and only then answers the receipt {\"ack\",\"ref\"}. A record the LIMS did not take 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\n### What you need\n1. n8n 1.x, self-hosted: start it with NODE_FUNCTION_ALLOW_BUILTIN=crypto (the Code nodes check the seal with the Node.js module crypto).\n2. Workflows -> Import from file -> this file. Node \"check\": MODES, TOKENS (mode 1), SECRET (mode 3), LIMS_URL, LIMS_TOKEN and the mapping; node \"receipt\": the same SECRET. HMAC-signed (mode 2) is not checked here (the Webhook node gives the parsed JSON): choose the sealed envelope in the webhook box of the scale.\n3. Activate the workflow (the ids seen and the last n per scale are kept between runs of the active workflow). The production address: https:///webhook/upscale - into LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export (security \"sealed envelope\", the same secret) or Settings -> 🔗 LIMS / ELN FORWARDING (+ the token; the app posts from https://up-scales.com: allow that origin for the webhook - option \"Allowed Origins (CORS)\" of the Webhook node in newer n8n versions).\n4. Instead of the LIMS: put any node in place of \"LIMS REST call\" (Postgres, MySQL, Google Sheets, Write Files) - keep \"On Error: Continue (using error output)\", so a failed save gets no receipt.\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", "height": 900, "width": 760 }, "id": "a1f0c000-0000-4000-8000-000000000001", "name": "Read me (MIT License)", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ -820, -300 ] }, { "parameters": { "httpMethod": "POST", "path": "upscale", "responseMode": "responseNode", "options": {} }, "id": "a1f0c000-0000-4000-8000-000000000002", "name": "Webhook from the scale / the app", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [ 0, 0 ], "webhookId": "5b0e7f1c-0d1a-4c55-9c4e-2f6b1d8a7e01" }, { "parameters": { "jsCode": "// The request of the scale (webhook export) or of the app (LIMS / ELN forwarding): check it, map it for the LIMS.\n// route: \"lims\" -> the REST call | \"answer\" -> a receipt at once (a record that came twice) | \"refuse\" -> an error answer.\n// Self-hosted n8n: the Code node may load \"crypto\" only with NODE_FUNCTION_ALLOW_BUILTIN=crypto in the environment of n8n.\nconst crypto = require('crypto');\n// ---------- your settings ----------\nconst MODES = [1, 3]; // 1 = token (the app / the scale with \"Bearer token\"), 3 = sealed envelope (the scale)\nconst TOKENS = ['CHANGE-ME-TOKEN']; // mode 1\nconst SECRET = 'CHANGE-ME-SECRET'; // mode 3: the secret of the webhook box of the scale\nconst LIMS_URL = 'https://lims.example.com/api/results';\nconst LIMS_TOKEN = '';\n// -----------------------------------\nconst req = $input.first().json, body = req.body || {}, hdr = req.headers || {};\nconst st = $getWorkflowStaticData('global'); // (kept between runs of the ACTIVE workflow: the last n per scale, the ids seen)\nst.lastN = st.lastN || {};\nst.seen = st.seen || [];\nfunction refuse(code, text) {return [{json: {route: 'refuse', status: code, answer: {error: text}}}];}\nlet mode = (body.schema === 'upscale.sealed/1') ? 3 : 1;\n// (HMAC-signed needs the exact bytes of the body: choose the sealed envelope in the webhook box of the scale)\nif (hdr['x-upscale-signature']) {mode = 2;}\nif (!MODES.includes(mode) || mode === 2) {return refuse(401, 'mode ' + mode + ' not accepted here');}\nif (!LIMS_URL || LIMS_URL.includes('example.com')) {return refuse(503, 'set LIMS_URL in the node \"check\"');}\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'] || (req.query || {}).token || '');\n const ok = TOKENS.some(t => !t.startsWith('CHANGE-ME') && 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.startsWith('CHANGE-ME')) {return refuse(503, 'set SECRET in the node \"check\"');}\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 const dev = device.toLowerCase();\n if (n <= (st.lastN[dev] || 0)) {return refuse(409, 'mode 3: n ' + n + ' not higher than ' + st.lastN[dev] + ' (replay)');}\n st.lastN[dev] = n;\n}\nif (!event || typeof event !== 'object' || typeof event.id !== 'string' || !event.id || !event.type) {return refuse(400, 'not a record');}\nconst ctx = {mode: mode, device: device, n: n, id: event.id, type: event.type};\n// a record that came twice (same id, after a lost answer): the same receipt again, no second LIMS entry\nconst before = st.seen.find(s => s[0] === event.id);\nif (before) {return [{json: Object.assign(ctx, {route: 'answer', ref: before[1]})}];}\n// tests, health and the live weight: acknowledged, not for the LIMS\nif (['ping', 'status', 'weight'].includes(event.type)) {return [{json: Object.assign(ctx, {route: 'answer', ref: 'not-for-the-lims'})}];}\n// ---------- the mapping (CHANGE IT for your LIMS): \"LIMS field\": the value from the record ----------\nconst d = event.data || {};\nconst lims = {\n sampleId: d.lot ?? null,\n test: d.name ?? d.request ?? event.type,\n result: d.grams ?? null,\n unit: d.unit || 'g',\n operator: d.user || event.user || '',\n measuredAt: d.time || event.sent_at || null,\n instrument: {id: event.device, name: event.scale || ''},\n type: event.type,\n externalId: event.id\n};\nreturn [{json: Object.assign(ctx, {route: 'lims', limsUrl: LIMS_URL, limsAuth: LIMS_TOKEN ? 'Bearer ' + LIMS_TOKEN : '', lims: lims})}];\n" }, "id": "a1f0c000-0000-4000-8000-000000000003", "name": "check", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 220, 0 ] }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict" }, "conditions": [ { "id": "c7a6f1d2-0001-4000-8000-000000000001", "leftValue": "={{ $json.route }}", "rightValue": "lims", "operator": { "type": "string", "operation": "equals" } } ], "combinator": "and" }, "options": {} }, "id": "a1f0c000-0000-4000-8000-000000000004", "name": "for the LIMS?", "type": "n8n-nodes-base.if", "typeVersion": 2, "position": [ 440, 0 ] }, { "parameters": { "method": "POST", "url": "={{ $json.limsUrl }}", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Authorization", "value": "={{ $json.limsAuth }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ JSON.stringify($json.lims) }}", "options": {} }, "id": "a1f0c000-0000-4000-8000-000000000005", "name": "LIMS REST call", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 660, -100 ], "onError": "continueErrorOutput" }, { "parameters": { "jsCode": "// The answer for the scale / the app: the receipt {\"ack\",\"ref\"} only when the LIMS took the record (sealed in mode 3).\nconst crypto = require('crypto');\nconst SECRET = 'CHANGE-ME-SECRET'; // the same as in the node \"check\"\nconst ctx = $('check').first().json, got = $input.first().json;\nconst st = $getWorkflowStaticData('global');\nst.seen = st.seen || [];\nif (ctx.route === 'refuse') {return [{json: {status: ctx.status, text: JSON.stringify(ctx.answer)}}];}\nif (got.error) {\n // (the LIMS did not answer, or answered an error: no receipt - the scale / the app sends the record again later)\n return [{json: {status: 503, text: JSON.stringify({error: 'the LIMS did not take it'})}}];\n}\nlet ref = ctx.ref;\nif (ctx.route === 'lims') {\n // your LIMS's id of the new entry as the receipt (change the key: \"id\", \"resultId\", ...)\n ref = String(got.id || got.resultId || crypto.createHash('sha256').update(ctx.id).digest('hex').substring(0, 16));\n st.seen.push([ctx.id, ref]);\n if (st.seen.length > 2000) {st.seen.shift();}\n}\nlet text = JSON.stringify({ack: ctx.id, ref: String(ref).substring(0, 36)});\nif (ctx.mode === 3) {\n const key = crypto.createHash('sha256').update(SECRET, 'utf8').digest();\n const nonce = Buffer.alloc(12);\n Buffer.from(ctx.device, 'hex').forEach((b, i) => {nonce[i] = b ^ 0xFF;});\n nonce.writeUIntLE(ctx.n, 6, 6);\n const c = crypto.createCipheriv('aes-256-gcm', key, nonce);\n const ct = Buffer.concat([c.update(text, 'utf8'), c.final(), c.getAuthTag()]);\n text = JSON.stringify({schema: 'upscale.sealed/1', n: ctx.n, ct: ct.toString('base64')});\n}\nreturn [{json: {status: 200, text: text}}];\n" }, "id": "a1f0c000-0000-4000-8000-000000000006", "name": "receipt", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 900, 0 ] }, { "parameters": { "respondWith": "text", "responseBody": "={{ $json.text }}", "options": { "responseCode": "={{ $json.status }}", "responseHeaders": { "entries": [ { "name": "Content-Type", "value": "application/json" } ] } } }, "id": "a1f0c000-0000-4000-8000-000000000007", "name": "answer", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [ 1120, 0 ] } ], "connections": { "Webhook from the scale / the app": { "main": [ [ { "node": "check", "type": "main", "index": 0 } ] ] }, "check": { "main": [ [ { "node": "for the LIMS?", "type": "main", "index": 0 } ] ] }, "for the LIMS?": { "main": [ [ { "node": "LIMS REST call", "type": "main", "index": 0 } ], [ { "node": "receipt", "type": "main", "index": 0 } ] ] }, "LIMS REST call": { "main": [ [ { "node": "receipt", "type": "main", "index": 0 } ], [ { "node": "receipt", "type": "main", "index": 0 } ] ] }, "receipt": { "main": [ [ { "node": "answer", "type": "main", "index": 0 } ] ] } }, "settings": { "executionOrder": "v1" }, "pinData": {} }