Webpack target: ‘electron-renderer’ option breaks my JWE encryption logic in ElectronJS

I need to use a specific encryption logic in my ElectronJS app. To achieve this, I have forked node-jose repo and implemented the curve I need: ECDH BP256 (brainpoolP256r1).

This works smoothly if I do not change the target option of webpack config. But to use all the features I require in ElectronJS, I have to use target: 'electron-renderer' in the webpack.config.js.

And after I set the right target, my encryption logic does not work anymore. I think webpack replaces some of the crypto features I need to create that JWE.

This is the error I receive:

node:internal/crypto/diffiehellman:252 Uncaught (in promise) Error: Failed to create key using named curve

My code works fine in the Node.js environment. That’s why I tried to use IPC bridge to run the code in the main.ts, but that also does not help.

Here is my configuration:

webpack.config.js:

const path = require("path");
const { resolve } = require("path");

module.exports = {
  mode: "development",
  target: 'electron-renderer',
  entry: {
    renderer: path.resolve(__dirname, "src/renderer.js"),
  },
  output: {
    path: path.resolve(__dirname, "dist_electron"),
    filename: "[name][contenthash].js",
    clean: true,
    assetModuleFilename: "[name][ext]",
  },
  devtool: "source-map",
  devServer: {
    static: {
      directory: path.resolve(__dirname, "dist_electron"),
    },
    port: 3000,
    open: false,
    hot: true,
    compress: true,
    historyApiFallback: true,
  },
  resolve: {
    modules: [resolve(process.cwd(), "src"), "node_modules"],
    extensions: [".js"],
    symlinks: false,
    cacheWithContext: false,
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
  module: {
    rules: [
      {
        test: /.js$/,
        /**
         * here we whitelist the vue components in the node_modules
         */
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
};

main.js (electron’s main file):

const { app, BrowserWindow } = require("electron");

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  if (process.env.NODE_ENV === "development") {
    // Load the url of the dev server if in development mode
    win.loadURL("http://localhost:3000/");
  } else {
    // Load the index.html when not in development
    win.loadFile(process.cwd() + "/dist_electron/index.html");
  }
}

app.whenReady().then(() => {
  createWindow();

  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});
const JWK = require('node-jose/lib/jwk');
const JWE = require('node-jose/lib/jwe');


const encryptJwe = (data) => {

  const { idpEncJwk, signature } = data;
  JWK.asKey(idpEncJwk).then((asKey) => {
    const opts = {
      fields: {
        exp: Date.now(),
        epk: {
          kty: idpEncJwk.kty,
          x: idpEncJwk.x,
          y: idpEncJwk.y,
          crv: idpEncJwk.crv,
        },
        cty: 'NJWT',
      },
    };

    const jwe = JWE.createEncrypt(opts, asKey);
    jwe.update(Buffer.from(signature));
    jwe.final().then((res) => {
      console.log(res );
    });

  });


};

encryptJwe({
  idpEncJwk: {
    use: 'enc',
    kid: 'puk_idp_enc',
    kty: 'EC',
    crv: 'BP-256',
    x: 'QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w',
    y: 'mHuknfNkoMmSbytt4br0YGihOixcmBKy80UfSLdXGe4',
  },
  signature:
    'eyJhbG.......',
})

The error I get
The error I get

And this is the exact place the error occurs:
Intern node module where error occurs

I would love to hear any kind of tip if you have something in your mind. Thank you.

How to add a reveal animation on scroll with the element (not the whole page)

My website example: My website example

Hello, I’m trying to figure out how to add a reveal animation on scroll with the element (not the whole page). Because I set the root background image to 100vh and only use an element (overflow) to scroll it vertically so that I’m not scrolling a whole page, just the one-page component. For example, this is my App.js example code:

import React from 'react'
import {Header, Page, Footer} from "./Hooks"
import './style.css'
function App(){
  return (
    <div className="App">
      <Header/>     -> this one is a fixed component.
      <Page/>       -> this one can scroll vertically.
      <Footer/>     -> this one is a fixed component.
    </div>
 );
};

And this is the style.css code:

.App{
   background-image: './macos';
   height: 100vh;
   width: 100%;
   overflowY: auto;
}

Because of this setup, I cannot use window.scrollTo(0,0) function for scrolling to the top. And I’m going to create the reveal animation but don’t know how to make it work. I watched a video about an onScroll event but it can’t work on my website because of the Page component, because the website isn’t scrolled, only the main page component, so window.ScrollY or window.ScrollX is always set to zero (0,0) (checked by console.log()).

I don’t know how to fix this or use any kind of method. It’s hard to re-create the root page UI so I don’t want to have a mess with it. Thank you for all of your contributions. Anyone answers will all receive my upvote.

Jest: test components with ESM dependencies

I have the following component:

App.js

import React from "react";
import { Slider } from "./Slider";

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Slider />
      </header>
    </div>
  );
}

export { App };

Slider.jsx

import {Virtual, Navigation} from 'swiper';
import {Swiper, SwiperSlide} from 'swiper/react';


export const Slider = ({meetings = []}) => {
  const rerenderSwiperKey = useMemo(() => Date.now(), [meetings.length]);
  const lessThanThree = meetings.length < 3;
  const lessThanTwo = meetings.length < 2;
  return (
    <Swiper
      key={rerenderSwiperKey}
      navigation={{
        nextEl: '.swiper-button.next',
        prevEl: '.swiper-button.prev',
      }}
      spaceBetween={24}
      slidesPerView={3}
      simulateTouch={false}
      breakpoints={{
        0: {
          slidesPerView: 1,
        },
        900: {
          slidesPerView: lessThanTwo ? 1 : 2,
        },
        1200: {
          slidesPerView: lessThanThree ? (lessThanTwo ? 1 : 2) : 3,
        },
      }}
      modules={[Virtual, Navigation]}
      virtual>
      {meetings.map((meeting, index) => (
        <SwiperSlide key={meeting.id} virtualIndex={index}>
          <Slide>{meeting}</Slide>
        </SwiperSlide>
      ))}
    </Swiper>
  );
}

Then I have the following test file:

App.test.js

import React from "react";
import { shallow } from "enzyme";
import { App } from "../../App";
import { Slider } from "../../Slider";

describe("App page", () => {
  it("render: learn react link", () => {
    const component = shallow(<App />);
    const buttons = component.find(Slider);

    expect(buttons.length).toBe(1);
  });
});

and the following configuration jest.config.js:

const { defaults } = require("jest-config");

module.exports = {
  moduleFileExtensions: [...defaults.moduleFileExtensions, "js"],
  setupFiles: ["<rootDir>/src/__test__/setupTests.js"],
  setupFilesAfterEnv: ["<rootDir>/src/__test__/setupTestsAfterEnv.js"],
  testPathIgnorePatterns: ["<rootDir>/node_modules/"],
  moduleNameMapper: {
    "\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "./__mocks__/fileMock.js",
  },
};

The issue is that: when I run yarn test – it produces the following error:

~/Downloads/jest-esm-issue/node_modules/swiper/swiper.esm.js:13
    export { default as Swiper, default } from './core/core.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

    > 1 | import {Virtual, Navigation} from 'swiper';
        | ^

Could somebody help me understand how to fix it?
Here is a demo example project https://github.com/DaveLomber/jest-esm-issue

`currentAuthenticatedUser` returns `User is not authenticated` After Sign In + React + AWS Amplify Sign In

I’m trying to get the authenticated user details using the AWS Amplify API currentAuthenticatedUser but I’m getting User is not authenticated.

Here is the code:

import { useRouter } from 'next/router'
import { Auth } from 'aws-amplify';
import { useForm } from "react-hook-form";
export default function SignIn({ setStatus }) {
  const { register, handleSubmit } = useForm();
  const router = useRouter()

  async function signIn({ username, password }) {
    try {
      let signObj = await Auth.signIn(username, password); // returns the result
      let userInfo = await Auth.currentAuthenticatedUser(); // returns User is not authenticated
    } catch (error) {
      console.log('error signing in', error);
    }
  }

  return (
    <h2></h2>
  )
}

signIn API returns the result but currentAuthenticatedUser returns User is not authenticated. Any thoughts why it might be happening ?

How to get id of selected item from react-dropdown-tree-select with ?reactjs

I’m working on reactJs project with laravel api. Actually now I want to display some informations in form after choosing one Item with react-dropdown-tree-select But I don’t know how to make it :
this is the function that allows showing the id of selected item :

  async function handleShow(unit_id) {
    setSelectedUnit(unit_id)
    console.warn(unit_id)
    let result = await fetch(`${API_ENDPOINT}/api/getUnit/` + unit_id);
    result = await result.json();
    console.warn(result)

  }

This is how I integrate the DropdownTreeSelect:

   <Col sm='6' className='mb-1'>
                <DropdownTreeSelect style={{width:'400'}} data={unitList} onChange={onChange}  mode='radioSelect' 
                 />
              </Col>
   <Col sm='6' className='mb-1'>
                <Label className='form-label'>
                  Contract Rent Per Period
                </Label>
                <Input placeholder='Contract Rent Per Period' />

              </Col>

Now I don’t know how I itegrate the function handleShow to show the Contract Rent Per Period related to this unit.
Thanks in advance for everyone can give me some help resolving this issue

How can I apply alternate color on cells with same values in app script

I have google sheet having 2 columns called start date and end date. while some date has repeated values. I want to find how many entries have same values. if it 2 or more cell has same values apply alternate colors.

All these i want to achive through app script/java script for google sheets.

please see two figures

Figure 1 = normal Figure

By default Figure

Figure 2 = what i want.

Intended work

So far, i have tried different method using conditional formatting by assigning column value to true and false. but no success yet.
any help will be appreciated

Is there a config or modules to handle react-native-webview for react-native-canvas?

I have been trying to integrate react native canvas in my app.
I followed the instructions exactly in https://www.npmjs.com/package/react-native-canvas.

When I run the app, I got the following error.
enter image description here

ATM, I don’t have any babel or webpack config files and I am writing an app in Next.js.
Should there be any configs for that or modules to be installed?
I would appreciate any help.

Cpanel SequelizeConnectionError: no pg_hba.conf entry for host X, user X, database X, SSL inactive

With sequelize migrations , i’m using the below config for connection :

  production: {
    username: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DB,
    host: process.env.POSTGRES_HOSTNAME,
    port: process.env.POSTGRES_PORT,
    dialect: 'postgres',
    logging: false,
    dialectOptions: {
      bigNumberStrings: true,
     },
  },

When i try to run i’t , im getting the error,

SequelizeConnectionError: no pg_hba.conf entry for host X, user X,
database X, SSL off

I tried to solved it with ssl like below:

 ssl: true,
    dialectOptions = {
      ssl: {
      require: true,
      rejectUnauthorized: false 
    }
    },

But the error becomes

Server does not allow ssl connexion

So ‘im in trouble, as the host was not able to help me.

I would appreciate any help.

How can I convert xml code dynamically to table with JS?

I want to display xml code as a table for better readability.
I don’t want to use XML parser, just a quick copy, paste converter.
But the way I’m coding it right now, is still very time consuming.
Is there a way to convert it dynamically?
So for every tag in the xml code a new row/cell etc?

In this example the XML is already in the text area. It contains 2 employees. (This will be a lot more, that’s why I said time consuming)
With a button you first convert it to innerHTML of a div called “output”. I thought that was neccesairy to get the data into the document and convert it to a table. But as you can see, that would mean I would have to adjust the JS code + table for all employees. And some times the xml will contain random number employees. So a dynamical way would be better.
Thank you in advance

function convertxml() {
  var getxml = document.getElementById("inputxml").value;
  document.getElementById("outputxml").innerHTML = getxml;

  name = document.getElementsByTagName("name")[0].childNodes[0].nodeValue;
  document.getElementById("name").innerHTML = name;

  adress = document.getElementsByTagName("adress")[0].childNodes[0].nodeValue;
  document.getElementById("adress").innerHTML = adress;

  birthday = document.getElementsByTagName("birthday")[0].childNodes[0].nodeValue;
  document.getElementById("birthday").innerHTML = birthday;

}
input,
button {
  display: block;
}

#outputxml {
  display: none;
}

