0
# Authenticator
1
2
The Authenticator class provides Google Authenticator compatible TOTP functionality with Base32 secret encoding. It's the most commonly used component for implementing two-factor authentication in web applications.
3
4
## Capabilities
5
6
### Token Generation
7
8
Generates a 6-digit TOTP token from a Base32-encoded secret.
9
10
```typescript { .api }
11
/**
12
* Generate a TOTP token from a Base32 secret
13
* @param secret - Base32-encoded secret key
14
* @returns 6-digit token string
15
*/
16
generate(secret: string): string;
17
```
18
19
**Usage Example:**
20
21
```typescript
22
import { authenticator } from "otplib";
23
24
const secret = "KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD";
25
const token = authenticator.generate(secret);
26
console.log(token); // "123456"
27
```
28
29
### Token Verification
30
31
Verifies a token against a secret with configurable time window tolerance.
32
33
```typescript { .api }
34
/**
35
* Verify a token against a Base32 secret
36
* @param token - 6-digit token to verify
37
* @param secret - Base32-encoded secret key
38
* @returns true if token is valid within time window
39
*/
40
check(token: string, secret: string): boolean;
41
42
/**
43
* Object-based token verification
44
* @param opts - Object containing token and secret
45
* @returns true if token is valid within time window
46
*/
47
verify(opts: { token: string; secret: string }): boolean;
48
```
49
50
**Usage Examples:**
51
52
```typescript
53
import { authenticator } from "otplib";
54
55
const secret = "KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD";
56
const token = "123456";
57
58
// Method 1: Direct parameters
59
const isValid = authenticator.check(token, secret);
60
61
// Method 2: Object parameters
62
const isValid2 = authenticator.verify({ token, secret });
63
64
console.log(isValid); // true or false
65
```
66
67
### Secret Generation
68
69
Generates cryptographically secure Base32-encoded secrets for new users.
70
71
```typescript { .api }
72
/**
73
* Generate a random Base32 secret key
74
* @param numberOfBytes - Number of random bytes (default: 10)
75
* @returns Base32-encoded secret string
76
*/
77
generateSecret(numberOfBytes?: number): string;
78
```
79
80
**Usage Example:**
81
82
```typescript
83
import { authenticator } from "otplib";
84
85
// Generate with default length (10 bytes = 16 Base32 characters)
86
const secret = authenticator.generateSecret();
87
console.log(secret); // "JBSWY3DPEHPK3PXP"
88
89
// Generate with custom length
90
const longSecret = authenticator.generateSecret(20);
91
console.log(longSecret); // Longer Base32 string
92
```
93
94
### QR Code URI Generation
95
96
Creates otpauth:// URIs for QR code generation, compatible with Google Authenticator and other apps.
97
98
```typescript { .api }
99
/**
100
* Generate an otpauth URI for QR code creation
101
* @param accountName - User identifier (usually email)
102
* @param issuer - Service name
103
* @param secret - Base32-encoded secret
104
* @returns otpauth:// URI string
105
*/
106
keyuri(accountName: string, issuer: string, secret: string): string;
107
```
108
109
**Usage Example:**
110
111
```typescript
112
import { authenticator } from "otplib";
113
import QRCode from "qrcode";
114
115
const secret = authenticator.generateSecret();
116
const user = "user@example.com";
117
const service = "My App";
118
119
const otpauth = authenticator.keyuri(user, service, secret);
120
console.log(otpauth);
121
// "otpauth://totp/My%20App:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=My%20App"
122
123
// Generate QR code
124
QRCode.toDataURL(otpauth, (err, imageUrl) => {
125
if (!err) {
126
console.log(imageUrl); // Data URL for QR code image
127
}
128
});
129
```
130
131
### Advanced Delta Checking
132
133
Check token with detailed timing information for debugging and advanced use cases.
134
135
```typescript { .api }
136
/**
137
* Check token with timing delta information
138
* @param token - Token to verify
139
* @param secret - Base32 secret
140
* @returns Delta value: 0 = exact match, negative = past window, positive = future window, null = invalid
141
*/
142
checkDelta(token: string, secret: string): number | null;
143
```
144
145
**Usage Example:**
146
147
```typescript
148
import { authenticator } from "otplib";
149
150
const secret = "KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD";
151
const token = "123456";
152
153
const delta = authenticator.checkDelta(token, secret);
154
if (delta === 0) {
155
console.log("Token is from current time window");
156
} else if (delta && delta < 0) {
157
console.log(`Token is from ${Math.abs(delta)} time window(s) ago`);
158
} else if (delta && delta > 0) {
159
console.log(`Token is from ${delta} time window(s) in the future`);
160
} else {
161
console.log("Token is invalid");
162
}
163
```
164
165
### Secret Encoding/Decoding
166
167
Convert between raw secret keys and Base32 encoding.
168
169
```typescript { .api }
170
/**
171
* Encode a raw secret to Base32
172
* @param secret - Raw secret key
173
* @returns Base32-encoded string
174
*/
175
encode(secret: string): string;
176
177
/**
178
* Decode a Base32 secret to raw format
179
* @param secret - Base32-encoded secret
180
* @returns Raw secret key
181
*/
182
decode(secret: string): string;
183
```
184
185
**Usage Example:**
186
187
```typescript
188
import { authenticator } from "otplib";
189
190
const rawSecret = "hello world";
191
const base32Secret = authenticator.encode(rawSecret);
192
console.log(base32Secret); // "NBSWY3DPEB3W64TMMQ======"
193
194
const decoded = authenticator.decode(base32Secret);
195
console.log(decoded); // "hello world"
196
```
197
198
### Configuration Management
199
200
Manage instance-level configuration options.
201
202
```typescript { .api }
203
/**
204
* Get/set configuration options
205
*/
206
options: Partial<AuthenticatorOptions>;
207
208
/**
209
* Reset options to default values
210
*/
211
resetOptions(): void;
212
213
/**
214
* Get all options with defaults applied
215
* @returns Complete options object
216
*/
217
allOptions(): Readonly<AuthenticatorOptions>;
218
```
219
220
**Usage Example:**
221
222
```typescript
223
import { authenticator } from "otplib";
224
225
// View current options
226
console.log(authenticator.options);
227
228
// Modify options
229
authenticator.options = { digits: 8, step: 60 };
230
231
// Reset to defaults
232
authenticator.resetOptions();
233
234
// Get complete options with defaults
235
const fullOptions = authenticator.allOptions();
236
console.log(fullOptions.digits); // 6 (default)
237
```
238
239
## Types
240
241
```typescript { .api }
242
interface AuthenticatorOptions extends TOTPOptions {
243
keyEncoder: (secret: string, encoding: string) => string;
244
keyDecoder: (secret: string, encoding: string) => string;
245
createRandomBytes: (size: number, encoding: string) => string;
246
}
247
248
interface TOTPOptions extends HOTPOptions {
249
epoch: number;
250
step: number;
251
window: number | [number, number];
252
}
253
254
interface HOTPOptions {
255
algorithm: 'sha1' | 'sha256' | 'sha512';
256
digits: number;
257
encoding: 'ascii' | 'base64' | 'hex' | 'latin1' | 'utf8';
258
createDigest: (algorithm: string, key: string, data: string) => string;
259
createHmacKey: (algorithm: string, secret: string, encoding: string) => string;
260
}
261
```