Widgets
@practic/bui
@practic/bui
@practic/persist
@practic/bui-theme-editor
@practic/tsconfig-builder
@practic/force-directed
@practic/force-directed
@practic/force-directed
Passkey sign-up and sign-in, plug and play: a one-time code proves an email or phone number, each device gets its own passkey, and one endpoint serves it all from Bun, Node, Express, Deno or a Lambda.
Passkeys cannot be phished or reused like passwords, but adding them means challenges, binary encodings, signature
checks, public keys to store, and deciding who may sign up. This package gives you the parts, each replaceable: React
forms, a browser client, one endpoint that takes actions as JSON, storage engines starting with a JSON file, and
channels that deliver codes, starting with the console. With no configuration, sign-up is open and everything works;
editing the store's data closes sign-up, invites a company's domain, or locks an account out, with no redeploy. Every
signature is verified with @passwordless-id/webauthn.
npm install @practic/passkey @practic/bui @base-ui/react react react-dom
Or bun add, pnpm add, yarn add.
Run the endpoint, here with Bun. Codes are printed to its console, and accounts are kept in .data/passkey.json:
import { adapterFetch } from '@practic/passkey/adapters/fetch'
import { passkeyServer } from '@practic/passkey/server'
const passkey = adapterFetch(passkeyServer())
Bun.serve({
port: Number(Bun.env.PORT ?? 3001),
// the client's IP address, which the rate limits count per
fetch: async (request, server) =>
(await passkey(request, { ip: server.requestIP(request)?.address })) ?? new Response('Not Found', { status: 404 }),
})
Then render the forms in a page served from the same origin. In development, send /api to the server, such as with
Vite's server.proxy: { '/api': 'http://localhost:3001' }. The components show their texts in English; the labels
section below rewords or translates them. In sign-in.tsx:
import { usePasskeySession } from '@practic/passkey'
import { PasskeyContinue, PasskeyCreate, PasskeyList, PasskeyProfile, PasskeySignOut, type PasskeyCreateProps } from '@practic/passkey/ui'
import '@practic/bui/themes/barebones.css'
export function SignIn({ client }: Pick<PasskeyCreateProps, 'client'> = {}) {
const { session } = usePasskeySession({ client })
return (
<div className='grid gap-6'>
<PasskeyCreate client={client} />
<PasskeyContinue client={client} />
{session ? (
<>
<p>
Signed in as <strong>{session.passkey.displayName}</strong> with “{session.passkey.label}”. <PasskeySignOut client={client} />
</p>
<PasskeyProfile client={client} />
<PasskeyList client={client} />
</>
) : (
<p>Signed out.</p>
)}
</div>
)
}
SignIn passes its optional client to every part, for an endpoint served elsewhere than /api/passkey
(<SignIn client={passkeyClient({ endpoint: '/auth/passkey' })} />); without one, they all use the default.
Type your email, choose Create Passkey, then type the code the server printed and choose Confirm code: your device creates the passkey and the account, and you are signed in. After signing out, Continue with Passkey signs you in again, and a reload keeps you signed in.
open, invited (allowed addresses and whole domains such as @company.com), or
closed; denied entries and disabled accounts lock people out, even with a passkey.passkey.session() protects your own routes.admins setting names (or your own roles, through isAdmin) or an admin key; passkey.admin()
runs the same from scripts.adapterFetch and adapterNode connect it to
Fetch API runtimes, Node and Express, and anything else calls server.process directly.storageMigrate moves the
data.| Import | Exports |
|---|---|
@practic/passkey | The hooks below, passkeyClient, and the browser's list, with no @practic/bui |
@practic/passkey/ui | The components below, built from @practic/bui |
@practic/passkey/server | passkeyServer, and the policy functions it decides sign-up with |
@practic/passkey/adapters/fetch | adapterFetch(server, { path, trustProxy }), for Bun, Deno and Workers |
@practic/passkey/adapters/node | adapterNode({ prefix, handle, fallback }), for Node servers and Express |
@practic/passkey/channels/console | channelConsole(), the default channel |
@practic/passkey/channels/outbox | channelOutbox(), which keeps codes for a demo page |
@practic/passkey/limiters/* | Limiter, limiterStorage(engine) (the default) and limiterMemory() |
@practic/passkey/protocol | Every zod schema and its type |
@practic/passkey/storage/* | The storage interface and engines, below |
@practic/passkey/translations | passkeyLabelsEn, every text the components show, in English |
@practic/passkey/demo | Demo, the package demo page, which needs a server with an outbox |
From @practic/passkey/ui; their hooks, below, come from @practic/passkey. Each takes an optional client from passkeyClient({ endpoint, app }); without one, it uses /api/passkey and the
default app. Each also takes optional labels, below.
| Component | Props | Does |
|---|---|---|
PasskeyCreate | children, legend, client, onCodeSent, onCreated, onError, busy, labels | Address, code, then the device creates the passkey and signs in: sign-up, or a passkey added. Words itself when sign-up is closed. |
PasskeyContinue | children, legend, client, onSignedIn, onError, busy, labels | Lists the passkeys used in this browser; its button lets the device's picker choose any other. |
PasskeyProfile | legend, client, onUpdated, labels | Changes the signed-in account's display name; nothing while signed out. |
PasskeyList | legend, client, labels, overrides | The signed-in account's passkeys, renamed in place or removed after asking. |
PasskeySignOut | children, everywhere, client, labels | Signs out this session, or every session of the account; only while signed in. Given children such as an icon, it keeps its label as its accessible name. |
PasskeyAdmin | label, client, labels, overrides | Settings, access entries and accounts, for an account the app's admins setting covers; each change confirmed in a toast. overrides takes props for the elements its Root renders (propsSection, propsLoadingStatus, propsPasskeyAlert, propsToastWidget, propsAdminContext), applied after its own; a className adds to its own. |
While a request runs, the button that started it is disabled and shows a spinner, through ButtonIcon from
@practic/bui/widgets, and the rest of the form is disabled. onError receives the words of a failure, which the form
also shows below itself, such as to put them in a toast. busy keeps the form busy after it succeeded, while you finish
what follows, such as navigating away inside a transition: busy={isPending} from useTransition.
The components share the session through usePasskeySession({ client?, labels }), which answers { state, session, signOut, signOutEverywhere, refresh } and is read once per page, so a reload stays signed in. A request refused with
session-required, such as after the session was ended from another device, signs the page out. Each component also comes as its
hook in @practic/passkey, which needs no @practic/bui, for a design of your own: usePasskeyCreate, usePasskeyContinue, usePasskeyProfile and usePasskeyList
answer the same state and actions the components use. Or keep the behaviour and rearrange the parts inside the
component's Root:
| Component | Parts inside Root |
|---|---|
PasskeyCreate | Intro, Address, Send, CodeSent, Code, DisplayName, Label, Confirm, Resend, StartOver, Created, Another, Error, and Step to show anything during one step |
PasskeyContinue | Intro, Passkeys, Pick, Error |
PasskeyProfile | Name, Save, Error |
PasskeyList | Items, Error |
PasskeyAdmin | Settings, Access, Accounts, and Account (one account's passkeys and sessions, by address, with onChanged) |
Each part shows itself only when it applies, such as Code once a code was sent. The parts that render elements of
their own take overrides, props for each element applied after its own, a className adding to its own:
PasskeyList.Root (propsFieldset, propsLegend), PasskeyList.Items (propsList, and for each passkey
propsItem, propsRename, propsName, propsDetails, propsRemove), and PasskeyAdmin's Settings, Access,
Accounts and Account, such as <PasskeyAdmin.Account address={address} overrides={{ propsActions: { className: 'justify-end' } }} /> for its row of actions.
Without labels, every component shows its texts in English, from passkeyLabelsEn, which
@practic/passkey/translations exports. A component's labels takes any of the PasskeyLabels groups it shows, such
as create and errors for PasskeyCreate, each with any of its texts: those given replace the English ones, and the
rest stay, including texts a later version adds. Texts with values are functions, and errors are worded from their
codes, so a server refusal reads in the same language. A translation replaces them, all or some, in
translated-create.tsx:
import { PasskeyCreate } from '@practic/passkey/ui'
import '@practic/bui/themes/barebones.css'
export function TranslatedCreate() {
return (
<PasskeyCreate
labels={{
create: { legend: 'Criar uma passkey', address: 'E-mail ou telefone', send: 'Criar passkey' },
errors: { 'code-invalid': 'Esse não é o código enviado.' },
}}
/>
)
}
passkeyClient returns info(), sendCode(address), create({ address, code, label?, displayName? }),
signIn(passkey?), session(), signOut(), signOutEverywhere(), updateAccount(displayName), passkeys(),
renamePasskey(id, label), removePasskey(id) and readOutbox(address). Creating a passkey and signing in open a
session, kept in an HttpOnly cookie, or, with the tokenStore option, as a bearer token. Refusals throw
PasskeyClientError, with a code such as code-invalid or not-allowed, and the server's message in English for
developers; passkeyErrorMessage(error, errors) words any error for the user, in the labels' errors.
passkeyServer(options)Returns { process(body, context), allowsOrigin(origin, context), session(request), admin(request) }. Give process a parsed JSON
body and { host, origin?, cookie?, authorization? }, the host the request was sent to and its Origin, Cookie and
Authorization headers, and it answers { status, body, headers }, where headers carries the session cookie a
sign-in sets; it never throws for a bad request. session({ app?, cookie?, authorization? }) answers the signed-in
passkey and account of a request to your own routes, or undefined. admin(request) runs an admin action from your own
code, such as a seed script, with no key or session.
| Option | Default | Description |
|---|---|---|
root | storageFilesystem({ path: '.data/passkey.json' }) | The root store: the apps, and the default app's settings, access entries, accounts and passkeys. |
engines | none | Engine factories by name, (namespace) => StorageEngine, that app records choose. |
channels | {} | Channels by name that app records choose; default takes what an app does not choose, and the console what nothing takes. |
codeLifetime | 600000 (10 minutes) | Milliseconds a code stays valid. |
codeAttempts | 5 | Wrong codes accepted before a code is discarded. |
challengeLifetime | 300000 (5 minutes) | Milliseconds the browser has to answer a challenge. |
limiter | limiterStorage over each app's data store | Counts hits for the rate limits, such as limiterMemory() for one process, or your own over Redis. |
adminKeys | [] | Keys that administer every app, sent as Authorization: Bearer <key>; long random strings from a secret. |
isAdmin | none | (account, app) => boolean: who administers each app, from the host's own roles; the app's admins setting is then ignored. |
allowsOrigin answers a CORS preflight, which names no app. adapterFetch uses both.
adapterFetch(server) is a Fetch API handler: give it to Bun.serve, Deno.serve or a Worker, as in the quick
start, with the client's IP address as its second argument ({ ip }), which the limits per IP need; behind a proxy that
appends it to X-Forwarded-For, pass trustProxy: true instead. adapterNode({ prefix, handle }) is a Node request
listener and Express middleware, which passes the connection's IP address on:
app.use(adapterNode({ prefix: '/api/passkey', handle: adapterFetch(server) })), before any body parser. Anything else
calls server.process with the parsed body, such as a Lambda behind a function URL:
import { schemaPasskeyJson, type PasskeyJson } from '@practic/passkey/protocol'
import { passkeyServer } from '@practic/passkey/server'
import { storageFilesystem } from '@practic/passkey/storage/filesystem'
export type FunctionUrlEvent = {
body?: string
isBase64Encoded?: boolean
headers: Record<string, string | undefined>
requestContext: { http: { sourceIp: string } }
}
// a Lambda keeps nothing between calls, and the server keeps everything in its store: here a file on a mounted EFS
const passkey = passkeyServer({ root: storageFilesystem({ path: '/mnt/passkey/passkey.json' }) })
function readBody(text: string): PasskeyJson | undefined {
try {
return schemaPasskeyJson.parse(JSON.parse(text))
} catch {
return undefined
}
}
export async function handler(event: FunctionUrlEvent) {
const body = readBody(event.isBase64Encoded ? Buffer.from(event.body ?? '', 'base64').toString() : (event.body ?? ''))
const { headers } = event
const answer =
body === undefined
? { status: 400, body: { error: { code: 'invalid-request', message: 'The request body is not JSON.' } }, headers: {} }
: await passkey.process(body, {
host: headers.host ?? '',
origin: headers.origin,
cookie: headers.cookie,
authorization: headers.authorization,
ip: event.requestContext.http.sourceIp,
})
// the session cookie a sign-in sets travels in the headers
return { statusCode: answer.status, headers: { 'Content-Type': 'application/json', ...answer.headers }, body: JSON.stringify(answer.body) }
}
passkey.session() reads the session a sign-in opened, from the cookie or a bearer token, so a route of your own answers
only the signed-in:
import { passkeyServer } from '@practic/passkey/server'
const passkey = passkeyServer()
export async function accountRoute(request: Request) {
const signedIn = await passkey.session({
cookie: request.headers.get('cookie') ?? undefined,
authorization: request.headers.get('authorization') ?? undefined,
})
if (!signedIn) return Response.json({ error: 'Sign in first.' }, { status: 401 })
return Response.json({ name: signedIn.passkey.displayName, address: signedIn.passkey.address })
}
A script sets an app up through the same admin actions the endpoint serves, with passkey.admin(), which needs no key
or session. Here one process counts its own rate limits, an admin key comes from the environment, and sign-up opens to
one company:
import { limiterMemory } from '@practic/passkey/limiters/memory'
import { passkeyServer } from '@practic/passkey/server'
export const passkey = passkeyServer({
limiter: limiterMemory(),
adminKeys: Bun.env.PASSKEY_ADMIN_KEY ? [Bun.env.PASSKEY_ADMIN_KEY] : [],
})
await passkey.admin({ action: 'admin-settings-set', settings: { signup: 'invited', admins: ['@company.com'] } })
await passkey.admin({ action: 'admin-access-set', pattern: '@company.com', rule: 'allowed' })
One endpoint serves many apps. A request names its app (default when it names none), and the server finds it in the
root store, read on every request, so adding an app or moving it is a data change:
| Collection | Key | Record |
|---|---|---|
apps | the app id | { origins?: string[], config?: { engine, namespace }, data?: { engine, namespace }, channels?: { email?, phone? } } |
config holds the app's settings and access; data its accounts, passkeys, codes and challenges.
Each names an engine registered in code, with its credentials, and a namespace, so data chooses among what code
allows. A store left out lives in the root store, under the app's id, through storageNamespace. The default app
needs no record, and keeps its records at the root.storageMigrate copies its collections to the new engine; changing its record points it there.
Pages keep calling the same endpoint.origins accepts only those: both the request's Origin header and what the browser
signed. Without them, any origin on the request's host name is accepted, whatever the port, so a dev proxy works.
Pages on another origin than the endpoint's call it through CORS, which adapterFetch answers for the origins the
apps list.A channel delivers codes: { send({ app, address, code, expiresAt }) }, where address is { value, kind } with
kind email or phone. Write one for your email service, SMS provider or chat by implementing send; register it
under a name in channels, and let app records choose it per kind, so one app can email while another texts.
| Channel | Import | Does |
|---|---|---|
channelConsole() | @practic/passkey/channels/console | Prints each code to the server's console: the default. |
channelOutbox({ limit?, log? }) | @practic/passkey/channels/outbox | Keeps the last limit codes per address (5) for the outbox action, and prints them unless log is false. Development only: anyone can read them. |
Every action is a POST of { app?, protocol?, action, …fields } to one endpoint, /api/passkey by default.
protocol is the version of this protocol the page speaks (passkeyProtocolVersion, from
@practic/passkey/protocol), which passkeyClient always sends: a server speaking another refuses the request with
protocol-mismatch (400), so a page left open across a release that changed the protocol asks to be reloaded rather
than being misread. A request without it, such as one written by hand, is taken to speak the server's. Refusals answer
{ error: { code, message, retryAfter? } } with a 4xx status; rate-limited (429) adds the seconds to wait, also as
Retry-After. The actions marked session need a signed-in session, and refuse with session-required (401).
action | Fields | Answers |
|---|---|---|
info | none | { signup } |
send-code | address | { expiresAt }, the same whether or not a code was sent |
register-options | address, code, displayName? | { challenge, user, excludeCredentials, outcome } |
register | challenge, registration, label?, token? | { outcome, passkey, session }, outcome signed-up or passkey-added |
sign-in-options | none | { challenge } |
sign-in | challenge, authentication, token? | { passkey, session }; session is { expiresAt, token? }, the token if asked |
session | none | { session }: { passkey, expiresAt }, or null when signed out |
sign-out | none | {}, and the cookie cleared |
sign-out-everywhere | none, session | { ended }, the sessions ended on every device |
update-account | displayName, session | { passkey }; a null name shows the address again |
passkeys | none, session | { passkeys }, the account's, oldest first |
rename-passkey | id, label, session | { passkey } |
remove-passkey | id, session | {}; ends the sessions it opened, and refuses the last one with last-passkey |
outbox | address | { messages }, only when the app's channel for the address is a channelOutbox |
The admin actions are allowed to a session whose account the app's admins setting covers (or that the server's
isAdmin accepts, when given), or to a request carrying an admin key; those marked key only to an admin key, since apps span every app. passkeyClient().admin has a method for
each of the others, such as admin.accountGet({ address }).
action | Fields | Answers |
|---|---|---|
admin-settings-get | none | { settings, adminsByHost }, defaults filled in; adminsByHost when isAdmin decides |
admin-settings-set | settings | { settings, adminsByHost }; nested objects merge, null restores a default |
admin-access-list | none | { entries } |
admin-access-set | pattern, rule | { entry }, added or changed |
admin-access-remove | pattern | {} |
admin-accounts-list | status?, limit? (50), after? | { accounts, next? }, in address order; next continues the list |
admin-account-get | address | { account, passkeys, sessions } |
admin-account-create | address, displayName? | { account }, active and invited, ready for a passkey whatever signup says |
admin-account-update | address, status?, displayName? | { account }; disabling ends its sessions |
admin-account-delete | address | { passkeys, sessions } removed with it, for good; disable it to keep the data |
admin-passkey-remove | id | {}, even an account's last passkey |
admin-sessions-end | address, id? | { ended }: one session, or all of the account's |
admin-apps-list | none, key | { apps } |
admin-app-set | id, record, key | { id, record }, added or replaced |
admin-app-remove | id, key | {}; its stores stay as they are |
An app's settings and access entries live in its store, and are read on every request:
| Collection | Key | Record | Effect |
|---|---|---|---|
settings | app | { signup: 'open' | 'invited' | 'closed', session, limits, admins } | Who may create an account (open when there is no record), and the settings below. |
access | the pattern | { pattern, rule: 'allowed' | 'denied' } | An exact address, @company.com, or @*.company.com for its subdomains. |
accounts | the address | { …, status: 'active' | 'disabled' } | A disabled account can neither sign in nor add passkeys. |
A denied entry always wins. While sign-up is invited, only addresses an allowed entry covers may create an account;
closed stops every new account, while existing ones still sign in and add devices.
The same record sets how long sessions last and the rate limits, each field defaulting when left out:
| Setting | Default | Limits |
|---|---|---|
session.lifetimeHours | 360 (15 days) | How long a session lasts however much it is used. |
session.idleHours | 72 (3 days) | How long a session lasts unused. |
limits.codesPerAddress | { limit: 3, windowSeconds: 600 } | Codes sent to one address. |
limits.requestsPerIp | { limit: 120, windowSeconds: 60 } | Requests from one IP address, whatever the action. |
limits.failuresPerAddress | { limit: 10, windowSeconds: 900 } | Wrong codes and passkeys that fail to verify, per address. |
limits.failuresPerIp | { limit: 30, windowSeconds: 900 } | The same, per IP address. |
admins | [] | Who administers the app while signed in, as access patterns, such as ['@company.com']. |
A limit on an address applies whether or not it has an account, so a refusal reveals nothing.
Every engine keeps records by collection and key behind one small interface, StorageEngine, so the JSON file can be
swapped for a database without touching the rest.
| Import | Export | Description |
|---|---|---|
@practic/passkey/storage | StorageEngine, StorageError | The interface every engine implements, and the error its refused writes throw. |
@practic/passkey/storage | storageMigrate(from, to, collections) | Copies collections between two engines, keys kept; stops rather than overwrite. |
@practic/passkey/storage | storageNamespace(engine, namespace) | Part of an engine with its own collections, so several apps share one store. |
@practic/passkey/storage/filesystem | storageFilesystem({ path }) | The default: one JSON file, replaced atomically on each write. Works on EFS too. |
@practic/passkey/storage/memory | storageMemory(seed?) | The same engine in memory, for tests and trials. |
@practic/passkey/storage/json-document | storageJsonDocument({ read, write }) | The JSON document engine over any backend that reads and writes text, such as an S3 object. |
@practic/passkey/storage/contract | storageContract(create) | The checks an engine must pass, for any test runner. |
StorageEngine method | Does |
|---|---|
get(collection, key) | The record, or undefined. |
list(collection, where?, page?) | The records, or those whose fields equal where's, in key order; page is { limit?, after? }. |
create(collection, key, record) | Stores a new record; throws StorageError exists when the key is taken. |
update(collection, key, changes, condition?) | Merges fields and returns the record; throws missing, or conflict when condition no longer matches. |
delete(collection, key) | Removes the record and returns it, so only one caller ever receives it. |
Records are plain JSON. To write an engine for another store, implement those five methods with its own atomic
operations, such as a conditional put for create and update and a delete that returns the row, then run
storageContract against it. The JSON document engines run one operation at a time, which is atomic within one
process; several processes writing one file can overwrite each other, which suits a small site served by one process.
Peer dependencies: react and react-dom 19. @practic/bui is an optional peer, needed only by
@practic/passkey/ui, whose forms come from it, with @base-ui/react and a theme such as
@practic/bui/themes/barebones.css. An app drawing its own forms imports the hooks from @practic/passkey and
installs neither.
Tailwind CSS 4. The forms lay themselves out with Tailwind classes. Point your Tailwind stylesheet at the package, with the path relative to that stylesheet:
@import 'tailwindcss';
@source '../node_modules/@practic/passkey';
A secure page. Browsers offer passkeys only over HTTPS, or on localhost. A passkey belongs to the page's
host name, so one created on localhost:3000 also works on localhost:4000, while each server keeps its own
accounts.
The browser's list is stored under practic_passkey_device in localStorage, with the last address typed.
Sessions are kept in the store under a hash of their token, and in the browser in an HttpOnly cookie named
practic_passkey_<app>, Secure on every host but a local one. A page on another site, or a native app, passes
tokenStore to passkeyClient and sends the token as Authorization: Bearer <token>.
MIT © Felipe Penno. See LICENSE.