NodeJS HD Wallet addresses generation issue

I am trying to code a HD wallet using NodeJS

There is the example I started with

https://medium.com/bitcraft/so-you-want-to-build-a-bitcoin-hd-wallet-part-1-8b27aa001ac3

I’m also using this to validate my data

https://iancoleman.io/bip39/

This is my code;

var bip39 = require('bip39');
var HDkey = require('hdkey');
var createHash = require('create-hash');
var bs58check = require('bs58check');

exports.seed = async () =>{
  return new Promise(resolve => {
    const mnemonic =  "drive captain sustain winner neutral anchor congress skirt buzz usage orient wood"
    
    //const mnemonic =  bip39.generateMnemonic(); //generates the string above
    const seed =  bip39.mnemonicToSeed(mnemonic); //creates seed buffer
    resolve(seed)
  })
}



 exports.key = async (seed) =>{
  return new Promise(resolve => {

    const hdkey = HDkey.fromMasterSeed(Buffer.from(seed, 'hex'))

    const masterPrivateKey = hdkey.privateExtendedKey

     // This key Match iancoleman BIP32 ROOT KEY
    console.log("x1b(32m%sx1b(0m",'PRIVATE KEY BIP32 ROOT: ', masterPrivateKey) 

    // this line will not give me valid BIP32 EXTENDED PRIVATE KEYS
    //const addrnode = hdkey.derive("m/44'/0'/0'/0/0")
    
    // This one will when I removed the last /0
    const addrnode = hdkey.derive("m/44'/0'/0'/0")
    
    // THESE 2 BIP32 Extended Key are valid on iancoleman's app
    console.log("x1b(32m%sx1b(0m",'PRIVATE EXTENDED : ', addrnode.privateExtendedKey)
    const step1 = addrnode.publicExtendedKey
    console.log("x1b(32m%sx1b(0m",'PUBLIC EXTENDED : ', step1.toString('hex'))

    // Here is what I could understand from the example

    //SHA256 of the public key
    const step2 = createHash('sha256').update(step1).digest()
  
    // PIPEDMD-160 of the SHA256 Hash
    const step3 = createHash('rmd160').update(step2).digest()
    

    // He we must add the network byte in front of that PIPEDMD result
    // 0x00 for mainnet and 0x6f for testnet
    var step4 = Buffer.allocUnsafe(21)
    step4.writeUInt8(0x00, 0)
    step3.copy(step4,1) 

    //step3 now holds the  Network ID +  RIPEMD160 result
    //we hash it twice
    var step5 = createHash('sha256').update(step4).digest()
    var step6 = createHash('sha256').update(step5).digest()


    //checksum first 4 byte of second hash
    var step7 = step6.slice(0,4)
    console.log("x1b(32m%sx1b(0m",'CHECKSUM : ', step7.toString('hex'))

   // Adding the checksum to the end of
    var step8 = Buffer.concat((step4, step7));  
    console.log("x1b(32m%sx1b(0m",'Base + CHECKSUM : ', step8.toString('hex'))
    // Return the bitcoins address
    var step9 = bs58check.encode(step8)


   resolve(step9)

    // The address generated by this code;
    // 1WpGHR9UmDm7UiJuFu1H3zE7TmtK187D1yZStMQ

    // The address generated with the same mnemonic on iancoleman app;
    // 1HaGGkWmUDTKExFxyXaiGHHPxYNaCefQrj
  })
}

I don’t get why i manage to get valid BIP32 keys but the address won’t come out right.

nodejs – Acceder a datos de una consulta de MongoDB

He estado tratando de acceder a datos de una colección en mongodb y al colocar la consulta en una constante y tratar de mostrar un elemento me da como resultado “undefined”, he leído algunas preguntas similares y aplicado lo que responden pero sin éxito, dejo acá a ver si alguno me ayuda.

Consulta en mongoose

 let report1 = await Client.aggregate((
                {
                    $lookup:
                    {
                        from: "trans",
                        localField: "cli_id",
                        foreignField: "cli_ced",
                        as: "docs"
                    }
                },
            ));

