In-place modification of large encrypted file

The server-side application I’m working on stores structured data in a single large file that is continuously encrypted using the ChaCha20 stream cipher. I want to modify parts of the file without having to decrypt and re-encrypt the whole thing.

As I know the structure of the underlying data, I could read specific encrypted parts, decrypt and modify them in-place, and afterwards re-encrypt said parts. However, as far as I understand the ChaCha algorithm, this would effectively break the encryption as I would use the same key+counter combination when re-encrypting the modified parts of the file.

My questions are:

  1. Am I correct that this would compromise the ChaCha encryption?
  2. If so, is there an alternative algorithm or approach I could use to achieve what I described?

How can I change images on click in a specfic order, with the final image being randomly selected from a folder?

I am very new to javascript, so help is much appreciated! On my website, I want to have seven photos that cycle on click. So every time the photo is clicked, it is replaced by the next photo in the sequence. Here’s the catch: I want the seventh photo to be randomly selected from a folder.

For context, I’m trying to create a fun feature on my blog where the user clicks an image of a cookie to “eat” it. I’ve had success with writing script for the image of the cookie to change onclick, so that every time the user clicks bite marks appear until the cookie disappears.

What I WANT to happen is for a fortune to appear once the cookie has been “eaten.” I want think fortune to be selected randomly from a folder of images of potential fortunes.

The problem I’m facing is I don’t know how to add a random image to the end of a var images sequence.

Here’s what I have for html and java (I left a spot for where I want the random image in the sequence):

<main>
    <img src="folk/cookie1.png" id="image" onclick="change()">
        <script>
          var imgCount = -1;
          var images = ["folk/cookie1.png", "folk/cookie3.png", "folk/cookie4.png", "folk/cookie5.png", "folk/cookie6.png", "RANDOM IMAGE HERE!"];
          function change() {
            if (imgCount !== images.length - 1)
            imgCount++;
            else 
            imgCount = 0;
            var image = document.getElementById('image');
            image.src = images[imgCount];
          }
        </script>
</main>

Mouseleave animation not showing

So, I’m trying an animation where a globe is filled with Indonesian flag colours in slide-down animation when i hover over a button. The mouseenter animation successfully delivers a slide-down animation. However, the mouseleave doesn’t. It does slide-down when i hover over the enter button, but it doesn’t slide up when i take my mouse off. The colors change instantly and doesn’t deliver a slide-up animation. What should I do?

const button = document.querySelector(“button”);
const globeCircle = document.querySelector(“.globe-circle”);

// On hover, change fill to Indonesian flag
button.addEventListener("mouseenter", () => {
  globeCircle.style.fill = "url(#indo-flag)";
});

// Reset when hover ends
button.addEventListener("mouseleave", () => {
  globeCircle.style.fill  = 'lightBlue'
});

const maskRect = document.getElementById(“mask-rect”);

button.addEventListener("mouseenter", () => {maskRect.style.animation = "slide-down 1s forwards";})

button.addEventListener("mouseleave", () => {maskRect.style.animation = "slide-up 1s forwards"})

Block all outgoing HTTP requests from page (javascript)

I am trying to make a very basic proxy just for learning purposes. The PHP file accesses a URL and displays it. I’m trying to block all outgoing HTTP requests from any links in the page displayed. I tried using a service worker but it does nothing – all requests go through.

proxy.php:

<script type="text/javascript">
function sendm(){
  navigator.serviceWorker.controller.postMessage('test');
}

if ('serviceWorker' in navigator) { 
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('sw.js').then(function(registration) {
      console.log('Service worker registered with scope: ', registration.scope);
    }, function(err) {
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

  
</script>


<!DOCTYPE html>
<html>

<body>

<div class="content">

<?php


    $url = "www.ft.com";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    $response = curl_exec($curl);
    echo $response;

?>
</div>
</body>
</html>

service worker:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    //fetch(event.request)
  );
});

What am I doing wrong? The service worker is registered successfully, but just doesn’t block any requests.

The submit button is disabled until recaptcha is solved. But now the form doesn’t validate until the recaptcha is solved

The submit button is disabled until recaptcha is solved. But now the form doesn’t validate until the recaptcha is solved. How do I set up so that the form validates before the recaptcha is solved but doesn’t submit the form?

HTML

<div class='g-recaptcha' data-sitekey='" . $recaptcha_user . "' data-callback='enableBtn'></div>
<div class="submit"><input type="submit" id="button" value="submit" disabled>></div>

JAVASCRIPT