textarea {
  height: 300px;
  width: 500px;
}
<textarea id="inputxml">
  <employee>
    <name>John Doe</name>
    <birthday>01-01-1990</birthday>
    <adress>Streetname 123</adress>
  </employee>
  
    <employee>
    <name>Jane Doe</name>
    <birthday>02-02-2000</birthday>
    <adress>Streetname 123</adress>
  </employee>
  
</textarea>
<button id="convertxml" type="button" onClick="convertxml()">Convert</button>

<div id="outputxml"></div>
<table>
  <tr>
    <th></th>
  </tr>
  <tr>
    <td class="label">Name:</td>
    <td id="name"></td>
  </tr>
  <tr>
    <td class="label">Adress:</td>
    <td id="adress"></td>
  </tr>
  <tr>
    <td class="label">Birthday:</td>
    <td id="birthday"></td>
  </tr>

Attempting to get message pin audit logs on discord.js does not return the log for the most recently pinned message

So I am trying to get my bot to log message pins and unpins. This code used to work until recently but now for some reason, the fetched logs do not have an entry for the message whose pinning triggered the messageUpdate event.

const fetchedLogs = await oldMessage.guild.fetchAuditLogs({
      type: 'MESSAGE_PIN',
    });
const pinLog = fetchedLogs.entries.filter(f => f.extra.messageID == oldMessage.id).first();
const { executor } = pinLog;

