├── .babelrc ├── .eslintrc ├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE.txt ├── README.md ├── log └── .gitkeep ├── package-lock.json ├── package.json ├── src ├── api.js ├── cli.js ├── moment.js ├── parser.js ├── render.js ├── serializer.js ├── ui.js └── web.js ├── test ├── api.test.js ├── moment.test.js ├── parser.test.js ├── render.test.js ├── serializer.test.js ├── test_cases │ ├── 01-logon-page.html │ ├── 02-home-page.html │ ├── 03-history-page.html │ ├── 04-history-partial.txt │ ├── 05-history-empty.txt │ ├── transaction-1.json │ ├── transaction-2.json │ └── transaction-3.json └── web.test.js └── yarn.lock /.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 | } -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .coveralls.yml* 2 | src/ 3 | log/ 4 | docs/ 5 | .vscode/ 6 | .yarnclean 7 | .credential 8 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2015 Tao Wang 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /log/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twang2218/node-cba-netbank/7feb68bf8d2580a4f04c75c0c00bb2308a5aa31c/log/.gitkeep -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/api.js: -------------------------------------------------------------------------------- 1 | // Dependencies 2 | const debug = require('debug')('node-cba-netbank'); 3 | const moment = require('./moment'); 4 | const WebClient = require('./web'); 5 | const parser = require('./parser'); 6 | const Url = require('url'); 7 | const uniq = require('lodash/uniq'); 8 | 9 | // Constant 10 | const NETBANK_HOST = 'https://www.my.commbank.com.au'; 11 | const PATH = { 12 | LOGON: '/netbank/Logon/Logon.aspx', 13 | HOME: '/netbank/Portfolio/Home/Home.aspx?RID=:RID&SID=:SID', 14 | }; 15 | 16 | // Utilities 17 | const concat = (a, b) => uniq(a.concat(b)); 18 | 19 | // API 20 | class API { 21 | constructor() { 22 | this.web = new WebClient(); 23 | this.host = NETBANK_HOST; 24 | } 25 | logon(username, password) { 26 | this.credentials = { username, password }; 27 | // retrieve the logon page 28 | return ( 29 | this.web 30 | .get(this.getUrl(PATH.LOGON)) 31 | // Parse the page to get logon form 32 | .then(resp => this.refreshBase(resp)) 33 | .then(parser.parseForm) 34 | .then(resp => 35 | // fill the logon form and submit 36 | this.web.post({ 37 | url: this.getUrl(PATH.LOGON), 38 | form: Object.assign({}, resp.form, { 39 | txtMyClientNumber$field: this.credentials.username, 40 | txtMyPassword$field: this.credentials.password, 41 | chkRemember$field: 'on', 42 | // and make JS detector happy 43 | JS: 'E', 44 | }), 45 | })) 46 | .then(resp => this.refreshBase(resp)) 47 | // parse the home page to retrieve the accounts list 48 | .then(parser.parseHomePage) 49 | ); 50 | } 51 | 52 | // Get transaction history data for given time period. 53 | // 54 | // * `from`: Default download begin at 6 years ago. FYI, I tried 8 years 55 | // without getting any error message, however, keep in mind that bank 56 | // usually only stored 2 years transactions history data. 57 | // * `to`: Default value is today. 58 | getTransactionHistory( 59 | account, 60 | from = moment() 61 | .subtract(6, 'years') 62 | .format(moment.formats.default), 63 | to = moment().format(moment.formats.default), 64 | ) { 65 | debug(`getTransactionHistory(account: ${account.name} [${account.number}] => ${account.available})`); 66 | // retrieve post form and key for the given account 67 | return this.web 68 | .get(this.getUrl(account.link)) 69 | .then(parser.parseTransactionPage) 70 | .then(resp => this.refreshBase(resp)) 71 | .then((resp) => { 72 | const acc = Object.assign({}, account, { link: Url.parse(resp.url).path }); 73 | if (resp.accounts !== null) { 74 | acc.key = resp.accounts.find(a => a.number === account.number).key; 75 | } 76 | 77 | // if the transaction section is lazy loading, we need do a panel update 78 | // first, before the real search. 79 | if (!resp.form.ctl00$BodyPlaceHolder$radioSwitchSearchType$field$) { 80 | return this.lazyLoading(resp, acc) 81 | .then(r => this.getTransactionsByDate(r, acc, from, to)) // attach pendings 82 | .then(r => Object.assign({}, r, { pendings: resp.pendings })); 83 | } 84 | return ( 85 | this.getTransactionsByDate(resp, acc, from, to) 86 | // attach pending 87 | .then(r => Object.assign({}, r, { pendings: resp.pendings })) 88 | .then((r) => { 89 | debug(`getTransactionHistory(): Total received ${r.transactions.length} transactions.`); 90 | return r; 91 | }) 92 | ); 93 | }); 94 | } 95 | 96 | // Web API 97 | 98 | // If the search panel is lazy loading, not only the transactions data is not in 99 | // the page, the search page widget is not ready as well. So, search request will 100 | // fail. To workaround such problem, we send an update panel partial callback 101 | // first,let server side prepared the search panel and download transaction. 102 | // Then, do the real search using the information from the parital callback result. 103 | lazyLoading(response, account) { 104 | debug(`lazyLoading(account: ${account.name} [${account.number}] => ${account.available}))`); 105 | return this.web 106 | .post({ 107 | url: this.getUrl(account.link), 108 | form: Object.assign({}, response.form, { 109 | // Send partial request 110 | ctl00$ctl00: 'ctl00$BodyPlaceHolder$UpdatePanelForAjax|ctl00$BodyPlaceHolder$UpdatePanelForAjaxh', 111 | __EVENTTARGET: 'ctl00$BodyPlaceHolder$UpdatePanelForAjax', 112 | __EVENTARGUMENT: 'doPostBackApiCall|LoadRecentTransactions|false', 113 | }), 114 | partial: true, 115 | }) 116 | .then(parser.parseViewState) 117 | .then(resp => parser.parseForm(resp).catch(() => resp)) 118 | .then(resp => Object.assign({}, resp, { form: Object.assign({}, response.form, resp.form) })); 119 | } 120 | 121 | getMoreTransactions(response, account) { 122 | debug(`getMoreTransactions(account: ${account.name} [${account.number}] => ${account.available})`); 123 | const form = Object.assign({}, response.form, { 124 | // fill the form 125 | ctl00$ctl00: 'ctl00$BodyPlaceHolder$UpdatePanelForAjax|ctl00$BodyPlaceHolder$UpdatePanelForAjax', 126 | __EVENTTARGET: 'ctl00$BodyPlaceHolder$UpdatePanelForAjax', 127 | __EVENTARGUMENT: 128 | 'doPostBackApiCall|LoadTransactions|{"ClearCache":"false","IsSorted":false,"IsAdvancedSearch":true,"IsMonthSearch":false}', 129 | }); 130 | // send the request 131 | return this.web 132 | .post({ 133 | url: this.getUrl(account.link), 134 | form, 135 | partial: true, 136 | }) 137 | .then(parser.parseTransactions) 138 | .then(resp => this.refreshBase(resp)) 139 | .then((resp) => { 140 | if (!resp.more || resp.limit) { 141 | // There is no more transactions or reached the limit. 142 | return resp; 143 | } 144 | return ( 145 | this.getMoreTransactions( 146 | Object.assign({}, resp, { form }), 147 | Object.assign({}, account, { link: Url.parse(resp.url).path }), 148 | ) 149 | // concat more transactions. 150 | .then(r => Object.assign({}, r, { form, transactions: concat(resp.transactions, r.transactions) })) 151 | // Ignore the error as we have got some transactions already 152 | .catch((error) => { 153 | debug(error); 154 | return resp; 155 | }) 156 | ); 157 | }); 158 | } 159 | 160 | getTransactionsByDate(response, account, from, to) { 161 | debug(`getTransactionsByDate(account: ${account.name} [${account.number}] => ${ 162 | account.available 163 | }, from: ${from}, to: ${to})`); 164 | const form = Object.assign({}, response.form, { 165 | // fill the form 166 | ctl00$ctl00: 'ctl00$BodyPlaceHolder$updatePanelSearch|ctl00$BodyPlaceHolder$lbSearch', 167 | __EVENTTARGET: 'ctl00$BodyPlaceHolder$lbSearch', 168 | __EVENTARGUMENT: '', 169 | ctl00$BodyPlaceHolder$searchTypeField: '1', 170 | ctl00$BodyPlaceHolder$radioSwitchDateRange$field$: 'ChooseDates', 171 | ctl00$BodyPlaceHolder$dateRangeField: 'ChooseDates', 172 | ctl00$BodyPlaceHolder$fromCalTxtBox$field: from, 173 | ctl00$BodyPlaceHolder$toCalTxtBox$field: to, 174 | // Add this for partial update 175 | ctl00$BodyPlaceHolder$radioSwitchSearchType$field$: 'AllTransactions', 176 | }); 177 | 178 | return this.web 179 | .post({ 180 | url: this.getUrl(account.link), 181 | form, 182 | partial: true, 183 | }) 184 | .then(parser.parseTransactions) 185 | .then(resp => this.refreshBase(resp)) 186 | .then((resp) => { 187 | if (!resp.more || resp.limit) { 188 | // there is no more transactions or reached the limit. 189 | return resp; 190 | } 191 | // There are more transactions available. 192 | return ( 193 | this.getMoreTransactions( 194 | Object.assign({}, resp, { form }), 195 | Object.assign({}, account, { link: Url.parse(resp.url).path }), 196 | ) 197 | // concat more transactions. 198 | .then(r => Object.assign({}, r, { form, transactions: concat(resp.transactions, r.transactions) })) 199 | .then((r) => { 200 | debug(`getTransactionsByDate(): getMoreTransactions(): More => ${r.more}, Limit => ${r.limit}`); 201 | if (r.more && r.limit) { 202 | // if there are more transactions, however it reaches limit 203 | // we need to send another search request to overcome the limit. 204 | throw Object.assign(new Error('Reach transations limit'), { response: r }); 205 | } 206 | return r; 207 | }) 208 | .catch((error) => { 209 | // an error happend during load more, it means that it may have more, 210 | // however, some restriction made it stopped, so we call it again, 211 | // but this time, we use the eariliest date from the transactions 212 | // we retrieved so far as the toDate, so it might workaround this 213 | // problem. 214 | 215 | debug(error); 216 | 217 | // if there is a `response` object attached to `error` object, that means 218 | // it's just reach the limit, and contains transations. Otherwise, it don't 219 | // have the transactions, a real error, then use previous `resp` instead. 220 | const r = error.response || resp; 221 | // find the earliest date as new 'to' date. 222 | let { timestamp: earliest } = r.transactions[0]; 223 | r.transactions.forEach((t) => { 224 | if (earliest > t.timestamp) { 225 | earliest = t.timestamp; 226 | } 227 | }); 228 | const newTo = moment(earliest).format(moment.formats.default); 229 | 230 | // Call self again 231 | debug(`Call getTransactionsByDate() again with new 'to' date (${to} => ${newTo})`); 232 | return ( 233 | this.getTransactionsByDate( 234 | Object.assign({}, r, { form }), 235 | Object.assign({}, account, { link: Url.parse(r.url).path }), 236 | from, 237 | newTo, 238 | ) 239 | // concat more transactions 240 | .then(rr => Object.assign({}, rr, { form, transactions: concat(r.transactions, rr.transactions) })) 241 | .catch((err) => { 242 | // cannot call it again, but we got some transactions at least, 243 | // so, just call it a success. 244 | debug(err); 245 | debug('getTransactionsByDate(): failed to call self again to load more'); 246 | return Object.assign({}, r, { form, transactions: r.transactions }); 247 | }) 248 | ); 249 | }) 250 | ); 251 | }); 252 | } 253 | 254 | // Utilities 255 | // Return `${this.base}+${path}` 256 | getUrl(path) { 257 | return Url.resolve(this.host, path); 258 | } 259 | 260 | // Change the BASE link if it's been redirected. 261 | refreshBase(resp) { 262 | const oldLink = Url.parse(this.host); 263 | const newLink = Url.parse(resp.url); 264 | 265 | if (oldLink.host !== newLink.host) { 266 | debug(`refreshBase(${oldLink.host} => ${newLink.host}`); 267 | oldLink.host = newLink.host; 268 | this.host = Url.format(oldLink); 269 | } 270 | return resp; 271 | } 272 | } 273 | 274 | // Exports 275 | module.exports = API; 276 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. `