nuxt 3 + cloudfare D1 problems with env.d.ts file

I’m using nuxt 3 with cloudfare D1, but I have encountered some problems.

It seems that it cannot read env.d.ts file I have created.
I’m getting this error:

500 Cannot read properties of undefined (reading ‘env’)

I used this repo:
https://github.com/tlebeitsuk/nuxt-cloudflare-lucia

My configured env.d.ts file

import { CfProperties, Request, ExecutionContext, KVNamespace, D1Database } from '@cloudflare/workers-types';

declare module 'h3' {
    interface H3EventContext {
        cf: CfProperties,
        cloudflare: {
          request: Request,
          env: {
            MY_KV: KVNamespace,
            DB: D1Database,
          }
          context: ExecutionContext,
        };
    }
}

And here is middleware->auth.ts

import { verifyRequestOrigin } from "lucia"
import { initializeLucia } from "../utils/auth"
import type { User, Session } from "lucia"

let lucia: ReturnType<typeof initializeLucia>

export default defineEventHandler(async (event) => {
  // CSRF protection
  if (!isMethod(event, "GET")) {
    const originHeader = getHeader(event, "Origin") ?? null
    const hostHeader = getHeader(event, "Host") ?? null
    if (
      !originHeader ||
      !hostHeader ||
      !verifyRequestOrigin(originHeader, [hostHeader])
    ) {
      return sendNoContent(event, 403)
    }
  }



  const { DB } = event.context.cloudflare.env

  if (!lucia) {
    lucia = initializeLucia(DB)
  }

  event.context.lucia = lucia


  const sessionId = getCookie(event, lucia.sessionCookieName) ?? null
  if (!sessionId) {
    event.context.session = null
    event.context.user = null
    return
  }

  const { session, user } = await lucia.validateSession(sessionId)
  if (session && session.fresh) {
    appendResponseHeader(
      event,
      "Set-Cookie",
      lucia.createSessionCookie(session.id).serialize()
    )
  }
  if (!session) {
    appendResponseHeader(
      event,
      "Set-Cookie",
      lucia.createBlankSessionCookie().serialize()
    )
  }

  event.context.session = session
  event.context.user = user
})

declare module "h3" {
  interface H3EventContext {
    user: User | null
    session: Session | null
    lucia: ReturnType<typeof initializeLucia>
  }
}

Specifically this part const { DB } = event.context.cloudflare.env is responsible

Server side api can’t pass cookies in NextJS app router

In my nextjs app, I am trying to fetch data by using async await mechanism like this