The error shown is:

Uncaught Promise Rejection TypeError: Cannot destructure property 'executor' of 'pinLog' as it is undefined.

This exact code used to work until recently.

Things I have tried:

  1. Attempted to make the code sleep for a bit (up to 10 seconds) before fetching the logs. Did not work
  2. Attempted to put the fetch into a loop until pinLog is not undefined anymore. Resulted in an infinite loop.

How to style react-select with css modules?

I need to style a react-select component with css modules, at the moment I’m using the classNamePrefix prop to style it, which works just fine with normal scss.
However if I use css modules the styles are not read by the browser.

JSX:

return (
    <div className={`${styles["StrategyForm__spin-dropdown"]}`}>
      <Select
        value={options.find((option) => option.value === spinCount)}
        options={options}
        onChange={handleChange}
        classNamePrefix="StrategyForm__spin-dropdown"
        captureMenuScroll={false}
        isSearchable={false}
      />
    </div>
  );

SCSS:

&__spin-dropdown {
    z-index: 100;
    max-width: 200px;
    width: 100%;
    min-width: 100px;
    color: $slate !important;
    justify-self: end;

    &__indicator-separator {
      display: none;
    }

    &__dropdown-indicator {
      path {
        fill: $secondary-color;
      }
    }

    &__spin-dropdown_menu {
      z-index: 1000;
    }

    &__menu-list,
    &__control,
    &__single-value {
      font-weight: 500;
      color: $slate !important;
    }

    &__option {
      &--is-focused {
        background-color: rgba($light-slate, 0.2) !important;
        color: $slate !important;
      }

      &--is-selected {
        font-weight: bold;
        background-color: transparent !important;
        color: $slate !important;
      }
    }
    &__control {
      &--is-focused {
        box-shadow: 0 0 0 1px $secondary-color !important;
        border-color: $secondary-color !important;
      }
    }
  }

