Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Added verify for the signed message in examples for browser wallets #964

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 84 additions & 27 deletions examples/angular/src/app/components/content/content.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import type {
AccountView,
CodeResult,
} from "near-api-js/lib/providers/provider";
import type { AccountState, Transaction } from "@near-wallet-selector/core";
import type {
AccountState,
SignMessageParams,
SignedMessage,
Transaction,
} from "@near-wallet-selector/core";
import {
verifyFullKeyBelongsToUser,
verifySignature,
Expand Down Expand Up @@ -48,6 +53,8 @@ export class ContentComponent implements OnInit, OnDestroy {
this.getAccount(),
]);

this.verifyMessageBrowserWallet();
erditkurteshiSQA marked this conversation as resolved.
Show resolved Hide resolved

this.account = account;
this.messages = messages;

Expand Down Expand Up @@ -165,45 +172,95 @@ export class ContentComponent implements OnInit, OnDestroy {
}
}

async verifyMessage(
message: SignMessageParams,
signedMessage: SignedMessage
) {
const verifiedSignature = verifySignature({
message: message.message,
nonce: message.nonce,
recipient: message.recipient,
publicKey: signedMessage.publicKey,
signature: signedMessage.signature,
callbackUrl: message.callbackUrl,
});
const verifiedFullKeyBelongsToUser = await verifyFullKeyBelongsToUser({
publicKey: signedMessage.publicKey,
accountId: signedMessage.accountId,
network: this.selector.options.network,
});

const isMessageVerified = verifiedFullKeyBelongsToUser && verifiedSignature;

const alertMessage = isMessageVerified
? "Successfully verified"
: "Failed to verify";

alert(
`${alertMessage} signed message: '${
message.message
}': \n ${JSON.stringify(signedMessage)}`
);
}

verifyMessageBrowserWallet() {
erditkurteshiSQA marked this conversation as resolved.
Show resolved Hide resolved
const urlParams = new URLSearchParams(
window.location.hash.substring(1) // skip the first char (#)
);

const accId = urlParams.get("accountId") as string;
const publicKey = urlParams.get("publicKey") as string;
const signature = urlParams.get("signature") as string;

if (!accId && !publicKey && !signature) {
return;
}

const message: SignMessageParams = JSON.parse(
localStorage.getItem("message") as string
);

const signedMessage = {
accountId: accId,
publicKey,
signature,
};

this.verifyMessage(message, signedMessage);
erditkurteshiSQA marked this conversation as resolved.
Show resolved Hide resolved

const url = new URL(location.href);
url.hash = "";
url.search = "";
window.history.replaceState({}, document.title, url);
localStorage.removeItem("message");
}

