How the security work on clintside JavaScript [closed]

I have confise on security on js when run on clint side for examples:
I have file config (Json or .env) has keys that used on js varb, js run on browser, this is the problem I think attacker can get the keys!
As I use firebase config on clintside when browser connect with firebase, attacker can get the keys!.

This my question attacker can find and get my keys on clintside?

I need explain the problem

Results is not displayed in the output [closed]

After installing visual studio code (installed code runner also), I’ve created a new JavaScript file, index.js and ran the code.

Code ended without errors, but I dont see my ‘5’ and ‘hello world’ in the output.

const result = 2 + 3;
console.log(result);
console.log('hello world');

Output:

[Running] node “c:UsersADMINZDesktopindex.js”
[Done] exited with code=0 in 0.053 seconds

How to efficiently manage its connections pool using the mariadb-connector-js package from npm?

I have some interogations about the mariadb connector (and the whole mariadb database’s functioning) on connections handling.

In my typescript program (using mariadb-connector v3.4.0 with a mariadb server v10.6.21) I’m instantiating a pool at my program start as well as a web server using expressJS. In each functions accross my app I’m using the async’s pool.query("<query>", [<params>]); directly (without creating proper connections nor releasing them after their use) like this:

// in my main file
...
const pool = createPool({
  ...config.mysql,
  trace: level === Level.Debug,
  insertIdAsNumber: true,
  bigIntAsNumber: true,
  connectionLimit: 10 // I know this is the default value
});

// Here let's imagine I'm brining up a web server through expressJS and have some routes
// from which I need to retrieve data from my mariadb database

// in another file, I have a collection of functions like this:
export class ElementRepository{
  constructor(private pool: Pool) {}

  async getElementById = (id: number): Promise<Element> => {
    const query = "SELECT * FROM elements WHERE id = :id";
    const params = [id];
    const [result] = await this.pool.query<Element[]>(query, params);
    console.log("some logs");
    return result;
  }

  async getElements = (): Promise<Element[]> => {
    const query = "SELECT * FROM elements";
    const result = await this.pool.query<Element[]>(query, []);
    console.log("some logs");
    return result;
  }
}

So first question:

As you can see, I’m not using getConnections() with a .release() at the end, but it does work, should I worry about it ? or is it managed under the hood ? I guess now 10 connections are reserved by the mariadb-connector and will never be killed even if idle ? Am I wrong ?


When my application start, I need to fetch a lot of data, and I can’t do it in one query (because the SQL query would looks like quite hideous with more than 300 lines), so I make only one simple query which fetch all my elements (those I call “raw elements”), and then I’ll iterate over each elements to make a multiple SQL queries that may take up to 5sec to compute (depending of the amount of elements in my table) to compute the element’s utilization rate. Using multiple seconds to compute element’s utilization rate is kinda “normal” because it may compute it based on millions entries.

My code looks like something like this:

const rawElems = await pool.query("SELECT * FROM elements", []);
const chunkSize = 10;
const chunkedElems = [...Array(Math.ceil(rawElems.length / chunkSize))].map((_) => rawElems.splice(0, chunkSize));
const elements: Element[] = [];

const start = performance.now();
// Iterate over each chunk and concurrently fetch their elements use rates
for (const elem of chunkedElems ) {
  const result = await Promise.all<Element>(
    elem.map(async (element) => {
      const lastMaintenanceDate = await this.getLastMaintenanceDate(element.id);
      // counter represent the raw counter value that is computed differently depending of the element's type
      const counter = await (async (mode: ConfigurationMode) => {
        switch (mode) {
          case ConfigurationMode.Occurrence:
            return this.getCurrentAmount(element.id, lastMaintenanceDate);
          case ConfigurationMode.Duration:
            return this.getCurrentDuration(element.id, lastMaintenanceDate);
          default:
            return 0;
        }
      })(element.mode);
      return { ...element, debounce: false, counter };
    })
  );
  elements.push(...result);
  // Display the percentage of ready observed elements
  const percentage = `${((elements.length / chunkSize / chunkedElems .length) * 100).toFixed(0)}%`;
  console.log("still processing observed elements...", percentage);
}
const stop = performance.now();
const elapsedTime = ((stop - start) / 1000).toFixed(2);
console.log(`finished to load element's counter in ${elapsedTime}s!`);

