JS: Problem while sign > serialize > deserialize > verify using web crypto

As a part of my JS code, using web crypto, I wanted to sign a string, serialize it and later desrialize it and verify it.
For this I created these custom functions createHexTokenFromStrClaim and verifyHexTokenAndGetStrClaim. However my code is not behaving as expected.

Minimal working code:

const keyUsages = ["sign","verify"];
const algo = {
    name: "HMAC",
    hash: {name: "SHA-512"}
};

class Util{
    static text_encoder=new TextEncoder();
    static text_decoder=new TextDecoder();
    static characters  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    static hexEncode(str) {
        let hex = '';
        for (let i = 0; i < str.length; i++) {
            let charCode = str.charCodeAt(i);
            if (charCode < 128) {
            hex += charCode.toString(16).padStart(2, '0');
            } else if (charCode < 2048) {
            hex += ((charCode >> 6) | 0xC0).toString(16).padStart(2, '0');
            hex += ((charCode & 0x3F) | 0x80).toString(16).padStart(2, '0');
            } else {
            hex += ((charCode >> 12) | 0xE0).toString(16).padStart(2, '0');
            hex += (((charCode >> 6) & 0x3F) | 0x80).toString(16).padStart(2, '0');
            hex += ((charCode & 0x3F) | 0x80).toString(16).padStart(2, '0');
            }
        }
        return hex;
    }

    static hexDecode(hex) {
        let str = '';
        for (let i = 0; i < hex.length; i += 2) {
            const byte = parseInt(hex.substr(i, 2), 16);
            str += String.fromCharCode(byte);
        }
        return decodeURIComponent(escape(str)); // Handle UTF-8 encoding
    }
    
    static async createHexTokenFromStrClaim(algo,str_claim,crypto_key){
        const hex_str_claim= Util.hexEncode(str_claim);
        const uint = Util.text_encoder.encode(hex_str_claim);
        const ab = uint.buffer;

        const sign = await crypto.subtle.sign(algo,crypto_key,ab);
        const des = Util.text_decoder.decode(sign);
        console.log(new Uint8Array(sign));
        
        const hex_sign=Util.hexEncode(des);

        return hex_str_claim+"."+hex_sign;
      }
    
    static async verifyHexTokenAndGetStrClaim(algo,hex_token,crypto_key){
        let hex_str_claim,hex_sign;
        [hex_str_claim,hex_sign]=hex_token.split(".");
        
        if(hex_str_claim && hex_sign){
            const uint = Util.text_encoder.encode(hex_str_claim);
            const ab = uint.buffer;

            const des = Util.hexDecode(hex_sign);
            const sign = Util.text_encoder.encode(des);
            console.log(sign);

            const r = await crypto.subtle.verify(algo,crypto_key,sign.buffer,ab);
            if(r){
                return Util.hexDecode(hex_str_claim);
            }
        }

        return;
    }
}

(async()=>{
    const crypto_key = await crypto.subtle.generateKey(algo,true,keyUsages);
    const message = "Hello world こんにちは、元気ですか ईश्वरेण सह एकतां प्राप्तुं एषः महान् दिवसः अस्ति";
    const token  = await Util.createHexTokenFromStrClaim(algo,message,crypto_key);
    console.log(token);

    const claim = await Util.verifyHexTokenAndGetStrClaim(algo,token,crypto_key);
    console.log(claim);
})();

Hex Enconder is used as encoding like base64 introduces special characters , which causes issues with other part of the code.

Problem:
Verification seems to be failing. Specially inverifyHexTokenAndGetStrClaim the sign is comming completely different after econding it using const sign = Util.text_encoder.encode(des);

Can’t figure out what I am doing wrong.
Have checked most of the resources about encoding and decoding.
Have checked most of the resource for signing and verifying.

Incrementing using prefix and postfix

Can someone explain why the alert still shows 5 under postfix? I understand prefix identifies the last iteration to be falsy, but with postfix, it will still return i as 5.

// Prefix Code:
let i = 0;
while (++i < 5) {
    alert(i);
}
// Postfix code:
let i = 0;
while (i++ < 5) {
    alert(i);
}

