0
# Environment Presets
1
2
OTPLib provides different preset packages optimized for specific environments. Each preset includes pre-configured crypto and base32 implementations suitable for their target platform.
3
4
## Capabilities
5
6
### Default Preset (Node.js)
7
8
The main `otplib` package and `@otplib/preset-default` provide Node.js optimized implementations.
9
10
```typescript { .api }
11
// Main package (re-exports preset-default)
12
import { authenticator, totp, hotp } from "otplib";
13
14
// Direct preset import
15
import { authenticator, totp, hotp } from "@otplib/preset-default";
16
```
17
18
**Features:**
19
- Node.js `crypto` module for HMAC operations
20
- `thirty-two` library for Base32 encoding/decoding
21
- Optimized for server-side applications
22
- Full TypeScript support
23
24
**Usage Example:**
25
26
```typescript
27
import { authenticator, totp, hotp } from "otplib";
28
29
// All instances pre-configured for Node.js
30
const secret = authenticator.generateSecret();
31
const token = authenticator.generate(secret);
32
const isValid = authenticator.check(token, secret);
33
34
// Direct usage without additional setup
35
const totpToken = totp.generate("secret-key");
36
const hotpToken = hotp.generate("secret-key", 0);
37
```
38
39
### Browser Preset
40
41
Browser-compatible preset using pure JavaScript crypto implementations.
42
43
```typescript { .api }
44
import { authenticator, totp, hotp } from "@otplib/preset-browser";
45
```
46
47
**Features:**
48
- `crypto-js` library for HMAC operations (no Node.js dependencies)
49
- `base32-encode`/`base32-decode` for Base32 operations
50
- UMD bundle available for direct browser inclusion
51
- Automatic Buffer polyfill injection
52
53
**Installation:**
54
55
```bash
56
npm install @otplib/preset-browser
57
```
58
59
**Browser Usage:**
60
61
```html
62
<!-- Include Buffer polyfill first -->
63
<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/buffer.js"></script>
64
<!-- Include OTPLib browser preset -->
65
<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/index.js"></script>
66
67
<script>
68
// Available as window.otplib
69
const secret = window.otplib.authenticator.generateSecret();
70
const token = window.otplib.authenticator.generate(secret);
71
const isValid = window.otplib.authenticator.check(token, secret);
72
73
console.log('Secret:', secret);
74
console.log('Token:', token);
75
console.log('Valid:', isValid);
76
</script>
77
```
78
79
**Module Usage:**
80
81
```typescript
82
import { authenticator, totp, hotp } from "@otplib/preset-browser";
83
84
// Works in browser environments without Node.js dependencies
85
const secret = authenticator.generateSecret();
86
const token = authenticator.generate(secret);
87
88
// All functionality available as in Node.js preset
89
totp.options = { digits: 8 };
90
const totpToken = totp.generate("browser-secret");
91
```
92
93
### v11 Compatibility Preset
94
95
Backward compatibility preset providing v11.x API compatibility.
96
97
```typescript { .api }
98
import { authenticator, totp, hotp } from "@otplib/preset-v11";
99
```
100
101
**Features:**
102
- Compatible with otplib v11.x API
103
- Provides deprecated method warnings
104
- Same crypto implementations as default preset
105
- Gradual migration support
106
107
**Installation:**
108
109
```bash
110
npm install @otplib/preset-v11
111
```
112
113
**Usage Example:**
114
115
```typescript
116
import { authenticator, totp, hotp } from "@otplib/preset-v11";
117
118
// v11 API compatibility
119
const secret = 'KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD';
120
const token = authenticator.generate(secret);
121
const isValid = authenticator.check(token, secret);
122
123
// Deprecated methods will show console warnings but still work
124
// This helps with gradual migration to v12 API
125
```
126
127
**Migration Pattern:**
128
129
```typescript
130
// Old v11 code
131
import { authenticator } from 'otplib';
132
133
// Migration step 1: Use v11 preset
134
import { authenticator } from '@otplib/preset-v11';
135
136
// Migration step 2: Update to v12 API
137
import { authenticator } from 'otplib';
138
```
139
140
### Async Preset
141
142
Async-compatible preset for environments requiring async crypto operations.
143
144
```typescript { .api }
145
import { authenticator, totp, hotp } from "@otplib/preset-default-async";
146
```
147
148
**Features:**
149
- All methods return Promises
150
- Compatible with async crypto libraries
151
- Useful for React Native, Expo, and Web Crypto API
152
- Same API but with async/await support
153
154
**Usage Example:**
155
156
```typescript
157
import { authenticator, totp, hotp } from "@otplib/preset-default-async";
158
159
async function handleOTP() {
160
// All operations are async
161
const secret = await authenticator.generateSecret();
162
const token = await authenticator.generate(secret);
163
const isValid = await authenticator.check(token, secret);
164
165
console.log('Generated:', token);
166
console.log('Valid:', isValid);
167
}
168
169
// TOTP async usage
170
async function handleTOTP() {
171
const token = await totp.generate("secret-key");
172
const isValid = await totp.check(token, "secret-key");
173
174
return { token, isValid };
175
}
176
```
177
178
### Custom Preset Creation
179
180
Create custom presets with specific crypto and base32 implementations.
181
182
```typescript { .api }
183
import { HOTP, TOTP, Authenticator } from "@otplib/core";
184
import { createDigest, createRandomBytes } from "custom-crypto-plugin";
185
import { keyEncoder, keyDecoder } from "custom-base32-plugin";
186
187
// Create custom instances
188
const customHOTP = new HOTP({ createDigest });
189
const customTOTP = new TOTP({ createDigest });
190
const customAuthenticator = new Authenticator({
191
createDigest,
192
createRandomBytes,
193
keyEncoder,
194
keyDecoder
195
});
196
197
export { customHOTP as hotp, customTOTP as totp, customAuthenticator as authenticator };
198
```
199
200
## Preset Comparison
201
202
### Feature Matrix
203
204
| Feature | Default | Browser | v11 | Async |
205
|---------|---------|---------|-----|-------|
206
| Node.js | ✅ | ❌ | ✅ | ✅ |
207
| Browser | ❌ | ✅ | ❌ | ⚠️ |
208
| TypeScript | ✅ | ✅ | ✅ | ✅ |
209
| Bundle Size | Small | Medium | Small | Small |
210
| Async Methods | ❌ | ❌ | ❌ | ✅ |
211
| v11 Compatibility | ❌ | ❌ | ✅ | ❌ |
212
213
### Performance Characteristics
214
215
```typescript
216
// Default preset - Fastest (Node.js crypto)
217
import { authenticator } from "otplib";
218
219
// Browser preset - Slower (pure JS crypto)
220
import { authenticator } from "@otplib/preset-browser";
221
222
// Async preset - Variable (depends on crypto implementation)
223
import { authenticator } from "@otplib/preset-default-async";
224
```
225
226
## Environment-Specific Usage
227
228
### React Native / Expo
229
230
```typescript
231
// Use browser preset or create custom with React Native crypto
232
import { authenticator } from "@otplib/preset-browser";
233
234
// Or with async preset if using crypto-js async
235
import { authenticator } from "@otplib/preset-default-async";
236
```
237
238
### Webpack/Bundler Environments
239
240
```typescript
241
// Browser preset recommended for webpack builds
242
import { authenticator } from "@otplib/preset-browser";
243
244
// Avoid Node.js preset in browser bundles
245
// import { authenticator } from "otplib"; // ❌ Will bundle Node.js dependencies
246
```
247
248
### Electron Applications
249
250
```typescript
251
// Main process (Node.js)
252
import { authenticator } from "otplib";
253
254
// Renderer process (Browser-like)
255
import { authenticator } from "@otplib/preset-browser";
256
```
257
258
### Web Workers
259
260
```typescript
261
// Use browser preset in web workers
262
import { authenticator } from "@otplib/preset-browser";
263
264
self.onmessage = function(e) {
265
const token = authenticator.generate(e.data.secret);
266
self.postMessage({ token });
267
};
268
```
269
270
## Types
271
272
```typescript { .api }
273
// All presets export the same interface types
274
interface PresetExports {
275
authenticator: Authenticator;
276
totp: TOTP;
277
hotp: HOTP;
278
}
279
280
// Async preset returns Promise-wrapped methods
281
interface AsyncPresetExports {
282
authenticator: AsyncAuthenticator;
283
totp: AsyncTOTP;
284
hotp: AsyncHOTP;
285
}
286
287
interface AsyncAuthenticator {
288
generate(secret: string): Promise<string>;
289
check(token: string, secret: string): Promise<boolean>;
290
verify(opts: { token: string; secret: string }): Promise<boolean>;
291
generateSecret(numberOfBytes?: number): Promise<string>;
292
keyuri(accountName: string, issuer: string, secret: string): Promise<string>;
293
}
294
```