# AI Integration Guide: Biometric Authentication Frontend

> **For AI Development Agents**: Complete integration instructions for `capacitor-biometric-authentication` with `webauthn-server-buildkit` backend.

## Package Pair

| Package                              | Role     | Install                                       |
| ------------------------------------ | -------- | --------------------------------------------- |
| `capacitor-biometric-authentication` | Frontend | `yarn add capacitor-biometric-authentication` |
| `webauthn-server-buildkit`           | Backend  | `yarn add webauthn-server-buildkit`           |

## Minimal Setup (Copy-Paste Ready)

### Frontend (React/Vue/Angular/Vanilla)

On the web platform this library runs the WebAuthn ceremony and returns the standard WebAuthn JSON in `result.webAuthnResponse`. A successful ceremony is **not** proof of identity by itself — the backend must verify `webAuthnResponse` against the challenge it issued. The first registration ceremony (no stored credential yet) returns `webAuthnCeremony: 'registration'`; later ceremonies return `'authentication'`.

```typescript
import BiometricAuth from 'capacitor-biometric-authentication';

const API = 'https://your-api.com';

// 1. Check availability (resolves to a boolean)
const available = await BiometricAuth.isAvailable();

// 2. Register: server issues a challenge -> client ceremony -> server verifies.
async function register(userId: string, username: string) {
  // a. Get registration options (incl. challenge) from the backend.
  const opts = await fetch(`${API}/webauthn/register/options`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId, username }),
  }).then((r) => r.json());

  // b. Run the ceremony, passing the SERVER-ISSUED challenge.
  const result = await BiometricAuth.authenticate({
    reason: 'Register biometric',
    webAuthnOptions: {
      create: {
        challenge: opts.challenge, // base64url string from the server
        rp: opts.rp,
        user: opts.user,
        pubKeyCredParams: opts.pubKeyCredParams,
      },
    },
  });

  if (!result.success) throw new Error(result.error?.message);

  // c. Send the attestation to the backend to VERIFY before trusting it.
  return fetch(`${API}/webauthn/register/verify`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId, response: result.webAuthnResponse }),
  }).then((r) => r.json());
}

// 3. Authenticate: same challenge -> ceremony -> verify pattern.
async function login(userId: string) {
  const opts = await fetch(`${API}/webauthn/authenticate/options`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId }),
  }).then((r) => r.json());

  const result = await BiometricAuth.authenticate({
    reason: 'Login',
    webAuthnOptions: {
      get: {
        challenge: opts.challenge, // base64url string from the server
        rpId: opts.rpId,
        allowCredentials: opts.allowCredentials,
      },
    },
  });

  if (!result.success) throw new Error(result.error?.message);

  // The server verifies the assertion against the challenge it issued.
  return fetch(`${API}/webauthn/authenticate/verify`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId, response: result.webAuthnResponse }),
  }).then((r) => r.json());
}
```

### Backend (Node.js)

```typescript
import express from 'express';
import { WebAuthnServer } from 'webauthn-server-buildkit';

const app = express();
app.use(express.json());

const webauthn = new WebAuthnServer({
  rpName: 'My App',
  rpID: 'myapp.com',
  origin: [
    'https://myapp.com',
    'android-app://com.myapp',
    'ios-app://com.myapp',
  ],
  encryptionSecret: process.env.ENCRYPTION_SECRET!, // 32+ chars
});

// In-memory storage (use DB in production)
const challenges = new Map();
const credentials = new Map();

// Registration
app.post('/webauthn/register/options', async (req, res) => {
  const { userId, username } = req.body;
  const { options, challenge } = await webauthn.createRegistrationOptions({
    id: userId,
    username,
    displayName: username,
  });
  challenges.set(userId, challenge);
  res.json(options);
});

app.post('/webauthn/register/verify', async (req, res) => {
  const { userId, response } = req.body;
  const { verified, registrationInfo } = await webauthn.verifyRegistration(
    response,
    challenges.get(userId)
  );
  if (verified && registrationInfo) {
    credentials.set(registrationInfo.credential.id, {
      ...registrationInfo.credential,
      userId,
    });
  }
  res.json({ verified });
});

// Authentication
app.post('/webauthn/authenticate/options', async (req, res) => {
  const { userId } = req.body;
  const userCreds = [...credentials.values()].filter(
    (c) => c.userId === userId
  );
  const { options, challenge } =
    await webauthn.createAuthenticationOptions(userCreds);
  challenges.set(`auth_${userId}`, challenge);
  res.json(options);
});

app.post('/webauthn/authenticate/verify', async (req, res) => {
  const { userId, response } = req.body;
  const credential = credentials.get(response.id);
  const { verified, authenticationInfo } = await webauthn.verifyAuthentication(
    response,
    challenges.get(`auth_${userId}`),
    credential
  );
  if (verified) {
    const token = await webauthn.createSession(
      userId,
      credential.id,
      authenticationInfo!.userVerified
    );
    res.json({ verified, token });
  } else {
    res.status(401).json({ verified: false });
  }
});

app.listen(3000);
```

## API Quick Reference

### Frontend Methods

| Method                     | Returns (resolved)                          | Use For                             |
| -------------------------- | ------------------------------------------- | ----------------------------------- |
| `isAvailable()`            | `boolean`                                   | Check if biometrics supported       |
| `authenticate(opts?)`      | `{ success, webAuthnResponse?, webAuthnCeremony?, error? }` | Run the ceremony (register or login on web) |
| `getSupportedBiometrics()` | `BiometryType[]`                            | Get available types                 |
| `hasCredentials()`         | `boolean`                                   | Whether a credential exists locally |
| `deleteCredentials()`      | `void`                                      | Clear stored credentials            |
| `logout()`                 | `void`                                      | End the local session               |
| `getState()`               | `BiometricAuthState`                        | Check current local state           |
| `subscribe(cb)`            | unsubscribe fn                              | Listen to state changes             |

