From dc6d50c202f21e692308bb3b2302152a41a282f3 Mon Sep 17 00:00:00 2001 From: homura Date: Sun, 11 Aug 2024 21:55:10 +0900 Subject: [PATCH] chore: make run.ts independent from neuron (#3231) --- scripts/admin/decrypt-log/run.ts | 62 +++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/scripts/admin/decrypt-log/run.ts b/scripts/admin/decrypt-log/run.ts index 632420929..ccf266bcc 100644 --- a/scripts/admin/decrypt-log/run.ts +++ b/scripts/admin/decrypt-log/run.ts @@ -1,4 +1,64 @@ -import { LogDecryption } from "../../../packages/neuron-wallet/src/services/log-encryption"; +import { createDecipheriv, privateDecrypt } from "node:crypto"; + +export const DEFAULT_ALGORITHM = "aes-256-cbc"; + +export class LogDecryption { + private readonly adminPrivateKey: string; + + constructor(adminPrivateKey: string) { + this.adminPrivateKey = adminPrivateKey; + } + + decrypt(encryptedMessage: string): string { + const { iv, key, content } = parseMessage(encryptedMessage); + + const decipher = createDecipheriv( + DEFAULT_ALGORITHM, + privateDecrypt(this.adminPrivateKey, Buffer.from(key, "base64")), + Buffer.from(iv, "base64") + ); + + return Buffer.concat([decipher.update(content, "base64"), decipher.final()]).toString("utf-8"); + } +} + +/** + * Parse a message into a JSON + * + * Input: + * ``` + * [key1:value2] [key2:value2] remain content + * ``` + * Output: + * ```json + * { + * "key1": "value1", + * "key2": "value2", + * "content": "remain content" + * } + * ``` + * @param message + */ +function parseMessage(message: string) { + const result: Record = {}; + const regex = /\[([^\]:]+):([^\]]+)]/g; + let match; + let lastIndex = 0; + + while ((match = regex.exec(message)) !== null) { + const [, key, value] = match; + result[key.trim()] = value.trim(); + lastIndex = regex.lastIndex; + } + + // Extract remaining content after the last bracket + const remainingContent = message.slice(lastIndex).trim(); + if (remainingContent) { + result.content = remainingContent; + } + + return result; +} const ADMIN_PRIVATE_KEY = process.env .ADMIN_PRIVATE_KEY!.split(/\r?\n/)