export const getHomeData = async (tokenCalled4PublicApis: string) => {
    try {
        // const all = getCookie('XSRF-TOKEN', { cookies });
        // console.log('all cookies', all);
        const data = await fetch(
            `${process.env.NEXT_PUBLIC_BASE_URL}/${API_ENDPOINTS.HOME}`,
            {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${tokenCalled4PublicApis}`,
                    Accept: 'application/json',
                    // abc: all,
                    'Cache-Control':
                        'public, max-age=60, stale-while-revalidate=60'
                },
                credentials: 'include'
            }
        );
        const result = await data.json();
        return result;
    } catch (error) {
        console.error('Error fetching platform token:', error);
        throw error;
    }
};

Unfortunately not getting data, as in this way i won’t be able to pass cookies set by API. How to pass browser cookies in server-side fetch functions?

Redis Not Adding Session into Cookie, but session being added when viewing via redis-cli

I have setup a spring boot backend with a react frontend. I want to use sessions, and have chosen Redis to do this.
The issue is that my chrome dev tools shows that there are no cookies being added, but in my redis-cli it shows that there are cookies. The issue no arises cause I want to send information using axios with withCredentials: true, but nothing will show up since there are no cookies in Chrome.

I won’t include the import statements as they may clutter the page.

Main

@SpringBootApplication
@EnableRedisHttpSession
public class LetstalkstartApplication {

    public static void main(String[] args) {
        SpringApplication.run(LetstalkstartApplication.class, args);
    }

}

Security Filter Chain

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final UserDetailsServiceImpl userDetailsServiceImpl;

    private final CustomLogoutHandler logoutHandler;

    private final UserDetailsService userDetailsService;
    public SecurityConfig(UserDetailsServiceImpl userDetailsServiceImpl,

                          CustomLogoutHandler logoutHandler, UserDetailsService userDetailsService) {
        this.userDetailsServiceImpl = userDetailsServiceImpl;
        this.logoutHandler = logoutHandler;
        this.userDetailsService = userDetailsService;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return
                http
                        .csrf(AbstractHttpConfigurer::disable)
                        .authorizeHttpRequests(
                                req -> req.requestMatchers("/login/**", "/register/**")
                                        .permitAll()
                                        .requestMatchers("/admin_only").hasAnyAuthority("ADMIN")
                                        .requestMatchers("/getinfo").authenticated()
                                        .anyRequest().authenticated()
                        ).userDetailsService(userDetailsServiceImpl)
                        .logout(l -> l.logoutUrl("/logout")
                                .addLogoutHandler(logoutHandler)
                                .logoutSuccessHandler(
                                        (request, response, authentication) -> SecurityContextHolder.clearContext()
                                ))
                        .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

}

Endpoints:


    @PostMapping("/register")
    public ResponseEntity<AuthenticationResponse> register(
            @RequestBody User request
    ) {
        return ResponseEntity.ok(authenticationService.register(request));
    }

    @PostMapping("/login")
    public ResponseEntity<AuthenticationResponse> login(
            HttpSession session,
            @RequestBody User request,
            HttpServletResponse httpResp
    ) {


        AuthenticationResponse response = authenticationService.authenticate(request);
        if (response != null && response.isSuccess()) { // Check if authentication was successful
            // Store user information in the session
            Cookie sessionCookie = new Cookie("SESSION_ID", session.getId());
            sessionCookie.setHttpOnly(true); // Make it HTTP-only
            sessionCookie.setSecure(false);   // Make it secure
            sessionCookie.setPath("/");      // Set the path for the cookie

            // Add the cookie to the response
            httpResp.addCookie(sessionCookie);
            UserDetails user = userDetailsService.loadUserByUsername(request.getUsername());
//            session.setUsername(user.getUsername());
        }

        return ResponseEntity.ok(response);
    }

    @GetMapping("/getinfo")
    public ResponseEntity<AuthenticationResponse> getUserInfo(HttpServletRequest request) {
        AuthenticationResponse authenticationResponse = new AuthenticationResponse();
        if (request != null) {
            authenticationResponse.setSuccess(true);
            authenticationResponse.setMessage("Success!");

            Cookie[] cookies = request.getCookies();

            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    System.out.println("Cookie Name: " + cookie.getName() + ", Cookie Value: " + cookie.getValue());
                }
            }

            HttpSession session = request.getSession(false);
            if (session != null) {
                System.out.println("Session ID: " + session.getId());
                System.out.println("Session Attributes: ");
                session.getAttributeNames().asIterator().forEachRemaining(name ->
                        System.out.println(name + ": " + session.getAttribute(name))
                );
            } else {
                System.out.println("No active session found");
            }

        } else {
            authenticationResponse.setSuccess(false);
            authenticationResponse.setMessage("Failed to retrieve user information");
        }

        return ResponseEntity.ok(authenticationResponse);
    }

I’ve been using the /getinfo endpoint to test if the cookies are actually working, it’s not meant to serve any greater function within the app.

Here’s my auth service:

public class AuthenticationService {

    private final UserRepository repository;
    private final PasswordEncoder passwordEncoder;

    private final AuthenticationManager authenticationManager;

    private final UserDetailsService userDetailsService;

    public AuthenticationService(UserRepository repository, PasswordEncoder passwordEncoder, JwtService jwtService, AuthenticationManager authenticationManager, TokenRepository tokenRepository, UserDetailsService userDetailsService) {
        this.repository = repository;
        this.passwordEncoder = passwordEncoder;

        this.authenticationManager = authenticationManager;

        this.userDetailsService = userDetailsService;
    }

    public AuthenticationResponse register(User request) {
        User user = new User();
        user.setFirstName(request.getFirstName());
        user.setLastName(request.getLastName());
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setRole(request.getRole());

        user = repository.save(user);

        AuthenticationResponse response = new AuthenticationResponse();

        response.setMessage("Registration Successful");
        response.setSuccess(true);

        return response;

    }

    public AuthenticationResponse authenticate(User request) {
        authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        request.getUsername(), request.getPassword()
                )
        );
        System.out.println(" in authentication ");

        UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());
        if (userDetails != null && passwordEncoder.matches(request.getPassword(), userDetails.getPassword())) {
            AuthenticationResponse authenticationResponse = new AuthenticationResponse();
            authenticationResponse.setSuccess(true);
            authenticationResponse.setMessage("Authentication successful");
            return authenticationResponse;
        }
        AuthenticationResponse authenticationResponse = new AuthenticationResponse();
        authenticationResponse.setSuccess(false);
        authenticationResponse.setMessage("Authentication failed");
        return authenticationResponse;
    }


}

I tried to log in as an example and redis showed after running redis-cli

127.0.0.1:6379> keys *
1) "spring:session:sessions:84c2f69f-f969-4427-b74b-e6e783c6053a"

However, in chrome the cookies page is empty completely. I followed a youtube tutorial and when they log in with the premade page given via spring boot it adds it to the cookies. I’m confused as to what the difference could be.

Login page for frontend in react:

class AuthService {
    login(username, password) {
        return axios.post(API_URL + "/login", 
        {
            username: username, 
            password: password
        },  
        {
            headers: {
                'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        },
       
    
    )
        .then(response => {
            console.log("response: ", response)
            if (response.status == 200) {
                console.log("Logged in")
            } else {
                console.log("Couldn't log in")
            }
            return response.data;
        });
    }

// get info call
  const getUserInfo = () => {
    axios.get(API_URL + "/getinfo", {
      withCredentials: true,
    });
  };

Thank you all

I tried following a youtube tutorial which led to the right result, but when I did the same stuff in my own page it didn’t work. I initially thought this may be an issue with my log in page, but if that’s the case why can I still see a session added via the redis-cli command. Just confused why it’s not showing up in chrome at all.

in discord js msg.attachments.first().name,all blank chars are replaced by an underbar, and if the underbar is present at the beginning, it disappears

Sorry my code is dirty
and also I’m not a native english speaker

~

As the title goes, all spaces in msg.attachments.first().name are replaced by underbars and disappear if there is an underbar in the first
when a user sends a file with “$fur2mp3” in the chat window, the file must be converted through an external script,
but before that, there is a problem in the process of finding the name of the file
if the name of the file user sends does not contain underbar(‘_’) or space (‘ ‘), everything works fine, but if it does not, it fails to find the file (there are no errors or crashes btw)

This is a list of the file names and their values that I tried

_kirb space.fur –> kirb_space.fur

_kirb sp_ace.fur –> kirb_sp_ace.fur

kirb space.fur –> kirb_space.fur


     commands.add('fur2mp3',() => {
    fs.exists('buffer_furrendering.txt',  function(exists){
        if(exists){
            msg.channel.send('Another file is being processed! Please wait!');      
        } else {

            if(msg.attachments.first()){//checks if an attachment is sent
            //arg = msg.attachments.first()
            msg.channel.send('Uploading...');

            download(msg.attachments.first().url, process.cwd());//Function

            msg.channel.send('Uploaded!');
    
    msg.channel.send(msg.attachments.first().name);

            fs.exists(msg.attachments.first().name,  function(exists){
            if(exists){
     
                msg.channel.send('Current Furnace Tracker Version : 0.6.5');
                msg.channel.send('Converting...');
                msg.channel.startTyping();
    exec('fur2wav.bat' + ' ' + msg.attachments.first().name, (error, stdout, stderr) =>{
                msg.channel.stopTyping();
    

                fs.readFile('buffer_fur2wavmsg.txt', 'utf8', (err, gwav) => {
                if (err) {

                    console.error(err);
                    return;
                }

            console.log(gwav);

            msg.channel.send(gwav);
            msg.channel.send({ files: ["furoutput.mp3"] });
     });
       });
        console.log("exixts! : ",exists);
        } else {
            msg.channel.stopTyping();
             msg.channel.send('The file does not exist!');
        }});
           } else { msg.channel.send('Send your file with this command!'); }
           
           
        };
    });
    });

I tried this, ‘msg.attachments.first().name.join(‘ ‘)’ but uhh I think i was wrong

No error, but the bot returns these

Uploading…
Uploaded!
kirb_sp_ace.fur
The file does not exist!

WEBGL_debug_render_info extension appears in getSupportedExtensions but doesn’t work

I have opened the following HTML on multiple browsers (Chrome, Opera, etc.) but in the console it always logs ‘WEBGL_debug_render_info extension doesn’t work’ despite gl.getSupportedExtensions() showing a list where WEBGL_debug_render_info is present. Am I doing something wrong?

<!DOCTYPE html>
<html>
<body>
<script>
    
    var canvas = document.createElement('canvas');
    var gl = canvas.getContext('webgl');
    
    if (!gl) {
        console.log('WebGL not supported');
    } else {
        
        var extensions = gl.getSupportedExtensions();
        console.log('Supported extensions:', extensions);
        
        
        
        var debugInfo = gl.getExtension("WEBGL_debug_render_info");
        if (debugInfo) {
            var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
            var renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
            console.log('Vendor: ' + vendor);
            console.log('Renderer: ' + renderer);
        } else {
            console.log('WEBGL_debug_render_info extension doesnt work');
        }
    }

  
</script>
</body>
</html>

Issue with get ranges using getRangeList

I am trying to get ranges by using getRangeList method but I am getting error Exception: The parameters (String) don't match the method signature for SpreadsheetApp.Sheet.getRangeList

How can we do it?

function consolidateData() {
  // defined all variables
  var sheetNames = [];
  var dataSheet = [];
  var conso = [];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var applyTo = ss.getSheetByName('Sheet10');
  // get all sheets
  var allsheets = ss.getSheets();

  for (var s in allsheets) {
    var sheet = allsheets[s];
    sheetNames[s] = sheet.getName();
    dataSheet[s] = ss.getSheetByName(sheetNames[s]);
    // adding all sheet's data to a single variable
    conso = conso.concat(dataSheet[s].getRange("A2:B" + dataSheet[s].getLastRow()).getValues());
    // conso = conso.concat(dataSheet[s].getRangeList(["A2:B","D2:E"] + dataSheet[s].getLastRow()).getValues());

  }
  applyTo.getRange("A2:B" + (conso.length + 1)).setValues(conso);
  // applyTo.getRangeList(["A2:B","D2:E"] + (conso.length + 1)).setValues(conso);
}

Image is not showing in datatable asp.net c#

I am trying to fetch the image from database but it showing no image (alt message) in the place of image.

Here is my image columnname, datatype and DataStoreValue

ColumnName : DesignImage
DataType : Image
DataStoreValue : Binary data [after applying query i.e. select * from abc I get output of image : 0xFFD8FFE000104A46494600010101006000600000FFDB004300080606070605080707070909080A0C1….]

Now, when I applying ajax and fetch image and show in datatable it does’nt show image. Here is my aspx code,

function format(d) {
    // `d` is the original data object for the row
    let greeting = '<dl>';  
    if (d.DesignImage !== null) {
        const imgTag = '<img src="data:image/png;base64," ' + d.DesignImage +' alt = "No Image" style = "width: 50px; height: 50px;" > ';
        greeting += '<dt><u>Image</u> : ' + imgTag + ' </dt>n ';
    }
    greeting += '</dl>';
    return greeting;            
}

$("#btnSubmit").click(function (e) {                
    $.ajax({
        type: "POST",
        url: "FillGridMethod.asmx/StockList",    
        dataType: "json",
        success: function (data) {                    
            var datatableVariable = $('#gv_Datatable').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'pdf', 'print', 'excel'
                ],                        
                "bDestroy": true,
                "paging": true,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                data: data,
                columns: [
                    {
                        className: 'dt-control',
                        orderable: false,
                        data: null,
                        defaultContent: ''
                    },
                    { 'data': 'Product' },                
            });                            
            // Add event listener for opening and closing details
            datatableVariable.on('click', 'td.dt-control', function (e) {
                let tr = e.target.closest('tr');
                let row = datatableVariable.row(tr);

                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                }
                else {
                    // Open this row
                    row.child(format(row.data())).show();
                }
            });                    
        }
    });
});

Here is my asmx code

[WebMethod(enableSession: true)]
public void StockList()
{
    var stock = new List<StockModel>();
    string constr = cn.ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        qryFillGrid = "select TagItem, CAST(STCK.DesignImage AS VARBINARY(MAX)) as DesignImage from tbl_StockRunning STCK " + System.Environment.NewLine;       
        var cmd = new SqlCommand(qryFillGrid, con);
        con.Open();
        var dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            var stockModel = new StockModel
            {
                Product = dr[0].ToString(),
                DesignImage = dr[1].ToString()
            };
            stock.Add(stockModel);
        }
    }
    var js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(stock));
}

Here is my model .cs file

public class StockModel
{
    public string Product { get; set; }
    public string DesignImage { get; set; }
}

Any guess…what’s issue?

how to continue array numbers in javascript whose data is displayed with a php loop

I have a phone number table in the database like this

id_wa id_proyek bagian no_wa
65 112 renev 087665775667
66 112 renev 087665445334
67 112 renev 087665445444

I show it like this

<label for="inlineinput" class="col-md-3 col-form-label">No WA</label>
<?php
    $no=0;
    $cek=mysqli_query($koneksi,"select no_wa from wa_renev where id_proyek='112'");
    while($data = mysqli_fetch_array($cek)){
    $no++
?>
<div class='col-md-9 p-0'>
<input name='no_wa[<?php echo"$no";?>]' value='' type='text' class='form-control input-full' id='inlineinput' placeholder='Masukkan No WA (ex:087712333488)'/>
</div>
<?php
}
?>

And below the code to add another cellphone number with dynamicly

<script language="JavaScript" type="text/JavaScript">
counter = 0;
function action()
{
counterNext = counter + 1;
document.getElementById("input"+counter).innerHTML = "<div class='col-md-9 p-0'><input name='no_wa["+counterNext+"]' value='' type='text' class='form-control input-full' id='inlineinput' placeholder='Masukkan No WA (ex:087712333488)'/></div><div id="input"+counterNext+""></div>";
counter++;
}
</script>

<div id="input0">
</div>
<a href="javascript:action();"><span class="badge badge-primary">Tambah WA</span></a><br/>

How to continue the array from my first code when the cellphone number is added again ?

results display

How can I prevent my cookies being blocked as Third Party Cookies?

I have an authentication workflow as follows:

  1. From the client I send encrypted user and password credentials in x-authorization header in a request to API entpoint example.net/login
  2. the response of this request sends back authorization cookies set with set-cookie in the header.
  3. The cookies are used in a subsequent request to example.net/user, where the endpoint validates the cookies.

Now, with current and upcoming policies regarding Third Party Cookies, the cookies set and forwarded via first response get blocked by modern browsers (it seems) and the endpoint example.net/user returns a 401 status code. It works when the user enables third party cookies in their browser.

Is there still any way of cookie based authorization possible, or any alternative authorization flow at all, without forcing the user to enable cookies in their browsers?

I tried setting the cookies manually in the client via javascript, since the first request also has the cookies as json in its response data. But nothing works so far.

How to proxy fetch requests in chrome extensions?

I see the solution to this nowhere, and yet have the question:
How to proxy fetch requests in chrome extensions?

I have this code:

async makeRequest() {
    const postData = {
      // ..payload
    };

    const jsonData = JSON.stringify(postData);
    const url = "http://127.0.0.1:8000/endpoint/";
    try {
      // HERE I WANT TO USE PROXY!

      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json", 
        },
        body: jsonData,
      });

      return response;

    } catch (error) {
      console.error("Error during fetch:", error);
      return false;
    }
  }

My app is a webscrapping chrome extension, therefore the usage of proxies for my webscrapping purposes is fundamental.

Also saw that we can use the proxies manifest permission, but the problem that I run into using that implementation is that configures the Proxy for the WHOLE COMPUTER, and i only want it for the chrome extension requests.

Any solution?
Thanks!

Ready-Made Restaurant Ordering System with POS, Loyalty Programs, Third Party Delivery Integrations

This will probably get taken down but we are in urgent need and I am freaking out and I don’t know where else to go for a solution.

We urgently need a comprehensive restaurant ordering system, similar to Restoplus, with essential features like restaurant login/signup, customizable menus with item variations, a POS interface, and access to sales data. The system must support both in-store pickup and dine-in notifications via SMS, as well as integrate with delivery services like Uber/DoorDash. Additionally, it should include a robust rewards system for users, allowing them to earn points with purchases and redeem them, similar to major fast-food chains’ loyalty program. Instant receipt printing and order processing capabilities, mirroring the efficiency of modern restaurant system.

We are looking to purchase a ready-made solution immediately, with a strong preference for off-the-shelf systems to meet our critical timeline. We need at least a partial deployment within the next 2 days. If you have an existing solution that fits these requirements, please contact us ASAP. Speed is of the essence in this project.

We are looking for a ready-made solution that can be deployed immediately, with at least partial functionality within the next 2 days. The system must support a centralized website where we can manage client restaurants. We prioritize acquiring an off-the-shelf system due to the critical urgency of this project. Immediate responses are required to meet our timeline.

Look I’ll be honest we have a meeting with a client on Tuesday and we want a solution asap to make him believe in us or else we will loose him to another platform possibly who does all these for a monthly fee. We will also charge a monthly fee from restaurants via Stripe.

If anyone has a similar site we are happy to book a meeting and take a look at it.

I tried Fiverr, freelander and upwork, then though that this site has the most developers working on it also someone might have a similar system already built for us to take a look at.

Thanks,
Sasuke.

How to Extract Digital Signatures from a PDF Using Node.js?

I’m trying to extract information about all the digital signatures in a PDF file using Node.js. I found a way to obtain some data that appears to contain this information, but it seems to be jumbled.

Here is my current code:

const forge = require("node-forge");
const fs = require("fs");
const { Buffer } = require("buffer");


function GetSignaturesByteRange(FileBuffer) {

    const ByteRangeList = [];

    let ByteRangeStart = 0;

    while ((ByteRangeStart = FileBuffer.indexOf("/ByteRange [", ByteRangeStart)) !== -1) {

        const ByteRangeEnd = FileBuffer.indexOf("]", ByteRangeStart);
        const ByteRange = FileBuffer.slice(ByteRangeStart, ByteRangeEnd + 1).toString();

        const ByteRangeString = /(d+) +(d+) +(d+) +(d+)/.exec(ByteRange);
        const ByteRangeArray = ByteRangeString.slice(1, 5).map(Number); // Convert to integers

        // Add the ByteRange to the list
        ByteRangeList.push(ByteRangeArray);

        // Move past the current ByteRange
        ByteRangeStart = ByteRangeEnd + 1;

    }

    return ByteRangeList;
}

function GetSignatureData(FileBuffer, ByteRange) {

    // Extract the specified range from the buffer
    let ByteRangeBuffer = FileBuffer.slice(ByteRange[1] + 1, ByteRange[2] - 1)

    // Remove the zeroes from the end of the buffer
    let EndIndex = ByteRangeBuffer.length;
    while (EndIndex > 0 && ByteRangeBuffer[EndIndex - 1] === 0x30) {
        EndIndex--;
    }

    ByteRangeBuffer = ByteRangeBuffer.slice(0, EndIndex);

    return ByteRangeBuffer.toString("binary");
}

const InputFile = fs.readFileSync("./signed.pdf");
const AllByteRanges = GetSignaturesByteRange(InputFile);

let SignatureBuffer = GetSignatureData(InputFile, AllByteRanges[0]);


console.log(SignatureBuffer);

fs.writeFileSync("Sigature.bin", Buffer.from(SignatureBuffer, "hex"));

The Signature.bin file produced by this code contains some data such as my name and city from when I digitally signed the PDF, but it is surrounded by what seems to be garbage data.

How can I properly extract and clean up the digital signature information from the PDF? Any advice or improvements to my code would be greatly appreciated!

Styling dropdown that is created with react-select

This is my first time using react-select and I have created the dropdown as below (I want this dropdown to be a re-usable component)

//import libraries
import React from 'react';
import Select, { components } from 'react-select';
import classNames from 'classnames';

//import some svg icons using svgr
import Twitter from '@/assets/images/icon-twitter.svg';
import Linkedin from '@/assets/images/icon-linkedin.svg';
import Youtube from '@/assets/images/icon-youtube.svg';


export const PlatformDropdown = (listProps: any) => {
const options = [           
        { label: 'Twitter', value: 'Twitter', icon: <Twitter /> },
        { label: 'Linkedin', value: 'Linkedin', icon: <Linkedin /> },
        { label: 'YouTube', value: 'YouTube', icon: <Youtube /> },
        { label: 'Facebook', value: 'Facebook', icon: <Facebook /> },       
    ];
const { Option } = components;

const IconOption = (props: any) => (
        <Option {...props}>
            <div className="flex items-center gap-2">
                <div>{props.data.icon}</div>
                {props.data.label}
            </div>
        </Option>
    );

const handleChange = (e: any) => {
        listProps.setValue(e.value.toLowerCase());
    };

return (
        <Select
            options={options}
            components={{ Option: IconOption }}
            className="w-40 mx-auto"
            unstyled
            isClearable
            onChange={handleChange}
            value={listProps.value}
            classNames={{
                control: ({ isFocused }) => 'border border-gray-300 rounded-md',
                option: ({ isDisabled, isFocused, isSelected }) =>
                    classNames(
                        isSelected && 'text-purple [&_svg]:fill-purple',                        
                    )
            }}
        />
    );
};

The dropdown is working fine but as you can see in the first pic, the icons show on the list for selection. But the icon is NOT seen on the selected item. Can anyone help me fix this issue so that icon is seen on the selected value as well?

[![List][1]][1]


  [1]: https://i.sstatic.net/Z4P5IV7m.png

Can anyone give me a specific or clear explanation that , when to use QUERY selector and ID selector in JavaScript?

I wanted to fetch the checkboxes from the html part through Id Selector but not getting the desired output. After that I tried through querySelector , then I get my desired output. So this is the confusion that when to use querySelector and ID selector. Please clarify.

const checkBoxElement = document.getElementById('checked');
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');

these are the cases where I switch to querySelector from IdSelector.