gongxiangp2/lib/external-auto-listing-crypto.ts

34 lines
1.4 KiB
TypeScript

import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
import { AutoListingCallbackError } from '@/lib/external-auto-listing-callback'
function callbackEncryptionKey() {
const key = process.env.API_KEY_ENCRYPTION_KEY?.trim()
if (!key || Buffer.byteLength(key) < 32) {
throw new AutoListingCallbackError('请先在服务端配置回调凭据加密密钥', 503)
}
return createHash('sha256').update('gongxiangp2:auto-listing:v1\0').update(key).digest()
}
export function encryptCallbackSecret(secret: string) {
const nonce = randomBytes(12)
const cipher = createCipheriv('aes-256-gcm', callbackEncryptionKey(), nonce)
return {
secretCiphertext: Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]).toString('base64'),
secretNonce: nonce.toString('base64'),
secretAuthTag: cipher.getAuthTag().toString('base64'),
}
}
export function decryptCallbackSecret(config: Record<string, string>) {
try {
const decipher = createDecipheriv('aes-256-gcm', callbackEncryptionKey(), Buffer.from(config.secretNonce, 'base64'))
decipher.setAuthTag(Buffer.from(config.secretAuthTag, 'base64'))
return Buffer.concat([
decipher.update(Buffer.from(config.secretCiphertext, 'base64')),
decipher.final(),
]).toString('utf8')
} catch {
throw new AutoListingCallbackError('回调鉴权凭据不可用,请重新填写', 503)
}
}