function enableBtn() {
  var response = grecaptcha.getResponse();
  var $result = $('#myParagraph');
  if(response.length === 0) { 
    $result.text("reCaptcha not verified"); 
  }
  else { 
    $result.text("reCaptcha Verified");
    document.getElementById("g-recaptcha-response").setAttribute('value', response);
     document.getElementById("button1").disabled = false;
  }
}

THIS IS WHAT I TRIED
HTML

<form id="myForm">
  <input type="text" id="input1" onkeyup="checkInputs()">
  <input type="text" id="input2" onkeyup="checkInputs()">
  <input type="text" id="input3" onkeyup="checkInputs()">
  <button type="submit" id="submitBtn" disabled>Submit</button>
</form>

JAVASCRIPT
f

unction checkInputs() {
  const input1 = document.getElementById('input1').value;
  const input2 = document.getElementById('input2').value;
  const input3 = document.getElementById('input3').value;
  const submitBtn = document.getElementById('submitBtn');

  if (input1.trim() !== '' || input2.trim() !== '' || input3.trim() !== '') {
    submitBtn.disabled = false; // Enable the button
  } else {
    submitBtn.disabled = true; // Keep the button disabled
  }
}

// Initial check when the page loads (in case inputs are pre-filled)
document.addEventListener('DOMContentLoaded', checkInputs);

How to use a lightweight PDF reader inside a Chrome Extension without exceeding the 5MB limit? [closed]

I am developing a Chrome Extension that needs to display PDF files.

I’ve tried a few approaches, but I’ve hit two major issues:

Some libraries (e.g., pdf.js builds with workers or WASM) require access to external resources, which are not allowed in the Chrome Extension environment.

Other solutions bundle too many files and easily exceed the 5MB package size limit imposed by the Chrome Web Store.

What I’ve tried:

pdf.js full build → works, but too large (~7–8MB).
pdf.js minimal build → still heavy and requires extra setup.
Some lightweight npm libraries → blocked because of external dependencies (CORS / CSP issues).

My requirements:

The reader should work fully inside the extension (no external requests).
Ideally lightweight, so the packaged extension does not exceed the 5MB limit.
Basic PDF rendering is enough (I don’t need advanced features like annotations or editing).

Question:
Are there any recommended lightweight PDF readers/libraries that work inside a Chrome Extension without exceeding the 5MB limit?
Or is there a way to strip down pdf.js (or another library) to only the minimum features needed (basic rendering)?

JWT Authentication for websockets in Springboot does not pass Principal for stomp commands other than connect

i am working on JWT Authentication for websockets in springboot. In my JWT filter for WS, I found that Principal is getting null while using other stomp commands such as SEND, SUBSCRIBE. My filter looks like this:


@Component
@RequiredArgsConstructor
public class JWTAuthenticationFilterForWS implements ChannelInterceptor {
    private final JwtUtility jwtUtil; // your existing JWT utility
    private final UsersRepository usersRepository;


    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);

        if (StompCommand.CONNECT.equals(accessor.getCommand())) {

            String token = accessor.getFirstNativeHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                String username = jwtUtil.getUsernameFromToken(token);
                // check user exists
                usersRepository.findByUsername(username)
                        .orElseThrow(() -> new RuntimeException("Invalid JWT"));
                // set user for STOMP session
                 accessor.setUser(new StompPrincipal(username));
            } else {
                throw new RuntimeException("No JWT token provided");
            }
        }else {
            // For other STOMP commands like SEND, SUBSCRIBE, retrieve user safely
            StompHeaderAccessor otherAccessor =
                    MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
            if (otherAccessor != null) {
                Principal user = otherAccessor.getUser();
                System.out.println("Handling STOMP command " + accessor.getCommand() + " from user: " + user);
                // Add any authorization logic for SEND, SUBSCRIBE here if needed
            }
        }

        System.out.println("WebSocket connection established with user: " + accessor.getUser());
        return message;
    }
}

Whenever stomp calls this filter for send or subscribe, it goes to else block and print “Handling stomp command send null”. That means if i am handling a method for message mapping in controller, i am not able to fetch a principal-its null.
My web socket config:


@Configuration
@EnableWebSocketMessageBroker
@RequiredArgsConstructor
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    private final JWTAuthenticationFilterForWS JWTAuthenticationFilterForWS;

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(JWTAuthenticationFilterForWS);
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").setAllowedOriginPatterns("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

My JS websocket tester code looks like this:

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat Tester</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/stomp.min.js"></script>
</head>
<body>

<h3>WebSocket Chat</h3>

<label>JWT Token:</label>
<input type="text" id="jwtToken" placeholder="Paste your JWT here" style="width:400px;">
<button onclick="connect()">Connect</button>
<button onclick="disconnect()">Disconnect</button>