So with this snippet, I will take 10 connection from the pool (it’s currently hardcodded but since it’s the pool’s connectionLimit I guess it’s okay), and I will segment my rawElems in chunck of 10, and sequentially iterate on each chunck of 10 rawElems and use an awaited Promise.all() to compute their use rate in the same time. It works.
But now let’s imagine I want to increase the connectionLimit in my pool, I could safely retrieve it with a mere pool.getActiveConnections() ? can I increase the connectionLimit property up to the maximim available connection on my MariaDB instance ? I have the default number, 151, that I get from SHOW variables LIKE 'max_connections';, and since the following query SHOW status LIKE 'Max_used_connections'; returned a Value of 16, it means I used 72 simultaneous connections, so I may increase connectionLimit by 50 without much issues ?

Second question:

Did I understood correctly ? or am I mixing multiple things / concept ?

Why is “this” still available in rxjs subscription [duplicate]

Looking to the code below

 @Component({
  .....
})
export class AngularComponent {
     componentVariable: bool;
 
     someMethod(){
        this.service.subscribe(x => this.componentVariable = x)
     }
}

Why this can access AngularComponent and set the componentVariable while being on the subscribe? Should this refer to the subscription context and not the component context?

Ps. I know this can be a bad practice but I want to understand how this is working.

Passing children to ResponsiveGridLayout doesn´t works (React-Gird-Layout)

I can´t see the childs I pass to ResponsiveGridLayout tag, this library is so outdated I dont know what else to do.
I have this a few .jsx I´ll show you two of them:

import { useEffect, useState } from "react";
import { Responsive, WidthProvider } from "react-grid-layout";
import "./PrototypeComponent.css";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";

const ResponsiveGridLayout = WidthProvider(Responsive);
const LOCAL_STORAGE_KEY = "my_layouts";
const BREAKPOINT_KEY = "my_breakpoint";

const defaultLayouts = {
  lg: [
    { i: "1", x: 0, y: 0, w: 4, h: 4 },
    { i: "2", x: 4, y: 0, w: 4, h: 4 },
    { i: "3", x: 8, y: 0, w: 4, h: 4 },
  ],
  md: [],
  sm: [],
};

function PrototypeComponent({ children }) {
  const [layouts, setLayouts] = useState(defaultLayouts);
  const [currentBreakpoint, setCurrentBreakpoint] = useState("lg");

  useEffect(() => {
    const savedLayouts = localStorage.getItem(LOCAL_STORAGE_KEY);
    const savedBreakpoint = localStorage.getItem(BREAKPOINT_KEY);
    if (savedLayouts) {
      try {
        const parsedLayouts = JSON.parse(savedLayouts);
        setLayouts(parsedLayouts);
      } catch (e) {
        console.error("Error al leer layouts desde localStorage", e);
      }
    }
    if (savedBreakpoint) {
      setCurrentBreakpoint(savedBreakpoint);
    }
  }, []);

  const handleBreakpointChange = (breakpoint) => {
    setLayouts((prevLayouts) => {
      if (!prevLayouts[breakpoint] || prevLayouts[breakpoint].length === 0) {
        return {
          ...prevLayouts,
          [breakpoint]: prevLayouts[currentBreakpoint] || [],
        };
      }
      return prevLayouts;
    });
    setCurrentBreakpoint(breakpoint);
    localStorage.setItem(BREAKPOINT_KEY, breakpoint);
  };

  const handleLayoutChange = (layout, allLayouts) => {
    setLayouts(allLayouts);
  };

  useEffect(() => {
    const handleBeforeUnload = () => {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(layouts));
      localStorage.setItem(BREAKPOINT_KEY, currentBreakpoint);
    };
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, [layouts, currentBreakpoint]);

  return (
    <ResponsiveGridLayout
      className="layout"
      layouts={layouts}
      breakpoints={{ lg: 1200, md: 996, sm: 768 }}
      cols={{ lg: 12, md: 10, sm: 6 }}
      rowHeight={100}
      isDraggable
      isResizable
      draggableHandle=".handle"
      compactType="horizontal"
      preventCollision={false}
      margin={[10, 10]}
      containerPadding={[10, 10]}
      onBreakpointChange={handleBreakpointChange}
      onLayoutChange={handleLayoutChange}
    >
      {children}
    </ResponsiveGridLayout>
  );
}

export default PrototypeComponent;

Second one:

import PrototypeComponent from "./PrototypeComponent";
import Portlet from "./Portlet";

const PrototypePage = () => {
  return (
    <>
      <PrototypeComponent>
        <h1>Hola</h1>
        <Portlet id="1" title="Portlet 1" src="https://www.example.com" />
        <Portlet id="2" title="Portlet 2" src="https://www.example.com" />
        <Portlet id="3" title="Portlet 3" src="https://www.example.com" />
      </PrototypeComponent>
    </>
  );
};