There are different outputs. With prefix, the output is 1, 2, 3, 4

With postfix, the output is 1, 2, 3, 4, 5

I’m unable to understand why the postfix output will return 5.

How can i ignore and aiortc offer?

I don’t know what response i may make in an aiortc offering from browser when i want to ignore it.

async def offer(self,request):  
        params = await request.json()
        offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
        if self.reject:#self.reject is True or False defined somewhere above in the code
            #reject offer
            ...
            ...
            ...
            return ????
        else:
            pc = RTCPeerConnection()
            ...
            ...
            ...
            return web.Response(content_type="application/json",text=json.dumps({"sdp": self.pc.localDescription.sdp, "type": self.pc.localDescription.type}))

Edit:

If i return an empty sdp for example:

return web.Response(content_type="application/json",text=json.dumps({"sdp": "", "type": ""}))

then where in a javascript can i handle this:

function negotiate() {
    return pc.createOffer({offerToReceiveAudio:true}).then(function(offer) {
        return pc.setLocalDescription(offer);
    }).then(function() {
        // wait for ICE gathering to complete
        return new Promise(function(resolve) {
            console.log(pc.iceGatheringState);
            if (pc.iceGatheringState === 'complete') {
                resolve();
            } else {
                function checkState() {
                    console.log(pc.iceGatheringState);
                    if (pc.iceGatheringState === 'complete') {
                        pc.removeEventListener('icegatheringstatechange', checkState);
                        resolve();
                    }
                }
                pc.addEventListener('icegatheringstatechange', checkState);

            }
        });
    }).then(function() {
        var offer = pc.localDescription;
        
        return fetch('/offer', {
            body: JSON.stringify({
                sdp: offer.sdp,
                type: offer.type,
                "name":name,
                "surname":surname
            }),
            headers: {
                'Content-Type': 'application/json'
            },
            method: 'POST'
        });
    }).then(function(response) {
        return response.json();
    }).then(function(answer) {
        return pc.setRemoteDescription(answer);
    }).catch(function(e) {
        alert(e);
        console.log(e);
    });
    
}

Ant Design: Issue with ‘primary’ Button Background Color Not Reflecting Specified Primary Color

I have implemented the following code to configure the colors of my buttons using Ant Design (antd). Although I’ve set colors.primaryColor as the colorPrimary for buttons of type ‘primary’, they consistently appear with a black background.

Despite trying various approaches, I can’t seem to make Ant Design utilize the specified blue primary color for these buttons. What additional steps or adjustments can I make to ensure that the ‘primary’ buttons reflect the intended blue color as defined in colors.primaryColor within the Ant Design theme configuration?

<ConfigProvider
  theme={{
    token: {
      colorPrimary: colors.primaryColor,
      fontFamily: fonts.appFont,
      colorBgContainer: colors.background
    },
    components: {
      Button: {
        defaultBg: colors.defaultBtnBg,
        colorBgContainerDisabled: colors.disabledBtnBg,
        textHoverBg: colors.textBtnHoverBg,
        colorText: colors.primaryColor,
        defaultBorderColor: colors.primaryColor,
        linkHoverBg: colors.linkBtnHover,
        colorBorder: colors.primaryColor,
        borderColorDisabled: 'transparent',
        colorPrimaryBorder: colors.primaryColorDark,
        colorPrimaryBg: colors.primaryColor
      },
      Modal: {
        colorBgMask: colors.modalBgColorMask,
        borderRadius: 100
      }
    }
  }}
>

How to stop Page Refrsh on javascript post

I am creating a Flask application using html, css, flask and vanilla javascript as well as ajax.
I have 0 experience using Javascript and all the code I have written is from around the internet trying to piece together things.
I am creating a contact form where after the contact form is subitted I want the main contact form to dissapear and display a message:
The code itself works like it sends and email creates a new commit to the database but the whole page now does not refresh at all and wont display the 2nd div. shown bellow. The issues I am having is this. If I use instead of a the form requirments work but it does the refresh but if i use a button the form requirments dont work and but it does not refresh the page.
I am not so good at posting questions here on stack so if you have questions ask
example:

<form>
<div>
    <h2> main form </h2>
    <button type = "submit" onclick="saveContactForm();return false">Submit</button>
</div>
<form>
<div>
<h2> show after form submit>
</div>

My js is

function saveContactForm() {
    var formData = {
        name: $("input[name='name']").val(),
        email: $("input[name='email']").val(),
        subject: $("select[name='subject']").val(),
        message: $("textarea[name='message']").val(),
    };
    $.ajax({
        url:  baseUrl,
        type: "POST",
        contentType : "application/json",
        data: JSON.stringify(formData),
        success: function (response) {
             autoReply(formData.email,formData.subject,formData.message)
                
           

        },
        error: function (error) {
            alert('Email failed to send:', error);
        },
    });

}
function autoReply(email,subject,message) {
    let parms = {
        email: email,
        subject: subject,
        message: message 
    };
    service_id = secret;
    template_id = secret;
    public_key = secret;
    
    emailjs.send(service_id, template_id, parms, public_key).then(function(response) {
        document.querySelector(".container").style.display="none";
        document.querySelector(".back").style.display="flex";
    }, 
    function(error) {
        console.error('Email failed to send:', error);
    });
}

I am trying to have my submit button not refresh the page

Why does border radius affect svg mask in CSS?

I have one div with 200px size and a svg rectangular mask with 200px size

  • the div in background is just to see how much of div is being masked ornot

when I apply that rectangle as a mask its behavior changes with the border-radius

case 1 – border radius causes mask to shrink

div {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: magenta;
}

#ref {
  background: green;
  mask: url('#mask');
  border-radius: 60px;
}
<svg width=0 height=0>
  <defs>
    <mask id="mask">
      <rect id="oneRect" fill="#fff" x=0 y=0 width=200 height=200 />

    </mask>
  </defs>
</svg>
  
  <div></div>
  <div id=ref></div>

case 2 with no border-radius, mask shows the full square

div {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: magenta;
}

#ref {
  background: green;
  mask: url('#mask')
}
<svg width=0 height=0>
  <defs>
    <mask id="mask">
      <rect id="oneRect" fill="#fff" x=0 y=0 width=200 height=200 />

    </mask>
  </defs>
</svg>
  
  <div></div>
  <div id=ref></div>

How to move a react native hook call to a hook?

This is what I simply have in my file:

  const isInProgress = progress?.status === 'IN_PROGRESS' ?? false;
  useEffect(() => {
    const interval = setInterval(() => {
      if (isInProgress) {
        return setTime(Date.now());
      } else {
        return null;
      }
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  }, [isInProgress]);

and now I would like to move it to another hook to utils file like this:

export const useRefreshProgress = (isInProgress: boolean) => {
  const [_, setTime] = useState(Date.now());
  const refreshProgress = useEffect(() => {
    const interval = setInterval(() => {
      if (isInProgress) {
        return setTime(Date.now());
      } else {
        return null;
      }
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  }, [isInProgress]);
  return { refreshProgress };
};

and trying to use it like this:

  const { refreshProgress } = useRefreshProgress(isInProgress);
  refreshProgress(); // This expression is not callable. Type 'void' has no call signatures.

I just started learning react native and cannot solve it here;) Thank you for your help;)

Response body is not available to scripts (Reason: CORS Missing Allow Origin) in Laravel and Vue Js App

developing Laravel 10 + Vue Js 3 application both projects files are separately. I have following api.php login route as well

Route::post('/login', [LoginController::class, 'submit']);

and using following Login in vue.js

const handleLogin = () => {
    axios.post('http://localhost/api/login', getFormattedCredentials())
        .then((response) => {
            console.log(response.data)
            waitingOnVerification.value = true
        })
        .catch((error) => {
            console.error(error)
            alert(error.response.data.message)
        })
}

but when I try to use log in vue front end it is inspect console encounted following error msg as response

OPTIONS http://localhost/api/login

Response body is not available to scripts (Reason: CORS Missing Allow Origin)

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/api/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.

how to fix this problem?

Getting error: “o.map is not a function” when using google maps distance matrix api in Node.js

I’m using the Google Maps API Node Client and calling the distancematrix function, but I’m getting an error that says o.map is not a function.

const {Client} = require("@googlemaps/google-maps-services-js")
const client = new Client

client.distancematrix({
    params: {
        origins: '40,40',
        destinations: '40,41',
        key: process.env.GOOGLE_MAPS_API_KEY
    }
})
.then((r) => {
    console.log(r.data.rows)
})
.catch((e) => {
    console.log(e)
})

I tried looking at the Google Maps services code. I found o.map at line 174 at this link.

React sending data to save giving json error

In react app I am sending some data to be saved. Data is collected as an array of an object with three elements. Names are corresponding with the server but still having error of json parse error.

fetch("http://localhost:57030/api/answers", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        QuestId:answers.QuestId, Ans:answers.Ans,correct:answers.correct
      }),
    })
      .then(res => res.json())
      .then(res => {
          console.log(res);
        },
        (error) => {
          alert("Failed" + error);
        }
      ); 

