node 8 10 12 v8 promise async aswait
https://v8.dev/blog/fast-async
https://v8.dev/blog/fast-async
https://newcodingera.com/datatables-server-side-processing-using-nodejs-mysql/ https://1drv.ms/u/s!At2KEcnT9DVaiw88MAEXeML0bRf3 Important! SqlInjection ====================== datatables mongodb https://github.com/deepikagunda/datatables
https://medium.com/@antonassocareer/web3-secp256k1-%E7%B0%BD%E7%AB%A0%E8%88%87solidity%E9%A9%97%E7%AB%A0-26ded518cfdc 那麼如果我們想要單純用私鑰簽章一段資料,不要有Ethereum定義的那些prefix的話,就必須要直接調用 secp256k1 這一包library了。不過在用之前要知道,所有要丟給secp256k1簽章的message,長度都必須是256 bits,也就是32 bytes。剛剛我們說web3的簽名函式丟什麼都可以,是因為它會幫我加上prefix之後再做sha3 Hash (keccak),最後一定會變成一個32 bytes的東西。如果我們自己純靠私要簽章訊息的話,也勢必要先通過這個函式來整理input長度 sha3 Hash (keccak)
const bip39 = require('bip39') const bip32 = require('bip32'); const EC = require('elliptic').ec; json =`test json file` mnemonic = "簡 熙 夢 幾 聲 可 高 汪 煙 版 統 仇" path = "m/2018'/5'/1'/0/1" const sJWSinit = async () => { console.log('-----sJWS Initial Start----- \n'); dkey = await DeriveKey(mnemonic, path) console.log("\nGet dkey: %o \n", dkey) console.log('\n-----elliptic ed25519 Start----- \n'); var EdDSA = require('elliptic').eddsa var ec = new EdDSA('ed25519'); var eckeypair = ec.keyFromSecret(dkey.privateKey) var privateKeyHex = new Buffer.from(eckeypair.getSecret()).toString('hex') var publickeyHex = new Buffer.from(eckeypair.getPublic()).toString('hex') console.log("private key hex: %o", privateKeyHex) console.log("public key hex: %o\n", publickeyHex) var signature = eckeypair.sign(json).toHex(); console.log("signature: %o\n", signature) var ec2 = new EdDSA('ed25519'); var ec2keypair2 = ec2.keyFromPublic(publickeyHex, 'hex'); console.log("EdDSA json verify: %o", ec2keypair2.verify(json, signature)); } (async () => { console.log("--- aysnc sJWS init---") await sJWSinit(); })(); async function DeriveKey(mnemonic, derivePath) { if (bip39.validateMnemonic(mnemonic)) { console.log("mnemonic is fake!") } return bip39.mnemonicToSeed(mnemonic).then((vseed)=>{ var root = bip32.fromSeed(vseed) var PathNode = root.derivePath(derivePath) console.log("# PATH 是 m/2018'/5'/1'/0/1/0 因為底下為derive(0),所以 path + '/0' \n") console.log("privateKey (Hex): %o", PathNode.derive(0).privateKey.toString('hex')) console.log("publicKey (Hex): %o", PathNode.derive(0).publicKey.toString('hex')) // 024ac10a81e3a0f86cb4dad68c6a26031d805a057f36048f80a5b91b1c2cb0588c 符合 return { prv_buf: PathNode.derive(0).privateKey, pub_buf: PathNode.derive(0).publicKey, wif: PathNode.derive(0).toWIF(), publicKey: PathNode.derive(0).publicKey.toString('hex'), privateKey: PathNode.derive(0).privateKey.toString('hex'), path: derivePath } }).catch((e) => { console.error('handle error here: ', e.message) }) }
bitcoinSecp256r1.HDNode.fromSeedBuffer 無法使用,目前正確應該是用 bitcoinSecp256r1.bip32.fromSeed jsrsasign 有異常 const bip39 = require('bip39') const bip32 = require('bip32'); const bitcoinSecp256r1 = require('bitcoinjs-lib') const ethUtil = require('ethereumjs-util') const EC = require('elliptic').ec; // bitcoinSecp256r1.HDNode.fromSeedBuffer 無法使用,目前正確應該是用 bitcoinSecp256r1.bip32.fromSeed mnemonic = "簡 熙 夢 幾 聲 可 高 汪 煙 版 統 仇" path = "m/2018'/5'/1'/0/1" type = "secp256r1" // 驗證網頁 https://iancoleman.io/bip39/#chinese_traditional if (bip39.validateMnemonic(mnemonic)) { console.log("mnemonic is fake!") } const seed = bip39.mnemonicToSeed(mnemonic).then((vseed)=>{ var root = bip32.fromSeed(vseed) var PathNode = root.derivePath(path) console.log("---------------------------------------------") console.log("# PATH 是 m/2018'/5'/1'/0/1/ \n") console.log("Bitcoin Address: %o 符合 \n", getAddress(PathNode)) // 1GcgQJN7XgqkZkQcD4dzaZ7bjCFvQ6wxF2 符合 m/2018'/5'/1'/0/1 console.log("root toWIF: %o", root.toWIF()) console.log("PathNode toWIF: %o 符合", PathNode.toWIF()) // Kzq7FAYiWjDAcwU44FvcyCsCpJyLCD19n13FyQgLY6oBNajYcAYz 符合 m/2018'/5'/1'/0/1 console.log("--------------------------------------------- \n") // 底下為derive(0),所以正確是 m/2018'/5'/1'/0/1/0 為 path + '/0' console.log("---------------------------------------------") console.log("# PATH 是 m/2018'/5'/1'/0/1/0 因為底下為derive(0),所以 path + '/0' \n") console.log("privateKey (WIF): %o 符合", PathNode.derive(0).toWIF()) // L5ccMER4KyRn6pY6amvrFAHacpEsKrH1eTjDNeWwgXMnqjSCUU6N 符合 console.log("privateKey (Buffer): %o", PathNode.derive(0).privateKey) console.log("privateKey (String): %o", PathNode.derive(0).privateKey.toString()) console.log("privateKey (Hex): %o", PathNode.derive(0).privateKey.toString('hex')) console.log("privatekeyHex: %o \n", PathNode.derive(0).privkeyHex) console.log("publicKey (Hex): %o 符合", PathNode.derive(0).publicKey.toString('hex')) //024ac10a81e3a0f86cb4dad68c6a26031d805a057f36048f80a5b91b1c2cb0588c 符合 console.log("Bitcoin Address: %o 符合", getAddress(PathNode.derive(0))) //1Gp8AuHiYyBixrvLkKtC4VDhxpvK8PmYEr 符合 console.log("--------------------------------------------- \n") console.log('\n-----elliptic Initial Start----- \n'); var ec = new EC('p256'); let keyPair = ec.keyFromPrivate("83CFCC6EF1864C3303A5F8DEF2540167CB2DFA5DD22BB8D197B396972525FD56") let pubKey = keyPair.getPublic(); console.log("pubKey: %o", pubKey) // https://github.com/kjur/jsrsasign/issues/394 // sha512('aaa') => d6f644b19812e97b5d871658d6d3400ecd4787faeb9b8990c1e7608288664be77257104a58d033bcf1a0e0945ff06468ebe53e2dff36e248424c7273117dac09 let msgHash = 'd6f644b19812e97b5d871658d6d3400ecd4787faeb9b8990c1e7608288664be7' let signatureBase64 = 'MEUCIBEcfv2o3UwqwV72CVuYi7HbjcoiuSQOULY5d+DuGt3UAiEAtoNrdNWvjfdz/vR6nPiD+RveKN5znBtYaIrRDp2K7Ks=' let signatureHex = Buffer.from(signatureBase64, 'base64').toString('hex'); let validSig = ec.verify(msgHash, signatureHex, pubKey); console.log("Signature valid? %o \n", validSig); // use json var ec = new EC('secp256k1'); keyPair = ec.keyFromPrivate(dkey.publicKey) pubKey = keyPair.getPublic(); console.log("pubKey: %o", pubKey) var signature = keyPair.sign(json); var derSign = signature.toDER(); //console.log("signature: %o", signature) console.log("json verify: %o", keyPair.verify(json, derSign)); console.log('\n-----elliptic ed25519 Start----- \n'); var EdDSA = require('elliptic').eddsa var ec2 = new EdDSA('ed25519'); var ec2keypair = ec2.keyFromSecret(dkey.privateKey) //console.log("key: %o", key) var signature = ec2keypair.sign(json).toHex(); console.log("signature: %o", signature) var privateKeyHex = new Buffer(ec2keypair.getSecret()).toString('hex') var publickeyHex = new Buffer(ec2keypair.getPublic()).toString('hex') console.log("private key hex: %o", privateKeyHex) console.log("public key hex: %o", publickeyHex) var ec2keypair2 = ec2.keyFromPublic(publickeyHex, 'hex'); console.log("EdDSA json verify: %o", ec2keypair2.verify(json, signature)); bip39.mnemonicToSeed(mnemonic).then((vseed)=>{ var root = bitcoinSecp256r1.bip32.fromSeed(vseed) var PathNode = root.derivePath(path) console.log("bitcoinSecp256r1 privateKey (Hex): %o", PathNode.derive(0).privateKey.toString('hex')) console.log("bitcoinSecp256r1 publicKey (Hex): %o", PathNode.derive(0).publicKey.toString('hex')) const buf = Buffer.allocUnsafe(32); new Buffer.from(msgHash).copy(buf, 0, 0, 32) //msgbuf32 = new Buffer("01234567890123456789012345678901") console.log("msgHash buf 32: %o", buf.toString("hex")) var ecPair = bitcoinSecp256r1.ECPair.fromPrivateKey(PathNode.derive(0).privateKey) var signstring = ecPair.sign(buf) console.log("signstring: %o", signstring.toString("hex")) var verifyresult = ecPair.verify(buf, signstring) console.log("verify: %o", verifyresult) }) }) DeriveKey(mnemonic, path, type).then((v)=>{ console.log("dkey: %o", v) }); function getAddress (node, network) { return bitcoinSecp256r1.payments.p2pkh({ pubkey: node.publicKey, network }).address } function getEthereumAddress(privkeyHex) { const hexAddress = ethUtil.privateToAddress(Buffer.from(privkeyHex, 'hex')).toString('hex') const checksumAddress = ethUtil.toChecksumAddress(hexAddress) return checksumAddress } function DeriveKey(mnemonic, derivePath, type) { switch (type) { case "secp256r1": if (bip39.validateMnemonic(mnemonic)) { console.log("mnemonic is fake!") } return bip39.mnemonicToSeed(mnemonic).then((vseed)=>{ var root = bip32.fromSeed(vseed) var PathNode = root.derivePath(derivePath) console.log("# PATH 是 m/2018'/5'/1'/0/1/0 因為底下為derive(0),所以 path + '/0' \n") console.log("privateKey (Hex): %o", PathNode.derive(0).privateKey.toString('hex')) console.log("publicKey (Hex): %o 符合", PathNode.derive(0).publicKey.toString('hex')) // 024ac10a81e3a0f86cb4dad68c6a26031d805a057f36048f80a5b91b1c2cb0588c 符合 const buf = Buffer.allocUnsafe(32); PathNode.derive(0).privateKey.copy(buf, 0, 0, 32) console.log("Ethereum Address: %o 符合", getEthereumAddress(buf.toString('hex')) ) // 0xe020343a09086F53a203c9A0Ea76010049399575 符合 return { pub_buf: PathNode.derive(0).publicKey, wif: PathNode.derive(0).toWIF(), publicKey: PathNode.derive(0).publicKey.toString('hex'), privateKey: PathNode.derive(0).privateKey.toString('hex'), ethAddress: getEthereumAddress(buf.toString('hex')), path: derivePath } }).catch((e) => { console.log('handle error here: ', e.message) }) break; default: throw "type should be secp256k1 or secp256r1"; } }
HDWalletProvider engine.stop() p = HDWalletProvider(MNEMONIC_SYSTEM, "http://ganache:8545", 0); p.engine.stop(); HDWalletProvider engine.stop() and pool export function GetHdProvider(id: number, rpcurl: string) { //return new HDWalletProvider(MNEMONIC_SYSTEM, url, id); return id==0?Provider1Pool.acquire():Provider2Pool.acquire(); } // Normal use const hdProvider0 = await GetHdProvider(0, providerUrl).then(function(client) {return client}).catch(function(err) {throw new HttpException(err.toString(), HttpStatus.BAD_REQUEST);}); const hdProvider1 = await GetHdProvider(1, providerUrl).then(function(client) {return client}).catch(function(err) {throw new HttpException(err.toString(), HttpStatus.BAD_REQUEST);}); // Normal release ReleaseHDProvider1(hdProvider1 ); // Pool code const genericPool = require("generic-pool"); const opts = { max: 10, // maximum size of the pool min: 2, // minimum size of the pool idleTimeoutMillis: 30000, log: true }; const factory0 = { // maybe different parms create: function() { return new HDWalletProvider(MNEMONIC_SYSTEM, RPCURL, 0); }, destroy: function(client) { client.engine.stop(); } }; const factory1 = { // maybe different parms create: function() { return new HDWalletProvider(MNEMONIC_SYSTEM, RPCURL, 1); }, destroy: function(client) { client.engine.stop(); } }; export function ReleaseHDProvider1(client){ Provider1Pool.release(client); console.log("Provider1Pool status: pool.size %o pool.available %o pool.pending %o", Provider1Pool.size, Provider1Pool.available, Provider1Pool.pending) } export function ReleaseHDProvider2(client){ Provider2Pool.release(client); console.log("Provider2Pool status: pool.size %o pool.available %o pool.pending %o", Provider2Pool.size, Provider2Pool.available, Provider2Pool.pending) } const Provider1Pool = genericPool.createPool(factory0, opts); const Provider2Pool = genericPool.createPool(factory1, opts);
https://codeforgeek.com/server-side-pagination-using-node-and-mongo/
const https = require('https'); export async function GetUserinfo(Token) { console.log(process.env["NODE_TLS_REJECT_UNAUTHORIZED"]) process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0; console.log(process.env["NODE_TLS_REJECT_UNAUTHORIZED"]) const baseURL = 'https://openid.hydra:9001'; const userinfoURL = '/userinfo'; axios({ method: 'get', headers: { 'Authorization': 'Bearer ' + Token, 'accept': 'application/json' }, httpsAgent: new https.Agent({ rejectUnauthorized: false, ecdhCurve: 'auto' }), url: userinfoURL, baseURL: baseURL, responseType: 'json' }).then(function (response) { process.env[“NODE_TLS_REJECT_UNAUTHORIZED”] = 0; No Need, No mean Error: self signed certificate Answer: rejectUnauthorized: false, HTTPs requests to API fail: ‘sslv3 alert handshake failure Answer: ecdhCurve: ‘auto’ ...
https://peach.ebu.io/technical/tutorials/tuto-oauth2-client/ https://www.pveller.com/oauth2-with-passport-10-steps-recipe/ http://www.hitotec.com/authentification-oauth-avec-passportjs-pour-une-api-rest/ https://www.shangyang.me/2018/03/11/javascript-nodejs-passport-04-deepinto-oauth2-authenticate-process/ https://blog.yorkxin.org/2013/09/30/oauth2-4-1-auth-code-grant-flow.html
https://www.ory.sh/docs/hydra/integration#interacting-with-oauth-20 https://github.com/lelylan/simple-oauth2 https://www.jianshu.com/p/5cf2b7a45b75
https://gitissue.com/repos/jiayisheji/blog pass csrf https://github.com/expressjs/csurf/issues/21 main.ts import { NestFactory } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; import { join } from 'path' import { AppModule } from './app.module'; import * as cookieSession from 'cookie-session'; import * as helmet from 'helmet'; import * as cookieParser from 'cookie-parser'; import * as csurf from 'csurf'; import * as rateLimit from 'express-rate-limit'; async function bootstrap() { const app = await NestFactory.create( AppModule, ); app.init() app.useStaticAssets(join(__dirname, '..', 'public')); app.setBaseViewsDir(join(__dirname, '..', 'views')); app.setViewEngine('pug'); app.set('trust proxy', 1); app.use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })); //app.enableCors(); app.use(helmet()); app.use(cookieParser()); //app.use(csurf({ cookie: true })); //正常是這行,但有些API POST時需要略過csrf app.use(function (req, res, next) { var mw = csurf({ cookie: true }); // console.log(req.url) // check real get url if (req.url === '/testpostcsrf') return next(); //pass csrf check mw(req, res, next); }); app.use( rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs }), ); await app.listen(3000); } bootstrap(); layout.pug doctype html html head title= title meta(content= csrfToken, name='csrf-token') body block content login.pug extends layout block content h1 Please log in if error p. #{error} form(action="/login",method="POST") input(type="hidden",name="_csrf",value=csrfToken) input(type="hidden",name="challenge",value=challenge) table(style="") tr td input(type="email",id="email",name="email",placeholder="email@foobar.com") td. (Example: "foo@bar.com") tr td input(type="password",id="password",name="password") td. (Example: "foobar") input(type="checkbox",id="remember",name="remember",value="1") label(for="remember") Remember me br input(type="submit",id="accept",value="Log in")
https://gitissue.com/repos/jiayisheji/blog 這網站中的 让我们用Nestjs来重写一个CNode(上、中、下) 幫了大忙,減少大量的浪費時間 =========== html -> jade/pug http://html2jade.aaron-powell.com/ when you html meta want to become jade/pug layout.pug meta(content= csrfToken, name='csrf-token')
https://expressjs.com/en/advanced/best-practice-security.html
https://docs.etherniti.org/architecture/benchmarks/performance_test/
https://adon988.logdown.com/posts/7831077-the-corresponding-way-of-node-operation-in-the-formal-environment 在這裡要探討關於 node 到底適不適合在正式環境運行,在一開場首先說明我"過去"對於這個問題的看法,答案是:不適合。
npm install –global windows-build-tools https://www.npmjs.com/package/windows-build-tools https://stackoverflow.com/questions/32457761/how-to-solve-node-gyp-rebuild-issue-on-windows-10
What this Error? Example: transaction A get nonce 1 transaction B get nonce 2 transaction C get nonce 3 But blockchain package B、C first, then package A. If happen this step, get error. With truffle? Because Normal const wallet = new HDWalletProvider(mnemonic, url, id); const AContract = new TruffleContract(Json_contract); AContract.setProvider(wallet); wallet.addresses[] AContract. use contract api Sometime you call contract “set/write” api two times. Example: Create contract first. Write data into contract second. This two step are in one function. This mean is you call two time “new HDWalletProvide”. Usually you think “New“ two time is ok, get “new” instance. But ...
https://juejin.im/post/5ab3f77df265da2392364341 本地模块引用 這段不錯
Jest Expect Methods https://jestjs.io/docs/en/expect it = test it('count > 30', async () => { await reqTarget.get("/members").expect(200) .then((res) => { //Can use foreach, more easy for(key in res.body){ //console.log(res.body\[key\].cou ); if (res.body\[key\].cou > 100) throw new Error("count: "+res.body\[key\].cou +" > 30"); //for vars value check message expect(res.body\[key\].cou ).toBeLessThan(30); } }); });
You can do: 1. reget git clone 2. npm install 3. remove node_module 4. npm install agin 5. npm audit fix 6. npm start or run Sometime can Run.