Compare commits

...

52 Commits

Author SHA1 Message Date
Sefa Ilkimen
314314d7f9 release v2.0.6 2019-03-11 14:20:57 +01:00
Sefa Ilkimen
a8e3637f27 Merge branch 'chrisjdev-master' 2019-03-11 14:01:37 +01:00
Sefa Ilkimen
56272b9a5d Update changelog 2019-03-11 13:59:17 +01:00
Sefa Ilkimen
8f859db57f Merge branch 'master' of https://github.com/chrisjdev/cordova-plugin-advanced-http into chrisjdev-master 2019-03-11 11:34:10 +01:00
Sefa Ilkimen
e673754b13 Test for #184 2019-03-01 18:12:46 +01:00
Sefa Ilkimen
a0f376233c Fix #187: setSSLCertMode with "default" throws an error on Android 2019-03-01 18:12:06 +01:00
Sefa Ilkimen
fcd142a70b release v2.0.5 2019-02-25 13:08:25 +01:00
Sefa Ilkimen
807400bc63 Fix #185: need more detailed SSL error message 2019-02-22 19:20:12 +01:00
Sefa Ilkimen
1fd857f1d9 release v2.0.4 2019-01-17 17:30:43 +01:00
Sefa Ilkimen
f801d2a283 Update changelog 2019-01-17 17:26:24 +01:00
Sefa Ilkimen
6033ea4b76 Fix #179: Can't send empty string with utf8 serializer 2019-01-17 17:03:12 +01:00
Sefa Ilkimen
dadbf97d0c release v2.0.3 2019-01-15 17:00:54 +01:00
Sefa Ilkimen
f06788d199 Update cordova to fix peer dependency issues 2019-01-15 16:58:00 +01:00
Sefa Ilkimen
a195de409d Fix #172: plugin does not respect user installed CA certs on Android 2018-12-23 19:00:51 +01:00
Chris J
0fade8351d Merge pull request #1 from chrisjdev/keepSessionManager
Keep AFHTTPSessionManager instance with the plugin
2018-12-20 10:49:05 -05:00
Chris J
ebd6ae9793 Keep AFHTTPSessionManager instance with the plugin
Persist the AFHTTPSessionManager instance for the life of the plugin to allow reusing the underlying sockets, for example, with "Connection: keep-alive" headers.
2018-12-20 10:47:13 -05:00
Sefa Ilkimen
49f219723d Fix test scripts for linux bash 2018-12-12 19:46:58 +01:00
Sefa Ilkimen
f1bb4f36d0 Fix android test suite 2018-12-12 15:29:27 +01:00
Sefa Ilkimen
e2a869bbd2 Running android tests based on android image instead of xcode image (travis config) 2018-12-12 15:23:05 +01:00
Sefa Ilkimen
d2f79352ae release v2.0.2 2018-12-10 18:52:43 +01:00
Sefa Ilkimen
cca1be9d91 Update android SDK and build tools 2018-12-10 18:03:11 +01:00
Sefa Ilkimen
b6d8763a18 Update cordova-android version in test app 2018-12-10 15:57:47 +01:00
Sefa Ilkimen
c70ce750ed Using Xcode 9.3 image for tests because higher versions don't include JDK v1.8 and therefore crash android builds 2018-12-10 15:54:19 +01:00
Sefa Ilkimen
54abb2ba37 Fix #170: Can't build iOS Test App with Xcode 10.1 2018-12-10 15:17:36 +01:00
Sefa Ilkimen
8d433d050f update changelog 2018-12-06 18:47:55 +01:00
Sefa Ilkimen
bf616fc6e5 Merge pull request #164 from ath0mas/patch-1
Fix argument double encoding for HttpHead
2018-12-06 18:03:16 +01:00
Alexis THOMAS
c31765bbcd Fix argument double encoding for HttpHead
To follow #157 that fixed double encoding on file download
2018-11-26 10:37:21 +01:00
Sefa Ilkimen
b5ec508c30 Merge pull request #157 from TheZopo/double-arg-encoding-fix
Fix argument double encoding on file download
2018-11-25 23:06:04 +01:00
Bastien Marsaud
6fcf4dc8eb Fix argument double encoding on file download
Disable argument encoding in get request
2018-10-18 12:33:05 +02:00
Sefa Ilkimen
f0e1522982 Fix #142: Plugin affected by REDoS Issue of tough-cookie 2018-09-04 20:27:45 +02:00
Sefa Ilkimen
c387e52ea3 release v2.0.1 2018-09-04 02:20:15 +02:00
Sefa Ilkimen
f87afa2217 - fix #136: Content-Type header not overwritable on browser platform
- remove obsolete methods "enableSSLPinning" and "acceptAllCerts"
2018-09-04 01:56:17 +02:00
Sefa Ilkimen
516aa6b61d release v2.0.0 2018-09-03 16:03:46 +02:00
Sefa Ilkimen
a6bf9041a5 add missing "updatecert" task to travis config 2018-09-03 15:25:11 +02:00
Sefa Ilkimen
c41fc11888 SSL certs must be places in "www/certificates"; project root folder is not scanned for certs anymore 2018-09-03 15:02:26 +02:00
Sefa Ilkimen
91515d30bd add test for gzipped content 2018-09-03 14:18:22 +02:00
Sefa Ilkimen
c8638ff204 exclude test certs from repository 2018-09-03 14:17:22 +02:00
Sefa Ilkimen
0acf2e2574 fix test #34 "should pin SSL cert correctly (GET)" 2018-09-03 13:52:09 +02:00
Sefa Ilkimen
f4674028b5 Merge pull request #118 from 0verrfl0w/ios-networking-indicator
Ios networking indicator
2018-07-23 15:18:45 +02:00
Florian Leitmann
5919d90698 Merge remote-tracking branch 'upstream/master' into ios-networking-indicator 2018-05-31 17:29:12 +02:00
Sefa Ilkimen
27e959800a remove deprecated AngularJS integration service 2018-05-27 20:33:02 +02:00
Sefa Ilkimen
96f45d7274 feature #103: implement HTTP SSL cert modes 2018-05-27 19:30:42 +02:00
Florian Leitmann
3dbd07c9df Merge branch 'master' into ios-networking-indicator 2018-05-27 14:01:04 +02:00
Florian Leitmann
cb597c0d30 Added SDNetworkActivityIndicator library and integrated it in plugin.xml definition as well as CordovaHttpPlugin.m
This library allows to show the network activity indicator on iOS devices, to indicate native networking
It uses a counter to hide the indicator depending on whether all request have been fulfilled or not
2018-05-27 12:45:52 +02:00
Sefa Ilkimen
60189a68b3 update httpbin.org SSL cert 2018-05-25 18:58:52 +02:00
Sefa Ilkimen
8e4bfdbc70 remove explicit host name verification setting on Android 2018-05-25 18:45:10 +02:00
Sefa Ilkimen
2ae4c7cf39 refactor cert handling for Android (preparing for v2 changes) 2018-04-11 03:24:27 +02:00
Sefa Ilkimen
32fdf49d31 fix misleading examples in README 2018-04-08 23:59:11 +02:00
Sefa Ilkimen
db0f233737 update README (missing url property in callback signature) 2018-03-21 22:35:31 +01:00
Sefa Ilkimen
2263950de9 release v1.11.1 2018-03-21 13:18:57 +01:00
Sefa Ilkimen
2a9d3296cc update httpbin.org SSL cert 2018-03-21 12:56:11 +01:00
Sefa Ilkimen
55dd751cec fix #92: headers not deserialized on platform "browser" 2018-03-16 03:04:03 +01:00
43 changed files with 8621 additions and 1765 deletions

1
.gitignore vendored
View File

