Merge branch 'fix/crypto-compatibility'
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
* Utility functions for authentication and API key management
|
||||
*/
|
||||
|
||||
import { getCryptoRandomValues } from './crypto-adapter';
|
||||
|
||||
/**
|
||||
* Generates a cryptographically secure random API key
|
||||
* @param length Length of the API key (default: 32 characters)
|
||||
@@ -10,15 +12,15 @@
|
||||
export function generateApiKey(length: number = 32): string {
|
||||
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
||||
const values = new Uint8Array(length);
|
||||
|
||||
// Use crypto.getRandomValues for cryptographically secure random numbers
|
||||
crypto.getRandomValues(values);
|
||||
|
||||
|
||||
// Use cross-environment crypto adapter
|
||||
getCryptoRandomValues(values);
|
||||
|
||||
let result = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += charset[values[i] % charset.length];
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
36
src/utils/crypto-adapter.ts
Normal file
36
src/utils/crypto-adapter.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Cross-environment crypto adapter
|
||||
* Provides unified access to cryptographically secure random number generation
|
||||
* Works in both browser/Electron (window.crypto) and Node.js (crypto.webcrypto)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gets the appropriate Crypto interface for the current environment
|
||||
* @returns Crypto interface with getRandomValues method
|
||||
* @throws Error if no crypto API is available
|
||||
*/
|
||||
function getCrypto(): Crypto {
|
||||
// Browser/Electron environment
|
||||
if (typeof window !== 'undefined' && window.crypto) {
|
||||
return window.crypto;
|
||||
}
|
||||
|
||||
// Node.js environment (15+) - uses Web Crypto API standard
|
||||
if (typeof global !== 'undefined') {
|
||||
const nodeCrypto = require('crypto');
|
||||
if (nodeCrypto.webcrypto) {
|
||||
return nodeCrypto.webcrypto;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('No Web Crypto API available in this environment');
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills a typed array with cryptographically secure random values
|
||||
* @param array TypedArray to fill with random values
|
||||
* @returns The same array filled with random values
|
||||
*/
|
||||
export function getCryptoRandomValues<T extends ArrayBufferView>(array: T): T {
|
||||
return getCrypto().getRandomValues(array);
|
||||
}
|
||||
Reference in New Issue
Block a user