hapticlink / server /src /helpers.ts
Anne Lefebvre
Added comments
58ad246 unverified
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);
}