84 lines
No EOL
2.5 KiB
TypeScript
84 lines
No EOL
2.5 KiB
TypeScript
// @ts-nocheck
|
|
const isNode = typeof window === 'undefined';
|
|
|
|
let cryptoModule: any;
|
|
if (isNode) {
|
|
cryptoModule = require('crypto');
|
|
} else {
|
|
cryptoModule = window.crypto;
|
|
}
|
|
|
|
export const NET_EVENTS = {
|
|
CONNECT: 'could_you_stop_pwease',
|
|
INCOMING: 'AAAAAAAAAAAAAAAGOCRAzYAAAAAAAAAAAAA',
|
|
OUTGOING: 'AAAAAAAAAAAAAAAAGOCRAzYAAAAAAAAAAAAA',
|
|
};
|
|
|
|
export async function signMessage(message: string, market: string): Promise<string> {
|
|
if (isNode) {
|
|
const hmac = cryptoModule.createHmac('sha256', market);
|
|
hmac.update(message);
|
|
const signature = hmac.digest('hex');
|
|
return JSON.stringify({ message, signature });
|
|
} else {
|
|
const encoder = new TextEncoder();
|
|
const keyData = encoder.encode(market);
|
|
const messageData = encoder.encode(message);
|
|
|
|
const cryptoKey = await cryptoModule.subtle.importKey(
|
|
'raw',
|
|
keyData,
|
|
{ name: 'HMAC', hash: 'SHA-256' },
|
|
false,
|
|
['sign']
|
|
);
|
|
|
|
const signature = await cryptoModule.subtle.sign('HMAC', cryptoKey, messageData);
|
|
const signatureHex = Array.from(new Uint8Array(signature))
|
|
.map(b => b.toString(16).padStart(2, '0'))
|
|
.join('');
|
|
|
|
return JSON.stringify({ message, signature: signatureHex });
|
|
}
|
|
}
|
|
|
|
export async function verifyMessage(signedData: string, market: string): Promise<string | null> {
|
|
try {
|
|
const parsed = JSON.parse(signedData);
|
|
const { message, signature } = parsed;
|
|
|
|
if (isNode) {
|
|
const hmac = cryptoModule.createHmac('sha256', market);
|
|
hmac.update(message);
|
|
const expectedSignature = hmac.digest('hex');
|
|
return signature === expectedSignature ? message : null;
|
|
} else {
|
|
const encoder = new TextEncoder();
|
|
const keyData = encoder.encode(market);
|
|
const messageData = encoder.encode(message);
|
|
|
|
const cryptoKey = await cryptoModule.subtle.importKey(
|
|
'raw',
|
|
keyData,
|
|
{ name: 'HMAC', hash: 'SHA-256' },
|
|
false,
|
|
['verify']
|
|
);
|
|
|
|
const signatureBytes = new Uint8Array(signature.match(/.{1,2}/g).map((byte: string) => parseInt(byte, 16)));
|
|
const isValid = await cryptoModule.subtle.verify('HMAC', cryptoKey, signatureBytes, messageData);
|
|
|
|
return isValid ? message : null;
|
|
}
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function compilePacket(data: any, market: string): Promise<any> {
|
|
return await signMessage(typeof data === 'object' ? JSON.stringify(data) : data, market);
|
|
}
|
|
|
|
export async function executePacket(bytecode: any, market: string): Promise<any> {
|
|
return await verifyMessage(bytecode, market);
|
|
} |