the json it produce is

[{"QuestId":1100,"Ans":"Test Test","correct":true},{"QuestId":1100,"Ans":"dddd","correct":false},{"QuestId":1100,"Ans":"gggg","correct":false}]

I want array index danamic because my categories tags and platforms are stored in an array .I don’t want to run loop for every index like [0].[1] [closed]

I am using Angular with node API my API accept data in this format

 "id": 7,
    "name": "Dom Game",
    "shortDescription": "This is Dom Game",
    "description": "<p>Dom is Best GAme</p>",
"categories": [
      {
        "id": 1,
        "name": "Action",
        "description": "Games with action elements"
      },
      {
        "id": 2,
        "name": "Wild",
        "description": "sacsacscs"
      }
    ],
    "platforms": [
      {
        "id": 1,
        "name": "IOS",
        "description": "This is. IOS",
        "games_platforms": {
          "createdAt": "2024-01-12T06:41:56.382Z",
          "updatedAt": "2024-01-12T06:41:56.382Z",
          "GameId": 7,
          "PlatformId": 1
        }
      },
      {
        "id": 2,
        "name": "Window",
        "description": "daddad",
        "games_platforms": {
          "createdAt": "2024-01-12T06:41:56.382Z",
          "updatedAt": "2024-01-12T06:41:56.382Z",
          "GameId": 7,
          "PlatformId": 2
        }
      }
    ],
    "tags": [
      {
        "id": 1,
        "name": "WEB 3",
        "description": "This is FPS",
        "games_tags": {
          "createdAt": "2024-01-12T06:41:56.387Z",
          "updatedAt": "2024-01-12T06:41:56.387Z",
          "GameId": 7,
          "TagsId": 1
        }
      },
      {
        "id": 2,
        "name": "web2",
        "description": "dd",
        "games_tags": {
          "createdAt": "2024-01-12T06:41:56.387Z",
          "updatedAt": "2024-01-12T06:41:56.387Z",
          "GameId": 7,
          "TagsId": 2
        }
      }

in Angular I call this data in this format.

<table>
  <tbody>
    <tr *ngFor="let data of tableData">
      <td> {{data.id}} </td>
      <td class="whitespace-nowrap "> <img class="w-20 h-20 rounded-full overflow-hidden object-cover ml-4" src= {{data.featuredImage}} alt="" >
      </td>
      <td> {{data.name}} </td>
      <td> {{data.categories[0].name}} </td>
      <td> {{data.platforms[0].name}} </td>
      <td> {{data.tags[0].name}} </td>
    </tr>
  </tbody>
</table>

I want to write a dynamic value instead of [0]

sendMessage from background js to content js doesn’t working but content js to background js works

content.js

chrome.runtime.onMessage.addListener(
    (request,sender,sendResponse) =>{
        console.log("Message is Received");
        console.log(request,sender,sendResponse);
        return true
    }
)
console.log("hello")

background.js

(async () => {
    const [tab] = await chrome.tabs.query({ url :"https://www.google.com/*"});
   console.log(tab)
    const response = await chrome.tabs.sendMessage(tab.id, {greeting: "hello"});
    // do something with response here, not outside the function
   
  })();

background.js:23 Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

error when running service worker.

when I tried to send message from content script to background js it works but not vice versa

I expect to receive message from background js to content js

Jest seems not to be rendering the SVG (but it works in the app)

I cannot figure this out – I keep getting the following error:

[{
    "resource": "/Users/daaronch/code/bacalhau/webui/tests/images/jobsIcon.test.tsx",
    "owner": "Jest (bacalhau)",
    "severity": 8,
    "message": "renders JobsIconn-----nError: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.nnCheck the render method of `AppTest`.",
    "source": "Jest",
    "startLineNumber": 7,
    "startColumn": 1,
    "endLineNumber": 7,
    "endColumn": 22
}]

Here’s the MVP reproducible code:

import { render } from "@testing-library/react"
import JobsIcon from "../../src/images/jobs-icon.svg"

export const AppTest = () => <JobsIcon />

test("renders JobsIcon", () => {
  render(<AppTest />)
})

(you need to have a real SVG in that directory)

Here’s my package.json:

{
  "name": "webui",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
    "@babel/plugin-transform-class-properties": "^7.23.3",
    "@babel/plugin-transform-nullish-coalescing-operator": "^7.23.4",
    "@babel/plugin-transform-numeric-separator": "^7.23.4",
    "@babel/plugin-transform-optional-chaining": "^7.23.4",
    "@babel/plugin-transform-private-property-in-object": "^7.23.4",
    "@faker-js/faker": "^8.3.1",
    "@fontsource/open-sans": "^5.0.17",
    "@jest/globals": "^29.7.0",
    "@jridgewell/sourcemap-codec": "^1.4.15",
    "@rollup/plugin-terser": "^0.4.4",
    "@testing-library/jest-dom": "^6.2.0",
    "@testing-library/react": "^14.1.2",
    "@types/node": "^20.10.5",
    "@types/react": "^18.2.45",
    "@types/react-dom": "^18.2.18",
    "axios": "^1.6.2",
    "moment": "^2.29.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-moment": "^1.1.3",
    "react-router-dom": "^6.21.1",
    "react-script": "^2.0.5",
    "react-scripts": "^5.0.1",
    "sass": "^1.69.5",
    "uuid": "^9.0.1",
    "web-vitals": "^2.1.4",
    "wesbos": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "build-bacalhau": "cd .. && make build && cd -",
    "start-bacalhau": "cd .. && ./bin/$(go env GOOS)/$(go env GOARCH)/bacalhau serve --web-ui --web-ui-port 3000 && cd -",
    "test": "NODE_ENV=test cross-env jest tests/",
    "eject": "react-scripts eject",
    "lint": "npx eslint .",
    "lint:fix": "npx eslint . --fix",
    "format": "prettier --write "src/**/*.{js,jsx,ts,tsx}", "tests/**/*.{js,jsx,ts,tsx}""
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.23.7",
    "@babel/preset-env": "^7.23.8",
    "@babel/preset-typescript": "^7.23.3",
    "@testing-library/dom": "^9.3.4",
    "@testing-library/user-event": "^14.5.1",
    "@types/jest": "^29.5.11",
    "@types/uuid": "^9.0.7",
    "babel-cli": "^6.26.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^29.7.0",
    "babel-plugin-module-resolver": "^5.0.0",
    "cross-env": "^7.0.3",
    "eslint": "^8.56.0",
    "eslint-config-wesbos": "^4.0.1",
    "eslint-plugin-import": "^2.29.1",
    "jest": "^29.7.0",
    "jest-css-modules-transform": "^4.4.2",
    "jest-environment-jsdom": "^29.7.0",
    "prettier": "^3.1.1",
    "ts-jest": "^29.1.1",
    "typescript": "^4.9.5",
    "wesbos": "^1.0.1"
  }
}

I’m not sure what I’m doing wrong – this is the minimum possible that I’ve seen elsewhere. To be clear, this renders correctly in the app! It’s JUST in the test framework.