I can’t get access the TMDB API KEY

How to access the TMDB API KEYs4

MONGO_URI = mongodb+srv://saisrinivasdandangi:[email protected]/netflix_db?retryWrites=true&w=majority&appName=Cluster0
PORT = 5000

JWT_SECRET = my_really_hard_to_decode_secret
NODE_ENV = development

TMDB_API_KEY = eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxODE1ZjFhYWVjNjZmNTEzMzY5MGFhOGRiM2MwNDFmMiIsIm5iZiI6MTc0NDAyNzc5MS40Mywic3ViIjoiNjdmM2MwOGY4NTRiMDUzOGNmZDkzOTc4Iiwic2NvcGVzIjpbImFwaV9yZWFkIl0sInZlcnNpb24iOjF9.f6pIcXzEGFyWKFNmF3pUgY5So_Az3duX4uA2_9WFZ44

jspdf Tahoma Font rendering different from other PDF

To use the Tahoma font in my PDF I loaded the TTF file from my Windows/Fonts folder into a converter which holds a Base64 string as input to the jsPDF plugin.

Now the results show different from another PDF I try to replace in the old system as depicted below. This is shown at 100% like the new PDF has slightly thicker letters and the spacing varies slightly which shows clearly when comparing the two PDF files

Comparison

enter image description here

enter image description here

jsPDF Code

doc.addFileToVFS( 'Tahoma-normal.ttf', fontBase64Str );
doc.addFont( 'Tahoma-normal.ttf', 'Tahoma', 'normal' );

doc.setFontSize( 7 );
doc.setFont( 'Tahoma' );

doc.text( 'Id.No.', 57, 10 );

What could be the issue or setting I am missing please?

Why does Chrome black out, or crash with “aw, snap – out of memory” when there is still plenty of memory available?

I’m developing a Svelte-based Javascript single-page app with a lot of Apache ECharts displays in it that is fairly heavy in both DOM elements and array data, but generally stays in the 400-500MB range of memory usage. However, whenever Task Manager shows it in the > 900MB range Chrome starts misbehaving – sometimes tabs go blank (failing to render? dropping their nodes?) and after 10 seconds or so seems to self-heal and reappear. Sometimes the whole page goes black for 10-20 seconds. And sometimes I get the “Aw, Snap! – Out of Memory” error. And yet when I watch Task Manager’s Performance tab, I see several GB remaining of free memory. This confuses me. I’ve never seen memory usage even get close to 100% – and yet I get all these problems happening when my page’s memory profile approaches 1GB.

Lowering memory use is of course something I can chip away at, but my question right now is when can I expect this kind of misbehavior from a web browser? Why would it freak out when there’s still available memory out there? What limit is it really hitting? How can I tell? Nothing I see in Task Manager (Window’s) or in Chrome’s own Task Manager, or in DevTools memory snapshots suggests running out of any resource – and yet clearly that must be happening. Does Chrome impose its own limits internally? Is there some other OS limit I’m not aware of? What is the standard procedure for diagnosing behavior like this?

My OS is Windows 10.

Why is state stale in my socket.on listener?

Please can someone tell me why the consumers variable is an empty object inside my user disconnected listener. It is clear that the state in the consumers variable is stale because the JSX maps through it and shows consumers on the screen.

Here is my react functional component:

"use client";

import { useEffect, useRef, useState } from "react";
import { socket } from "@/lib/socket";
import * as mediasoupClient from "mediasoup-client";
import { useSearchParams } from "next/navigation";
import createProducerTransport from "./functions/createProducerTransport.js";
import createProducer from "./functions/createProducer.js";
import requestTransportToConsume from "./functions/requestTransportToConsume.js";