<br><br>

<input type="text" id="chatMessage" placeholder="Type a message" style="width:300px;">
<button onclick="sendMessage()">Send</button>

<ul id="messages"></ul>

<script>
    let stompClient = null;

    function connect() {
        const token = document.getElementById("jwtToken").value.trim();
        if (!token) {
            alert("Please enter JWT token");
            return;
        }

        const socket = new SockJS('http://localhost:8080/chat'); // your endpoint
        stompClient = Stomp.over(socket);

        stompClient.connect(
            { Authorization: 'Bearer ' + token },
            function(frame) {
                console.log('Connected: ' + frame);
                alert("Connected!");

                // Subscribe to your chat topic (replace '1' with chatId)
                stompClient.subscribe('/topic/chat', function(messageOutput) {
                    const msg = JSON.parse(messageOutput.body);
                    const li = document.createElement("li");
                    li.innerText = `[${msg.timestamp}] ${msg.sender}: ${msg.content}`;
                    document.getElementById("messages").appendChild(li);
                });
            },
            function(error) {
                console.error('STOMP error: ' + error);
                alert('Error connecting: ' + error);
            }
        );
    }

    function disconnect() {
        if (stompClient !== null) {
            stompClient.disconnect(function() {
                console.log("Disconnected");
                alert("Disconnected!");
            });
            }else {
        alert("Not connected!");
    }
        }


    function sendMessage() {
        const msgInput = document.getElementById("chatMessage").value.trim();
        if (!msgInput) return;

        if (stompClient && stompClient.connected) {
            stompClient.send(
                '/app/message',
                {},
               JSON.stringify({ content: msgInput })
            );
            document.getElementById("chatMessage").value = '';
        } else {
            alert("Not connected!");
        }
    }
</script>

</body>
</html>

Please do help!

I was expecting that after connect command, the session of principal must be stored and used in any other commands, but its not happening

Child shows undefined. for this i want 500 character body for the

I am working on a React project where I need to pass data from a parent component to a child, but the child component keeps showing undefined. Problem: Even though I pass the prop like <Child data={myData} />, it doesn’t render correctly in the child.

Defined myData in state and passed it as a prop. What I expected: The child should receive and render the value, but instead it shows undefined. How can I fix this?

Ping/connection check stops when print window is open – leads to false “Lost connection to server” error

Description

I have implemented a print report feature in Angular.
When the user clicks the Print button, the browser’s print dialog opens (using window.print()).

At the same time, I also have a ping mechanism to check if the connection between Angular (frontend) and .NET (backend) is active. If no ping response is received within 30 seconds, the UI shows an error message:

“Lost connection to server”

The problem is: when the print window is open, all JavaScript execution is paused (including the ping mechanism). If the user leaves the print window open for more than 30 seconds, Angular displays the “Lost connection to server” error even though the connection is fine.

Steps to Reproduce

  1. Implement a ping/heartbeat mechanism in Angular that checks server
    connection every few seconds.
  2. Trigger window.print() from a button click.
  3. Keep the print window open for longer than the ping timeout
    (30 seconds in my case).
  4. Observe that the ping stops during print
    window → after timeout, Angular shows Lost connection to server.

Expected Behavior

The ping/heartbeat mechanism should continue working in the background (or resume seamlessly after print dialog is closed) so that the app does not incorrectly show Lost connection to server.

Actual Behavior

When the print dialog is open, JavaScript execution halts (including setInterval, setTimeout, and HTTP calls).
As a result, the ping never executes, and Angular incorrectly shows a server disconnection error after 30 seconds.

Environment

  1. Angular version: 18

  2. Browser(s): Chrome, Edge, etc.

  3. OS: Windows 11

Question

Is there any Angular-recommended workaround or best practice to handle this scenario where background tasks (like ping/heartbeat) stop working when the print window is open?

Need a reliable way to keep timer running for displaying server date/time in Angular

Description

I have a use case where the backend sends me the date/time.
On the UI side (Angular), I need to display this date/time and keep incrementing it every second, so that the user always sees the current server time.

I implemented this with setInterval(), but when I minimize the browser or switch to another tab, the timer stops updating because of browser throttling. This results in the displayed time lagging or freezing until the tab becomes active again.

Steps to Reproduce

  1. Receive a date string from backend.

  2. Start a timer that increments the date every second and displays it
    in the UI.

    updateDateTime(inputDate: string) {
        setInterval(() => {
            this.incrementDate(inputDate);
        }, 1000);
    }
    
    incrementDate(inputDate: Date) {
        inputDate.setSeconds(inputDate.getSeconds() + 1);
        this.formattedDateTimeSubject.next(this.formatDate(inputDate));
    }
    

