/**
 * DID (Decentralized Identifier) helpers
 */
import fetch from 'node-fetch';
import { createVerify } from 'crypto';
export class DIDResolver {
    async resolve(did) {
        // Extract method and identifier from DID
        const didParts = did.split(':');
        if (didParts.length < 3) {
            throw new Error(`Invalid DID format: ${did}`);
        }
        const method = didParts[1];
        const identifier = didParts.slice(2).join(':');
        // Resolve based on DID method
        if (method === 'web') {
            // did:web resolution
            const url = `https://${identifier}/.well-known/did.json`;
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Failed to resolve DID: ${response.status}`);
            }
            return (await response.json());
        }
        else if (method === 'key') {
            // did:key resolution - generate document from key
            const publicKeyMultibase = identifier;
            return {
                id: did,
                '@context': ['https://www.w3.org/ns/did/v1'],
                verificationMethod: [
                    {
                        id: `${did}#keys-1`,
                        type: 'Ed25519VerificationKey2020',
                        controller: did,
                        publicKeyMultibase,
                    },
                ],
                authentication: [`${did}#keys-1`],
            };
        }
        throw new Error(`Unsupported DID method: ${method}`);
    }
    async verifySignature(did, message, signature) {
        try {
            const document = await this.resolve(did);
            const verificationMethod = document.verificationMethod[0];
            if (!verificationMethod) {
                return false;
            }
            const verify = createVerify('SHA256');
            verify.update(message);
            verify.end();
            // Handle different key formats
            if (verificationMethod.publicKeyMultibase) {
                // Multibase-encoded public key (e.g., Ed25519)
                // Decode multibase format (simplified - in production use proper multibase library)
                const multibaseKey = verificationMethod.publicKeyMultibase;
                if (multibaseKey.startsWith('z')) {
                    // Base58btc encoding - decode first byte (0xed for Ed25519)
                    // For Ed25519, the key is 32 bytes after the prefix
                    try {
                        // In production, use proper multibase/base58 decoding
                        // This is a simplified implementation
                        const keyBuffer = Buffer.from(multibaseKey.slice(1), 'base64');
                        return verify.verify(keyBuffer, Buffer.from(signature, 'base64'));
                    }
                    catch {
                        // Fallback: try direct verification if key is already in correct format
                        return verify.verify(verificationMethod.publicKeyMultibase, Buffer.from(signature, 'base64'));
                    }
                }
            }
            // Handle JWK format
            if (verificationMethod.publicKeyJwk) {
                const jwk = verificationMethod.publicKeyJwk;
                if (jwk.kty === 'EC' && jwk.crv === 'secp256k1' && jwk.x && jwk.y) {
                    // ECDSA with secp256k1
                    // In production, use proper JWK to PEM conversion
                    // This requires additional crypto libraries
                    verify.update(message);
                    // For now, delegate to external verification service
                    return false; // Requires proper EC key handling
                }
                if (jwk.kty === 'RSA' && jwk.n && jwk.e) {
                    // RSA keys
                    // In production, convert JWK to PEM format and verify
                    // This requires additional crypto libraries
                    return false; // Requires proper RSA key handling
                }
            }
            return false;
        }
        catch (error) {
            // Log error in production
            console.error('DID signature verification failed:', error);
            return false;
        }
    }
}
//# sourceMappingURL=did.js.map