diff --git a/web/utils/device-id.js b/web/utils/device-id.js new file mode 100644 --- /dev/null +++ b/web/utils/device-id.js @@ -0,0 +1,35 @@ +// @flow +import crypto from 'crypto'; + +export const deviceIDTypes = Object.freeze({ + KEYSERVER: 0, + WEB: 1, + MOBILE: 2, +}); +export type DeviceIDType = $Values; + +const alphanumeric = + '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + +function generateDeviceID(type: DeviceIDType): string { + const symbols = alphanumeric.split(''); + const rand = crypto.randomBytes(64); + const randomAlphanums = []; + + for (let i = 0; i < 64; i++) { + const index = rand[i] % symbols.length; + randomAlphanums.push(symbols[index]); + } + const suffix = randomAlphanums.join(''); + + if (type === deviceIDTypes.KEYSERVER) { + return `ks:${suffix}`; + } else if (type === deviceIDTypes.WEB) { + return `web:${suffix}`; + } else if (type === deviceIDTypes.MOBILE) { + return `mobile:${suffix}`; + } + return ''; +} + +export { generateDeviceID };