Insecure Use of setAtributeNS()

Im fixing some security issues that AppScan found on my Angular Application, one of them is the insecure use of “setAttributeNS()” I use this method in my application to inject some namespaces in the correct htmlElemnt

I have reader about the setAttribute() XSS vulnerability and that a workaround for it is directly injecting the code in the attribute name instead of using ‘setAttribute()’, but for setAttributeNS() I haven’t found any workaround to avoid this vulnerability

Example code:

.setAttributeNS("http://www.w3.org/1999/xlink", "href", canvas.toDataURL('image/png')

Any suggestions will be appreciated

I’m having problems playing áudio files in Discord

So, It’s been two long days traying to figure what the reck is going on… I’m creating a Bot to my Discord Channel that plays an audio.mp3 when a command is written, like !laugh then the bot should enter the voice channel and reproduce laugh.mp3. I’ve tried in so manny different ways but the bot keeps entering the channel, the green circle quickly appears but no sound is played…

const { join } = require('path');
const { joinVoiceChannel,  createAudioPlayer,  createAudioResource, getVoiceConnection, entersState, StreamType,  AudioPlayerStatus,  VoiceConnectionStatus, AudioResource } = require("@discordjs/voice");

module.exports = {
   name: 'laugh', 
   aliases: ["l"], 

   run: async(client, message, args) => {

   const player = createAudioPlayer()
   const connection = joinVoiceChannel({
   channelId: message.member.voice.channel.id,
   guildId: message.guild.id,
   adapterCreator: message.guild.voiceAdapterCreator
                     }).subscribe(player)
   let resource = createAudioResource(join('./som/', 'laugh.mp3'));
   player.play(resource)
   player.on(AudioPlayerStatus.AutoPaused, () => {
   player.stop();
         
     });
   }
}

I’ve already tried to caugh error but apparently nothing is wrong, I already have all intents in my index.js.

So, anyone could help me find a solution?

Smooth scroll – additional margin

I am trying to create template for CMS joomla 4, and I am using Template Toaster tool for such purpose. I have some issue with page converted to onepage style of website. I have set anchors for my menu, and when I click to any position of menu, then page is scrooling to my anchor but my floating menu cover some part of my text. I am trying to find how I can add some margin for smooth scrool and when I select any menu postion then when page will be scrolled to menu then text will be not hidden under menu.

Thank you for support

How to remove duplicates from different arrays in one array ReactJS

Here is my array. How can I remove duplicates in this type of structure. When I map over arr I get the values of each arrays nested in each object. And I want to filter the duplicated values. This returns : bye hello hello

[

    {
        arr: ['']
        val: "string"
    }
    {
        arr: ['bye', 'hello']
        val: "string"
    }
    {
        arr: ['hello']
        val: "string"
    }

]
    
    
myArray.map(item => item.arr.map((el, index) =>
    <p key={index}>{el}</p>       
))

Create Javascript localStorage for website background change

Hello and big thanks for a all S.O community

I come today because i try to create local storage with Javascript for my users can change background and page settings on my website and find it back when page reload.
I tried many attempt but i’m so beginner for do make it work

    var m = new s.a.Store({
    modules: {
        programs: p,
        preferences: {
            state: {
                background: "images/backgrounds/background2.jpg",
                preferredColor: "#1e90ff",
                isWiFiConnected: !1
            },
            getters: {
                background: function(t) {
                    return t.background
                },
                preferredColor: function(t) {
                    return t.preferredColor
                },
                isWiFiConnected: function(t) {
                    return t.isWiFiConnected
                }
            },
            actions: {},
            mutations: {
                changePreferredColor: function(t, e) {
                    t.preferredColor = e
                },
                changeBackground: function(t, e) {
                    t.background = e
                },
                toggleWiFiConnection: function(t) {
                    t.isWiFiConnected = !t.isWiFiConnected
                }
            }
        },
        filesystem: d
    },
    strict: !1
});
i.a.prototype.$t = function(t) {
    return t
}, i.a.config.devtools = !0, new i.a({
    el: "#app",
    store: m,
    components: {
        App: a.a
    }
})
},
function(t, e, n) {
    "use strict";
    (function(e, n) {
            var r = Object.freeze({});

            function i(t) {
                return null == t
            }

            function o(t) {
                return null != t
            }

            function a(t) {
                return !0 === t
            }

            function s(t) {
                return "string" == typeof t || "number" == typeof t || "symbol" == typeof t || "boolean" == typeof t
            }

            function u(t) {
                return null !== t && "object" == typeof t
            }

 there is the code i tried to add just before without sucess (blank page) :

        var m = { ...localStorage };
    localStorage.getItem("background");
    localStorage.setItem("background"); 

Thanks for your support

Best regards

Javascript return statement doesn’t stop rest of function from completing

I am using Docuware’s API to staple (merge) documents together. I have written my question as simple as I can so people with no Docuware knowledge should be able to understand.

So in my main function, I call another function and check the return value of the called function. If the value equals zero, it should return null – meaning the rest of the function should not run.

const lastStored = await searchDocument("Invoice", ORDER_NUMBER = '', cookie)
console.log("Full id func: " + id)
console.log("id[0]: " + id[0])

if (lastStored[0] === 0) {
    console.log("id[0]: " + id[0])
    return null;
};

I am getting weird errors with my code, so I have a lot of console.logs. Here are the console.logs when the code successfully works.

 cookie set
 Document is Invoice (Invoice)
 Invoice order #: ORD83001
 Current ID: 52724 Order #: ORD83001
 cookie set
 Document is DELIVERY SLIP (DELIVERY SLIP)
 Invoice order #: ORD83001
 DELIVERY SLIP Doc ID: 52553
 Current ID: 52553 Order #: ORD83001
 Full id func: 52553,ORD83001
 id[0]: 52553
 New Tray Doc ID: 1410
 Document's successfully merged.

Now, with the error, the console.logs are:

 //.....
 Current ID: 0 Order #: ORD83009
 Full id func: 0,ORD83009
 id[0]: 0
 id[0]: 0
 Document's successfully merged.

The thing about this error, is that if id[0] was truly zero, then the document’s wouldn’t be able to be merged. But the documents ARE merged if I look at them. So why is my code returning 0, even INSIDE my if statement, yet continues to run?

Is it some sort of timing issue? Like id[0] === 0 but .00000001 seconds later it gets updated so the return null doesn’t follow through?

Angular Electron not working on first load

I have tried building an Angular application with Electron and I have the following issue: When the app starts, the browser window is empty, nothing in the console. The whole body tag is empty as well. However, after I manually press reload in the Electron browser, it works – everything runs as expected. Any ideas why this might happen?

This is my main.js file:

const {app, BrowserWindow} = require('electron');
const {autoUpdater} = require("electron-updater");
const log = require('electron-log');

const url = require("url");
const path = require("path");
var webpackTargetElectronRenderer = require('webpack-target-electron-renderer');


autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');

let win;

function sendStatusToWindow(text) {
  log.info(text);
  console.log(text);
  mainWindow.console.log(text);
  win.webContents.send('message', text);
}
// function createDefaultWindow() {
//   win = new BrowserWindow();
//   win.webContents.openDevTools();
//   win.on('closed', () => {
//     win = null;
//   });
//   win.loadURL(`file://${__dirname}/version.html#v${app.getVersion()}`);
//   return win;
// }

app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  // On certificate error we disable default behaviour (stop loading the page)
  // and we then say "it is all fine - true" to the callback
  console.log(JSON.stringify(certificate));
  event.preventDefault();
  callback(true);
});

let mainWindow


var options = {
  // webPreferences: {
  //   webSecurity: false
  // },
  node: {
    __dirname: false
  }
}

options.target = webpackTargetElectronRenderer(options)

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      nodeIntegration: true
    }
    // webPreferences: {
      // plugins: true,
      // nodeIntegration: true,
      // webSecurity: false
    // }
  })

  // log.info('Hello, log');
  // log.info(log.transports.console);
  // console.log(log.transports.console);
  // log.warn('Some problem appears');
  // // log.info("Test");
  // console.log = log.info;
  console.log("TEst");
  // log.info(log.transports.file.getFile());
  mainWindow.loadURL(
    url.format({
      pathname: path.join(__dirname, `/dist/index.html`),
      protocol: "file:", 
      slashes: true
    })
  );
  // mainWindow.webContents.devToolsWebContents("Test");
  // var x = path.join(__dirname, `/dist/index.html`);
  // console.log(x);
  // mainWindow.loadURL(`file://${__dirname}/version.html#v${app.getVersion()}`);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
  // console.log("Test");

  mainWindow.on('closed', function () {
    mainWindow = null
  })

  autoUpdater.on('checking-for-update', () => {
    sendStatusToWindow('Checking for update...');
  })
  autoUpdater.on('update-available', (ev, info) => {
    sendStatusToWindow('Update available.');
  })
  autoUpdater.on('update-not-available', (ev, info) => {
    sendStatusToWindow('Update not available.');
  })
  autoUpdater.on('error', (ev, err) => {
    sendStatusToWindow('Error in auto-updater.');
  })
  autoUpdater.on('download-progress', (ev, progressObj) => {
    sendStatusToWindow('Download progress...');
  })
  autoUpdater.on('update-downloaded', (ev, info) => {
    sendStatusToWindow('Update downloaded; will install in 5 seconds');
  });

}

