Winston: Encrypting sensitive information
Asked Answered
P

1

7

I started using winston, express-winston and winston-mongodb to log both request and responses and add them to the mongodb. After a while I was able to generate the logs while also hiding information in body while needed with the usage of black/whitelists but, what I actually need, is to encrypt all the sensitive data such as passwords before saving them to the database. How can I possibly customize the data before it is saved?

Example:

Before

{
    "_id" : ObjectId("5bbf30b37ca8b70015b8efc6"),
    "timestamp" : ISODate("2018-10-11T11:14:59.084Z"),
    "level" : "info",
    "message" : "HTTP POST /auth - 200 - 147ms",
    "meta" : {
        "res" : {
            "statusCode" : 200
        },
        "req" : {
            "url" : "/auth",
            "headers" : {
                "host" : "???.herokuapp.com",
                "connection" : "close",
                "content-type" : "application/json; charset=UTF-8",
                "accept-encoding" : "gzip",
                "user-agent" : "okhttp/3.10.0",
                "x-request-id" : "3b42aa9c-6ead-44cd-939f-cc09bb5318c3",
                "x-forwarded-for" : "0.0.0.0",
                "x-forwarded-proto" : "https",
                "x-forwarded-port" : "443",
                "via" : "1.1 vegur",
                "connect-time" : "0",
                "x-request-start" : "1539256498932",
                "total-route-time" : "0",
                "content-length" : "54"
            },
            "method" : "POST",
            "httpVersion" : "1.1",
            "originalUrl" : "/auth",
            "query" : {},
            "body" : {
                "email" : "[email protected]",
                "password": "123abc"
            }
        },
        "responseTime" : 147
    }
}

After

"body" : {
    "email" : "[email protected]",
    "password": "ENCRYPTEDPASSWORD"
}
Pyro answered 11/10, 2018 at 14:26 Comment(0)
S
0

i am using nestjs but you can convert the logic to nodejs as well, there might be better solutions but i made a function that calls the logger and i encrypt before sending to it, hope it helps,
example :

log(message: string) {
    // Encrypt the log message here
    const encryptedMessage = this.encryptMessage(message);
    this.watson.log(encryptedMessage);
  }

  private encryptMessage(message: string): string {
    // Implement your encryption logic here
    // Example: Replace each character with the next one in ASCII
    const encrypted = message
      .split('')
      .map(char => String.fromCharCode(char.charCodeAt(0) + 1))
      .join('');
    return encrypted;
  }
Schedule answered 23/7, 2024 at 9:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.