├── log └── .gitkeep ├── .npmignore ├── .babelrc ├── .eslintrc ├── src ├── moment.js ├── render.js ├── web.js ├── serializer.js ├── ui.js ├── cli.js ├── parser.js └── api.js ├── .travis.yml ├── test ├── test_cases │ ├── transaction-1.json │ ├── transaction-3.json │ ├── transaction-2.json │ ├── 05-history-empty.txt │ ├── 01-logon-page.html │ └── 04-history-partial.txt ├── moment.test.js ├── render.test.js ├── web.test.js ├── serializer.test.js ├── api.test.js └── parser.test.js ├── .gitignore ├── package.json ├── README.md └── LICENSE.txt /log/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .coveralls.yml* 2 | src/ 3 | log/ 4 | docs/ 5 | .vscode/ 6 | .yarnclean 7 | .credential 8 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { 4 | "targets": { 5 | "node": 6 6 | } 7 | }] 8 | ] 9 | } -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb-base", 3 | "rules": { 4 | "no-console": "off", 5 | "max-len": ["error", { 6 | "code": 120, 7 | "ignoreStrings": true, 8 | "ignoreTemplateLiterals": true 9 | }] 10 | } 11 | } -------------------------------------------------------------------------------- /src/moment.js: -------------------------------------------------------------------------------- 1 | const moment = require('moment-timezone'); 2 | 3 | moment.tz.setDefault('Australia/Sydney'); 4 | 5 | moment.formats = { 6 | default: 'DD/MM/YYYY', 7 | aus: 'DD/MM/YY', 8 | us: 'MM/DD/YY', 9 | sortable: 'YYYY-MM-DD', 10 | }; 11 | 12 | module.exports = moment; 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | dist: trusty 4 | sudo: false 5 | 6 | node_js: 7 | - node 8 | - '8' 9 | - '6' 10 | git: 11 | depth: 10 12 | script: yarn test-debug 13 | after_success: yarn coveralls 14 | deploy: 15 | provider: npm 16 | email: twang2218@gmail.com 17 | api_key: 18 | secure: YrqLetpC22L3ntvLbujg5S9un9gvYmLYnDoCT3FSydS1Q7Expcii5C9w+eZ+kM/nvuZViHFQ3TApilHdrVAcnMBh2kkW4Yixo5uCMZoOZ14I3eTQntbG7G14ZmN33mzh89uT56ESZEFnNBBHYp7gOllVNgL2tuMY+nVmLfZb7pM= 19 | on: 20 | tags: true 21 | repo: twang2218/node-cba-netbank 22 | branch: master 23 | skip_cleanup: true 24 | -------------------------------------------------------------------------------- /test/test_cases/transaction-1.json: -------------------------------------------------------------------------------- 1 | { 2 | "Date": { 3 | "Sort": [635529888000000000, "201411302026194883471"], 4 | "Text": "01 Dec 2014" 5 | }, 6 | "MonthYear": { 7 | "Text": "122014" 8 | }, 9 | "WebSearch": null, 10 | "Description": { 11 | "Url": "", 12 | "Sort": ["credit interest", -635529888000000000], 13 | "Text": "Credit Interest" 14 | }, 15 | "SortableDebit": { 16 | "Sort": [0, 0], 17 | "Text": "" 18 | }, 19 | "SortableCredit": { 20 | "Sort": [2, 0.01], 21 | "Text": "$0.01 CR" 22 | }, 23 | "SortableAmount": { 24 | "Sort": [2, 0.01], 25 | "Text": "$0.01 CR" 26 | }, 27 | "SortableCurrencyAmount": { 28 | "Sort": [2, 5.68], 29 | "Text": "$5.68 CR" 30 | }, 31 | "Debit": { 32 | "Text": "" 33 | }, 34 | "Credit": { 35 | "Text": "$0.01 CR" 36 | }, 37 | "Amount": { 38 | "Text": "$0.01 CR" 39 | }, 40 | "Balance": { 41 | "Text": "$5.68 CR" 42 | }, 43 | "FeeLink": { 44 | "Text": "", 45 | "Url": null, 46 | "Type": "" 47 | }, 48 | "TranCode": { 49 | "Text": "700000" 50 | }, 51 | "ReceiptNumber": { 52 | "Text": "" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | ### Node ### 4 | # Logs 5 | logs 6 | *.log 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | 13 | # Directory for instrumented libs generated by jscoverage/JSCover 14 | lib-cov 15 | 16 | # Coverage directory used by tools like istanbul 17 | coverage 18 | 19 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 20 | .grunt 21 | 22 | # node-waf configuration 23 | .lock-wscript 24 | 25 | # Compiled binary addons (http://nodejs.org/api/addons.html) 26 | build/Release 27 | 28 | # Dependency directory 29 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 30 | node_modules 31 | 32 | ### Tags ### 33 | # Ignore tags created by etags, ctags, gtags (GNU global) and cscope 34 | TAGS 35 | .TAGS 36 | !TAGS/ 37 | tags 38 | .tags 39 | !tags/ 40 | gtags.files 41 | GTAGS 42 | GRTAGS 43 | GPATH 44 | cscope.files 45 | cscope.out 46 | cscope.in.out 47 | cscope.po.out 48 | 49 | 50 | 51 | ### Project Specified ### 52 | 53 | .coveralls.yml* 54 | dist/ 55 | log/ 56 | docs/ 57 | .vscode/ 58 | .yarnclean 59 | .credential 60 | \[*.json 61 | \[*.qif 62 | \[*.csv 63 | 64 | -------------------------------------------------------------------------------- /src/render.js: -------------------------------------------------------------------------------- 1 | // Dependencies 2 | const chalk = require('chalk'); 3 | const Table = require('easy-table'); 4 | const moment = require('./moment'); 5 | 6 | // Functions 7 | const currency = amount => 8 | (amount >= 0 ? chalk.green.bold(`$${amount.toFixed(2)}`) : chalk.red.bold(`$${amount.toFixed(2)}`)); 9 | const account = a => 10 | `${chalk.bold(a.name)} \t(${chalk.red(a.bsb)} ${chalk.red(a.account)})` + 11 | `\t Balance: ${currency(a.balance)} ` + 12 | `\t Available Funds: ${currency(a.available)}`; 13 | const accounts = accs => 14 | Table.print(accs.map(a => ({ 15 | Name: chalk.bold(a.name), 16 | Number: `${chalk.red(a.bsb)} ${chalk.red(a.account)}`, 17 | Balance: `${currency(a.balance)}`, 18 | Available: `${currency(a.available)}`, 19 | }))); 20 | const transactions = ts => 21 | Table.print(ts.map(t => ({ 22 | Time: chalk.italic.cyan(moment(t.timestamp).format('YYYY-MM-DD HH:mm')), 23 | Description: t.pending ? chalk.gray(t.description) : chalk.white(t.description), 24 | Amount: currency(t.amount), 25 | Balance: t.pending ? '' : currency(t.balance), 26 | }))); 27 | 28 | module.exports = { 29 | currency, 30 | account, 31 | accounts, 32 | transactions, 33 | }; 34 | -------------------------------------------------------------------------------- /test/test_cases/transaction-3.json: -------------------------------------------------------------------------------- 1 | { 2 | "Date": { 3 | "Sort": [635655168000000000, "000000000000000000003"], 4 | "Text": "25 Apr 2015" 5 | }, 6 | "MonthYear": { 7 | "Text": "042015" 8 | }, 9 | "WebSearch": { 10 | "Text": "", 11 | "Url": "MCC", 12 | "Type": "" 13 | }, 14 | "Description": { 15 | "Url": "/netbank/TransactionHistory/MerchantDetails.aspx?RID=Id0RboN-VUGkvNYJjWex6A&SID=9j3x0nrpJHI%3d&OD=DAMS+APPLE+AT+THE+STAT+++HURSTVILLE&MId=5411", 16 | "Sort": ["dams apple at the stat hurstville", -635655168000000000], 17 | "Text": "DAMS APPLE AT THE STAT HURSTVILLE" 18 | }, 19 | "SortableDebit": { 20 | "Sort": [1, 19.72], 21 | "Text": "$19.72 DR" 22 | }, 23 | "SortableCredit": { 24 | "Sort": [0, 0], 25 | "Text": "" 26 | }, 27 | "SortableAmount": { 28 | "Sort": [1, 19.72], 29 | "Text": "$19.72 DR" 30 | }, 31 | "SortableCurrencyAmount": { 32 | "Sort": [1, 0], 33 | "Text": "" 34 | }, 35 | "Debit": { 36 | "Text": "$19.72 DR" 37 | }, 38 | "Credit": { 39 | "Text": "" 40 | }, 41 | "Amount": { 42 | "Text": "$19.72 DR" 43 | }, 44 | "Balance": { 45 | "Text": "" 46 | }, 47 | "FeeLink": { 48 | "Text": "", 49 | "Url": null, 50 | "Type": "" 51 | }, 52 | "TranCode": { 53 | "Text": "00 05" 54 | }, 55 | "ReceiptNumber": { 56 | "Text": null 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /test/moment.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | const moment = require('../src/moment'); 3 | 4 | describe('moment.js', () => { 5 | it('should contains some formats', () => { 6 | expect(moment.formats.default).toBeDefined(); 7 | expect(moment.formats.aus).toBeDefined(); 8 | expect(moment.formats.us).toBeDefined(); 9 | expect(moment.formats.sortable).toBeDefined(); 10 | }); 11 | it('should format date in right format', () => { 12 | // 2017-07-03T23:08:15+10:00 13 | const timestamp = 1499087295615; 14 | expect(moment(timestamp).format(moment.formats.default)).toEqual('03/07/2017'); 15 | expect(moment(timestamp).format(moment.formats.aus)).toEqual('03/07/17'); 16 | expect(moment(timestamp).format(moment.formats.us)).toEqual('07/03/17'); 17 | expect(moment(timestamp).format(moment.formats.sortable)).toEqual('2017-07-03'); 18 | }); 19 | it('should format date in right timezone', () => { 20 | // 2017-07-03T00:12:11+10:00 21 | const timestamp = 1499004731767; 22 | expect(moment(timestamp).format(moment.formats.default)).toEqual('03/07/2017'); 23 | expect(moment(timestamp).format(moment.formats.aus)).toEqual('03/07/17'); 24 | expect(moment(timestamp).format(moment.formats.us)).toEqual('07/03/17'); 25 | expect(moment(timestamp).format(moment.formats.sortable)).toEqual('2017-07-03'); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /test/test_cases/transaction-2.json: -------------------------------------------------------------------------------- 1 | { 2 | "Date": { 3 | "Sort": [635520384000000000, "201411200816413066111"], 4 | "Text": "20 Nov 2014" 5 | }, 6 | "MonthYear": { 7 | "Text": "112014" 8 | }, 9 | "WebSearch": null, 10 | "Description": { 11 | "Url": "/netbank/TransactionHistory/Details.aspx?ACCOUNT_PRODUCT_TYPE=DDA&IsMisa=False&_e=RG9nIGdvZXMgd29vZg0KQ2F0IGdvZXMgbWVvdw0KQmlyZCBnb2VzIHR3ZWV0DQpBbmQgbW91c2UgZ29lcyBzcXVlYWsNCkNvdyBnb2VzIG1vbw0KRnJvZyBnb2VzIGNyb2FrDQpBbmQgdGhlIGVsZXBoYW50IGdvZXMgdG9vdA%3D%3D&RID=Qs3uTcaN80GwIHC7dp31uQ&SID=M9JfKqQ0iKY%3d", 12 | "Sort": ["transfer to xx0010 commbank app", -635520384000000000], 13 | "Text": "Transfer to xx0010 CommBank app" 14 | }, 15 | "SortableDebit": { 16 | "Sort": [1, 100.00], 17 | "Text": "$100.00 DR" 18 | }, 19 | "SortableCredit": { 20 | "Sort": [0, 0], 21 | "Text": "" 22 | }, 23 | "SortableAmount": { 24 | "Sort": [1, 100.00], 25 | "Text": "$100.00 DR" 26 | }, 27 | "SortableCurrencyAmount": { 28 | "Sort": [2, 20.67], 29 | "Text": "$20.67 CR" 30 | }, 31 | "Debit": { 32 | "Text": "$100.00 DR" 33 | }, 34 | "Credit": { 35 | "Text": "" 36 | }, 37 | "Amount": { 38 | "Text": "$100.00 DR" 39 | }, 40 | "Balance": { 41 | "Text": "$20.67 CR" 42 | }, 43 | "FeeLink": { 44 | "Text": "", 45 | "Url": null, 46 | "Type": "" 47 | }, 48 | "TranCode": { 49 | "Text": "550085" 50 | }, 51 | "ReceiptNumber": { 52 | "Text": "N112044272766" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-cba-netbank", 3 | "version": "0.8.2", 4 | "description": "Unofficial Commonwealth Bank Australia Netbank API Wrapper for Node.js", 5 | "author": "Tao Wang ", 6 | "license": "Apache-2.0", 7 | "homepage": "https://github.com/twang2218/node-cba-netbank", 8 | "bugs": "https://github.com/twang2218/node-cba-netbank/issues", 9 | "main": "dist/api.js", 10 | "bin": { 11 | "cba-netbank": "dist/cli.js" 12 | }, 13 | "directories": { 14 | "lib": "./dist" 15 | }, 16 | "dependencies": { 17 | "bluebird": "^3.5.1", 18 | "chalk": "^2.3.2", 19 | "cheerio": "^0.22.0", 20 | "debug": "^3.1.0", 21 | "easy-table": "^1.1.1", 22 | "inquirer": "^5.1.0", 23 | "lodash": "^4.17.5", 24 | "moment-timezone": "^0.5.14", 25 | "mz": "^2.7.0", 26 | "ofx": "^0.4.0", 27 | "request": "^2.83.0", 28 | "request-promise": "^4.2.2", 29 | "yargs": "^11.0.0" 30 | }, 31 | "devDependencies": { 32 | "babel-cli": "^6.26.0", 33 | "babel-core": "^6.26.0", 34 | "babel-eslint": "^8.2.2", 35 | "babel-jest": "^22.4.1", 36 | "babel-preset-env": "^1.6.1", 37 | "coveralls": "^3.0.0", 38 | "eslint": "^4.18.2", 39 | "eslint-config-airbnb-base": "^12.1.0", 40 | "eslint-loader": "^2.0.0", 41 | "eslint-plugin-import": "^2.9.0", 42 | "jest": "^22.4.2", 43 | "jest-cli": "^22.4.2", 44 | "nock": "^9.2.3", 45 | "strip-ansi": "^4.0.0" 46 | }, 47 | "scripts": { 48 | "start": "node dist/cli.js", 49 | "start-debug": "DEBUG=node-cba-netbank yarn start", 50 | "build": "babel src -d dist", 51 | "eslint": "eslint src test", 52 | "prepare": "yarn build", 53 | "pretest": "yarn build && yarn eslint", 54 | "test": "jest --coverage --verbose", 55 | "test-debug": "DEBUG=node-cba-netbank yarn test -- --runInBand", 56 | "test-coveralls": "yarn test-debug && yarn coveralls", 57 | "coveralls": "cat ./coverage/lcov.info | coveralls", 58 | "clean": "rm -rf ./log/* ./coverage ./dist" 59 | }, 60 | "repository": "twang2218/node-cba-netbank", 61 | "keywords": [ 62 | "api", 63 | "bank", 64 | "financial", 65 | "netbank", 66 | "cba", 67 | "commonwealth bank australia" 68 | ] 69 | } 70 | -------------------------------------------------------------------------------- /test/render.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | const render = require('../src/render.js'); 3 | // as it's not easy to test the chalk style result across platform, so the style will not be tested. 4 | const stripAnsi = require('strip-ansi'); 5 | 6 | describe('render.js', () => { 7 | it('should parse currency', () => { 8 | expect(stripAnsi(render.currency(1))).toEqual('$1.00'); 9 | expect(stripAnsi(render.currency(-1))).toEqual('$-1.00'); 10 | expect(stripAnsi(render.currency(0.01))).toEqual('$0.01'); 11 | expect(stripAnsi(render.currency(0.333))).toEqual('$0.33'); 12 | }); 13 | it('should parse account', () => { 14 | const account = { 15 | name: 'Smart Access', 16 | bsb: '2012', 17 | account: '12345678', 18 | number: '201212345678', 19 | balance: 1234.56, 20 | available: 1034.56, 21 | }; 22 | expect(stripAnsi(render.account(account))).toEqual('Smart Access \t(2012 12345678)\t Balance: $1234.56 \t Available Funds: $1034.56'); 23 | }); 24 | it('should parse account list into table', () => { 25 | const accounts = [ 26 | { 27 | name: 'Smart Access', 28 | bsb: '2012', 29 | account: '12345678', 30 | number: '201212345678', 31 | balance: 1234.56, 32 | available: 1034.56, 33 | }, 34 | { 35 | name: 'Goal Saver', 36 | bsb: '2013', 37 | account: '76543210', 38 | number: '201376543210', 39 | balance: 2345.78, 40 | available: 2345.56, 41 | }, 42 | ]; 43 | 44 | expect(stripAnsi(render.accounts(accounts))).toEqual('Name Number Balance Available\n' + 45 | '------------ ------------- -------- ---------\n' + 46 | 'Smart Access 2012 12345678 $1234.56 $1034.56 \n' + 47 | 'Goal Saver 2013 76543210 $2345.78 $2345.56 \n'); 48 | }); 49 | it('should parse transaction list into table', () => { 50 | const transactions = [ 51 | { 52 | timestamp: 1499087295615, 53 | pending: true, 54 | description: 'PENDING - YUMCHA', 55 | amount: 123, 56 | balance: 1234.12, 57 | }, 58 | { 59 | timestamp: 1499004731767, 60 | description: 'CAFE', 61 | amount: 12.3, 62 | balance: 1234.12, 63 | }, 64 | ]; 65 | expect(stripAnsi(render.transactions(transactions))).toEqual('Time Description Amount Balance \n' + 66 | '---------------- ---------------- ------- --------\n' + 67 | '2017-07-03 23:08 PENDING - YUMCHA $123.00 \n' + 68 | '2017-07-03 00:12 CAFE $12.30 $1234.12\n'); 69 | }); 70 | }); 71 | -------------------------------------------------------------------------------- /src/web.js: -------------------------------------------------------------------------------- 1 | // Dependencies 2 | const debug = require('debug')('node-cba-netbank'); 3 | const fs = require('mz/fs'); 4 | const isString = require('lodash/isString'); 5 | const request = require('request-promise'); 6 | const truncate = require('lodash/truncate'); 7 | 8 | // Initialisation 9 | const DEFAULT_OPTION = { 10 | jar: true, 11 | followAllRedirects: true, 12 | resolveWithFullResponse: true, 13 | headers: { 14 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 15 | 'Cache-Control': 'no-cache', 16 | }, 17 | }; 18 | 19 | // Utilities 20 | function shorten(form) { 21 | const shortenForm = {}; 22 | Object.keys(form).forEach((key) => { 23 | shortenForm[key] = truncate(form[key], { length: 200 }); 24 | }); 25 | return shortenForm; 26 | } 27 | 28 | function doRequest(req, params = {}) { 29 | const sequence = Date.now(); 30 | const { partial } = params; 31 | const headers = Object.assign({}, params.headers); 32 | if (partial) { 33 | headers['X-MicrosoftAjax'] = 'Delta=true'; 34 | } 35 | const myParams = Object.assign({ method: 'GET' }, params, { headers }); 36 | 37 | if (debug.enabled) { 38 | debug(`${myParams.method} ${myParams.url.substring(0, 80)}...`); 39 | debug(`headers => ${JSON.stringify(shorten(myParams.headers))}`); 40 | if (myParams.method === 'POST') { 41 | debug(`form => ${JSON.stringify(shorten(myParams.form))}`); 42 | } 43 | fs.writeFile(`log/${sequence}-1-request.json`, JSON.stringify(shorten(myParams), null, 2)); 44 | } 45 | 46 | return req(myParams).then((response) => { 47 | if (debug.enabled) { 48 | fs.writeFile( 49 | `log/${sequence}-2-response.json`, 50 | JSON.stringify( 51 | { 52 | request: response.request, 53 | status: { 54 | code: response.statusCode, 55 | message: response.statusMessage, 56 | }, 57 | headers: response.headers, 58 | body: `${response.body.substring(0, 1000)}...`, 59 | }, 60 | null, 61 | 2, 62 | ), 63 | ); 64 | fs.writeFile(`log/${sequence}-3-response-body.html`, response.body); 65 | } 66 | return { url: response.request.href, headers: response.headers, body: response.body }; 67 | }); 68 | } 69 | 70 | class WebClient { 71 | constructor() { 72 | this.request = request.defaults(DEFAULT_OPTION); 73 | } 74 | get(params) { 75 | return isString(params) ? doRequest(this.request, { url: params }) : doRequest(this.request, params); 76 | } 77 | post(params) { 78 | return doRequest(this.request, Object.assign({ method: 'POST' }, params)); 79 | } 80 | } 81 | 82 | // Export 83 | module.exports = WebClient; 84 | -------------------------------------------------------------------------------- /test/web.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | 3 | // Dependencies 4 | const WebClient = require('../src/web'); 5 | const nock = require('nock'); 6 | 7 | // create a simple parser to use 8 | function parser(resp) { 9 | expect(resp.body).toEqual('Hello from Google!'); 10 | return Object.assign(resp, { data: resp.body.split(' ') }); 11 | } 12 | 13 | // create a simple consumer 14 | function processor(resp) { 15 | expect(resp.data).toEqual(['Hello', 'from', 'Google!']); 16 | return resp; 17 | } 18 | 19 | describe('web.js', () => { 20 | describe('- get()', () => { 21 | beforeEach(() => nock.disableNetConnect()); 22 | afterEach(() => nock.cleanAll()); 23 | 24 | test('should get a page, run parser, call back', (done) => { 25 | const commbank = nock('https://www.my.commbank.com.au').get('/').reply(200, 'Hello from Google!'); 26 | 27 | // Disable newline-per-chained-call rule as it's an open issue for now. 28 | // Ref: https://github.com/prettier/prettier/issues/1282 29 | /* eslint-disable newline-per-chained-call */ 30 | new WebClient().get('https://www.my.commbank.com.au/').then(parser).then(processor).then(() => { 31 | commbank.done(); 32 | done(); 33 | }); 34 | }); 35 | 36 | test('should raise error if request failed.', (done) => { 37 | const commbank = nock('https://www.my.commbank.com.au').get('/').replyWithError('something awful happened'); 38 | 39 | new WebClient().get('https://www.my.commbank.com.au/').then(parser).then(processor).catch((error) => { 40 | expect(error).not.toBeNull(); 41 | commbank.done(); 42 | done(); 43 | }); 44 | }); 45 | }); 46 | 47 | describe('- post()', () => { 48 | beforeEach(() => nock.disableNetConnect()); 49 | afterEach(() => nock.cleanAll()); 50 | 51 | test('should post a form, parse the page, and call back', (done) => { 52 | const commbank = nock('https://www.my.commbank.com.au') 53 | .post('/users', (body) => { 54 | expect(body.username).toEqual('johndoe'); 55 | expect(body.password).toEqual('123456'); 56 | return body.username === 'johndoe' && body.password === '123456'; 57 | }) 58 | .reply(200, 'Hello from Google!'); 59 | 60 | new WebClient() 61 | .post({ 62 | url: 'https://www.my.commbank.com.au/users', 63 | form: { 64 | username: 'johndoe', 65 | password: '123456', 66 | }, 67 | }) 68 | .then(parser) 69 | .then(processor) 70 | .then(() => { 71 | commbank.done(); 72 | done(); 73 | }); 74 | }); 75 | 76 | test('should raise error if request failed.', (done) => { 77 | const commbank = nock('https://www.my.commbank.com.au') 78 | .post('/users', (body) => { 79 | expect(body.username).toEqual('johndoe'); 80 | expect(body.password).toEqual('123456'); 81 | return body.username === 'johndoe' && body.password === '123456'; 82 | }) 83 | .replyWithError('something awful happened'); 84 | 85 | new WebClient() 86 | .post({ 87 | url: 'https://www.my.commbank.com.au/users', 88 | form: { 89 | username: 'johndoe', 90 | password: '123456', 91 | }, 92 | }) 93 | .then(parser) 94 | .then(processor) 95 | .catch((error) => { 96 | expect(error).not.toBeNull(); 97 | commbank.done(); 98 | done(); 99 | }); 100 | }); 101 | }); 102 | 103 | describe('- real world test', () => { 104 | beforeEach(() => nock.enableNetConnect()); 105 | test('www.google.com.au', (done) => { 106 | new WebClient().get('https://www.google.com.au').then((resp) => { 107 | expect(resp.body.indexOf('Google')).toBeGreaterThan(-1); 108 | done(); 109 | }); 110 | }); 111 | }); 112 | }); 113 | -------------------------------------------------------------------------------- /src/serializer.js: -------------------------------------------------------------------------------- 1 | const ofxSerializer = require('ofx'); 2 | 3 | // Dependencies 4 | const moment = require('./moment'); 5 | 6 | // Functions 7 | const csvAmount = n => (n > 0 ? `+${n.toFixed(2)}` : `${n.toFixed(2)}`); 8 | 9 | const csvTransaction = t => 10 | `${moment(t.timestamp).format(moment.formats.default)}` + 11 | `,"${csvAmount(t.amount)}"` + 12 | `,"${t.description}"` + 13 | `,"${csvAmount(t.balance)}"\r\n`; 14 | 15 | const qifTransaction = (transaction, type = 'default') => { 16 | let format; 17 | switch (type) { 18 | case 'aus': 19 | format = moment.formats.aus; 20 | break; 21 | case 'us': 22 | format = moment.formats.us; 23 | break; 24 | default: 25 | format = moment.formats.default; 26 | break; 27 | } 28 | const lline = type === 'default' ? `L${transaction.amount >= 0 ? 'DEP' : 'DEBIT'}\r\n` : ''; 29 | return ( 30 | `D${moment(transaction.timestamp).format(format)}\r\n` + 31 | `T${transaction.amount.toFixed(2)}\r\n` + 32 | `P${transaction.description}\r\n${lline}^\r\n` 33 | ); 34 | }; 35 | 36 | // Transactions Serialization 37 | const csv = transactions => transactions.map(csvTransaction).join(''); 38 | const qif = (transactions, type = 'default') => 39 | `!Type:Bank\r\n${transactions.map(transaction => qifTransaction(transaction, type)).join('')}`; 40 | const ofx = (transactions, account, from, to) => { 41 | const current = moment().format('YYYYMMDDHHmmss'); 42 | const header = { 43 | OFXHEADER: '100', 44 | DATA: 'OFXSGML', 45 | VERSION: '102', 46 | SECURITY: 'NONE', 47 | ENCODING: 'USASCII', 48 | CHARSET: '1252', 49 | COMPRESSION: 'NONE', 50 | OLDFILEUID: 'NONE', 51 | NEWFILEUID: 'NONE', 52 | }; 53 | 54 | const body = { 55 | SIGNONMSGSRSV1: { 56 | SONRS: { 57 | STATUS: { 58 | CODE: 0, 59 | SEVERITY: 'INFO', 60 | }, 61 | DTSERVER: current, 62 | LANGUAGE: 'ENG', 63 | }, 64 | }, 65 | }; 66 | 67 | // BANKTRANLIST 68 | const translist = { 69 | DTSTART: moment(from, moment.formats.default).format('YYYYMMDD000000'), 70 | DTEND: moment(to, moment.formats.default).format('YYYYMMDD000000'), 71 | STMTTRN: transactions.map(t => ({ 72 | TRNTYPE: t.amount > 0 ? 'CREDIT' : 'DEBIT', 73 | DTPOSTED: moment(t.timestamp).format('YYYYMMDD'), 74 | DTUSER: moment(t.timestamp).format('YYYYMMDD'), 75 | TRNAMT: t.amount.toFixed(2), 76 | // use timestamp as FITID if necessary to fix the OFX missing FITID issue. 77 | FITID: t.receiptnumber || t.timestamp, 78 | MEMO: t.description.replace(';', ''), 79 | })), 80 | }; 81 | 82 | if (account.type === 'DDA') { 83 | body.BANKMSGSRSV1 = { 84 | STMTTRNRS: { 85 | TRNUID: 1, 86 | STATUS: { 87 | CODE: 0, 88 | SEVERITY: 'INFO', 89 | }, 90 | STMTRS: { 91 | CURDEF: 'AUD', 92 | BANKACCTFROM: { 93 | BANKID: account.bsb, 94 | ACCTID: account.account, 95 | ACCTTYPE: 'SAVINGS', 96 | }, 97 | BANKTRANLIST: translist, 98 | LEDGERBAL: { 99 | BALAMT: account.balance, 100 | DTASOF: current, 101 | }, 102 | AVAILBAL: { 103 | BALAMT: account.available, 104 | DTASOF: current, 105 | }, 106 | }, 107 | }, 108 | }; 109 | } else { 110 | body.CREDITCARDMSGSRSV1 = { 111 | CCSTMTTRNRS: { 112 | TRNUID: 1, 113 | STATUS: { 114 | CODE: 0, 115 | SEVERITY: 'INFO', 116 | }, 117 | CCSTMTRS: { 118 | CURDEF: 'AUD', 119 | CCACCTFROM: { 120 | ACCTID: account.number, 121 | }, 122 | BANKTRANLIST: translist, 123 | LEDGERBAL: { 124 | BALAMT: account.balance, 125 | DTASOF: current, 126 | }, 127 | AVAILBAL: { 128 | BALAMT: account.available, 129 | DTASOF: current, 130 | }, 131 | }, 132 | }, 133 | }; 134 | } 135 | 136 | return ofxSerializer.serialize(header, body); 137 | }; 138 | 139 | // Exports 140 | module.exports = { 141 | csv, 142 | qif, 143 | ofx, 144 | }; 145 | -------------------------------------------------------------------------------- /src/ui.js: -------------------------------------------------------------------------------- 1 | // Dependencies 2 | const moment = require('./moment'); 3 | const API = require('./api'); 4 | const Render = require('./render'); 5 | 6 | const chalk = require('chalk'); 7 | const debug = require('debug')('node-cba-netbank'); 8 | const inquirer = require('inquirer'); 9 | 10 | // Constant 11 | const msgQuit = 'quit'; 12 | const tagQuit = chalk.red(''); 13 | 14 | /* eslint-disable class-methods-use-this */ 15 | class UI { 16 | constructor() { 17 | this.accounts = []; 18 | } 19 | 20 | start(argv) { 21 | return new Promise((resolve) => { 22 | // check given credential 23 | const questions = []; 24 | 25 | // client number 26 | if (!argv.username) { 27 | questions.push({ 28 | type: 'input', 29 | name: 'username', 30 | message: 'Client number:', 31 | validate: input => /^\d{1,8}$/.test(input), 32 | }); 33 | } 34 | 35 | // password 36 | if (!argv.password) { 37 | questions.push({ 38 | type: 'password', 39 | name: 'password', 40 | message: 'Password:', 41 | validate: input => /^[\w\d-]{4,16}$/.test(input), 42 | }); 43 | } 44 | 45 | return resolve(questions.length > 0 ? inquirer.prompt(questions) : argv); 46 | }) 47 | .then(c => this.logon(c)) 48 | .then(() => this.chooseAccountAndShowHistory(argv.months)) 49 | .catch((error) => { 50 | debug(error); 51 | console.log('Bye!'); 52 | }); 53 | } 54 | 55 | logon(credential) { 56 | this.api = new API(); 57 | console.log(`Logon as account ${credential.username} ...`); 58 | return this.api 59 | .logon(credential.username, credential.password) 60 | .catch(() => 61 | inquirer 62 | .prompt({ 63 | type: 'confirm', 64 | name: 'tryagain', 65 | message: 'Failed to logged in, try again?', 66 | }) 67 | .then((answer) => { 68 | if (answer.tryagain) { 69 | console.log(); 70 | // retry without give username/password, so user can give a new one to try. 71 | return this.start(Object.assign({}, credential, { username: '', password: '' })); 72 | } 73 | throw new Error(msgQuit); 74 | })) 75 | .then((resp) => { 76 | this.accounts = resp.accounts; 77 | return this.accounts; 78 | }); 79 | } 80 | 81 | chooseAccountAndShowHistory(months) { 82 | return this.selectAccount() 83 | .then(account => 84 | this.downloadHistoryAndShow( 85 | account, 86 | moment() 87 | .subtract(months, 'months') 88 | .format(moment.formats.default), 89 | )) 90 | .then(() => this.chooseAccountAndShowHistory(months)); 91 | } 92 | 93 | selectAccount() { 94 | return inquirer 95 | .prompt({ 96 | type: 'list', 97 | name: 'account', 98 | message: 'Which account?', 99 | choices: this.accounts.map(a => ({ name: Render.account(a), value: a })).concat([tagQuit]), 100 | }) 101 | .then((answer) => { 102 | if (answer.account === tagQuit) { 103 | throw new Error(msgQuit); 104 | } 105 | const account = this.accounts.find(v => answer.account.number === v.number); 106 | if (!account) { 107 | throw new Error(msgQuit); 108 | } 109 | debug(`selectAccount(${Render.account(answer.account)}): found account ${Render.account(account)}`); 110 | return account; 111 | }); 112 | } 113 | 114 | downloadHistory(account, from, to) { 115 | console.log(`Downloading history [${from} => ${to}] ...`); 116 | return this.api.getTransactionHistory(account, from, to); 117 | } 118 | 119 | downloadHistoryAndShow(account, from, to = moment().format(moment.formats.default)) { 120 | return this.downloadHistory(account, from, to).then((history) => { 121 | const allTransactions = history.pendings 122 | .map(t => Object.assign({}, t, { pending: true })) 123 | .concat(history.transactions); 124 | console.log(Render.transactions(allTransactions)); 125 | console.log(`Total ${history.transactions.length} transactions and ${history.pendings.length} pending transactions.`); 126 | return history; 127 | }); 128 | } 129 | } 130 | 131 | module.exports = UI; 132 | -------------------------------------------------------------------------------- /src/cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* eslint-disable no-use-before-define */ 4 | 5 | // Dependencies 6 | const serializer = require('./serializer'); 7 | const UI = require('./ui'); 8 | const render = require('./render'); 9 | 10 | const debug = require('debug')('node-cba-netbank'); 11 | const fs = require('fs'); 12 | const moment = require('./moment'); 13 | const yargs = require('yargs'); 14 | 15 | const tagAccountName = ''; 16 | const tagAccountNumber = ''; 17 | const tagFrom = ''; 18 | const tagTo = ''; 19 | const tagExt = ''; 20 | const outputFilenameTemplate = `[${tagAccountName}](${tagAccountNumber}) [${tagFrom} to ${tagTo}].${tagExt}`; 21 | 22 | const ui = new UI(); 23 | const myArgv = yargs 24 | .usage('CBA Netbank CLI\nUsage: $0 [args]') 25 | .option('u', { 26 | alias: 'username', 27 | demandOption: !process.env.NETBANK_USERNAME, 28 | default: process.env.NETBANK_USERNAME, 29 | defaultDescription: '$NETBANK_USERNAME', 30 | describe: 'client number', 31 | type: 'string', 32 | }) 33 | .option('p', { 34 | alias: 'password', 35 | demandOption: !process.env.NETBANK_PASSWORD, 36 | default: process.env.NETBANK_PASSWORD, 37 | defaultDescription: '$NETBANK_PASSWORD', 38 | describe: 'password', 39 | type: 'string', 40 | }) 41 | .command( 42 | 'list', 43 | 'List accounts', 44 | () => {}, 45 | (argv) => { 46 | debug(`Listing accounts ${JSON.stringify(argv)}...`); 47 | ui.logon(argv).then((accounts) => { 48 | console.log(render.accounts(accounts)); 49 | }); 50 | }, 51 | ) 52 | .command( 53 | 'download', 54 | 'Download transactions history for given account', 55 | { 56 | a: { 57 | alias: 'account', 58 | demandOption: true, 59 | describe: 'account name or number', 60 | type: 'string', 61 | }, 62 | f: { 63 | alias: 'from', 64 | default: moment() 65 | .subtract(3, 'months') 66 | .format(moment.formats.default), 67 | describe: 'history range from date', 68 | type: 'string', 69 | }, 70 | t: { 71 | alias: 'to', 72 | default: moment().format(moment.formats.default), 73 | describe: 'history range to date', 74 | type: 'string', 75 | }, 76 | o: { 77 | alias: 'output', 78 | default: outputFilenameTemplate, 79 | describe: 'output file name', 80 | type: 'string', 81 | }, 82 | format: { 83 | default: 'json', 84 | describe: 'the output file format', 85 | type: 'string', 86 | choices: ['json', 'csv', 'qif', 'aus.qif', 'us.qif', 'ofx'], 87 | }, 88 | }, 89 | (argv) => { 90 | debug(`Download transactions ${JSON.stringify(argv)}...`); 91 | ui.logon(argv).then((accounts) => { 92 | // matching accounts 93 | const account = accounts.find(a => a.name.toLowerCase().indexOf(argv.account.toLowerCase()) >= 0 94 | || a.number.indexOf(argv.account) >= 0); 95 | if (account) { 96 | debug(`${render.account(account)}`); 97 | ui.downloadHistory(account, argv.from, argv.to).then((history) => { 98 | console.log(`Retrieved ${history.transactions.length} transactions`); 99 | const filename = argv.output 100 | .replace(tagAccountName, account.name) 101 | .replace(tagAccountNumber, account.number) 102 | .replace(tagFrom, moment(argv.from, moment.formats.default).format(moment.formats.sortable)) 103 | .replace(tagTo, moment(argv.to, moment.formats.default).format(moment.formats.sortable)) 104 | .replace(tagExt, argv.format); 105 | console.log(`filename: ${filename}`); 106 | let content; 107 | switch (argv.format) { 108 | default: 109 | case 'json': 110 | content = JSON.stringify(history.transactions); 111 | break; 112 | case 'csv': 113 | content = serializer.csv(history.transactions); 114 | break; 115 | case 'qif': 116 | content = serializer.qif(history.transactions); 117 | break; 118 | case 'aus.qif': 119 | content = serializer.qif(history.transactions, 'aus'); 120 | break; 121 | case 'us.qif': 122 | content = serializer.qif(history.transactions, 'us'); 123 | break; 124 | case 'ofx': 125 | content = serializer.ofx(history.transactions, account, argv.from, argv.to); 126 | break; 127 | } 128 | fs.writeFile(filename, content, (error) => { 129 | if (error) { 130 | throw error; 131 | } 132 | }); 133 | }); 134 | } else { 135 | console.log(`Cannot find account matching pattern '${argv.account}'`); 136 | } 137 | }); 138 | }, 139 | ) 140 | .command( 141 | 'ui', 142 | 'Interactive user interface.', 143 | { 144 | m: { 145 | alias: 'months', 146 | default: 2, 147 | describe: 'how many months of history should be shown', 148 | type: 'number', 149 | }, 150 | }, 151 | (argv) => { 152 | debug(`UI: ${JSON.stringify(argv)}...`); 153 | ui.start(argv).catch(debug); 154 | }, 155 | ) 156 | .demandCommand(1, 'You have to tell me what to do, right?') 157 | .help().argv; 158 | 159 | debug(`argv => ${JSON.stringify(myArgv)}`); 160 | -------------------------------------------------------------------------------- /test/serializer.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | const serializer = require('../src/serializer'); 3 | const moment = require('../src/moment'); 4 | 5 | describe('serializer.js', () => { 6 | const transactions = [ 7 | { 8 | timestamp: 1499087295615, 9 | pending: true, 10 | description: 'PENDING - YUMCHA', 11 | amount: -123, 12 | balance: 0, 13 | }, 14 | { 15 | timestamp: 1499004731767, 16 | description: 'CAFE', 17 | amount: 12.3, 18 | balance: 1234.12, 19 | }, 20 | ]; 21 | 22 | const accountDDA = { 23 | name: 'Smart Access', 24 | bsb: '2012', 25 | account: '12345678', 26 | number: '201212345678', 27 | balance: 1234.56, 28 | available: 1034.56, 29 | type: 'DDA', 30 | }; 31 | 32 | const accountMCD = { 33 | name: 'Master Card', 34 | bsb: '', 35 | account: '5020012345678901', 36 | number: '5020012345678901', 37 | balance: -1234.56, 38 | available: 12345.56, 39 | type: 'MCD', 40 | }; 41 | 42 | it('should be able to serialize to CSV', () => { 43 | expect(serializer.csv(transactions)).toEqual('03/07/2017,"-123.00","PENDING - YUMCHA","0.00"\r\n03/07/2017,"+12.30","CAFE","+1234.12"\r\n'); 44 | }); 45 | it('should be able to serialize to QIF (default)', () => { 46 | expect(serializer.qif(transactions)).toEqual('!Type:Bank\r\n' + 47 | 'D03/07/2017\r\n' + 48 | 'T-123.00\r\n' + 49 | 'PPENDING - YUMCHA\r\n' + 50 | 'LDEBIT\r\n' + 51 | '^\r\n' + 52 | 'D03/07/2017\r\n' + 53 | 'T12.30\r\n' + 54 | 'PCAFE\r\n' + 55 | 'LDEP\r\n' + 56 | '^\r\n'); 57 | }); 58 | it('should be able to serialize to QIF (old Quicken AUS)', () => { 59 | expect(serializer.qif(transactions, 'aus')).toEqual('!Type:Bank\r\n' + 60 | 'D03/07/17\r\n' + 61 | 'T-123.00\r\n' + 62 | 'PPENDING - YUMCHA\r\n' + 63 | '^\r\n' + 64 | 'D03/07/17\r\n' + 65 | 'T12.30\r\n' + 66 | 'PCAFE\r\n' + 67 | '^\r\n'); 68 | }); 69 | it('should be able to serialize to QIF (old Quicken US)', () => { 70 | expect(serializer.qif(transactions, 'us')).toEqual('!Type:Bank\r\n' + 71 | 'D07/03/17\r\n' + 72 | 'T-123.00\r\n' + 73 | 'PPENDING - YUMCHA\r\n' + 74 | '^\r\n' + 75 | 'D07/03/17\r\n' + 76 | 'T12.30\r\n' + 77 | 'PCAFE\r\n' + 78 | '^\r\n'); 79 | }); 80 | it('should be able to serialize to OFX (DDA)', () => { 81 | expect(serializer.ofx(transactions, accountDDA, '01/07/2017', '05/07/2017')).toEqual('OFXHEADER:100\n' + 82 | 'DATA:OFXSGML\n' + 83 | 'VERSION:102\n' + 84 | 'SECURITY:NONE\n' + 85 | 'ENCODING:USASCII\n' + 86 | 'CHARSET:1252\n' + 87 | 'COMPRESSION:NONE\n' + 88 | 'OLDFILEUID:NONE\n' + 89 | 'NEWFILEUID:NONE\n' + 90 | '\n' + 91 | '\n' + 92 | '\n' + 93 | '\n' + 94 | '\n' + 95 | '0\n' + 96 | 'INFO\n' + 97 | '\n' + 98 | `${moment().format('YYYYMMDDHHmmss')}\n` + 99 | 'ENG\n' + 100 | '\n' + 101 | '\n' + 102 | '\n' + 103 | '\n' + 104 | '1\n' + 105 | '\n' + 106 | '0\n' + 107 | 'INFO\n' + 108 | '\n' + 109 | '\n' + 110 | 'AUD\n' + 111 | '\n' + 112 | '2012\n' + 113 | '12345678\n' + 114 | 'SAVINGS\n' + 115 | '\n' + 116 | '\n' + 117 | '20170701000000\n' + 118 | '20170705000000\n' + 119 | '\n' + 120 | 'DEBIT\n' + 121 | '20170703\n' + 122 | '20170703\n' + 123 | '-123.00\n' + 124 | '1499087295615\n' + 125 | 'PENDING - YUMCHA\n' + 126 | '\n' + 127 | '\n' + 128 | 'CREDIT\n' + 129 | '20170703\n' + 130 | '20170703\n' + 131 | '12.30\n' + 132 | '1499004731767\n' + 133 | 'CAFE\n' + 134 | '\n' + 135 | '\n' + 136 | '\n' + 137 | '1234.56\n' + 138 | `${moment().format('YYYYMMDDHHmmss')}\n` + 139 | '\n' + 140 | '\n' + 141 | '1034.56\n' + 142 | `${moment().format('YYYYMMDDHHmmss')}\n` + 143 | '\n' + 144 | '\n' + 145 | '\n' + 146 | '\n' + 147 | '\n'); 148 | }); 149 | it('should be able to serialize to OFX (CreditCard)', () => { 150 | expect(serializer.ofx(transactions, accountMCD, '01/07/2017', '05/07/2017')).toEqual('OFXHEADER:100\n' + 151 | 'DATA:OFXSGML\n' + 152 | 'VERSION:102\n' + 153 | 'SECURITY:NONE\n' + 154 | 'ENCODING:USASCII\n' + 155 | 'CHARSET:1252\n' + 156 | 'COMPRESSION:NONE\n' + 157 | 'OLDFILEUID:NONE\n' + 158 | 'NEWFILEUID:NONE\n' + 159 | '\n' + 160 | '\n' + 161 | '\n' + 162 | '\n' + 163 | '\n' + 164 | '0\n' + 165 | 'INFO\n' + 166 | '\n' + 167 | `${moment().format('YYYYMMDDHHmmss')}\n` + 168 | 'ENG\n' + 169 | '\n' + 170 | '\n' + 171 | '\n' + 172 | '\n' + 173 | '1\n' + 174 | '\n' + 175 | '0\n' + 176 | 'INFO\n' + 177 | '\n' + 178 | '\n' + 179 | 'AUD\n' + 180 | '\n' + 181 | '5020012345678901\n' + 182 | '\n' + 183 | '\n' + 184 | '20170701000000\n' + 185 | '20170705000000\n' + 186 | '\n' + 187 | 'DEBIT\n' + 188 | '20170703\n' + 189 | '20170703\n' + 190 | '-123.00\n' + 191 | '1499087295615\n' + 192 | 'PENDING - YUMCHA\n' + 193 | '\n' + 194 | '\n' + 195 | 'CREDIT\n' + 196 | '20170703\n' + 197 | '20170703\n' + 198 | '12.30\n' + 199 | '1499004731767\n' + 200 | 'CAFE\n' + 201 | '\n' + 202 | '\n' + 203 | '\n' + 204 | '-1234.56\n' + 205 | `${moment().format('YYYYMMDDHHmmss')}\n` + 206 | '\n' + 207 | '\n' + 208 | '12345.56\n' + 209 | `${moment().format('YYYYMMDDHHmmss')}\n` + 210 | '\n' + 211 | '\n' + 212 | '\n' + 213 | '\n' + 214 | '\n'); 215 | }); 216 | }); 217 | -------------------------------------------------------------------------------- /test/api.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | 3 | // Dependencies 4 | const nock = require('nock'); 5 | const path = require('path'); 6 | const API = require('../src/api'); 7 | const debug = require('debug')('node-cba-netbank'); 8 | 9 | // jasmine.DEFAULT_TIMEOUT_INTERVAL = 600000; 10 | 11 | const getFilePath = file => path.resolve(path.resolve(__dirname, 'test_cases'), file); 12 | 13 | const pages = { 14 | // logon page 15 | logon: getFilePath('01-logon-page.html'), 16 | // account list page 17 | home: getFilePath('02-home-page.html'), 18 | // history page 19 | history: getFilePath('03-history-page.html'), 20 | // history page 21 | historyPartial: getFilePath('04-history-partial.txt'), 22 | // final empty history page 23 | historyEmpty: getFilePath('05-history-empty.txt'), 24 | // transaction json - case 1 25 | transactionJson1: getFilePath('transaction-1.json'), 26 | // transaction json - case 2 27 | transactionJson2: getFilePath('transaction-2.json'), 28 | // transaction json - case 3 29 | transactionJson3: getFilePath('transaction-3.json'), 30 | }; 31 | 32 | const credential = { username: '76543210', password: 'YourPassword' }; 33 | const credentialWrong = { username: '23423423', password: 'WrongPassword' }; 34 | 35 | let isLoggedIn = false; 36 | 37 | function mockWebsite() { 38 | return ( 39 | nock('https://www.my.commbank.com.au') 40 | // Remove the query string 41 | .filteringPath(/\?.*$/g, '') 42 | // Logon page 43 | .get('/netbank/Logon/Logon.aspx') 44 | .replyWithFile(200, pages.logon) 45 | // Logon page: submit logon form with right credential 46 | .post('/netbank/Logon/Logon.aspx', (body) => { 47 | if (body.txtMyClientNumber$field === credential.username && body.txtMyPassword$field === credential.password) { 48 | isLoggedIn = true; 49 | return true; 50 | } 51 | isLoggedIn = false; 52 | return false; 53 | }) 54 | .replyWithFile(200, pages.home) 55 | // Logon page: submit logon form with wrong credential 56 | .post('/netbank/Logon/Logon.aspx') 57 | .replyWithFile(200, pages.logon) 58 | // retrieve transaction page (logged in) 59 | .get('/netbank/TransactionHistory/History.aspx') 60 | .replyWithFile(200, pages.history) 61 | // Post to search transaction 62 | .post('/netbank/TransactionHistory/History.aspx', () => isLoggedIn) 63 | .replyWithFile(200, pages.history) 64 | // get more transaction 65 | .post('/netbank/TransactionHistory/History.aspx', () => isLoggedIn) 66 | .replyWithFile(200, pages.historyPartial) 67 | // get more transaction (but no more transactions) 68 | .post('/netbank/TransactionHistory/History.aspx', () => isLoggedIn) 69 | .replyWithFile(200, pages.historyEmpty) 70 | ); 71 | } 72 | 73 | describe('api.js', () => { 74 | // start the real world testing if there is a credential file. 75 | if (process.env.NETBANK_USERNAME && process.env.NETBANK_PASSWORD) { 76 | // this.timeout(20000); 77 | 78 | beforeAll(() => { 79 | /* eslint-disable global-require,import/no-unresolved */ 80 | // Load test credential 81 | credential.username = process.env.NETBANK_USERNAME; 82 | credential.password = process.env.NETBANK_PASSWORD; 83 | // Real world testing 84 | nock.enableNetConnect(); 85 | }); 86 | 87 | describe('- logon()', () => { 88 | it( 89 | 'should be able to logon with correct credential', 90 | () => { 91 | expect.assertions(3); 92 | return expect(new API() 93 | .logon(credential.username, credential.password) 94 | .then((resp) => { 95 | expect(resp.accounts).toBeDefined(); 96 | expect(resp.accounts.length).toBeGreaterThan(1); 97 | return resp; 98 | }) 99 | .catch((err) => { 100 | debug(err); 101 | throw err; 102 | })).resolves.toBeDefined(); 103 | }, 104 | 10000, 105 | ); 106 | it( 107 | 'should failed if credential is not working', 108 | () => { 109 | expect.assertions(1); 110 | return expect(new API().logon(credentialWrong.username, credentialWrong.password)).rejects.toBeDefined(); 111 | }, 112 | 10000, 113 | ); 114 | }); 115 | 116 | describe('- getTransactionHistory()', () => { 117 | it( 118 | 'should retrieve transactions for given account', 119 | () => { 120 | expect.assertions(5); 121 | const api = new API(); 122 | return expect(api 123 | .logon(credential.username, credential.password) 124 | .then((resp) => { 125 | expect(resp.accounts).toBeDefined(); 126 | expect(resp.accounts.length).toBeGreaterThan(0); 127 | return api.getTransactionHistory(resp.accounts[0]); 128 | }) 129 | .then((resp) => { 130 | expect(resp.transactions).toBeDefined(); 131 | expect(resp.transactions.length).toBeGreaterThan(400); 132 | return resp; 133 | }) 134 | .catch((err) => { 135 | debug(err); 136 | throw err; 137 | })).resolves.toBeDefined(); 138 | }, 139 | 120000, 140 | ); 141 | }); 142 | } else { 143 | // use nock to mock the website 144 | debug('Mocking website ...'); 145 | describe('- logon()', () => { 146 | beforeEach(() => { 147 | mockWebsite(); 148 | nock.disableNetConnect(); 149 | }); 150 | afterEach(() => { 151 | nock.cleanAll(); 152 | nock.enableNetConnect(); 153 | }); 154 | 155 | it('should be able to logon with correct credential', () => { 156 | expect.assertions(3); 157 | return expect(new API() 158 | .logon(credential.username, credential.password) 159 | .then((resp) => { 160 | expect(resp.accounts).toBeDefined(); 161 | expect(resp.accounts.length).toBeGreaterThan(1); 162 | return resp; 163 | }) 164 | .catch((err) => { 165 | debug(err); 166 | throw err; 167 | })).resolves.toBeDefined(); 168 | }); 169 | it('should failed if credential is not working', () => { 170 | expect.assertions(1); 171 | return expect(new API().logon(credentialWrong.username, credentialWrong.password)).rejects.toBeDefined(); 172 | }); 173 | }); 174 | 175 | describe('- getTransactionHistory()', () => { 176 | beforeEach(() => { 177 | mockWebsite(); 178 | nock.disableNetConnect(); 179 | }); 180 | afterEach(() => { 181 | nock.cleanAll(); 182 | nock.enableNetConnect(); 183 | }); 184 | 185 | it('should retrieve transactions for given account', () => { 186 | expect.assertions(5); 187 | const api = new API(); 188 | return expect(api 189 | .logon(credential.username, credential.password) 190 | .then((resp) => { 191 | expect(resp.accounts).toBeDefined(); 192 | expect(resp.accounts.length).toEqual(4); 193 | return api.getTransactionHistory(resp.accounts[0]); 194 | }) 195 | .then((resp) => { 196 | expect(resp.transactions).toBeDefined(); 197 | expect(resp.transactions.length).toEqual(99); 198 | return resp; 199 | }) 200 | .catch((err) => { 201 | debug(err); 202 | throw err; 203 | })).resolves.toBeDefined(); 204 | }); 205 | it('should failed if error happend during the transactions page parsing', () => { 206 | expect.assertions(1); 207 | return expect(new API().logon(credentialWrong.username, credentialWrong.password)).rejects.toBeDefined(); 208 | }); 209 | }); 210 | } 211 | }); 212 | -------------------------------------------------------------------------------- /test/test_cases/05-history-empty.txt: -------------------------------------------------------------------------------- 1 | 0|updatePanel|ctl00_BodyPlaceHolder_UpdatePanelForAjax||0|hiddenField|__EVENTTARGET||0|hiddenField|__EVENTARGUMENT||17488|hiddenField|__VIEWSTATE|WW91IGtub3cgdGhlIGJlZCBmZWVscyB3YXJtZXINClNsZWVwaW5nIGhlcmUgYWxvbmUNCllvdSBrbm93IEkgZHJlYW0gaW4gY29sb3VyDQpBbmQgZG8gdGhlIHRoaW5ncyBJIHdhbnQNCg0KWW91IHRoaW5rIHlvdSBnb3QgdGhlIGJlc3Qgb2YgbWUNClRoaW5rIHlvdSd2ZSBoYWQgdGhlIGxhc3QgbGF1Z2gNCkJldCB5b3UgdGhpbmsgdGhhdCBldmVyeXRoaW5nIGdvb2QgaXMgZ29uZQ0KVGhpbmsgeW91IGxlZnQgbWUgYnJva2VuIGRvd24NClRoaW5rIHRoYXQgSSdkIGNvbWUgcnVubmluZyBiYWNrDQpCYWJ5IHlvdSBkb24ndCBrbm93IG1lLCBjYXVzZSB5b3UncmUgZGVhZCB3cm9uZw0KDQpXaGF0IGRvZXNuJ3Qga2lsbCB5b3UgbWFrZXMgeW91IHN0cm9uZ2VyDQpTdGFuZCBhIGxpdHRsZSB0YWxsZXINCkRvZXNuJ3QgbWVhbiBJJ20gbG9uZWx5IHdoZW4gSSdtIGFsb25lDQpXaGF0IGRvZXNuJ3Qga2lsbCB5b3UgbWFrZXMgYSBmaWdodGVyDQpGb290c3RlcHMgZXZlbiBsaWdodGVyDQpEb2Vzbid0IG1lYW4gSSdtIG92ZXIgY2F1c2UgeW91J3JlIGdvbmUNCg0KV2hhdCBkb2Vzbid0IGtpbGwgeW91IG1ha2VzIHlvdSBzdHJvbmdlciwgc3Ryb25nZXINCkp1c3QgbWUsIG15c2VsZiBhbmQgSQ0KV2hhdCBkb2Vzbid0IGtpbGwgeW91IG1ha2VzIHlvdSBzdHJvbmdlcg0KU3RhbmQgYSBsaXR0bGUgdGFsbGVyDQpEb2Vzbid0IG1lYW4gSSdtIGxvbmVseSB3aGVuIEknbSBhbG9uZQ0KDQpZb3UgaGVhcmQgdGhhdCBJIHdhcyBzdGFydGluZyBvdmVyIHdpdGggc29tZW9uZSBuZXcNClRoZXkgdG9sZCB5b3UgSSB3YXMgbW92aW5nIG9uIG92ZXIgeW91DQoNCllvdSBkaWRuJ3QgdGhpbmsgdGhhdCBJJ2QgY29tZSBiYWNrDQpJJ2QgY29tZSBiYWNrIHN3aW5naW5nDQpZb3UgdHJ5IHRvIGJyZWFrIG1lLCBidXQgeW91IHNlZQ0KDQpXaGF0IGRvZXNuJ3Qga2lsbCB5b3UgbWFrZXMgeW91IHN0cm9uZ2VyDQpTdGFuZCBhIGxpdHRsZSB0YWxsZXINCkRvZXNuJ3QgbWVhbiBJJ20gbG9uZWx5IHdoZW4gSSdtIGFsb25lDQpXaGF0IGRvZXNuJ3Qga2lsbCB5b3UgbWFrZXMgYSBmaWdodGVyDQpGb290c3RlcHMgZXZlbiBsaWdodGVyDQpEb2Vzbid0IG1lYW4gSSdtIG92ZXIgY2F1c2UgeW91J3JlIGdvbmUNCg0KV2hhdCBkb2Vzbid0IGtpbGwgeW91IG1ha2VzIHlvdSBzdHJvbmdlciwgc3Ryb25nZXINCkp1c3QgbWUsIG15c2VsZiBhbmQgSQ0KV2hhdCBkb2Vzbid0IGtpbGwgeW91IG1ha2VzIHlvdSBzdHJvbmdlcg0KU3RhbmQgYSBsaXR0bGUgdGFsbGVyDQpEb2Vzbid0IG1lYW4gSSdtIGxvbmVseSB3aGVuIEknbSBhbG9uZQ0KDQpUaGFua3MgdG8geW91IEkgZ290IGEgbmV3IHRoaW5nIHN0YXJ0ZWQNClRoYW5rcyB0byB5b3UgSSdtIG5vdCB0aGUgYnJva2VuLWhlYXJ0ZWQNClRoYW5rcyB0byB5b3UgSSdtIGZpbmFsbHkgdGhpbmtpbmcgYWJvdXQgbWUNCllvdSBrbm93IGluIHRoZSBlbmQgdGhlIGRheSB5b3UgbGVmdCB3YXMganVzdCBteSBiZWdpbm5pbmcNCkluIHRoZSBlbmQuLi4NCg0KV2hhdCBkb2Vzbid0IGtpbGwgeW91IG1ha2VzIHlvdSBzdHJvbmdlcg0KU3RhbmQgYSBsaXR0bGUgdGFsbGVyDQpEb2Vzbid0IG1lYW4gSSdtIGxvbmVseSB3aGVuIEknbSBhbG9uZQ0KV2hhdCBkb2Vzbid0IGtpbGwgeW91IG1ha2VzIGEgZmlnaHRlcg0KRm9vdHN0ZXBzIGV2ZW4gbGlnaHRlcg0KRG9lc24ndCBtZWFuIEknbSBvdmVyIGNhdXNlIHlvdSdyZSBnb25lDQo|8|hiddenField|__VIEWSTATEGENERATOR|241D9FF0|424|hiddenField|__EVENTVALIDATION|/wEWMgKtm/a9DgKhpdLcDwLy7PbGCQK29faxBgLZpJW6DQLrmbM/Ap/d4MMHAsafrqQJAv6ArdYIAqqkv60MArOY6LkIApv45s8KAs3jyf0IAvKaz+MPAoCAwAMCgIDcAwLrldLmDwLBqrqrBQLOxZDFCQLPxZDFCQLMxZDFCQLNxZDFCQLKxZDFCQLLxZDFCQLIxZDFCQLZxZDFCQLUmc2/DgKIk4v0BQLf2cSBCgL6sOYcAqmMidwPAsTmqvcFAojT2JoDAoqbkbQEApDHsusDApO9ydQDApijlpAJAuGSk9YBApvSgYwDAuHXsqkCArmO590DAqbgq84BAr2Du8IOAuaG7tIKAp+365QCAuX3+U4Cn/LK6wECx6ufHwLYxdOMAgK73eTDAkLoPPsQePxVPwPNwGIJ+F2k9y/I|0|asyncPostBackControlIDs|||0|postBackControlIDs|||469|updatePanelIDs||tctl00$ContentHeaderPlaceHolder$updatePanelAccount,tctl00$BodyPlaceHolder$UpdatePanelForAjax,fctl00$BodyPlaceHolder$UpdatePanelForLoading,fctl00$BodyPlaceHolder$updatePanelAccountSummary,tctl00$BodyPlaceHolder$updatePanelSearch,fctl00$BodyPlaceHolder$updatePanelResults,fctl00$InformationPlaceholder$updatePanelContactUs,fctl00$InformationPlaceholder$updatePanelIWantTo,fctl00$ToobarFooterRight$updatePanelExport,fctl00$CustomFooterContentPlaceHolder$updatePanelExport1|0|childUpdatePanelIDs|||40|panelsToRefreshIDs||ctl00$BodyPlaceHolder$UpdatePanelForAjax|2|asyncPostBackTimeout||90|295|formAction||History.aspx?ACCOUNT_PRODUCT_TYPE=DDA&DEEPLINKING_WITH_CONTEXT=True&_e=VGFrZSBteSBtaW5kIGFuZCB0YWtlIG15IHBhaW4NCkxpa2UgYW4gZW1wdHkgYm90dGxlIHRha2VzIHRoZSByYWluDQpBbmQgaGVhbC4%3D&RID=7joKD7VnnkWKNLxBhRcMOw&SID=M9JfKqQ0iKY%3d|22|pageTitle||NetBank - Transactions|195|dataItem|ctl00_BodyPlaceHolder_UpdatePanelForAjax|{"OrigEventArg":"doPostBackApiCall|LoadTransactions|{\"ClearCache\":\"false\",\"IsSorted\":false,\"ShowMore\":true,\"IsAdvancedSearch\":false,\"IsMonthSearch\":false,\"IsCompleteSearch\":false}"}|158|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/core/js/core-merge.34d5dd3768b405e80596aa625bce496a.js","rel-album":"6.4"}|169|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/core/js/instrumentation-merge.4043785f5795e2e8297bdfe0cdf60f4d.js","rel-album":"6.4"}|184|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/transactionhistory/js/online.transactionhistory.875f430afdc1a8381522a8dd61962a5d.js","rel-album":""}|45|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('Icon'); 2 | |57|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('CustomJsControls'); 3 | |493|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.TransactionHistory.GetFutureTransactions('VGFrZSBteSBtaW5kIGFuZCB0YWtlIG15IHBhaW4NCkxpa2UgYW4gZW1wdHkgYm90dGxlIHRha2VzIHRoZSByYWluDQpBbmQgaGVhbC4%3D&SID=M9JfKqQ0iKY%3d', 0) 4 | |701|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.TransactionHistory.GetAccountInfo('/netbank/AccountMaintenance/AjaxPages/AjaxAccountInfo.aspx?RID=Qs3uTcaN80GwIHC7dp31uQ&SID=M9JfKqQ0iKY%3d', 0, 'VGFrZSBteSBtaW5kIGFuZCB0YWtlIG15IHBhaW4NCkxpa2UgYW4gZW1wdHkgYm90dGxlIHRha2VzIHRoZSByYWluDQpBbmQgaGVhbC4%3D&SID=M9JfKqQ0iKY%3d","MinimumDueCopy":"This is the minimum amount you must pay by the due date and doesn\u0027t include any payments you\u0027ve already made in this statement period. The information here will be updated when your next statement is issued.","DescriptionCopy":"Transactions are displayed when we receive them from the place you made your purchase. Usually this is overnight, but depending on the merchant, can be up to five days later. Your available balance is updated as soon as you make the transaction.","PendingTransactionCopy":"These transactions are currently being processed. Some transactions may temporarily appear in both your pending transactions and transaction history (e.g. hotel deposits, overseas transactions and uncleared cheques). Your available funds will reflect any pending transactions, however they\u0027re not included in your account balance. The merchant name shown in the transaction description may change when processed.","DatesCopy":"You can search here for transactions you\u0027ve made within the last two years. For older transactions, go to \u003cstrong\u003eView accounts\u003c/strong\u003e, then \u003cstrong\u003eStatements\u003c/strong\u003e to view up to seven years of statements.","AvailableBalanceCopy":"This is the total of any additional repayments you\u0027ve made, above your required minimum, excluding any uncleared funds. Any partial repayments, weekly or fortnightly instalments will appear as part of your available redraw until your monthly repayment date. If you choose to redraw, make sure you have enough funds in your available balance to make your next required monthly minimum repayment.","IsCombineDebitCreditColumn":true,"DescriptionCopyForTMC":"Transactions are displayed when we receive them from the place you made your purchase. Usually this is overnight, but depending on the merchant, can be up to five days later. Your available balance is updated as soon as you make the transaction.","AmountsCopy":"Amounts entered here will be searched in Transaction amount and Currency used.","NewSearchPageSize":"40","AutoScrollDelay":1000});|66|scriptStartupBlock|ScriptContentNoTags|$.cbaPostback.uniqueId='ctl00$BodyPlaceHolder$UpdatePanelForAjax';|47920|scriptStartupBlock|ScriptContentNoTags|$.CbaCustomJs.registerAsyncPostbackFunction('helper.appendDataForScrolling',{"Transactions":[],"OutstandingAuthorizations":[],"More":false,"Limit":false,"Error":"","Warning":"","ShowBalanceColumn":true,"OutstandingAuthorizationsError":"","PendingTotal":"","PendingDebitTotal":"","PendingCreditTotal":"","Search":false,"MonthSearch":false,"RecentSearch":false,"IsRecentClick":false,"IsTMCProduct":false,"ShowMoreTransactions":true,"IsAutoScrollQuickSearch":null});|71|scriptStartupBlock|ScriptContentNoTags|$.CbaCustomJs.registerAsyncPostbackFunction('helper.setCurrentPage',1);|49|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('RvMaster'); 5 | |181|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/netbank/js/cba.globalsearchheader.plugin.c5906f8990a669b52d2b3762dedfff8c.js","rel-album":"R370"}|174|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/netbank/js/cba.globalsearchheader.eeb6edee019d698e9b89f13c5d09c17f.js","rel-album":"R370"}|59|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('GlobalSearchHeader'); 6 | |50|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('Watermark'); 7 | |168|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/netbank/js/mywealthlauncher.a0f57c579fefd3601d817ce169982e9b.js","rel-album":"R370"}|57|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('MyWealthLauncher'); 8 | |167|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/core/js/session_timer_panel.00f91ccc6aa53ef51ff5ce1ffb456629.js","rel-album":"6.4"}|162|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/core/js/cba.helpdialog.e1b147e3bc93f6d0fd0c80cd1690d4cf.js","rel-album":"6.4"}|50|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('CbaSelect'); 9 | |47|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('Dialog'); 10 | |52|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('ImageLoader'); 11 | |52|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('MonthPicker'); 12 | |52|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('SearchField'); 13 | |51|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('Validation'); 14 | |52|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('RadioSwitch'); 15 | |49|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('Calendar'); 16 | |49|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('Currency'); 17 | |58|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('ExpandableControl'); 18 | |166|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/netbank/js/tracking-merge.aa7f273ba6edd1381f3ed406b53d3680.js","rel-album":"R370"}|167|scriptStartupBlock|ScriptContentWithTags|{"text":"","type":"text/javascript","src":"https://static.my.commbank.com.au/static/netbank/js/marketing-merge.b30b71ecf20ce5bcf0b4d8a83c9700b9.js","rel-album":"R370"}|50|scriptStartupBlock|ScriptContentNoTags|CommBank.Online.Common.Plugins.Init('Marketing'); 19 | | 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # node-cba-netbank 2 | 3 | [![NPM version][npm-version-image]][npm-url] 4 | [![MIT License][license-image]][license-url] 5 | [![Build Status][travis-image]][travis-url] 6 | [![Dependency Status][dependency-image]][dependency-url] 7 | [![Coverage Status][coverage-image]][coverage-url] 8 | 9 | [![NPM][npm-classy-badge-image]][npm-classy-badge-url] 10 | 11 | Unofficial The Commonwealth Bank of Australia NetBank API wrap for 12 | Node.js 13 | 14 | # Usage 15 | 16 | ## CLI 17 | 18 | ### Install 19 | 20 | ```bash 21 | npm install node-cba-netbank -g 22 | ``` 23 | 24 | ### Usage 25 | 26 | ```bash 27 | $ cba-netbank --help 28 | CBA Netbank CLI 29 | Usage: cba-netbank [args] 30 | 31 | Commands: 32 | list List accounts 33 | download Download transactions history for given account 34 | ui Interactive user interface. 35 | 36 | Options: 37 | -u, --username client number [string] [required] [default: $NETBANK_USERNAME] 38 | -p, --password password [string] [required] [default: $NETBANK_PASSWORD] 39 | --help Show help [boolean] 40 | ``` 41 | 42 | There are 3 commands, `list`, `download` and `ui`. 43 | 44 | Username and password can be given via the arguments, `--username` and `--password`, as well as the environment variables, `NETBANK_USERNAME` and `NETBANK_PASSWORD`. 45 | 46 | You can use `list` command to see the account list, and use `download` command to download the transaction history in given format, there are more arguments for `download` command: 47 | 48 | ```bash 49 | $ cba-netbank download --help 50 | cba-netbank download 51 | 52 | Options: 53 | -u, --username client number [string] [required] [default: $NETBANK_USERNAME] 54 | -p, --password password [string] [required] [default: $NETBANK_PASSWORD] 55 | --help Show help [boolean] 56 | -a, --account account name or number [string] [required] 57 | -f, --from history range from date [string] [default: "03/04/2017"] 58 | -t, --to history range to date [string] [default: "03/07/2017"] 59 | -o, --output output file name 60 | [string] [default: "[]() [ to ]."] 61 | --format the output file format 62 | [string] [choices: "json", "csv", "qif", "aus.qif", "us.qif", "ofx"] [default: 63 | "json"] 64 | ``` 65 | 66 | You can use `-a` to specify which account you want to download the history from, and the value can be part of the name or account number. For example, if the account name you want to specified is `Smart Access`, then you can use `-a smart` to save some time. 67 | 68 | Currently, `JSON`, `CSV`, `QIF` and `OFX` format is supported for the transactions history export format. 69 | 70 | About the QIF format, there are several options: 71 | 72 | * `qif` is most common one, which is for `QIF(MYOB, MSMoney, or Quicken 2005 or later)`; 73 | * `aus.qif` is for some old software, such as `QIF (Quicken AUS 2004 or earlier)`; 74 | * `us.qif` is for some old software, such as `QIF (Quicken US 2004 or earlier)`. 75 | 76 | ### Interactive UI 77 | 78 | This is an UI you can just use `` and `` key to list accounts and its recent transactions. 79 | 80 | ```bash 81 | $ cba-netbank ui 82 | Logon as account 1234567 ... 83 | ? Which account? 84 | ❯ Smart Access (062001 12340001) Balance: $987.65 Available Funds: $907.65 85 | NetBank Saver (062002 12340012) Balance: $4321.01 Available Funds: $4021.00 86 | GoalSaver (062003 12340013) Balance: $32109.87 Available Funds: $32109.87 87 | Complete Access (062004 12340014) Balance: $1234.56 Available Funds: $1023.45 88 | MasterCard Platinum ( 5520123456789012) Balance: $-1234.56 Available Funds: $12345.67 89 | 90 | ``` 91 | 92 | Use `` and `` key to select an account then press ``, the recent transaction history will be downloaded and shown below. 93 | 94 | ```bash 95 | Downloading history [03/05/2017 => 03/07/2017] ... 96 | Time Description Amount Balance 97 | ---------------- ------------------------------------------------------------------------------ -------- -------- 98 | 2017-07-01 00:00 PENDING - HURSTSVILLE TONGLI S HURSTVILLE , 0701; LAST 4 CARD DIGITS 4341 $-3.09 99 | 2017-07-01 00:00 PENDING - DAMS APPLE AT THE STAT HURSTVILLE , 0701; LAST 4 CARD DIGITS 4341 $-12.37 100 | ... 101 | 2017-07-01 04:39 THE NAKED DUCK DARLING SYDNEY NS AUS; Card xx4341; Value Date: 28/06/2017 $-13.50 $909.66 102 | 2017-07-01 04:39 TOPSHOP TOPMAN SYDNE SYDNEY AUS; Card xx4341; Value Date: 30/06/2017 $-80.00 $927.16 103 | ... 104 | 2017-06-12 16:13 Cardless Cash for collection $-40.00 $1111.83 105 | 106 | Total 69 transactions and 12 pending transactions. 107 | ``` 108 | 109 | To quit the CLI, just select `` then press ``. 110 | 111 | ## Library 112 | 113 | ### Install 114 | 115 | ```bash 116 | npm install node-cba-netbank --save 117 | ``` 118 | 119 | ### List Accounts 120 | 121 | API: `netbank.logon(username, password)` 122 | 123 | * `username`: the netbank client number; 124 | * `password`: the netbank password; 125 | 126 | Returned object will contains an `accounts` field, which contains all the account information. 127 | 128 | #### Example of list accounts 129 | 130 | ```js 131 | const Netbank = require('node-cba-netbank'); 132 | 133 | const netbank = new Netbank(); 134 | 135 | netbank.logon('76543210', 'YOUR_PASSWORD') 136 | .then(resp => { 137 | // output account to console 138 | resp.accounts.forEach( 139 | a => console.log(`${a.name} (${a.bsb} ${a.account}) => ${a.balance}/${a.available}`) 140 | ); 141 | }) 142 | .catch(console.error); 143 | ``` 144 | 145 | Just replace `76543210` with your client number, and replace 146 | `YOUR_PASSWORD` with your netbank password. 147 | 148 | The result will look like below: 149 | 150 | ```js 151 | Smart Access (062001 12340001) => 987.65/907.65 152 | NetBank Saver (062002 12340012) => 4321.01/4021.00 153 | ... 154 | ``` 155 | 156 | For each account, there are following properties: 157 | 158 | * `name`: Account name; 159 | * `url`: Transaction page for the account, it will be different everytime you logged in; 160 | * `bsb`: BSB number; 161 | * `account`: Account number (without BSB part); 162 | * `number`: The entire account number, `bsb`+`account`, without space; 163 | * `balance`: Current account balance. It might be different from the available funds; 164 | * `available`: Current available funds of the account. 165 | 166 | ### Retrieve Transactions for Given Account 167 | 168 | API: `netbank.getTransactionHistory(account, from, to)` 169 | 170 | * `account`: one of the account object retrieved from the previous `.logon()` api 171 | * `from`: the begin date of the search period. format is `DD/MM/YYYY`, *[default: 6 years ago (bank may not store transactions for such long time.)]* 172 | * `to`: the end date of the search period. format is `DD/MM/YYYY`, *[default: today]* 173 | 174 | The returned object will contains following field: 175 | 176 | * `transactions`: the processed transactions; 177 | * `pendings`: the pending transactions; 178 | 179 | #### Example of retrieve transactions 180 | 181 | ```js 182 | const Netbank = require('node-cba-netbank'); 183 | 184 | const netbank = new Netbank(); 185 | 186 | netbank.logon('76543210', 'YOUR_PASSWORD') 187 | // Assume we are going to retrieve the transactions of the first account, from '1/1/2017' to today 188 | .then(resp => netbank.getTransactionHistory(resp.accounts[0], '1/1/2017')) 189 | .then((resp) => { 190 | // output transactions to console 191 | resp.transactions.forEach(t => console.log(`${t.date} ${t.description} => ${t.amount}`)); 192 | }) 193 | .catch(console.error); 194 | ``` 195 | 196 | **Be aware, it might take several minutes if there are thousands transactions.** 197 | 198 | The transaction list will look like below: 199 | 200 | ```bash 201 | 2015-04-20T00:00:00.004Z SO THAI RESTAURANT KOGARAH => -13.9 202 | 2015-04-20T00:00:00.003Z NOK NOK SYDNEY => -41.8 203 | ... 204 | ``` 205 | 206 | For each transaction object, there are following properties: 207 | 208 | * ```timestamp```: Timestamp of given transaction, it's milliseconds since epoch. Although, it might be pretty accurate for some accounts (non-credit card account), it might just be accurate at date level; 209 | * ```date```: It's human readable date format; 210 | * ```description```: Transaction description; 211 | * ```amount```: Transaction amount, negative value is DR, positive value is CR; 212 | * ```balance```: The balance of the account after the transaction happened, however, the field might be empty for some accounts, such as credit card account; 213 | * ```trancode```: It's a category code for the transaction, such as ATM, EFTPOS, cash out might be different code; 214 | * ```receiptnumber```: The receipt number for the transaction. However, I cannot found it on my real paper receipt, and the field might be missing for some accounts, such as credit card account; 215 | 216 | ### Testing 217 | 218 | Offline test can be done by simply run `yarn test`. 219 | 220 | To enable real world testing, please set environment variables `NETBANK_USERNAME` and `NETBANK_PASSWORD` to your client number and password for online banking. 221 | 222 | Then run command: 223 | 224 | ```bash 225 | yarn test 226 | ``` 227 | 228 | to have more details, you can run `yarn test-debug` for more verbose output. 229 | 230 | The test will try to login and get transactions from the first account, and if it will fail if the retrieved transactions number is less than 400. It's ok if you don't have that much transactions in the account. The purpose of checking whether it get more than 400 transactions is to check whether it can overcome the maximum transactions limits. 231 | 232 | [license-image]: http://img.shields.io/badge/license-Apache%202.0-blue.svg?style=flat 233 | [license-url]: LICENSE.txt 234 | 235 | [npm-url]: https://npmjs.org/package/node-cba-netbank 236 | [npm-version-image]: http://img.shields.io/npm/v/node-cba-netbank.svg?style=flat 237 | [npm-downloads-image]: http://img.shields.io/npm/dm/node-cba-netbank.svg?style=flat 238 | [npm-classy-badge-image]: https://nodei.co/npm/node-cba-netbank.png?downloads=true&downloadRank=true&stars=true 239 | [npm-classy-badge-url]: https://nodei.co/npm/node-cba-netbank/ 240 | 241 | [travis-url]: http://travis-ci.org/twang2218/node-cba-netbank 242 | [travis-image]: http://img.shields.io/travis/twang2218/node-cba-netbank.svg?style=flat 243 | 244 | [dependency-url]: https://gemnasium.com/twang2218/node-cba-netbank 245 | [dependency-image]: http://img.shields.io/gemnasium/twang2218/node-cba-netbank.svg 246 | 247 | [coverage-url]: https://coveralls.io/r/twang2218/node-cba-netbank 248 | [coverage-image]: http://img.shields.io/coveralls/twang2218/node-cba-netbank.svg 249 | -------------------------------------------------------------------------------- /src/parser.js: -------------------------------------------------------------------------------- 1 | // Dependencies 2 | const Promise = require('bluebird'); 3 | const cheerio = require('cheerio'); 4 | const moment = require('./moment'); 5 | const debug = require('debug')('node-cba-netbank'); 6 | const util = require('util'); 7 | 8 | // Constants 9 | const submittableSelector = 'input,select,textarea,keygen'; 10 | const rCRLF = /\r?\n/g; 11 | 12 | // Utilities 13 | // reference: https://github.com/cheeriojs/cheerio/blob/master/lib/api/forms.js 14 | // Add support for allow `disabled` and `button` input element in the serialized array. 15 | function serializeArray(element, options = { disabled: false, button: false }) { 16 | // Resolve all form elements from either forms or collections of form elements 17 | return ( 18 | element 19 | .map((i, elem) => { 20 | const $elem = cheerio(elem); 21 | if (elem.name === 'form') { 22 | return $elem.find(submittableSelector).toArray(); 23 | } 24 | return $elem.filter(submittableSelector).toArray(); 25 | }) 26 | // Verify elements have a name (`attr.name`) 27 | // and are not disabled (`:disabled`) if `options.disabled === false` 28 | // and cannot be clicked (`[type=submit]`) if `options.button === true` 29 | // are used in 'x-www-form-urlencoded' ('[type=file]') 30 | // and are either checked/don't have a checkable state 31 | // Convert each of the elements to its value(s) 32 | .filter(`[name!=""]${options.disabled ? '' : ':not(:disabled)'}:not(${ 33 | options.button ? '' : ':submit, :button, ' 34 | }:image, :reset, :file):matches([checked], :not(:checkbox, :radio))`) 35 | .map((i, elem) => { 36 | const $elem = cheerio(elem); 37 | const name = $elem.attr('name'); 38 | let value = $elem.val(); 39 | 40 | // If there is no value set (e.g. `undefined`, `null`), then default value to empty 41 | if (value == null) { 42 | value = $elem.attr('type') === 'checkbox' ? 'on' : ''; 43 | } 44 | 45 | // If we have an array of values (e.g. `