274 lines
8.1 KiB
TypeScript
Raw Normal View History

import * as ed from '@noble/ed25519';
2025-08-05 11:42:08 +05:30
import { sha512 } from '@noble/hashes/sha512';
import { bytesToHex, hexToBytes } from '@/lib/utils';
2025-08-28 18:44:35 +05:30
import { OpchanMessage } from '@/types/forum';
2025-08-30 18:34:50 +05:30
import { UnsignedMessage } from '@/types/waku';
import { DelegationDuration, DelegationInfo, DelegationStatus } from './types';
import { DelegationStorage } from './storage';
2025-08-28 18:44:35 +05:30
// Set up ed25519 with sha512
2025-08-05 11:42:08 +05:30
ed.etc.sha512Sync = (...m) => sha512(ed.etc.concatBytes(...m));
2025-09-02 11:06:18 +05:30
// Enhanced status interface that consolidates all delegation information
export interface DelegationFullStatus extends DelegationStatus {
publicKey?: string;
address?: string;
walletType?: 'bitcoin' | 'ethereum';
}
export class DelegationManager {
// Duration options in hours
private static readonly DURATION_HOURS = {
2025-08-30 18:34:50 +05:30
'7days': 24 * 7, // 168 hours
'30days': 24 * 30, // 720 hours
} as const;
2025-08-28 18:44:35 +05:30
/**
* Get the number of hours for a given duration
*/
static getDurationHours(duration: DelegationDuration): number {
return DelegationManager.DURATION_HOURS[duration];
}
2025-08-28 18:44:35 +05:30
// ============================================================================
2025-09-02 11:06:18 +05:30
// PUBLIC API
2025-08-28 18:44:35 +05:30
// ============================================================================
/**
2025-09-02 11:06:18 +05:30
* Create a complete delegation with a single method call
* @param address - Wallet address to delegate from
* @param walletType - Type of wallet (bitcoin/ethereum)
* @param duration - How long the delegation should last
* @param signFunction - Function to sign the delegation message with the wallet
* @returns Promise<boolean> - Success status
*/
2025-09-02 11:06:18 +05:30
async delegate(
address: string,
walletType: 'bitcoin' | 'ethereum',
duration: DelegationDuration = '7days',
2025-09-02 11:06:18 +05:30
signFunction: (message: string) => Promise<string>
): Promise<boolean> {
try {
// Generate new keypair
const keypair = this.generateKeypair();
// Create delegation message with expiry
const expiryHours = DelegationManager.getDurationHours(duration);
const expiryTimestamp = Date.now() + expiryHours * 60 * 60 * 1000;
const delegationMessage = this.createDelegationMessage(
keypair.publicKey,
address,
expiryTimestamp
);
// Sign the delegation message with wallet
const signature = await signFunction(delegationMessage);
// Create and store the delegation
const delegationInfo: DelegationInfo = {
signature,
expiryTimestamp,
browserPublicKey: keypair.publicKey,
browserPrivateKey: keypair.privateKey,
walletAddress: address,
walletType,
};
DelegationStorage.store(delegationInfo);
return true;
} catch (error) {
console.error('Error creating delegation:', error);
return false;
}
}
2025-08-28 18:44:35 +05:30
/**
2025-09-02 11:06:18 +05:30
* Get comprehensive delegation status
* @param currentAddress - Optional address to validate against
* @param currentWalletType - Optional wallet type to validate against
* @returns Complete delegation status information
*/
2025-09-02 11:06:18 +05:30
getStatus(
2025-08-30 18:34:50 +05:30
currentAddress?: string,
currentWalletType?: 'bitcoin' | 'ethereum'
2025-09-02 11:06:18 +05:30
): DelegationFullStatus {
const delegation = DelegationStorage.retrieve();
2025-09-02 11:06:18 +05:30
if (!delegation) {
return {
hasDelegation: false,
isValid: false,
};
2025-08-06 17:21:56 +05:30
}
2025-08-30 18:34:50 +05:30
2025-09-02 11:06:18 +05:30
// Check if delegation has expired
2025-08-28 18:44:35 +05:30
const now = Date.now();
2025-09-02 11:06:18 +05:30
const hasExpired = now >= delegation.expiryTimestamp;
// Check address/wallet type matching if provided
const addressMatches = !currentAddress || delegation.walletAddress === currentAddress;
const walletTypeMatches = !currentWalletType || delegation.walletType === currentWalletType;
const isValid = !hasExpired && addressMatches && walletTypeMatches;
const timeRemaining = Math.max(0, delegation.expiryTimestamp - now);
return {
2025-09-02 11:06:18 +05:30
hasDelegation: true,
isValid,
timeRemaining: timeRemaining > 0 ? timeRemaining : undefined,
2025-09-02 11:06:18 +05:30
publicKey: delegation.browserPublicKey,
address: delegation.walletAddress,
walletType: delegation.walletType,
};
}
/**
* Clear the stored delegation
*/
2025-09-02 11:06:18 +05:30
clear(): void {
DelegationStorage.clear();
2025-08-28 18:44:35 +05:30
}
/**
2025-09-02 11:06:18 +05:30
* Sign a message with the delegated browser key
* @param message - Unsigned message to sign
* @returns Signed message or null if delegation invalid
*/
2025-09-02 11:06:18 +05:30
signMessage(message: UnsignedMessage): OpchanMessage | null {
const status = this.getStatus();
if (!status.isValid) {
2025-08-28 18:44:35 +05:30
console.error('No valid key delegation found. Cannot sign message.');
return null;
}
2025-08-30 18:34:50 +05:30
const delegation = DelegationStorage.retrieve();
if (!delegation) return null;
2025-08-30 18:34:50 +05:30
2025-08-28 18:44:35 +05:30
// Create the message content to sign (without signature fields)
const messageToSign = JSON.stringify({
...message,
signature: undefined,
2025-08-30 18:34:50 +05:30
browserPubKey: undefined,
2025-08-28 18:44:35 +05:30
});
2025-08-30 18:34:50 +05:30
2025-09-02 11:06:18 +05:30
const signature = this.signRaw(messageToSign);
2025-08-28 18:44:35 +05:30
if (!signature) return null;
2025-08-30 18:34:50 +05:30
2025-08-28 18:44:35 +05:30
return {
...message,
signature,
2025-08-30 18:34:50 +05:30
browserPubKey: delegation.browserPublicKey,
} as OpchanMessage;
}
2025-08-28 18:44:35 +05:30
/**
2025-09-02 11:06:18 +05:30
* Verify a message signature
* @param message - Signed message to verify
* @returns True if signature is valid
*/
2025-09-02 11:06:18 +05:30
verify(message: OpchanMessage): boolean {
2025-08-28 18:44:35 +05:30
// Check for required signature fields
if (!message.signature || !message.browserPubKey) {
2025-08-30 18:34:50 +05:30
const messageId = message.id || `${message.type}-${message.timestamp}`;
2025-08-28 18:44:35 +05:30
console.warn('Message is missing signature information', messageId);
return false;
}
2025-08-30 18:34:50 +05:30
2025-08-28 18:44:35 +05:30
// Reconstruct the original signed content
const signedContent = JSON.stringify({
...message,
signature: undefined,
2025-08-30 18:34:50 +05:30
browserPubKey: undefined,
2025-08-28 18:44:35 +05:30
});
2025-08-30 18:34:50 +05:30
2025-08-28 18:44:35 +05:30
// Verify the signature
2025-09-02 11:06:18 +05:30
const isValid = this.verifyRaw(
2025-08-28 18:44:35 +05:30
signedContent,
message.signature,
message.browserPubKey
);
2025-08-30 18:34:50 +05:30
2025-08-28 18:44:35 +05:30
if (!isValid) {
2025-08-30 18:34:50 +05:30
const messageId = message.id || `${message.type}-${message.timestamp}`;
2025-08-28 18:44:35 +05:30
console.warn(`Invalid signature for message ${messageId}`);
}
2025-08-30 18:34:50 +05:30
2025-08-28 18:44:35 +05:30
return isValid;
}
2025-09-02 10:17:42 +05:30
2025-09-02 11:06:18 +05:30
// ============================================================================
// PRIVATE HELPERS
// ============================================================================
/**
* Generate a new browser-based keypair for signing messages
*/
private generateKeypair(): { publicKey: string; privateKey: string } {
const privateKey = ed.utils.randomPrivateKey();
const privateKeyHex = bytesToHex(privateKey);
const publicKey = ed.getPublicKey(privateKey);
const publicKeyHex = bytesToHex(publicKey);
return {
privateKey: privateKeyHex,
publicKey: publicKeyHex,
};
}
/**
* Create a delegation message to be signed by the wallet
*/
private createDelegationMessage(
browserPublicKey: string,
walletAddress: string,
expiryTimestamp: number
): string {
return `I, ${walletAddress}, delegate authority to this pubkey: ${browserPublicKey} until ${expiryTimestamp}`;
}
/**
* Sign a raw string message using the browser-generated private key
*/
private signRaw(message: string): string | null {
const delegation = DelegationStorage.retrieve();
if (!delegation) return null;
try {
const privateKeyBytes = hexToBytes(delegation.browserPrivateKey);
const messageBytes = new TextEncoder().encode(message);
const signature = ed.sign(messageBytes, privateKeyBytes);
return bytesToHex(signature);
} catch (error) {
console.error('Error signing with browser key:', error);
return null;
}
}
2025-09-02 10:17:42 +05:30
/**
* Verify a signature made with the browser key
2025-09-02 10:17:42 +05:30
*/
2025-09-02 11:06:18 +05:30
private verifyRaw(
2025-09-02 10:17:42 +05:30
message: string,
signature: string,
publicKey: string
): boolean {
try {
const messageBytes = new TextEncoder().encode(message);
const signatureBytes = hexToBytes(signature);
const publicKeyBytes = hexToBytes(publicKey);
return ed.verify(signatureBytes, messageBytes, publicKeyBytes);
} catch (error) {
console.error('Error verifying signature:', error);
return false;
}
}
2025-08-28 18:44:35 +05:30
}
// Export singleton instance
export const delegationManager = new DelegationManager();
export * from './types';
export { DelegationStorage };