or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authenticator.mdconfiguration.mdhotp.mdindex.mdpresets.mdtotp.md

totp.mddocs/

0

# TOTP (Time-based One-Time Password)

1

2

TOTP implements RFC 6238 time-based one-time passwords. Unlike the Authenticator class, TOTP works with raw secret keys in various encodings and provides more direct control over time-based token generation.

3

4

## Capabilities

5

6

### Token Generation

7

8

Generates time-based tokens using the current timestamp and configured time step.

9

10

```typescript { .api }

11

/**

12

* Generate a TOTP token based on current time

13

* @param secret - Secret key in the configured encoding

14

* @returns Token string with configured digit length

15

*/

16

generate(secret: string): string;

17

```

18

19

**Usage Example:**

20

21

```typescript

22

import { totp } from "otplib";

23

24

const secret = "your-secret-key";

25

const token = totp.generate(secret);

26

console.log(token); // "123456"

27

28

// Generate with custom options

29

totp.options = { digits: 8, step: 60 };

30

const longToken = totp.generate(secret);

31

console.log(longToken); // "12345678"

32

```

33

34

### Token Verification

35

36

Verifies tokens with configurable time window tolerance for network delays and clock skew.

37

38

```typescript { .api }

39

/**

40

* Verify a TOTP token with time window tolerance

41

* @param token - Token to verify

42

* @param secret - Secret key

43

* @returns true if token is valid within configured window

44

*/

45

check(token: string, secret: string): boolean;

46

47

/**

48

* Object-based token verification

49

* @param opts - Object containing token and secret

50

* @returns true if token is valid within configured window

51

*/

52

verify(opts: { token: string; secret: string }): boolean;

53

```

54

55

**Usage Examples:**

56

57

```typescript

58

import { totp } from "otplib";

59

60

const secret = "your-secret-key";

61

const token = "123456";

62

63

// Method 1: Direct parameters

64

const isValid = totp.check(token, secret);

65

66

// Method 2: Object parameters

67

const isValid2 = totp.verify({ token, secret });

68

69

// Configure time window (±1 time step = ±30 seconds by default)

70

totp.options = { window: 1 };

71

const isValidWithWindow = totp.check(token, secret);

72

73

// Asymmetric window: 2 steps past, 1 step future

74

totp.options = { window: [2, 1] };

75

const isValidAsymmetric = totp.check(token, secret);

76

```

77

78

### Delta Checking

79

80

Advanced verification that returns timing information about when the token was valid.

81

82

```typescript { .api }

83

/**

84

* Check token with detailed timing information

85

* @param token - Token to verify

86

* @param secret - Secret key

87

* @returns Delta value: 0 = current window, negative = past, positive = future, null = invalid

88

*/

89

checkDelta(token: string, secret: string): number | null;

90

```

91

92

**Usage Example:**

93

94

```typescript

95

import { totp } from "otplib";

96

97

const secret = "your-secret-key";

98

const token = "123456";

99

100

const delta = totp.checkDelta(token, secret);

101

if (delta === 0) {

102

console.log("Token is from current time window");

103

} else if (delta && delta < 0) {

104

console.log(`Token was valid ${Math.abs(delta)} window(s) ago`);

105

} else if (delta && delta > 0) {

106

console.log(`Token will be valid in ${delta} window(s)`);

107

} else {

108

console.log("Token is invalid");

109

}

110

```

111

112

### Time Information

113

114

Get timing information about the current token period.

115

116

```typescript { .api }

117

/**

118

* Get seconds remaining in current time window

119

* @returns Seconds until next token

120

*/

121

timeRemaining(): number;

122

123

/**

124

* Get seconds used in current time window

125

* @returns Seconds since current token became valid

126

*/

127

timeUsed(): number;

128

```

129

130

**Usage Example:**

131

132

```typescript

133

import { totp } from "otplib";

134

135

const remaining = totp.timeRemaining();

136

const used = totp.timeUsed();

137

138

console.log(`Token expires in ${remaining} seconds`);

139

console.log(`Token has been valid for ${used} seconds`);

140

141

// Useful for showing countdown timers in UIs

142

setInterval(() => {

143

const remaining = totp.timeRemaining();

144

if (remaining === 30) { // Start of new period

145

console.log("New token generated");

146

}

147

}, 1000);

148

```