export default PrototypePage;

This is what i see in the browser 1

It looks like there is nothing inside
I can´t see the childs I pass to ResponsiveGridLayout tag, this library is so outdated I dont know what else to do.I can´t see the childs I pass to ResponsiveGridLayout tag, this library is so outdated I dont know what else to do.

Pin positioning gets disturbed due to rerendering in other component

Demo Repo : https://github.com/ks-mani/gsap-doubt

Issue’s Video : https://github.com/ks-mani/gsap-doubt/blob/main/gsap-issue.mov


I have two component.

  1. First component has GSAP specific code wrapped in useEffect with a dependency.
  2. Second component has GSAP specific code wrapped in useEffect without a dependency.

The issue is that rerendering in the first component disturbs the pin position of the second component.

My guess is that rerendering the second component also will make the pin positioing of second component align perfectly. But is this right approach for this? Shouldn’t GSAP handle this scenario automatically ?

P.S. I can’t use useGSAP hook in my project.

Convert from stereo to mono on Vimeo SDK

I have a web app with embedded Vimeo videos. These videos are in stereo, with sound panned to the left (60-40%) and some to the right (40-60%). Several users have speakers where one side is broken and they only hear the right or the left, therefore the video often sounds like there’s a drop in the sound volume.

I would like some Javascript from the Vimeo SDK that lets these users hear the video in mono, while the others can hear it in stereo. Does that exist?

Add custom theme spacing to unocss for tailwind 4 preset

I can’t configure additional spacing values for the tailwind 4 preset

import { defineConfig } from "unocss";
import { presetAttributify } from "@unocss/preset-attributify";
import presetWind from "@unocss/preset-wind4";

export default defineConfig({
  presets: [ presetWind()],
  theme: {
    colors: {
      veryCool: "#0ff",
    },
    spacing: {
      md: "24rem",
    },
  },
});

Usage example <div class="text-very-cool p-md">12312</div>
Paddings are expected to be 24rem

C @unocss/preset-wind3 works fine, how to configure for @unocss/preset-wind4?

Failed to load resource: the server responded with a status of 500 (Internal Server Error).status of 500 (Internal Server Error)

Failed to load resource: the server responded with a status of 500 (Internal Server Error).status of 500 (Internal Server Error)

not able to redirect to webmethod called in aspx page

on button click redirect webmenthod

I want call the web method on perticular button click
not able to redirect to webmethod called in aspx page

on button click redirect webmenthod

I want call the web method on perticular button click

not able to redirect to webmethod called in aspx page

on button click redirect webmenthod

I want call the web method on perticular button click

React native expo, expo-location, undefined coords

I’m developing expo react native app and have a probelem with location.

Code:
const {coords} = Location.getCurrentPositionAsync({})

Result:
coords is undefined.

Every time I refresh app the geolocation icon in status bar appears.

Permission is granted. App.json is configured for ios and android.

I tried ios emulator iphone 16 pro, my own 14 pro and Sony on android. For all of them I have the same result as described above. I console.log() objects and other variables.

Where could I search the source of the problem? Could it be app.json or another file?

What should I do to overcome this issue?

This issue blocks me a lot!

Thanks in advance for your responses.

I tried many variants of configuration of app.json.

Web Deployment options for small businesses [closed]

I am new to web development and have done training for MERN full stack, but I found it quite difficult to deploy especially for small business which dont afford high web hosting costs for MERN. What should be choice of tools in this scenario that reduces deployment cost as well as development time; pure JS/JSP, or JS with 3rd party libraries such as datatables or anyother combination?
Thanks

Asset pipeline rails 7.1

I am trying to implement a simple shopping website from a ready made HTML template.
I moved all the files to respective folders in rails and trying make it work but tough luck.I have both css and scss files in the template project which is causing more confusion.

template project’s asset folder has these assets

enter image description here

I followed following steps in the migration

  1. moved all files to respective folders
  2. moved scss files to stylesheets folder and renamed application.css to application.scss and imported all css files in that file
  3. registered all assets to assets.rb under Rails.application.config.assets.precompile += %w(….) and ran assets:precompile which is creating stamped files for cashing.
  4. in application.html.erb change all script and style tags to rails 7 relevant tags <%= stylesheet_link_tag %> <%= javascript_importmap_tags%>

rails folders rails folders..

My assets are not making any changes on the front end and also js not working as expected.

