forked from nativescript-community/https
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps.ios.ts
More file actions
161 lines (136 loc) · 5.5 KB
/
https.ios.ts
File metadata and controls
161 lines (136 loc) · 5.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import { isDefined, isNullOrUndefined, isObject } from 'tns-core-modules/utils/types';
import * as Https from './https.common';
interface Ipolicies {
def: AFSecurityPolicy;
secured: boolean;
secure?: AFSecurityPolicy;
}
let policies: Ipolicies = {
def: AFSecurityPolicy.defaultPolicy(),
secured: false,
};
policies.def.allowInvalidCertificates = true;
policies.def.validatesDomainName = false;
export function enableSSLPinning(options: Https.HttpsSSLPinningOptions) {
if (!policies.secure) {
policies.secure = AFSecurityPolicy.policyWithPinningMode(AFSSLPinningMode.PublicKey);
policies.secure.allowInvalidCertificates = (isDefined(options.allowInvalidCertificates)) ? options.allowInvalidCertificates : false;
policies.secure.validatesDomainName = (isDefined(options.validatesDomainName)) ? options.validatesDomainName : true;
let data = NSData.dataWithContentsOfFile(options.certificate);
policies.secure.pinnedCertificates = NSSet.setWithObject(data);
}
policies.secured = true;
console.log('nativescript-https > Enabled SSL pinning');
}
export function disableSSLPinning() {
policies.secured = false;
console.log('nativescript-https > Disabled SSL pinning');
}
console.info('nativescript-https > Disabled SSL pinning by default');
function AFSuccess(resolve, task: NSURLSessionDataTask, data: NSDictionary<string, any> & NSData & NSArray<any>) {
let content: any;
if (data && data.class) {
if (data.enumerateKeysAndObjectsUsingBlock || (<any>data) instanceof NSArray) {
let serial = NSJSONSerialization.dataWithJSONObjectOptionsError(data, NSJSONWritingOptions.PrettyPrinted);
content = NSString.alloc().initWithDataEncoding(serial, NSUTF8StringEncoding).toString();
} else if ((<any>data) instanceof NSData) {
content = NSString.alloc().initWithDataEncoding(data, NSASCIIStringEncoding).toString();
} else {
content = data;
}
try {
content = JSON.parse(content);
} catch (ignore) {
}
} else {
content = data;
}
resolve({task, content});
}
function AFFailure(resolve, reject, task: NSURLSessionDataTask, error: NSError) {
let data: NSData = error.userInfo.valueForKey(AFNetworkingOperationFailingURLResponseDataErrorKey);
let body = NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding).toString();
try {
body = JSON.parse(body);
} catch (ignore) {
}
let content: any = {
body,
description: error.description,
reason: error.localizedDescription,
url: error.userInfo.objectForKey('NSErrorFailingURLKey').description
};
if (policies.secured === true) {
content.description = 'nativescript-https > Invalid SSL certificate! ' + content.description;
}
let reason = error.localizedDescription;
resolve({task, content, reason});
}
export function request(opts: Https.HttpsRequestOptions): Promise<Https.HttpsResponse> {
return new Promise((resolve, reject) => {
try {
const manager = AFHTTPSessionManager.alloc().initWithBaseURL(NSURL.URLWithString(opts.url));
if (opts.headers && (<any>opts.headers['Content-Type']).substring(0, 16) === 'application/json') {
manager.requestSerializer = AFJSONRequestSerializer.serializer();
manager.responseSerializer = AFJSONResponseSerializer.serializerWithReadingOptions(NSJSONReadingOptions.AllowFragments);
} else {
manager.requestSerializer = AFHTTPRequestSerializer.serializer();
manager.responseSerializer = AFHTTPResponseSerializer.serializer();
}
manager.requestSerializer.allowsCellularAccess = true;
manager.securityPolicy = (policies.secured === true) ? policies.secure : policies.def;
let heads = opts.headers;
if (heads) {
Object.keys(heads).forEach(key => manager.requestSerializer.setValueForHTTPHeaderField(heads[key] as any, key));
}
let dict = null;
if (opts.body) {
let cont = opts.body;
if (Array.isArray(cont)) {
dict = NSMutableArray.new();
cont.forEach(function (item, idx) {
dict.addObject(item);
});
} else if (isObject(cont)) {
dict = NSMutableDictionary.new<string, any>();
Object.keys(cont).forEach(key => dict.setValueForKey(cont[key] as any, key));
}
}
manager.requestSerializer.timeoutInterval = opts.timeout ? opts.timeout : 10;
let methods = {
'GET': 'GETParametersSuccessFailure',
'POST': 'POSTParametersSuccessFailure',
'PUT': 'PUTParametersSuccessFailure',
'DELETE': 'DELETEParametersSuccessFailure',
'PATCH': 'PATCHParametersSuccessFailure',
'HEAD': 'HEADParametersSuccessFailure',
};
manager[methods[opts.method]](opts.url, dict, function success(task: NSURLSessionDataTask, data: any) {
AFSuccess(resolve, task, data);
}, function failure(task, error) {
AFFailure(resolve, reject, task, error);
});
} catch (error) {
reject(error);
}
}).then((AFResponse: {
task: NSURLSessionDataTask
content: any
reason?: string
}) => {
let sendi: Https.HttpsResponse = {
content: AFResponse.content,
headers: {},
};
let response = AFResponse.task.response as NSHTTPURLResponse;
if (!isNullOrUndefined(response)) {
sendi.statusCode = response.statusCode;
let dict = response.allHeaderFields;
dict.enumerateKeysAndObjectsUsingBlock((k, v) => sendi.headers[k] = v);
}
if (AFResponse.reason) {
sendi.reason = AFResponse.reason;
}
return Promise.resolve(sendi);
});
}