I am trying to sanitize object but still getting error snyk.io in | NODE.js

I have 2 types of error in snyk report https://snyk.io/ I don’t know if it can be solved with Deepcode AI as well but appreciate the answers.

  1. SQL injection: unsanitize input from an HTTP parameter flow into query.
  2. PATH traversal: unsanitize input from the http request body flow into rimraf, where it is used as a path, this may result in traversal
    vulnerability and allow attacker to delete arbitrary files.

What I have tried but not worked to get rid of Snyk error.

const validator = require('validator');

function sanitizeValue(value) {
  if (typeof value === 'string') {
    return validator.escape(value);
  } else if (Array.isArray(value)) {
    return value.map(item => sanitizeValue(item)); // Sanitize each item in the array
  } else if (typeof value === 'object' && value !== null) {
    return sanitizeObject(value); // Recursively sanitize nested objects
  } else {
    return value; // Return values that are neither strings, arrays, nor objects
  }
}

function sanitizeObject(obj) {
  const sanitizedObject = {};

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      sanitizedObject[key] = sanitizeValue(obj[key]);
    }
  }

  return sanitizedObject;
}

// Sample user input with nested objects and arrays
const userInput = {
  username: 'John <script>alert("XSS")</script> Doe',
  comments: [
    'This is a <b>bold</b> statement!',
    'Another <i>italic</i> comment',
  ],
  profile: {
    bio: 'This is a <b>bold</b> statement!',
    website: 'http://example.com/?search=<script>alert("XSS")</script>',
    social: [
      { platform: 'Twitter', handle: '<b>@john_doe</b>' },
      { platform: 'Facebook', handle: '<script>alert("XSS")</script>' },
    ],
  },
};

const sanitizedUserInput = sanitizeObject(userInput);

console.log('Sanitized Nested Object with Arrays:', sanitizedUserInput);

I want to ask about echart’s magic type. Isn’t there a way to change the chart other than magic type?

I’m making it using echart and next+ ts
I checked that the magic type of E-chart is only line, bar, and stack. Can’t you do something like a bar chart in a pie chart? Do I need to create a separate logic to make it like that?
The code is an e-chart dos example.

`const option = {
  title: {
    text: 'Temperature Change in the Coming Week'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {},
  toolbox: {
    show: true,
    feature: {
      dataZoom: {
        yAxisIndex: 'none'
      },
      dataView: { readOnly: false },
      magicType: { type: ['line', 'bar'] },
      restore: {},
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value} °C'
    }
  },
  series: [
    {
      name: 'Highest',
      type: 'line',
      data: [10, 11, 13, 11, 12, 12, 9],
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    },
    {
      name: 'Lowest',
      type: 'line',
      data: [1, -2, 2, 5, 3, 2, 0],
      markPoint: {
        data: [{ name: '周最低', value: -2, xAxis: 1, yAxis: -1.5 }]
      },
      markLine: {
        data: [
          { type: 'average', name: 'Avg' },
          [
            {
              symbol: 'none',
              x: '90%',
              yAxis: 'max'
            },
            {
              symbol: 'circle',
              label: {
                position: 'start',
                formatter: 'Max'
              },
              type: 'max',
              name: '最高点'
            }
          ]
        ]
      }
    }
  ]
};

`

help !
I’ll wait for an answer from someone who has tried chart change other than magic type.
Have a nice day everyone.

Type error in TypeScript 5.6: Type ‘() => Generator’ is not assignable to type ‘() => BuiltinIterator’

For my unit tests I create a fake window.location object. Here’s the slightly simplified code:

function getFakeLocation(getCurrentUrl: () => URL): Location {
  return {
    get ancestorOrigins(): DOMStringList {
      return {
        length: 1,
        contains: (origin: string) => origin === getCurrentUrl().origin,
        item(index: number) {
          if (index === 0) {
            return getCurrentUrl().origin;
          } else {
            return null;
          }
        },
        *[Symbol.iterator]() {
          yield getCurrentUrl().origin;
        },
      };
    },
    assign: vi.fn((url: string) => {
      pushState({}, new URL(url, getCurrentUrl()));
    }),
    get href() {
      return getCurrentUrl().href;
    },
    set href(url: string) {
      pushState({}, new URL(url, getCurrentUrl()));
    },
    // …
  };
}

This worked fine until I upgraded from TypeScript 5.4.2 to 5.6.0-beta. Now, tsc complains about the ancestorOrigins definition above:

