Skip to content

Commit

Permalink
making progress with sign-in
Browse files Browse the repository at this point in the history
  • Loading branch information
WyattMufson committed Jan 24, 2025
1 parent c4899f7 commit 14b07bf
Show file tree
Hide file tree
Showing 12 changed files with 208 additions and 119 deletions.
15 changes: 15 additions & 0 deletions examples/connect-electron/electron.vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ export default defineConfig({
},
build: {
outDir: "out/app/dist/renderer",
rollupOptions: {
input: {
launcher: resolve(__dirname, "src/renderer/index.html"),
authComplete: resolve(__dirname, "src/renderer/auth/index.html"),
},
output: {
entryFileNames: (chunkInfo) => {
if (chunkInfo.name === "authComplete") {
return "auth/auth-bundle.js";
}
return "assets/[name].js";
},
assetFileNames: () => "public/[name][extname]",
},
},
},
},
});
1 change: 0 additions & 1 deletion examples/connect-electron/out/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"express": "catalog:",
"@electron-toolkit/preload": "catalog:",
"@electron-toolkit/utils": "catalog:",
"@treasure-dev/launcher": "workspace:*",
"thirdweb": "catalog:"
}
}
5 changes: 5 additions & 0 deletions examples/connect-electron/src/main/app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import http from "node:http";
import path from "node:path";
import type { BrowserWindow } from "electron";
import express from "express";

Expand Down Expand Up @@ -33,6 +34,10 @@ export default class RedirectApp {
next();
});

this.app.use("/auth", [
express.static(path.resolve(__dirname, "../renderer/auth/")),
]);

