provider.ts (1200B)
1 import { cl_crypto_error } from "./error.js"; 2 import type { KeyMaterialProvider } from "./types.js"; 3 import { crypto_registry_get_device_material, crypto_registry_set_device_material } from "./registry.js"; 4 import { is_error } from "../utils/resolve.js"; 5 6 const DEVICE_PROVIDER_ID = "device"; 7 const DEVICE_MATERIAL_BYTES = 32; 8 9 export interface IDeviceKeyMaterialProvider extends KeyMaterialProvider { } 10 11 export class DeviceKeyMaterialProvider implements IDeviceKeyMaterialProvider { 12 public async get_key_material(): Promise<Uint8Array> { 13 if (!globalThis.crypto) throw new Error(cl_crypto_error.crypto_undefined); 14 const existing = await crypto_registry_get_device_material(); 15 if (is_error(existing)) throw new Error(existing.err); 16 if (existing) return new Uint8Array(existing); 17 const material = new Uint8Array(DEVICE_MATERIAL_BYTES); 18 crypto.getRandomValues(material); 19 const stored = await crypto_registry_set_device_material(material); 20 if (is_error(stored)) throw new Error(stored.err); 21 return new Uint8Array(material); 22 } 23 24 public async get_provider_id(): Promise<string> { 25 return DEVICE_PROVIDER_ID; 26 } 27 }