"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PairingManager=void 0;const shared_1=require("../_deps/shared/index.js");class PairingManager{pendingNonces=new Map;registry;deviceDid;constructor(e,r){this.deviceDid=e,this.registry=r,setInterval(()=>{const e=Date.now();for(const[r,i]of this.pendingNonces.entries())e-i>6e4&&this.pendingNonces.delete(r)},1e4)}createRequest(){const e=new Uint8Array(16);if(void 0!==globalThis.crypto&&globalThis.crypto.getRandomValues)globalThis.crypto.getRandomValues(e);else{require("node:crypto").getRandomValues(e)}const r=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),i=Date.now();return this.pendingNonces.set(r,i),{device_a_did:this.deviceDid,nonce:r,timestamp:i}}validateRequest(e){const r=Date.now()-e.timestamp;return r>6e4?(0,shared_1.err)(`Request expired (${Math.floor(r/1e3)}s old, max 60s)`):r<0?(0,shared_1.err)("Request timestamp in the future (clock skew detected)"):e.device_a_did&&e.nonce&&e.timestamp?(0,shared_1.ok)(void 0):(0,shared_1.err)("Missing required fields (device_a_did, nonce, timestamp)")}async acceptPairing(e,r){const i=this.validateRequest(e);if(!i.ok)return(0,shared_1.err)(i.error);const t=await r();if(t){const r=await this.registry.register({did:e.device_a_did,publicKey:new Uint8Array(32),name:"Paired Device",scopes:["pairing"]});if(!r.ok){const e="string"==typeof r.error?r.error:"Unknown error";return(0,shared_1.err)(`Failed to register pairing: ${e}`)}}return(0,shared_1.ok)({device_b_did:this.deviceDid,accepted:t,nonce:e.nonce})}async finalizePairing(e,r){if(e.nonce!==r)return(0,shared_1.err)("Nonce mismatch (possible MITM attack)");if(!e.accepted)return(0,shared_1.err)("Pairing rejected by remote device");this.pendingNonces.delete(r);const i=await this.registry.register({did:e.device_b_did,publicKey:new Uint8Array(32),name:"Paired Device",scopes:["pairing"]});if(!i.ok){const e="string"==typeof i.error?i.error:"Unknown error";return(0,shared_1.err)(`Failed to register pairing: ${e}`)}return(0,shared_1.ok)(void 0)}getPendingNonceCount(){return this.pendingNonces.size}}exports.PairingManager=PairingManager;