# Biometric Web API SDK - User Guide

## 1. Quick Start

For experienced developers, here's the fastest way to get started:

1.  **Run the Service:** Execute `webapi.exe` from the `executables` directory. It will start the local server on `http://localhost:8080`.
2.  **Include the Library:** Add `biometric-scanner-lib.js` to your frontend project.
3.  **Instantiate the Class:** In your JavaScript, create a new instance of the `BiometricScanner` class, targeting a container element on your page:
    ```javascript
    const scanner = new BiometricScanner('#scanner-container', {
        baseUrl: 'http://localhost:8080' // Optional: if your service runs elsewhere
    });
    ```
4.  **Listen for Events:** Add an event listener to capture the fingerprint data when the process is complete.
    ```javascript
    document.addEventListener('enrollmentComplete', (e) => {
        console.log('Fingerprint Data:', e.detail.scannedData);
        // Send this data to your server
    });
    ```

For more detailed instructions, please continue reading.

## 2. Introduction

Welcome to the Biometric Web API SDK! This guide provides a complete, production-ready solution for integrating Futronic fingerprint scanners into any web application. The core of the project is a high-performance C++ Web API that runs as a local service on a client's machine, bridging the communication gap between the browser and the hardware.

This package is designed for flexibility. You can integrate the included JavaScript library directly into your existing projects (whether plain HTML/JS, React, Vue, Angular, etc.) or use the full-featured Laravel example application as a starting point for a complete member management and authentication system.

### 1.1. Core Features

*   **Standalone C++ Web API:** A lightweight, self-contained executable (`webapi.exe`) that runs a local web server, exposing a simple RESTful API for fingerprint scanning. No complex server-side dependencies are required on the client machine.
*   **Flexible Frontend Integration:** A modern, component-based JavaScript library that can be easily dropped into any new or existing web project to add fingerprint enrollment and verification UI.
*   **Full-Featured Laravel Example:** A complete, production-ready Laravel 10 application demonstrating member management (CRUD), multi-finger enrollment, and both 1:1 and 1:N verification.
*   **Multi-Finger Enrollment:** A guided UI process for enrolling up to four fingerprints per member, significantly improving verification reliability.
*   **1:N & 1:1 Verification:** Supports both identifying a member from a large database by their fingerprint (1:N) and verifying a specific member's identity against their stored templates (1:1).
*   **Demo Mode:** Test the complete enrollment and verification flow without a physical fingerprint scanner, perfect for development and demonstrations.

## 3. Installation

### 3.1. For End-Users (Installer)

This is the standard method for deploying the service to a user's machine.

