import type { CryptoKey } from 'jose' import type { EncryptionKeypair, EncryptionPrivateKey, EncryptionPublicKey, PrivateKey, PublicKey, } from '../../../domain/keypair.js' import { exportJWK, importJWK } from 'jose' import { ENCRYPTION_KEYPAIR_ALGORITHM } from './algorithm.js' export function buildSerde() { return { serialize: async function serialize(keypair: { privateKey: CryptoKey publicKey: CryptoKey }) { const [privateKey, publicKey] = await Promise.all([ exportJWK(keypair.privateKey), exportJWK(keypair.publicKey), ]) const encryptionKeypair: EncryptionKeypair = { privateKey: privateKey as EncryptionPrivateKey, publicKey: publicKey as EncryptionPublicKey, } return encryptionKeypair }, deserialize: async function deserialize(keypair: EncryptionKeypair) { const [privateKey, publicKey] = await Promise.all([ importJWK(keypair.privateKey, ENCRYPTION_KEYPAIR_ALGORITHM), importJWK(keypair.publicKey, ENCRYPTION_KEYPAIR_ALGORITHM), ]) return { privateKey, publicKey } as const }, deserializeSingleKey: async function deserializeSingleKey( key: PrivateKey | PublicKey, ) { return await importJWK(key, ENCRYPTION_KEYPAIR_ALGORITHM) }, } as const }