// app.on('ready', createWindow)
app.on('ready', function()  {
  createWindow();
  autoUpdater.checkForUpdatesAndNotify();
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  if (mainWindow === null) createWindow()
})

javascript JSON.stringify converts zodjs boolean to a number (1 or 0)

I am building an app with Typescript/nextjs/reactjs and I am using zodjs schema and types to validate user input in my frontend and backend. One of my problem is that when I JSON.stringify my user input (an object with a zod boolean) to send it to my backend/api, the boolean will be changed in 1 for true and 0 for false. That ends in an validation error in my backend.

The validation error looks like this:

“code”: “invalid_type”,
“expected”: “boolean”,
“received”: “number”,

“message”: “Expected boolean, received number”

My Zodjs Object/Schema and type looks like this:

export const SomeObject = z
  .object({
  ...
  active: z.boolean().default(true),
  ...
 }).strict();
export type SomeObject = z.infer<typeof SomeObject>;

what am I doing wrong?

Are there any libraries to make Chrome work like IE?

I know there used to be libraries to get IE to work like Chrome but I want the opposite. I guess you could say I’m throwing a hail marry trying to find a script that I can just drop in and have this legacy application work. Yes, IE has special permissions on Windows but I’m not worried about that right this second. First thing I want to try is just adding an IEify script.

