npm package: @lucasflsantos/agekey-web
Description: Web SDK for AgeKey - Age verification with a simple popup interface.
Latest version: 0.1.10

# @lucasflsantos/agekey-web

Web SDK for AgeKey - Age verification with a simple popup interface.

## Installation

```bash
npm install @lucasflsantos/agekey-web
# or
pnpm add @lucasflsantos/agekey-web
# or
yarn add @lucasflsantos/agekey-web
```

## Quick Start

### Basic Usage

```typescript
import { AgeKeyWeb } from '@lucasflsantos/agekey-web';

// Initialize (optional - can also pass apiBaseUrl in showPopup)
AgeKeyWeb.init({
  apiKey: "your-api-key",  // Optional: pre-fill API key in popup
  apiBaseUrl: "https://agekey-auth.richiemuhammed.workers.dev"
});

// Show the verification popup
AgeKeyWeb.showPopup({
  email: "user@example.com",  // Optional: pre-fill email
  userId: "user-123",          // Optional: pre-fill user ID
  apiKey: "your-api-key",      // Optional: pre-fill API key (if not set in init)
  apiBaseUrl: "https://agekey-auth.richiemuhammed.workers.dev",  // Optional: override worker URL
  onSuccess: (token) => {
    console.log('Verified!', token);
    // token.token - JWT token string
    // token.payload - Decoded token payload (email, verified, age, etc.)
  },
  onError: (err) => {
    console.error('Verification failed:', err);
  },
  onClose: () => {
    console.log('Popup closed');
  }
});
```

### Using in HTML (UMD/Global)

```html
<script src="https://cdn.jsdelivr.net/npm/@lucasflsantos/agekey-web@0.1.9/dist/agekey-web.js"></script>

<script>
// Wait for SDK to load
function waitForAgeKey(callback) {
  if (window.AgeKey) return callback();
  setTimeout(() => waitForAgeKey(callback), 50);
}

waitForAgeKey(() => {
  // Initialize with your API key and worker URL
  AgeKey.init({
    apiKey: "your-api-key",
    apiBaseUrl: "https://agekey-auth.richiemuhammed.workers.dev"
  });
  
  // Show popup
  AgeKey.showPopup({
    email: "user@example.com",  // Optional
    onSuccess: (token) => {
      console.log('Verified!', token);
    }
  });
});
</script>
```

## API Reference

### `AgeKeyWeb.init(config)`

Initialize the SDK with default configuration.

```typescript
AgeKeyWeb.init({
  apiKey?: string;           // Default API key (optional)
  apiBaseUrl?: string;        // Worker URL (optional)
});
```

### `AgeKeyWeb.showPopup(options)`

Show the age verification popup.

**Options:**
- `email?: string` - Pre-fill email address
- `userId?: string` - Pre-fill user ID
- `apiKey?: string` - Pre-fill API key (if not set in init)
- `apiBaseUrl?: string` - Worker URL (if not set in init)
- `onSuccess?: (token: AgeKeyToken) => void` - Called when verification succeeds
- `onError?: (err: Error) => void` - Called when verification fails
- `onClose?: () => void` - Called when popup is closed

**Returns:** Nothing (popup is shown)

### `AgeKeyWeb.closePopup()`

Programmatically close the popup.

### `AgeKeyWeb.verifyAge(request)`

Verify age programmatically (without popup).

```typescript
const result = await AgeKeyWeb.verifyAge({
  email: "user@example.com",
  apiKey: "your-api-key",  // Required if not set in init()
  userId: "user-123"       // Optional
});
```

### `AgeKeyWeb.requestToken()`

Get the stored token after verification.

```typescript
const token = await AgeKeyWeb.requestToken();
```

### `AgeKeyWeb.onToken(handler)`

Listen for token events.

```typescript
AgeKeyWeb.onToken((token) => {
  console.log('New token:', token);
});
```

### `AgeKeyWeb.onError(handler)`

Listen for error events.

```typescript
AgeKeyWeb.onError((err) => {
  console.error('Error:', err);
});
```

## How It Works

1. **User opens popup** - Shows API key and email input fields
2. **User enters credentials** - API key and email (can be pre-filled)
3. **SDK sends request** - POST to your Cloudflare Worker with `{ email, apiKey }`
4. **Worker verifies** - Calls your Bubble.io endpoint with the API key
5. **Worker returns JWT** - Signed token with verification results
6. **SDK stores token** - Available via `requestToken()` or `onToken` event

## API Key Management

Each user/customer gets their own API key:
- **Generate API keys** - Create unique keys for each customer
- **Store in Bubble** - Your Bubble workflow validates the API key
- **Pass to SDK** - Either in `init()` or `showPopup()`, or let users enter it

## Example: Bubble.io Integration

```html
<script src="https://cdn.jsdelivr.net/npm/@lucasflsantos/agekey-web@0.1.6/dist/agekey-web.js"></script>

<script>
function waitForAgeKey(callback) {
  if (window.AgeKey) return callback();
  setTimeout(() => waitForAgeKey(callback), 50);
}

waitForAgeKey(() => {
  AgeKey.init({
    apiKey: "ak_pk_customer123",  // Customer's API key
    apiBaseUrl: "https://agekey-auth.richiemuhammed.workers.dev"
  });
});

// Expose for Bubble to call
window.runAgeKeyPopup = function(email, userId) {
  AgeKey.showPopup({
    email: email,
    userId: userId,
    onSuccess: (token) => {
      // Trigger Bubble workflow with token
      console.log('Token:', token.token);
    }
  });
};
</script>
```

## TypeScript Support

Full TypeScript definitions are included:

```typescript
import type { AgeKeyToken, PopupOptions } from '@lucasflsantos/agekey-web';

const options: PopupOptions = {
  email: "user@example.com",
  onSuccess: (token: AgeKeyToken) => {
    // token is fully typed
  }
};
```

## License

MIT