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: verify v2 #5236

Merged
merged 28 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
951f993
wip: verify v2 - submit attestation
ganchoradkov Jul 30, 2024
0596131
chore: sents `attestation` with publish payload
ganchoradkov Jul 31, 2024
d1966d4
feat: verify v2
ganchoradkov Aug 1, 2024
f755ef6
refactor: uses getDocument()
ganchoradkov Aug 6, 2024
07823a5
Merge branch 'v2.0' into feat/verify-v2
ganchoradkov Aug 9, 2024
2c79c58
Merge branch 'feat/verify-v2' of github.com:WalletConnect/walletconne…
ganchoradkov Aug 9, 2024
318a0e2
refactor: makes verify v2 public key being fetched only when attempte…
ganchoradkov Aug 9, 2024
d11901e
chore: canary relay api
ganchoradkov Aug 9, 2024
18d5f6b
chore: prettier
ganchoradkov Aug 9, 2024
6b5a70a
fix: adds new `attestation` field to publisher tests
ganchoradkov Aug 9, 2024
e0d979e
fix: relayer test with new `attestation` param
ganchoradkov Aug 9, 2024
730bca3
chore: updates relay-api to stable
ganchoradkov Aug 9, 2024
5210e5a
feat: adds test
ganchoradkov Aug 9, 2024
3ddbfc7
chore: clean up logs
ganchoradkov Aug 9, 2024
372a42e
chore: bump node to 20
ganchoradkov Aug 9, 2024
9659018
fix: logging & rm event listener
ganchoradkov Aug 9, 2024
faeed6d
fix: subtle crypto in node
ganchoradkov Aug 9, 2024
0141609
Merge branch 'v2.0' into feat/verify-v2
ganchoradkov Aug 12, 2024
82e5cd4
refactor: log rejections & unsubscribe on abortController
ganchoradkov Aug 12, 2024
9535ca9
Merge branch 'feat/verify-v2' of github.com:WalletConnect/walletconne…
ganchoradkov Aug 12, 2024
0ef5ee2
chore: handle invalid keys
ganchoradkov Aug 12, 2024
92d77a9
Merge branch 'v2.0' into feat/verify-v2
ganchoradkov Aug 12, 2024
24614bd
chore: fixes typo
ganchoradkov Aug 12, 2024
9e9bf2e
Merge branch 'feat/verify-v2' of github.com:WalletConnect/walletconne…
ganchoradkov Aug 12, 2024
fb3dceb
feat: implements `ecdsa` signature validation without relying on `nod…
ganchoradkov Aug 14, 2024
0c4df5c
chore: cleanup
ganchoradkov Aug 15, 2024
29f8df8
feat: adds unhappy path tests
ganchoradkov Aug 15, 2024
1c229bd
chore: uses const
ganchoradkov Aug 15, 2024
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
1 change: 1 addition & 0 deletions packages/core/src/constants/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ export const VERIFY_CONTEXT = "verify-api";
const VERIFY_SERVER_COM = "https://verify.walletconnect.com";
const VERIFY_SERVER_ORG = "https://verify.walletconnect.org";
export const VERIFY_SERVER = VERIFY_SERVER_ORG;
export const VERIFY_SERVER_V2 = "https://verify.walletconnect.com/v2";
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved

export const TRUSTED_VERIFY_URLS = [VERIFY_SERVER_COM, VERIFY_SERVER_ORG];
21 changes: 18 additions & 3 deletions packages/core/src/controllers/publisher.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { HEARTBEAT_EVENTS } from "@walletconnect/heartbeat";
import { JsonRpcPayload, RequestArguments } from "@walletconnect/jsonrpc-types";
import { generateChildLogger, getLoggerContext, Logger } from "@walletconnect/logger";
Expand Down Expand Up @@ -44,7 +45,18 @@ export class Publisher extends IPublisher {
const prompt = opts?.prompt || false;
const tag = opts?.tag || 0;
const id = opts?.id || (getBigIntRpcId().toString() as any);
const params = { topic, message, opts: { ttl, relay, prompt, tag, id } };
const params = {
topic,
message,
opts: {
ttl,
relay,
prompt,
tag,
id,
attestation: opts?.attestation,
},
};
const failedPublishMessage = `Failed to publish payload, please try again. id:${id} tag:${tag}`;
const startPublish = Date.now();
let result;
Expand All @@ -63,8 +75,8 @@ export class Publisher extends IPublisher {

this.logger.trace({ id, attempts }, `publisher.publish - attempt ${attempts}`);
const publish = await createExpiringPromise(
this.rpcPublish(topic, message, ttl, relay, prompt, tag, id).catch((e) =>
this.logger.warn(e),
this.rpcPublish(topic, message, ttl, relay, prompt, tag, id, opts?.attestation).catch(
(e) => this.logger.warn(e),
),
this.publishTimeout,
failedPublishMessage,
Expand Down Expand Up @@ -121,6 +133,7 @@ export class Publisher extends IPublisher {
prompt?: boolean,
tag?: number,
id?: number,
attestation?: string,
) {
const api = getRelayProtocolApi(relay.protocol);
const request: RequestArguments<RelayJsonRpc.PublishParams> = {
Expand All @@ -131,9 +144,11 @@ export class Publisher extends IPublisher {
ttl,
prompt,
tag,
attestation,
},
id,
};
console.log("rpc publish request", request);
if (isUndefined(request.params?.prompt)) delete request.params?.prompt;
if (isUndefined(request.params?.tag)) delete request.params?.tag;
this.logger.debug(`Outgoing Relay Payload`);
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/controllers/relayer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { EventEmitter } from "events";
import { JsonRpcProvider } from "@walletconnect/jsonrpc-provider";
import {
Expand Down Expand Up @@ -444,11 +445,12 @@ export class Relayer extends IRelayer {
private async onProviderPayload(payload: JsonRpcPayload) {
this.logger.debug(`Incoming Relay Payload`);
this.logger.trace({ type: "payload", direction: "incoming", payload });
console.log("onProviderPayload", payload);
if (isJsonRpcRequest(payload)) {
if (!payload.method.endsWith(RELAYER_SUBSCRIBER_SUFFIX)) return;
const event = (payload as JsonRpcRequest<RelayJsonRpc.SubscriptionParams>).params;
const { topic, message, publishedAt } = event.data;
const messageEvent: RelayerTypes.MessageEvent = { topic, message, publishedAt };
const { topic, message, publishedAt, attestation } = event.data;
const messageEvent: RelayerTypes.MessageEvent = { topic, message, publishedAt, attestation };
this.logger.debug(`Emitting Relayer Payload`);
this.logger.trace({ type: "event", event: event.id, ...messageEvent });
this.events.emit(event.id, messageEvent);
Expand Down
258 changes: 153 additions & 105 deletions packages/core/src/controllers/verify.ts
Original file line number Diff line number Diff line change
@@ -1,68 +1,140 @@
/* eslint-disable no-console */
import { generateChildLogger, getLoggerContext, Logger } from "@walletconnect/logger";
import { IVerify } from "@walletconnect/types";
import { isBrowser, isNode, isReactNative } from "@walletconnect/utils";
import {
getCryptoKeyFromKeyData,
isNode,
P256KeyDataType,
verifyP256Jwt,
} from "@walletconnect/utils";
import { FIVE_SECONDS, ONE_SECOND, toMiliseconds } from "@walletconnect/time";

import { TRUSTED_VERIFY_URLS, VERIFY_CONTEXT, VERIFY_SERVER } from "../constants";
import { TRUSTED_VERIFY_URLS, VERIFY_CONTEXT, VERIFY_SERVER, VERIFY_SERVER_V2 } from "../constants";
import { IKeyValueStorage } from "@walletconnect/keyvaluestorage";

type jwk = {
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
publicKey: P256KeyDataType;
expiresAt: number;
};
export class Verify extends IVerify {
public name = VERIFY_CONTEXT;
private verifyUrl: string;
private iframe?: HTMLIFrameElement;
private initialized = false;
private abortController: AbortController;
private isDevEnv;
// the queue is only used during the loading phase of the iframe to ensure all attestations are posted
private queue: string[] = [];
// flag to disable verify when the iframe fails to load on main & fallback urls.
// this means Verify API is not enabled for the current projectId and there's no point in trying to initialize it again.
private verifyDisabled = false;

constructor(public projectId: string, public logger: Logger) {
super(projectId, logger);
private verifyUrlV2 = VERIFY_SERVER_V2;
private publicKey?: jwk;
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved

constructor(public projectId: string, public logger: Logger, public store: IKeyValueStorage) {
super(projectId, logger, store);
this.logger = generateChildLogger(logger, this.name);
this.verifyUrl = VERIFY_SERVER;
this.abortController = new AbortController();
this.isDevEnv = isNode() && process.env.IS_VITEST;
console.log("Verify v2 init", this.verifyUrlV2);
this.init();
}

public init: IVerify["init"] = async (params) => {
if (this.verifyDisabled) return;

// ignore on non browser environments
if (isReactNative() || !isBrowser()) return;

const verifyUrl = this.getVerifyUrl(params?.verifyUrl);
// if init is called again with a different url, remove the iframe and start over
if (this.verifyUrl !== verifyUrl) {
this.removeIframe();
}
this.verifyUrl = verifyUrl;
get storeKey(): string {
return `verify:public:key`;
}

try {
await this.createIframe();
} catch (error) {
this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`);
this.logger.info(error);
// if the iframe fails to load, disable verify
this.verifyDisabled = true;
public init = async () => {
this.publicKey = await this.store.getItem(this.storeKey);
console.log("persistedKey", this.publicKey);
if (this.publicKey && toMiliseconds(this.publicKey?.expiresAt) < Date.now()) {
console.log("public key expired");
await this.removePublicKey();
}
if (this.publicKey) return;
const key = await this.fetchPublicKey();
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
console.log("public key", key);
await this.persistPublicKey(key);
};