resultado de la consulta en mongoDB

    {
        "_id" : ObjectId("5fc9afe9a855fe903cdc458d"),
        "cli_create_date" : ISODate("2020-12-04T03:34:50.382Z"),
        "cli_name" : "James",
        "cli_lname" : "Muller",
        "cli_nac" : "Panameño",
        "cli_id" : "8-741-9875",
        "cli_mig" : "N/A",
        "cli_mig_vig" : ISODate("0001-01-01T00:00:00Z"),
        "cli_licen" : "AS45887",
        "cli_licen_vig" : ISODate("2022-12-11T00:00:00Z"),
        "cli_email" : "jamesmax@yahoo.com",
        "cli_tel" : "",
        "cli_cel1" : "69110734",
        "cli_cel2" : "",
        "cli_insta" : "",
        "cli_face" : "",
        "cli_dir" : "",
        "cli_sector" : "",
        "cli_street" : "",
        "cli_dir2" : "",
        "cli_home" : "",
        "cli_referido" : "",
        "cli_job" : "Freelance",
        "cli_ocu" : "mensajero",
        "cli_job_time" : "1 año",
        "cli_job_sec" : "Tumba muerto",
        "cli_job_dir" : "calle 2",
        "cli_job_tel" : "",
        "cli_job_boss" : "",
        "cli_job_boss_tel" : "",
        "cli_other" : "",
        "cli_salary" : 1000,
        "cli_fortnight" : 500,
        "cli_cont" : "2",
        "cli_biweekly" : 120,
        "cli_dir_ref" : "",
        "cli_periodo" : "Semanal",
        "ref_name" : "Maria",
        "ref_lname" : "salas",
        "ref_ocu" : "Estilista",
        "ref_cel" : "66987411",
        "ref_name2" : "javier",
        "ref_lname2" : "Perez",
        "ref_ocu2" : "Prograador",
        "ref_cel2" : "65201074",
        "cli_user" : ObjectId("5fb337b20d55e83530ea0992"),
        "__v" : 0,
        "docs" : (
                {
                        "_id" : ObjectId("5fc9b7a7653ef89748dedb04"),
                        "tran_date" : ISODate("2020-12-04T04:13:52.408Z"),
                        "cli_id" : ( ),
                        "tran_age" : 10,
                        "tran_stat" : 10,
                        "tran_sons" : 3,
                        "tran_house" : 10,
                        "tran_house_time" : 10,
                        "tran_job_time" : 10,
                        "tran_account" : 10,
                        "tran_apps" : 3,
                        "tran_css" : 3,
                        "tran_insurance" : 3,
                        "tran_att" : 3,
                        "tran_talk" : 10,
                        "tran_pan_time" : 10,
                        "tran_legal" : 10,
                        "tran_loan" : 6,
                        "tran_payment" : 6,
                        "tran_fortnight" : 10,
                        "tran_cony_fornight" : 3,
                        "tran_result" : 65,
                        "cli_ced" : "8-741-9875",
                        "__v" : 0
                }
        )
}

Deseo mostrar por ejemplo en un console.log() el elemento tran_age, he intentado colocarlo de muchas maneras, por ejemplo:

console.log(report1.tran_age);
console.log(report1(0).tran_age);
console.log(report1.docs(0).tran_age);
console.log(report1.docs.tran_age);
console.log(report1(0)(0).tran_age);
console.log(docs(0).tran_age);

además he probado funciones como JSON.stringify(), toArray(), con $unwind en el aggregation y nada.
colocando console.log(report1(0).cli_name) si obtengo la respuesta deseada, el problema está en los elementos dentro de docs.

Muchas gracias de antemano.

node.js – Type ‘ProductDocument’ does not satisfy the constraint ‘Document’

Estou desenvolvendo a api ( Node.js, express, mongoose, typescript ) para um sistema que estou criando. Porem acabei me deparando com o seguinte erro: “Type ‘ProductDocument’ does not satisfy the constraint ‘Document’.”

Segue meu código a baixo:

import mongoose, { Model, Document, Schema } from "mongoose";

export type ProductAttributes = {
    name: string;
    description?: string;
    price: number;
    tags?: (string);
    image: string;
};

export type ProductDocument = Document & ProductAttributes;

type ProductModel = Model<ProductDocument>;

const ProductSchema  = new Schema({
    name: {
        type: String,
        trim: true,
        required: true
    },
    description: {
        type: String,
        trim: true
    },
    price: {
        type: Number,
        trim: true,
        required: true
    },
    tags: {
        type: (String),
        trim: true
    },
    image: {
        type: String,
        trim: true,
        required: true
    }
},{timestamps: true});

export default mongoose.model<ProductDocument, ProductModel>("Product", ProductSchema);

Isso funcionava anteriormente mas agora não sei o que pode ter ocorrido.

databases – Help accesing MongoDB API data using Node.js website

Need help accessing data from MongoDB using node to create a website.

I have data being extracted to MongoDB from the Last.fm API. It is stored in the json format.

When trying to extract the data to a website using node and express to host the website, and monk to connect to mongo, I cannot get past the object field in the json data in the database. The html page displays it as ‘object’ instead if the data I need to see, and I cannot build the hierarchy to display past the object field. I need my website to display the full data for the track information that is in the database is there a way to convert this data so I can display it. Please correct the code or write your own to solve this issue. Thank you in advance.

