diff --git a/javascript_backend/.env.example b/javascript_backend/.env.example index c10ed30..5926940 100644 --- a/javascript_backend/.env.example +++ b/javascript_backend/.env.example @@ -5,6 +5,10 @@ PINATA_JWT=your_pinata_jwt_token_here QDRANT_API_KEY=your_qdrant_api_key QDRANT_URL=your_qdrant_url +# Anonymization +# Secret salt for patient pseudonyms (WIDs). Use the same value as python_backend. +# BIOBLOCK_STUDY_SALT=replace-with-a-long-random-secret + # Server Configuration PORT=3001 NODE_ENV=development diff --git a/javascript_backend/tests/anonymize_limits.test.js b/javascript_backend/tests/anonymize_limits.test.js index eb6e669..91302f2 100644 --- a/javascript_backend/tests/anonymize_limits.test.js +++ b/javascript_backend/tests/anonymize_limits.test.js @@ -2,6 +2,8 @@ const request = require("supertest"); const expect = require("chai").expect; const app = require("../server"); +process.env.BIOBLOCK_STUDY_SALT = process.env.BIOBLOCK_STUDY_SALT || "anonymize-test-salt"; + describe("Anonymize Upload Limits", function () { it("accepts a small valid CSV upload", async function () { const smallCsv = Buffer.from("patient_id,name\n1,Alice\n2,Bob\n", "utf8"); diff --git a/javascript_backend/tests/api.test.js b/javascript_backend/tests/api.test.js index 5a7bc1e..5182252 100644 --- a/javascript_backend/tests/api.test.js +++ b/javascript_backend/tests/api.test.js @@ -5,6 +5,8 @@ const path = require("path"); const fs = require("fs"); const app = require("../server"); +process.env.BIOBLOCK_STUDY_SALT = process.env.BIOBLOCK_STUDY_SALT || "anonymize-test-salt"; + const testFilePath = path.join(__dirname, "test.xlsx"); before(function () { diff --git a/javascript_backend/tests/controllers/anonymizeController.test.js b/javascript_backend/tests/controllers/anonymizeController.test.js index bf979fa..8c1947d 100644 --- a/javascript_backend/tests/controllers/anonymizeController.test.js +++ b/javascript_backend/tests/controllers/anonymizeController.test.js @@ -1,8 +1,11 @@ const request = require("supertest"); const { expect } = require("chai"); const XLSX = require("xlsx"); +const crypto = require("crypto"); const app = require("../../server"); +process.env.BIOBLOCK_STUDY_SALT = process.env.BIOBLOCK_STUDY_SALT || "anonymize-test-salt"; + /** * Helper: create an in-memory XLSX buffer from an array-of-arrays. * Optionally accepts a sheet name (defaults to "Sheet1"). @@ -268,6 +271,99 @@ describe("PHI Detection in Anonymization", function () { expect(String(output[2][1])).to.match(WID_PATTERN); expect(output[1][1]).to.not.equal(output[2][1]); }); + + it("should not produce the unsalted SHA-256 of the Patient ID", async function () { + const data = [ + ["Patient ID", "Score"], + ["P0042", 85], + ]; + const buffer = createXlsxBuffer(data); + const output = await anonymizeAndParse(buffer); + + const unsalted = + "WID_" + crypto.createHash("sha256").update("p0042").digest("hex").substring(0, 8); + expect(String(output[1][0])).to.match(WID_PATTERN); + expect(output[1][0]).to.not.equal(unsalted); + }); + + it("should give the same Patient ID different WIDs under different salts", async function () { + const data = [ + ["Patient ID", "Score"], + ["P0042", 85], + ]; + const originalSalt = process.env.BIOBLOCK_STUDY_SALT; + try { + const first = await anonymizeAndParse(createXlsxBuffer(data)); + const again = await anonymizeAndParse(createXlsxBuffer(data)); + process.env.BIOBLOCK_STUDY_SALT = "another-study-salt"; + const otherStudy = await anonymizeAndParse(createXlsxBuffer(data)); + + expect(first[1][0]).to.equal(again[1][0]); + expect(first[1][0]).to.not.equal(otherStudy[1][0]); + } finally { + process.env.BIOBLOCK_STUDY_SALT = originalSalt; + } + }); + + it("should hash the trimmed, lowercased Patient ID like stable_hash in Python", async function () { + const data = [ + ["Patient ID", "Score"], + [" P0042 ", 85], + ]; + const output = await anonymizeAndParse(createXlsxBuffer(data)); + + const salt = process.env.BIOBLOCK_STUDY_SALT; + const expected = + "WID_" + + crypto + .createHash("sha256") + .update(`${salt}:PATIENT_ID:p0042`) + .digest("hex") + .substring(0, 8); + expect(output[1][0]).to.equal(expected); + }); + + it("should give the same wallet the same WID regardless of letter case", async function () { + const data = [ + ["Name", "Score"], + ["John Doe", 85], + ]; + const upload = async (walletAddress) => { + const res = await request(app) + .post("/api/anonymize") + .attach("file", createXlsxBuffer(data), "test.xlsx") + .field("walletAddress", walletAddress) + .field("generatePreview", "true"); + expect(res.status).to.equal(200); + const wb = XLSX.read(Buffer.from(res.body.files.main.data, "base64"), { type: "buffer" }); + return XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], { header: 1 }); + }; + + const checksummed = await upload("0x52908400098527886E0F7030069857D2E4169EE7"); + const lowercase = await upload("0x52908400098527886e0f7030069857d2e4169ee7"); + + expect(String(checksummed[1][0])).to.match(WID_PATTERN); + expect(checksummed[1][0]).to.equal(lowercase[1][0]); + }); + + it("should refuse to anonymize when no salt is configured", async function () { + const data = [ + ["Patient ID", "Name"], + ["P0042", "John Doe"], + ]; + const originalSalt = process.env.BIOBLOCK_STUDY_SALT; + try { + delete process.env.BIOBLOCK_STUDY_SALT; + const res = await request(app) + .post("/api/anonymize") + .attach("file", createXlsxBuffer(data), "test.xlsx"); + + expect(res.status).to.not.equal(200); + expect(res.body.error).to.include("BIOBLOCK_STUDY_SALT"); + } finally { + process.env.BIOBLOCK_STUDY_SALT = originalSalt; + } + }); }); // ------------------------------------------------------------------ diff --git a/javascript_backend/workers/anonymizeWorker.js b/javascript_backend/workers/anonymizeWorker.js index be20017..f30fa6d 100644 --- a/javascript_backend/workers/anonymizeWorker.js +++ b/javascript_backend/workers/anonymizeWorker.js @@ -64,8 +64,14 @@ const sanitizeSheetData = (data) => { return data.map((row) => row.map((cell) => sanitizeCellValue(cell))); }; -const generateAnonymizedId = (input, index) => { - const hash = crypto.createHash("sha256").update(input).digest("hex"); +const STUDY_SALT_ENV_VAR = "BIOBLOCK_STUDY_SALT"; + +// Salted the same way as stable_hash in python_backend/services/text_anonymization.py, +// so a WID can't be reversed by hashing guessed Patient IDs +const generateAnonymizedId = (input, salt) => { + // Normalize like stable_hash in python_backend, so P0042 and p0042 get the same WID + const normalized = String(input).trim().toLowerCase(); + const hash = crypto.createHash("sha256").update(`${salt}:PATIENT_ID:${normalized}`).digest("hex"); return `WID_${hash.substring(0, 8)}`; }; @@ -74,6 +80,11 @@ parentPort.on("message", (workerData) => { const { fileBuffer, walletAddress, generatePreview, originalFileName } = workerData; const isPersonalData = !!walletAddress; + const salt = (process.env[STUDY_SALT_ENV_VAR] || "").trim(); + if (!salt) { + throw new Error(`Anonymization salt is not configured. Set ${STUDY_SALT_ENV_VAR}.`); + } + const workbook = XLSX.read(fileBuffer, { type: "buffer", cellDates: true, @@ -123,7 +134,7 @@ parentPort.on("message", (workerData) => { const sortedIds = Array.from(allIdentifiers).sort(); const idMap = {}; - sortedIds.forEach((id, i) => (idMap[id] = generateAnonymizedId(id, i + 1))); + sortedIds.forEach((id) => (idMap[id] = generateAnonymizedId(id, salt))); const outWb = XLSX.utils.book_new(); @@ -160,8 +171,8 @@ parentPort.on("message", (workerData) => { if (row && row.some((c) => c !== undefined && c !== null && c !== "")) { const id = isPersonalData && walletAddress - ? generateAnonymizedId(walletAddress, 1) - : generateAnonymizedId(uuidv4(), i); + ? generateAnonymizedId(walletAddress, salt) + : generateAnonymizedId(uuidv4(), salt); maskCols.forEach((c) => { if (row[c] !== undefined) row[c] = id; @@ -177,7 +188,7 @@ parentPort.on("message", (workerData) => { } // Rows with no Patient ID still need masking, so give them their own WID if (!id && row && row.some((c) => c !== undefined && c !== null && c !== "")) { - id = generateAnonymizedId(uuidv4(), i); + id = generateAnonymizedId(uuidv4(), salt); } if (id) { maskCols.forEach((c) => {