@privateav/sdk 3.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 SafePassage
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,344 @@
1
+ # PrivateAV SDK v3.4
2
+
3
+ A lightweight SDK for integrating PrivateAV age verification into your website or application.
4
+
5
+ ## Features
6
+
7
+ - **Ultra-lightweight**: ~18KB minified
8
+ - **Simple integration**: 5 lines of code to get started
9
+ - **Two modes**: Same-tab redirect or new-tab popup
10
+ - **TypeScript support**: Full type definitions included
11
+ - **Auto-environment detection**: Works seamlessly across environments
12
+ - **Secure**: HMAC-signed state parameters, automatic session management
13
+ - **Compliant**: Enforces minimum age of 25
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @privateav/sdk
19
+ ```
20
+
21
+ Or load directly from jsDelivr CDN (no bundler required):
22
+
23
+ ```html
24
+ <script src="https://cdn.jsdelivr.net/npm/@privateav/sdk@latest/dist/privateav.min.js"></script>
25
+ ```
26
+
27
+ ## Quick Start
28
+
29
+ ### With npm/bundler
30
+
31
+ ```javascript
32
+ import { PrivateAV } from '@privateav/sdk';
33
+
34
+ const sp = new PrivateAV({
35
+ apiKey: 'pk_...', // Your public key from the dashboard
36
+ returnUrl: window.location.origin + '/verified'
37
+ });
38
+
39
+ // Start verification - redirects user to PrivateAV
40
+ await sp.verify();
41
+ ```
42
+
43
+ ### With CDN (no bundler)
44
+
45
+ ```html
46
+ <script src="https://cdn.jsdelivr.net/npm/@privateav/sdk@latest/dist/privateav.min.js"></script>
47
+ <script>
48
+ const sp = new PrivateAV({
49
+ apiKey: 'pk_...',
50
+ returnUrl: window.location.origin + '/verified'
51
+ });
52
+
53
+ document.getElementById('verify-btn').onclick = () => sp.verify();
54
+ </script>
55
+ ```
56
+
57
+ That's it! The SDK handles session creation automatically.
58
+
59
+ ## Configuration
60
+
61
+ | Option | Type | Required | Description |
62
+ |--------|------|----------|-------------|
63
+ | apiKey | string | Yes | Your public API key (`pk_...`) |
64
+ | returnUrl | string | Yes | URL to redirect after verification |
65
+ | environment | string | No | `'production'` or `'staging'` (auto-detected) |
66
+ | mode | string | No | `'redirect'` (default) or `'new-tab'` |
67
+ | defaultChallengeAge | number | No | Default minimum age (25 or higher) |
68
+ | defaultVerificationMode | string | No | `'L1'` or `'L2'` |
69
+ | onComplete | function | No | Callback for new-tab mode |
70
+ | onCancel | function | No | Called when user closes popup (new-tab mode) |
71
+ | onError | function | No | Error handler |
72
+
73
+ ## Verification Options
74
+
75
+ Override settings per-verification:
76
+
77
+ ```javascript
78
+ await sp.verify({
79
+ challengeAge: 30, // Override minimum age for this session
80
+ verificationMode: 'L2', // Force ID verification for this session
81
+ externalUserId: 'user-123', // Your user ID (returned in webhooks)
82
+ skipIntro: true, // Skip intro screen
83
+ autoReturn: true // Auto-redirect after success
84
+ });
85
+ ```
86
+
87
+ ### Verification Modes
88
+
89
+ - **L1**: Age estimation using computer vision (faster, less friction)
90
+ - **L2**: Full ID document verification (more thorough)
91
+
92
+ ## Integration Modes
93
+
94
+ ### Same-Tab Redirect (Default)
95
+
96
+ User is redirected to PrivateAV, then back to your `returnUrl`:
97
+
98
+ ```javascript
99
+ const sp = new PrivateAV({
100
+ apiKey: 'pk_...',
101
+ returnUrl: '/age-verified'
102
+ });
103
+
104
+ await sp.verify();
105
+ // User is redirected to PrivateAV...
106
+ // After verification, user returns to /age-verified?sessionId=xxx&status=verified
107
+ ```
108
+
109
+ ### New-Tab Mode
110
+
111
+ Verification opens in a popup window:
112
+
113
+ ```javascript
114
+ const sp = new PrivateAV({
115
+ apiKey: 'pk_...',
116
+ returnUrl: '/age-verified',
117
+ mode: 'new-tab',
118
+ onComplete: (result) => {
119
+ console.log('Verification complete:', result.sessionId, result.status);
120
+ // Validate on your server, then update UI
121
+ },
122
+ onCancel: () => {
123
+ console.log('User closed the verification window');
124
+ },
125
+ onError: (error) => {
126
+ console.error('Verification error:', error.message);
127
+ }
128
+ });
129
+
130
+ await sp.verify();
131
+ ```
132
+
133
+ ## Server-Side Validation (Required!)
134
+
135
+ After verification completes, **always validate the result on your server** before granting access:
136
+
137
+ ```javascript
138
+ // Node.js / Express example
139
+ app.get('/age-verified', async (req, res) => {
140
+ const { sessionId } = req.query;
141
+
142
+ // Validate with your SECRET key (sk_...)
143
+ const response = await fetch(
144
+ `https://api.privateav.com/api/v1/sessions/${sessionId}`,
145
+ {
146
+ headers: {
147
+ 'Authorization': `Bearer ${process.env.SAFEPASSAGE_SECRET_KEY}`
148
+ }
149
+ }
150
+ );
151
+
152
+ const session = await response.json();
153
+
154
+ if (session.status === 'VERIFIED') {
155
+ // Grant access
156
+ req.session.ageVerified = true;
157
+ res.redirect('/content');
158
+ } else {
159
+ res.redirect('/age-verification-failed');
160
+ }
161
+ });
162
+ ```
163
+
164
+ > **Security Note**: Never trust client-side verification status alone. Always validate server-side using your secret key.
165
+
166
+ ## Webhooks (Recommended)
167
+
168
+ For reliable verification tracking, configure webhooks in your dashboard:
169
+
170
+ ```javascript
171
+ // Webhook payload example
172
+ {
173
+ "event": "verification.completed",
174
+ "sessionId": "abc-123",
175
+ "verified": true,
176
+ "externalUserId": "your-user-id", // If provided during verify()
177
+ "timestamp": "2025-01-15T10:30:00Z"
178
+ }
179
+ ```
180
+
181
+ ## Complete Example
182
+
183
+ ### HTML + CDN
184
+
185
+ ```html
186
+ <!DOCTYPE html>
187
+ <html>
188
+ <head>
189
+ <title>Age Verification</title>
190
+ <script src="https://cdn.jsdelivr.net/npm/@privateav/sdk@latest/dist/privateav.min.js"></script>
191
+ </head>
192
+ <body>
193
+ <button id="verify-btn">Verify Your Age</button>
194
+
195
+ <script>
196
+ const sp = new PrivateAV({
197
+ apiKey: 'pk_...',
198
+ returnUrl: window.location.origin + '/verified'
199
+ });
200
+
201
+ document.getElementById('verify-btn').onclick = () => sp.verify();
202
+ </script>
203
+ </body>
204
+ </html>
205
+ ```
206
+
207
+ ### React Component
208
+
209
+ ```jsx
210
+ import { useState } from 'react';
211
+ import { PrivateAV } from '@privateav/sdk';
212
+
213
+ function AgeGate() {
214
+ const [verifying, setVerifying] = useState(false);
215
+
216
+ const sp = new PrivateAV({
217
+ apiKey: process.env.NEXT_PUBLIC_SAFEPASSAGE_KEY,
218
+ returnUrl: window.location.origin + '/verified'
219
+ });
220
+
221
+ const handleVerify = async () => {
222
+ setVerifying(true);
223
+ try {
224
+ await sp.verify();
225
+ } catch (error) {
226
+ console.error('Failed to start verification:', error);
227
+ setVerifying(false);
228
+ }
229
+ };
230
+
231
+ return (
232
+ <button onClick={handleVerify} disabled={verifying}>
233
+ {verifying ? 'Redirecting...' : 'Verify Your Age'}
234
+ </button>
235
+ );
236
+ }
237
+ ```
238
+
239
+ ## TypeScript
240
+
241
+ Full TypeScript support included:
242
+
243
+ ```typescript
244
+ import { PrivateAV, PrivateAVConfig, VerificationResult } from '@privateav/sdk';
245
+
246
+ const config: PrivateAVConfig = {
247
+ apiKey: process.env.NEXT_PUBLIC_SAFEPASSAGE_KEY!,
248
+ returnUrl: '/verified',
249
+ mode: 'new-tab',
250
+ onComplete: (result: VerificationResult) => {
251
+ console.log(`Session ${result.sessionId}: ${result.status}`);
252
+ }
253
+ };
254
+
255
+ const sp = new PrivateAV(config);
256
+ ```
257
+
258
+ ## Skip Parameters
259
+
260
+ For streamlined embedded flows:
261
+
262
+ ```javascript
263
+ // Skip intro screen (go directly to camera)
264
+ await sp.verify({ skipIntro: true });
265
+
266
+ // Auto-redirect after success (no success screen)
267
+ await sp.verify({ autoReturn: true });
268
+
269
+ // Both - minimal user interaction
270
+ await sp.verify({ skipIntro: true, autoReturn: true });
271
+ ```
272
+
273
+ ## Error Handling
274
+
275
+ ```javascript
276
+ const sp = new PrivateAV({
277
+ apiKey: 'pk_...',
278
+ returnUrl: '/verified',
279
+ onError: (error) => {
280
+ if (error.message.includes('popup')) {
281
+ alert('Please allow popups for age verification');
282
+ } else if (error.message.includes('rate limit')) {
283
+ alert('Too many attempts. Please wait a moment.');
284
+ } else {
285
+ console.error('Verification error:', error);
286
+ }
287
+ }
288
+ });
289
+ ```
290
+
291
+ ## API Keys
292
+
293
+ PrivateAV uses two types of API keys:
294
+
295
+ | Key Type | Prefix | Use Case |
296
+ |----------|--------|----------|
297
+ | Public Key | `pk_` | Client-side SDK (this package) |
298
+ | Secret Key | `sk_` | Server-side validation only |
299
+
300
+ > **Important**: This SDK only works with public keys (`pk_`). For server-side integrations using secret keys, use the [Direct API](https://docs.privateav.com/api) instead.
301
+
302
+ ## Browser Support
303
+
304
+ - Chrome 60+
305
+ - Firefox 60+
306
+ - Safari 12+
307
+ - Edge 79+
308
+ - Mobile browsers (iOS Safari, Chrome for Android)
309
+
310
+ ## Security Best Practices
311
+
312
+ 1. **Use public keys client-side** - Never expose secret keys in browser code
313
+ 2. **Validate server-side** - Always verify results using your secret key
314
+ 3. **Configure webhooks** - For reliable, tamper-proof verification notifications
315
+ 4. **Register callback URLs** - Pre-register your `returnUrl` in the dashboard
316
+ 5. **Use HTTPS** - SDK enforces HTTPS in production
317
+
318
+ ## Cleanup
319
+
320
+ When done with the SDK (e.g., in SPA route changes):
321
+
322
+ ```javascript
323
+ sp.destroy();
324
+ ```
325
+
326
+ ## Migration from v3.0.x
327
+
328
+ If you were using merchant-generated session IDs:
329
+
330
+ ```javascript
331
+ // Old (v3.0.x)
332
+ safePassage.verify({ sessionId: crypto.randomUUID() });
333
+
334
+ // New (v3.4+) - sessionId is auto-generated
335
+ await sp.verify();
336
+ ```
337
+
338
+ The SDK now creates sessions automatically via the API when using public keys.
339
+
340
+ ## Support
341
+
342
+ - [Documentation](https://docs.privateav.com)
343
+ - [API Reference](https://docs.privateav.com/api)
344
+ - [Dashboard](https://portal.privateav.com)
@@ -0,0 +1,13 @@
1
+ /**
2
+ * PrivateAV SDK - Redirect-based age verification
3
+ */
4
+ import { VerificationSDK } from '../../core/VerificationSDK';
5
+ import type { SDKConfig, VerificationOptions, VerificationResult, SessionValidationResponse, SessionCreationResponse, CreateSessionRequest } from '../../types/base';
6
+ export interface PrivateAVConfig extends SDKConfig {
7
+ }
8
+ export declare class PrivateAV extends VerificationSDK {
9
+ constructor(config: PrivateAVConfig);
10
+ }
11
+ export declare const VERSION = "3.4.2";
12
+ export type { SDKConfig, VerificationOptions, VerificationResult, SessionValidationResponse, SessionCreationResponse, CreateSessionRequest, };
13
+ export default PrivateAV;
@@ -0,0 +1,3 @@
1
+ import type { BrandUrls, BrandConstants } from '../../core/VerificationSDK';
2
+ export declare const BRAND_URLS: BrandUrls;
3
+ export declare const BRAND_CONSTANTS: BrandConstants;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Verification SDK - Redirect-based age verification
3
+ *
4
+ * Lightweight SDK for integrating age verification using redirect flow.
5
+ * Provides a secure, easy-to-implement solution with comprehensive
6
+ * security features and flexible integration options.
7
+ */
8
+ import type { SDKConfig, VerificationOptions } from '../types/base';
9
+ export interface UrlConfig {
10
+ apiUrl: string;
11
+ verifyUiUrl: string;
12
+ engineUrl: string;
13
+ wsUrl: string;
14
+ trustedOrigins: string[];
15
+ }
16
+ export interface BrandUrls {
17
+ production: UrlConfig;
18
+ staging: UrlConfig;
19
+ }
20
+ export interface BrandConstants {
21
+ name: string;
22
+ hmacSecretProd: string;
23
+ hmacSecretStaging: string;
24
+ messageType: string;
25
+ legacyMessageType?: string;
26
+ popupName: string;
27
+ docsUrl: string;
28
+ }
29
+ /**
30
+ * SDK Main Class
31
+ *
32
+ * Primary SDK class that manages verification sessions with comprehensive
33
+ * security and error handling. Supports both redirect and new-tab modes with
34
+ * automatic session management and PostMessage communication.
35
+ */
36
+ export declare class VerificationSDK {
37
+ private config;
38
+ private readonly brandUrls;
39
+ private readonly brandConstants;
40
+ private popupWindow;
41
+ private messageListener;
42
+ private popupMonitorInterval;
43
+ private unloadListener;
44
+ private isVerificationInProgress;
45
+ private currentSessionId;
46
+ private lastVerifyUrl;
47
+ private lastSessionToken;
48
+ private temporaryHandoffToken;
49
+ /**
50
+ * Initialize SDK
51
+ *
52
+ * Validates configuration, sets up security measures, and prepares the SDK
53
+ * for verification operations. Performs comprehensive environment validation
54
+ * and security initialization.
55
+ */
56
+ constructor(config: SDKConfig, brandUrls: BrandUrls, brandConstants: BrandConstants);
57
+ /**
58
+ * Initiate verification with race condition protection
59
+ */
60
+ verify(options?: VerificationOptions): Promise<void>;
61
+ /**
62
+ * Build verification URL with HMAC-signed state
63
+ */
64
+ private buildVerificationUrl;
65
+ /**
66
+ * Redirect in same tab
67
+ */
68
+ private redirect;
69
+ /**
70
+ * Open in new tab with PostMessage communication and proper cleanup
71
+ */
72
+ private openNewTab;
73
+ /**
74
+ * Set up automatic cleanup on page unload to prevent memory leaks
75
+ */
76
+ private setupAutoCleanup;
77
+ /**
78
+ * Auto-detect environment based on current URL
79
+ */
80
+ private detectEnvironment;
81
+ /**
82
+ * Get the current environment
83
+ */
84
+ getEnvironment(): 'production' | 'staging';
85
+ /**
86
+ * Unlock verification process to allow new verifications
87
+ */
88
+ private unlockVerification;
89
+ /**
90
+ * Internal cleanup method to prevent memory leaks
91
+ */
92
+ private cleanup;
93
+ /**
94
+ * Remove auto-cleanup listeners
95
+ */
96
+ private removeAutoCleanupListeners;
97
+ /**
98
+ * Public cleanup method for manual resource management
99
+ */
100
+ destroy(): void;
101
+ /**
102
+ * Get Portal API URL based on environment and brand
103
+ */
104
+ private getPortalApiUrl;
105
+ /**
106
+ * Get Engine URL based on environment and brand
107
+ */
108
+ private getEngineUrl;
109
+ /**
110
+ * Get WebSocket URL based on environment and brand
111
+ */
112
+ private getWebSocketUrl;
113
+ /**
114
+ * Detect if this is a public key (pk_ prefix) vs private key (sk_ prefix)
115
+ */
116
+ private isPublicKey;
117
+ /**
118
+ * Create session internally for public keys
119
+ */
120
+ private createInternalSession;
121
+ private getUrlConfig;
122
+ private getTrustedOrigins;
123
+ private getHmacSecret;
124
+ }
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './brands/privateav';
2
+ export { default } from './brands/privateav';