149

150

### QR Code URI Generation

151

152

Generate otpauth:// URIs for TOTP configuration.

153

154

```typescript { .api }

155

/**

156

* Generate an otpauth URI for TOTP setup

157

* @param accountName - User identifier

158

* @param issuer - Service name

159

* @param secret - Secret key

160

* @returns otpauth://totp/ URI string

161

*/

162

keyuri(accountName: string, issuer: string, secret: string): string;

163

```

164

165

**Usage Example:**

166

167

```typescript

168

import { totp } from "otplib";

169

170

const secret = "your-secret-key";

171

const user = "user@example.com";

172

const service = "My Service";

173

174

const otpauth = totp.keyuri(user, service, secret);

175

console.log(otpauth);

176

// "otpauth://totp/My%20Service:user@example.com?secret=your-secret-key&issuer=My%20Service"

177

```

178

179

### Configuration Management

180

181

Manage TOTP-specific configuration options.

182

183

```typescript { .api }

184

/**

185

* Get/set configuration options

186

*/

187

options: Partial<TOTPOptions>;

188

189

/**

190

* Reset options to default values

191

*/

192

resetOptions(): void;

193

194

/**

195

* Get all options with defaults applied

196

* @returns Complete options object

197

*/

198

allOptions(): Readonly<TOTPOptions>;

199

200

/**

201

* Create new instance with custom defaults

202

* @param defaultOptions - Custom default options

203

* @returns New TOTP instance

204

*/

205

create(defaultOptions?: Partial<TOTPOptions>): TOTP;

206

```

207

208

**Usage Examples:**

209

210

```typescript

211

import { totp } from "otplib";

212

213

// Configure options

214

totp.options = {

215

digits: 8, // 8-digit tokens

216

step: 60, // 60-second time step

217

window: [2, 1], // Allow 2 past, 1 future window

218

algorithm: 'sha256'

219

};

220

221

// Create instance with custom defaults

222

const customTotp = totp.create({

223

digits: 6,

224

step: 30,

225

algorithm: 'sha1'

226

});

227

228

// Reset to library defaults

229

totp.resetOptions();

230

231

// View complete configuration

232

const config = totp.allOptions();

233

console.log(config.step); // 30

234

console.log(config.digits); // 6

235

```

236

237

## Common Configuration Patterns

238

239

### Standard Google Authenticator Compatible

240

241

```typescript

242

import { totp } from "otplib";

243

244

totp.options = {

245

digits: 6,

246

step: 30,

247

algorithm: 'sha1',

248

encoding: 'ascii',

249

window: 1

250

};

251

```

252

253

### High Security Configuration

254

255

```typescript

256

import { totp } from "otplib";

257

258

totp.options = {

259

digits: 8,

260

step: 15, // Shorter validity period

261

algorithm: 'sha256', // Stronger hash

262

window: 0 // No time tolerance

263

};

264

```

265

266

### Network Tolerant Configuration

267

268

```typescript

269

import { totp } from "otplib";

270

271

totp.options = {

272

window: [3, 2] // Allow more past/future tolerance

273

};

274

```

275

276

## Types

277

278

```typescript { .api }

279

interface TOTPOptions extends HOTPOptions {

280

/** Starting time in milliseconds since JavaScript epoch */

281

epoch: number;

282

/** Time step in seconds */

283

step: number;

284

/** Time window tolerance: number or [past, future] */

285

window: number | [number, number];

286

}

287

288

interface HOTPOptions {

289

algorithm: 'sha1' | 'sha256' | 'sha512';

290

digits: number;

291

encoding: 'ascii' | 'base64' | 'hex' | 'latin1' | 'utf8';

292

createDigest: (algorithm: string, key: string, data: string) => string;

293

createHmacKey: (algorithm: string, secret: string, encoding: string) => string;

294

digest?: string;

295

}

296

```