async onSignMessage() {
const wallet = await this.selector.wallet();
const message = "test message to sign";
const nonce = Buffer.from(Array.from(Array(32).keys()));
const recipient = "guest-book.testnet";

if (wallet.type === "browser") {
localStorage.setItem(
"message",
JSON.stringify({
message,
nonce: [...nonce],
recipient,
callbackUrl: location.href,
})
);
}

try {
const signedMessage = await wallet.signMessage({
message,
nonce,
recipient,
});
if (signedMessage) {
const verifiedSignature = verifySignature({
message,
nonce,
recipient,
publicKey: signedMessage.publicKey,
signature: signedMessage.signature,
});
const verifiedFullKeyBelongsToUser = await verifyFullKeyBelongsToUser({
publicKey: signedMessage.publicKey,
accountId: signedMessage.accountId,
network: this.selector.options.network,
});

if (verifiedFullKeyBelongsToUser && verifiedSignature) {
alert(
`Successfully verify signed message: '${message}': \n ${JSON.stringify(
signedMessage
)}`
);
} else {
alert(
`Failed to verify signed message '${message}': \n ${JSON.stringify(
signedMessage
)}`
);
}
await this.verifyMessage({ message, nonce, recipient }, signedMessage);
}
} catch (err) {
const errMsg =
Expand Down
115 changes: 88 additions & 27 deletions examples/react/components/Content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import type {
AccountView,
CodeResult,
} from "near-api-js/lib/providers/provider";
import type { Transaction } from "@near-wallet-selector/core";
import type {
SignedMessage,
SignMessageParams,
Transaction,
} from "@near-wallet-selector/core";
import { verifyFullKeyBelongsToUser } from "@near-wallet-selector/core";
import { verifySignature } from "@near-wallet-selector/core";
import BN from "bn.js";
Expand Down Expand Up @@ -103,6 +107,14 @@ const Content: React.FC = () => {
useEffect(() => {
// TODO: don't just fetch once; subscribe!
getMessages().then(setMessages);

const timeoutId = setTimeout(() => {
verifyMessageBrowserWallet();
}, 500);

return () => {
clearTimeout(timeoutId);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down Expand Up @@ -224,6 +236,68 @@ const Content: React.FC = () => {
}
};

const verifyMessage = async (
message: SignMessageParams,
signedMessage: SignedMessage
) => {
const verifiedSignature = verifySignature({
message: message.message,
nonce: message.nonce,
recipient: message.recipient,
publicKey: signedMessage.publicKey,
signature: signedMessage.signature,
callbackUrl: message.callbackUrl,
});
const verifiedFullKeyBelongsToUser = await verifyFullKeyBelongsToUser({
publicKey: signedMessage.publicKey,
accountId: signedMessage.accountId,
network: selector.options.network,
});

const isMessageVerified = verifiedFullKeyBelongsToUser && verifiedSignature;

const alertMessage = isMessageVerified
? "Successfully verified"
: "Failed to verify";

alert(
`${alertMessage} signed message: '${
message.message
}': \n ${JSON.stringify(signedMessage)}`
);
};

const verifyMessageBrowserWallet = useCallback(async () => {
const urlParams = new URLSearchParams(
window.location.hash.substring(1) // skip the first char (#)
);
const accId = urlParams.get("accountId") as string;
const publicKey = urlParams.get("publicKey") as string;
const signature = urlParams.get("signature") as string;

if (!accId && !publicKey && !signature) {
return;
}

const message: SignMessageParams = JSON.parse(
localStorage.getItem("message")!
);

const signedMessage = {
accountId: accId,
publicKey,
signature,
};

await verifyMessage(message, signedMessage);

const url = new URL(location.href);
url.hash = "";
url.search = "";
window.history.replaceState({}, document.title, url);
localStorage.removeItem("message");
}, []);

const handleSubmit = useCallback(
async (e: Submitted) => {
e.preventDefault();
Expand Down Expand Up @@ -266,39 +340,26 @@ const Content: React.FC = () => {
const nonce = Buffer.from(Array.from(Array(32).keys()));
const recipient = "guest-book.testnet";

if (wallet.type === "browser") {
localStorage.setItem(
"message",
JSON.stringify({
message,
nonce: [...nonce],
recipient,
callbackUrl: location.href,
})
);
}

try {
const signedMessage = await wallet.signMessage({
message,
nonce,
recipient,
});
if (signedMessage) {
const verifiedSignature = verifySignature({
message,
nonce,
recipient,
publicKey: signedMessage.publicKey,
signature: signedMessage.signature,
});
const verifiedFullKeyBelongsToUser = await verifyFullKeyBelongsToUser({
publicKey: signedMessage.publicKey,
accountId: signedMessage.accountId,
network: selector.options.network,
});

if (verifiedFullKeyBelongsToUser && verifiedSignature) {
alert(
`Successfully verify signed message: '${message}': \n ${JSON.stringify(
signedMessage
)}`
);
} else {
alert(
`Failed to verify signed message '${message}': \n ${JSON.stringify(
signedMessage
)}`
);
}
await verifyMessage({ message, nonce, recipient }, signedMessage);
}
} catch (err) {
const errMsg =
Expand Down