Have you ever heard of such a thing?

How to display multiple y axis titles on seperate lines and rotated 90 degrees clockwise in chart.js

My goal is to display several y axis titles on separate lines rotated 90 degrees clockwise in chartjs.


The first code snippet illustrates how to display multiple y axis titles on seperate lines and is inspired by: Add multiple lines as Y axis title in chartJs

Relevant section for 1st code snippet of displaying multiple y axis titles on separate lines:

y: {
   stacked: true,
   title: {
      text: ['Project1', 'Number of defects', 'Project2'],
      display: true
   }
}

const labels = ['2021-06-07 00:00:00', '2021-06-08 00:00:00', '2021-06-09 00:00:00'];

const data = {
    labels: labels,
    datasets: [{
        label: 'Fixed defects',
        backgroundColor: 'rgb(0, 255, 0)',
        borderColor: 'rgb(0, 255, 0)',
        data: ['2', '73', '34'],
        barThickness: 5
    }, {
        label: 'Open defects',
        backgroundColor: 'rgb(255, 0, 0)',
        borderColor: 'rgb(255, 0, 0)',
        data: ['0', '5', '2'],
        barThickness: 5

    }]
};

const config = {
    type: 'bar',
    data: data,
    options: {
        scales: {
            x: {
                min: '2021-06-07 00:00:00',
                max: '2021-09-10 00:00:00',
                type: 'time',
                time: {
                    unit: 'week'
                },
                stacked: true,
                title: {
                    text: 'Dates (weeks)',
                    display: true
                }
            },
            y: {
                stacked: true,
                title: {
                    text: ['Project1', 'Number of defects', 'Project2'],
                    display: true
                }
            }
        }
    }
};

