Add HMAC function, and update the CMS and Mailer services

A new module has been added to create HMACs, primarily used in the billing service for data verification. Keystatic CMS usage has been conditioned to Node.js runtime only, and a fallback to the mock CMS client has been implemented for Edge Runtime. Mailer services now accommodate environment-specific providers.
This commit is contained in:
giancarlo
2024-04-17 15:47:50 +08:00
parent d62bcad657
commit bf43c48dff
9 changed files with 107 additions and 30 deletions

View File

@@ -0,0 +1,33 @@
function bufferToHex(buffer: ArrayBuffer) {
return Array.from(new Uint8Array(buffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
export async function createHmac({ key, data }: { key: string; data: string }) {
const encoder = new TextEncoder();
const crypto = new Crypto();
const encodedKey = encoder.encode(key);
const encodedData = encoder.encode(data);
const hmacKey = await crypto.subtle.importKey(
'raw',
encodedKey,
{
name: 'HMAC',
hash: 'SHA-256',
},
true,
['sign', 'verify'],
);
const signature = await window.crypto.subtle.sign(
'HMAC',
hmacKey,
encodedData,
);
const hex = bufferToHex(signature);
return { hex };
}