attached are screenshots of the database data, the app.js, index.js, and the ejs file being displayed, as well as the output on the website.

Database screenshot
App.js screenshot
Index.js screenshot
Main website code screenshot
Current output screenshot

nodejs – Nodemailer – Error: Invalid greeting. response=* OK [CAPABILITY IMAP4rev1 UNSELECT ID CHILDREN NAMESPACE IDLE UIDPLUS STARTTLS AUTH=PLAIN]

Estoy tratando de enviar un correo tras recibir el formulario de contacto pero me da un error estoy usando node js y el modulo nodemailer y segun yo todo debería estar bien pero me da un error.

Este es el error de consola:
Este es el error de consola

Código JS:

    let { name, lastname, email, quest } = req.body;
    contentHTML = `
        <h1>User Information</h1>
        <ul>
            <li>Username: ${name}</li>
            <li>User lastname: ${lastname}</li>
            <li>User correo: ${email}</li>
        </ul>
        <p>${quest}</p>
    `;

    let transporter = nodemailer.createTransport({
        host: 'imap.secureserver.net',
        port: 143,
        secure: false,
        auth: {
            user: config.email,
            pass: config.pass
        },
        tls: {
            rejectUnauthorized: false
        }
    });
    await transporter.sendMail({
        from: `"Team" <${config.email}>`, 
        to: `${email}`,
        subject: 'Solicitud',
        html: contentHTML,
        text: "is a test"
    })

node.js – While executing app.js it gives an error with socket.io

        socketserver.listen(g_ServerPort);
     var httpred = require('http');
     httpred.createServer(function (req, res) {
         res.writeHead(301, { "Location": "https://" + req.headers('host') + req.url });
         res.end();
     }).listen(80);
    var io = require('socket.io').listen(socketserver);
node app.js
/var/apps/app.js:31
var io = require('socket.io').listen(socketserver);

socket.io@3.0.3 version
nodejs version v12.19.1

                          ^

After i run app.js i get this error :

/var/apps/app.js:31
var io = require('socket.io').listen(socketserver);
                              ^

TypeError: require(...).listen is not a function
    at Object.<anonymous> (/var/apps/app.js:31:31)

node.js – NextJS API endpoint for a ‘form backend’ service

(This is using NextJs but there was no tag for that available)

I’m building a form backend service, similar to Formspree. The user can create a form however they like on their frontend and submit it to my API endpoint to be collected and stored. This becomes tricky when needing to handle files as well as plain body fields. The code I have below seems to work fine but it has become excessively messy.

import nextConnect from 'next-connect';
import bodyParser from 'body-parser';
import { nanoid } from 'nanoid';
import multer from 'multer';
import aws from 'aws-sdk';
import multerS3 from 'multer-s3';
import middleware from '../../../../middlewares/middleware';
import trimObject from '../../../../helpers/trimObject';
import runMiddleware from '../../../../helpers/runMiddleware';
import { MAX_FILE_SIZE, USER_FILE_LIMIT } from '../../../../constants';

const spacesEndpoint = new aws.Endpoint('nyc3.digitaloceanspaces.com');
const s3 = new aws.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID, // Set access key here
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  endpoint: spacesEndpoint,
});
const handler = nextConnect();

handler.use(middleware);
export const config = {
  api: {
    bodyParser: false,
  },
};