this.app.post("/auth", (req, res) => {
const { searchParams }: { searchParams: string } = req.body;

Expand Down
90 changes: 85 additions & 5 deletions examples/connect-electron/src/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,93 @@
import { join } from "node:path";
import { electronApp, is, optimizer } from "@electron-toolkit/utils";
import {
getTreasureLauncherAuthToken,
getTreasureLauncherWalletComponents,
} from "@treasure-dev/launcher";
import { BrowserWindow, app, ipcMain, shell } from "electron";
import { BrowserWindow, app, ipcMain, session, shell } from "electron";
import icon from "../../resources/icon.png?asset";
import { startRedirectApp } from "./app";

let mainWindow: BrowserWindow;

export function getTreasureLauncherAuthToken(): string | undefined {
let args: string[] | undefined;

if (typeof process !== "undefined" && Array.isArray(process.argv)) {
args = process.argv;
} else if (
typeof window !== "undefined" &&
window.process &&
Array.isArray(window.process.argv)
) {
args = window.process.argv;
} else {
return undefined;
}

const arg = args.find((arg) => arg.startsWith("--tdk-auth-token="));
return arg ? arg.split("=")[1] : undefined;
}

export function getTreasureLauncherWalletComponents():
| { walletId: string; authProvider: string; authCookie: string }
| undefined {
let args: string[] | undefined;

if (typeof process !== "undefined" && Array.isArray(process.argv)) {
args = process.argv;
} else if (
typeof window !== "undefined" &&
window.process &&
Array.isArray(window.process.argv)
) {
args = window.process.argv;
} else {
return undefined;
}

let walletId: string | undefined = args.find((arg) =>
arg.startsWith("--tdk-wallet-id="),
);
if (walletId) {
walletId = walletId.split("=")[1];
}

let authProvider: string | undefined = args.find((arg) =>
arg.startsWith("--tdk-auth-provider="),
);
if (authProvider) {
authProvider = authProvider.split("=")[1];
}

let authCookie: string | undefined = args.find((arg) =>
arg.startsWith("--tdk-auth-cookie="),
);
if (authCookie) {
authCookie = authCookie.split("=")[1];
}

if (!walletId || !authProvider || !authCookie) {
return undefined;
}

return {
walletId,
authProvider,
authCookie,
};
}

function initThirdwebBundleHeader() {
session.defaultSession.webRequest.onBeforeSendHeaders(
{
urls: ["https://*.thirdweb.com/*"],
},
(details, callback) => {
// TODO: should be updated to actual bundle id once signing is done
details.requestHeaders["x-bundle-id"] =
"lol.treasure.tdk-examples-connect-electron";
callback({ cancel: false, requestHeaders: details.requestHeaders });
},
);
}

function createWindow(): void {
// Create the browser window.
mainWindow = new BrowserWindow({
Expand Down Expand Up @@ -59,6 +137,8 @@ app.whenReady().then(() => {
// IPC test
ipcMain.on("ping", () => console.log("pong"));

initThirdwebBundleHeader();

createWindow();

app.on("activate", () => {
Expand Down
6 changes: 5 additions & 1 deletion examples/connect-electron/src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import Versions from "./components/Versions";

let started = false;

const isPackaged = import.meta.env.MODE !== "development";

function App(): JSX.Element {
useEffect(() => {
if (!started) {
Expand All @@ -16,7 +18,9 @@ function App(): JSX.Element {
return (
<>
<p>
<ConnectButton redirectUrl={`${window.location.origin}/auth/`} />
<ConnectButton
redirectUrl={`${!isPackaged && typeof window !== "undefined" ? window.location.origin : "http://localhost:5180"}/auth/`}
/>
</p>
<Versions />
</>
Expand Down
1 change: 1 addition & 0 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"i18next": "catalog:",
"i18next-browser-languagedetector": "catalog:",
"input-otp": "catalog:",
"jwt-decode": "catalog:",
"react-i18next": "catalog:",
"tailwind-merge": "catalog:"
},
Expand Down
42 changes: 31 additions & 11 deletions packages/react/src/contexts/treasure.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
type WalletComponents,
startUserSessionViaLauncher,
} from "@treasure-dev/launcher";
import { startUserSessionViaLauncher } from "@treasure-dev/launcher";
import {
AnalyticsManager,
DEFAULT_TDK_API_BASE_URI,
Expand Down Expand Up @@ -42,6 +39,7 @@ import {
import { isZkSyncChain } from "thirdweb/utils";
import { type Wallet, ecosystemWallet } from "thirdweb/wallets";

import type { AuthStoredTokenWithCookieReturnType } from "thirdweb/dist/types/wallets/in-app/core/authentication/types";
import { useLauncher } from "../hooks/useLauncher";
import { i18n } from "../i18n";
import type { AnalyticsEvent, Config, ContextValues } from "../types";
Expand Down Expand Up @@ -71,6 +69,8 @@ export const useTreasure = () => {

type Props = PropsWithChildren<Config>;

let hasSetUrlParams = false;

const TreasureProviderInner = ({
children,
appName,
Expand Down Expand Up @@ -195,26 +195,43 @@ const TreasureProviderInner = ({
);

const onWalletComponentsUpdated = useCallback(
(walletComponents: WalletComponents) => {
async (
authResult: AuthStoredTokenWithCookieReturnType,
authProvider: string,
walletId: string,
authCookie: string,
) => {
if (activeWallet) {
console.debug(
"[TreasureProvider] There is already an active wallet, skipping updating with launcher wallet components",
);
return;
}
if (hasSetUrlParams) {
return;
}
hasSetUrlParams = true;
console.debug(
"[TreasureProvider] Updating wallet with launcher wallet components",
);

authResult.storedToken.cookieString = authCookie;
const encoded = encodeURIComponent(JSON.stringify(authResult));
const url = new URL(window.location.href);
url.searchParams.set("walletId", walletComponents.walletId);
url.searchParams.set("authProvider", walletComponents.authProvider);
url.searchParams.set("authCookie", walletComponents.authCookie);
window.history.pushState({}, "", url);
url.searchParams.set("authResult", encoded);
url.searchParams.set("authProvider", authProvider);
url.searchParams.set("walletId", walletId);
url.searchParams.set("authCookie", authCookie);
window.history.pushState({}, "", url.toString());
},
[activeWallet],
);

const { isUsingTreasureLauncher, openLauncherAccountModal } = useLauncher({
const {
isUsingTreasureLauncher,
isUsingLauncherAuthToken,
openLauncherAccountModal,
} = useLauncher({
getAuthTokenOverride: launcherOptions?.getAuthTokenOverride,
getWalletComponentsOverride: launcherOptions?.getWalletComponentsOverride,
setRootElement: setEl,
Expand All @@ -228,6 +245,7 @@ const TreasureProviderInner = ({
name: EVT_TREASURECONNECT_DISCONNECTED,
properties: {
isUsingTreasureLauncher,
isUsingLauncherAuthToken,
},
})
.then((eventId) => {
Expand All @@ -248,7 +266,7 @@ const TreasureProviderInner = ({
chainId?: number,
skipCurrentUser = false,
): Promise<{ user: User | undefined; legacyProfiles: LegacyProfile[] }> => {
if (isUsingTreasureLauncher) {
if (isUsingLauncherAuthToken) {
console.debug(
"[TreasureProvider] Skipping login because launcher is being used",
);
Expand Down Expand Up @@ -345,6 +363,7 @@ const TreasureProviderInner = ({
name: EVT_TREASURECONNECT_CONNECTED,
properties: {
isUsingTreasureLauncher,
isUsingLauncherAuthToken,
},
})
.then((eventId) => {
Expand Down Expand Up @@ -409,6 +428,7 @@ const TreasureProviderInner = ({
userAddress: undefined,
}),
isUsingTreasureLauncher,
isUsingLauncherAuthToken,
logIn,
logOut,
updateUser: (partialUser) =>
Expand Down
10 changes: 2 additions & 8 deletions packages/react/src/hooks/useConnect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const useConnect = (options?: Options) => {
logOut,
setRootElement,
isUsingTreasureLauncher,
isUsingLauncherAuthToken,
openLauncherAccountModal,
trackCustomEvent,
} = useTreasure();
Expand All @@ -60,13 +61,6 @@ export const useConnect = (options?: Options) => {
: [chain];

const openConnectModal = () => {
if (isUsingTreasureLauncher) {
console.debug(
"[useConnect] openConnectModal cannot be used when Treasure Launcher is being used",
);
return;
}

trackCustomEvent({
name: EVT_TREASURECONNECT_UI_LOGIN,
});
Expand All @@ -89,7 +83,7 @@ export const useConnect = (options?: Options) => {
},
});

if (isUsingTreasureLauncher) {
if (isUsingLauncherAuthToken) {
openLauncherAccountModal(connectModalSize);
return;
}
Expand Down
33 changes: 28 additions & 5 deletions packages/react/src/hooks/useLauncher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,22 @@ import {
getTreasureLauncherAuthToken,
getTreasureLauncherWalletComponents,
} from "@treasure-dev/launcher";
import { type ReactNode, useEffect } from "react";
import { jwtDecode } from "jwt-decode";
import { type ReactNode, useEffect, useState } from "react";
import type { AuthStoredTokenWithCookieReturnType } from "thirdweb/dist/types/wallets/in-app/core/authentication/types";
import { AccountModal } from "../components/launcher/AccountModal";

type Props = {
getAuthTokenOverride?: () => string | undefined;
getWalletComponentsOverride?: () => WalletComponents | undefined;
setRootElement: (el: ReactNode) => void;
onAuthTokenUpdated: (authToken: string) => void;
onWalletComponentsUpdated: (walletComponents: WalletComponents) => void;
onWalletComponentsUpdated: (
authResult: AuthStoredTokenWithCookieReturnType,
authProvider: string,
walletId: string,
authCookie: string,
) => Promise<void>;
};

export const useLauncher = ({
Expand All @@ -22,11 +29,13 @@ export const useLauncher = ({
onWalletComponentsUpdated,
}: Props) => {
const authToken = getAuthTokenOverride?.() ?? getTreasureLauncherAuthToken();
const isUsingTreasureLauncher =
authToken !== undefined && authToken.length > 0;
const walletComponents: WalletComponents | undefined =
getWalletComponentsOverride?.() ?? getTreasureLauncherWalletComponents();

const [isUsingTreasureLauncher, setIsUsingTreasureLauncher] = useState(false);
const [isUsingLauncherAuthToken, setIsUserLauncherAuthToken] =
useState(false);

const openLauncherAccountModal = (size?: "lg" | "xl" | "2xl" | "3xl") => {
if (!isUsingTreasureLauncher) {
console.debug(
Expand All @@ -47,13 +56,26 @@ export const useLauncher = ({
useEffect(() => {
if (walletComponents) {
console.debug("[useLauncher] Using launcher wallet components");
onWalletComponentsUpdated(walletComponents);
const authResult: AuthStoredTokenWithCookieReturnType = jwtDecode(
walletComponents.authCookie,
);
onWalletComponentsUpdated(
authResult,
walletComponents.authProvider,
walletComponents.walletId,
walletComponents.authCookie,
);
setIsUsingTreasureLauncher(true);
return;
}
if (authToken) {
console.debug("[useLauncher] Using launcher auth token");
setIsUsingTreasureLauncher(true);
setIsUserLauncherAuthToken(true);
onAuthTokenUpdated(authToken);
return;
}
setIsUsingTreasureLauncher(false);
}, [
authToken,
onAuthTokenUpdated,
Expand All @@ -63,6 +85,7 @@ export const useLauncher = ({

return {
isUsingTreasureLauncher,
isUsingLauncherAuthToken,
openLauncherAccountModal,
};
};
Loading

0 comments on commit 14b07bf

Please sign in to comment.