UNPKG

@commit451/salamander

Version:

Never be AFK

71 lines 2.92 kB
import { createHash, randomBytes } from 'crypto'; export class EncryptionService { /** * Generate a random shared secret * This ensures the backend never knows the encryption key */ static generateRandomSecret() { // Generate 8 random bytes and convert to hex for a 16-character string const randomBuffer = randomBytes(8); return randomBuffer.toString('hex').toUpperCase(); } /** * Simple XOR-based encryption compatible with Dart implementation */ static encrypt(data, secret) { try { // Use a hash of the secret to create consistent encryption const secretHash = createHash('sha256').update(secret).digest('hex'); const keyBytes = Buffer.from(secretHash.substring(0, 32), 'utf8'); const dataBytes = Buffer.from(data, 'utf8'); const encrypted = Buffer.alloc(dataBytes.length); for (let i = 0; i < dataBytes.length; i++) { encrypted[i] = dataBytes[i] ^ keyBytes[i % keyBytes.length]; } // Convert to hex string const result = encrypted.toString('hex'); return { encrypted: result, success: true }; } catch (error) { return { encrypted: '', success: false }; } } /** * Simple XOR-based decryption */ static decrypt(encryptedData, secret) { try { // Use a hash of the secret to create consistent decryption key const secretHash = createHash('sha256').update(secret).digest('hex'); const keyBytes = Buffer.from(secretHash.substring(0, 32), 'utf8'); // Convert hex string back to bytes const encrypted = Buffer.from(encryptedData, 'hex'); const decrypted = Buffer.alloc(encrypted.length); for (let i = 0; i < encrypted.length; i++) { decrypted[i] = encrypted[i] ^ keyBytes[i % keyBytes.length]; } const result = decrypted.toString('utf8'); return { decrypted: result, success: true }; } catch (error) { return { decrypted: '', success: false }; } } /** * Create verification string encrypted with the secret * This can be stored on the runner to verify the correct secret */ static createVerificationString(secret) { const verificationText = 'salamander_verification_success'; const result = this.encrypt(verificationText, secret); return result.encrypted; } /** * Verify if a secret is correct by trying to decrypt the verification string */ static verifySecret(encryptedVerification, secret) { const result = this.decrypt(encryptedVerification, secret); return result.success && result.decrypted === 'salamander_verification_success'; } } //# sourceMappingURL=encryption.js.map