Skip to content
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
58 changes: 58 additions & 0 deletions .changeset/cold-dryers-dream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
"@thirdweb-dev/react-native": patch
---

Custom JWT support in React Native

Enables passing a custom JWT to the embeddedWallet:

```javascript
import {
EmbeddedWallet,
embeddedWallet,
ThirdwebProvider,
useCreateWalletInstance,
useSetConnectedWallet,
} from '@thirdweb-dev/react-native';
import {Button} from 'react-native';
import React from 'react';

const App = () => {
return (
<ThirdwebProvider
supportedWallets={[
embeddedWallet({
custom_auth: true, // when true, it will not display a UI
}),
]}>
<AppInner />
</ThirdwebProvider>
);
};

const AppInner = () => {
const createInstance = useCreateWalletInstance();
const setConnectedWallet = useSetConnectedWallet();

const triggerConnect = async () => {
const embeddedWalletConfig = embeddedWallet();

if (embeddedWalletConfig) {
const instance = createInstance(embeddedWalletConfig);

if (instance) {
await (instance as EmbeddedWallet).connect({
loginType: 'custom_jwt_auth',
encryptionKey: 'hello',
jwtToken: 'customJwt' || '',
});
setConnectedWallet(instance); // this sets the active wallet on the provider enabling all thirdweb hooks
}
}
};

return <Button title={'Connect with custom JWT'} onPress={triggerConnect} />;
};


```
1 change: 1 addition & 0 deletions packages/react-native/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@magic-sdk/provider": "17.2.0",
"@magic-sdk/react-native-bare": "^18.5.0",
"@paperxyz/embedded-wallet-service-sdk": "^1.2.4",
"@react-native-community/checkbox": "^0.5.16",
"@shopify/restyle": "^2.4.2",
"@tanstack/react-query": "^4.33.0",
"@thirdweb-dev/chains": "workspace:*",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ export function ChooseWallet({

const guestWallet = wallets.find((w) => w.id === walletIds.localWallet);
const emailWallet = wallets.find(
(w) => w.id === walletIds.magicLink || w.id === walletIds.embeddedWallet,
(w) =>
w.id === walletIds.magicLink ||
(w.id === walletIds.embeddedWallet && w.selectUI),
);
const connectionWallets = wallets
.filter(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ export const SmartWalletFlow = ({
<>
<Text variant="header" mt="lg" textAlign="center">
{mismatch
? l.smart_wallet.network_mistmach
? l.smart_wallet.network_mismatch
: `${l.smart_wallet.connecting} ...`}
</Text>
{mismatch ? (
Expand Down
8 changes: 6 additions & 2 deletions packages/react-native/src/evm/i18n/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export const _en = {
copy_address_or_scan:
"Copy the wallet address or scan the QR code to send funds to this wallet.",
request_testnet_funds: "Request Testnet Funds",
view_transatcion_history: "View Transaction History",
your_address: "Your address",
qr_code: "QR Code",
select_token: "Select Token",
Expand Down Expand Up @@ -72,14 +71,17 @@ export const _en = {
smart_wallet: {
switch_to_smart: "Switch to Smart Wallet",
switch_to_personal: "Switch to Personal Wallet",
network_mistmach: "Network Mismatch",
network_mismatch: "Network Mismatch",
connecting: "Connecting",
},
embedded_wallet: {
request_new_code: "Request new code",
sign_in: "Sign In",
sign_in_google: "Sign in with Google",
enter_your_email: "Enter your email address",
forgot_password: "Forgot password",
enter_account_recovery_code: "Enter account recovery code",
backup_your_account: "Backup your account",
},
wallet_connect: {
no_results_found: "No results found",
Expand All @@ -103,5 +105,7 @@ export const _en = {
or: "OR",
from: "from",
to: "from",
next: "Next",
learn_more: "Learn More",
},
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
AuthOptions,
EmbeddedWalletConnectionArgs,
EmbeddedWalletConnectorOptions,
OauthOption,
Expand All @@ -7,14 +8,20 @@ import type { Chain } from "@thirdweb-dev/chains";
import { Connector, normalizeChainId } from "@thirdweb-dev/wallets";
import { providers, Signer } from "ethers";
import { utils } from "ethers";
import { sendEmailOTP, socialLogin, validateEmailOTP } from "./embedded/auth";
import {
customJwt,
sendEmailOTP,
socialLogin,
validateEmailOTP,
} from "./embedded/auth";
import { getEthersSigner } from "./embedded/signer";
import { logoutUser } from "./embedded/helpers/auth/logout";
import {
clearConnectedEmail,
getConnectedEmail,
saveConnectedEmail,
} from "./embedded/helpers/storage/local";
import { AuthProvider } from "@paperxyz/embedded-wallet-service-sdk";

export class EmbeddedWalletConnector extends Connector<EmbeddedWalletConnectionArgs> {
private options: EmbeddedWalletConnectorOptions;
Expand All @@ -30,11 +37,38 @@ export class EmbeddedWalletConnector extends Connector<EmbeddedWalletConnectionA
this.email = getConnectedEmail();
}

async connect(options?: { email?: string; chainId?: number }) {
async connect(options?: { chainId?: number } & EmbeddedWalletConnectionArgs) {
const connected = await this.isConnected();

if (!connected) {
throw new Error("Not connected");
if (connected) {
return this.getAddress();
}

switch (options?.loginType) {
case "headless_google_oauth":
{
await socialLogin(
{
provider: AuthProvider.GOOGLE,
redirectUrl: options.redirectUrl,
},
this.options.clientId,
);
}
break;
case "headless_email_otp_verification": {
await this.validateEmailOtp(options.otp);
break;
}
case "custom_jwt_auth": {
await this.customJwt({
jwtToken: options.jwtToken,
encryptionKey: options.encryptionKey,
});
break;
}
default:
throw new Error("Invalid login type");
}

if (options?.chainId) {
Expand Down Expand Up @@ -114,6 +148,30 @@ export class EmbeddedWalletConnector extends Connector<EmbeddedWalletConnectionA
return { success: true };
}

async customJwt(authOptions: AuthOptions) {
try {
const resp = await customJwt(authOptions, this.options.clientId);
this.email = resp.email;
} catch (error) {
console.error(`Error while verifying auth: ${error}`);
this.disconnect();
throw error;
}

try {
await this.getSigner();
this.emit("connected");
} catch (error) {
if (error instanceof Error) {
return { error: error.message };
} else {
return { error: "Error getting the signer" };
}
}

return { success: true };
}

async disconnect(): Promise<void> {
clearConnectedEmail();
await logoutUser(this.options.clientId);
Expand Down Expand Up @@ -148,12 +206,7 @@ export class EmbeddedWalletConnector extends Connector<EmbeddedWalletConnectionA
return this.signer;
}

let signer;
try {
signer = await getEthersSigner(this.options.clientId);
} catch (error) {
console.error(`Error while getting the signer: ${error}`);
}
const signer = await getEthersSigner(this.options.clientId);

if (!signer) {
throw new Error("Error fetching the signer");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,20 @@ import {
cognitoEmailSignIn,
cognitoEmailSignUp,
} from "./helpers/auth/cognitoAuth";
import { postPaperAuth, prePaperAuth } from "./helpers/auth/middleware";
import {
postPaperAuth,
postPaperAuthUserManaged,
prePaperAuth,
} from "./helpers/auth/middleware";
import { isDeviceSharePresentForUser } from "./helpers/storage/local";
import { getCognitoUser, setCognitoUser } from "./helpers/storage/state";
import { SendEmailOtpReturnType } from "@thirdweb-dev/wallets";
import { InAppBrowser } from "react-native-inappbrowser-reborn";
import { OauthOption } from "../types";
import { ROUTE_HEADLESS_GOOGLE_LOGIN } from "./helpers/constants";
import { AuthOptions, OauthOption } from "../types";
import {
ROUTE_AUTH_JWT_CALLBACK,
ROUTE_HEADLESS_GOOGLE_LOGIN,
} from "./helpers/constants";

export async function sendEmailOTP(
email: string,
Expand Down Expand Up @@ -196,3 +203,46 @@ export async function socialLogin(oauthOptions: OauthOption, clientId: string) {
);
}
}

export async function customJwt(authOptions: AuthOptions, clientId: string) {
const { jwtToken, encryptionKey } = authOptions;

const resp = await fetch(ROUTE_AUTH_JWT_CALLBACK, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jwtToken,
authProvider: AuthProvider.CUSTOM_JWT,
developerClientId: clientId,
}),
});
if (!resp.ok) {
const { error } = await resp.json();
throw new Error(`JWT authentication error: ${error} `);
}

try {
const { verifiedToken, verifiedTokenJwtString } = await resp.json();

const toStoreToken: AuthStoredTokenWithCookieReturnType["storedToken"] = {
jwtToken: verifiedToken.rawToken,
authProvider: verifiedToken.authProvider,
authDetails: {
...verifiedToken.authDetails,
email: verifiedToken.authDetails.email,
},
developerClientId: verifiedToken.developerClientId,
cookieString: verifiedTokenJwtString,
shouldStoreCookieString: false,
isNewUser: verifiedToken.isNewUser,
};

await postPaperAuthUserManaged(toStoreToken, clientId, encryptionKey);

return { verifiedToken, email: verifiedToken.authDetails.email };
} catch (e) {
throw new Error(
`Malformed response from post authentication: ${JSON.stringify(e)}`,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,45 @@ export async function postPaperAuth(

return storedToken;
}

export async function postPaperAuthUserManaged(
storedToken: AuthStoredTokenWithCookieReturnType["storedToken"],
clientId: string,
encryptionKey: string,
) {
if (storedToken.shouldStoreCookieString) {
await setAuthTokenClient(storedToken.cookieString, clientId);
}

await setWallerUserDetails({
clientId,
userId: storedToken.authDetails.userWalletId,
email: storedToken.authDetails.email,
});

if (storedToken.isNewUser) {
console.log("========== New User ==========");
await setUpNewUserWallet(encryptionKey, clientId);
} else {
try {
// existing device share
await getDeviceShare(clientId);
console.log("========== Existing user with device share ==========");
} catch (e) {
// trying to recreate device share from recovery code to derive wallet
console.log("========== Existing user on new device ==========");

try {
await setUpShareForNewDevice({
clientId,
recoveryCode: encryptionKey,
});
} catch (error) {
console.error("Error setting up wallet on device", error);
throw error;
}
}
}

return storedToken;
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const ROUTE_INIT_RECOVERY_CODE_FREE_WALLET = `${ROUTE_2022_08_12_API_BASE
export const ROUTE_STORE_USER_SHARES = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/store-shares`;
export const ROUTE_GET_USER_SHARES = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/get-shares`;
export const ROUTE_VERIFY_THIRDWEB_CLIENT_ID = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/verify-thirdweb-client-id`;
export const ROUTE_AUTH_JWT_CALLBACK = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/jwt-callback`;

export const ROUTE_HEADLESS_GOOGLE_LOGIN = `${BASE_URL}/api/2022-08-12/embedded-wallet/headless-login-link`;

Expand Down
Loading