update auth openpgp.js

This commit is contained in:
2023-05-12 07:59:32 +02:00
parent dc11e8235e
commit a78bd8404a
85 changed files with 47890 additions and 1042 deletions

View File

@@ -0,0 +1,20 @@
const glob = require("glob");
const path = require("path");
const fs = require("fs-extra");
/**
* To manage any communication between Pagan
* mayor druid emailing/sms/paper from tribe register smtp, simcard, mail api to Person(s) / Pagan(s)
* volatile notification message from tribe activities to Pagans / person ()
*
*/
const Notifications = {};
Notifications.send = (data) => {
const ret = {};
console.log("TODO dev notification emailing");
return ret;
};
module.exports = Notifications;

View File

@@ -1,97 +1,125 @@
const glob = require("glob");
const path = require("path");
const dayjs = require("dayjs");
const fs = require("fs-extra");
const axios = require('axios');
const openpgp = require('openpgp');
const conf=require('../../nationchains/tribes/conf.json')
const axios = require("axios");
const openpgp = require("openpgp");
var conf = {};
if (fs.existsSync("../../nationchains/tribes/conf.json")) {
conf = require("../../nationchains/tribes/conf.json");
}
console.log(conf);
/**
* Pagan Management numeric Identity
*
*
*
* Pagan Management numeric Identity and Person (Person = Pagan Id + tribe)
*
*
*
*/
const Pagans= {}
const Pagans = {};
Pagans.createId = async (alias,passphrase) =>{
/**
* @param {string} alias a unique alias that identify an identity
* @param {string} passphrase a string to cipher the publicKey (can be empty, less secure but simpler)
* @return {publicKey,privateKey} with userIds = [{alias}]
*/
let apxpagans={};
if (fs.existsSync(`${conf.dirname}/nationchains/pagans/idx/alias_all.json`)){
apxpagans = fs.readJsonSync(
`${conf.dirname}/nationchains/pagans/idx/alias_all.json`
);
}
if (Object.keys(apxpagans).includes(alias)){
return {status:409,ref:"pagans",msg:"aliasalreadyexist"}
};
const {privateKey,publicKey} = await openpgp.generateKey({
type: "ecc", // Type of the key, defaults to ECC
curve: "curve25519", // ECC curve name, defaults to curve25519
userIDs: [{ alias: alias }], // you can pass multiple user IDs
passphrase: passphrase, // protects the private key
format: "armored", // output key format, defaults to 'armored' (other options: 'binary' or 'object')
});
apxpagans[alias]={alias,publicKey};
fs.outputJsonSync(`${conf.dirname}/nationchains/pagans/idx/alias_all.json`,apxpagans);
fs.outputJsonSync(`${conf.dirname}/nationchains/pagans/itm/${alias}.json`,{alias,publicKey});
return {status:200, data:{alias,privateKey,publicKey}}
}
//console.log( Pagans.generateKey('toto',''))
Pagans.detachedSignature = async (pubK, privK, passphrase, message) => {
/**
* @pubK {string} a text public key
* @privK {string} a test priv key
* @passphrase {string} used to read privK
* @message {string} message to sign
* @Return a detached Signature of the message
*/
const publicKey = await openpgp.readKey({ armoredKey: pubK });
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privK }),
passphrase,
});
const msg = await openpgp.createMessage({ text: message });
return await openpgp.sign({ msg, signinKeys: privK, detached: true });
};
Pagans.checkdetachedSignature = async (
Pagans.create = (alias, publicKey) => {
/**
* @param {string} alias a unique alias that identify an identity
* @param {string} publicKey a publicKey
* @return {object} { status: 200, data: { alias, publicKey } }
* xhash was checked by isauthenticated
* @todo use Odmdb to add a pagan
*/
let apxpagans = {};
if (fs.existsSync(`${__base}nationchains/pagans/idx/alias_all.json`)) {
apxpagans = fs.readJsonSync(
`${__base}nationchains/pagans/idx/alias_all.json`
);
}
apxpagans[alias] = { alias, publicKey };
fs.outputJsonSync(
`${__base}nationchains/pagans/idx/alias_all.json`,
apxpagans
);
fs.outputJsonSync(`${__base}nationchains/pagans/itm/${alias}.json`, {
alias,
pubK,
detachedSignature,
message
) => {
/**
* @alias {string} alias link to the publicKey
* @pubK {string} publiKey text format
* @detachedSignature {string} a detachedsignatured get from apx.detachedSignature
* @message {string} the message signed
* @return {boolean} true the message was signed by alias
* false the message was not signed by alias
*/
const publicKey = await openpgp.readKey({ armoredKey: pubK });
const msg = await openpgp.createMessage({ text: message });
const signature = await openpgp.readSignature({
armoredSignature: detachedSignature, // parse detached signature
});
const verificationResult = await openpgp.verify({
msg, // Message object
signature,
verificationKeys: publicKey
});
const { verified, keyID } = verificationResult.signatures[0];
try {
await verified; // throws on invalid signature
console.log("Signed by key id " + keyID.toHex());
return KeyId.toHex().alias == alias;
} catch (e) {
console.log("Signature could not be verified: " + e.message);
return false;
}
publicKey,
});
return { status: 200, data: { alias, publicKey } };
};
Pagans.personupdate = (alias, tribe, persondata) => {
//later use Odmdb ans schema person to manage this
/**
* @Param {string} alias pagan unique id
* @Param {string} tribe tribe id in this town
* @Param {object} persondata that respect /nationchains/schema/person.json + nationchains/tribe/tribeid/schema/personextented.json
* @return create or update a person /tribe/tribeid/person/alias.json
*/
let person = {
alias: alias,
dt_create: dayjs(),
accessrights: { profil: "user" },
};
module.exports=Pagans;
if (fs.existsSync(`${__base}tribes/${tribe}/person/itm/${alias}.json`)) {
person = fs.readJsonSync(
`${__base}tribes/${tribe}/person/itm/${alias}.json`
);
person.dt_update = dayjs();
}
Object.keys(persondata).forEach((d) => {
person[d] = persondata[d];
});
//const checkjson= Checkjson.schema.data = (fs.readJsonSync(`${__base}}nationchains/schema/person.json`, person, false)
// if checkjson.status==200 create /update with odmdb to update index data
// see odmdb that did all and return standard message
fs.outputJSONSync(
`${__base}tribes/${tribe}/person/itm/${alias}.json`,
person,
{
space: 2,
}
);
return {
status: 200,
ref: "Pagans",
msg: "successfullupdate",
data: { tribe: tribe },
};
};
Pagans.authenticatedetachedSignature = async (
alias,
pubK,
detachedSignature,
message
) => {
/**
* Check that a message was signed with a privateKey from a publicKey
* This is not necessary if isAuthenticated, but can be usefull to double check
* @TODO finish it and implement it also in /apxpagan.js for browser
* @alias {string} alias link to the publicKey
* @pubK {string} publiKey text format
* @detachedSignature {string} a detachedsignatured get from apx.detachedSignature
* @message {string} the message signed
* @return {boolean} true the message was signed by alias
* false the message was not signed by alias
*/
const publicKey = await openpgp.readKey({ armoredKey: pubK });
const msg = await openpgp.createMessage({ text: message });
const signature = await openpgp.readSignature({
armoredSignature: detachedSignature, // parse detached signature
});
const verificationResult = await openpgp.verify({
msg, // Message object
signature,
verificationKeys: publicKey,
});
const { verified, keyID } = verificationResult.signatures[0];
try {
await verified; // throws on invalid signature
console.log("Signed by key id " + keyID.toHex());
return KeyId.toHex().alias == alias;
} catch (e) {
console.log("Signature could not be verified: " + e.message);
return false;
}
};
module.exports = Pagans;

View File

@@ -4,6 +4,7 @@ const dnsSync = require("dns-sync");
const mustache = require("mustache");
const readlineSync = require("readline-sync");
const Wwws = require("../models/Wwws.js");
/**
* This Setup is run at the first installation
* This is not an exportable module
@@ -28,9 +29,9 @@ Setup.check = () => {
);
process.exit();
}
if (fs.existsSync("./nationchains/tribes/conf.json")) {
if (fs.existsSync("./nationchains/www/nginx_adminapx.conf")) {
console.log(
"\x1b[31m Be carefull you already have a town set in ./nationchains/tribes/index.conf.json, check and remove it if you want to setup this town."
"\x1b[31m Be carefull you already have a town set, check http://adminapx or remove ./nationchains/www/nginx_adminapx.conf to reset a sync with the last nationchains"
);
process.exit();
}
@@ -38,19 +39,51 @@ Setup.check = () => {
};
Setup.init = async () => {
/**
* create empty nationchains
* rsync all subfolder nationchains except the tribes/ and /www/nginx_adminapx.conf
*
* Then to send new version we fix a master production
*
*/
const initconf = fs.readJSONSync(
"./nationchains/www/adminapx/static/tpldata/initconf.json"
);
initconf.sudoerUser = process.env.USER;
initconf.dirname = path.resolve(`${__dirname}/../../`);
// To allow to serve the nation website until the end
initconf.nginx.include.push(
`${townconf.dirname}/nationchains/www/nginx_*.conf`
);
// To allow to serve tribes web site
initconf.nginx.include.push(
`${townconf.dirname}/nationchains/tribes/*/www/nginx_*.conf`
);
initconf.nginx.logs = `${townconf.dirname}/nationchains/logs/nginx`;
initconf.nginx.website = "adminapx";
initconf.nginx.fswww = "nationchains/"; //for a local tribe nationchains/tribes/tribeid
initconf.nginx.tribeid = "town";
initconf.nginx.pageindex = "index_en.html";
const nginxconf = Wwws.apxtribinstall(initconf);
if (nginxconf.status == 200) {
}
};
if (Setup.check()) Setup.init();
// After testing remove all stuff after this line
Setup.initold = async () => {
// Get standard conf and current data
const townconf = fs.readJsonSync("./nationchains/www/adminapx/townconf.json");
const apxnations = fs.readJsonSync(
`./nationchains/nations/idx/nationId_all.json`
);
const apxtowns = fs.readJsonSync(`./nationchains/towns/idx/townId_all.json`);
let apxpagans={}
if (fs.existsSync(`./nationchains/pagans/idx/alias_all.json`)){
apxpagans = fs.readJsonSync(
`./nationchains/pagans/idx/alias_all.json`
);
}
let apxpagans = {};
if (fs.existsSync(`./nationchains/pagans/idx/alias_all.json`)) {
apxpagans = fs.readJsonSync(`./nationchains/pagans/idx/alias_all.json`);
}
if (!Object.keys(apxnations).includes(townconf.nationId)) {
console.log(
@@ -95,7 +128,7 @@ Setup.init = async () => {
)
)
process.exit();
// saved and change nginx conf
if (!fs.existsSync("/etc/nginx/nginxconf.saved")) {
fs.moveSync("/etc/nginx/nginx.conf", "/etc/nginx/nginxconf.saved");
@@ -112,6 +145,16 @@ Setup.init = async () => {
mustache.render(tplnginxconf, townconf),
"utf8"
);
//proxyparam
const proxy_params = fs.readFileSync(
"./nationchains/www/adminapx/nginx/proxy_params.mustache",
"utf8"
);
fs.outputFileSync(
"/etc/nginx/proxy_params",
mustache.render(proxy_params, townconf),
"utf8"
);
const tplnginxwww = fs.readFileSync(
"./nationchains/www/adminapx/nginx/modelwebsite.conf.mustache",
"utf8"
@@ -124,8 +167,10 @@ Setup.init = async () => {
fs.outputJsonSync("./nationchains/tribes/conf.json", townconf, {
spaces: 2,
});
// Integrer cette partie du setup en inteactif.
// l'objectif du setup est de rendere accessible adminapx en local (IP local) ou production IP public
//CREATE A TOWN setup local voir utiliser towns.create
townconf.town = {
/* townconf.town = {
townId: townconf.townId,
nationId: townconf.nationId,
url: `http://${townconf.dns[0]}`,
@@ -133,9 +178,13 @@ Setup.init = async () => {
mayorid: townconf.mayorId,
status: "unchain",
};
apxtowns[townconf.townId]=townconf.town;
fs.outputJsonSync(`./nationchains/towns/idx/townId_all.json`,apxtowns);
fs.outputJsonSync(`./nationchains/towns/itm/${townconf.townId}.json`,townconf.town,{spaces:2});
apxtowns[townconf.townId] = townconf.town;
fs.outputJsonSync(`./nationchains/towns/idx/townId_all.json`, apxtowns);
fs.outputJsonSync(
`./nationchains/towns/itm/${townconf.townId}.json`,
townconf.town,
{ spaces: 2 }
);
// Create tribe id voir a utiliser tribes.create()
townconf.tribe = {
tribeId: townconf.tribeId,
@@ -145,27 +194,47 @@ Setup.init = async () => {
townId: townconf.townId,
};
//tribe does not exist in a new town
apxtribes={}
apxtribes[townconf.tribeId]=townconf.tribe;
fs.outputJsonSync(`./nationchains/tribes/idx/tribeId_all.json`,apxtribes);
fs.outputJsonSync(`./nationchains/tribes/itm/${townconf.tribeId}.json`,townconf.tribe,{spaces:2});
apxtribes = {};
apxtribes[townconf.tribeId] = townconf.tribe;
fs.outputJsonSync(`./nationchains/tribes/idx/tribeId_all.json`, apxtribes);
fs.outputJsonSync(
`./nationchains/tribes/itm/${townconf.tribeId}.json`,
townconf.tribe,
{ spaces: 2 }
);
fs.ensureDirSync(`./nationchains/tribes/${townconf.tribeId}/logs/nginx`);
//CREATE a mayorId pagans if it does not exist
if (!apxpagans[townconf.mayorId]){
const Pagans=require('./Pagans');
const createPagans=await Pagans.createId(townconf.mayorId,townconf.passphrase);
if (createPagans.status==200){
fs.outputFileSync(`./${townconf.mayorId}_PrivateKey.txt`,createPagans.data.privateKey,"utf8");
fs.outputFileSync(`./${townconf.mayorId}_PublicKey.txt`,createPagans.data.publicKey,"utf8");
console.log(`\x1b[43mCut paste your keys /${townconf.mayorId}_PrivateKey.txt /${townconf.mayorId}_PublicKey.txt \x1b[0m`)
}else{
console.log('Error at Pagan creation ');
if (!apxpagans[townconf.mayorId]) {
const Pagans = require("./Pagans");
const createPagans = await Pagans.createId(
townconf.mayorId,
townconf.passphrase
);
if (createPagans.status == 200) {
fs.outputFileSync(
`./${townconf.mayorId}_PrivateKey.txt`,
createPagans.data.privateKey,
"utf8"
);
fs.outputFileSync(
`./${townconf.mayorId}_PublicKey.txt`,
createPagans.data.publicKey,
"utf8"
);
console.log(
`\x1b[43mCut paste your keys /${townconf.mayorId}_PrivateKey.txt /${townconf.mayorId}_PublicKey.txt \x1b[0m`
);
} else {
console.log("Error at Pagan creation ");
console.log(createPagans);
process.exit();
}
}
//restart nginx
}*/
//fin de partie à integer dans l'interface graphique adminapx
//restart nginx
const { exec } = require("child_process");
exec(townconf.nginx.restart, (error, stdout, stderr) => {
if (error) {

118
api/models/Wwws.js Normal file
View File

@@ -0,0 +1,118 @@
const fs = require("fs-extra");
const path = require("path");
const dnsSync = require("dns-sync");
const mustache = require("mustache");
const readlineSync = require("readline-sync");
const conf = fs.existsSync("../../nationchains/tribes/conf.json")
? require("../../nationchains/tribes/conf.json")
: {};
const Wwws = {};
Wwws.apxtribinstall = (paramconf) => {
/**
* First install for a setup
*
*/
if (fs.existsSync("../../nationchains/www/nginx_adminapx.conf")) {
console.log("You already have a conf on this town");
process.exit();
}
//first install
const nginxconf = fs.readFileSync(
"../../nationchains/www/adminapx/static/tpl/nginx.conf.mustache",
"utf8"
);
const proxyparams = fs.readFileSync(
"../../nationchains/www/adminapx/static/tpl/nginxproxy_params.mustache",
"utf8"
);
// saved and change nginx conf
if (!fs.existsSync("/etc/nginx/nginxconf.saved")) {
fs.moveSync("/etc/nginx/nginx.conf", "/etc/nginx/nginxconf.saved");
console.log(
"your previous /etc/nginx/nginx.conf was backup in /etc/nginx/nginxconf.saved"
);
}
fs.outputFileSync(
"/etc/nginx/nginx.conf",
mustache.render(nginxconf, paramconf),
"utf8"
);
fs.outputFileSync(
"/etc/nginx/proxy_params",
mustache.render(proxyparams, paramconf),
"utf8"
);
if (!fs.existsSync(paramconf.nginx.logs)) fs.mkdirSync(paramconf.nginx.logs);
paramconf.nginx.firstinstall = true;
fs.outputJsonSync("../../nationchains/tribes/conf.json", paramconf, {
space: 2,
});
return Www.create(paramconf.nginx);
};
Wwws.create = (paramnginx) => {
/**
* Create an nginx conf to make available https://adminapx on a local network
* paramconf nginx.fswww place where the www folder is /tribeId/
*/
const res = {
status: 200,
ref: "Www",
msg: "successfulwww",
data: { website: paramnginx.website },
};
const nginxwebsite = fs.readFileSync(
"../../nationchains/www/adminapx/static/tpl/nginxmodelwebsite.conf.mustache",
"utf8"
);
fs.outputFileSync(
`./${paramnginx.fswww}www/nginx_${paramnginx.website}.conf`,
mustache.render(nginxwebsite, paramnginx),
"utf8"
);
if (!fs.existsSync(`./${paramnginx.fswww}www/${paramnginx.website}`)) {
//See later how to generate specific template of webapp
fs.mkdirSync(`./${paramnginx.fswww}www/${paramnginx.website}`);
}
if (!fs.existsSync(`./${paramnginx.fswww}www/cdn`)) {
//See later how to generate specific template of webapp
fs.mkdirSync(`./${paramnginx.fswww}www/cdn`);
}
//restart nginx
const { exec } = require("child_process");
exec(paramnginx.restart, (error, stdout, stderr) => {
if (error) {
if (paramnginx.firstinstall) {
console.log("\x1b[42m", error, stdout, stderr, "x1b[0m");
}
//@todo supprimer la derniere config et relancer
res.status = 500;
res.msg = "nginxError";
res.data = { msg: `${error}<br>${stdout}<br>${stderr}` };
} else {
if (paramnginx.firstinstall) {
// the tribes/conf.json is saved in apxtribinstall
console.log(
`\x1b[42m###########################################################################################\x1b[0m\n\x1b[42mWellcome into apxtrib, you can now 'yarn dev' for dev or 'yarn startpm2' for prod or \n'yarn unittest' for testing purpose. Access to your town here \x1b[0m\x1b[32mhttp://adminapx\x1b[0m \x1b[42m \nto finish your town setup. Don't forget to set your localhost /etc/hosts by adding 127.0.0.1 adminapx or {LAN IP} adminapx . Check README's project to learn more. \x1b[0m\n\x1b[42m###########################################################################################\x1b[0m`
);
} else {
// add website to tribe conf
}
}
});
return res;
};
Wwws.setssl = () => {
// Run process to change nginx conf to get a ssl
};
Wwws.configlist = (tribeId) => {
//if accessright R return list of conf parameter {webapp:{conf parameter}}
const res = { status: 200, data: {} };
return res;
};
module.exports = Wwws;

View File

@@ -1,3 +1,5 @@
{
}
"successfullcreate": "Alias creation for {{alias}} successfull. {{#withemail}} An email was sent to {{email}}, if you do not receive it, please download your keys before living this page.{{/withemail}}",
"successfulluppdate": "Your alias as a Person is now update into {{tribe}}",
"tribedoesnotexist": "Your tribe {{tribe}} does not exist in this town"
}