@@ -1,4 +1,5 @@
node_modules/**
test/app-template/www/certificates/*.cer
tags
.zedstate
npm-debug.log

View File

@@ -1,12 +1,6 @@
sudo: false
language: objective-c
os: osx
osx_image: xcode9.1
env:
- TARGET_PLATFORM=android
- TARGET_PLATFORM=ios
notifications:
slack:
secure: lXE+2AgsxZU5G5dI91LkMAIgo8MAWfdM7DB5UOtn5LpuNln+2FmJo1gOI7tkdmLOqpXTGYnpI2VyQN3H4nOF21YhuouzD1Sh8n2wtQg1iTm353kuQpqiVhSBX8ZJ7Be1e1G8OsnxoYOxbs4Zo9qI40EruwkvqLCBHWM5MRGyd4M7EFWwb9Z29VZN0y1Nt5g/c3bT76kdKmF+JCLur2OeEKxAity7sIKgZekSqeIMwEVLSxXnda6Dbjc/cg0MJ0iDArkD7iu6fz/Fcrrxgm/pUxjcgvqze7Gy5i31mjEfspnrglWV1cshMd48BTDKCJ2AMmxH8O3GPSWE2txjIvGRWUve7iViNylvmQCVz3Eyf99+4EuuVGa+5PSodQ/CqODx/65EwtcN3PE1tNz2puKOK8nrOJcFkcbG8KTHKUlQtHCkjitbykUnj/hvhLK5/oWlQYVOLWWrHwdGUh8FI8aFPVGjRjWbHbhdayjEIqxwr1ns+6mYrP1EFNXbaeZxnLNC59XpJl1ifuezqYAk7YEiU5j4rtC7YKgyQ3ueb7anOHTJoTMyDn8mpZXgwuyhoBaeEYytQVgRyMtL6Y5cP98Jn2kv0+vdne3rkk9/JEBTo32HOjvoij6rsqEvXC0LhUDJSNadOVdHht0jjoN6zBH37HIE5/3zysLlPcAcHAS83ow=
cache:
directories:
@@ -15,29 +9,51 @@ cache:
addons:
sauce_connect: true
before_install:
- export LANG=en_US.UTF-8
matrix:
include:
- name: "iOS Build & Test"
language: objective-c
sudo: false
os: osx
osx_image: xcode10.1
install:
- npm install
- if [ $TARGET_PLATFORM = "android" ]; then
brew update &&
brew install gradle &&
scripts/setup-android-sdk.sh &&
export ANDROID_HOME=$(pwd)/android-sdk-macosx &&
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$ANDROID_HOME/build-tools/23.0.2;
fi
before_install:
- export LANG=en_US.UTF-8
script:
- npm run testjs
- travis_wait scripts/build-test-app.sh --$TARGET_PLATFORM --emulator &&
scripts/upload-artifact.sh --$TARGET_PLATFORM &&
scripts/test-app.sh --$TARGET_PLATFORM --emulator;
install:
- npm install
after_success:
script:
- npm run testjs &&
npm run updatecert &&
scripts/build-test-app.sh --ios --emulator &&
scripts/upload-artifact.sh --ios &&
scripts/test-app.sh --ios --emulator;
deploy:
- name: "Android Build & Test"
language: android
sudo : required
notifications:
slack:
secure: lXE+2AgsxZU5G5dI91LkMAIgo8MAWfdM7DB5UOtn5LpuNln+2FmJo1gOI7tkdmLOqpXTGYnpI2VyQN3H4nOF21YhuouzD1Sh8n2wtQg1iTm353kuQpqiVhSBX8ZJ7Be1e1G8OsnxoYOxbs4Zo9qI40EruwkvqLCBHWM5MRGyd4M7EFWwb9Z29VZN0y1Nt5g/c3bT76kdKmF+JCLur2OeEKxAity7sIKgZekSqeIMwEVLSxXnda6Dbjc/cg0MJ0iDArkD7iu6fz/Fcrrxgm/pUxjcgvqze7Gy5i31mjEfspnrglWV1cshMd48BTDKCJ2AMmxH8O3GPSWE2txjIvGRWUve7iViNylvmQCVz3Eyf99+4EuuVGa+5PSodQ/CqODx/65EwtcN3PE1tNz2puKOK8nrOJcFkcbG8KTHKUlQtHCkjitbykUnj/hvhLK5/oWlQYVOLWWrHwdGUh8FI8aFPVGjRjWbHbhdayjEIqxwr1ns+6mYrP1EFNXbaeZxnLNC59XpJl1ifuezqYAk7YEiU5j4rtC7YKgyQ3ueb7anOHTJoTMyDn8mpZXgwuyhoBaeEYytQVgRyMtL6Y5cP98Jn2kv0+vdne3rkk9/JEBTo32HOjvoij6rsqEvXC0LhUDJSNadOVdHht0jjoN6zBH37HIE5/3zysLlPcAcHAS83ow=
android:
components:
- platform-tools
- build-tools-28.0.3
- android-27
- extra-android-support
- extra-android-m2repository
- extra-google-m2repository
before_install:
- export LANG=en_US.UTF-8 &&
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - &&
sudo apt-get install -y nodejs
install:
- npm install
script:
- npm run testjs &&
npm run updatecert &&
scripts/build-test-app.sh --android --emulator &&
scripts/upload-artifact.sh --android &&
scripts/test-app.sh --android --emulator;

View File

@@ -1,5 +1,48 @@
# Changelog
## 2.0.6
- Fixed #187: setSSLCertMode with "default" throws an error on Android
- Fixed #115: HTTP connections are not kept alive on iOS (thanks MorpheusDe97)
## 2.0.5
- Fixed #185: need more detailed SSL error message
## 2.0.4
- Fixed #179: sending empty string with utf8 serializer throws an exception
## 2.0.3
- Fixed #172: plugin does not respect user installed CA certs on Android
#### Important information
We've changed a default behavior on Android. User installed CA certs are respected now.
If you don't want this for your needs, you can switch back to old behavior by setting SSL cert mode to `legacy`.
## 2.0.2
- Fixed #142: Plugin affected by REDoS Issue of tough-cookie
- Fixed #157: Arguments are double URL-encoded on "downloadFile" (thanks TheZopo)
- Fixed #164: Arguments are double URL-encoded on "head" (thanks ath0mas)
## 2.0.1
- Fixed #136: Content-Type header non-overwritable on browser platform
## 2.0.0
- Feature #103: implement HTTP SSL cert modes
- :warning: **Breaking Change**: Removed AngularJS (v1) integration service
- :warning: **Breaking Change**: Removed "enableSSLPinning" and "acceptAllCerts", use "setSSLCertMode" instead
- :warning: **Breaking Change**: Certificates must be placed in "www/certificates" folder
## 1.11.1
- Fixed #92: headers not deserialized on platform "browser"
## 1.11.0
- Feature #77: allow overriding global settings for each single request

View File

@@ -41,19 +41,6 @@ This plugin registers a global object located at `cordova.plugin.http`.
Check the [Ionic docs](https://ionicframework.com/docs/native/http/) for how to use this plugin with Ionic-native.
### With AngularJS (Deprecated)
:warning: *This feature is deprecated and will be removed anytime soon.* :warning:
This plugin creates a cordovaHTTP service inside of a cordovaHTTP module. You must load the module when you create your app's module.
```js
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'cordovaHTTP']);
```
You can then inject the cordovaHTTP service into your controllers. The functions can then be used identically to the examples shown below except that instead of accepting success and failure callback functions, each function returns a promise. For more information on promises in AngularJS read the [AngularJS docs](http://docs.angularjs.org/api/ng/service/$q). For more info on promises in general check out this article on [html5rocks](http://www.html5rocks.com/en/tutorials/es6/promises/). Make sure that you load cordova.js or phonegap.js after AngularJS is loaded.
## Synchronous Functions
### getBasicAuthHeader
@@ -141,31 +128,46 @@ cordova.plugin.http.clearCookies();
## Asynchronous Functions
These functions all take success and error callbacks as their last 2 arguments.
### enableSSLPinning
Enable or disable SSL pinning. This defaults to false.
### setSSLCertMode<a name="setSSLCertMode"></a>
Set SSL Cert handling mode, being one of the following values:
To use SSL pinning you must include at least one .cer SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. For ios include your certificate in the root level of your bundle (just add the .cer file to your project/target at the root level). For android include your certificate in your project's platforms/android/assets folder. In both cases all .cer files found will be loaded automatically. If you only have a .pem certificate see this [stackoverflow answer](http://stackoverflow.com/a/16583429/3182729). You want to convert it to a DER encoded certificate with a .cer extension.
* `default`: default SSL cert handling using system's CA certs
* `legacy`: use legacy default behavior (< 2.0.3), excluding user installed CA certs (only for Android)
* `nocheck`: disable SSL cert checking, trusting all certs (meant to be used only for testing purposes)
* `pinned`: trust only provided certs
As an alternative, you can store your .cer files in the www/certificates folder.
To use SSL pinning you must include at least one `.cer` SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. Include your certificate in the `www/certificates` folder. All `.cer` files found there will be loaded automatically.
:warning: Your certificate must be DER encoded! If you only have a PEM encoded certificate read this [stackoverflow answer](http://stackoverflow.com/a/16583429/3182729). You want to convert it to a DER encoded certificate with a .cer extension.
```js
cordova.plugin.http.enableSSLPinning(true, function() {
// enable SSL pinning
cordova.plugin.http.setSSLCertMode('pinned', function() {
console.log('success!');
}, function() {
console.log('error :(');
});
// use system's default CA certs
cordova.plugin.http.setSSLCertMode('default', function() {
console.log('success!');
}, function() {
console.log('error :(');
});
// disable SSL cert checking, only meant for testing purposes, do NOT use in production!
cordova.plugin.http.setSSLCertMode('nocheck', function() {
console.log('success!');
}, function() {
console.log('error :(');
});
```
### acceptAllCerts
Accept all SSL certificates. Or disable accepting all certificates. This defaults to false.
### enableSSLPinning (obsolete)
This function was removed in 2.0.0. Use ["setSSLCertMode"](#setSSLCertMode) to enable SSL pinning (mode "pinned").
```js
cordova.plugin.http.acceptAllCerts(true, function() {
console.log('success!');
}, function() {
console.log('error :(');
});
```
### acceptAllCerts (obsolete)
This function was removed in 2.0.0. Use ["setSSLCertMode"](#setSSLCertMode) to disable checking certs (mode "nocheck").
### disableRedirect
If set to `true`, it won't follow redirects automatically. This defaults to false.
@@ -178,8 +180,8 @@ cordova.plugin.http.disableRedirect(true, function() {
});
```
### validateDomainName
This function was removed in v1.6.2. Domain name validation is disabled automatically when you enable "acceptAllCerts".
### validateDomainName (obsolete)
This function was removed in v1.6.2. Domain name validation is disabled automatically when you set SSL cert mode to "nocheck".
### removeCookies
Remove all cookies associated with a given URL.
@@ -228,7 +230,7 @@ cordova.plugin.http.sendRequest('https://google.com/', options, function(respons
Execute a POST request. Takes a URL, data, and headers.
#### success
The success function receives a response object with 3 properties: status, data, and headers. **status** is the HTTP response code as numeric value. **data** is the response from the server as a string. **headers** is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The success function receives a response object with 4 properties: status, data, url, and headers. **status** is the HTTP response code as numeric value. **data** is the response from the server as a string. **url** is the final URL obtained after any redirects as a string. **headers** is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
Here's a quick example:
@@ -236,6 +238,7 @@ Here's a quick example:
{
status: 200,
data: '{"id": 12, "message": "test"}',
url: 'http://example.net/rest'
headers: {
'content-length': '247'
}
@@ -268,7 +271,7 @@ cordova.plugin.http.post('https://google.com/', {
```
#### failure
The error function receives a response object with 3 properties: status, error and headers. **status** is the HTTP response code as numeric value. **error** is the error response from the server as a string. **headers** is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The error function receives a response object with 4 properties: status, error, url, and headers (url and headers being optional). **status** is the HTTP response code as numeric value. **error** is the error response from the server as a string. **url** is the final URL obtained after any redirects as a string. **headers** is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
Here's a quick example:
@@ -276,6 +279,7 @@ Here's a quick example:
{
status: 403,
error: 'Permission denied',
url: 'http://example.net/noperm'
headers: {
'content-length': '247'
}
@@ -287,7 +291,7 @@ Execute a GET request. Takes a URL, parameters, and headers. See the [post](#p
```js
cordova.plugin.http.get('https://google.com/', {
id: 12,
id: '12',
message: 'test'
}, { Authorization: 'OAuth2: token' }, function(response) {
console.log(response.status);
@@ -313,7 +317,7 @@ Uploads a file saved on the device. Takes a URL, parameters, headers, filePath,
```js
cordova.plugin.http.uploadFile("https://google.com/", {
id: 12,
id: '12',
message: 'test'
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', 'picture', function(response) {
console.log(response.status);
@@ -327,7 +331,7 @@ Downloads a file and saves it to the device. Takes a URL, parameters, headers,
```js
cordova.plugin.http.downloadFile("https://google.com/", {
id: 12,
id: '12',
message: 'test'
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry) {
// prints the filename

6345
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,12 @@
{
"name": "cordova-plugin-advanced-http",
"version": "1.11.0",
"version": "2.0.6",
"description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
"scripts": {
"updatecert": "node ./scripts/update-test-cert.js",
"buildbrowser": "./scripts/build-test-app.sh --browser",
"testandroid": "./scripts/build-test-app.sh --android --emulator && ./scripts/test-app.sh --android --emulator",
"testios": "./scripts/build-test-app.sh --ios --emulator && ./scripts/test-app.sh --ios --emulator",
"testandroid": "npm run updatecert && ./scripts/build-test-app.sh --android --emulator && ./scripts/test-app.sh --android --emulator",
"testios": "npm run updatecert && ./scripts/build-test-app.sh --ios --emulator && ./scripts/test-app.sh --ios --emulator",
"testapp": "npm run testandroid && npm run testios",
"testjs": "mocha ./test/js-mocha-specs.js",
"test": "npm run testjs && npm run testapp",
@@ -58,11 +59,11 @@
"chai": "4.1.2",
"chai-as-promised": "7.1.1",
"colors": "1.1.2",
"cordova": "7.1.0",
"cordova": "8.1.2",
"mocha": "4.0.0",
"mock-require": "2.0.2",
"mz": "2.7.0",
"umd-tough-cookie": "2.3.2",
"umd-tough-cookie": "2.4.3",
"wd": "1.4.1",
"xml2js": "0.4.19"
}

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-advanced-http" version="1.11.0">
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-advanced-http" version="2.0.6">
<name>Advanced HTTP plugin</name>
<description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
@@ -13,7 +13,6 @@
<js-module src="www/messages.js" name="messages"/>
<js-module src="www/local-storage-store.js" name="local-storage-store"/>
<js-module src="www/cookie-handler.js" name="cookie-handler"/>
<js-module src="www/angular-integration.js" name="angular-integration"/>
<js-module src="www/helpers.js" name="helpers"/>
<js-module src="www/advanced-http.js" name="http">
<clobbers target="cordova.plugin.http"/>
@@ -34,6 +33,7 @@
<header-file src="src/ios/AFNetworking/AFURLRequestSerialization.h"/>
<header-file src="src/ios/AFNetworking/AFURLResponseSerialization.h"/>
<header-file src="src/ios/AFNetworking/AFURLSessionManager.h"/>
<header-file src="src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.h"/>
<source-file src="src/ios/CordovaHttpPlugin.m"/>
<source-file src="src/ios/TextResponseSerializer.m"/>
<source-file src="src/ios/TextRequestSerializer.m"/>
@@ -43,6 +43,7 @@
<source-file src="src/ios/AFNetworking/AFURLRequestSerialization.m"/>
<source-file src="src/ios/AFNetworking/AFURLResponseSerialization.m"/>
<source-file src="src/ios/AFNetworking/AFURLSessionManager.m"/>
<source-file src="src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.m"/>
<framework src="Security.framework"/>
<framework src="SystemConfiguration.framework"/>
</platform>

View File

@@ -1,7 +1,8 @@
#!/usr/bin/env bash
set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd ..; pwd )"
WORKINGCOPY=$ROOT/temp/workingcopy
CDV=$ROOT/node_modules/.bin/cordova
PLATFORM=ios
@@ -36,9 +37,10 @@ done
rm -rf $ROOT/temp
mkdir $ROOT/temp
cp -r $ROOT/test/app-template/ $ROOT/temp/
cp -r $ROOT/test/app-template/. $ROOT/temp/
cp $ROOT/test/app-test-definitions.js $ROOT/temp/www/
rsync -ax --exclude node_modules --exclude scripts --exclude temp --exclude test $ROOT/. $WORKINGCOPY
cd $ROOT/temp
$CDV prepare
$CDV plugins add $ROOT
$CDV build $PLATFORM --$TARGET
$CDV plugins add $WORKINGCOPY
$CDV build $PLATFORM --$TARGET --buildConfig build.json

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd ..; pwd )"
pushd $ROOT
VERSION=$(node -e "console.log(require('./package.json').version)")

View File

@@ -1,12 +1,19 @@
#!/usr/bin/env bash
set -e
while getopts a:b: option; do
case "${option}" in
a) API_LEVEL=${OPTARG};;
b) BUILD_TOOLS_VERSION=${OPTARG};;
esac
done
curl http://dl.google.com/android/android-sdk_r24.4-macosx.zip -o android-sdk-macosx.zip
tar -xvf android-sdk-macosx.zip
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter platform-tools
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter build-tools-25.0.0
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter android-25
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter build-tools-${BUILD_TOOLS_VERSION}
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter android-${API_LEVEL}
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter extra-android-support
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter extra-android-m2repository
echo y | ./android-sdk-macosx/tools/android update sdk --no-ui --all --filter extra-google-m2repository

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd ..; pwd )"
if [ $CI == "true" ] && ([ -z $SAUCE_USERNAME ] || [ -z $SAUCE_ACCESS_KEY ]); then
echo "Skipping CI tests, because Saucelabs credentials are not set.";

View File

@@ -0,0 +1,42 @@
const fs = require('fs');
const https = require('https');
const path = require('path');
const SOURCE_HOST = 'httpbin.org';
const TARGET_PATH = path.join(__dirname, '../test/app-template/www/certificates/httpbin.org.cer');
const getCert = hostname => new Promise((resolve, reject) => {
const options = {
hostname,
agent: false,
rejectUnauthorized: false,
ciphers: 'ALL'
};
const req = https.get(options, response => {
const certificate = response.socket.getPeerCertificate();
if (certificate === null) {
return reject({ message: 'The website did not provide a certificate' });
}
resolve(certificate);
});
req.on('error', error => {
return reject(error)
});
req.end();
});
console.log(`Updating test certificate from ${SOURCE_HOST}`);
getCert(SOURCE_HOST)
.then(cert => {
fs.writeFileSync(TARGET_PATH, cert.raw);
})
.catch(error => {
console.error(`Updating test cert failed: ${error}`);
process.exit(1);
});

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd ..; pwd )"
cd $ROOT
npm i

View File

@@ -2,7 +2,7 @@
set -e
PLATFORM=$([[ "${@#--android}" = "$@" ]] && echo "ios" || echo "android")
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd ..; pwd )"
TEMP=$ROOT/temp
if [ -z $SAUCE_USERNAME ] || [ -z $SAUCE_ACCESS_KEY ]; then
@@ -15,7 +15,7 @@ if [ $PLATFORM = "android" ]; then
-X POST \
-H "Content-Type: application/octet-stream" \
https://saucelabs.com/rest/v1/storage/$SAUCE_USERNAME/HttpDemo.apk?overwrite=true \
--data-binary @$TEMP/platforms/android/build/outputs/apk/android-debug.apk
--data-binary @$TEMP/platforms/android/app/build/outputs/apk/debug/app-debug.apk
else
rm -rf $TEMP/HttpDemo.app.zip
pushd $TEMP/platforms/ios/build/emulator

View File

@@ -263,6 +263,12 @@ public class HttpRequest {
*/
public static final String PARAM_CHARSET = "charset";
public static final String CERT_MODE_DEFAULT = "default";
public static final String CERT_MODE_PINNED = "pinned";
public static final String CERT_MODE_TRUSTALL = "trustall";
private static final String BOUNDARY = "00content0boundary00";
private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary="
@@ -272,13 +278,13 @@ public class HttpRequest {
private static final String[] EMPTY_STRINGS = new String[0];
private static SSLSocketFactory PINNED_FACTORY;
private static SSLSocketFactory SOCKET_FACTORY;
private static SSLSocketFactory TRUSTED_FACTORY;
private static String CURRENT_CERT_MODE = CERT_MODE_DEFAULT;
private static ArrayList<Certificate> PINNED_CERTS;
private static HostnameVerifier TRUSTED_VERIFIER;
private static HostnameVerifier HOSTNAME_VERIFIER;
private static String getValidCharset(final String charset) {
if (charset != null && charset.length() > 0)
@@ -287,63 +293,97 @@ public class HttpRequest {
return CHARSET_UTF8;
}
private static SSLSocketFactory getPinnedFactory()
throws HttpRequestException {
if (PINNED_FACTORY != null) {
return PINNED_FACTORY;
} else {
IOException e = new IOException("You must add at least 1 certificate in order to pin to certificates");
throw new HttpRequestException(e);
/**
* Configure SSL cert handling for all future HTTPS connections
*
* @param mode
*/
public static void setSSLCertMode(String mode) {
try {
if (mode == CERT_MODE_TRUSTALL) {
SOCKET_FACTORY = createSocketFactory(getNoopTrustManagers());
HOSTNAME_VERIFIER = getTrustedVerifier();
} else if (mode == CERT_MODE_PINNED) {
SOCKET_FACTORY = createSocketFactory(getPinnedTrustManagers());
HOSTNAME_VERIFIER = null;
} else {
SOCKET_FACTORY = null;
HOSTNAME_VERIFIER = null;
}
CURRENT_CERT_MODE = mode;
} catch(IOException e) {
throw new HttpRequestException(e);
}
}
private static SSLSocketFactory getTrustedFactory()
throws HttpRequestException {
if (TRUSTED_FACTORY == null) {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
} };
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom());
if (android.os.Build.VERSION.SDK_INT < 20) {
TRUSTED_FACTORY = new TLSSocketFactory(context);
} else {
TRUSTED_FACTORY = context.getSocketFactory();
}
} catch (GeneralSecurityException e) {
IOException ioException = new IOException(
"Security exception configuring SSL context");
ioException.initCause(e);
throw new HttpRequestException(ioException);
}
private static TrustManager[] getPinnedTrustManagers() throws IOException {
if (PINNED_CERTS == null) {
throw new IOException("You must add at least 1 certificate in order to pin to certificates");
}
return TRUSTED_FACTORY;
try {
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
for (int i = 0; i < PINNED_CERTS.size(); i++) {
keyStore.setCertificateEntry("CA" + i, PINNED_CERTS.get(i));
}
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
return tmf.getTrustManagers();
} catch (GeneralSecurityException e) {
IOException ioException = new IOException("Security exception configuring SSL trust managers");
ioException.initCause(e);
throw new HttpRequestException(ioException);
}
}
private static TrustManager[] getNoopTrustManagers() {
return new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
}};
}
private static SSLSocketFactory createSocketFactory(TrustManager[] trustManagers)
throws HttpRequestException {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, new SecureRandom());
if (android.os.Build.VERSION.SDK_INT < 20) {
return new TLSSocketFactory(context);
} else {
return context.getSocketFactory();
}
} catch (GeneralSecurityException e) {
IOException ioException = new IOException("Security exception configuring SSL context");
ioException.initCause(e);
throw new HttpRequestException(ioException);
}
}
private static HostnameVerifier getTrustedVerifier() {
if (TRUSTED_VERIFIER == null)
TRUSTED_VERIFIER = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
return TRUSTED_VERIFIER;
return new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}
private static StringBuilder addPathSeparator(final String baseUrl,
@@ -453,32 +493,15 @@ public class HttpRequest {
* @throws IOException
*/
public static void addCert(Certificate ca) throws GeneralSecurityException, IOException {
if (PINNED_CERTS == null) {
PINNED_CERTS = new ArrayList<Certificate>();
}
PINNED_CERTS.add(ca);
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
if (PINNED_CERTS == null) {
PINNED_CERTS = new ArrayList<Certificate>();
}
for (int i = 0; i < PINNED_CERTS.size(); i++) {
keyStore.setCertificateEntry("CA" + i, PINNED_CERTS.get(i));
}
PINNED_CERTS.add(ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
if (android.os.Build.VERSION.SDK_INT < 20) {
PINNED_FACTORY = new TLSSocketFactory(sslContext);
} else {
PINNED_FACTORY = sslContext.getSocketFactory();
}
if (CURRENT_CERT_MODE == CERT_MODE_PINNED) {
SOCKET_FACTORY = createSocketFactory(getPinnedTrustManagers());
}
}
/**
@@ -500,6 +523,13 @@ public class HttpRequest {
}
}
/**
* Clear certs which were added to test against when using ssl pinning.
*/
public static void clearCerts() {
PINNED_CERTS = null;
}
/**
* Callback interface for reporting upload progress for a request.
*/
@@ -1632,6 +1662,7 @@ public class HttpRequest {
throw new HttpRequestException(e);
}
this.requestMethod = method;
this.setupSecurity();
}
/**
@@ -1645,6 +1676,23 @@ public class HttpRequest {
throws HttpRequestException {
this.url = url;
this.requestMethod = method;
this.setupSecurity();
}
private void setupSecurity() {
final HttpURLConnection connection = getConnection();
if (!(connection instanceof HttpsURLConnection)) {
return;
}
if (SOCKET_FACTORY != null) {
((HttpsURLConnection) connection).setSSLSocketFactory(SOCKET_FACTORY);
}
if (HOSTNAME_VERIFIER != null) {
((HttpsURLConnection) connection).setHostnameVerifier(HOSTNAME_VERIFIER);
}
}
private Proxy createProxy() {
@@ -3351,58 +3399,6 @@ public class HttpRequest {
return this;
}
/**
* Configure HTTPS connection to trust only certain certificates
* <p>
* This method throws an exception if the current request is not a HTTPS request
*
* @return this request
* @throws HttpRequestException
*/
public HttpRequest pinToCerts() throws HttpRequestException {
final HttpURLConnection connection = getConnection();
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setSSLSocketFactory(getPinnedFactory());
} else {
IOException e = new IOException("You must use a https url to use ssl pinning");
throw new HttpRequestException(e);
}
return this;
}
/**
* Configure HTTPS connection to trust all certificates
* <p>
* This method does nothing if the current request is not a HTTPS request
*
* @return this request
* @throws HttpRequestException
*/
public HttpRequest trustAllCerts() throws HttpRequestException {
final HttpURLConnection connection = getConnection();
if (connection instanceof HttpsURLConnection)
((HttpsURLConnection) connection)
.setSSLSocketFactory(getTrustedFactory());
return this;
}
/**
* Configure HTTPS connection to trust all hosts using a custom
* {@link HostnameVerifier} that always returns <code>true</code> for each
* host verified
* <p>
* This method does nothing if the current request is not a HTTPS request
*
* @return this request
*/
public HttpRequest trustAllHosts() {
final HttpURLConnection connection = getConnection();
if (connection instanceof HttpsURLConnection)
((HttpsURLConnection) connection)
.setHostnameVerifier(getTrustedVerifier());
return this;
}
/**
* Get the {@link URL} of this request's connection
*

View File

@@ -38,10 +38,6 @@ import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
abstract class CordovaHttp {
protected static final String TAG = "CordovaHTTP";
protected static final String[] ACCEPTED_CHARSETS = new String[] { HttpRequest.CHARSET_UTF8, HttpRequest.CHARSET_LATIN1 };
private static AtomicBoolean sslPinning = new AtomicBoolean(false);
private static AtomicBoolean acceptAllCerts = new AtomicBoolean(false);
private static AtomicBoolean validateDomainName = new AtomicBoolean(true);
private static AtomicBoolean disableRedirect = new AtomicBoolean(false);
private String urlString;
@@ -64,24 +60,6 @@ abstract class CordovaHttp {
this.callbackContext = callbackContext;
}
public static void enableSSLPinning(boolean enable) {
sslPinning.set(enable);
if (enable) {
acceptAllCerts.set(false);
}
}
public static void acceptAllCerts(boolean accept) {
acceptAllCerts.set(accept);
if (accept) {
sslPinning.set(false);
}
}
public static void validateDomainName(boolean accept) {
validateDomainName.set(accept);
}
public static void disableRedirect(boolean disable) {
disableRedirect.set(disable);
}
@@ -122,20 +100,6 @@ abstract class CordovaHttp {
return this.callbackContext;
}
protected HttpRequest setupSecurity(HttpRequest request) {
if (acceptAllCerts.get()) {
request.trustAllCerts();
}
if (!validateDomainName.get()) {
request.trustAllHosts();
}
if (sslPinning.get()) {
request.pinToCerts();
}
return request;
}
protected HttpRequest setupRedirect(HttpRequest request) {
if (disableRedirect.get()) {
request.followRedirects(false);
@@ -222,7 +186,6 @@ abstract class CordovaHttp {
protected void prepareRequest(HttpRequest request) throws HttpRequestException, JSONException {
this.setupRedirect(request);
this.setupSecurity(request);
request.readTimeout(this.getRequestTimeout());
request.acceptCharset(ACCEPTED_CHARSETS);
@@ -307,11 +270,11 @@ abstract class CordovaHttp {
protected void handleHttpRequestException(HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
this.respondWithError(0, "The host could not be resolved: " + e.getMessage());
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
this.respondWithError(1, "The request timed out: " + e.getMessage());
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
this.respondWithError(-2, "SSL handshake failed: " + e.getMessage());
} else {
this.respondWithError("There was an error with the request: " + e.getMessage());
}

View File

@@ -31,7 +31,7 @@ class CordovaHttpDownload extends CordovaHttp implements Runnable {
@Override
public void run() {
try {
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParamsMap(), true);
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParamsMap(), false);
this.prepareRequest(request);

View File

@@ -23,7 +23,7 @@ class CordovaHttpHead extends CordovaHttp implements Runnable {
@Override
public void run() {
try {
HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), true);
HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), false);
this.prepareRequest(request);
this.returnResponseObject(request);

View File

@@ -8,8 +8,12 @@ import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStore.TrustedCertificateEntry;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
@@ -30,6 +34,14 @@ public class CordovaHttpPlugin extends CordovaPlugin {
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
try {
HttpRequest.clearCerts();
this.pinSSLCertsFromCAStore();
} catch (Exception e) {
e.printStackTrace();
System.err.println("There was an error loading system's CA certificates");
}
}
@Override
@@ -86,21 +98,35 @@ public class CordovaHttpPlugin extends CordovaPlugin {
CordovaHttpHead head = new CordovaHttpHead(urlString, params, headers, timeoutInMilliseconds, callbackContext);
cordova.getThreadPool().execute(head);
} else if (action.equals("enableSSLPinning")) {
try {
boolean enable = args.getBoolean(0);
this.enableSSLPinning(enable);
callbackContext.success();
} catch(Exception e) {
e.printStackTrace();
callbackContext.error("There was an error setting up ssl pinning");
}
} else if (action.equals("acceptAllCerts")) {
boolean accept = args.getBoolean(0);
} else if (action.equals("setSSLCertMode")) {
String mode = args.getString(0);
CordovaHttp.acceptAllCerts(accept);
CordovaHttp.validateDomainName(!accept);
callbackContext.success();
HttpRequest.clearCerts();
if (mode.equals("legacy")) {
HttpRequest.setSSLCertMode(HttpRequest.CERT_MODE_DEFAULT);
callbackContext.success();
} else if (mode.equals("nocheck")) {
HttpRequest.setSSLCertMode(HttpRequest.CERT_MODE_TRUSTALL);
callbackContext.success();
} else if (mode.equals("pinned")) {
try {
this.loadSSLCertsFromBundle();
HttpRequest.setSSLCertMode(HttpRequest.CERT_MODE_PINNED);
callbackContext.success();
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("There was an error setting up ssl pinning");
}
} else if (mode.equals("default")) {
try {
this.pinSSLCertsFromCAStore();
callbackContext.success();
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("There was an error loading system's CA certificates");
}
}
} else if (action.equals("uploadFile")) {
String urlString = args.getString(0);
Object params = args.get(1);
@@ -121,49 +147,51 @@ public class CordovaHttpPlugin extends CordovaPlugin {
cordova.getThreadPool().execute(download);
} else if (action.equals("disableRedirect")) {
boolean disable = args.getBoolean(0);
CordovaHttp.disableRedirect(disable);
callbackContext.success();
boolean disable = args.getBoolean(0);
CordovaHttp.disableRedirect(disable);
callbackContext.success();
} else {
return false;
}
return true;
}
private void enableSSLPinning(boolean enable) throws GeneralSecurityException, IOException {
if (enable) {
AssetManager assetManager = cordova.getActivity().getAssets();
String[] files = assetManager.list("");
int index;
ArrayList<String> cerFiles = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
index = files[i].lastIndexOf('.');
if (index != -1) {
if (files[i].substring(index).equals(".cer")) {
cerFiles.add(files[i]);
}
}
}
private void pinSSLCertsFromCAStore() throws GeneralSecurityException, IOException {
this.loadSSLCertsFromKeyStore("AndroidCAStore");
HttpRequest.setSSLCertMode(HttpRequest.CERT_MODE_PINNED);
}
// scan the www/certificates folder for .cer files as well
files = assetManager.list("www/certificates");
for (int i = 0; i < files.length; i++) {
index = files[i].lastIndexOf('.');
if (index != -1) {
if (files[i].substring(index).equals(".cer")) {
cerFiles.add("www/certificates/" + files[i]);
}
}
}
private void loadSSLCertsFromKeyStore(String storeType) throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance(storeType);
ks.load(null);
Enumeration<String> aliases = ks.aliases();
for (int i = 0; i < cerFiles.size(); i++) {
InputStream in = cordova.getActivity().getAssets().open(cerFiles.get(i));
InputStream caInput = new BufferedInputStream(in);
HttpRequest.addCert(caInput);
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
TrustedCertificateEntry certEntry = (TrustedCertificateEntry) ks.getEntry(alias, null);
Certificate cert = certEntry.getTrustedCertificate();
HttpRequest.addCert(cert);
}
}
private void loadSSLCertsFromBundle() throws GeneralSecurityException, IOException {
AssetManager assetManager = cordova.getActivity().getAssets();
String[] files = assetManager.list("www/certificates");
ArrayList<String> cerFiles = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
int index = files[i].lastIndexOf('.');
if (index != -1) {
if (files[i].substring(index).equals(".cer")) {
cerFiles.add("www/certificates/" + files[i]);
}
CordovaHttp.enableSSLPinning(true);
} else {
CordovaHttp.enableSSLPinning(false);
}
}
for (int i = 0; i < cerFiles.size(); i++) {
InputStream in = cordova.getActivity().getAssets().open(cerFiles.get(i));
InputStream caInput = new BufferedInputStream(in);
HttpRequest.addCert(caInput);
}
}
}

View File

@@ -37,12 +37,27 @@ function serializeParams(params) {
}).join('&');
}
function deserializeResponseHeaders(headers) {
var headerMap = {};
var arr = headers.trim().split(/[\r\n]+/);
arr.forEach(function (line) {
var parts = line.split(': ');
var header = parts.shift().toLowerCase();
var value = parts.join(': ');
headerMap[header] = value;
});
return headerMap;
}
function createXhrSuccessObject(xhr) {
return {
url: xhr.responseURL,
status: xhr.status,
data: helpers.getTypeOf(xhr.responseText) === 'String' ? xhr.responseText : xhr.response,
headers: xhr.getAllResponseHeaders()
headers: deserializeResponseHeaders(xhr.getAllResponseHeaders())
};
}
@@ -59,9 +74,27 @@ function createXhrFailureObject(xhr) {
return obj;
}
function getHeaderValue(headers, headerName) {
let result = null;
Object.keys(headers).forEach(function(key) {
if (key.toLowerCase() === headerName.toLowerCase()) {
result = headers[key];
}
});
return result;
}
function setDefaultContentType(headers, contentType) {
if (getHeaderValue(headers, 'Content-Type') === null) {
headers['Content-Type'] = contentType;
}
}
function setHeaders(xhr, headers) {
Object.keys(headers).forEach(function(key) {
if (key === 'Cookie') return;
if (key.toLowerCase() === 'cookie') return;
xhr.setRequestHeader(key, headers[key]);
});
@@ -86,7 +119,7 @@ function sendRequest(method, withData, opts, success, failure) {
switch (serializer) {
case 'json':
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf8');
setDefaultContentType(headers, 'application/json; charset=utf8');
processedData = serializeJsonData(data);
if (processedData === null) {
@@ -96,12 +129,12 @@ function sendRequest(method, withData, opts, success, failure) {
break;
case 'utf8':
xhr.setRequestHeader('Content-Type', 'text/plain; charset=utf8');
setDefaultContentType(headers, 'text/plain; charset=utf8');
processedData = data.text;
break;
case 'urlencoded':
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
setDefaultContentType(headers, 'application/x-www-form-urlencoded');
processedData = serializeParams(data);
break;
}
@@ -136,7 +169,7 @@ var browserInterface = {
put: function (success, failure, opts) {
return sendRequest('put', true, opts, success, failure);
},
patch: function (success, failure, opts) {
patch: function (success, failure, opts) {
return sendRequest('patch', true, opts, success, failure);
},
delete: function (success, failure, opts) {
@@ -151,11 +184,8 @@ var browserInterface = {
downloadFile: function (success, failure, opts) {
return failure('advanced-http: function "downloadFile" not supported on browser platform');
},
enableSSLPinning: function (success, failure, opts) {
return failure('advanced-http: function "enableSSLPinning" not supported on browser platform');
},
acceptAllCerts: function (success, failure, opts) {
return failure('advanced-http: function "acceptAllCerts" not supported on browser platform');
setSSLCertMode: function (success, failure, opts) {
return failure('advanced-http: function "setSSLCertMode" not supported on browser platform');
},
disableRedirect: function (success, failure, opts) {
return failure('advanced-http: function "disableRedirect" not supported on browser platform');

View File

@@ -156,16 +156,9 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
@implementation AFSecurityPolicy
+ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"www/certificates"];
NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
// also add certs from www/certificates
paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"www/certificates"];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
@@ -284,13 +277,13 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
// obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
return YES;
}
}
return NO;
}
case AFSSLPinningModePublicKey: {
@@ -307,7 +300,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
return trustedPublicKeyCount > 0;
}
}
return NO;
}

View File

@@ -392,11 +392,11 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
- On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled.
- On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled.
- Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there.
Some Assumptions:
- No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it.
- No background task classes override `resume` or `suspend`
The current solution:
1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task.
2) Grab a pointer to the original implementation of `af_resume`
@@ -415,7 +415,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
#pragma clang diagnostic pop
IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume)));
Class currentClass = [localDataTask class];
while (class_getInstanceMethod(currentClass, @selector(resume))) {
Class superClass = [currentClass superclass];
IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume)));
@@ -426,7 +426,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
}
currentClass = [currentClass superclass];
}
[localDataTask cancel];
[session finishTasksAndInvalidate];
}
@@ -454,7 +454,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
NSURLSessionTaskState state = [self state];
[self af_resume];
if (state != NSURLSessionTaskStateRunning) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self];
}
@@ -464,7 +464,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
NSURLSessionTaskState state = [self state];
[self af_suspend];
if (state != NSURLSessionTaskStateSuspended) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self];
}
@@ -978,7 +978,7 @@ didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
disposition = NSURLSessionAuthChallengeRejectProtectionSpace;
}
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
@@ -1025,7 +1025,7 @@ didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
disposition = NSURLSessionAuthChallengeUseCredential;
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
disposition = NSURLSessionAuthChallengeRejectProtectionSpace;
}
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;

View File

@@ -4,8 +4,7 @@
@interface CordovaHttpPlugin : CDVPlugin
- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command;
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command;
- (void)setSSLCertMode:(CDVInvokedUrlCommand*)command;
- (void)disableRedirect:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;

View File

@@ -3,6 +3,7 @@
#import "TextResponseSerializer.h"
#import "TextRequestSerializer.h"
#import "AFHTTPSessionManager.h"
#import "SDNetworkActivityIndicator.h"
@interface CordovaHttpPlugin()
@@ -19,10 +20,12 @@
@implementation CordovaHttpPlugin {
AFSecurityPolicy *securityPolicy;
bool redirect;
AFHTTPSessionManager *manager;
}
- (void)pluginInitialize {
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
manager = [AFHTTPSessionManager manager];
redirect = true;
}
@@ -103,6 +106,9 @@
case -1009:
// no connection
return [NSNumber numberWithInt:3];
case -1202:
// untrusted SSL certificate
return [NSNumber numberWithInt:-2];
default:
return [NSNumber numberWithInt:-1];
}
@@ -120,23 +126,31 @@
return headerFieldsCopy;
}
- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager {
[manager.requestSerializer setTimeoutInterval:timeout];
}
- (void)setSSLCertMode:(CDVInvokedUrlCommand*)command {
NSString *certMode = [command.arguments objectAtIndex:0];
- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command {
bool enable = [[command.arguments objectAtIndex:0] boolValue];
if (enable) {
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
} else {
if ([certMode isEqualToString: @"default"] || [certMode isEqualToString: @"legacy"]) {
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = NO;
securityPolicy.validatesDomainName = YES;
} else if ([certMode isEqualToString: @"nocheck"]) {
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
securityPolicy.validatesDomainName = NO;
} else if ([certMode isEqualToString: @"pinned"]) {
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
securityPolicy.allowInvalidCertificates = NO;
securityPolicy.validatesDomainName = YES;
}
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager {
[manager.requestSerializer setTimeoutInterval:timeout];
}
- (void)disableRedirect:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil;
bool disable = [[command.arguments objectAtIndex:0] boolValue];
@@ -147,19 +161,7 @@
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil;
bool allow = [[command.arguments objectAtIndex:0] boolValue];
securityPolicy.allowInvalidCertificates = allow;
securityPolicy.validatesDomainName = !allow;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)post:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
@@ -175,6 +177,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
@@ -183,21 +186,23 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}
- (void)get:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
@@ -213,6 +218,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
@@ -221,21 +227,23 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}
- (void)put:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
@@ -251,6 +259,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager PUT:url parameters:parameters success:^(NSURLSessionTask *task, id responseObject) {
@@ -259,21 +268,23 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}
- (void)patch:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
@@ -289,6 +300,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager PATCH:url parameters:parameters success:^(NSURLSessionTask *task, id responseObject) {
@@ -297,21 +309,23 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}
- (void)delete:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
@@ -326,6 +340,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager DELETE:url parameters:parameters success:^(NSURLSessionTask *task, id responseObject) {
@@ -334,21 +349,23 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}
- (void)head:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
@@ -361,6 +378,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager HEAD:url parameters:parameters success:^(NSURLSessionTask *task) {
@@ -370,21 +388,23 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}
- (void)uploadFile:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
@@ -402,6 +422,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
@@ -413,6 +434,7 @@
[dictionary setObject:@"Could not add file to post body." forKey:@"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
return;
}
} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
@@ -421,22 +443,24 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}
- (void)downloadFile:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
@@ -455,6 +479,7 @@
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
@try {
[manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
@@ -495,6 +520,7 @@
}
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
return;
}
NSData *data = (NSData *)responseObject;
@@ -504,6 +530,7 @@
[dictionary setObject:@"Could not write the data to the given filePath." forKey:@"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
return;
}
@@ -514,6 +541,7 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
@@ -521,9 +549,11 @@
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
}];
}
@catch (NSException *exception) {
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
[self handleException:exception withCommand:command];
}
}

View File

@@ -0,0 +1,20 @@
Copyright (c) 2010 Olivier Poitrey <rs@dailymotion.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,52 @@
# SDNetworkActivityIndicator
Handle showing / hiding of the iOS network activity indicator to allow multiple concurrent threads to show / hide the indicator such that the indicator remains visible until all the requests have completed and requested the indicator to be hidden.
## Requirements
* iOS 5.0 or later.
* ARC memory management.
## Installation
The easiest way to install it is by copying the following files to your project:
* SDNetworkActivityIndicator.h
* SDNetworkActivityIndicator.m
## Usage
* When you start a network activity (will show the network activity indicator):
[[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
* When you finish a network activity (will hide the network activity indicator only if the number of calls to `stopActivity` matches the number of calls to `startActivity`):
[[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
* To hide the network activity indicator regardless of whether all activities have finished (without having to call `stopActivity` for each `startActivity` called):
[[SDNetworkActivityIndicator sharedActivityIndicator] stopAllActivity];
## License
Copyright (c) 2010 Olivier Poitrey <rs@dailymotion.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,18 @@
/*
* This file is part of the SDNetworkActivityIndicator package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
@interface SDNetworkActivityIndicator : NSObject
+ (id)sharedActivityIndicator;
- (void)startActivity;
- (void)stopActivity;
- (void)stopAllActivity;
@end

View File

@@ -0,0 +1,70 @@
/*
* This file is part of the SDNetworkActivityIndicator package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDNetworkActivityIndicator.h"
@interface SDNetworkActivityIndicator()
{
@private NSUInteger counter;
}
@end
@implementation SDNetworkActivityIndicator
+ (instancetype) sharedActivityIndicator
{
static id _sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
- (id)init
{
if ((self = [super init]))
{
counter = 0;
}
return self;
}
- (void)startActivity
{
@synchronized(self)
{
counter++;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
}
- (void)stopActivity
{
@synchronized(self)
{
if (counter > 0 && --counter == 0)
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
}
}
- (void)stopAllActivity
{
@synchronized(self)
{
counter = 0;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
}
@end

View File

@@ -6,5 +6,5 @@ if (process.env.SAUCE_USERNAME) {
} else {
// these paths are relative to working directory
exports.iosTestApp = path.resolve('temp/platforms/ios/build/emulator/HttpDemo.app');
exports.androidTestApp = path.resolve('temp/platforms/android/build/outputs/apk/android-debug.apk');
exports.androidTestApp = path.resolve('temp/platforms/android/app/build/outputs/apk/debug/app-debug.apk');
}

View File

@@ -1,7 +1,5 @@
const local = {
iosDevice: {
browserName: '',
'appium-version': '1.7.1',
platformName: 'iOS',
platformVersion: '10.3',
deviceName: 'iPhone 6',
@@ -9,8 +7,6 @@ const local = {
app: undefined // will be set later
},
iosEmulator: {
browserName: '',
'appium-version': '1.7.1',
platformName: 'iOS',
platformVersion: '11.0',
deviceName: 'iPhone Simulator',
@@ -18,12 +14,11 @@ const local = {
app: undefined // will be set later
},
androidEmulator: {
browserName: '',
'appium-version': '1.7.1',
platformName: 'Android',
platformVersion: '5.1',
deviceName: 'Android Emulator',
autoWebview: true,
fullReset: true,
app: undefined // will be set later
}
};

View File

@@ -83,10 +83,10 @@ describe('Advanced HTTP', function() {
}));
testDefinitions.tests.forEach((definition, index) => {
it(definition.description, function() {
it(index + ': ' + definition.description, function() {
return clickNext()
.then(() => validateTestIndex(index))
.then(() => validateTestTitle(this.test.title))
.then(() => validateTestTitle(definition.description))
.then(() => waitToBeFinished(definition.timeout || 10000))
.then(() => validateResult(definition))
});

View File

@@ -0,0 +1,14 @@
{
"ios": {
"debug": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
},
"release": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
}
}
}

View File

@@ -22,8 +22,9 @@
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>
<engine name="android" spec="6.2.3" />
<engine name="android" spec="7.1.0" />
<engine name="browser" spec="5.0.0" />
<engine name="ios" spec="4.4.0" />
<plugin name="cordova-plugin-file" spec="4.3.3" />
<plugin name="cordova-plugin-file" spec="6.0.1" />
<preference name="AndroidPersistentFileLocation" value="Internal" />
</widget>

View File

@@ -12,7 +12,8 @@
"license": "Apache-2.0",
"dependencies": {
"cordova": "7.0.1",
"cordova-android": "6.2.3",
"cordova-android": "7.1.0",
"cordova-browser": "5.0.0",
"cordova-ios": "4.4.0"
},
"cordova": {

View File

@@ -1,15 +1,14 @@
const hooks = {
onBeforeEachTest: function(done) {
cordova.plugin.http.clearCookies();
cordova.plugin.http.acceptAllCerts(false, function() {
cordova.plugin.http.enableSSLPinning(false, done, done);
}, done);
helpers.setDefaultCertMode(done);
}
};
const helpers = {
acceptAllCerts: function(done) { cordova.plugin.http.acceptAllCerts(true, done, done); },
enableSSLPinning: function(done) { cordova.plugin.http.enableSSLPinning(true, done, done); },
setDefaultCertMode: function(done) { cordova.plugin.http.setSSLCertMode('default', done, done); },
setNoCheckCertMode: function(done) { cordova.plugin.http.setSSLCertMode('nocheck', done, done); },
setPinnedCertMode: function(done) { cordova.plugin.http.setSSLCertMode('pinned', done, done); },
setJsonSerializer: function(done) { done(cordova.plugin.http.setDataSerializer('json')); },
setUtf8StringSerializer: function(done) { done(cordova.plugin.http.setDataSerializer('utf8')); },
setUrlEncodedSerializer: function(done) { done(cordova.plugin.http.setDataSerializer('urlencoded')); },
@@ -38,51 +37,56 @@ const helpers = {
}
};
const messageFactory = {
sslTrustAnchor: function() { return 'SSL handshake failed: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.' },
invalidCertificate: function(domain) { return 'The certificate for this server is invalid. You might be connecting to a server that is pretending to be “' + domain + '” which could put your confidential information at risk.' }
}
const tests = [
{
description: 'should reject self signed cert (GET)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
expected: 'rejected: {"status":-2, ...',
func: function(resolve, reject) { cordova.plugin.http.get('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result, targetInfo) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error: targetInfo.isAndroid ? 'SSL handshake failed' : 'cancelled' });
result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.sslTrustAnchor() : messageFactory.invalidCertificate('self-signed.badssl.com') });
}
},{
description: 'should reject self signed cert (PUT)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
expected: 'rejected: {"status":-2, ...',
func: function(resolve, reject) { cordova.plugin.http.put('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result, targetInfo) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error: targetInfo.isAndroid ? 'SSL handshake failed' : 'cancelled' });
result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.sslTrustAnchor() : messageFactory.invalidCertificate('self-signed.badssl.com') });
}
},{
description: 'should reject self signed cert (POST)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
expected: 'rejected: {"status":-2, ...',
func: function(resolve, reject) { cordova.plugin.http.post('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result, targetInfo) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error: targetInfo.isAndroid ? 'SSL handshake failed' : 'cancelled' });
result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.sslTrustAnchor() : messageFactory.invalidCertificate('self-signed.badssl.com') });
}
},{
description: 'should reject self signed cert (PATCH)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
expected: 'rejected: {"status":-2, ...',
func: function(resolve, reject) { cordova.plugin.http.patch('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result, targetInfo) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error: targetInfo.isAndroid ? 'SSL handshake failed' : 'cancelled' });
result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.sslTrustAnchor() : messageFactory.invalidCertificate('self-signed.badssl.com') });
}
},{
description: 'should reject self signed cert (DELETE)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
expected: 'rejected: {"status":-2, ...',
func: function(resolve, reject) { cordova.plugin.http.delete('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result, targetInfo) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error: targetInfo.isAndroid ? 'SSL handshake failed' : 'cancelled' });
result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.sslTrustAnchor() : messageFactory.invalidCertificate('self-signed.badssl.com') });
}
},{
description: 'should accept bad cert (GET)',
expected: 'resolved: {"status":200, ...',
before: helpers.acceptAllCerts,
before: helpers.setNoCheckCertMode,
func: function(resolve, reject) { cordova.plugin.http.get('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
@@ -91,7 +95,7 @@ const tests = [
},{
description: 'should accept bad cert (PUT)',
expected: 'rejected: {"status":405, ... // will be rejected because PUT is not allowed',
before: helpers.acceptAllCerts,
before: helpers.setNoCheckCertMode,
func: function(resolve, reject) { cordova.plugin.http.put('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
@@ -100,7 +104,7 @@ const tests = [
},{
description: 'should accept bad cert (POST)',
expected: 'rejected: {"status":405, ... // will be rejected because POST is not allowed',
before: helpers.acceptAllCerts,
before: helpers.setNoCheckCertMode,
func: function(resolve, reject) { cordova.plugin.http.post('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
@@ -109,7 +113,7 @@ const tests = [
},{
description: 'should accept bad cert (PATCH)',
expected: 'rejected: {"status":405, ... // will be rejected because PATCH is not allowed',
before: helpers.acceptAllCerts,
before: helpers.setNoCheckCertMode,
func: function(resolve, reject) { cordova.plugin.http.patch('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
@@ -118,7 +122,7 @@ const tests = [
},{
description: 'should accept bad cert (DELETE)',
expected: 'rejected: {"status":405, ... // will be rejected because DELETE is not allowed',
before: helpers.acceptAllCerts,
before: helpers.setNoCheckCertMode,
func: function(resolve, reject) { cordova.plugin.http.delete('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
@@ -127,7 +131,7 @@ const tests = [
},{
description: 'should fetch data from http://httpbin.org/ (GET)',
expected: 'resolved: {"status":200, ...',
before: helpers.acceptAllCerts,
before: helpers.setNoCheckCertMode,
func: function(resolve, reject) { cordova.plugin.http.get('http://httpbin.org/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
@@ -285,7 +289,7 @@ const tests = [
JSON
.parse(result.data.data)
.url
.should.be.equal('http://httpbin.org/get?myArray[]=val1&myArray[]=val2&myArray[]=val3&myString=testString');
.should.include('httpbin.org/get?myArray[]=val1&myArray[]=val2&myArray[]=val3&myString=testString');
}
},{
description: 'should throw on non-string values in local header object #54',
@@ -430,12 +434,24 @@ const tests = [
},{
description: 'should pin SSL cert correctly (GET)',
expected: 'resolved: {"status": 200 ...',
before: helpers.enableSSLPinning,
before: helpers.setPinnedCertMode,
func: function(resolve, reject) {
cordova.plugin.http.get('https://httpbin.org', {}, {}, resolve, reject);
},
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
result.data.status.should.be.equal(200);
}
},{
description: 'should reject when pinned cert does not match received server cert (GET)',
expected: 'rejected: {"status": -2 ...',
before: helpers.setPinnedCertMode,
func: function(resolve, reject) {
cordova.plugin.http.get('https://sha512.badssl.com/', {}, {}, resolve, reject);
},
validationFunc: function(driver, result, targetInfo) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -2, error: targetInfo.isAndroid ? messageFactory.sslTrustAnchor() : messageFactory.invalidCertificate('sha512.badssl.com') });
}
},{
description: 'should send deeply structured JSON object correctly (POST) #65',
@@ -464,6 +480,34 @@ const tests = [
result.data.status.should.be.equal(403);
result.data.error.should.be.equal('There was an error downloading the file');
}
},{
description: 'should handle gzip encoded response correctly',
expected: 'resolved: {"status": 200, "headers": "{\\"Content-Encoding\\": \\"gzip\\" ...',
func: function(resolve, reject) { cordova.plugin.http.get('http://httpbin.org/gzip', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
result.data.status.should.be.equal(200);
JSON.parse(result.data.data).gzipped.should.be.equal(true);
}
},{
description: 'should send empty string correctly',
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"\\" ...',
before: helpers.setUtf8StringSerializer,
func: function(resolve, reject) { cordova.plugin.http.post('http://httpbin.org/anything', '', {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
JSON.parse(result.data.data).data.should.be.equal('');
}
},{
description: 'shouldn\'t escape forward slashes #184',
expected: 'resolved: {"status": 200, "data": "{\\"json\\":\\"/\\" ...',
before: helpers.setJsonSerializer,
func: function(resolve, reject) { cordova.plugin.http.post('http://httpbin.org/anything', { testString: '/' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
console.log(result.data.data);
JSON.parse(result.data.data).json.testString.should.be.equal('/');
}
}
];

View File

@@ -28,7 +28,6 @@ describe('Advanced HTTP www interface', function() {
mock(`${PLUGIN_ID}.cookie-handler`, {});
mock(`${HELPERS_ID}.cookie-handler`, {});
mock(`${HELPERS_ID}.messages`, require('../www/messages'));
mock(`${PLUGIN_ID}.angular-integration`, { registerService: noop });
loadHttp();
});

View File

@@ -5,7 +5,6 @@
var pluginId = module.id.slice(0, module.id.lastIndexOf('.'));
var exec = require('cordova/exec');
var angularIntegration = require(pluginId +'.angular-integration');
var cookieHandler = require(pluginId + '.cookie-handler');
var helpers = require(pluginId + '.helpers');
@@ -67,14 +66,11 @@ var publicInterface = {
setRequestTimeout: function (timeout) {
globalConfigs.timeout = timeout;
},
enableSSLPinning: function (enable, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'enableSSLPinning', [ enable ]);
},
acceptAllCerts: function (allow, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'acceptAllCerts', [ allow ]);
setSSLCertMode: function (mode, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'setSSLCertMode', [ helpers.checkSSLCertMode(mode) ]);
},
disableRedirect: function (disable, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'disableRedirect', [ disable ]);
return exec(success, failure, 'CordovaHttpPlugin', 'disableRedirect', [ !!disable ]);
},
sendRequest: function (url, options, success, failure) {
helpers.handleMissingCallbacks(success, failure);
@@ -126,6 +122,4 @@ var publicInterface = {
}
};
// angular service is deprecated and will be removed anytime soon
angularIntegration.registerService(publicInterface);
module.exports = publicInterface;

View File

@@ -1,96 +0,0 @@
function registerService(http) {
if (typeof angular === 'undefined') return;
angular.module('cordovaHTTP', []).factory('cordovaHTTP', function ($timeout, $q) {
function makePromise(fn, args, async) {
var deferred = $q.defer();
var success = function (response) {
if (async) {
$timeout(function () {
deferred.resolve(response);
});
} else {
deferred.resolve(response);
}
};
var fail = function (response) {
if (async) {
$timeout(function () {
deferred.reject(response);
});
} else {
deferred.reject(response);
}
};
args.push(success);
args.push(fail);
fn.apply(http, args);
return deferred.promise;
}
var cordovaHTTP = {
getBasicAuthHeader: http.getBasicAuthHeader,
useBasicAuth: function (username, password) {
return http.useBasicAuth(username, password);
},
setHeader: function (host, header, value) {
return http.setHeader(host, header, value);
},
setDataSerializer: function (serializer) {
return http.setDataSerializer(serializer);
},
clearCookies: function () {
return http.clearCookies();
},
removeCookies: function (url) {
return http.removeCookies(url);
},
setRequestTimeout: function (timeout) {
return http.setRequestTimeout(timeout);
},
enableSSLPinning: function (enable) {
return makePromise(http.enableSSLPinning, [enable]);
},
acceptAllCerts: function (allow) {
return makePromise(http.acceptAllCerts, [allow]);
},
disableRedirect: function(disable) {
return makePromise(http.disableRedirect, [disable]);
},
validateDomainName: function (validate) {
return makePromise(http.validateDomainName, [validate]);
},
post: function (url, data, headers) {
return makePromise(http.post, [url, data, headers], true);
},
get: function (url, params, headers) {
return makePromise(http.get, [url, params, headers], true);
},
put: function (url, data, headers) {
return makePromise(http.put, [url, data, headers], true);
},
delete: function (url, params, headers) {
return makePromise(http.delete, [url, params, headers], true);
},
head: function (url, params, headers) {
return makePromise(http.head, [url, params, headers], true);
},
uploadFile: function (url, params, headers, filePath, name) {
return makePromise(http.uploadFile, [url, params, headers, filePath, name], true);
},
downloadFile: function (url, params, headers, filePath) {
return makePromise(http.downloadFile, [url, params, headers, filePath], true);
}
};
return cordovaHTTP;
});
}
module.exports = {
registerService: registerService
};

View File

@@ -3,12 +3,14 @@ var cookieHandler = require(pluginId + '.cookie-handler');
var messages = require(pluginId + '.messages');
var validSerializers = [ 'urlencoded', 'json', 'utf8' ];
var validCertModes = [ 'default', 'nocheck', 'pinned', 'legacy' ];
var validHttpMethods = [ 'get', 'put', 'post', 'patch', 'head', 'delete', 'upload', 'download' ];
module.exports = {
b64EncodeUnicode: b64EncodeUnicode,
getTypeOf: getTypeOf,
checkSerializer: checkSerializer,
checkSSLCertMode: checkSSLCertMode,
checkForBlacklistedHeaderKey: checkForBlacklistedHeaderKey,
checkForInvalidHeaderValue: checkForInvalidHeaderValue,
injectCookieHandler: injectCookieHandler,
@@ -79,6 +81,10 @@ function checkSerializer(serializer) {
return checkForValidStringValue(validSerializers, serializer, messages.INVALID_DATA_SERIALIZER);
}
function checkSSLCertMode(mode) {
return checkForValidStringValue(validCertModes, mode, messages.INVALID_SSL_CERT_MODE);
}
function checkForBlacklistedHeaderKey(key) {
if (key.toLowerCase() === 'cookie') {
throw new Error(messages.ADDING_COOKIES_NOT_SUPPORTED);
@@ -207,8 +213,6 @@ function getAllowedDataTypes(dataSerializer) {
}
function getProcessedData(data, dataSerializer) {
data = data || {};
var currentDataType = getTypeOf(data);
var allowedDataTypes = getAllowedDataTypes(dataSerializer);
@@ -242,7 +246,7 @@ function handleMissingOptions(options, globals) {
timeout: checkTimeoutValue(options.timeout || globals.timeout),
headers: checkHeadersObject(options.headers || {}),
params: checkParamsObject(options.params || {}),
data: options.data || null,
data: getTypeOf(options.data) === 'Undefined' ? null : options.data,
filePath: options.filePath || '',
name: options.name || ''
};

View File

@@ -5,6 +5,7 @@ module.exports = {
MANDATORY_FAIL: 'advanced-http: missing mandatory "onFail" callback function',
INVALID_HTTP_METHOD: 'advanced-http: invalid HTTP method, supported methods are:',
INVALID_DATA_SERIALIZER: 'advanced-http: invalid serializer, supported serializers are:',
INVALID_SSL_CERT_MODE: 'advanced-http: invalid SSL cert mode, supported modes are:',
INVALID_HEADERS_VALUE: 'advanced-http: header values must be strings',
INVALID_TIMEOUT_VALUE: 'advanced-http: invalid timeout value, needs to be a positive numeric value',
INVALID_PARAMS_VALUE: 'advanced-http: invalid params object, needs to be an object with strings'

File diff suppressed because one or more lines are too long