1.  **Connect Scanner:** Connect your Futronic fingerprint scanner to a USB port.
2.  **Build Installer:** If you are a developer, you must first build the installer. Navigate to the `installer/` directory and run the `setup.iss` script using [Inno Setup](https://jrsoftware.org/isinfo.php). The compiled installer (e.g., `Biometric_Web_API_Installer.exe`) will be in the `installer/Output/` subdirectory.
3.  **Run Installer:** Distribute and run the compiled installer on the end-user's machine. It will automatically install the necessary Futronic drivers and the Biometric Web API service.
4.  **Verify Service:** After installation, a console window for `webapi.exe` will appear. This window must remain open for the service to function.

### 3.2. For Developers (Compiling from Source)

If you need to modify or debug the C++ backend, follow these steps:

1.  **Prerequisites:** Ensure you have Visual Studio 2022 (or later) with the "Desktop development with C++" workload installed.
2.  **Open Solution:** Navigate to `src/server/cpp/` and open the `webapi.sln` file in Visual Studio.
3.  **Set Build Configuration:** Choose the `Release` and `x64` configuration for the best performance.
4.  **Build the Project:** Build the solution (F7 or Build > Build Solution). The compiled `webapi.exe` will be located in the `src/server/cpp/x64/Release/` directory.
5.  **Run:** You can run the executable directly from Visual Studio or from the command line.

## 4. Configuration

The C++ Web API service can be configured via command-line arguments.

### 4.1. `--origin`

Specifies the allowed origin for Cross-Origin Resource Sharing (CORS). This is a critical security feature.

*   **Usage:** `webapi.exe --origin https://your-domain.com`
*   **Default:** `*` (Allows all origins, suitable for development but **not** recommended for production).
*   **Recommendation:** In a production environment, always set this to the domain of your web application to prevent unauthorized websites from accessing the API.

## 5. C++ Web API Reference

The backend server exposes the following RESTful API endpoints. All communication happens over HTTP on `localhost:8080` by default.

### 5.1. GET /api/config

Retrieves a session-specific CSRF token. This should be the first call your frontend makes. The token received must be sent in the `X-CSRF-Token` header for all subsequent API calls.

*   **Method:** `GET`
*   **Success Response:** `application/json`
    ```json
    {
        "csrfToken": "a1b2c3d4e5f6..."
    }
    ```

### 5.2. GET /api/scan/single

Initiates a single fingerprint scan. The server waits for the user to touch the scanner and captures the fingerprint image and template.

*   **Method:** `GET`
*   **Headers:**
    *   `X-CSRF-Token` (string, required): The token obtained from `/api/config`.
*   **Success Response:** `application/json`
    ```json
    {
        "success": true,
        "imageBase64": "data:image/bmp;base64,...",
        "templateBase64": "..."
    }
    ```
*   **Error Response:**
    ```json
    {
        "success": false,
        "message": "Error message explaining the failure."
    }
    ```

### 5.3. POST /verify_with_template

Verifies a live fingerprint scan against one or more provided fingerprint templates.

*   **Method:** `POST`
*   **Headers:**
    *   `X-CSRF-Token` (string, required): The token obtained from `/api/config`.
*   **Content-Type:** `application/x-www-form-urlencoded`
*   **Request Body Parameters:**
    *   `template1` (string, required): Base64 encoded fingerprint template.
    *   `template2` (string, optional): Additional template.
    *   ... (and so on)
*   **Success Response:** `application/json`
    ```json
    {
        "success": true,
        "verified": true
    }
    ```
*   **Failure Response (No Match):**
    ```json
    {
        "success": true,
        "verified": false,
        "message": "Verification failed: No matching fingerprint found."
    }
    ```

## 6. Frontend Usage

The core of the frontend is the `BiometricScanner` class found in `src/frontend/biometric-scanner-lib.js`.

### 6.1. Initialization

To use the scanner, create a `div` element and initialize the class in your JavaScript.

```html
<div id="scanner-container"></div>

<script src="biometric-scanner-lib.js"></script>
<script>
    const scanner = new BiometricScanner('#scanner-container', {
        baseUrl: 'http://localhost:8080' // Connect to the local service
    });
</script>
```

### 6.2. Customization Options

You can pass an options object as the second argument to the constructor:

*   `baseUrl`: (String, required) The full URL of the Biometric Web API service.
*   `themeColor`: (String, optional) The primary color for UI elements. Defaults to `#007bff`.
*   `logoUrl`: (String, optional) URL for a logo to be displayed in the header. Defaults to `null`.
*   `verification`: (Boolean, optional) If `true`, the UI is configured for a single verification scan instead of the multi-finger enrollment process. Defaults to `false`.

### 6.3. Handling Events

The component emits custom events to signal completion.

*   **`enrollmentComplete`**: Fired after all fingerprints have been successfully scanned in enrollment mode. The `event.detail` object contains the `scannedData`.
*   **`verificationComplete`**: Fired after a successful scan in verification mode. The `event.detail` object contains the `template`.

### 6.4. Full Enrollment Example

This example shows how to initialize the scanner and submit the captured templates to your server.

```html
<div id="scanner-container"></div>
<form id="enrollForm" action="/your-enroll-route" method="POST" style="display:none;">
    <input type="hidden" name="template1" id="template1">
    <input type="hidden" name="template2" id="template2">
    <input type="hidden" name="template3" id="template3">
    <input type="hidden" name="template4" id="template4">
</form>

<script>
    const scanner = new BiometricScanner('#scanner-container');

    document.addEventListener('enrollmentComplete', (e) => {
        const scannedData = e.detail.scannedData;
        document.getElementById('template1').value = scannedData.left[0].templateBase64;
        document.getElementById('template2').value = scannedData.left[1].templateBase64;
        document.getElementById('template3').value = scannedData.right[0].templateBase64;
        document.getElementById('template4').value = scannedData.right[1].templateBase64;
        document.getElementById('enrollForm').submit();
    });
</script>
```

## 7. Troubleshooting

*   **Issue: The scanner UI shows "Local Service Required".**
    *   **Solution:** This means the frontend could not connect to the `baseUrl`. Ensure `webapi.exe` is running and that the `baseUrl` you provided during initialization is correct.
*   **Issue: Fingerprint Scanner Not Detected.**
    *   **Solution:** Ensure the scanner is connected via USB and reinstall the Futronic drivers from the installer if necessary.

## 8. Security

### 8.1. Localhost Binding

The `webapi.exe` service binds exclusively to `localhost` (`127.0.0.1`), meaning it only accepts connections from the same machine. It is not accessible from the local network, minimizing its attack surface.

### 8.2. CORS (Cross-Origin Resource Sharing)

For security, the API service enforces a strict CORS policy. By default, it only allows requests from the same origin. You must use the `--origin` command-line flag to specify the domain of your web application.

```bash
# Example for production
webapi.exe --origin https://your-secure-domain.com
```

### 8.3. CSRF (Cross-Site Request Forgery) Protection

The SDK implements a dynamic token-based CSRF protection to ensure that only your web application can interact with the local API.

**Workflow:**
1.  On initialization, the `BiometricScanner` library calls `/api/config` to get a unique, session-specific CSRF token.
2.  The library automatically sends this token in the `X-CSRF-Token` header with every subsequent API request.
3.  The C++ service validates this token. If the token is missing or invalid, the request is rejected with a `403 Forbidden` error.

This entire process is handled automatically by the library.

### 8.4. Server Architecture

The C++ Web API is built on a multi-threaded architecture. Each incoming client connection is handled on a separate thread, allowing the server to process multiple requests concurrently. This ensures that a long-running operation (like waiting for a fingerprint scan) on one browser tab will not block or affect other browser tabs or applications interacting with the service. This robust, non-blocking design is what makes the API suitable for production environments.

## 9. Licenses & Disclaimer

**Legal Disclaimer:** The following is for informational purposes only and does not constitute legal advice. You are responsible for your own legal compliance.

### 9.1. Futronic Components

This SDK utilizes official drivers and certain library files (`.dll`) from the free SDK provided by Futronic. Our product acts as a bridge to make these components accessible and easy to integrate into web applications.

*   The Futronic drivers and SDK components are the intellectual property of Futronic Technology Company Ltd.
*   The use and redistribution of these components are subject to the license agreement provided by Futronic. It is your responsibility to review and comply with their terms.
*   This product does not claim ownership of the Futronic drivers or SDK files. We are providing a custom-built integration solution.
*   For the original drivers, SDK, and license agreements, please visit the official Futronic website: [https://www.futronic-tech.com/](https://www.futronic-tech.com/)

### 9.2. Disclaimer of Warranty

The Futronic components are provided "as is". While we have built our SDK to integrate with them, we do not provide a warranty for the performance, reliability, or suitability of the Futronic drivers or DLL files themselves. Any support requests related to the core functionality of the Futronic hardware or drivers should be directed to Futronic.

## 10. Support

If you encounter any issues or have questions, please refer to the CodeCanyon support page for this item or contact the author directly.
