Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 8 min read

Passkeys in TypeScript: A Zero-Dependency WebAuthn Library for Browser, Node.js and Android

Passwords get phished, reused and leaked. Passkeys (built on the W3C WebAuthn standard) fix that: the private key never leaves the user's device, every login is bound to your domain, and users sign in with a fingerprint,

Passkeys in TypeScript: A Zero-Dependency WebAuthn Library for Browser, Node.js and Android

Passwords get phished, reused and leaked. Passkeys (built on the W3C WebAuthn standard) fix that: the private key never leaves the user's device, every login is bound to your domain, and users sign in with a fingerprint, face or PIN.

The hard part is the server side. You have to decode CBOR and COSE keys, parse X.509 certificates, check origins, challenges, flags and signature counters, and get every one of those checks right.

I built @xkid1/webauthn to handle all of that in one package. It's a zero-dependency, security-first WebAuthn / passkeys library written in strict TypeScript, and it runs in browsers, Node.js, Deno, Bun, Cloudflare Workers, Electron and React Native (Android).

Demo: registering a passkey and signing in with @xkid1/webauthn

GitHub logo xkid1 / webauthn

Zero-dependency, security-first WebAuthn / passkeys toolkit for browsers, Node.js, Electron and React Native (Android). Client ceremonies, server verification and Android Credential Manager bridge.

@xkid1/webauthn

CI Build Tests E2E CodeQL OpenSSF Scorecard Release
npm GitHub Packages license dependencies Buy me a coffee

Node.js TypeScript WebAuthn browser Deno Bun Cloudflare Workers Electron React Native
React Next.js Vue Nuxt Angular Svelte Solid module tree-shakeable

Zero-dependency, security-first WebAuthn / passkeys for every runtime: browsers, Node.js, Electron, React Native (Android) and edge workers. Written in strict TypeScript.

  • Zero runtime dependencies. It ships its own CBOR, COSE, ASN.1/X.509, base64url and UTF-8 code, built only on WebCrypto.
  • Small and tree-shakeable. It is pure ESM with sideEffects: false and separate /client, /server and /android entry points. The client entry is about 10 kB gzipped.
  • Secure by default. It enforces exact origin allowlists, checks challenges in constant time, and makes every challenge single-use. It checks the RP ID hash, UP/UV and BE/BS flags, the algorithm allowlist, signature counters (clone detection) and the 1023-byte credential-ID limit. Its parsers have bounds checks, depth limits and length-bomb protection.
  • Customisable. Every setting has a safe default you can override: algorithms, UV policy, attestation policy and trust anchors, counter policy, timeouts, cross-origin rules, plug-in attestation verifiers, an injectable WebCrypto and clock, a custom…

Why another WebAuthn library?

  • Zero runtime dependencies. CBOR, COSE, ASN.1/X.509, base64url and UTF-8 are all implemented in the package, on top of WebCrypto only. No transitive supply chain to audit.
  • Small and tree-shakeable. Pure ESM, sideEffects: false, and separate /client, /server and /android entry points. startRegistration + startAuthentication is about 4.2 kB brotli.
  • Secure by default. Exact origin allowlists, constant-time challenge comparison, single-use challenges, RP ID hash checks, UP/UV and BE/BS flag checks, an algorithm allowlist (RS1 is never accepted), RSA β‰₯ 2048 bits, signature counter clone detection, and strict, bounds-checked parsers.
  • WebAuthn Level 3. JSON serialisation, hints, passkey autofill (conditional mediation), auto-register (conditional create), getClientCapabilities() and the Signal API.
  • Every attestation format. packed, tpm, android-key, android-safetynet, fido-u2f, apple and none are verified out of the box.
  • Runs everywhere and is SSR-safe. Importing it never touches window, so it works with React, Next.js, Vue, Nuxt, Angular, SvelteKit, Solid and Electron.

Install

npm i @xkid1/webauthn
# or: yarn add @xkid1/webauthn / pnpm add @xkid1/webauthn
Entry point Use it in
@xkid1/webauthn/client Browser, Electron renderer, WebView
@xkid1/webauthn/server Node.js β‰₯ 20, Deno, Bun, Cloudflare Workers
@xkid1/webauthn/android React Native / native Android (Credential Manager bridge)

How to add passkey login: the server (Node.js)

A passkey flow has two ceremonies, registration and authentication. Each is one request for options and one request to verify. Here's the whole server with Express:

import { createWebAuthnServer, MemoryChallengeStore } from '@xkid1/webauthn/server';

const webauthn = createWebAuthnServer({
  rpId: 'example.com',
  rpName: 'Example Inc.',
  origins: ['https://example.com'], // exact match, no wildcards
  challengeStore: new MemoryChallengeStore(), // use Redis/DB with several instances
});