// Catch posts submissions
handler.post(async (req, res) => {
  try {
    // Get the form and make sure it exists
    const { formId } = req.query;
    const form = await req.db.collection('forms').findOne({ _id: formId });
    if (!form) {
      return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=404`);
    }

    // Get the form creator and subscription level
    const user = await req.db.collection('users').findOne({
      _id: form._creator,
    });
    if (!user) {
      return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=404`);
    }

    let isFileUploadAllowed = false;

    // Determine if the form is multipart
    const isMultipart = req.headers('content-type').toLocaleLowerCase().startsWith('multipart/form-data');

    if (isMultipart) {
      // Get the file sizes of all the users files
      const userFiles = await req.db.collection('files').aggregate(
        (
          { $match: { _owner: form._creator } },
          {
            $group: {
              _id: null,
              totalSize: {
                $sum: '$size',
              },
            },
          },
        ),
      ).toArray();

      // Check that the user hasn't exceed thier file upload limit
      const totalFileSize = userFiles.length && userFiles(0).totalSize;
      if (totalFileSize < USER_FILE_LIMIT) {
        isFileUploadAllowed = true;
      }
    }

    // Create the transaction
    const session = req.dbClient.startSession();
    try {
      const transactionOptions = {
        readPreference: 'primary',
        readConcern: { level: 'local' },
        writeConcern: { w: 'majority' },
      };

      const transactionResults = await session.withTransaction(async () => {
        const submissionId = nanoid();

        // Is multipart form and fileupload allowed
        if (isFileUploadAllowed && isMultipart) {
          await runMiddleware(
            req,
            res,
            multer({
              limits: { fileSize: 26214400 },
              storage: multerS3({
                s3,
                bucket: process.env.AWS_S3_BUCKET,
                acl: 'public-read',
                key(_, file, cb) {
                  cb(null, `${user._id}/${form._id}/${submissionId}/${file.originalname}`);
                },
              }),
            }).array('_file', 5),
          );

          // Create File objects and insert them
          let files = ();
          req.files.forEach((file) => {
            const { key, size, originalname } = file;
            files = (...files, {
              name: originalname,
              key,
              size,
              _id: nanoid(),
              _created: new Date(),
              _submission: submissionId,
              _form: form._id,
              _owner: form._creator,
            });
          });

          await req.db.collection('files').insert(files, { session });
        } else if (isMultipart) {
          // Is multipart form and fileupload not allowed, errors if any files attached
          await runMiddleware(
            req,
            res,
            multer().none(),
          );
        } else {
          // Is not multipart form form
          await runMiddleware(
            req,
            res,
            bodyParser.urlencoded({ extended: false }),
          );
        }
        // Create Submission object
        const body = trimObject(req.body);
        const submission = {
          ...body,
          _id: submissionId,
          _created: new Date(),
          _form: formId,
        };

        await req.db.collection('submissions').insertOne(submission, { session });
      }, transactionOptions);

      // Transaction was successful, send to thank you apge
      if (transactionResults) {
        return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/thanks`);
      }
      return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=500`);
    } catch (e) {
      // Error when uploading files
      if (e instanceof multer.MulterError) {
        // Files included when not allowed
        if (e.code === 'LIMIT_UNEXPECTED_FILE') {
          return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=400`);
        }
        // Any other error uploading file (most likely file size)
        return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=413`);
      }

      // Error not caused by file uploads
      return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=500`);
    } finally {
      await session.endSession();
    }
  } catch (e) {
    // Catch all send to 500 error invalid page
    return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=500`);
  }
});

// Catch all other methods
handler.all(async (req, res) => res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=405`));

export default handler;

mysql – Multiple JOIN Sequelize NodeJS

I’ve 3 tables:

Orders: id, user_id, etc...

ProductOrders: id, order_id, product_id, etc...

Products: id, name, price, etc...

With Sequelize I can easily do the relationship between Orders and ProductOrders in the Controller using this code:

Orders.hasMany(ProductOrders, {foreignKey: 'order_id'});
ProductOrders.belongsTo(Orders, {foreignKey: "order_id"});

But when I want to do a JOIN with the third table, the field “product” is null as you can see:

{
    "id": 1,
    "user_id": 1,
    "productOrders": (
        {
            "id": 1,
            "order_id": 1,
            "product_id": 5,
            "product": null
        }
    )
}

Any idea how you could associate them to show the product data? Thanks

nodejs – interpretación pm2 error

Tengo este error que me sale al tratar de correr mi programa con pm2 me dice esto:

[PM2][WARN] Applications nodejs_onem_backend not running, starting...

[PM2][ERROR] Error: Script not found: C:UsersroydeDocumentsPROYECTO FUNLAMnodejs_onem_backendsrcindex.ts
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nodejs_onem_backend@0.0.1 start: pm2 start pm2.json --only nodejs_onem_backend --env devnpm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nodejs_onem_backend@0.0.1 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersroydeAppDataRoamingnpm-cache_logs2020-11-29T22_45_53_694Z-debug.log

Como que no me carga correctamente el script, pero tengo bien configurado en el pm2.json con la ruta del script y demás.

    "apps": [{
    "name": "nodejs_onem_backend",
    "script": "C:/Users/royde/Documents/PROYECTO FUNLAM/nodejs_onem_backend/src/index.ts",
    "disable_logs": false,
    "instances": "1",
    "watch_options": {
        "followSymlinks": false

Espero me puedan ayudar o si tienen alguna idea de como corregirlo me ayudarían mucho, muchas gracias.

javascript – How can I create a nodejs provider hosted SharePoint add in

AS-IS: I’m programming NodeJS apps that connect to sharepoint using ADFS – no problem, works like a charm

TO-BE: Register the NodeJS app as an add-in.
I’m having trouble finding a way of doing this. Is there a step-by-step guide documented somewhere ?
Keeping in mind I’m trying to do this via

Ideally I want to swap out my ADFS authentication and replace it with an Add-In authentication.

Thanks a lot for any pointers