Spaces:
Paused
Paused
File size: 785 Bytes
2b43822 34a23a6 2b43822 58ad246 2b43822 34a23a6 2b43822 34a23a6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import * as crypto from "crypto";
import basex from "base-x";
/**
* Generates a random, cryptographically secure token using uppercase, readable characters.
* Characters that are used: ABCDEFGHJKMNPQRSTUVWXYZ23456789
* @param {number} length - length of the token
* @returns {string}
*/
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);
}
|