export default function Call({ name }) {
  const searchParams = useSearchParams();
  const roomName = searchParams.get("id");
  const localVideo = useRef();
  const localStream = useRef();
  const runOnce = useRef(false);
  const joinRoomResp = useRef({});
  const device = useRef();
  const producerTransport = useRef(null);
  const videoProducer = useRef(null);
  const audioProducer = useRef(null);
  const [isAudioMuted, setIsAudioMuted] = useState(false);
  const [consumers, setConsumers] = useState({});

  useEffect(() => {
    if (runOnce.current) return;
    runOnce.current = true;

    socket.emit("connected");
    socket.on("connected", async () => {
      console.log("socket connected");
      await gum();
      joinRoomResp.current = await joinRoom();
      await sendFeed();
    });

    socket.on("updateActiveSpeakers", async (newListOfActives) => {
      console.log(newListOfActives);
      console.log(consumers);
      setConsumers((prevState) => {
        const newState = { ...prevState };
        newListOfActives.forEach((active) => {
          if (newState[active.id]) {
            newState[active.id].combinedStream = active.combinedStream;
            newState[active.id].userName = active.userName;
            newState[active.id].audioConsumer = active.audioConsumer;
            newState[active.id].videoConsumer = active.videoConsumer;
            newState[active.id].consumerTransport = active.consumerTransport;
          }
        });
        return newState;
      });
    });
    socket.on("newProducersToConsume", (consumeData) => {
      // console.log("newProducersToConsume");
      // console.log(consumeData);
      requestTransportToConsume(
        consumeData,
        socket,
        device.current,
        setConsumers
      );
    });
    const gum = async () => {
      localStream.current = await navigator.mediaDevices.getUserMedia({
        audio: true,
        video: true,
      });
      localVideo.current.srcObject = localStream.current;
      // localVideo.current.muted = true;
    };
    const joinRoom = async () => {
      const res = await socket.emitWithAck("joinRoom", {
        userName: name,
        roomName,
      });
      device.current = new mediasoupClient.Device();
      await device.current.load({
        routerRtpCapabilities: res.routerRtpCapabilities,
      });
      console.log("joinRoomResp", res);
      // console.log("device", device.current);
      requestTransportToConsume(res, socket, device.current, setConsumers);
      return res;
    };
    const sendFeed = async () => {
      producerTransport.current = await createProducerTransport(
        socket,
        device.current
      );
      console.log("Have the producer transport, now we need to produce");
      const producers = await createProducer(
        localStream.current,
        producerTransport.current
      );
      videoProducer.current = producers.videoProducer;
      audioProducer.current = producers.audioProducer;
      console.log("Producers are created!");
    };
    socket.on("userDisconnected", (userName) => {
      console.log("user disconnected", userName);

      setConsumers((prevState) => {
        const newState = { ...prevState };

        // Find and remove the user
        Object.keys(newState).forEach((key) => {
          if (newState[key].userName === userName) {
            // Close the consumer's connections before removing it
            newState[key].audioConsumer.close();
            newState[key].videoConsumer.close();
            newState[key].consumerTransport.close();

            // Remove the user from the state object
            delete newState[key];
          }
        });

        console.log("Updated consumers after removal:", newState);
        return newState;
      });
    });

    socket.on("disconnect", () => {
      console.log("disconnected");
      producerTransport.current = null;
      videoProducer.current = null;
      audioProducer.current = null;
    });
  }, []);

  useEffect(() => {
    console.log("consumers", consumers);
  }, [consumers]);

  const muteAudio = () => {
    if (audioProducer.current.paused) {
      audioProducer.current.resume();
      socket.emit("audioChange", "unmute");
      setIsAudioMuted(false);
    } else {
      audioProducer.current.pause();
      socket.emit("audioChange", "mute");
      setIsAudioMuted(true);
    }
  };
  return (
    <div>
      {roomName && <h1>Room ID: {roomName}</h1>}
      <button onClick={muteAudio}>{isAudioMuted ? "Unmute" : "Mute"}</button>
      <video
        ref={localVideo}
        autoPlay
        playsInline
        style={{ width: "100px", height: "100px" }}
      />
      <div>
        {Object.keys(consumers).map((key) => {
          return (
            <div key={key}>
              <h3>{consumers[key].userName}</h3>
              <video
                id={`remote-video-${key}`}
                autoPlay
                playsInline
                style={{ width: "300px", height: "300px" }}
                ref={(video) => {
                  if (video) {
                    video.srcObject = consumers[key].combinedStream;
                  }
                }}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
}

I have narrowed the problem down to the consumers variable with console logs and noticed it is definitely an empty object inside the event listener.

How to use `frida` to hook Linux app developed based on electron

I am currently learning frida, and I found a lot of tutorials about how to use frida hook app on Android, and I did some practice, which made me feel that frida is a powerful tool.

Now I want to hook functions on a Linux desktop application FreeTube, which is developed in electron. The function I want to hook is in this file:

    handleClick: function (e) {
      // No action if no input text
      if (!this.inputDataPresent) {
        return
      }

      this.searchState.showOptions = false
      this.searchState.selectedOption = -1
      this.searchState.keyboardSelectedOptionIndex = -1
      this.removeButtonSelectedIndex = -1
      this.$emit('input', this.inputData)
      this.$emit('click', this.inputData, { event: e })
    },

But strangely, I can’t find any tutorials on hooking functions on electron on the Internet. And the official documentation of frida provides very little information.

So, I tried it myself by injecting the code below using frida in the renderer process of FreeTube:

// hook.js
if (typeof document !== "undefined") {
    console.log("[Frida] Attached to renderer process");
} else {
    console.log("[Frida] Attached to main process or invalid context");
}

However, this hook can’t get the process context of renderer process, the document is not defined.

So, I want to ask:

  1. Can frida hook functions in PC applications developed based on electron, or just can frida hook functions in Javascript? If javascript is not supported, does that mean Python is not supported either?
  2. If frida can hook functions in Javascript, which layer should I hook to? Should I hook into the renderer process, the V8 engine, or somewhere else?
  3. I would be very grateful if you could provide a hook code for an electron application.

I am new to frida and know very little about javascript and electron. If there is something wrong with the way I think about the problem, I hope to be corrected. Thank you very much.


In addition, I found an issue that did not contain any information on how to use frida hook in Python.

Disable PayPal “Shipping to billing address” option

Our ASP.NET app sells only digital goods and doesn’t need the “Shipping to billing address” checkbox shown. Using the code example from the PayPal Checkout documentation, I’ve got the following index.html page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PayPal JS SDK Standard Integration</title>
</head>
<body>
    <div id="paypal-button-container"></div>
    <p id="result-message"></p>

    <!-- Initialize the JS-SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=<my_client_id>&buyer-country=US&currency=USD&components=buttons&enable-funding=card&commit=false&disable-funding=paylater&debug=true"
            data-sdk-integration-source="developer-studio"></script>
    <script src="Scripts/paypal/app.js"></script>
</body>
</html>

The code in app.js is:

const paypalButtons = window.paypal.Buttons({
    style: {
        shape: "rect",
        layout: "vertical",
        color: "gold",
        label: "paypal",
    },
    message: {
        amount: 100,
    },
    
    async createOrder() {
        try {
            const response = await fetch("/api/paypal/orders", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                // use the "body" param to optionally pass additional order information
                // like product ids and quantities
                body: JSON.stringify({
                    cart: [
                        {
                            id: "YOUR_PRODUCT_ID",
                            quantity: "YOUR_PRODUCT_QUANTITY",
                        },
                    ]
                })
            });

            const orderData = await response.json();

            if (orderData.id) {
                return orderData.id;
            }
            const errorDetail = orderData?.details?.[0];
            const errorMessage = errorDetail
                ? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
                : JSON.stringify(orderData);

            throw new Error(errorMessage);
        } catch (error) {
            console.error(error);
            // resultMessage(`Could not initiate PayPal Checkout...<br><br>${error}`);
        }
    },
    async onApprove(data, actions) {
        try {
            const response = await fetch(
                `/api/paypal/orders/${data.orderID}/capture`,
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                }
            );

            const orderData = await response.json();
            // Three cases to handle:
            //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
            //   (2) Other non-recoverable errors -> Show a failure message
            //   (3) Successful transaction -> Show confirmation or thank you message

            const errorDetail = orderData?.details?.[0];

            if (errorDetail?.issue === "INSTRUMENT_DECLINED") {
                // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                // recoverable state, per
                // https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/
                return actions.restart();
            } else if (errorDetail) {
                // (2) Other non-recoverable errors -> Show a failure message
                throw new Error(
                    `${errorDetail.description} (${orderData.debug_id})`
                );
            } else if (!orderData.purchase_units) {
                throw new Error(JSON.stringify(orderData));
            } else {
                // (3) Successful transaction -> Show confirmation or thank you message
                // Or go to another URL:  actions.redirect('thank_you.html');
                const transaction =
                    orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
                    orderData?.purchase_units?.[0]?.payments
                        ?.authorizations?.[0];
                resultMessage(
                    `Transaction ${transaction.status}: ${transaction.id}<br>
          <br>See console for all available details`
                );
                console.log(
                    "Capture result",
                    orderData,
                    JSON.stringify(orderData, null, 2)
                );
            }
        } catch (error) {
            console.error(error);
            resultMessage(
                `Sorry, your transaction could not be processed...<br><br>${error}`
            );
        }
    }
});
paypalButtons.render("#paypal-button-container");

// Example function to show a result to the user. Your site's UI library can be used instead.
function resultMessage(message) {
    const container = document.querySelector("#result-message");
    container.innerHTML = message;
}

The above code needs to include the following to disable the shipping option but where do you add it?

application_context: {
    shipping_preference: "NO_SHIPPING"
}

This question has application_context but note that it doesn’t have anywhere to put the server API endpoint for the fetch as in my code above.

Your help is appreciated.

VuePrime datepicker does not change css attributes

I am using the PrimeVue UI component libary. I am trying to change the font size and color of the datepicker but it just won’t work.

This is my template:

<div style="flex: 1;">
          <label for="eventEndDate" class="labels">Enddatum</label>
          <DatePicker id="eventEndDate" v-model="eventEndDate" :minDate="eventStartDate"
            dateFormat="dd/mm/yy" showIcon fluid :showOnFocus="true"  />
        </div>

This is the relevant part of my style section:

.p-datepicker {
  width: 100%;
  margin-bottom: 1rem;
}

.p-datepicker-input {
  font-size: small;
  color: crimson;
  padding: 2rem;
}

.p-datepicker-fluid .p-datepicker-input {
  font-size: small;
  color: red;
}

.p-datepicker::placeholder {
  font-style: italic;
}

.p-datepicker-time-picker {
  font-style: italic;
}

Cypress check href with a redirect to the github site

I am trying to do a test, check href on my web page with redirect to github page and navigate them back.

I run commands in a cy.origin but Unfortunately, it is not possible to do this within the same domain.

    cy.visit('https:/my-domain.com');

    cy.origin('https://my-domain.com', () => {
    cy.get('a[href*="https://github.com/"]').invoke('removeAttr', 'target').click().should('be.visible');
    cy.go('back');
    })

Can anyone give me some advice on how to fix it?

why my console is always display “document is not defined” or “404”

Please help me!
I tried to ask chatgpt 4o mini ,but it says that the program is not run in browser but in node.js or html is not load js right…
I tried to fix it according to chatgpt but failed.

 'use strict';
    let score = 20;
    let Highscore = 0;
    let secretNumber = Math.trunc(Math.random() * 20) + 1;
    
    document.querySelector('.check').addEventListener('click', function () {
      const guess = Number(document.querySelector('.guess').value);
      if (!guess) {
        document.querySelector('.message').textContent = 'No number!';
      } else if (guess > secretNumber || guess < secretNumber) {
        guess > secretNumber
          ? (document.querySelector('.message').textContent = 'Too big!')
          : (document.querySelector('.message').textContent = 'Too small!');
        score--;
        if (score < 0) {
          score = 0;
          document.querySelector('.message').textContent =
            'Wrong number! You lost the game!';
        }
        document.querySelector('.score').textContent = score;
      } else if (guess === secretNumber) {
        document.querySelector('.number').textContent = secretNumber;
        document.querySelector('.message').textContent =
          'Cool! You guess the right number!';
        Highscore = score;
        document.querySelector('.score').textContent = score;
        document.querySelector('.highscore').textContent = Highscore;
        document.querySelector('body').style.backgroundColor = '#60b347';
      }
    });
    
    document.addEventListener('DOMContentLoaded', function () {
      ducument.querySelector('.again').addEventListener('click', function () {
        score = 20;
        secretNumber = Math.trunc(Math.random() * 20) + 1;
        document.querySelector('.message').textContent = 'starting guessing......';
        document.querySelector('.score').textContent = score;
        document.querySelector('.highscore').textContent = Highscore;
        ducument.querySelector('body').style.backgroundColor = '#222';
        document.querySelector('.number').style.width = '15rem';
        document.querySelector('.guess').value = '';
        document.querySelector('.number').textContent = '?';
      });
    });

NTLM Auth & WithCredentials [closed]

In my project our team uses NTLM auth, and from Frontend we need to pass withCredentials property to each request to Backend.

According to docs: https://learn.microsoft.com/en-us/windows/win32/secauthn/microsoft-ntlm, FE somehow send encrypted data to BE (omitted steps for simplicity).

According to specs: https://xhr.spec.whatwg.org/#the-withcredentials-attribute, by adding withCredentials we include authentication entries into requests.

So, my question is – how can we see encrypted credentials? Do I need to use Wireshark or another application for investigation?

In my opinion, a detailed understanding of how the protocol works will help to avoid security problems, and the documentation only provides theoretical knowledge, but as a developer I want to see the real data that goes to the backend

P.S. I’m trying to compare JWT auth with NTLM, and JWT is more clear for me.

Are ArrayBuffers coming from GPUBuffers Views or separate Copies?

(shorter and modified version of a deleted post, that was unclear and too long.)

In WebGPU, we can create Mappable GPUBuffers that can be written to (with JS data).

Example (pseudocode)

gpuBuffer = device.createBuffer("MAP_WRITE", length);
writableArrayBuffer = gpuBuffer.mapAsync().getMappedRange() // I'm ignoring `await`

new Uint8Array(writableArrayBuffer).set([1,2,3])
gpuBuffer.unmap()
  • While the buffer is in mapped state, it’s non-writable by GPU, but writable by CPU.
  • This is reversed when we unmap (and the ArrayBuffer is detached, according to the link.)

Question

  • Is the ArrayBuffer (AB) in JS at the same memory location as the GPU buffer (and AB would be a sort of View) ? This’d be strange though, since unmap sets the AB to 0 length, but not the GPUBuffer.
  • Or is it a copy of the data that synchronizes with the GPUBuffer ?
  • Or something else?

Related Resources and Definitions

  • ArrayBuffer: representation of data in memory. It can not be written directly, but using array views.

  • Mappable GPUBuffers: ones that are created in a CPU accessible memory. This is regardless of discrete vs integrated GPUs.

  • GPU Buffers Blogpost

  • MDN Map Async

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 ?