You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7 KiB

11 months ago
  1. const crypto = require("crypto");
  2. const fs = require("fs");
  3. const path = require("path");
  4. const keyPath =
  5. process.env.NODE_ENV === "development"
  6. ? path.resolve(__dirname, `../../../server/storage/comkey`)
  7. : path.resolve(
  8. process.env.STORAGE_DIR ??
  9. path.resolve(__dirname, `../../../server/storage`),
  10. `comkey`
  11. );
  12. class CommunicationKey {
  13. #pubKeyName = "ipc-pub.pem";
  14. #storageLoc = keyPath;
  15. constructor() {}
  16. log(text, ...args) {
  17. console.log(`\x1b[36m[CommunicationKeyVerify]\x1b[0m ${text}`, ...args);
  18. }
  19. #readPublicKey() {
  20. return fs.readFileSync(path.resolve(this.#storageLoc, this.#pubKeyName));
  21. }
  22. // Given a signed payload from private key from /app/server/ this signature should
  23. // decode to match the textData provided. This class does verification only in collector.
  24. // Note: The textData is typically the JSON stringified body sent to the document processor API.
  25. verify(signature = "", textData = "") {
  26. try {
  27. let data = textData;
  28. if (typeof textData !== "string") data = JSON.stringify(data);
  29. return crypto.verify(
  30. "RSA-SHA256",
  31. Buffer.from(data),
  32. this.#readPublicKey(),
  33. Buffer.from(signature, "hex")
  34. );
  35. } catch {}
  36. return false;
  37. }
  38. // Use the rolling public-key to decrypt arbitrary data that was encrypted via the private key on the server side CommunicationKey class
  39. // that we know was done with the same key-pair and the given input is in base64 format already.
  40. // Returns plaintext string of the data that was encrypted.
  41. decrypt(base64String = "") {
  42. return crypto
  43. .publicDecrypt(this.#readPublicKey(), Buffer.from(base64String, "base64"))
  44. .toString();
  45. }
  46. }
  47. module.exports = { CommunicationKey };