public register: IVerify["register"] = async (params) => {
if (!this.initialized) {
this.addToQueue(params.attestationId);
await this.init();
} else {
this.sendPost(params.attestationId);
console.log("register", params);
const { id, decryptedId } = params;
const url = `${this.verifyUrlV2}/attestation?projectId=${this.projectId}`;
let src = "";
try {
const response = await fetch(url, {
method: "POST",
body: JSON.stringify({ id, decryptedId }),
headers: {
origin: "https://8951-78-130-198-143.ngrok-free.app/",
},
});
const { srcdoc } = await response.json();
src = srcdoc;
} catch (e) {
console.error("error", e);
return;
}
console.log("srcdoc", src);

const abortTimeout = this.startAbortTimer(ONE_SECOND * 2);
const attestatiatonJwt = await new Promise((resolve) => {
const abortListener = () => {
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
document.body.removeChild(iframe);
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
window.removeEventListener("message", listener);
this.abortController.signal.removeEventListener("abort", abortListener);
};

this.abortController.signal.addEventListener("abort", abortListener);
const iframe = document.createElement("iframe");
iframe.srcdoc = src;
iframe.src = "https://verify.walletconnect.com";
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
iframe.style.display = "none";
const listener = (event: MessageEvent) => {
console.log("message event received", event);
if (!event.data) return;
const data = JSON.parse(event.data);
if (data.type === "verify_attestation") {
// best-practice field
clearInterval(abortTimeout);
window.removeEventListener("message", listener);
document.body.removeChild(iframe);
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
this.abortController.signal.removeEventListener("abort", abortListener);
console.log("attestation", data.attestation);
resolve(data.attestation === null ? "" : data.attestation);
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
}
};
document.body.appendChild(iframe);
window.addEventListener("message", listener);
});
console.log("attestatiatonJwt", attestatiatonJwt);
return attestatiatonJwt as string;
};

public resolve: IVerify["resolve"] = async (params) => {
if (this.isDevEnv) return "";
const { attestationId, hash } = params;

console.log("resolve attestation", params);

if (attestationId === "") {
console.log("resolve: attestationId is empty string");
return;
}
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved

if (attestationId) {
const data = await this.isValidJwtAttestation(attestationId);
console.log("resolve data", data);

if (data?.hasExpired) {
console.log("resolve: jwt attestation expired");
return;
}

if (data?.valid) {
return {
origin: data.payload.origin,
isScam: data.payload.isScam,
};
}
}
if (!hash) return;
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
console.log("resolve hash", hash);
const verifyUrl = this.getVerifyUrl(params?.verifyUrl);
return this.fetchAttestation(params.attestationId, verifyUrl);
return this.fetchAttestation(hash, verifyUrl);
};

get context(): string {
Expand All @@ -80,77 +152,11 @@ export class Verify extends IVerify {
return result.status === 200 ? await result.json() : undefined;
};

private addToQueue = (attestationId: string) => {
this.queue.push(attestationId);
};

private processQueue = () => {
if (this.queue.length === 0) return;
this.queue.forEach((attestationId) => this.sendPost(attestationId));
this.queue = [];
};

private sendPost = (attestationId: string) => {
try {
if (!this.iframe) return;
this.iframe.contentWindow?.postMessage(attestationId, "*"); // setting targetOrigin to "*" fixes the `Failed to execute 'postMessage' on 'DOMWindow': The target origin provided...` while the iframe is still loading
this.logger.info(`postMessage sent: ${attestationId} ${this.verifyUrl}`);
} catch (e) {}
};

private createIframe = async () => {
let iframeOnLoadResolve: () => void;
const onMessage = (event: MessageEvent) => {
if (event.data === "verify_ready") {
this.onInit();
window.removeEventListener("message", onMessage);
iframeOnLoadResolve();
}
};
await Promise.race([
new Promise<void>((resolve) => {
const existingIframe = document.getElementById(VERIFY_CONTEXT);
if (existingIframe) {
this.iframe = existingIframe as HTMLIFrameElement;
this.onInit();
return resolve();
}

window.addEventListener("message", onMessage);
const iframe = document.createElement("iframe");
iframe.id = VERIFY_CONTEXT;
iframe.src = `${this.verifyUrl}/${this.projectId}`;
iframe.style.display = "none";
document.body.append(iframe);
this.iframe = iframe;
iframeOnLoadResolve = resolve;
}),
new Promise((_, reject) =>
setTimeout(() => {
window.removeEventListener("message", onMessage);
reject("verify iframe load timeout");
}, toMiliseconds(FIVE_SECONDS)),
),
]);
};

private onInit = () => {
this.initialized = true;
this.processQueue();
};

private startAbortTimer(timer: number) {
this.abortController = new AbortController();
return setTimeout(() => this.abortController.abort(), toMiliseconds(timer));
}

private removeIframe = () => {
if (!this.iframe) return;
this.iframe.remove();
this.iframe = undefined;
this.initialized = false;
};

private getVerifyUrl = (verifyUrl?: string) => {
let url = verifyUrl || VERIFY_SERVER;
if (!TRUSTED_VERIFY_URLS.includes(url)) {
Expand All @@ -161,4 +167,46 @@ export class Verify extends IVerify {
}
return url;
};

private fetchPublicKey = async () => {
this.logger.info(`fetching public key from: ${this.verifyUrlV2}`);
const timeout = this.startAbortTimer(FIVE_SECONDS);
const result = await fetch(`${this.verifyUrlV2}/public-key`, {
signal: this.abortController.signal,
});
clearTimeout(timeout);
return (await result.json()) as jwk;
};

private persistPublicKey = async (publicKey: jwk) => {
console.log(`persisting public key to local storage`, publicKey);
await this.store.setItem(this.storeKey, publicKey);
this.publicKey = publicKey;
};

private removePublicKey = async () => {
console.log(`removing public key from local storage`);
await this.store.removeItem(this.storeKey);
this.publicKey = undefined;
};

private isValidJwtAttestation = async (attestation: string) => {
if (!this.publicKey) {
console.log("public key not found");
return;
}
const cryptoKey = await getCryptoKeyFromKeyData(this.publicKey.publicKey);
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
const result = await verifyP256Jwt<{
exp: number;
id: string;
origin: string;
isScam: boolean;
}>(attestation, cryptoKey);
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved

return {
valid: result.verified,
hasExpired: toMiliseconds(result.payload.payload.exp) < Date.now(),
payload: result.payload.payload,
};
};
}
2 changes: 1 addition & 1 deletion packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export class Core extends ICore {
projectId: this.projectId,
});
this.pairing = new Pairing(this, this.logger);
this.verify = new Verify(this.projectId || "", this.logger);
this.verify = new Verify(this.projectId || "", this.logger, this.storage);
this.echoClient = new EchoClient(this.projectId || "", this.logger);
}

Expand Down
Loading
Loading