api.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. * vim: ts=4:sw=4:expandtab
  3. */
  4. function PortManager(ports) {
  5. this.ports = ports;
  6. this.idx = 0;
  7. }
  8. PortManager.prototype = {
  9. constructor: PortManager,
  10. getPort: function() {
  11. var port = this.ports[this.idx];
  12. this.idx = (this.idx + 1) % this.ports.length;
  13. return port;
  14. }
  15. };
  16. var TextSecureServer = (function() {
  17. 'use strict';
  18. function validateResponse(response, schema) {
  19. try {
  20. for (var i in schema) {
  21. switch (schema[i]) {
  22. case 'object':
  23. case 'string':
  24. case 'number':
  25. if (typeof response[i] !== schema[i]) {
  26. return false;
  27. }
  28. break;
  29. }
  30. }
  31. } catch(ex) {
  32. return false;
  33. }
  34. return true;
  35. }
  36. // Promise-based async xhr routine
  37. function promise_ajax(url, options) {
  38. return new Promise(function (resolve, reject) {
  39. if (!url) {
  40. url = options.host + ':' + options.port + '/' + options.path;
  41. }
  42. console.log(options.type, url);
  43. var xhr = new XMLHttpRequest();
  44. xhr.open(options.type, url, true /*async*/);
  45. if ( options.responseType ) {
  46. xhr[ 'responseType' ] = options.responseType;
  47. }
  48. if (options.user && options.password) {
  49. xhr.setRequestHeader("Authorization", "Basic " + btoa(getString(options.user) + ":" + getString(options.password)));
  50. }
  51. if (options.contentType) {
  52. xhr.setRequestHeader( "Content-Type", options.contentType );
  53. }
  54. xhr.setRequestHeader( 'X-Signal-Agent', 'OWD' );
  55. xhr.onload = function() {
  56. var result = xhr.response;
  57. if ( (!xhr.responseType || xhr.responseType === "text") &&
  58. typeof xhr.responseText === "string" ) {
  59. result = xhr.responseText;
  60. }
  61. if (options.dataType === 'json') {
  62. try { result = JSON.parse(xhr.responseText + ''); } catch(e) {}
  63. if (options.validateResponse) {
  64. if (!validateResponse(result, options.validateResponse)) {
  65. console.log(options.type, url, xhr.status, 'Error');
  66. reject(HTTPError(xhr.status, result, options.stack));
  67. }
  68. }
  69. }
  70. if ( 0 <= xhr.status && xhr.status < 400) {
  71. console.log(options.type, url, xhr.status, 'Success');
  72. resolve(result, xhr.status);
  73. } else {
  74. console.log(options.type, url, xhr.status, 'Error');
  75. reject(HTTPError(xhr.status, result, options.stack));
  76. }
  77. };
  78. xhr.onerror = function() {
  79. console.log(options.type, url, xhr.status, 'Error');
  80. reject(HTTPError(xhr.status, null, options.stack));
  81. };
  82. xhr.send( options.data || null );
  83. });
  84. }
  85. function retry_ajax(url, options, limit, count) {
  86. count = count || 0;
  87. limit = limit || 3;
  88. if (options.ports) {
  89. options.port = options.ports[count % options.ports.length];
  90. }
  91. count++;
  92. return promise_ajax(url, options).catch(function(e) {
  93. if (e.name === 'HTTPError' && e.code === -1 && count < limit) {
  94. return new Promise(function(resolve) {
  95. setTimeout(function() {
  96. resolve(retry_ajax(url, options, limit, count));
  97. }, 1000);
  98. });
  99. } else {
  100. throw e;
  101. }
  102. });
  103. }
  104. function ajax(url, options) {
  105. options.stack = new Error().stack; // just in case, save stack here.
  106. return retry_ajax(url, options);
  107. }
  108. function HTTPError(code, response, stack) {
  109. if (code > 999 || code < 100) {
  110. code = -1;
  111. }
  112. var e = new Error();
  113. e.name = 'HTTPError';
  114. e.code = code;
  115. e.stack = stack;
  116. if (response) {
  117. e.response = response;
  118. }
  119. return e;
  120. }
  121. var URL_CALLS = {
  122. accounts : "v1/accounts",
  123. devices : "v1/devices",
  124. keys : "v2/keys",
  125. signed : "v2/keys/signed",
  126. messages : "v1/messages",
  127. attachment : "v1/attachments"
  128. };
  129. function TextSecureServer(url, ports, username, password) {
  130. if (typeof url !== 'string') {
  131. throw new Error('Invalid server url');
  132. }
  133. this.portManager = new PortManager(ports);
  134. this.url = url;
  135. this.username = username;
  136. this.password = password;
  137. }
  138. TextSecureServer.prototype = {
  139. constructor: TextSecureServer,
  140. getUrl: function() {
  141. return this.url + ':' + this.portManager.getPort();
  142. },
  143. ajax: function(param) {
  144. if (!param.urlParameters) {
  145. param.urlParameters = '';
  146. }
  147. return ajax(null, {
  148. host : this.url,
  149. ports : this.portManager.ports,
  150. path : URL_CALLS[param.call] + param.urlParameters,
  151. type : param.httpType,
  152. data : param.jsonData && textsecure.utils.jsonThing(param.jsonData),
  153. contentType : 'application/json; charset=utf-8',
  154. dataType : 'json',
  155. user : this.username,
  156. password : this.password,
  157. validateResponse: param.validateResponse
  158. }).catch(function(e) {
  159. var code = e.code;
  160. if (code === 200) {
  161. // happens sometimes when we get no response
  162. // (TODO: Fix server to return 204? instead)
  163. return null;
  164. }
  165. var message;
  166. switch (code) {
  167. case -1:
  168. message = "Failed to connect to the server, please check your network connection.";
  169. break;
  170. case 413:
  171. message = "Rate limit exceeded, please try again later.";
  172. break;
  173. case 403:
  174. message = "Invalid code, please try again.";
  175. break;
  176. case 417:
  177. // TODO: This shouldn't be a thing?, but its in the API doc?
  178. message = "Number already registered.";
  179. break;
  180. case 401:
  181. message = "Invalid authentication, most likely someone re-registered and invalidated our registration.";
  182. break;
  183. case 404:
  184. message = "Number is not registered.";
  185. break;
  186. default:
  187. message = "The server rejected our query, please file a bug report.";
  188. }
  189. e.message = message
  190. throw e;
  191. });
  192. },
  193. requestVerificationSMS: function(number) {
  194. return this.ajax({
  195. call : 'accounts',
  196. httpType : 'GET',
  197. urlParameters : '/sms/code/' + number,
  198. });
  199. },
  200. requestVerificationVoice: function(number) {
  201. return this.ajax({
  202. call : 'accounts',
  203. httpType : 'GET',
  204. urlParameters : '/voice/code/' + number,
  205. });
  206. },
  207. confirmCode: function(number, code, password, signaling_key, registrationId, deviceName) {
  208. var jsonData = {
  209. signalingKey : btoa(getString(signaling_key)),
  210. supportsSms : false,
  211. fetchesMessages : true,
  212. registrationId : registrationId,
  213. };
  214. var call, urlPrefix, schema;
  215. if (deviceName) {
  216. jsonData.name = deviceName;
  217. call = 'devices';
  218. urlPrefix = '/';
  219. schema = { deviceId: 'number' };
  220. } else {
  221. call = 'accounts';
  222. urlPrefix = '/code/';
  223. }
  224. this.username = number;
  225. this.password = password;
  226. return this.ajax({
  227. call : call,
  228. httpType : 'PUT',
  229. urlParameters : urlPrefix + code,
  230. jsonData : jsonData,
  231. validateResponse : schema
  232. });
  233. },
  234. getDevices: function(number) {
  235. return this.ajax({
  236. call : 'devices',
  237. httpType : 'GET',
  238. });
  239. },
  240. registerKeys: function(genKeys) {
  241. var keys = {};
  242. keys.identityKey = btoa(getString(genKeys.identityKey));
  243. keys.signedPreKey = {
  244. keyId: genKeys.signedPreKey.keyId,
  245. publicKey: btoa(getString(genKeys.signedPreKey.publicKey)),
  246. signature: btoa(getString(genKeys.signedPreKey.signature))
  247. };
  248. keys.preKeys = [];
  249. var j = 0;
  250. for (var i in genKeys.preKeys) {
  251. keys.preKeys[j++] = {
  252. keyId: genKeys.preKeys[i].keyId,
  253. publicKey: btoa(getString(genKeys.preKeys[i].publicKey))
  254. };
  255. }
  256. // This is just to make the server happy
  257. // (v2 clients should choke on publicKey)
  258. keys.lastResortKey = {keyId: 0x7fffFFFF, publicKey: btoa("42")};
  259. return this.ajax({
  260. call : 'keys',
  261. httpType : 'PUT',
  262. jsonData : keys,
  263. });
  264. },
  265. setSignedPreKey: function(signedPreKey) {
  266. return this.ajax({
  267. call : 'signed',
  268. httpType : 'PUT',
  269. jsonData : {
  270. keyId: signedPreKey.keyId,
  271. publicKey: btoa(getString(signedPreKey.publicKey)),
  272. signature: btoa(getString(signedPreKey.signature))
  273. }
  274. });
  275. },
  276. getMyKeys: function(number, deviceId) {
  277. return this.ajax({
  278. call : 'keys',
  279. httpType : 'GET',
  280. validateResponse : {count: 'number'}
  281. }).then(function(res) {
  282. return res.count;
  283. });
  284. },
  285. getKeysForNumber: function(number, deviceId) {
  286. if (deviceId === undefined)
  287. deviceId = "*";
  288. return this.ajax({
  289. call : 'keys',
  290. httpType : 'GET',
  291. urlParameters : "/" + number + "/" + deviceId,
  292. validateResponse : {identityKey: 'string', devices: 'object'}
  293. }).then(function(res) {
  294. if (res.devices.constructor !== Array) {
  295. throw new Error("Invalid response");
  296. }
  297. res.identityKey = StringView.base64ToBytes(res.identityKey);
  298. res.devices.forEach(function(device) {
  299. if ( !validateResponse(device, {signedPreKey: 'object'}) ||
  300. !validateResponse(device.signedPreKey, {publicKey: 'string', signature: 'string'}) ) {
  301. throw new Error("Invalid signedPreKey");
  302. }
  303. if ( device.preKey ) {
  304. if ( !validateResponse(device, {preKey: 'object'}) ||
  305. !validateResponse(device.preKey, {publicKey: 'string'})) {
  306. throw new Error("Invalid preKey");
  307. }
  308. device.preKey.publicKey = StringView.base64ToBytes(device.preKey.publicKey);
  309. }
  310. device.signedPreKey.publicKey = StringView.base64ToBytes(device.signedPreKey.publicKey);
  311. device.signedPreKey.signature = StringView.base64ToBytes(device.signedPreKey.signature);
  312. });
  313. return res;
  314. });
  315. },
  316. sendMessages: function(destination, messageArray, timestamp) {
  317. var jsonData = { messages: messageArray, timestamp: timestamp};
  318. return this.ajax({
  319. call : 'messages',
  320. httpType : 'PUT',
  321. urlParameters : '/' + destination,
  322. jsonData : jsonData,
  323. });
  324. },
  325. getAttachment: function(id) {
  326. return this.ajax({
  327. call : 'attachment',
  328. httpType : 'GET',
  329. urlParameters : '/' + id,
  330. validateResponse : {location: 'string'}
  331. }).then(function(response) {
  332. return ajax(response.location, {
  333. type : "GET",
  334. responseType: "arraybuffer",
  335. contentType : "application/octet-stream"
  336. });
  337. }.bind(this));
  338. },
  339. putAttachment: function(encryptedBin) {
  340. return this.ajax({
  341. call : 'attachment',
  342. httpType : 'GET',
  343. }).then(function(response) {
  344. return ajax(response.location, {
  345. type : "PUT",
  346. contentType : "application/octet-stream",
  347. data : encryptedBin,
  348. processData : false,
  349. }).then(function() {
  350. return response.idString;
  351. }.bind(this));
  352. }.bind(this));
  353. },
  354. getMessageSocket: function() {
  355. var url = this.getUrl();
  356. console.log('opening message socket', url);
  357. return new WebSocket(
  358. url.replace('https://', 'wss://').replace('http://', 'ws://')
  359. + '/v1/websocket/?login=' + encodeURIComponent(this.username)
  360. + '&password=' + encodeURIComponent(this.password)
  361. + '&agent=OWD'
  362. );
  363. },
  364. getProvisioningSocket: function () {
  365. var url = this.getUrl();
  366. console.log('opening provisioning socket', url);
  367. return new WebSocket(
  368. url.replace('https://', 'wss://').replace('http://', 'ws://')
  369. + '/v1/websocket/provisioning/?agent=OWD'
  370. );
  371. }
  372. };
  373. return TextSecureServer;
  374. })();