|
| 1 | +import QRCode from 'qrcode'; |
| 2 | +import { ref, onUnmounted } from 'vue'; |
| 3 | + |
| 4 | +// TOTP configuration |
| 5 | +const TOTP_CONFIG = { |
| 6 | + digits: 6, |
| 7 | + timeStep: 30, // seconds |
| 8 | +}; |
| 9 | + |
| 10 | +export function useOneTimeQrCode() { |
| 11 | + const qrDataUrl = ref<string>(''); |
| 12 | + const expiryTimestamp = ref<number>(0); |
| 13 | + const timeLeft = ref<number>(0); |
| 14 | + const isLoading = ref<boolean>(false); |
| 15 | + let intervalId: NodeJS.Timeout | null = null; |
| 16 | + |
| 17 | + /** |
| 18 | + * Convert string to Uint8Array |
| 19 | + */ |
| 20 | + const stringToBytes = (str: string): Uint8Array => { |
| 21 | + return new TextEncoder().encode(str); |
| 22 | + }; |
| 23 | + |
| 24 | + /** |
| 25 | + * Generate HMAC using Web Crypto API |
| 26 | + */ |
| 27 | + const generateHMAC = async (key: Uint8Array, message: Uint8Array): Promise<ArrayBuffer> => { |
| 28 | + const cryptoKey = await crypto.subtle.importKey( |
| 29 | + 'raw', |
| 30 | + key, |
| 31 | + { name: 'HMAC', hash: 'SHA-256' }, |
| 32 | + false, |
| 33 | + ['sign'] |
| 34 | + ); |
| 35 | + return crypto.subtle.sign('HMAC', cryptoKey, message); |
| 36 | + }; |
| 37 | + |
| 38 | + /** |
| 39 | + * Generates a time-based one-time password token for a user |
| 40 | + * @param userId The ID of the user |
| 41 | + * @param secret An optional secret. If not provided, one will be generated based on the userId |
| 42 | + * @returns The generated token |
| 43 | + */ |
| 44 | + const generateToken = async (userId: string, secret?: string): Promise<string> => { |
| 45 | + try { |
| 46 | + const userSecret = secret || `LabSyncro-${userId}-${new Date().toISOString().split('T')[0]}`; |
| 47 | + const counter = Math.floor(Date.now() / 1000 / TOTP_CONFIG.timeStep); |
| 48 | + |
| 49 | + // Convert counter to 8-byte buffer |
| 50 | + const counterBytes = new Uint8Array(8); |
| 51 | + let tempCounter = counter; |
| 52 | + for (let i = counterBytes.length - 1; i >= 0; i--) { |
| 53 | + counterBytes[i] = tempCounter & 0xff; |
| 54 | + tempCounter >>= 8; |
| 55 | + } |
| 56 | + |
| 57 | + const hmac = await generateHMAC(stringToBytes(userSecret), counterBytes); |
| 58 | + const hmacArray = new Uint8Array(hmac); |
| 59 | + |
| 60 | + // Get offset from last nibble |
| 61 | + const offset = hmacArray[hmacArray.length - 1] & 0xf; |
| 62 | + |
| 63 | + // Generate 4-byte code from HMAC |
| 64 | + let code = |
| 65 | + ((hmacArray[offset] & 0x7f) << 24) | |
| 66 | + (hmacArray[offset + 1] << 16) | |
| 67 | + (hmacArray[offset + 2] << 8) | |
| 68 | + hmacArray[offset + 3]; |
| 69 | + |
| 70 | + // Get last n digits |
| 71 | + code = code % Math.pow(10, TOTP_CONFIG.digits); |
| 72 | + |
| 73 | + // Pad with leading zeros if needed |
| 74 | + return code.toString().padStart(TOTP_CONFIG.digits, '0'); |
| 75 | + } catch (error) { |
| 76 | + console.error('Error generating token:', error); |
| 77 | + throw error; |
| 78 | + } |
| 79 | + }; |
| 80 | + |
| 81 | + /** |
| 82 | + * Verify a token against expected values |
| 83 | + * @param token The token to verify |
| 84 | + * @param userId The userId that was used to generate the token |
| 85 | + * @param secret Optional secret used when generating the token |
| 86 | + * @returns True if the token is valid, false otherwise |
| 87 | + */ |
| 88 | + const verifyToken = async (token: string, userId: string, secret?: string): Promise<boolean> => { |
| 89 | + try { |
| 90 | + const currentToken = await generateToken(userId, secret); |
| 91 | + return token === currentToken; |
| 92 | + } catch (error) { |
| 93 | + console.error('Error verifying token:', error); |
| 94 | + return false; |
| 95 | + } |
| 96 | + }; |
| 97 | + |
| 98 | + /** |
| 99 | + * Generate a QR code containing a one-time token for a user |
| 100 | + * @param userId The ID of the user |
| 101 | + * @param extraData Optional additional data to include in the QR code |
| 102 | + */ |
| 103 | + const generateQrCode = async (userId: string, extraData?: Record<string, any>) => { |
| 104 | + try { |
| 105 | + isLoading.value = true; |
| 106 | + |
| 107 | + // Generate token |
| 108 | + const token = await generateToken(userId); |
| 109 | + |
| 110 | + // Calculate token expiry time |
| 111 | + const now = Math.floor(Date.now() / 1000); |
| 112 | + const step = TOTP_CONFIG.timeStep; |
| 113 | + expiryTimestamp.value = (Math.floor(now / step) + 1) * step * 1000; |
| 114 | + |
| 115 | + // Create data object to be encoded in QR code |
| 116 | + const qrData = JSON.stringify({ |
| 117 | + token, |
| 118 | + userId, |
| 119 | + timestamp: Date.now(), |
| 120 | + expiry: expiryTimestamp.value, |
| 121 | + ...extraData, |
| 122 | + }); |
| 123 | + |
| 124 | + // Generate QR code as data URL |
| 125 | + qrDataUrl.value = await QRCode.toDataURL(qrData); |
| 126 | + |
| 127 | + // Start the countdown |
| 128 | + startCountdown(); |
| 129 | + } catch (error) { |
| 130 | + console.error('Error generating QR code:', error); |
| 131 | + } finally { |
| 132 | + isLoading.value = false; |
| 133 | + } |
| 134 | + }; |
| 135 | + |
| 136 | + /** |
| 137 | + * Start countdown for token expiry |
| 138 | + */ |
| 139 | + const startCountdown = () => { |
| 140 | + // Clear any existing interval |
| 141 | + if (intervalId) clearInterval(intervalId); |
| 142 | + |
| 143 | + // Update time left on interval |
| 144 | + intervalId = setInterval(() => { |
| 145 | + const now = Date.now(); |
| 146 | + if (now >= expiryTimestamp.value) { |
| 147 | + // Token expired, regenerate |
| 148 | + timeLeft.value = 0; |
| 149 | + if (intervalId) clearInterval(intervalId); |
| 150 | + } else { |
| 151 | + timeLeft.value = Math.floor((expiryTimestamp.value - now) / 1000); |
| 152 | + } |
| 153 | + }, 1000); |
| 154 | + }; |
| 155 | + |
| 156 | + /** |
| 157 | + * Handle a scanned QR code to verify the token inside |
| 158 | + * @param scannedQrData The data from the scanned QR code |
| 159 | + * @returns The user ID and any extra data if verification succeeds, null otherwise |
| 160 | + */ |
| 161 | + const verifyScannedQrCode = async (scannedQrData: string): Promise<{ userId: string; extraData?: any } | null> => { |
| 162 | + try { |
| 163 | + // Parse the QR data |
| 164 | + const qrData = JSON.parse(scannedQrData); |
| 165 | + const { token, userId, timestamp, expiry, ...extraData } = qrData; |
| 166 | + |
| 167 | + // Check if token has expired |
| 168 | + if (Date.now() > expiry) { |
| 169 | + console.error('Token has expired'); |
| 170 | + return null; |
| 171 | + } |
| 172 | + |
| 173 | + // Verify the token |
| 174 | + const isValid = await verifyToken(token, userId); |
| 175 | + if (!isValid) { |
| 176 | + console.error('Invalid token'); |
| 177 | + return null; |
| 178 | + } |
| 179 | + |
| 180 | + // Token is valid, return user ID and any extra data |
| 181 | + return { userId, extraData }; |
| 182 | + } catch (error) { |
| 183 | + console.error('Error verifying QR code:', error); |
| 184 | + return null; |
| 185 | + } |
| 186 | + }; |
| 187 | + |
| 188 | + /** |
| 189 | + * Clean up resources when component unmounts |
| 190 | + */ |
| 191 | + const cleanUp = () => { |
| 192 | + if (intervalId) clearInterval(intervalId); |
| 193 | + qrDataUrl.value = ''; |
| 194 | + expiryTimestamp.value = 0; |
| 195 | + timeLeft.value = 0; |
| 196 | + }; |
| 197 | + |
| 198 | + onUnmounted(() => { |
| 199 | + cleanUp(); |
| 200 | + }); |
| 201 | + |
| 202 | + return { |
| 203 | + qrDataUrl, |
| 204 | + timeLeft, |
| 205 | + isLoading, |
| 206 | + generateToken, |
| 207 | + verifyToken, |
| 208 | + generateQrCode, |
| 209 | + verifyScannedQrCode, |
| 210 | + cleanUp, |
| 211 | + }; |
| 212 | +} |
0 commit comments