3.Minimize the browser or switch to another tab.

4.Observe that the timer stops firing (UI stops updating).

Expected Behavior

The timer should continue updating every second even when the tab is inactive or minimized, so that the displayed time always reflects the correct running server time.

Actual Behavior

Due to browser throttling, the setInterval() callback is delayed or stopped when the tab is not active, and the UI clock freezes.

Environment

Angular version: 18
Browser(s): Chrome, Edge, etc.
Operating System: Windows 11

What is the recommended Angular way (or workaround) to avoid browser throttling issues for such a use case where we need continuous UI updates (like a clock) even if the tab is inactive?

I can’t created repeated events using ICS.js

I am struggling with ics.js (https://github.com/nwcell/ics.js/)

  1. It is ignoring rules for repeat events set up in rrules

  2. It is not allowing me to add another event from another .ics file after I have added a first one. However, if I delete the first one, I can add the second one.

  3. I am unable to add a calendar event using a JavaScript object.

    var myfunc = function(e) {

    var myfunc = function(e) {
        let target = e.currentTarget;
        if (target.tagName != 'X-EVENT') {
          throw "downloadEvent is for use on x-events only";
        }
        let form = target.querySelector("form");
        let fd = new FormData(form);
        //console.log(fd.has('subject'));
        let recur = fd.get("freq") != "none";
        let rRule = recur ? {"freq" : fd.get("freq"), "interval" : fd.get("interval"), "byday" : fd.getAll("byday"), "until" : fd.get('until') } : null;
    
        let cal  = ics();
    //    cal.addEvent(eventData);
        cal.addEvent(fd.get("subject"),fd.get("description"), fd.get("location"),       fd.get("start"), fd.get("end"), rRule);
        cal.download(fd.get("subject"));
    }
    

As you can infer from the code snippet above, I create adding an event as an object but that failed.

How can I fix this code so that the reoccurrence instructions in rRule are obeyed?

Flask python generate a white web page

I’m trying a small start with flaks and web tools, but the html, css does not show in the page, just a blank page, I need an explanation please, I’m using VSCode, this is my code :

Project structure :

FLASKTEST/
│ test.py              
│
├── templates/
│     index.html
└── static/
      style.css
      script.js

test.py file :

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html")  

if __name__ == "__main__":
    app.run(debug=True)

index.html file :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Small Example</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Welcome to Flask</h1>
    <p>This is a small example combining HTML + CSS + JS + Flask</p>
    <button onclick="showMessage()">Click here</button>

    <script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>

style.css file :

body {
    background-color: #396e9d;
    font-family: Arial, sans-serif;
    text-align: center;
    padding-top: 50px;
}
h1 {
    color: darkblue;
}
button {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}

script.js file :

function showMessage() {
    alert("Hello");
}

Should I Avoid Global Variables At All Cost? [closed]

In my project, I am trying to create a chat room. In the chat room, I need to send different kind of data about other sections of my app. I use web sockets to that.

To send same data to every client in the room they are inside of, I need to iterate over like, all of the clients. And if like, I have 1000 clients, it could create lag, so messages or other datas could be laggy. To prevent this, I can actually create a map object and set room name, to that key(room name) name I can use set object as value that is having an instance of client object of web socket itself. So thanks to that global variable map object I saved performance of iterating through all clients to just to send to the clients in the same room.

Code for the loop I am currently using to avoid global variable:

ws.communityName = communityName;

// Send to all clients in the same community
webSocket.clients.forEach((client) => {
      if(client.communityName === communityName) {
            client.send(stringifiedActiveUsers);

            // Send only to owner of the community within user's community 
            if(client.userid === communityOwnerId) {
                  client.send(suspendedUsersData);
            }
      }
});

That is my logic on how to send data to all clients in the same room. But I am using global variable, which I shouldnt because it could create memory leak problems etc…

Do you think there is a more efficient solution to this problem? Should I use global variable to save performance?

Unit testing AssertionError: expected false to be true after js-dom update

For a security compliance reason I had to update the js-dom libray to version 27.0.0 from 23.0.0 after that few unit tests failed.

This is a Vue.js project and use these libries for testing

import { expect } from 'chai';
import { mount } from '@vue/test-utils';

This is the unit test getting failed. After updating.

console.log(wrapper.find('.myclass')); // Output [Object: null prototype] {}
expect(wrapper.find('.myclass').exists()).to.be.false;

Error message I am getting here is

AssertionError: expected false to be true

Even though the console.log prints the same output, I am wondering why this is failing. What am I missing here?