better-auth-eth
Get started
Passkey accounts on an EVM chain, for Better Auth. One passkey signs a person up, signs them in, and signs what they do on the chain.
What it is
A Better Auth plugin, a small browser SDK and three contracts. Together they give every user of your app an ERC-4337 smart account whose only keys are their passkeys.
- No password and no wallet extension. The person only ever sees their device's passkey prompt.
- Your server never holds a user's key, so it cannot act on the chain in their name.
- Contracts can tell which passkey approved a call, not only which account made it.
This site is the demo: a guest book where every message is signed with a passkey and recorded on a local chain.
How it works
- 1Sign upThe browser creates a passkey. The plugin creates the user, stores the passkey's public key, and picks a random salt that fixes the address of the person's account on the chain. Nothing is deployed yet.
- 2First actionThe SDK builds a user operation and the passkey signs it. The operation carries the server's approval of that first passkey, so the factory deploys the account and runs the action in the same transaction.
- 3Every action afterOne prompt each. The account contract checks the passkey's signature on the chain, and the contract being called can read which passkey signed.
Who holds what:
| Thing | Held by | Note |
|---|---|---|
| The passkey's private key | The person's device or password manager | Never leaves it. The server only has the public key. |
| The session | Better Auth, on your server | Says who is signed in. It cannot sign an action. |
| The first-key approval key | Your server | One key for the whole service. It can only say "this first passkey belongs to this account". |
| The bundler's key | The bundler | Pays to submit operations. It cannot change them: the chain checks every signature. |
Run the demo
You need Node 22 or newer, pnpm, Docker and Foundry.
pnpm install
pnpm dev # chain, contracts, bundler, API and web appThen open http://localhost:3310. Browsers allow passkeys on plain localhost; any other host needs https.
A passkey made on localhost is offered to every app you run there. To give the demo a domain of its own, install mkcert and run pnpm domain:setup once: pnpm dev then serves it at https://guestbook.localhost through a small Caddy proxy.
1. Add the plugin to Better Auth
The plugin knows nothing about your chain. You give it three functions: how to compute an account's address, how to approve a first passkey, and how to check which keys an account holds.
import { betterAuth } from "better-auth";
import { ethPasskey } from "@better-auth-eth/plugin";
export const auth = betterAuth({
database,
// no emailAndPassword: the plugin creates and opens accounts with a passkey
plugins: [
ethPasskey({
rpName: "Guestbook",
// A passkey belongs to one site. Say which host each origin may use.
rpIdFor: (origin) => (origin === "http://localhost:3310" ? "localhost" : undefined),
expectedOrigins: ["http://localhost:3310"],
// The three things the plugin needs to know about your chain:
webAuthnVerifier, // address of the ERC-7913 WebAuthn verifier
accountAddress: (chainSalt) => // the factory's address for a salt
publicClient.readContract({ address: factory, abi, functionName: "accountAddress", args: [chainSalt] }),
approveFirstKey: async ({ chainSalt, key }) => ({
// signed with the server's own key: "this first passkey belongs to this person"
local: await serverKey.signTypedData({
domain: { name: "PasskeyAccountFactory", version: "1", chainId, verifyingContract: factory },
types: { CreateAccount: [{ name: "salt", type: "bytes32" }, { name: "keyHash", type: "bytes32" }] },
primaryType: "CreateAccount",
message: { salt: chainSalt, keyHash: keccak256(key) },
}),
}),
accountHasKey: ({ account, key }) => readKeysOf(account).then((keys) => keys.includes(key)),
}),
],
});It adds two fields to the user (chainSalt and account) and one table, signingPasskey. Run Better Auth's migration after adding it.
2. Add the client plugin
import { createAuthClient } from "better-auth/react";
import { ethPasskeyClient } from "@better-auth-eth/plugin/client";
export const authClient = createAuthClient({ plugins: [ethPasskeyClient()] });
// The SDK reaches the plugin through one small function.
export async function passkeyPlugin<T>(path: string, body?: unknown): Promise<T> {
const { data, error } = await authClient.$fetch<T>("/eth-passkey/" + path, body === undefined ? { method: "GET" } : { method: "POST", body });
if (error) throw new Error(error.message);
return data as T;
}3. Sign up and sign in
Both functions leave the person signed in with a normal Better Auth session.
import { signInWithPasskey, signUpWithPasskey } from "@better-auth-eth/account";
// One prompt: creates the passkey, the user and their session.
await signUpWithPasskey(passkeyPlugin, { name: "Ada Lovelace", email: "ada@example.com" });
// One prompt, nothing to type: the browser offers the passkeys it holds for this site.
await signInWithPasskey(passkeyPlugin);4. Send an action
The browser builds, signs and sends the operation, as a wallet would. Your server is not involved, apart from forwarding the request to the bundler if you choose to keep everything on one origin.
import { createPasskeyAccount } from "@better-auth-eth/account";
import { encodeFunctionData } from "viem";
const account = createPasskeyAccount({
plugin: passkeyPlugin,
network: "local", // the key of your approvals in approveFirstKey
chain: { id: 73571, name: "Local Besu chain" },
rpcUrl: location.origin + "/api/rpc",
bundlerUrl: location.origin + "/api/bundler",
factory,
});
// Builds a user operation, asks the passkey to sign it, sends it, waits for it.
const result = await account.send([
{ to: guestBook, data: encodeFunctionData({ abi, functionName: "sign", args: ["hello, wall"] }) },
]);
result.success; // true once it is in a block
result.transactionHash;
result.via; // "passkey" (one prompt) or "session" (none)
result.signedBy?.keyId; // which passkey signed, when one didThe account object also has status() (address, passkeys, deployed or not), addPasskey() (a second device, approved by an existing passkey) and resend(op) for replay tests.
5. Read who signed, in your contract
The call arrives from the person's account, so msg.sender is the account. During the operation the account also exposes the id of the passkey that signed it.
contract GuestBook {
PasskeyAccountFactory public immutable factory;
uint256 public count;
function sign(string calldata message) external returns (uint256 id) {
// Only accounts made by the factory.
if (!factory.isAccount(msg.sender)) revert NotAnAccount(msg.sender);
PasskeyAccount account = PasskeyAccount(payable(msg.sender));
// The passkey that signed the operation now running. Zero when a module
// of the account acted instead: then currentValidator() names the
// validator module that approved it.
bytes32 keyId = account.currentKeyId();
id = ++count;
emit Signed(id, msg.sender, keyId, account.currentValidator(), message, uint64(block.timestamp));
}
}6. Modules (ERC-7579)
The account accepts standard ERC-7579 modules: validators (another way to approve an operation, such as a session key), executors (a contract allowed to act for the account) and fallback handlers (extra functions). Passkeys are built into the account and are not a module, so the account works with nothing installed, and removing a module can never lock a person out.
// Install a validator module (type 1). The account calls itself, in an
// operation a passkey signs: one prompt.
await account.send([
{
to: accountAddress,
data: encodeFunctionData({
abi: parseAbi(["function installModule(uint256 moduleTypeId, address module, bytes initData)"]),
functionName: "installModule",
args: [1n, sessionModule, initData],
}),
},
]);
// From then on the module approves operations whose nonce key starts with
// its address: nonce = <module address, 20 bytes> <key, 4 bytes> <sequence, 8 bytes>
const key = BigInt(sessionModule) << 32n;
const nonce = await entryPoint.read.getNonce([accountAddress, key]);Three rules hold whatever a module does, and the contract tests check each one against a module that approves everything:
- Only a passkey changes the account. Adding or removing a passkey or a module needs an operation a passkey signed. An operation a module approved, or an executor acting for the account, is refused.
- Apps can tell the difference.
currentKeyId()is zero unless a passkey signed the calls now running. The wall labels such messages "Sent by a module". - No delegate calls and no hooks. Both are optional in the standard and both could get around the first rule or block the account, so they are left out.
// In your contract: refuse anything a passkey did not sign itself.
if (PasskeyAccount(payable(msg.sender)).currentKeyId() == bytes32(0)) revert PasskeyRequired();The SDK sends every operation through the account's executeUserOp hook. That is what ties the passkey's authority to one operation, so another operation in the same bundle cannot borrow it. One module ships with the demo: session keys, below.
7. Apps and roles
Around the accounts sits a small auth stack, all of it on the chain: a web account becomes an on-chain account, and that account can hold a role in each app. One contract, the Registry, holds both lists.
- Apps. The app contracts that belong to the stack. An app registers once, and whoever registers it becomes its admin. An admin can be a person's account, a multisig or any other contract.
- Roles. One number per person and app. The app's admin sets it. The app decides what the number means.
contract GuestBook {
uint256 public constant MODERATOR = 1; // the number means what this app says it means
Registry public immutable registry;
function setHidden(uint256 id, bool hidden_) external {
// What role does the caller have in this app?
if (registry.roleOf(address(this), msg.sender) < MODERATOR) revert NotAModerator(msg.sender);
hidden[id] = hidden_;
emit Moderated(id, msg.sender, hidden_);
}
}Who may register an app is an entry rule, a small contract the registry takes when it is deployed: open to anyone, managed by an approver, or a rule of your own.
// Chosen when the stack is deployed, and final. The demo uses the managed rule.
IEntryRule rule = new ApprovedEntry(authServer); // managed: each registration needs the approver's signature
// IEntryRule rule = new OpenEntry(); // permissionless: anyone may register an app
// IEntryRule rule = new YourRule(...); // anything with allows(caller, subject, proof)
Registry registry = new Registry(factory, rule); // apps and roles; also names the factory and the ruleIn the demo the rule is managed by the server's key, and the server approves the first signed-in person who asks: they register the guest book from the Roles page and become its admin. Its one role is moderator: a moderator may hide a message from the wall. When the admin is a person's account, registering and giving roles insist on a passkey, so a module of the account cannot do it.
// Register the app. The server approves it (managed rule); the caller becomes the app's admin.
const { proof } = await fetch("/api/app/approval", { method: "POST" }).then((r) => r.json());
await account.send([{ to: registry, data: encodeFunctionData({ abi, functionName: "register", args: [guestBook, proof] }) }]);
// The admin gives a person a role in the app. One passkey prompt.
await account.send([{ to: registry, data: encodeFunctionData({ abi, functionName: "setRole", args: [guestBook, person, 1n] }) }]);One stack serves one website. The contract addresses are the server's configuration, and the page reads them from /api/config.
8. Sessions
A prompt for every action is right for the ones that matter and tiring for the rest. A session lets one browser sign a few chosen calls without a prompt, for a few hours.
- The key. The browser makes a P-256 key with WebCrypto, marked non-extractable, and keeps it in IndexedDB. No script can read it and it never leaves that browser.
- The grant. A passkey signs one operation that tells the account's
SessionKeysmodule: this key, these functions, until this time. A day at most. - The limit. The module checks every call of a session operation against that list. A session can never touch the account itself, so passkeys, modules and roles stay behind the passkey.
const account = createPasskeyAccount({ ...options, sessionModule: sessionKeys });
// One passkey prompt: grant a new key in this browser the right to post, for 8 hours,
// and post the first message in the same operation.
await account.startSession({
permissions: [{ to: guestBook, selector: toFunctionSelector("sign(string)") }],
ttlSeconds: 8 * 3600,
then: [{ to: guestBook, data }],
});
// Until it expires, a call the session covers is signed here, with no prompt.
const result = await account.send([{ to: guestBook, data }]);
result.via; // "session"
// Anything else still asks the passkey. So does this, always:
await account.send(calls, { via: "passkey" });
await account.endSession(); // deletes the key in this browser: no prompt, nobody has a copyIn the demo, signing in or signing up asks for a second passkey touch, unless you untick it, and that touch opens a session for posting. It takes two touches because one touch signs one thing: the first proves who you are to the server, the second signs the grant on the chain. Without a session, the first post asks the passkey and can open one then. The wall labels each message "Signed with passkey" or "Signed in a session": the contract records which. Signing out deletes the key. Settings list every session the chain knows for your account, and revoke one opened on another device.
contract SessionKeys is IERC7579Validator {
uint48 public constant MAX_DURATION = 1 days;
// Called by the account, in an operation a passkey signed.
function grant(bytes32 x, bytes32 y, uint48 validUntil, Permission[] calldata permissions) external;
function revoke(bytes32 keyId) external;
// Called by the account for an operation whose nonce key names this module.
function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external view returns (uint256) {
// 1. the key was granted, for this account
// 2. every call in the batch is one it was granted, with no value
// 3. the signature is the key's, over sha256(userOpHash), as WebCrypto signs
// and the EntryPoint refuses the operation after validUntil
}
}What a session may do is exactly what a malicious script on the page could do while it is open, so keep the list short. On a chain with fees, also cap what a session operation may spend on gas: this module does not, because gas is free here.
Endpoints
All under Better Auth's base path, /api/auth by default.
| Endpoint | Session | What it does |
|---|---|---|
| POST /eth-passkey/sign-up-options | No | Takes a name and an email. Returns WebAuthn options for a new passkey. |
| POST /eth-passkey/sign-up-verify | No | Checks the new passkey, creates the user, opens a session, returns the first-key approval. |
| POST /eth-passkey/sign-in-options | No | Returns WebAuthn options with no credential list: the browser offers what it holds. |
| POST /eth-passkey/sign-in-verify | No | Finds the passkey, checks the signature, opens a session. |
| GET /eth-passkey/keys | Yes | The person's account address, salt and passkeys. |
| GET /eth-passkey/first-key-approval | Yes | The approval again, for an account that is deployed later. |
| POST /eth-passkey/register-options | Yes | Starts adding another passkey. |
| POST /eth-passkey/register-verify | Yes | Stores the extra passkey as pending. |
| POST /eth-passkey/confirm-key | Yes | Marks an extra passkey active once the account holds it on the chain. |
What the chain needs
- The ERC-4337 EntryPoint v0.8 and a bundler. The demo runs Alto.
- The built-in P-256 check (EIP-7951, in the Osaka upgrade). It makes checking a passkey cost about 21,000 gas. Without it the contracts fall back to a Solidity check that costs roughly 370,000.
- A way to pay for gas. The demo chain has free gas. On a chain with fees you need a paymaster or funded accounts.
Limits
- No recovery. A person who loses every passkey cannot get back in. Encourage a second passkey.
- One site. A passkey only works on the host it was created for.
- The page is trusted. The passkey prompt does not show what is being signed, so whoever serves the page decides what it asks the passkey to sign. A sign-in challenge can never pass as an on-chain action, as long as your server issues it.
- Emails are not verified, and the demo's keys are throwaway keys committed to the repository. Do not reuse them.