`authenticate()` resolves with a result object (it does not throw). On web, the web adapter decides between registration and authentication automatically: if no credential is stored on the device it runs a registration ceremony, otherwise an authentication ceremony.

### Authentication Options

```typescript
BiometricAuth.authenticate({
  reason: 'Authenticate', // Shown to user (native prompt subtitle/description)
  title: 'Login', // Android dialog title
  subtitle: 'Verify identity', // Android subtitle
  fallbackTitle: 'Use Passcode',
  cancelTitle: 'Cancel',
  maxAttempts: 3,
  // Web: pass the server-issued challenge via webAuthnOptions (or platform.web).
  webAuthnOptions: {
    get: { challenge: serverChallenge, userVerification: 'required' },
  },
});
```

### Error Codes (canonical)

```typescript
import { BiometricErrorCode } from 'capacitor-biometric-authentication';

// result.error?.code is one of:
// USER_CANCELLED | SYSTEM_CANCELLED | AUTHENTICATION_FAILED
// NOT_AVAILABLE | NOT_ENROLLED | LOCKED_OUT | PERMISSION_DENIED
// INSECURE_CONTEXT | NO_CREDENTIALS | USER_FALLBACK | PASSCODE_NOT_SET
// INVALID_CONTEXT | TIMEOUT | PLATFORM_NOT_SUPPORTED | UNKNOWN
//
// Deprecated aliases (still exported, no longer emitted):
// BIOMETRIC_UNAVAILABLE -> NOT_AVAILABLE, LOCKOUT -> LOCKED_OUT, UNKNOWN_ERROR -> UNKNOWN
```

## Platform Requirements

| Platform | Min Version            | Setup                                        |
| -------- | ---------------------- | -------------------------------------------- |
| Web      | Chrome 67+, Safari 14+ | HTTPS required                               |
| iOS      | iOS 13+                | Add `NSFaceIDUsageDescription` to Info.plist |
| Android  | API 23+                | Permissions auto-included                    |
| Electron | macOS/Windows          | Touch ID / Windows Hello                     |

### iOS Info.plist

```xml
<key>NSFaceIDUsageDescription</key>
<string>We use Face ID to securely authenticate you</string>
```

## React Hook Example

```typescript
import { useState, useEffect } from 'react';
import BiometricAuth from 'capacitor-biometric-authentication';

function useBiometric() {
  const [available, setAvailable] = useState(false);
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    BiometricAuth.isAvailable().then(setAvailable);
    const unsub = BiometricAuth.subscribe((state) =>
      setAuthenticated(state.isAuthenticated)
    );
    return unsub;
  }, []);

  const login = async (userId: string) => {
    const result = await BiometricAuth.authenticate({ reason: 'Login' });
    if (result.success && result.webAuthnResponse) {
      // REQUIRED: POST result.webAuthnResponse to your backend to verify it
      // against the challenge the server issued. Until the server confirms,
      // the user is NOT authenticated.
    }
    return result;
  };

  return { available, authenticated, login };
}
```

## Vue 3 Composable Example

```typescript
import { ref, onMounted, onUnmounted } from 'vue';
import BiometricAuth from 'capacitor-biometric-authentication';

export function useBiometric() {
  const available = ref(false);
  const authenticated = ref(false);
  let unsub: (() => void) | undefined;

  onMounted(async () => {
    available.value = await BiometricAuth.isAvailable();
    unsub = BiometricAuth.subscribe((state) => {
      authenticated.value = state.isAuthenticated;
    });
  });

  onUnmounted(() => unsub?.());

  const login = async (reason = 'Login') => {
    return BiometricAuth.authenticate({ reason });
  };

  return { available, authenticated, login };
}
```

## Capacitor Setup

```bash
# Install
yarn add capacitor-biometric-authentication

# Sync native projects
npx cap sync

# Run
npx cap run android  # or ios
```

## Security Notes

1. **A successful client ceremony is not proof of identity.** `result.success === true` only means the WebAuthn / biometric ceremony completed locally. The backend MUST verify `result.webAuthnResponse` against the challenge it issued before granting access.
2. **Secure context required on web.** WebAuthn only runs over HTTPS or `localhost`; otherwise `authenticate()` resolves with `error.code === 'INSECURE_CONTEXT'`.
3. **Always pass a server-issued challenge.** A locally generated challenge cannot be verified server-side; the library logs a warning if you omit one.
4. **`isAuthenticated()` / client state is a UX gate, not a security boundary.** Gate sensitive operations on server-verified sessions, not on client state.
5. **Versions `< 2.3.0` are deprecated for a security issue** where the client could surface unverified or placeholder authentication results. Upgrade to `2.3.0+` and verify on the server.

## Links

- **Frontend npm**: [capacitor-biometric-authentication](https://www.npmjs.com/package/capacitor-biometric-authentication)
- **Backend npm**: [webauthn-server-buildkit](https://www.npmjs.com/package/webauthn-server-buildkit)
- **Backend AI Guide**: [AI-INTEGRATION-GUIDE.md](https://github.com/aoneahsan/webauthn-server-buildkit/blob/main/AI-INTEGRATION-GUIDE.md)
- **Author**: [Ahsan Mahmood](https://aoneahsan.com) | aoneahsan@gmail.com