// 1. Registration options
app.post('/webauthn/register/options', async (req, res) => {
  const user = req.session.user;
  res.json(
    await webauthn.generateRegistrationOptions({
      user: { id: user.webauthnId, name: user.email, displayName: user.name },
      excludeCredentials: await db.credentials.listFor(user.id),
      sessionKey: req.session.id,
    }),
  );
});

// 2. Verify registration and store the credential
app.post('/webauthn/register/verify', async (req, res) => {
  const { credential } = await webauthn.verifyRegistration({
    response: req.body.response,
    sessionKey: req.session.id,
  });
  await db.credentials.insert({ userId: req.session.user.id, ...credential });
  res.json({ ok: true });
});

// 3. Authentication options
app.post('/webauthn/authenticate/options', async (req, res) => {
  res.json(await webauthn.generateAuthenticationOptions({ sessionKey: req.session.id }));
});

// 4. Verify the sign-in
app.post('/webauthn/authenticate/verify', async (req, res) => {
  const stored = await db.credentials.findById(req.body.response.id);
  if (!stored) return res.status(401).json({ message: 'Unknown credential' });

  const result = await webauthn.verifyAuthentication({
    response: req.body.response,
    sessionKey: req.session.id,
    credential: stored,
    expectedUserHandle: stored.userWebauthnId,
  });
  await db.credentials.update(stored.id, { counter: result.newCounter, backedUp: result.backedUp });
  req.session.userId = stored.userId;
  res.json({ ok: true });
});

verifyRegistration returns plain JSON-friendly values (id, publicKey, counter, transports, deviceType, backedUp, aaguid…), so you can store them in any database without extra encoding.

The challenge is stored server-side under sessionKey and deleted the moment it's used, so a replayed response fails. If you'd rather manage challenges yourself, pass expectedChallenge instead.

How to add passkey login: the browser

On the client, createWebAuthnClient calls the four endpoints above for you:

import { createWebAuthnClient, isWebAuthnSupported } from '@xkid1/webauthn/client';

const passkeys = createWebAuthnClient({
  headers: () => ({ 'X-CSRF-Token': getCsrfToken() }),
});

if (isWebAuthnSupported()) {
  await passkeys.register(); // create a passkey
  await passkeys.authenticate(); // sign in with it
}

Already have an HTTP layer? Use the low-level functions instead:

import { startRegistration } from '@xkid1/webauthn/client';

const optionsJSON = await api.post('/webauthn/register/options');
const response = await startRegistration({ optionsJSON });
await api.post('/webauthn/register/verify', { response });

Passkey autofill (conditional mediation) in React

Show saved passkeys right in the username field's autofill menu:

'use client';
import { useEffect } from 'react';
import {
  cancelCeremony,
  isConditionalMediationAvailable,
  startAuthentication,
} from '@xkid1/webauthn/client';

export function LoginForm() {
  useEffect(() => {
    void (async () => {
      if (!(await isConditionalMediationAvailable())) return;
      const optionsJSON = await fetch('/webauthn/authenticate/options', { method: 'POST' }).then(
        (r) => r.json(),
      );
      const response = await startAuthentication({ optionsJSON, useBrowserAutofill: true }).catch(
        () => null,
      );
      if (response) {
        await fetch('/webauthn/authenticate/verify', {
          method: 'POST',
          body: JSON.stringify({ response }),
        });
      }
    })();
    return cancelCeremony; // StrictMode-safe: aborts the pending request on unmount
  }, []);

  return <input name="username" autoComplete="username webauthn" />;
}

The repository has the same recipe for Vue/Nuxt, Angular, Svelte/SvelteKit and Electron.

Passkeys in React Native (Android)

React Native has no navigator.credentials; Android passkeys go through Jetpack Credential Manager. The /android entry point handles the JavaScript side (JSON normalisation, validation and error mapping), and you supply a small native module:

import { NativeModules } from 'react-native';
import { createAndroidPasskeyClient } from '@xkid1/webauthn/android';

const passkeys = createAndroidPasskeyClient(NativeModules.Passkey);

const optionsJSON = await api.post('/webauthn/register/options');
const response = await passkeys.startRegistration({ optionsJSON });
await api.post('/webauthn/register/verify', { response });

On the server, allow the app's signing-key origin and serve Digital Asset Links:

import { androidOriginFromFingerprint, buildAssetLinks } from '@xkid1/webauthn/android';

const FP = 'FA:C6:17:45:…:91:03:3B:9C'; // SHA-256 of your app's signing certificate

createWebAuthnServer({
  rpId: 'example.com',
  rpName: 'Example',
  origins: ['https://example.com', androidOriginFromFingerprint(FP)],
});

