Skip to content

Commit

Permalink
Fixed bunker method handling
Browse files Browse the repository at this point in the history
  • Loading branch information
calvadev committed Jan 13, 2025
1 parent 1c50d9c commit d31eeae
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 50 deletions.
6 changes: 5 additions & 1 deletion components/display-product-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,11 @@ export default function DisplayProductModal({
};

const beginDeleteListingProcess = () => {
if (signInMethod === "extension") {
if (
signInMethod === "extension" ||
signInMethod === "amber" ||
signInMethod === "bunker"
) {
finalizeDeleteListingProcess();
} else if (signInMethod === "nsec") {
setRequestPassphrase(true);
Expand Down
1 change: 1 addition & 0 deletions components/messages/messages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ const Messages = ({ isPayment }: { isPayment: boolean }) => {
}
}
let sealEvent = JSON.parse(sealEventString);
sealEvent = JSON.parse(sealEvent);
if (sealEvent.kind === 13) {
const messageEventDecryptId = crypto.randomUUID();
await sendBunkerRequest(
Expand Down
9 changes: 5 additions & 4 deletions components/sign-in/SignInModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ export default function SignInModal({
clientPubkey: clientPubkey,
clientPrivkey: clientPrivkey,
bunkerRemotePubkey: remotePubkey,
bunkerRelays: JSON.stringify(relays),
bunkerRelays: relays,
bunkerSecret: secret,
});
} else {
Expand All @@ -190,7 +190,7 @@ export default function SignInModal({
clientPubkey: clientPubkey,
clientPrivkey: clientPrivkey,
bunkerRemotePubkey: remotePubkey,
bunkerRelays: JSON.stringify(relays),
bunkerRelays: relays,
bunkerSecret: secret,
});
}
Expand Down Expand Up @@ -360,10 +360,11 @@ export default function SignInModal({
backdrop="blur"
isOpen={isOpen}
onClose={() => {
onClose();
setShowBunkerSignIn(false);
setShowNsecSignIn(false);
setPrivateKey("");
setPassphrase("");
onClose();
}}
// className="bg-light-fg dark:bg-dark-fg text-black dark:text-white"
classNames={{
Expand Down Expand Up @@ -422,7 +423,7 @@ export default function SignInModal({
<div className="">
<Button
onClick={() => setShowBunkerSignIn(true)}
className={`mt-2 w-full ${
className={`${SHOPSTRBUTTONCLASSNAMES} w-full ${
showBunkerSignIn ? "hidden" : ""
}`}
>
Expand Down
46 changes: 30 additions & 16 deletions components/utility/nostr-helper-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { ProductFormValues } from "@/pages/api/nostr/post-event";
import { DeleteEvent } from "@/pages/api/nostr/crud-service";
import { gunzipSync } from "zlib";
import { Buffer } from "buffer";
import crypto from "crypto";
import { DateTime } from "luxon";

function containsRelay(relays: string[], relay: string): boolean {
Expand Down Expand Up @@ -74,6 +73,7 @@ function generateEventId(event: EncryptedMessageEvent) {
});

// Step 3: Create SHA256 hash of the serialized string
const crypto = require("crypto");
const hash = crypto.createHash("sha256");
hash.update(serialized);
return hash.digest("hex");
Expand Down Expand Up @@ -117,7 +117,7 @@ export function parseBunkerToken(token: string): BunkerTokenParams | null {
export async function sendBunkerRequest(
method: string,
requestIdString: string,
event?: DraftNostrEvent,
event?: any,
content?: string,
thirdPartyPubkey?: string,
clientPubkey?: string,
Expand All @@ -131,9 +131,7 @@ export async function sendBunkerRequest(
const finalClientPrivkey = clientPrivkey || storage.clientPrivkey;
const finalBunkerRemotePubkey =
bunkerRemotePubkey || storage.bunkerRemotePubkey;
const finalBunkerRelays =
bunkerRelays ||
(storage.bunkerRelays ? JSON.parse(storage.bunkerRelays) : undefined);
const finalBunkerRelays = bunkerRelays || storage.bunkerRelays;
const finalBunkerSecret = bunkerSecret || storage.bunkerSecret;

if (
Expand Down Expand Up @@ -225,9 +223,7 @@ export async function awaitBunkerResponse(
const finalClientPrivkey = clientPrivkey || storage.clientPrivkey;
const finalBunkerRemotePubkey =
bunkerRemotePubkey || storage.bunkerRemotePubkey;
const finalBunkerRelays =
bunkerRelays ||
(storage.bunkerRelays ? JSON.parse(storage.bunkerRelays) : undefined);
const finalBunkerRelays = bunkerRelays || storage.bunkerRelays;

if (
!finalClientPubkey ||
Expand Down Expand Up @@ -457,22 +453,25 @@ export async function PostListing(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
const signRecEventId = crypto.randomUUID();
await sendBunkerRequest("sign_event", signRecEventId, event);
await sendBunkerRequest("sign_event", signRecEventId, recEvent);
while (!signedRecEvent) {
signedRecEvent = await awaitBunkerResponse(signRecEventId);
if (!signedRecEvent) {
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedRecEvent = JSON.parse(signedRecEvent);
const signHandlerEventId = crypto.randomUUID();
await sendBunkerRequest("sign_event", signHandlerEventId, event);
await sendBunkerRequest("sign_event", signHandlerEventId, handlerEvent);
while (!signedHandlerEvent) {
signedHandlerEvent = await awaitBunkerResponse(signHandlerEventId);
if (!signedHandlerEvent) {
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedHandlerEvent = JSON.parse(signedHandlerEvent);
} else if (signInMethod === "amber") {
try {
signedEvent = await amberSignEvent(event);
Expand Down Expand Up @@ -662,6 +661,7 @@ export async function constructMessageSeal(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
signedEvent = await amberSignEvent(sealEvent);
} else if (signInMethod === "nsec") {
Expand Down Expand Up @@ -741,6 +741,7 @@ export async function publishReviewEvent(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
signedEvent = await amberSignEvent(reviewEvent);
} else if (signInMethod === "nsec") {
Expand Down Expand Up @@ -841,6 +842,7 @@ export async function publishShoppingCartEvent(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
signedEvent = await amberSignEvent(cartEvent);
} else if (signInMethod === "nsec") {
Expand Down Expand Up @@ -953,6 +955,7 @@ export async function publishWalletEvent(passphrase?: string, dTag?: string) {
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
const encryptedContent = await amberNip44Encrypt(
walletContent,
Expand Down Expand Up @@ -1090,6 +1093,7 @@ export async function publishProofEvent(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
const encryptedContent = await amberNip44Encrypt(
tokenArray,
Expand Down Expand Up @@ -1190,6 +1194,7 @@ export async function publishProofEvent(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
const encryptedContent = await amberNip44Encrypt(
tokenArray,
Expand Down Expand Up @@ -1322,6 +1327,7 @@ export async function publishSpendingHistoryEvent(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
const encryptedContent = await amberNip44Encrypt(
eventContent,
Expand Down Expand Up @@ -1387,6 +1393,7 @@ export async function finalizeAndSendNostrEvent(
await new Promise((resolve) => setTimeout(resolve, 2100));
}
}
signedEvent = JSON.parse(signedEvent);
} else if (signInMethod === "amber") {
signedEvent = await amberSignEvent(nostrEvent);
} else {
Expand Down Expand Up @@ -1556,7 +1563,7 @@ export const setLocalStorageDataOnSignIn = ({
clientPubkey?: string;
clientPrivkey?: string;
bunkerRemotePubkey?: string;
bunkerRelays?: string;
bunkerRelays?: string[];
bunkerSecret?: string;
}) => {
localStorage.setItem(LOCALSTORAGECONSTANTS.signInMethod, signInMethod);
Expand Down Expand Up @@ -1633,7 +1640,9 @@ export const setLocalStorageDataOnSignIn = ({
);
localStorage.setItem(
LOCALSTORAGECONSTANTS.bunkerRelays,
JSON.stringify(bunkerRelays),
JSON.stringify(
bunkerRelays && bunkerRelays.length != 0 ? bunkerRelays : [],
),
);
if (bunkerSecret) {
localStorage.setItem(LOCALSTORAGECONSTANTS.bunkerSecret, bunkerSecret);

Check failure

Code scanning / CodeQL

Clear text storage of sensitive information High

This stores sensitive data returned by
an access to secret
as clear text.
This stores sensitive data returned by
an access to bunkerSecret
as clear text.
This stores sensitive data returned by
an access to secret
as clear text.
This stores sensitive data returned by
an access to secret
as clear text.
This stores sensitive data returned by
a call to get
as clear text.
This stores sensitive data returned by
an access to secret
as clear text.
This stores sensitive data returned by
an access to bunkerSecret
as clear text.
Expand Down Expand Up @@ -1665,7 +1674,7 @@ export interface LocalStorageInterface {
clientPubkey?: string;
clientPrivkey?: string;
bunkerRemotePubkey?: string;
bunkerRelays?: string;
bunkerRelays?: string[];
bunkerSecret?: string;
}

Expand Down Expand Up @@ -1788,6 +1797,7 @@ export const getLocalStorageData = (): LocalStorageInterface => {
wot = localStorage.getItem(LOCALSTORAGECONSTANTS.wot)
? Number(localStorage.getItem(LOCALSTORAGECONSTANTS.wot))
: 3;

clientPubkey = localStorage.getItem(LOCALSTORAGECONSTANTS.clientPubkey)
? localStorage.getItem(LOCALSTORAGECONSTANTS.clientPubkey)
: undefined;
Expand All @@ -1800,8 +1810,12 @@ export const getLocalStorageData = (): LocalStorageInterface => {
? localStorage.getItem(LOCALSTORAGECONSTANTS.bunkerRemotePubkey)
: undefined;
bunkerRelays = localStorage.getItem(LOCALSTORAGECONSTANTS.bunkerRelays)
? localStorage.getItem(LOCALSTORAGECONSTANTS.bunkerRelays)
: undefined;
? (
JSON.parse(
localStorage.getItem(LOCALSTORAGECONSTANTS.bunkerRelays) as string,
) as string[]
).filter((r) => r)
: [];
bunkerSecret = localStorage.getItem(LOCALSTORAGECONSTANTS.bunkerSecret)
? localStorage.getItem(LOCALSTORAGECONSTANTS.bunkerSecret)
: undefined;
Expand All @@ -1822,7 +1836,7 @@ export const getLocalStorageData = (): LocalStorageInterface => {
clientPubkey: clientPubkey?.toString(),
clientPrivkey: clientPrivkey?.toString(),
bunkerRemotePubkey: bunkerRemotePubkey?.toString(),
bunkerRelays: bunkerRelays?.toString(),
bunkerRelays: bunkerRelays || [],
bunkerSecret: bunkerSecret?.toString(),
};
};
Expand Down
1 change: 1 addition & 0 deletions pages/api/nostr/fetch-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,7 @@ export const fetchGiftWrappedChatsAndMessages = async (
}
}
let sealEvent = JSON.parse(sealEventString);
sealEvent = JSON.parse(sealEvent);
if (sealEvent.kind === 13) {
const messageEventDecryptId = crypto.randomUUID();
await sendBunkerRequest(
Expand Down
7 changes: 6 additions & 1 deletion pages/settings/shop-settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,12 @@ const ShopSettingsPage = () => {
};

const isButtonDisabled = useMemo(() => {
if (signInMethod === "extension") return false;
if (
signInMethod === "extension" ||
signInMethod === "amber" ||
signInMethod === "bunker"
)
return false;
if (passphrase === "") return true;
try {
let nsec = getNsecWithPassphrase(passphrase);
Expand Down
83 changes: 55 additions & 28 deletions pages/wallet/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useMemo } from "react";
import { useRouter } from "next/router";
import {
getLocalStorageData,
Expand All @@ -23,7 +23,8 @@ const Wallet = () => {
const [mintKeySetIds, setMintKeySetIds] = useState<MintKeyset[]>([]);
const router = useRouter();

const { signInMethod, mints, tokens } = getLocalStorageData();
const localStorageData = useMemo(() => getLocalStorageData(), []);
const { signInMethod, mints, tokens } = localStorageData;

useEffect(() => {
if (signInMethod === "nsec" && !validPassphrase(passphrase)) {
Expand All @@ -50,37 +51,63 @@ const Wallet = () => {
fetchLocalKeySet();
}, [wallet]);

const filteredProofs = useMemo(() => {
if (mints && tokens && mintKeySetIds) {
return tokens.filter(
(p: Proof) =>
mintKeySetIds?.some((keysetId: MintKeyset) => keysetId.id === p.id),
);
}
return [];
}, [mintKeySetIds, mints, tokens]);

useEffect(() => {
if (tokens) {
const tokensTotal =
tokens.length >= 1
? tokens.reduce((acc, token: Proof) => acc + token.amount, 0)
: 0;
setTotalBalance(tokensTotal);
}

const walletTotal =
filteredProofs.length >= 1
? filteredProofs.reduce((acc, p: Proof) => acc + p.amount, 0)
: 0;
setWalletBalance(walletTotal);
}, [tokens, filteredProofs]);

useEffect(() => {
// Function to fetch and update balances
const fetchAndUpdateBalances = async () => {
if (tokens) {
let tokensTotal =
tokens && tokens.length >= 1
? tokens.reduce((acc, token: Proof) => acc + token.amount, 0)
const interval = setInterval(() => {
const { tokens: newTokens } = getLocalStorageData();
console.log("check");
if (newTokens) {
const tokensTotal =
newTokens.length >= 1
? newTokens.reduce(
(acc: number, token: Proof) => acc + token.amount,
0,
)
: 0;
setTotalBalance(tokensTotal);
}
if (mints && tokens && mintKeySetIds) {
const filteredProofs = tokens.filter(
(p: Proof) =>
mintKeySetIds?.some((keysetId: MintKeyset) => keysetId.id === p.id),
);
let walletTotal =
filteredProofs && filteredProofs.length >= 1
? filteredProofs.reduce((acc, p: Proof) => acc + p.amount, 0)
: 0;
setWalletBalance(walletTotal);
}
};
// Initial fetch
fetchAndUpdateBalances();
// Set up polling with setInterval
const interval = setInterval(() => {
fetchAndUpdateBalances();
}, 2100); // Polling every 2100 milliseconds (2.1 seconds)
// Clean up on component unmount

const newFilteredProofs = newTokens.filter(
(p: Proof) =>
mintKeySetIds?.some((keysetId: MintKeyset) => keysetId.id === p.id),
);
const newWalletTotal =
newFilteredProofs.length >= 1
? newFilteredProofs.reduce(
(acc: number, p: Proof) => acc + p.amount,
0,
)
: 0;
setWalletBalance(newWalletTotal);
}, 2100);

return () => clearInterval(interval);
}, [mintKeySetIds, mints, tokens]);
}, []); // Empty dependency array for continuous polling

const handleMintClick = () => {
router.push("/settings/preferences");
Expand Down

0 comments on commit d31eeae

Please sign in to comment.