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: siwe with viem #1997

Draft
wants to merge 8 commits into
base: _daniel/viem-wagmi-upgrade
Choose a base branch
from
Draft
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
2 changes: 0 additions & 2 deletions examples/with-next-siwe-iron-session/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
},
"dependencies": {
"@rainbow-me/rainbowkit": "workspace:*",
"ethers": "^5.6.8",
"iron-session": "^6.3.1",
"next": "^14.2.3",
"react": "^18.3.0",
"react-dom": "^18.3.0",
"siwe": "^2.1.4",
"viem": "2.12.5",
"wagmi": "^2.9.8",
"@tanstack/react-query": "^5.28.4"
Expand Down
10 changes: 3 additions & 7 deletions examples/with-next-siwe-iron-session/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
RainbowKitAuthenticationProvider,
AuthenticationStatus,
} from '@rainbow-me/rainbowkit';
import { SiweMessage } from 'siwe';
import { createSiweMessage } from 'viem/siwe';

import { config } from '../wagmi';

Expand Down Expand Up @@ -60,21 +60,17 @@ export default function App({ Component, pageProps }: AppProps) {
},

createMessage: ({ nonce, address, chainId }) => {
return new SiweMessage({
return createSiweMessage({
domain: window.location.host,
address,
statement: 'Sign in with Ethereum to the app.',
uri: window.location.origin,
version: '1',
chainId,
nonce,
nonce
});
},

getMessageBody: ({ message }) => {
return message.prepareMessage();
},

verify: async ({ message, signature }) => {
verifyingRef.current = true;

Expand Down
4 changes: 2 additions & 2 deletions examples/with-next-siwe-iron-session/src/pages/api/nonce.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { withIronSessionApiRoute } from 'iron-session/next';
import { NextApiRequest, NextApiResponse } from 'next';
import { generateNonce } from 'siwe';
import { generateSiweNonce } from 'viem/siwe';
import { ironOptions } from '../../../lib/iron';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const { method } = req;
switch (method) {
case 'GET':
req.session.nonce = generateNonce();
req.session.nonce = generateSiweNonce();
await req.session.save();
res.setHeader('Content-Type', 'text/plain');
res.send(req.session.nonce);
Expand Down
23 changes: 16 additions & 7 deletions examples/with-next-siwe-iron-session/src/pages/api/verify.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,34 @@
import { withIronSessionApiRoute } from 'iron-session/next';
import { NextApiRequest, NextApiResponse } from 'next';
import { SiweMessage } from 'siwe';
import { publicActions } from 'viem';
import { parseSiweMessage } from 'viem/siwe';

import { ironOptions } from '../../../lib/iron';
import { config } from '../../wagmi';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const { method } = req;
switch (method) {
case 'POST':
try {
const { message, signature } = req.body;
const siweMessage = new SiweMessage(message);
const { success, error, data } = await siweMessage.verify({
const { message, signature, address } = req.body;

const publicClient = config.getClient().extend(publicActions);

const valid = await publicClient.verifyMessage({
address,
message,
signature,
});

if (!success) throw error;
if (!valid) {
throw new Error('Invalid message');
}

if (data.nonce !== req.session.nonce)
if (parseSiweMessage(message).nonce !== req.session.nonce)
return res.status(422).json({ message: 'Invalid nonce.' });

req.session.siwe = data;
req.session.siwe = { address };
await req.session.save();
res.json({ ok: true });
} catch (_error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import 'iron-session';
import { SiweMessage } from 'siwe';
import { Address } from 'viem';

declare module 'iron-session' {
interface IronSessionData {
nonce?: string;
siwe?: SiweMessage;
siwe?: { address: Address };
}
}
2 changes: 0 additions & 2 deletions examples/with-next-siwe-next-auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@
"dependencies": {
"@rainbow-me/rainbowkit": "workspace:*",
"@rainbow-me/rainbowkit-siwe-next-auth": "workspace:*",
"ethers": "^5.6.8",
"next": "^14.2.3",
"next-auth": "4.24.5",
"react": "^18.3.0",
"react-dom": "^18.3.0",
"siwe": "^2.1.4",
"viem": "2.12.5",
"wagmi": "^2.9.8",
"@tanstack/react-query": "^5.28.4"
Expand Down
1 change: 0 additions & 1 deletion examples/with-next-siwe-next-auth/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
GetSiweMessageOptions,
} from '@rainbow-me/rainbowkit-siwe-next-auth';


import { config } from '../wagmi';

const getSiweMessageOptions: GetSiweMessageOptions = () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,41 +7,58 @@ import { NextApiRequest, NextApiResponse } from 'next';
import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { getCsrfToken } from 'next-auth/react';
import { SiweMessage } from 'siwe';
import { ByteArray, Hex, Signature, publicActions } from 'viem';
import { parseSiweMessage } from 'viem/siwe';

import { config } from '../../../wagmi';

export function getAuthOptions(req: IncomingMessage): NextAuthOptions {
const providers = [
CredentialsProvider({
async authorize(credentials) {
try {
const siwe = new SiweMessage(
JSON.parse(credentials?.message || '{}')
);
const message = credentials?.message ?? '';

const { domain, nonce, address } = parseSiweMessage(message);

if (!address) return null;

const nextAuthUrl =
process.env.NEXTAUTH_URL ||
(process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: null);

if (!nextAuthUrl) {
return null;
}

const nextAuthHost = new URL(nextAuthUrl).host;
if (siwe.domain !== nextAuthHost) {

if (domain !== nextAuthHost) {
return null;
}

if (
siwe.nonce !==
(await getCsrfToken({ req: { headers: req.headers } }))
nonce !== (await getCsrfToken({ req: { headers: req.headers } }))
) {
return null;
}

await siwe.verify({ signature: credentials?.signature || '' });
const publicClient = config.getClient().extend(publicActions);

const valid = await publicClient.verifyMessage({
address,
message,
signature: credentials?.signature as Hex | ByteArray | Signature,
});

if (!valid) {
throw new Error('Invalid message');
}

return {
id: siwe.address,
id: address,
};
} catch (e) {
return null;
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@
"autoprefixer": "^10.4.16",
"esbuild": "^0.20.2",
"esbuild-plugin-replace": "^1.4.0",
"ethers": "^5.6.8",
"husky": "^8.0.3",
"jsdom": "^23.0.1",
"lokijs": "^1.5.12",
Expand Down
2 changes: 0 additions & 2 deletions packages/example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
"@rainbow-me/rainbowkit-siwe-next-auth": "workspace:*",
"@rainbow-me/rainbow-button": "workspace:*",
"@tanstack/react-query": "^5.28.4",
"ethers": "^5.6.8",
"next": "^14.2.3",
"next-auth": "4.24.5",
"react": "^18.3.0",
"react-dom": "^18.3.0",
"siwe": "^2.1.4",
"viem": "2.12.5",
"wagmi": "^2.9.8"
},
Expand Down
1 change: 0 additions & 1 deletion packages/example/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ const CustomAvatar: AvatarComponent = ({ size }) => {
const getSiweMessageOptions: GetSiweMessageOptions = () => ({
statement: 'Sign in to the RainbowKit Demo',
});

const themes = [
{ name: 'light', theme: lightTheme },
{ name: 'dark', theme: darkTheme },
Expand Down
35 changes: 26 additions & 9 deletions packages/example/src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,41 +7,58 @@ import { NextApiRequest, NextApiResponse } from 'next';
import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { getCsrfToken } from 'next-auth/react';
import { SiweMessage } from 'siwe';
import { ByteArray, Hex, Signature, publicActions } from 'viem';
import { parseSiweMessage } from 'viem/siwe';

import { config } from '../../../wagmi';

export function getAuthOptions(req: IncomingMessage): NextAuthOptions {
const providers = [
CredentialsProvider({
async authorize(credentials) {
try {
const siwe = new SiweMessage(
JSON.parse(credentials?.message || '{}'),
);
const message = credentials?.message ?? '';

const { domain, nonce, address } = parseSiweMessage(message);

if (!address) return null;

const nextAuthUrl =
process.env.NEXTAUTH_URL ||
(process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: null);

if (!nextAuthUrl) {
return null;
}

const nextAuthHost = new URL(nextAuthUrl).host;
if (siwe.domain !== nextAuthHost) {

if (domain !== nextAuthHost) {
return null;
}

if (
siwe.nonce !==
(await getCsrfToken({ req: { headers: req.headers } }))
nonce !== (await getCsrfToken({ req: { headers: req.headers } }))
) {
return null;
}

await siwe.verify({ signature: credentials?.signature || '' });
const publicClient = config.getClient().extend(publicActions);

const valid = await publicClient.verifyMessage({
address,
message,
signature: credentials?.signature as Hex | ByteArray | Signature,
});

if (!valid) {
throw new Error('Invalid message');
}

return {
id: siwe.address,
id: address,
};
} catch (e) {
console.error('siwe authorization failed', e);
Expand Down
6 changes: 2 additions & 4 deletions packages/rainbowkit-siwe-next-auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,10 @@
"@rainbow-me/rainbowkit": "2.0.x || 2.1.x",
"next-auth": ">=4.21.0 <5",
"react": ">=18",
"siwe": "^2.1.4"
"viem": ">=2.12.0"
},
"devDependencies": {
"@rainbow-me/rainbowkit": "workspace:*",
"ethers": "^5.6.8",
"siwe": "^2.1.4"
"@rainbow-me/rainbowkit": "workspace:*"
},
"repository": {
"type": "git",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@ import {
} from '@rainbow-me/rainbowkit';
import { getCsrfToken, signIn, signOut, useSession } from 'next-auth/react';
import React, { ReactNode, useMemo } from 'react';
import { SiweMessage } from 'siwe';
import type { Address } from 'viem';
import { type CreateSiweMessageParameters, createSiweMessage } from 'viem/siwe';

type UnconfigurableMessageOptions = {
address: string;
address: Address;
chainId: number;
nonce: string;
};

type ConfigurableMessageOptions = Partial<
Omit<SiweMessage, keyof UnconfigurableMessageOptions>
> & {
[_Key in keyof UnconfigurableMessageOptions]?: never;
};
type ConfigurableMessageOptions = Omit<
CreateSiweMessageParameters,
keyof UnconfigurableMessageOptions
>;

export type GetSiweMessageOptions = () => ConfigurableMessageOptions;
export type GetSiweMessageOptions = () => Partial<ConfigurableMessageOptions>;

interface RainbowKitSiweNextAuthProviderProps {
enabled?: boolean;
Expand Down Expand Up @@ -49,19 +49,27 @@ export function RainbowKitSiweNextAuthProvider({
nonce,
};

return new SiweMessage({
...defaultConfigurableOptions,
const siweMessageOptions = getSiweMessageOptions?.() ?? {};

return createSiweMessage({
// Use provided SIWE message options, fallback to defaults if undefined
domain:
siweMessageOptions.domain ?? defaultConfigurableOptions.domain,
uri: siweMessageOptions.uri ?? defaultConfigurableOptions.uri,
version:
siweMessageOptions.version ?? defaultConfigurableOptions.version,
statement:
siweMessageOptions.statement ??
defaultConfigurableOptions.statement,

// Spread custom SIWE message options provided by the consumer
...getSiweMessageOptions?.(),
...siweMessageOptions,

// Spread unconfigurable options last so they can't be overridden
...unconfigurableOptions,
});
},

getMessageBody: ({ message }) => message.prepareMessage(),

getNonce: async () => {
const nonce = await getCsrfToken();
if (!nonce) throw new Error();
Expand All @@ -74,7 +82,7 @@ export function RainbowKitSiweNextAuthProvider({

verify: async ({ message, signature }) => {
const response = await signIn('credentials', {
message: JSON.stringify(message),
message,
redirect: false,
signature,
});
Expand Down
Loading