const myChart = new Chart(
    document.getElementById('myChart'),
    config
);
<!DOCTYPE html>
<meta charset="utf-8">

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
<link rel="stylesheet" type="text/css" href="../styles.css">

<body>
    
    <div>
        <canvas height="100px" id="myChart"></canvas>
    </div>
</body>

The second snippet shows one solution for rotating the y axis title 90 degrees clockwise inspired by: Ability to rotate y axis title in chart.js

Relevant section for 2nd code snippet of rotating y axis title 90 degrees clockwise:

ctx.fillText(text, 3, (top + bottom) / 2)

and

plugins: {
      customTitle: {
        display: true,
        text: 'Number of defects',
        color: 'blue'
      }
    }

const customTitle = {
    id: 'customTitle',
    beforeLayout: (chart, args, opts) => {
        const {display,font} = opts;
        if (!display) {
            return;
        }
        const {ctx} = chart;
        ctx.font = font || '12px "Helvetica Neue", Helvetica, Arial, sans-serif'
        const {width} = ctx.measureText(opts.text);
        chart.options.layout.padding.left = width * 1.1;
    },
    afterDraw: (chart, args, opts) => {
        const {font,text,color} = opts;
        const {ctx,chartArea: {top,bottom,left,right}} = chart;
        if (opts.display) {
            ctx.fillStyle = color || Chart.defaults.color
            ctx.font = font || '12px "Helvetica Neue", Helvetica, Arial, sans-serif'
            ctx.fillText(text, 3, (top + bottom) / 2)
        }
    }
}

const labels = ['2021-06-07 00:00:00', '2021-06-08 00:00:00', '2021-06-09 00:00:00'];

const data = {
    labels: labels,
    datasets: [{
        label: 'Fixed defects',
        backgroundColor: 'rgb(0, 255, 0)',
        borderColor: 'rgb(0, 255, 0)',
        data: ['2', '73', '34'],
        barThickness: 5
    }, {
        label: 'Open defects',
        backgroundColor: 'rgb(255, 0, 0)',
        borderColor: 'rgb(255, 0, 0)',
        data: ['0', '5', '2'],
        barThickness: 5

    }]
};

const config = {
    type: 'bar',
    data: data,
    options: {
        scales: {
            x: {
                min: '2021-06-07 00:00:00',
                max: '2021-09-10 00:00:00',
                type: 'time',
                time: {
                    unit: 'week'
                },
                stacked: true,
            },
            y: {
                stacked: true,
            }
        },
        plugins: {
            customTitle: {
                display: true,
                text: 'Number of defects',
                color: 'blue'
            }
        }
    },
    plugins: [customTitle]
};

const myChart = new Chart(
    document.getElementById('myChart'),
    config
);
<!DOCTYPE html>
<meta charset="utf-8">

<script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

<body>
  <div>
    <canvas height="100px" id="myChart"></canvas>
  </div>
</body>

However when I try to combine both solutions together I can either get the correct rotated 90 degrees title (but not on seperate lines) or the multiple titles on seperate lines (but not rotated 90 degrees clockwise) as shown in this fiddle: Example fiddle

I also tried adding new lines in the rotated title:

['Project1nNumber of defectsnProject2']

But that didn’t work either.

Any help would be appreciated.

To be clear: I want the title to be on separate lines and rotated 90 degrees clockwise, not the ticks/labels.

Setting a state using spread operator updates the state vs setting the same object not updating the state

I have an initial object called as initUser, it consists of initial fields of the user as follows

const initUser: UserProfile = {
    firstName: '',
    lastName: '',
    phone: '',
    email: '',
    // and so on
};

The object is very big, it has more than 30 fields in it. So while re initialising the state to its initial state, I did this

setUser(initUser);

Which didn’t work.

But when I did this

setUser({...initUser});

It started to work, although the spread operator is very expensive as it makes the copy of the variable, so any idea why passing the variable is not working? Thank you in advance.

PS: The initUser is placed in another file and is imported correctly since its working properly in the spread operator.

Render BitTorrent/Transmission bitfield

I’m trying to render a BitTorrent (transmission) bitfield into a chart like the following:

enter image description here

I’m getting my bitfield from the pieces field of the Transmission RPC API.

My code right now looks like the following:

function renderPieces(pieces: string, pieceCount: number) {
  const w = 100;
  const h = 100;

  const ppp = pieceCount / w; // pieceCount per pixel

  pieces = Buffer.from(pieces, "base64").toString("utf8");

  const cells = [];
  let bitIndex = 0.0;
  let sb, eb, db;
  let b, c;
  let j = 0;
  for (let i = 0, len = pieces.length; i < len; ++i) {
    b = (b << 8) | pieces.charCodeAt(i);
    bitIndex += 8.0;
    sb = Math.round(bitIndex);
    while (bitIndex > ppp) {
      bitIndex -= ppp;
      eb = Math.round(bitIndex);
      db = sb - eb;

      c = b >> eb;
      c <<= 32 - db;
      c = c - ((c >> 1) & 0x55555555);
      c = (c & 0x33333333) + ((c >> 2) & 0x33333333);
      c = (((c + (c >> 4)) & 0x0f0f0f0f) * 0x01010101) >> 24;

      cells.push({
        alpha: c / db,
        moveTo: [j, 0],
        lineTo: [j++, h],
      });

      sb = eb;
    }
  }
  return cells;
}

I’d like to then use the array of { alpha: number, moveTo: [number, number], lineTo: [number, number] } to render an SVG:

const printTorrentDetails = (torrent: Torrent) => {
  return `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
      ${renderPieces(torrent.pieces, torrent.pieceCount)
        .map(
          ({ moveTo, lineTo, alpha }) =>
            `<line x1="${moveTo[0]}" y1="${moveTo[1]}" x2="${lineTo[0]}" y2="${lineTo[1]}" stroke="rgba(0, 0, 0, ${alpha})" />`
        )
        .join("")}
    </svg>`;
}

The problem is that my code is only rendering a list of vertical lines instead of something resembling the image I posted.

This is my base64 encoded bitfield:

Ph/d7r/f/fN///xwVv///v///+/Y7///54QH///ePc///vt///D//3/8fgDvf/////8f3n+CH+f+TI///DwA//9MAGMAfB/P4BYAAcf2AaHjj//+D+eAAf/v/+HiAH4f/x/hAAP//8PEBkAAf8AxEEcAPwCMIEB4j4AFAQAAAQBDgAAAoAAATAAAsAAAAYAAAAAAAAAABAAAAACAAHgAAAAQAABAAJAAAAEAASAAAAACAAAYAAgAAAAAAmAAABAAAAgAAAAAAAAAEAgAAAAIACAAACEEAAAAAEwIAAABAAAAAAAQAAAARADIACAACCAgAgAAAQAAAABAIAACEBAAAAAAAAAAAEAAEAAAAEAgCAAAAAIIAAIAAAIAAAEIAAAAiBAAAAEAAAAAAAAAAAAAAAAAAA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