I am seeing ActionController::RoutingError (No route matches [GET] “/fonts/fontAwesome/fa-solid-900.woff2”) for every asset I mentioned in the application.html.erb

I request a clear understanding on asset pipeline in rails and rails 7 and steps I need to follow during migration of html template to rails project.

Is there a smart way to handle focus/blur when using tabindex attribute?

I have a number of sliding menus that are offscreen or behind other elements and slide into view using transform: translateY. They’ve been working for about two years without issue. Today, I added keydown events to the menus which requires that the otherwise unfocusable divisions be focused. This was done using the tabindex attribute and setting it to -1 and using focus() and blur() and mouseenter and mouseleave. This works also.

The issue that occurs, now, but not at every event is that after the menu has been given focus upon mouseenter, a keydown event is performed, and the menu loses focus upon mouseleave, when the menu is closed, instead of the menu sliding away (down, off-screen for example) it starts moving down and then, suddenly, the rest of the UI moves up instead and the menu that should be hidden is visible, just as if the translateY was applied to the rest of the UI.

The menus are in a division that is positioned absolute to its container element that has overflow-y and -x set to hidden. This does not stop the scrolling but only changes what part of the UI is hidden.

As long as the menu does not receive the focus, the open/close button can be clicked repeatedly without issue and the menus slide on and off screen as expected.

If the optionable property of {preventScroll: true} is used in the focus() method when giving the focus to the menus, all seems to work fine; that is, I haven’t been able to cause the issue when it is used. But I’m not sure how reliable preventScroll is.

My question is, Is there a better way to handle this? I tried to use blur() when the menu is closed (even though the mouseleave event already invoked blur()) but that does not help. It seems that blur() does not remove the focus for the purpose of scrolling and rather than trying to cause the menu to lose focus, the focus should be given to another element. I also tried removing the tabindex attribute upon close and that did not help either.

Thank you.

Adding currency as default value on record initialization on vendor payment record using suitescript to get the correct apply sublist data

I am trying to create a vendorpayment record using script. This is my script.

var transactionId = '11111';
var vendorId = '222';
var subsidiaryId = '2';
var apAccountId = '333'
var inputAmount = 1000;
var currencyId = '4'; //USD

var make_billPayment_record = record.create({
    type: 'vendorpayment',
    defaultValues: { entity: vendorId, subsidiary: subsidiaryId, apacct: apAccountId }
});
if(!!currencyId){make_billPayment_record.setValue({ fieldId: 'currency', value: currencyId });}; //Currency
if(!!bankAccountId){make_billPayment_record.setValue({ fieldId: 'account', value: bankAccountId });}; //Account
if(!!departmentId){make_billPayment_record.setValue({ fieldId: 'department', value: departmentId });}; //Department
if(!!classId){make_billPayment_record.setValue({ fieldId: 'class', value: classId });}; //Cash Flow Segment
if(!!exchangeRate){make_billPayment_record.setValue({ fieldId: 'exchangerate', value: parseFloat(exchangeRate) });}; //Exchange Rate
make_billPayment_record.setValue({ fieldId: 'custbody_9997_is_for_ep_eft', value: true }); //For Electronic Bank Payment

var apply_numLines = make_billPayment_record.getLineCount({sublistId: 'apply'});

for(i = 0; i < apply_numLines; i++){
    var lineTxnId = make_billPayment_record.getSublistValue({
        sublistId: 'apply',
        fieldId: 'internalid',
        line: i
    });
    if(parseFloat(lineTxnId) == parseFloat(transactionId)){
        make_billPayment_record.setSublistValue({
            sublistId: 'apply',
            fieldId: 'apply',
            line: i,
            value: true
        });
        make_billPayment_record.setSublistValue({
            sublistId: 'apply',
            fieldId: 'amount',
            line: i,
            value: parseFloat(inputAmount)
        });
    }
};

var created_bp_id = make_billPayment_record.save({ enableSourcing: true, ignoreMandatoryFields: true });

I am aware that you cannot create a list on vendorpayment, it is preloaded based on the vendor, subsidiary and currency and you have to iterate each line and apply the transaction. The thing that I am having trouble with is initializing that list. When I do record.create with default values, the initialized sublist data does not contain the apply line that I am looking for because the default currency being set is different. When I add currency as a default value on my record.create, Netsuite is giving me an error {“name”:”INVALID_RCRD_INITIALIZE”,”message”:”You have entered an invalid default value for this record initialize operation.”}. I also tried creating a vendorpayment record without applying any transactions first but Netsuite is also giving me an error “You must enter at least one line item for this transaction.”

