-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtotp.ts
More file actions
58 lines (50 loc) · 1.33 KB
/
totp.ts
File metadata and controls
58 lines (50 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { generate, generateSecret, generateURI, verify } from 'otplib'
import QRCode from 'qrcode'
import { decrypt, encrypt } from './crypto.js'
import { env } from './env.js'
export function generateTotpSecret(): string {
return generateSecret()
}
export function generateTotpUri({
secret,
issuer,
label,
}: {
secret: string
issuer: string
label: string
}): string {
return generateURI({
issuer,
label,
secret,
})
}
export async function generateTotpCode(secret: string): Promise<string> {
return generate({ secret })
}
export async function verifyTotpCode({
secret,
token,
}: {
secret: string
token: string
}): Promise<boolean> {
const result = await verify({ secret, token, epochTolerance: 30 })
return result.valid
}
export async function getTotpQrDataUrl(otpauthUri: string): Promise<string> {
return QRCode.toDataURL(otpauthUri, { width: 200, margin: 2 })
}
export function encryptTotpSecret(secret: string): string | null {
return encrypt(secret)
}
export function decryptTotpSecret(encrypted: string): string | null {
return decrypt(encrypted)
}
export function getTotpIssuer(): string {
const issuer = env.TOTP_ISSUER ?? env.JWT_ISSUER
if (!issuer || typeof issuer !== 'string')
throw new Error('TOTP issuer is required: set TOTP_ISSUER or JWT_ISSUER in environment')
return issuer
}