Format code

This commit is contained in:
Nicola Benaglia 2025-04-20 13:49:23 +02:00
parent de9285a280
commit e1bb064d1a

View File

@ -1,28 +1,32 @@
import { getBaseApi } from "../background"; import { getBaseApi } from '../background';
import { createSymmetricKeyAndNonce, decryptGroupData, encryptDataGroup, objectToBase64 } from "../qdn/encryption/group-encryption"; import {
import { publishData } from "../qdn/publish/pubish"; createSymmetricKeyAndNonce,
import { getData } from "../utils/chromeStorage"; decryptGroupData,
import { RequestQueueWithPromise } from "../utils/queue/queue"; encryptDataGroup,
objectToBase64,
} from '../qdn/encryption/group-encryption';
import { publishData } from '../qdn/publish/pubish';
import { getData } from '../utils/chromeStorage';
import { RequestQueueWithPromise } from '../utils/queue/queue';
export const requestQueueGetPublicKeys = new RequestQueueWithPromise(10); export const requestQueueGetPublicKeys = new RequestQueueWithPromise(10);
const apiEndpoints = [ const apiEndpoints = [
"https://api.qortal.org", 'https://api.qortal.org',
"https://api2.qortal.org", 'https://api2.qortal.org',
"https://appnode.qortal.org", 'https://appnode.qortal.org',
"https://apinode.qortalnodes.live", 'https://apinode.qortalnodes.live',
"https://apinode1.qortalnodes.live", 'https://apinode1.qortalnodes.live',
"https://apinode2.qortalnodes.live", 'https://apinode2.qortalnodes.live',
"https://apinode3.qortalnodes.live", 'https://apinode3.qortalnodes.live',
"https://apinode4.qortalnodes.live", 'https://apinode4.qortalnodes.live',
]; ];
async function findUsableApi() { async function findUsableApi() {
for (const endpoint of apiEndpoints) { for (const endpoint of apiEndpoints) {
try { try {
const response = await fetch(`${endpoint}/admin/status`); const response = await fetch(`${endpoint}/admin/status`);
if (!response.ok) throw new Error("Failed to fetch"); if (!response.ok) throw new Error('Failed to fetch');
const data = await response.json(); const data = await response.json();
if (data.isSynchronizing === false && data.syncPercent === 100) { if (data.isSynchronizing === false && data.syncPercent === 100) {
@ -36,42 +40,46 @@ async function findUsableApi() {
} }
} }
throw new Error("No usable API found"); throw new Error('No usable API found');
} }
async function getSaveWallet() { async function getSaveWallet() {
const res = await getData<any>("walletInfo").catch(() => null); const res = await getData<any>('walletInfo').catch(() => null);
if (res) { if (res) {
return res return res;
} else { } else {
throw new Error("No wallet saved"); throw new Error('No wallet saved');
}
} }
}
export async function getNameInfo() { export async function getNameInfo() {
const wallet = await getSaveWallet(); const wallet = await getSaveWallet();
const address = wallet.address0; const address = wallet.address0;
const validApi = await getBaseApi() const validApi = await getBaseApi();
const response = await fetch(validApi + "/names/address/" + address); const response = await fetch(validApi + '/names/address/' + address);
const nameData = await response.json(); const nameData = await response.json();
if (nameData?.length > 0) { if (nameData?.length > 0) {
return nameData[0].name; return nameData[0].name;
} else { } else {
return ""; return '';
}
} }
}
async function getKeyPair() { async function getKeyPair() {
const res = await getData<any>("keyPair").catch(() => null); const res = await getData<any>('keyPair').catch(() => null);
if (res) { if (res) {
return res return res;
} else { } else {
throw new Error("Wallet not authenticated"); throw new Error('Wallet not authenticated');
} }
} }
const getPublicKeys = async (groupNumber: number) => {
const getPublicKeys = async (groupNumber: number) => {
const validApi = await getBaseApi(); const validApi = await getBaseApi();
const response = await fetch(`${validApi}/groups/members/${groupNumber}?limit=0`); const response = await fetch(
`${validApi}/groups/members/${groupNumber}?limit=0`
);
const groupData = await response.json(); const groupData = await response.json();
if (groupData && Array.isArray(groupData.members)) { if (groupData && Array.isArray(groupData.members)) {
@ -80,7 +88,9 @@ async function getKeyPair() {
.filter((member) => member.member) .filter((member) => member.member)
.map((member) => .map((member) =>
requestQueueGetPublicKeys.enqueue(async () => { requestQueueGetPublicKeys.enqueue(async () => {
const resAddress = await fetch(`${validApi}/addresses/${member.member}`); const resAddress = await fetch(
`${validApi}/addresses/${member.member}`
);
const resData = await resAddress.json(); const resData = await resAddress.json();
return resData.publicKey; return resData.publicKey;
}) })
@ -91,9 +101,9 @@ async function getKeyPair() {
} }
return []; return [];
}; };
export const getPublicKeysByAddress = async (admins: string[]) => { export const getPublicKeysByAddress = async (admins: string[]) => {
const validApi = await getBaseApi(); const validApi = await getBaseApi();
if (Array.isArray(admins)) { if (Array.isArray(admins)) {
@ -113,130 +123,163 @@ async function getKeyPair() {
} }
return []; // Return empty array if admins is not an array return []; // Return empty array if admins is not an array
};
export const encryptAndPublishSymmetricKeyGroupChat = async ({
groupId,
previousData,
}: {
groupId: number;
previousData: Object;
}) => {
try {
let highestKey = 0;
if (previousData) {
highestKey = Math.max(
...Object.keys(previousData || {})
.filter((item) => !isNaN(+item))
.map(Number)
);
}
const resKeyPair = await getKeyPair();
const parsedData = resKeyPair;
const privateKey = parsedData.privateKey;
const userPublicKey = parsedData.publicKey;
const groupmemberPublicKeys = await getPublicKeys(groupId);
const symmetricKey = createSymmetricKeyAndNonce();
const nextNumber = highestKey + 1;
const objectToSave = {
...previousData,
[nextNumber]: symmetricKey,
}; };
const symmetricKeyAndNonceBase64 = await objectToBase64(objectToSave);
export const encryptAndPublishSymmetricKeyGroupChat = async ({groupId, previousData}: {
groupId: number,
previousData: Object,
}) => {
try {
let highestKey = 0
if(previousData){
highestKey = Math.max(...Object.keys((previousData || {})).filter(item=> !isNaN(+item)).map(Number));
}
const resKeyPair = await getKeyPair()
const parsedData = resKeyPair
const privateKey = parsedData.privateKey
const userPublicKey = parsedData.publicKey
const groupmemberPublicKeys = await getPublicKeys(groupId)
const symmetricKey = createSymmetricKeyAndNonce()
const nextNumber = highestKey + 1
const objectToSave = {
...previousData,
[nextNumber]: symmetricKey
}
const symmetricKeyAndNonceBase64 = await objectToBase64(objectToSave)
const encryptedData = encryptDataGroup({ const encryptedData = encryptDataGroup({
data64: symmetricKeyAndNonceBase64, data64: symmetricKeyAndNonceBase64,
publicKeys: groupmemberPublicKeys, publicKeys: groupmemberPublicKeys,
privateKey, privateKey,
userPublicKey userPublicKey,
}) });
if(encryptedData){ if (encryptedData) {
const registeredName = await getNameInfo() const registeredName = await getNameInfo();
const data = await publishData({ const data = await publishData({
registeredName, file: encryptedData, service: 'DOCUMENT_PRIVATE', identifier: `symmetric-qchat-group-${groupId}`, uploadType: 'file', isBase64: true, withFee: true registeredName,
}) file: encryptedData,
service: 'DOCUMENT_PRIVATE',
identifier: `symmetric-qchat-group-${groupId}`,
uploadType: 'file',
isBase64: true,
withFee: true,
});
return { return {
data, data,
numberOfMembers: groupmemberPublicKeys.length numberOfMembers: groupmemberPublicKeys.length,
} };
} else { } else {
throw new Error('Cannot encrypt content') throw new Error('Cannot encrypt content');
} }
} catch (error: any) { } catch (error: any) {
throw new Error(error.message); throw new Error(error.message);
} }
} };
export const encryptAndPublishSymmetricKeyGroupChatForAdmins = async ({groupId, previousData, admins}: {
groupId: number, export const encryptAndPublishSymmetricKeyGroupChatForAdmins = async ({
previousData: Object, groupId,
previousData,
admins,
}: {
groupId: number;
previousData: Object;
}) => { }) => {
try { try {
let highestKey = 0;
let highestKey = 0 if (previousData) {
if(previousData){ highestKey = Math.max(
highestKey = Math.max(...Object.keys((previousData || {})).filter(item=> !isNaN(+item)).map(Number)); ...Object.keys(previousData || {})
.filter((item) => !isNaN(+item))
.map(Number)
);
} }
const resKeyPair = await getKeyPair() const resKeyPair = await getKeyPair();
const parsedData = resKeyPair const parsedData = resKeyPair;
const privateKey = parsedData.privateKey const privateKey = parsedData.privateKey;
const userPublicKey = parsedData.publicKey const userPublicKey = parsedData.publicKey;
const groupmemberPublicKeys = await getPublicKeysByAddress(admins.map((admin)=> admin.address)) const groupmemberPublicKeys = await getPublicKeysByAddress(
admins.map((admin) => admin.address)
);
const symmetricKey = createSymmetricKeyAndNonce();
const symmetricKey = createSymmetricKeyAndNonce() const nextNumber = highestKey + 1;
const nextNumber = highestKey + 1
const objectToSave = { const objectToSave = {
...previousData, ...previousData,
[nextNumber]: symmetricKey [nextNumber]: symmetricKey,
} };
const symmetricKeyAndNonceBase64 = await objectToBase64(objectToSave) const symmetricKeyAndNonceBase64 = await objectToBase64(objectToSave);
const encryptedData = encryptDataGroup({ const encryptedData = encryptDataGroup({
data64: symmetricKeyAndNonceBase64, data64: symmetricKeyAndNonceBase64,
publicKeys: groupmemberPublicKeys, publicKeys: groupmemberPublicKeys,
privateKey, privateKey,
userPublicKey userPublicKey,
}) });
if(encryptedData){ if (encryptedData) {
const registeredName = await getNameInfo() const registeredName = await getNameInfo();
const data = await publishData({ const data = await publishData({
registeredName, file: encryptedData, service: 'DOCUMENT_PRIVATE', identifier: `admins-symmetric-qchat-group-${groupId}`, uploadType: 'file', isBase64: true, withFee: true registeredName,
}) file: encryptedData,
service: 'DOCUMENT_PRIVATE',
identifier: `admins-symmetric-qchat-group-${groupId}`,
uploadType: 'file',
isBase64: true,
withFee: true,
});
return { return {
data, data,
numberOfMembers: groupmemberPublicKeys.length numberOfMembers: groupmemberPublicKeys.length,
} };
} else { } else {
throw new Error('Cannot encrypt content') throw new Error('Cannot encrypt content');
} }
} catch (error: any) { } catch (error: any) {
throw new Error(error.message); throw new Error(error.message);
} }
} };
export const publishGroupEncryptedResource = async ({encryptedData, identifier}) => {
export const publishGroupEncryptedResource = async ({
encryptedData,
identifier,
}) => {
try { try {
if (encryptedData && identifier) {
if(encryptedData && identifier){ const registeredName = await getNameInfo();
const registeredName = await getNameInfo() if (!registeredName) throw new Error('You need a name to publish');
if(!registeredName) throw new Error('You need a name to publish')
const data = await publishData({ const data = await publishData({
registeredName, file: encryptedData, service: 'DOCUMENT', identifier, uploadType: 'file', isBase64: true, withFee: true registeredName,
}) file: encryptedData,
return data service: 'DOCUMENT',
identifier,
uploadType: 'file',
isBase64: true,
withFee: true,
});
return data;
} else { } else {
throw new Error('Cannot encrypt content') throw new Error('Cannot encrypt content');
} }
} catch (error: any) { } catch (error: any) {
throw new Error(error.message); throw new Error(error.message);
} }
} };
export const publishOnQDN = async ({data, identifier, service, title,
export const publishOnQDN = async ({
data,
identifier,
service,
title,
description, description,
category, category,
tag1, tag1,
@ -244,84 +287,82 @@ export const publishOnQDN = async ({data, identifier, service, title,
tag3, tag3,
tag4, tag4,
tag5, tag5,
uploadType = 'file' uploadType = 'file',
}) => { }) => {
if (data && service) {
if(data && service){ const registeredName = await getNameInfo();
const registeredName = await getNameInfo() if (!registeredName) throw new Error('You need a name to publish');
if(!registeredName) throw new Error('You need a name to publish')
const res = await publishData({ const res = await publishData({
registeredName, file: data, service, identifier, uploadType, isBase64: true, withFee: true, title, registeredName,
file: data,
service,
identifier,
uploadType,
isBase64: true,
withFee: true,
title,
description, description,
category, category,
tag1, tag1,
tag2, tag2,
tag3, tag3,
tag4, tag4,
tag5 tag5,
});
}) return res;
return res
} else { } else {
throw new Error('Cannot publish content') throw new Error('Cannot publish content');
} }
};
}
export function uint8ArrayToBase64(uint8Array: any) { export function uint8ArrayToBase64(uint8Array: any) {
const length = uint8Array.length const length = uint8Array.length;
let binaryString = '' let binaryString = '';
const chunkSize = 1024 * 1024; // Process 1MB at a time const chunkSize = 1024 * 1024; // Process 1MB at a time
for (let i = 0; i < length; i += chunkSize) { for (let i = 0; i < length; i += chunkSize) {
const chunkEnd = Math.min(i + chunkSize, length) const chunkEnd = Math.min(i + chunkSize, length);
const chunk = uint8Array.subarray(i, chunkEnd) const chunk = uint8Array.subarray(i, chunkEnd);
// @ts-ignore // @ts-ignore
binaryString += Array.from(chunk, byte => String.fromCharCode(byte)).join('') binaryString += Array.from(chunk, (byte) => String.fromCharCode(byte)).join(
''
);
} }
return btoa(binaryString) return btoa(binaryString);
} }
export function base64ToUint8Array(base64: string) { export function base64ToUint8Array(base64: string) {
const binaryString = atob(base64) const binaryString = atob(base64);
const len = binaryString.length const len = binaryString.length;
const bytes = new Uint8Array(len) const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i) bytes[i] = binaryString.charCodeAt(i);
} }
return bytes return bytes;
} }
export const decryptGroupEncryption = async ({data}: { export const decryptGroupEncryption = async ({ data }: { data: string }) => {
data: string
}) => {
try { try {
const resKeyPair = await getKeyPair() const resKeyPair = await getKeyPair();
const parsedData = resKeyPair const parsedData = resKeyPair;
const privateKey = parsedData.privateKey const privateKey = parsedData.privateKey;
const encryptedData = decryptGroupData( const encryptedData = decryptGroupData(data, privateKey);
data,
privateKey,
)
return { return {
data: uint8ArrayToBase64(encryptedData.decryptedData), data: uint8ArrayToBase64(encryptedData.decryptedData),
count: encryptedData.count count: encryptedData.count,
} };
} catch (error: any) { } catch (error: any) {
throw new Error(error.message); throw new Error(error.message);
} }
} };
export function uint8ArrayToObject(uint8Array: any) { export function uint8ArrayToObject(uint8Array: any) {
// Decode the byte array using TextDecoder // Decode the byte array using TextDecoder
const decoder = new TextDecoder() const decoder = new TextDecoder();
const jsonString = decoder.decode(uint8Array) const jsonString = decoder.decode(uint8Array);
// Convert the JSON string back into an object // Convert the JSON string back into an object
return JSON.parse(jsonString) return JSON.parse(jsonString);
} }