If I can’t initialize record.create with currencyId, I can’t get the correct apply sublist data.

If initializing record with currencyId is not possible, is there a way for me to get the correct apply sublist? Or is there a different way to achieve what I am trying to do?
Any help would be appreciated, thanks.

Winston optionally include label

So I am writing up Node.js Express.js API that utilizes winston for logging. I was hoping if I could achieve a log that looks like this:

[Timestamp] [label] [level]: message

So far I have been able to have the timestamp, level, and messsage. Can anyone help me with how I need to modify the code?

.utilslogger.js

const { createLogger, format, transports } = require('winston')
const config = require('../configs/app.conf')

const devFormat = format.printf(({ timestamp, level, message }) => `${timestamp} ${level}: ${message}`)
const prodFormat = format.printf(({ level, message }) => `${level}: ${message}`)

const logger = createLogger({
    level: 'debug',
    format: format.combine(
        format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        format.errors({ stack: true }),
        format.splat(),
        format.json()
    ),
    transports: [
        new transports.Console({
            format: format.combine(
                format.colorize(),
                config.env === 'development' ? devFormat : prodFormat
            )
        }),
        new transports.File({ filename: 'logs/error.log', level: 'error' }),
        new transports.File({ filename: 'logs/combined.log' })
    ]
})

module.exports = logger

.index.js

const express = require('express')
const cors = require('cors')
const useragent = require('express-useragent')
const cookieParser = require('cookie-parser')
const app = express()
const logger = require('./utils/logger')
const errorHandler = require('./middlewares/ErrorHandler')
const config = require('./configs/app.conf')
const { connectDB } = require('./db/database')

app.use(cors({
    origin: [
        'http://localhost:5173',
        'https://localhost:5173',
    ],
    methods: 'GET,POST,DELETE,PUT,PATCH',
    allowedHeaders: 'Content-Type,Accept,Authorization,x-requested-with',
    credentials: true,
}))

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(useragent.express())
app.use(cookieParser())
app.set('trust proxy', true)

app.use('/user', require('./routes/userRoutes'))

app.use(errorHandler)

const startServer = async () => {
    try {
        await connectDB()

        app.listen(config.port, () => logger.info(`Server running in ${config.env} mode at port ${config.port}`))
    }
    catch (error) {
        logger.error(error.message)
        process.exit(1)
    }
}

startServer()

.middlewaresErrorHandler.js

const logger = require('../utils/logger')

const errorHandler = (err, req, res) => {
    const statusCode = res.statusCode || 500

    logger.error(`[${statusCode}] ${err.message}`, {
        method: req.method,
        path: req.originalUrl,
        ip: req.ip,
        userAgent: req.headers['user-agent'],
        stack: err.stack
    })

    res.status(statusCode).json({
        title: getErrorTitle(statusCode),
        message: err.message,
        stackTrace: err.stack
    })
}

const getErrorTitle = (statusCode) => {
    const titles = {
        400: "Bad Request",
        401: "Unauthorized",
        403: "Forbidden",
        404: "Not Found",
        405: "Method Not Allowed",
        406: "Not Acceptable",
        408: "Request Timeout",
        409: "Conflict",
        410: "Gone",
        413: "Payload Too Large",
        414: "URI Too Long",
        415: "Unsupported Media Type",
        422: "Unprocessable Entity",
        429: "Too Many Requests",
        500: "Internal Server Error",
        502: "Bad Gateway",
        503: "Service Unavailable",
        504: "Gateway Timeout"
    }

    return titles[statusCode] || "Unexpected Error"
}

module.exports = errorHandler

.dbdatabase.js

const { MongoClient, ServerApiVersion } = require('mongodb')
const logger = require('../utils/logger')
const config = require('../configs/app.conf')

let client

const connectDB = async () => {
    if (!client) {
        try {
            client = await MongoClient.connect(config.db_url, {
                serverApi: {
                    version: ServerApiVersion.v1,
                    strict: true,
                    deprecationErrors: true
                }
            })
            logger.info('Connected to MongoDB')
        }
        catch (error) {
            throw new Error(error.message)
        }
    }

    return client.db()
}

module.exports = { connectDB }

I was hoping to achieve like for example in the database, if I log the success message, I could somehow make it timestamp [MongoDB] info: Successfully connected to database when logged. Another would be in the index.js when it successfully starts the server, I want it to be timestamp [Server] info: success message. And if I did not indicate a label in the log, it will just default to ‘App’, such that: timestamp [App] info: message. Any ideas on how to achieve this?