1
0
forked from apxtri/apxtri

modif Odmdb and Pagans

This commit is contained in:
philc 2024-06-30 22:06:37 +02:00
parent 7ebbc29d73
commit c221fc98da
3 changed files with 318 additions and 52 deletions

File diff suppressed because one or more lines are too long

View File

@ -3,7 +3,7 @@ const path = require("path");
const dayjs = require("dayjs");
const fs = require("fs-extra");
const axios = require("axios");
const Mustache = require('mustache');
const Mustache = require("mustache");
const openpgp = require("openpgp");
const Notifications = require("./Notifications.js");
const Odmdb = require("./Odmdb.js");
@ -36,7 +36,7 @@ Pagans.logout = (alias, tribe, xdays, xhash) => {
//max filename in ext4: 255 characters
tmpfs += `_${xhash.substring(150, 150 + tmpfs.length - 249)}.json`;
fs.remove(tmpfs);
if (log) console.log(currentmod,'logout token',tmpfs)
if (log) console.log(currentmod, "logout token", tmpfs);
return { status: 200, ref: "Pagans", msg: "logout" };
};
@ -48,15 +48,13 @@ Pagans.logout = (alias, tribe, xdays, xhash) => {
**/
Pagans.getalias = (alias) => {
//bypass Odmdb cause all is public save ressources
console.log(path.resolve(`../objects/pagans/itm/${alias}.json`))
console.log(path.resolve(`../objects/pagans/itm/${alias}.json`));
if (fs.existsSync(`../objects/pagans/itm/${alias}.json`)) {
return {
status: 200,
ref: "Pagans",
msg: "aliasexist",
data: fs.readJSONSync(
`../objects/pagans/itm/${alias}.json`
),
data: fs.readJSONSync(`../objects/pagans/itm/${alias}.json`),
};
} else {
return {
@ -68,7 +66,6 @@ Pagans.getalias = (alias) => {
}
};
/**
* Send email with alias's keys to email or person alias person.recovery.email
*
@ -84,23 +81,28 @@ Pagans.getalias = (alias) => {
* @param {string} data.lg
*/
Pagans.sendmailkey = (data) => {
if (log) console.log(currentmod,
if (log)
console.log(
currentmod,
data.alias,
"-",
(data.privatekey)?data.privatekey.substring(0,10):"",
data.privatekey ? data.privatekey.substring(0, 10) : "",
"-",
data.tribe,
"-",
data.passphrase,
"-",
(data.publickey)? data.publickey.substring(0,10):"",
data.publickey ? data.publickey.substring(0, 10) : "",
"-",
data.email,
"-",
data.lg
);
const person = { alias:data.alias, privatekey:data.privatekey, tribe:data.tribe };
const person = {
alias: data.alias,
privatekey: data.privatekey,
tribe: data.tribe,
};
if (!data.publickey || !data.email || !data.privatekey) {
const personfile = `../../${data.tribe}/objects/persons/itm/${data.alias}.json`;
@ -118,8 +120,8 @@ Pagans.sendmailkey = (data) => {
status: 404,
ref: "Pagans",
msg: "personhasnorecoveryauth",
data:{alias:data.alias, tribe:data.tribe,email:data.email}
}
data: { alias: data.alias, tribe: data.tribe, email: data.email },
};
}
person.email = persondata.recoveryauth.email;
person.publickey = persondata.recoveryauth.publickey;
@ -130,7 +132,7 @@ Pagans.sendmailkey = (data) => {
person.passphrase = data.passphrase;
person.publickey = data.publickey;
}
person.avecpassphrase=(person.passphrase!="")
person.avecpassphrase = person.passphrase != "";
let tplfile = `../../${data.tribe}/template/createidentity_${data.lg}.js`;
if (!fs.existsSync(tplfile)) {
tplfile = `../template/createidentity_${data.lg}.js`;
@ -139,11 +141,11 @@ Pagans.sendmailkey = (data) => {
status: 406,
ref: "Pagans",
msg: "templatedoesnotexist",
data:{tplfile}
data: { tplfile },
};
}
}
}
const tplemail = require(path.resolve(tplfile))
const tplemail = require(path.resolve(tplfile));
/*
Remove from attachments for less user confusing
{
@ -162,9 +164,9 @@ Pagans.sendmailkey = (data) => {
{
filename: `${person.alias}_privatekey.txt`,
content: person.privatekey,
contentType:"text/plain"
}
]
contentType: "text/plain",
},
],
};
return Notifications.sendmail(maildata, data.tribe);
};
@ -202,10 +204,10 @@ Pagans.authenticatedetachedSignature = async (
if (log) console.log(currentmod, "Signed by key id " + keyID.toHex());
return KeyId.toHex().alias == alias;
} catch (e) {
if (log) console.log(currentmod,"Signature could not be verified: " + e.message);
if (log)
console.log(currentmod, "Signature could not be verified: " + e.message);
return false;
}
};
module.exports = Pagans;

View File

@ -0,0 +1,262 @@
const assert = require('assert');
const openpgp = require('openpgp');
const dayjs = require('dayjs');
const ut = { name: 'Pagans' };
const apx = {};
apx.generateKey = async (alias, passphrase) => {
try {
const pgpParams = {
type: 'ecc',
curve: 'curve25519',
userIDs: [{ name: alias }],
passphrase: passphrase,
format: 'armored'
};
const key = await openpgp.generateKey(pgpParams);
return {
alias,
passphrase,
privatekey: key.privateKeyArmored,
publickey: key.publicKeyArmored
};
} catch (error) {
console.error('Error generating key:', error);
return {}
}
};
apx.createIdentity = async (alias, passphrase) => {
try {
const { privatekey, publickey } = await apx.generateKey(alias, passphrase);
return { alias, privatekey, publickey };
} catch (error) {
console.error('Error creating identity:', error);
}
};
apx.clearmsgSignature = async (privateKeyArmored, passphrase, message) => {
try {
const { keys: [privateKey] } = await openpgp.decryptKey({
privateKey: await openpgp.readKey({ armoredKey: privateKeyArmored }),
passphrase
});
const signedMessage = await openpgp.sign({
message: await openpgp.createMessage({ text: message }),
signingKeys: privateKey
});
return signedMessage;
} catch (error) {
console.error('Error signing message:', error);
}
};
const personData = {};
const apxFunctions = {
modifyPersonData(alias, newFirstName) {
if (!personData[alias]) {
personData[alias] = {};
}
personData[alias].firstName = newFirstName;
return personData[alias];
},
checkPersonData(alias, expectedFirstName) {
return personData[alias] && personData[alias].firstName === expectedFirstName;
},
removePersonModification(alias, originalFirstName) {
if (personData[alias]) {
personData[alias].firstName = originalFirstName;
}
return personData[alias];
},
deleteAlias(alias) {
delete personData[alias];
return !personData[alias];
}
};
const pagans={"adminsmatchits":{passphrase:""},"recruiters":{passphrase:""},"seekers":{},"adminrecruiters":{}}
pagans.A.headers = {
xtrkversion: 1,
xalias: 'anonymous',
xapp: 'smatchapp',
xdays: 0,
xhash: 'anonymous',
xlang: 'fr',
xprofils: 'anonymous',
xtribe: 'smatchit',
xuuid: '0'
};
paganA.alias = 'testalias';
paganA.passphrase = 'testpassphrase';
let privateKey, publicKey;
let authHeaders;
const testroutes={}
testroutes.createidentity=(alias,passphrase)=>{
const mykey=apx.generateKey(alias,passphrase)
if (!mykey.alias){return testerror}
Pagans.gertalias(alias) pass test or not
}
const testCases = [
{
name: 'Generate Key',
async run() {
const keys = await apx.generateKey(alias, passphrase);
privateKey = keys.privatekey;
publicKey = keys.publickey;
return keys;
},
verify(keys) {
assert(keys, 'Keys should not be undefined');
assert(keys.privatekey, 'Private key should not be undefined');
assert(keys.publickey, 'Public key should not be undefined');
assert(keys.privatekey.includes('BEGIN PGP PRIVATE KEY BLOCK'), 'Private key is not valid');
assert(keys.publickey.includes('BEGIN PGP PUBLIC KEY BLOCK'), 'Public key is not valid');
}
},
{
name: 'Create Identity',
async run(alias) {
const identity = await apx.createIdentity(alias, passphrase);
privateKey = identity.privatekey;
publicKey = identity.publickey;
Pagans.getalias
return identity;
},
verify(identity) {
assert(identity, 'Identity should not be undefined');
assert(identity.alias === alias, 'Alias should match');
assert(identity.privatekey.includes('BEGIN PGP PRIVATE KEY BLOCK'), 'Private key is not valid');
assert(identity.publickey.includes('BEGIN PGP PUBLIC KEY BLOCK'), 'Public key is not valid');
}
},
{
name: 'Authenticate',
async run() {
headers.xalias = alias;
headers.xdays = dayjs().valueOf();
const msg = `${alias}_${headers.xdays}`;
headers.xhash = await apx.clearmsgSignature(privateKey, passphrase, msg);
authHeaders = {
...headers,
xhash: headers.xhash,
xdays: headers.xdays
};
return authHeaders;
},
verify(authHeaders) {
assert(authHeaders, 'Auth headers should not be undefined');
assert(authHeaders.xhash.includes('BEGIN PGP SIGNED MESSAGE'), 'xhash is not valid');
}
},
{
name: 'Modify Person Data',
async run() {
const newFirstName = 'NewFirstName';
return apxFunctions.modifyPersonData(alias, newFirstName);
},
verify(modifiedData) {
assert(modifiedData, 'Modified data should not be undefined');
assert.strictEqual(modifiedData.firstName, 'NewFirstName', 'First name should be updated');
}
},
{
name: 'Check Person Data',
async run() {
const expectedFirstName = 'NewFirstName';
return apxFunctions.checkPersonData(alias, expectedFirstName);
},
verify(isCorrect) {
assert(isCorrect, 'Person data should be correctly updated');
}
},
{
name: 'Remove Person Modification',
async run() {
const originalFirstName = 'OriginalFirstName';
return apxFunctions.removePersonModification(alias, originalFirstName);
},
verify(modifiedData) {
assert(modifiedData, 'Modified data should not be undefined');
assert.strictEqual(modifiedData.firstName, 'OriginalFirstName', 'First name should be reverted');
}
},
{
name: 'Check Reverted Person Data',
async run() {
const expectedFirstName = 'OriginalFirstName';
return apxFunctions.checkPersonData(alias, expectedFirstName);
},
verify(isCorrect) {
assert(isCorrect, 'Person data should be correctly reverted');
}
},
{
name: 'Delete Alias',
async run() {
return apxFunctions.deleteAlias(alias);
},
verify(isDeleted) {
assert(isDeleted, 'Alias should be deleted');
}
}
];
ut.run = async (options) => {
console.log('Test Pagans Registration and Authentication');
for (const testCase of testCases) {
console.log(`Running test case: ${testCase.name}`);
try {
/*
Have a look in routes/pagans.jss
create personae={4 alias utadminsmatchit ut....}
forEach()alias=>{
ut.create(alias)
}
//test perons
forEach()alias=>{
join tribe smatchit === create persons for a tribe
}
forEach()alias=>W{
ut.delete(alias)}
*/
const result = await testCase.run(alias);
testCase.verify(result);
console.log(`Test case ${testCase.name} passed`);
} catch (error) {
console.error(`Test case ${testCase.name} failed:`, error);
}
}
console.log('All test cases ran successfully');
};
module.exports = ut;
// Run the tests
if (require.main === module) {
ut.run({ verbose: true }).catch(err => {
console.error('Test case failed:', err);
});
}