Bunker mode in an extension
An attacker who can turn a public key into a private key needs the public key first. On most
chains an address is only a hash of it, so the key stays unseen until the account signs
something. @anywalletkit/bunker tracks
that, and the @anywalletkit/extension-kit/bunker entry puts it into a
browser extension:
- A journal of every signature the wallet makes, written before the key signs.
- A scan that says which accounts are still sealed, which are exposed, and which cannot be sealed at all.
- Protected accounts. Sites cannot see them, and they sign one thing: a full sweep to a sealed address of the same wallet.
It is a separate entry. An extension that does not import it gets the kit as it was, and the
two packages it needs are optional. Snippets come from
examples/extension-kit,
which our CI typechecks and tests.
npm install @anywalletkit/bunker @anywalletkit/kitimport { ExposureLedger, exposureKey, type BunkerRequest, type BunkerRule, type ExposureEntry } from '@anywalletkit/bunker'import { ApprovalQueue, NetworksTable, PermissionStore, RequestRouter, chromeJsonStorage, createSignHandler, macJsonStorage, type EvmNetwork, type MacJsonStorage, type SignDeps, type StorageAreaLike, type StorageVersionLedger,} from '@anywalletkit/extension-kit'import { bunkerLedgerStorage, extensionBunker, type BunkerAccount, type BunkerSweep, type ExtensionBunker } from '@anywalletkit/extension-kit/bunker'import type { Keyring } from '@anywalletkit/keyring'The journal
Section titled “The journal”The journal holds no secret: addresses and reasons. But it must not be editable. An entry taken
out, or an older list put back, would turn an exposed key into a “sealed” one. So keep it where
the kit keeps state a page must not change: a macJsonStorage store, with your
storageVersionLedger against rollback.
/** * After unlock, and again at every worker start: the journal of what this wallet signed. * It is kept like your settings and site grants: signed, with the version ledger against rollback. * `BunkerLedgerError` when what is stored cannot be trusted; it never loads as an empty journal. */export async function openLedger(local: StorageAreaLike, key: MacKey, versions: StorageVersionLedger): Promise<ExposureLedger> { const store = macJsonStorage<ExposureEntry[]>(chromeJsonStorage(local, 'my-wallet.bunker-ledger'), { label: 'bunker-ledger', key, versions }) return ExposureLedger.load(bunkerLedgerStorage(store))}Open it in the service worker after unlock (the check needs the vault key), and again at every worker start. Keep one instance: it holds the list in memory.
bunkerLedgerStorage loads only a value that verifies. Anything else throws
BunkerLedgerError; a refused journal is never read as an empty one.
error.state |
What happened | What to do |
|---|---|---|
no-key |
The wallet is locked | Open the journal after unlock |
unsigned |
The value carries no check | Moving from a plain store: sign it once (store.read(), then store.write(value)). Otherwise treat it as invalid |
invalid |
Edited, or signed under another vault key | Tell the user. Start again with store.write([]) and scan |
stale |
An older list was put back, or the list was deleted | The same |
malformed |
Not a list of journal entries | The same |
After a journal is lost, the scan still finds transactions. It cannot find a login signature: only the journal knew about it. Say so on the screen where the user starts again.
Who is protected
Section titled “Who is protected”The adapter does not decide which accounts are in the bunker. You do, with a protect function:
by the user’s choice, or by balance. Keep your list signed too, and read a list that does not
verify as “every account is protected”.
/** Which accounts are in the bunker: your wallet's own list, one entry per key, signed like the ledger. */export function safeAccounts(store: MacJsonStorage<string[]>) { const read = async (): Promise<Set<string> | null> => { const found = await store.read() if (found.state === 'empty') return new Set() return found.state === 'ok' && Array.isArray(found.value) ? new Set(found.value) : null // null: the list cannot be trusted } const change = async (update: (list: Set<string>) => void): Promise<void> => { const list = await read() if (!list) throw new Error('The list of protected accounts cannot be read. Ask the user which accounts stay protected, then reset().') update(list) await store.write([...list]) } return { /** The adapter's `protect`. A list that does not verify protects every account. */ isProtected: async ({ chain, address }: BunkerAccount): Promise<boolean> => (await read())?.has(exposureKey(chain, address)) ?? true, /** From your own screen only: put an account in the bunker. */ protect: (account: BunkerAccount) => change((list) => { list.add(exposureKey(account.chain, account.address)) }), /** From your own screen only: the way out. The account then signs, connects and sends like any other. */ release: (account: BunkerAccount) => change((list) => { list.delete(exposureKey(account.chain, account.address)) }), /** From your own screen only: write the whole list again, after the stored one was refused. */ reset: (accounts: BunkerAccount[]) => store.write(accounts.map((a) => exposureKey(a.chain, a.address))), }}export type SafeAccounts = ReturnType<typeof safeAccounts>exposureKey is one value per key: the same for an EVM address on every network, and for a
TON address in its raw (0:ab…) and friendly (UQ…) forms.
The way out is this list. Bunker mode keeps no state of its own that could lock funds. When your own screen takes an account off the list, the next request finds it unprotected: it signs, connects and sends like any other account, and you can sweep it. No site can do this, because the request router has no method that reaches your list.
Wire it in
Section titled “Wire it in”/** One adapter for the worker. Keep the keyring it returns; give the raw one to nothing else. */export function createBunker(keyring: Keyring, parts: BunkerParts) { const bunker = extensionBunker(parts.ledger, { protect: parts.safe.isProtected, isSealedDestination: parts.isSealedDestination, isFullSweep: parts.isFullSweep, own: (origin) => origin === parts.ownOrigin, ...(parts.notify ? { onWarning: parts.notify } : {}), }) // Every account this keyring opens is journaled and judged before its key signs, on every chain. return { bunker, keyring: bunker.keyring(keyring) }}/** The request router with the three site-facing guards in place. */export function createGuardedRouter(bunker: ExtensionBunker, parts: GuardedRouterParts) { // What sites may see of the grants. Your Solana, TON Connect, Tron, Bitcoin and NEAR providers read this view too. const permissions = bunker.permissions(parts.permissions) const router = new RequestRouter({ permissions, networks: parts.networks, approvals: parts.approvals, rpc: parts.rpc, emit: parts.emit, accounts: bunker.accounts(parts.accounts), // a protected account is never the exposed one sign: createSignHandler({ approvals: parts.approvals, rpc: parts.rpc, signerFor: bunker.signerFor(parts.signerFor) }), }) return { router, permissions }}An extension uses a key in two places. The adapter guards both, and each writes the journal before the key signs:
| Place | Guard | What goes through it |
|---|---|---|
| The account a keyring handle opens | bunker.keyring(keyring) |
Every chain and every method that signs: your Send, the swap engine, Earn modules, and the providers you write for Solana, TON Connect, Tron, Bitcoin, NEAR and WalletConnect |
The signer of createSignHandler |
bunker.signerFor(signerFor) |
personal_sign, typed data and eth_sendTransaction from sites: the only signatures the kit itself calls a key for |
Use the keyring createBunker returns everywhere, and hand the raw one to nothing else. A
router you write next year then cannot get a key that skips the journal. The guarded keyring
is applyPolicies with bunkerPolicies; pass your own policies as the
second argument of bunker.keyring and they apply after the bunker rules.
If your signerFor opens its key through the guarded keyring, as the
extension guide does, both guards run for a dApp signature. The journal
entry is one; in warn mode you are told twice, once that a site asked and once what it asked
for.
There is no single point below these two. The kit holds no key outside the sign handler, and the vault only sees that a secret was read, not what it is used for. Our build fails when the keyring, the signer or the permission store gains a public method the adapter does not classify.
When the journal cannot be saved, nothing is signed. ledgerFailure: 'continue' lets an account
that is not protected go on and tells onLedgerError; in enforce mode a protected account is
always refused.
What a protected account can do
Section titled “What a protected account can do”| It is asked to… | Result |
|---|---|
| connect to a site, or sign anything for one | dapp-request |
| sign a message or typed data (a permit, a gasless order) | off-chain-signature |
| approve or revoke | not-a-sweep |
| call a contract | unsealed-destination at the keyring account, not-a-sweep at the sign handler |
| send to an address that is not sealed and its own | unsealed-destination |
| send part of its balance | partial-spend |
| sweep everything to a sealed address of the same wallet, from your own screen | Signed, after the journal is written |
The refusal is a BunkerViolationError with rule and a message you can show. A swap or an
Earn plan fails at its first operation, after its sheet. Refuse it earlier:
await bunker.check({ kind: 'other', what: 'swap', chain: plan.fromChain, from: account }) // before reviewSwapPlanmode: 'warn' refuses nothing and hides nothing. onWarning gets the rule enforce would have
used, and the journal is still written. Use it to show users what Bunker mode would change
before you turn it on.
Hidden from sites
Section titled “Hidden from sites”A protected account is in no list a site gets:
bunker.accountskeeps it out ofeth_accounts, out of the connect sheet, and out of the check every signing request passes.bunker.permissions(store)is the permission store as sites may see it. Reads leave protected accounts out of every list: EVM, Solana, TON, Tron, Bitcoin, NEAR.grant,connectandconnectChainrefuse one. Give this view, not the store, to the router and to your own providers.
A site that asks for a protected account gets the answer it would get for an account it was
never granted (4100), so it cannot tell a protected account from one that is not there. Keep
it that way in your own providers: never pass the message of a BunkerViolationError to a page.
When the active account is protected, the connect sheet gets an empty account list. Offer the user another account there, or decline.
The stored grant is not rewritten. An account that becomes protected stops being shown at once, and is shown again to the same sites when it leaves the bunker. Tell the pages when you protect an account:
/** Your own screen puts an account in the bunker, then tells the pages that were connected to it. */export async function protectAccount(bunker: ExtensionBunker, safe: SafeAccounts, store: PermissionStore, account: BunkerAccount, emit: (origin: string, event: string, data: unknown) => void): Promise<void> { await safe.protect(account) const view = bunker.permissions(store) for (const grant of await bunker.hiddenGrants(store)) { if (grant.key === 'accounts') emit(grant.origin, 'accountsChanged', (await view.get(grant.origin))?.accounts ?? []) }}Your own providers
Section titled “Your own providers”The kit routes EVM requests. The Solana, TON Connect, Tron, Bitcoin and NEAR providers are your code, and three rules cover them:
- Keys from the guarded keyring. Every signature is then in the journal, and a protected account refuses it.
- Grants through the view. What your provider reads from
permissions.get(origin)has no protected account in it. - Store the grant before you answer a connection. A TON Connect reply hands the site the
public key and the wallet’s StateInit; a Bitcoin connection hands out the public key of each
address. The view writes that to the journal (
dapp-session) before the grant is stored.
/** * A TON Connect `connect` in your own provider code. The reply hands the site the public key, so store * the grant first: the view refuses a protected account, and writes the hand-out to the ledger. */export async function connectTon(permissions: PermissionStore, origin: string, address: string, reply: () => Promise<void>): Promise<void> { await permissions.connectChain(origin, 'tonAccounts', [address], 'eip155:1') // BunkerViolationError('dapp-request') for a protected account await reply()}| Chain | What a connection shows | In the journal |
|---|---|---|
| EVM, Tron | The address (a hash of the key) | No |
| TON | The public key | Yes |
| Bitcoin | The public key of each address | Yes |
| Solana, NEAR | The address, which is the key: these accounts cannot be sealed | No |
Change the list with sessionExposesKey if your provider differs. For a key that never passes
the keyring (a hardware signer), call await bunker.admit(request) before it signs.
Sweep to a sealed address
Section titled “Sweep to a sealed address”A sealed address is one of the wallet’s own that the chain has never seen and the journal does
not list. nextSealedIndex from @anywalletkit/bunker finds the first one; your
isSealedDestination says yes to it, and isFullSweep says whether the send leaves nothing of
its asset behind. When your isUsed cannot reach the chain, answer undefined: the search stops
with a SealedIndexError (code: 'cannot-tell') instead of picking an address it knows nothing
about.
/** "Move to safety": the one thing a protected account signs. `keyring` is the guarded one. */export async function sweep(bunker: ExtensionBunker, keyring: Keyring, accountId: string, to: string, amount: bigint) { const from = keyring.getAccountMeta(accountId).addresses.evm! // The same rules, before any sheet: a clear message for your Send screen instead of a late refusal. await bunker.check({ kind: 'send', chain: 'eip155:1', from, destinations: [to], amount }) return keyring.withAccount(accountId, 'evm', (account) => account.transfer({ recipient: to, amount }))}The journal is written before the account signs. If the send then fails, the key stays marked exposed, never the other way round.
The sign handler’s guard reads no calldata, so for it only a native send without data can be a
sweep. Sweep tokens through the keyring account (account.transfer), as above: there the kit
reads who the transfer pays.
/** The exposure of every EVM account, on the networks you name. Every network named learns every address. */export function scanAccounts(bunker: ExtensionBunker, keyring: Keyring, networks: NetworksTable, rpc: GuardedRouterParts['rpc']) { const seedRooted = new Map(keyring.listSources().map((source) => [source.id, source.type === 'mnemonic'])) const accounts = keyring.listAccounts({ includeHidden: true }).flatMap((account) => account.addresses.evm ? [{ chain: 'eip155:1', address: account.addresses.evm, seedRooted: seedRooted.get(account.sourceId) === true }] : []) return bunker.scan(accounts, { networks, rpc, chains: ['eip155:1', 'eip155:8453', 'eip155:42161', 'eip155:10'] })}Each account comes back sealed, exposed, unsealable (Solana, NEAR, Taproot) or unknown.
codes says why, for your own text and styling: how the key was exposed (transaction,
message, typed-data, dapp-session, on-chain), or why nothing is known (no-probe: you
gave no probe for that chain; probe-failed: the chain did not answer). reasons holds the
default English sentence of each code, and firstExposedAt the time the journal first knew.
The EVM check reads the pending nonce on every network you name,
through your own RPC. One key is one address on all EVM networks, so name every network the
user may have used: a network you leave out is not asked. A network that does not answer makes
the result unknown, never sealed.
What you still build
Section titled “What you still build”- The screens: the scan result, “protect this account”, “move to safety”, and the notice when a request was refused.
- Your list of protected accounts, and
isSealedDestination/isFullSweepover your own balance reads. - The providers for the chains you support, following the three rules above.
Limits
Section titled “Limits”keyring.exportSecretandexportPrivateKeyhand out the secret itself. Nothing guards a key after that.- Hidden means the wallet does not hand the account out. A site that learned the address elsewhere still knows it.
- The sweep transaction shows the key while it waits in the mempool.
- Only an EVM probe ships with the scan. Bitcoin, Zcash, Tron and TON probes are planned; pass
your own with
probes.