inspecting from browser I see that the classes I made to modify the component don’t have a hash like normal css.modules classes

enter image description here

How to get value for merged cell in table(Canvas)?

I have a table in my editor which is made on canvas, so i’m calculating the rows and columns from it,but there is some problem with the counting of table.

enter image description here

Here in column(1), it only has cells of September 30,2020 and $ in that column information.

column(2) has cell of 750,(2123,2863

So, can someone help with what i’m doing wrong here?

I cannot provide a proper example for it,but i can provide a mock through which you can at least get the cells information.

FYI: the information i’m getting from my application are all in Object so it hard to provide the information,if needed i can provide a screenshot’s of the information.

Here is the calculation code for table rows and columns

CTable.prototype.GetTableMapping = function (currentTable) {
    
    //get row count
    let oRowCount = currentTable.GetRowsCount();
    const rowArr2D = Array(oRowCount);
    for (let i = 0; i < oRowCount; i++) {
         //get cell information
         let oRow = currentTable.GetRow(i);
         let oCellCount = oRow.GetCellsCount();
         rowArr2D[i] = Array(oCellCount);
         for (let j = 0; j < oCellCount; j++) {
              //get cell count
              let oCell = oRow.GetCell(j);
              rowArr2D[i][j] = oCell;
         }
    }
    // get column information
    const colArr2D = (array) => array[0].map((a, i) => array.map((b) => b[i]));

    return {
        columnMapping: colArr2D(rowArr2D),
        rowMapping: rowArr2D
    };
};

mockTable = { // mocking the portions of my code
  GetRowsCount : () => 4,
  GetRow: (x) => ({
    GetCellsCount : () => 7,
    GetCell : (x) => x
  })
}

CTable_prototype_GetTableMapping = function(currentTable)
{
   
    //get row count
    let oRowCount = currentTable.GetRowsCount();
    const rowArr2D = Array(oRowCount);
    for (let i = 0; i < oRowCount; i++) {
         //get cell information
         let oRow = currentTable.GetRow(i);
         let oCellCount = oRow.GetCellsCount();
         rowArr2D[i] = Array(oCellCount);
         for (let j = 0; j < oCellCount; j++) {
              //get cell count
              let oCell = oRow.GetCell(j);
              rowArr2D[i][j] = oCell;
         }
    }
    // get column information
    const colArr2D = (array) => array[0].map((a, i) => array.map((b) => b[i]));


    colArr2D(rowArr2D, oRowCount);
  return rowArr2D
    console.log(rowArr2D);
};

const theArray = CTable_prototype_GetTableMapping(mockTable);

console.log("full 2D array", theArray)