forked from nativescript-community/https
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttps.ios.ts
268 lines (226 loc) · 8.53 KB
/
https.ios.ts
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
//
import * as application from 'application'
import { HttpRequestOptions, Headers, HttpResponse } from 'http'
import { isDefined, isNullOrUndefined, isObject } from '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) {
// console.log('options', options)
if (!policies.secure) {
policies.secure = AFSecurityPolicy.policyWithPinningMode(AFSSLPinningMode.PublicKey)
let allowInvalidCertificates = (isDefined(options.allowInvalidCertificates)) ? options.allowInvalidCertificates : false
policies.secure.allowInvalidCertificates = allowInvalidCertificates
let validatesDomainName = (isDefined(options.validatesDomainName)) ? options.validatesDomainName : true
policies.secure.validatesDomainName = validatesDomainName
let data = NSData.dataWithContentsOfFile(options.certificate)
// console.log('data.description', data.description)
// console.log('data.bytes', data.bytes)
// console.log('data.base64Encoding()', data.base64Encoding())
// console.log('data.length', data.length)
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>) {
// console.log('AFSuccess')
let content: any
if (data && data.class) {
// console.log('data.class().name', data.class().name)
if (data.enumerateKeysAndObjectsUsingBlock || data.class().name == 'NSArray') {
// content = {}
// data.enumerateKeysAndObjectsUsingBlock(function(k, v) {
// console.log('v.description', v.description)
// content[k] = v
// })
let serial = NSJSONSerialization.dataWithJSONObjectOptionsError(data, NSJSONWritingOptions.PrettyPrinted)
content = NSString.alloc().initWithDataEncoding(serial, NSUTF8StringEncoding).toString()
// console.log('content', content)
} else if (data.class().name == 'NSData') {
content = NSString.alloc().initWithDataEncoding(data, NSASCIIStringEncoding).toString()
// } else if (data.class().name == 'NSArray') {
// content = []
// let i: number, len: number = data.count
// for (i = 0; i < len; i++) {
// let item
// let result: NSDictionary<string, any> = data[i]
// if (result.enumerateKeysAndObjectsUsingBlock) {
// item = {}
// result.enumerateKeysAndObjectsUsingBlock(function(k, v) {
// item[k] = v
// })
// } else {
// item = data[i]
// }
// content.push(item)
// }
} else {
content = data
}
try {
content = JSON.parse(content)
} catch (e) { }
} else {
content = data
}
resolve({ task, content })
}
function AFFailure(resolve, reject, task: NSURLSessionDataTask, error: NSError) {
// console.error('AFFailure')
// console.log('error.description', error.description)
// console.log('error.userInfo.description', error.userInfo.description)
// console.log('error.localizedDescription', error.localizedDescription)
let data: NSData = error.userInfo.valueForKey(AFNetworkingOperationFailingURLResponseDataErrorKey)
let body = NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding).toString()
try {
body = JSON.parse(body)
} catch (e) { }
let content: any = {
body,
description: error.description,
reason: error.localizedDescription,
url: error.userInfo.objectForKey('NSErrorFailingURLKey').description
}
// console.log('content.url', content.url)
// try {
// content.body = JSON.parse(body.description)
// } catch (e) {
if (policies.secured == true) {
// console.log('error.description', error.description)
// console.log('error.userInfo.description', error.userInfo.description)
content.description = 'nativescript-https > Invalid SSL certificate! ' + content.description
// return reject(content)
}
// }
// console.log('error.description', error.description)
// console.keys('error', error)
// console.keys('error.userInfo', error.userInfo)
// error.userInfo.enumerateKeysAndObjectsUsingBlock(function(k, v) {
// console.log('k', k)
// console.log('v.description', v.description)
// })
// let keys = error.userInfo.allKeysForObject(error.userInfo)
// console.log('keys.description', keys.description)
// let url = error.valueForKey('URL')
// console.error('url', url)
// if (!isNullOrUndefined(task.response)) {
// content.URL = task.response.URL
// }
let reason = error.localizedDescription
resolve({ task, content, reason })
}
export function request(opts: Https.HttpsRequestOptions): Promise<Https.HttpsResponse> {
return new Promise(function(resolve, reject) {
try {
let manager = AFHTTPSessionManager.manager()
if (opts.headers && opts.headers['Content-Type'] == 'application/json') {
manager.requestSerializer = AFJSONRequestSerializer.serializer()
manager.responseSerializer = AFJSONResponseSerializer.serializerWithReadingOptions(NSJSONReadingOptions.AllowFragments)
} else {
manager.requestSerializer = AFHTTPRequestSerializer.serializer()
// manager.responseSerializer = AFXMLParserResponseSerializer.serializer()
manager.responseSerializer = AFHTTPResponseSerializer.serializer()
// manager.responseSerializer.acceptableContentTypes = NSSet.setWithObject('text/html')
// manager.responseSerializer.acceptableContentTypes = NSSet.setWithObject('application/json')
}
manager.requestSerializer.allowsCellularAccess = true
manager.securityPolicy = (policies.secured == true) ? policies.secure : policies.def
manager.requestSerializer.timeoutInterval = 10
let heads = opts.headers
if (heads) {
Object.keys(heads).forEach(function(key) {
manager.requestSerializer.setValueForHTTPHeaderField(heads[key] as any, key)
})
}
let dict: NSMutableDictionary<string, any> = null
if (opts.body) {
let cont = opts.body
if (isObject(cont)) {
dict = NSMutableDictionary.new<string, any>()
Object.keys(cont).forEach(function(key) {
dict.setValueForKey(cont[key] as any, key)
})
}
}
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)
})
// if (opts.method == 'GET') {
// manager.GETParametersSuccessFailure(opts.url, dict, function success(task: NSURLSessionDataTask, data: any) {
// AFSuccess(resolve, task, data)
// }, function failure(task, error) {
// AFFailure(resolve, reject, task, error)
// })
// } else if (opts.method == 'POST') {
// manager.POSTParametersSuccessFailure(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(function(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(function(k, v) {
sendi.headers[k] = v
})
}
if (AFResponse.reason) {
sendi.reason = AFResponse.reason
}
return Promise.resolve(sendi)
})
// {
// "content": {
// "code": "PreconditionFailed",
// "message": "!x-uuid"
// },
// "statusCode": 412,
// "headers": {
// "Content-Length": "49",
// "Server": "nginx/1.10.1",
// "Content-Type": "application/json",
// "Connection": "keep-alive",
// "Date": "Mon, 26 Dec 2016 03:31:42 GMT"
// }
// }
}
export * from './https.common'