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 all 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
110 changes: 83 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 @@ -52,6 +57,7 @@ export class ContentComponent implements OnInit, OnDestroy {
this.messages = messages;

this.subscribeToEvents();
await this.verifyMessageBrowserWallet();
}

async getAccountBalance({ provider, accountId }: GetAccountBalanceProps) {
Expand Down Expand Up @@ -165,45 +171,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)}`
);
}

async verifyMessageBrowserWallet() {
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,
};

await this.verifyMessage(message, signedMessage);

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
116 changes: 89 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,69 @@ 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");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const handleSubmit = useCallback(
async (e: Submitted) => {
e.preventDefault();
Expand Down Expand Up @@ -266,39 +341,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