File size: 555 Bytes
2b43822
34a23a6
2b43822
 
34a23a6
 
 
 
 
2b43822
34a23a6
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import * as crypto from "crypto";
import basex from "base-x";

export function generateSessionToken(length: number): string {
    if (length < 1) throw new Error("invalid length. length must be greater than 0");
    const base31Tokens = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
    const base31 = basex(base31Tokens);

    const byteLength = Math.ceil((length * Math.log(256)) / Math.log(base31Tokens.length)) + 2;

    const buffer = crypto.randomBytes(Math.ceil(byteLength));
    const token = base31.encode(buffer);

    return token.substring(0, length);
}