app.get('/.well-known/assetlinks.json', (_req, res) =>
  res.json(buildAssetLinks([{ packageName: 'com.example.app', sha256CertFingerprints: [FP] }])),
);

The README includes a ~40-line Kotlin module you can copy.

Errors you can actually act on

Every failure is a single WebAuthnError type with a stable code and a hint that tells you how to fix it:

import { isWebAuthnError } from '@xkid1/webauthn/client';

try {
  await passkeys.authenticate();
} catch (e) {
  if (isWebAuthnError(e, 'CEREMONY_NOT_ALLOWED', 'CEREMONY_ABORTED')) return; // user cancelled
  if (isWebAuthnError(e)) console.warn(String(e));
  // WebAuthnError [ORIGIN_MISMATCH]: … Hint: Add the exact origin (scheme, host and port) to config.origins
  throw e;
}

Messages and hints never include challenges, keys, signatures or user handles, so they're safe to log. On the server, error.toJSON() returns { name, code, message, hint } without the stack, ready to send back from an API.

Secure defaults, customisable when you need it

Every option has a safe default, and options can only make verification stricter or opt in explicitly. None of them loosens a check silently.

import { createAndroidKeyVerifier, createWebAuthnServer } from '@xkid1/webauthn/server';

createWebAuthnServer({
  rpId: 'example.com',
  rpName: 'Example',
  origins: ['https://example.com'],
  supportedAlgorithms: [-8, -7, -257], // EdDSA, ES256, RS256 (the default)
  requireUserVerification: true,
  attestation: 'direct',
  trustAnchors: [appleWebAuthnRootDer],
  requireTrustedAttestation: true,
  attestationVerifiers: {
    'android-key': createAndroidKeyVerifier({ requireTeeEnforced: true }),
  },
});

You can also plug in your own challenge store (Redis, a database), your own attestation verifiers, an injected WebCrypto, or a custom clock for tests.

How it's tested

  • A software authenticator produces real signed ES256, EdDSA and RS256 responses, so tests exercise actual cryptography instead of canned fixtures.
  • Negative tests for every security check: each tampered input must be rejected with the right error code.
  • End-to-end tests against the packed tarball. CI builds the package, installs it offline into a fresh app (which fails if it has any dependency), and runs registration and sign-in over real HTTP. A separate CBOR encoder is used there so the library never verifies data it encoded itself.
  • Bundle-size budgets enforced in CI, plus benchmarks in Node, Bun, Deno, Chromium, Firefox and WebKit.

Verification is fast too: about 5,000 registrations/s and 2,500 sign-ins/s on Node 26.

FAQ

What is the difference between WebAuthn and passkeys?

WebAuthn is the W3C browser API and protocol for public-key authentication. A passkey is a discoverable WebAuthn credential, usually synced across a user's devices by Apple, Google or a password manager. @xkid1/webauthn supports both synced passkeys and device-bound security keys.

Does it support FIDO2 and FIDO U2F security keys?

Yes. FIDO2 is WebAuthn plus CTAP2, and @xkid1/webauthn is a FIDO2 relying-party library: it creates the options and verifies the responses from any FIDO2 authenticator, such as a YubiKey, Touch ID, Windows Hello or an Android phone. Older FIDO U2F (CTAP1) security keys also work through WebAuthn, and their fido-u2f attestation is verified. Credentials registered with the legacy U2F JavaScript API (appid extension) aren't supported, so users re-register those keys once.

Does it work with Next.js, Nuxt and other SSR frameworks?

Yes. Importing the package never touches window or navigator, so it's safe in server components and SSR. Call the client functions from the browser only.

Can I use it on Cloudflare Workers, Deno or Bun?

Yes. The server entry point only needs globalThis.crypto (WebCrypto), with no node:* imports and no Buffer.

Do I need attestation?

Usually not. The default, attestation: 'none', is the most privacy-friendly choice and fits most consumer apps. Turn on direct attestation with trustAnchors only if you need to know which authenticator model created a credential, for example in enterprise deployments.

Does it support iOS?

In Safari and WKWebView, yes, through the /client entry point. For React Native on iOS, bridge to ASAuthorizationPlatformPublicKeyCredentialProvider; the server side is identical.

Try it

git clone https://github.com/xkid1/webauthn.git
cd webauthn && yarn install && yarn demo

Open http://localhost:5173 to register a passkey, sign in, try passkey autofill, and change every registration and authentication option from the Advanced Settings panel.

It's MIT-licensed and at v0.1.0. Feedback, issues and stars are very welcome. If you add passkeys to your app with it, tell me in the comments! πŸš€

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.