Type '() => Generator<string, void, any>' is not assignable to type '() => BuiltinIterator<string, undefined, any>'.
  Call signature return types 'Generator<string, void, any>' and 'BuiltinIterator<string, undefined, any>' are incompatible.
    The types returned by 'next(...)' are incompatible between these types.
      Type 'IteratorResult<string, void>' is not assignable to type 'IteratorResult<string, undefined>'.
        Type 'IteratorReturnResult<void>' is not assignable to type 'IteratorResult<string, undefined>'.
          Type 'IteratorReturnResult<void>' is not assignable to type 'IteratorReturnResult<undefined>'.
            Type 'void' is not assignable to type 'undefined'.

            *[Symbol.iterator]() {
             ~~~~~~~~~~~~~~~~~

I already updated @types/node to version 20.16.1 as per this question which solved another type error but the above error still remains. However, to me the latter sounds very similar to what Daniel Rosenwasser wrote in his answer in that thread.

Pattern attribute value is not a valid regular expression with email pattern [duplicate]

I have a pattern like this. But when I enter the email input. It shows up an error

pattern : "^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"

I don’t know why it’s show this error. Can you guys explain me this and how to solved it?

^[a-zA-Z0-9.!#$%&’+/=?^_{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^[a-zA-Z0-9.!#$%&'*+/=?^_{|}~-]+@a-zA-Z0-9?(?:.a-zA-Z0-9?)$/v: Invalid character in character class

Hiding a class name an element has [closed]

I want to hide from the user that an element has a certain class.
Essentially just that it just won’t show up in the page’s elements.

Is it possible to do with pure js or jQuery?

I only found answers to hide the element itself and not the class name

For drag and drop file in react js

How to use hooks to drag and drop file upload in React while providing a preview of the uploaded image?

I use the package of react name “DropZone” for making drag and drop file component but want to make this with hooks.

How to get video tag source file from input in HTML

I have a HLS encrypted video consisting of a playlist file (namely stream.m3u8) and a key file (namely stream.m3u8.key) and some stream.ts files. I use code below (https://hlsbook.net/playing-hls-video-in-the-browser-part-2/) to play it in a web player and it works fine

<head>
    <link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
    <script src="https://vjs.zencdn.net/7.4.1/video.min.js"></script>
</head>
<body>
    <video id="example-video" class="video-js vjs-default-skin" controls="controls" width="640" height="360">
       <source src="./stream.m3u8" type="application/x-mpegURL" />
    </video>
    <script>
        var player = videojs('example-video');
    </script>
</body>

Now I want to get source file (./stream.m3u8) from an input tag in HTML (instead of the path defined inside code). What I tried is below but it does not work.

<html>
    
    <head>
        <link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
        <script src="https://vjs.zencdn.net/7.4.1/video.min.js"></script>
    </head>
    
    <body>
        <label for="input">Choose a video file to process:</label>
        <input type="file" id="input" name="input_video">
        <video id="video" class="video-js vjs-default-skin" width="320" height="240" controls style="display: none;"></video>
    </body>
    
    <script>
        document.getElementById("input").addEventListener("change", function() {
          var media = URL.createObjectURL(this.files[0]);
          var video = document.getElementById("video");
          video.src = media;
          video.style.display = "block";
          video.play();
        });

        var player = videojs('video');
    </script>

</html>

What is the wrong?

Image after upload does not exist without restart

I save my image with writeFile but i can’t load it in my browser.
Except if i restart (npm run dev || node build/index)

await writeFile("static/img/tmp/"+now+".jpg", contentReplace, 'base64');

I use SvelteKit with node-adapter, i don’t want to use s3 or anything else because is only for uploading one file the be deleted after an other operation.

I’ve tried to save my image in many different folders:

  • build/client/img/tmp
  • src/lib/images/tmp
  • static/img/tmp

Any way to run obsolete HTML, CSS and mostly JavaScript code? [closed]

My question may sound weird, but I’ve been working on this personal (not commercial) project for years and I suddenly find myself in a position where almost nothing works. I haven’t made any changes to the code for a long time, but now it comes up with “undefined function” or “undefined variable” and lots of weird things in the console. Took me years to build this science/mathematical “app”. It is made to run locally, not for the web.

I’m using a Windows 10 computer for development and an Android 11 or 13 for comfort. I did made like 100 searches, but to no avail.

Any help would be greatly appreciated.

Thanks in advance.

Ajax send response successfully but PHP dont receive data

I have a shopping cart page and button like

`<button class="purchase-button" data-courses-id="<?php echo $coursesID; ?>" onclick="Payment()">
</button>`

so when user click on it, the payment form will show and I want to get the ID of the product to display.
This is the js file:

`
function Payment() {
  document.querySelector(".body-payment").style.display = "flex";
  document.body.style.overflow = "hidden";

  document.querySelectorAll(".purchase-button").forEach((button) => {
    button.addEventListener("click", (event) => {
      const courseID = button.getAttribute("data-courses-id");
      const data = { courseID: courseID };
      $.post("payment.php", data)
        .done(function (response) {
          console.log("Payment data sent successfully:", data);
        })
        .fail(function (error) {
          console.error("Error sending payment data:", error);
        });
    });
  });
}

`

The ajax work fine, it send data, but PHP dont:

`
if (isset($_POST['courseID'])) {}
else echo "Error";
`

I try print the SERVER and POST like:

`
print_r($POST);
`

and the output I got is array empty.

I guess that I dont have a form tag, and maybe the button is clicked twice. Please help me!

How to extend eslint config when using yarn workspaces

I have yarn workspaces in my repository in packages directory with 3 packages: shared and app-1, app-2.
In shared package i have .eslintrc.js config file with following rules:

module.exports = {
    root: true,
    env: {
        node: true,
        browser: true,
        es6: true,
    },
    // other rules
}

and in app-1 & app-2 i have .eslintrc.js which extends the config above like so:

module.exports = {
    extends: ["@superapp/shared/.eslintrc.js"],
};

and this does not work. And this does not work either

module.exports = {
    extends: ["@superapp/shared"],
};

I m starting to assume that it is not even possible to extend eslint config unless config is published to npm.

How to Enable a Button Based on Browser-Autofilled (Not Autocompleted) Credentials?

I realize this question might seem like a duplicate, but I have read all relevant answers and haven’t found a solution that works for my specific case.

My scenario is similar to the one described in this question, with some differences. The issue only occurs on the remote server, which makes testing doubly difficult. The code works fine except when the browser auto-fills the credentials without any user intervention. On page load, the login button is greyed out, even though the credentials are prefilled. A simple click anywhere enables the button, but that shouldn’t be necessary. I’ve tried the solutions from the original question and its comments, but none worked. I also found an answer to this question, but it isn’t suitable since it prevents the browser from binding the saved credentials altogether.

What I can do:

  1. Programmatically prevent the browser from autofilling fields when the page first loads (Autofilling occurs without user interaction, while autocompletion happens after the user starts typing/clicks inside the field).
  2. Run validation immediately after the browser autofills credentials, so the button is enabled.

What I cannot do:

  1. Prevent autocompletion or the browser from saving credentials altogether (users should still be able to click inside a field and select from saved credentials in the dropdown).
  2. Skip validation on the first load, as this would leave the button active if the browser doesn’t autofill.

My code:

function validateForm() {
    var username = document.getElementById('Username').value;
    var password = document.getElementById('Password').value;
    var submitButton = document.getElementById('ActionSubmit');

    if (username && password) {
        submitButton.disabled = false;
        submitButton.style.backgroundColor = '#34495e';
        submitButton.style.color = '#ffffff';
        submitButton.style.cursor = 'pointer';
    }
    else {
        submitButton.disabled = true;
        submitButton.style.backgroundColor = '#ccc';
        submitButton.style.color = '#ffffff';
        submitButton.style.cursor = 'not-allowed';
    }
}

document.getElementById('Username').addEventListener('input', validateForm);
document.getElementById('Password').addEventListener('input', validateForm);

window.addEventListener('load', function () {
    validateForm();
});

Any help would be greatly appreciated!

How to upload a photo to the server in SunEditor using onImageUploadBefore?

I need to upload a photo to the server so that the image with the path is displayed in the editor. I wrote the function, everything works, the photo is uploaded to the server and displayed in the editor. But the editor displays two photos, one with the path from the server, the second in base64 format, how can I make sure that photos in base64 format are not displayed.

const TextSunEditor = ({
    onChange,
    value
}) => {

    async function handleImageUploadBefore(files, info, uploadHandler){
        console.log(files, info)

        const currentFile = files[0];

        const res = await FileUpload.upload(currentFile);

        if (res.statusCode === 200) {
            const { url } = res.content;
            uploadHandler({
                result: [{ url }],
            });
            toast.success(res.message)
        } else {
            toast.error(res.message)
        }
    }

  return (
    <SunEditor 
        setOptions={{
          height: 400,
          buttonList: [
            ['undo', 'redo'],
            ['bold', 'italic', 'underline', 'strike'],
            ['font', 'fontSize', 'formatBlock'],
            ['paragraphStyle', 'blockquote'],
            ['fontColor', 'hiliteColor', 'textStyle'],
            ['removeFormat'],
            '/',
            ['outdent', 'indent'],
            ['align', 'horizontalRule', 'list', 'lineHeight'],
            ['link', 'image', 'video'],
            ['fullScreen', 'showBlocks', 'codeView'],
            ['preview', 'print']
          ],
        }}
        onImageUploadBefore={handleImageUploadBefore}
        onChange={onChange}
        setContents={value}
      />
  )
}