From 7afcd6e2a48d14fb4e8566c3b24366b8521f5581 Mon Sep 17 00:00:00 2001 From: AbigailDeng Date: Thu, 21 Nov 2024 12:15:06 +0800 Subject: [PATCH 1/3] feat: credentials --- jest-report.xml | 516 ++++++++++---------- package.json | 2 +- src/util/httpProvider.js | 14 +- test/unit/util/httpProvider.browser-test.js | 4 + 4 files changed, 270 insertions(+), 266 deletions(-) diff --git a/jest-report.xml b/jest-report.xml index 8e793cdb..636a2aa4 100644 --- a/jest-report.xml +++ b/jest-report.xml @@ -1,25 +1,25 @@ - - - + + + - + - + - + - + - + - + - + @@ -27,499 +27,499 @@ - + - + - + - + - + - + - - + + - + - + - + - + - + - + - + - + - + + + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - + + + - + - + - + - + + + + + - + - + - + - + - + - + - + - - + + - - - + - + - + - + - + - + - + - - + + - + - - - + - + + + - + - + - + - + - + - + - + + + - + - + + + - + - + - + - + - + - + - + - + - + - + - + - - + + - - - + - + + + - + - + - + - + - - + + - + - + + + - + - + - + - + - + - - - + - + - + - - - + - + - + - + - + - + - + - - - + - + - + - + - + - + - + - - - + - + - - - - + + - - + + - - - + - + - + - - - + - + - - - + - - + + - + - - - + - + - + - + - + - + + + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + \ No newline at end of file diff --git a/package.json b/package.json index 9023247d..8e32de53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "aelf-sdk", - "version": "3.4.17", + "version": "3.4.18", "description": "aelf-sdk js library", "type": "module", "main": "dist/aelf.cjs.js", diff --git a/src/util/httpProvider.js b/src/util/httpProvider.js index 16762716..2f805827 100644 --- a/src/util/httpProvider.js +++ b/src/util/httpProvider.js @@ -21,12 +21,12 @@ if (process.env.RUNTIME_ENV === 'browser') { // eslint-disable-next-line no-restricted-globals const _self = typeof self === 'object' ? self : {}; const _window = typeof window === 'object' ? window : _self; - if (typeof _window.XMLHttpRequest !== 'undefined') { - RequestLibrary = _window.XMLHttpRequest; - isFetch = false; - } else if (typeof _window.fetch !== 'undefined') { + if (typeof _window.fetch !== 'undefined') { RequestLibrary = _window.fetch; isFetch = true; + } else if (typeof _window.XMLHttpRequest !== 'undefined') { + RequestLibrary = _window.XMLHttpRequest; + isFetch = false; } } else { // For node use xmlhttprequest @@ -128,7 +128,7 @@ export default class HttpProvider { const request = RequestLibrary; const { timeout } = this; const control = typeof AbortController === 'function' ? new AbortController() : {}; - const config = { ...requestConfig, signal: control.signal, credentials: 'omit' }; + const config = { ...requestConfig, signal: control.signal, credentials: 'include' }; // Simulation timeout return Promise.race([this.requestSendByFetch(config, request), HttpProvider.timeoutPromise(timeout)]).then( result => @@ -191,7 +191,7 @@ export default class HttpProvider { } else { request = new RequestLibrary(); } - request.withCredentials = false; + // request.withCredentials = false; this.requestSend(requestConfig, request); let result = request.responseText; @@ -209,7 +209,7 @@ export default class HttpProvider { sendAsyncByXMLHttp(requestConfig) { const request = RequestLibraryXMLOnly ? new RequestLibraryXMLOnly() : new RequestLibrary(); - request.withCredentials = false; + // request.withCredentials = false; request.timeout = this.timeout; this.requestSend(requestConfig, request, true); return new Promise((resolve, reject) => { diff --git a/test/unit/util/httpProvider.browser-test.js b/test/unit/util/httpProvider.browser-test.js index 49d7a081..71d18595 100644 --- a/test/unit/util/httpProvider.browser-test.js +++ b/test/unit/util/httpProvider.browser-test.js @@ -356,6 +356,8 @@ describe('test httpProvider', () => { } }); const xhr = window.XMLHttpRequest; + const _fetch = window.fetch; + window.fetch = undefined; window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass); const NewHttpProvider = require('../../../src/util/httpProvider').default; const httpProvider = new NewHttpProvider(tdvwEndPoint); @@ -370,6 +372,8 @@ describe('test httpProvider', () => { }); } catch (e) { expect(e).toEqual({ Error: 'error xhr' }); + } finally { + window.fetch = _fetch; } }); test('test send async by fetch method', async () => { From 1c7c99adfd179abdfcd242ea5dbcfe385fc75e1f Mon Sep 17 00:00:00 2001 From: AbigailDeng Date: Sat, 23 Nov 2024 14:00:51 +0800 Subject: [PATCH 2/3] feat: credential --- build/webpack.node.js | 2 +- examples/browser/index.html | 6 +- .../node/{crossChain.js => crossChain.cjs} | 0 .../node/crossChain/{utils.js => utils.cjs} | 0 examples/node/{index.js => index.cjs} | 7 +- .../node/random/{approve.js => approve.cjs} | 0 examples/node/random/{index.js => index.cjs} | 154 +++--- ...newRandomNumber.js => newRandomNumber.cjs} | 0 .../node/random/{random.js => random.cjs} | 0 jest-report.xml | 500 +++++++++--------- package.json | 4 +- src/util/httpProvider.js | 22 +- test/unit/util/httpProvider.browser-test.js | 57 +- 13 files changed, 419 insertions(+), 333 deletions(-) rename examples/node/{crossChain.js => crossChain.cjs} (100%) rename examples/node/crossChain/{utils.js => utils.cjs} (100%) rename examples/node/{index.js => index.cjs} (90%) rename examples/node/random/{approve.js => approve.cjs} (100%) rename examples/node/random/{index.js => index.cjs} (56%) rename examples/node/random/{newRandomNumber.js => newRandomNumber.cjs} (100%) rename examples/node/random/{random.js => random.cjs} (100%) diff --git a/build/webpack.node.js b/build/webpack.node.js index 47395ce2..aea7fc2d 100644 --- a/build/webpack.node.js +++ b/build/webpack.node.js @@ -12,7 +12,7 @@ const nodeConfig = { mode: 'production', output: { path: OUTPUT_PATH, - filename: 'aelf.cjs.js', + filename: 'aelf.cjs', library: { type: 'commonjs2' }, diff --git a/examples/browser/index.html b/examples/browser/index.html index 5d1f628d..e5a532c7 100644 --- a/examples/browser/index.html +++ b/examples/browser/index.html @@ -22,7 +22,11 @@ console.log(walletGotByMn); // link to Blockchain const aelf = new AElf(new AElf.providers.HttpProvider( - 'https://tdvw-test-node.aelf.io/' + 'https://tdvw-test-node.aelf.io/', + // 8000, + // { + // credentials: 'include' + // } )); if (!aelf.isConnected()) { diff --git a/examples/node/crossChain.js b/examples/node/crossChain.cjs similarity index 100% rename from examples/node/crossChain.js rename to examples/node/crossChain.cjs diff --git a/examples/node/crossChain/utils.js b/examples/node/crossChain/utils.cjs similarity index 100% rename from examples/node/crossChain/utils.js rename to examples/node/crossChain/utils.cjs diff --git a/examples/node/index.js b/examples/node/index.cjs similarity index 90% rename from examples/node/index.js rename to examples/node/index.cjs index ed8bbdc7..f9281e37 100644 --- a/examples/node/index.js +++ b/examples/node/index.cjs @@ -9,7 +9,12 @@ const defaultPrivateKey = 'bdb3b39ef4cd18c2697a920eb6d9e8c3cf1a930570beb37d04fb5 // const walletCreatedByMethod = Wallet.createNewWallet(); const wallet = Wallet.getWalletByPrivateKey(defaultPrivateKey); // link to Blockchain -const aelf = new AElf(new AElf.providers.HttpProvider('https://tdvw-test-node.aelf.io/')); +const aelf = new AElf( + new AElf.providers.HttpProvider('https://tdvw-test-node.aelf.io/', 8000, { + // cookie: '123', + credential: 'omit' + }) +); if (!aelf.isConnected()) { console.log('Blockchain Node is not running.'); diff --git a/examples/node/random/approve.js b/examples/node/random/approve.cjs similarity index 100% rename from examples/node/random/approve.js rename to examples/node/random/approve.cjs diff --git a/examples/node/random/index.js b/examples/node/random/index.cjs similarity index 56% rename from examples/node/random/index.js rename to examples/node/random/index.cjs index 4d468f8f..3f0e7ef5 100644 --- a/examples/node/random/index.js +++ b/examples/node/random/index.cjs @@ -2,9 +2,7 @@ const AElf = require('../../../dist/aelf.cjs'); const Wallet = AElf.wallet; -const { - sha256 -} = AElf.utils; +const { sha256 } = AElf.utils; // address: 2hxkDg6Pd2d4yU1A16PTZVMMrEDYEPR8oQojMDwWdax5LsBaxX const defaultPrivateKey = 'bdb3b39ef4cd18c2697a920eb6d9e8c3cf1a930570beb37d04fb52400092c42b'; @@ -41,29 +39,35 @@ const lotteryContract = aelf.chain.contractAt(lotteryContractAddress, wallet, { sync: true }); -const initialize = lotteryContract.Initialize({ - sponsor: '2hxkDg6Pd2d4yU1A16PTZVMMrEDYEPR8oQojMDwWdax5LsBaxX', - startPeriod: 0, - startTimestamp: { - seconds: (new Date()).getTime() / 1000 +const initialize = lotteryContract.Initialize( + { + sponsor: '2hxkDg6Pd2d4yU1A16PTZVMMrEDYEPR8oQojMDwWdax5LsBaxX', + startPeriod: 0, + startTimestamp: { + seconds: new Date().getTime() / 1000 + }, + tokenSymbol: 'ELF', + ready: true }, - tokenSymbol: 'ELF', - ready: true, -}, { - sync: true -}); + { + sync: true + } +); console.log('initialInfo', initialize); try { - "Error": "\nAElf.Sdk.CSharp.AssertionException: No record now.\n' - let records = lotteryContract.GetRecord.call({ - offset: 0, - limit: 10 - }, { - sync: true - }); -} catch(e) { + // "Error": "\nAElf.Sdk.CSharp.AssertionException: No record now.\n' + let records = lotteryContract.GetRecord.call( + { + offset: 0, + limit: 10 + }, + { + sync: true + } + ); +} catch (e) { // 错误返回不合适 // { Code: '20008', // Message: 'Invalid transaction information', @@ -74,33 +78,42 @@ try { // init: bf1fca5468599d2e04b24848fb498e2976fa6c976cfcb31540409df40bddd01c // noRecord: bc196d94ed41890886534ba824a325728eeb5f818b328db3079a94b3ea79d555 -lotteryContract.GetRecord({ - offset: 0, - limit: 10 -}, { - sync: true -}); +lotteryContract.GetRecord( + { + offset: 0, + limit: 10 + }, + { + sync: true + } +); -var record = lotteryContract.GetRecord.call({ - offset: 0, - limit: 10 -}, { - sync: true -}); +var record = lotteryContract.GetRecord.call( + { + offset: 0, + limit: 10 + }, + { + sync: true + } +); console.log(JSON.stringify(record)); // 开启新的一轮 -let peroid = lotteryContract.NewPeriod({ - periodNumber: 1, - // bc6672baf5e4984f4f1e0fbe698d170e07ebe8a29320cce17a899495dcd391d0 - randomNumberToken: '7e55bbc211171e48131d8ff7c8c2b38def7923ab717011066658b90219c1cae6' // 0 -}, { - sync: true -}); +let peroid = lotteryContract.NewPeriod( + { + periodNumber: 1, + // bc6672baf5e4984f4f1e0fbe698d170e07ebe8a29320cce17a899495dcd391d0 + randomNumberToken: '7e55bbc211171e48131d8ff7c8c2b38def7923ab717011066658b90219c1cae6' // 0 + }, + { + sync: true + } +); -lotteryContract.GetLuckyNumber({sync: true}); +lotteryContract.GetLuckyNumber({ sync: true }); -lotteryContract.GetState.call({sync: true}); +lotteryContract.GetState.call({ sync: true }); // message Lotteries { // repeated Lottery lottery = 1; @@ -123,33 +136,42 @@ for (let i = 0; i <= 9; i++) { }); } -lotteryContract.Bet({ - salerAddress: '2C2Acy4saYsnkRYEf54VawvmvUTAvrrWHKbLSwLg33b26woJVu', - proportionSale: 5, - proportionBonus: 5, - targetPeriod: 0, - senderAddress: '2hxkDg6Pd2d4yU1A16PTZVMMrEDYEPR8oQojMDwWdax5LsBaxX', - lottery -}, {sync: true}); - -lotteryContract.Bet({ - salerAddress: '2C2Acy4saYsnkRYEf54VawvmvUTAvrrWHKbLSwLg33b26woJVu', - proportionSale: 5, - proportionBonus: 5, - targetPeriod: 1, - senderAddress: '2hxkDg6Pd2d4yU1A16PTZVMMrEDYEPR8oQojMDwWdax5LsBaxX', - lottery: [ - {type: 1, value: [0, 0, 0, 0, 3]}, - {type: 1, value: [0, 0, 0, 0, 4]}, - {type: 1, value: [0, 0, 0, 0, 5]}, - ] -}, {sync: true}); +lotteryContract.Bet( + { + salerAddress: '2C2Acy4saYsnkRYEf54VawvmvUTAvrrWHKbLSwLg33b26woJVu', + proportionSale: 5, + proportionBonus: 5, + targetPeriod: 0, + senderAddress: '2hxkDg6Pd2d4yU1A16PTZVMMrEDYEPR8oQojMDwWdax5LsBaxX', + lottery + }, + { sync: true } +); + +lotteryContract.Bet( + { + salerAddress: '2C2Acy4saYsnkRYEf54VawvmvUTAvrrWHKbLSwLg33b26woJVu', + proportionSale: 5, + proportionBonus: 5, + targetPeriod: 1, + senderAddress: '2hxkDg6Pd2d4yU1A16PTZVMMrEDYEPR8oQojMDwWdax5LsBaxX', + lottery: [ + { type: 1, value: [0, 0, 0, 0, 3] }, + { type: 1, value: [0, 0, 0, 0, 4] }, + { type: 1, value: [0, 0, 0, 0, 5] } + ] + }, + { sync: true } +); lotteryContract.TakeReward('a24fec480944c16f0ed250cb3412e2b27312afc59adad6941adb20eb08b1a3c9', { sync: true }); -console.log('tx', aelf.chain.getTxResult('4c12bd187803fa1b63ac5794f614496154454725aa6c6747c890cdab39708e02', { - sync: true -})); +console.log( + 'tx', + aelf.chain.getTxResult('4c12bd187803fa1b63ac5794f614496154454725aa6c6747c890cdab39708e02', { + sync: true + }) +); console.log('RandomToken', RandomToken); diff --git a/examples/node/random/newRandomNumber.js b/examples/node/random/newRandomNumber.cjs similarity index 100% rename from examples/node/random/newRandomNumber.js rename to examples/node/random/newRandomNumber.cjs diff --git a/examples/node/random/random.js b/examples/node/random/random.cjs similarity index 100% rename from examples/node/random/random.js rename to examples/node/random/random.cjs diff --git a/jest-report.xml b/jest-report.xml index 636a2aa4..626a4d90 100644 --- a/jest-report.xml +++ b/jest-report.xml @@ -1,87 +1,87 @@ - - - + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - + - + - + - + - + - + - + - - + + - + - + - + - + - + - + - + - + - + @@ -89,189 +89,157 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - + - + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - + - + - + - - + + - - - - - + - + - + - + - + - + - + - + + + - + - + - + - + - - - + - + - - - + - + - + - + - + - - + + - + - - + + - + - + - + - + - + - + - + - + - + - + - + @@ -281,245 +249,281 @@ - + - + - + - - + + + + - - + + - + - + - + - + - + + + - + - - + + - + + + - + - + + + + + + + - + - + - + + + + + - - + + - - + + + + + + - + - + - + - + + + + + + + + + + + + + - + - + - + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - + - + - + - + - + - + - + - + - + - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + - + - + - + - + - + - + - + - + - + - + \ No newline at end of file diff --git a/package.json b/package.json index 8e32de53..ed3e4330 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "3.4.18", "description": "aelf-sdk js library", "type": "module", - "main": "dist/aelf.cjs.js", + "main": "dist/aelf.cjs", "module": "dist/aelf.esm.js", "browser": "dist/aelf.umd.js", "unpkg": "dist/aelf.umd.js", @@ -11,7 +11,7 @@ "exports": { ".": { "import": "./dist/aelf.esm.js", - "require": "./dist/aelf.cjs.js" + "require": "./dist/aelf.cjs" } }, "scripts": { diff --git a/src/util/httpProvider.js b/src/util/httpProvider.js index 2f805827..c6b607b3 100644 --- a/src/util/httpProvider.js +++ b/src/util/httpProvider.js @@ -14,25 +14,23 @@ const defaultHeaders = { let RequestLibrary = {}; let RequestLibraryXMLOnly = null; let isFetch = false; -let NodeHeaders; if (process.env.RUNTIME_ENV === 'browser') { // For browsers use DOM Api XMLHttpRequest // serviceworker without window and document, only with self // eslint-disable-next-line no-restricted-globals const _self = typeof self === 'object' ? self : {}; const _window = typeof window === 'object' ? window : _self; - if (typeof _window.fetch !== 'undefined') { - RequestLibrary = _window.fetch; - isFetch = true; - } else if (typeof _window.XMLHttpRequest !== 'undefined') { + if (typeof _window.XMLHttpRequest !== 'undefined') { RequestLibrary = _window.XMLHttpRequest; isFetch = false; + } else if (typeof _window.fetch !== 'undefined') { + RequestLibrary = _window.fetch; + isFetch = true; } } else { // For node use xmlhttprequest RequestLibraryXMLOnly = XHR; RequestLibrary = NodeFetch; - NodeHeaders = NodeFetch.Headers; isFetch = true; } @@ -106,7 +104,7 @@ export default class HttpProvider { const { url, method = 'POST', params = {}, signal } = requestConfig; const path = `/api/${url}`.replace(/\/\//g, '/'); let uri = `${this.host}${path}`.replace(); - const myHeaders = process.env.RUNTIME_ENV === 'browser' ? new Headers() : new NodeHeaders(); + const myHeaders = new Headers(); let body = JSON.stringify(params); if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') { uri = Object.keys(params).length > 0 ? `${uri}?${stringify(params)}` : uri; @@ -128,7 +126,11 @@ export default class HttpProvider { const request = RequestLibrary; const { timeout } = this; const control = typeof AbortController === 'function' ? new AbortController() : {}; - const config = { ...requestConfig, signal: control.signal, credentials: 'include' }; + const config = { + ...requestConfig, + signal: control.signal, + credentials: this.headers.credentials || 'omit' + }; // Simulation timeout return Promise.race([this.requestSendByFetch(config, request), HttpProvider.timeoutPromise(timeout)]).then( result => @@ -191,7 +193,7 @@ export default class HttpProvider { } else { request = new RequestLibrary(); } - // request.withCredentials = false; + request.withCredentials = this.headers.credentials === 'include' || this.headers.credentials === 'same-origin'; this.requestSend(requestConfig, request); let result = request.responseText; @@ -209,7 +211,7 @@ export default class HttpProvider { sendAsyncByXMLHttp(requestConfig) { const request = RequestLibraryXMLOnly ? new RequestLibraryXMLOnly() : new RequestLibrary(); - // request.withCredentials = false; + request.withCredentials = this.headers.credentials === 'include' || this.headers.credentials === 'same-origin'; request.timeout = this.timeout; this.requestSend(requestConfig, request, true); return new Promise((resolve, reject) => { diff --git a/test/unit/util/httpProvider.browser-test.js b/test/unit/util/httpProvider.browser-test.js index 71d18595..af60f465 100644 --- a/test/unit/util/httpProvider.browser-test.js +++ b/test/unit/util/httpProvider.browser-test.js @@ -276,6 +276,33 @@ describe('test httpProvider', () => { }) ).rejects.toEqual('failed when result is not ok'); }); + test('test send async by fetch with credentials', async () => { + const xhr = window.XMLHttpRequest; + delete window.XMLHttpRequest; + const originFetch = fetch; + window.fetch = jest.fn(() => + Promise.resolve({ + ok: true, + status: 200, + text: () => Promise.resolve('Success') + }) + ); + const NewHttpProvider = require('../../../src/util/httpProvider').default; + const httpProvider = new NewHttpProvider(tdvwEndPoint, 8000, { credentials: 'include' }); + window.XMLHttpRequest = xhr; + await httpProvider.sendAsyncByFetch({ + url: 'blockChain/blockHeight', + method: 'GET' + }); + + const sentHeaders = window.fetch.mock.calls[0][1].headers; + // headers is symbol map not object, so we cannot use objectContaining + const credentialsHeaderValue = sentHeaders.get('credentials'); + expect(credentialsHeaderValue).toEqual('include'); + + window.fetch = originFetch; + }); + test('test get request send by xhr', () => { const httpProvider = new HttpProvider(tdvwEndPoint); const RequestLibrary = window.XMLHttpRequest; @@ -356,8 +383,6 @@ describe('test httpProvider', () => { } }); const xhr = window.XMLHttpRequest; - const _fetch = window.fetch; - window.fetch = undefined; window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass); const NewHttpProvider = require('../../../src/util/httpProvider').default; const httpProvider = new NewHttpProvider(tdvwEndPoint); @@ -372,10 +397,34 @@ describe('test httpProvider', () => { }); } catch (e) { expect(e).toEqual({ Error: 'error xhr' }); - } finally { - window.fetch = _fetch; } }); + + test('test send by xhr with credentials', async () => { + const headers = { + credentials: 'include' + }; + const mockXHR = { + send: jest.fn(), + withCredentials: undefined, + responseText: 'Success' + }; + window.XMLHttpRequest = jest.fn(() => mockXHR); + const NewHttpProvider = require('../../../src/util/httpProvider').default; + const httpProvider = new NewHttpProvider(tdvwEndPoint, 8000, headers); + httpProvider.requestSend = jest.fn((config, request) => { + // Verify withCredentials setting + expect(request.withCredentials).toBe(true); + return request.responseText; + }); + const requestConfig = { + url: 'blockChain/executeTransaction', + method: 'POST' + }; + const result = httpProvider.send(requestConfig); + expect(result).toEqual('Success'); + }); + test('test send async by fetch method', async () => { const xhr = window.XMLHttpRequest; delete window.XMLHttpRequest; From 150b39527b4d47358d6a83ddc03ee33bfdb3bd62 Mon Sep 17 00:00:00 2001 From: AbigailDeng Date: Sat, 23 Nov 2024 16:49:33 +0800 Subject: [PATCH 3/3] feat: version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ed3e4330..67ca0b86 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "author": "hzz780", "license": "MIT", "devEngines": { - "node": "16.x || 18.x || 20.x" + "node": "18.x || 20.x" }, "engines": { "node": ">=18.18.0"