You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

uri.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. // @flow
  2. import { parseURLParams } from './parseURLParams';
  3. import { normalizeNFKC } from './strings';
  4. /**
  5. * The app linking scheme.
  6. * TODO: This should be read from the manifest files later.
  7. */
  8. export const APP_LINK_SCHEME = 'org.jitsi.meet:';
  9. /**
  10. * A list of characters to be excluded/removed from the room component/segment
  11. * of a conference/meeting URI/URL. The list is based on RFC 3986 and the jxmpp
  12. * library utilized by jicofo.
  13. */
  14. const _ROOM_EXCLUDE_PATTERN = '[\\:\\?#\\[\\]@!$&\'()*+,;=></"]';
  15. /**
  16. * The {@link RegExp} pattern of the authority of a URI.
  17. *
  18. * @private
  19. * @type {string}
  20. */
  21. const _URI_AUTHORITY_PATTERN = '(//[^/?#]+)';
  22. /**
  23. * The {@link RegExp} pattern of the path of a URI.
  24. *
  25. * @private
  26. * @type {string}
  27. */
  28. const _URI_PATH_PATTERN = '([^?#]*)';
  29. /**
  30. * The {@link RegExp} pattern of the protocol of a URI.
  31. *
  32. * FIXME: The URL class exposed by JavaScript will not include the colon in
  33. * the protocol field. Also in other places (at the time of this writing:
  34. * the DeepLinkingMobilePage.js) the APP_LINK_SCHEME does not include
  35. * the double dots, so things are inconsistent.
  36. *
  37. * @type {string}
  38. */
  39. export const URI_PROTOCOL_PATTERN = '^([a-z][a-z0-9\\.\\+-]*:)';
  40. /**
  41. * Excludes/removes certain characters from a specific path part which are
  42. * incompatible with Jitsi Meet on the client and/or server sides. The main
  43. * use case for this method is to clean up the room name and the tenant.
  44. *
  45. * @param {?string} pathPart - The path part to fix.
  46. * @private
  47. * @returns {?string}
  48. */
  49. function _fixPathPart(pathPart: ?string) {
  50. return pathPart
  51. ? pathPart.replace(new RegExp(_ROOM_EXCLUDE_PATTERN, 'g'), '')
  52. : pathPart;
  53. }
  54. /**
  55. * Fixes the scheme part of a specific URI (string) so that it contains a
  56. * well-known scheme such as HTTP(S). For example, the mobile app implements an
  57. * app-specific URI scheme in addition to Universal Links. The app-specific
  58. * scheme may precede or replace the well-known scheme. In such a case, dealing
  59. * with the app-specific scheme only complicates the logic and it is simpler to
  60. * get rid of it (by translating the app-specific scheme into a well-known
  61. * scheme).
  62. *
  63. * @param {string} uri - The URI (string) to fix the scheme of.
  64. * @private
  65. * @returns {string}
  66. */
  67. function _fixURIStringScheme(uri: string) {
  68. const regex = new RegExp(`${URI_PROTOCOL_PATTERN}+`, 'gi');
  69. const match: Array<string> | null = regex.exec(uri);
  70. if (match) {
  71. // As an implementation convenience, pick up the last scheme and make
  72. // sure that it is a well-known one.
  73. let protocol = match[match.length - 1].toLowerCase();
  74. if (protocol !== 'http:' && protocol !== 'https:') {
  75. protocol = 'https:';
  76. }
  77. /* eslint-disable no-param-reassign */
  78. uri = uri.substring(regex.lastIndex);
  79. if (uri.startsWith('//')) {
  80. // The specified URL was not a room name only, it contained an
  81. // authority.
  82. uri = protocol + uri;
  83. }
  84. /* eslint-enable no-param-reassign */
  85. }
  86. return uri;
  87. }
  88. /**
  89. * Converts a path to a backend-safe format, by splitting the path '/' processing each part.
  90. * Properly lowercased and url encoded.
  91. *
  92. * @param {string?} path - The path to convert.
  93. * @returns {string?}
  94. */
  95. export function getBackendSafePath(path: ?string): ?string {
  96. if (!path) {
  97. return path;
  98. }
  99. return path
  100. .split('/')
  101. .map(getBackendSafeRoomName)
  102. .join('/');
  103. }
  104. /**
  105. * Converts a room name to a backend-safe format. Properly lowercased and url encoded.
  106. *
  107. * @param {string?} room - The room name to convert.
  108. * @returns {string?}
  109. */
  110. export function getBackendSafeRoomName(room: ?string): ?string {
  111. if (!room) {
  112. return room;
  113. }
  114. /* eslint-disable no-param-reassign */
  115. try {
  116. // We do not know if we get an already encoded string at this point
  117. // as different platforms do it differently, but we need a decoded one
  118. // for sure. However since decoding a non-encoded string is a noop, we're safe
  119. // doing it here.
  120. room = decodeURIComponent(room);
  121. } catch (e) {
  122. // This can happen though if we get an unencoded string and it contains
  123. // some characters that look like an encoded entity, but it's not.
  124. // But in this case we're fine goin on...
  125. }
  126. // Normalize the character set.
  127. room = normalizeNFKC(room);
  128. // Only decoded and normalized strings can be lowercased properly.
  129. room = room.toLowerCase();
  130. // But we still need to (re)encode it.
  131. room = encodeURIComponent(room);
  132. /* eslint-enable no-param-reassign */
  133. // Unfortunately we still need to lowercase it, because encoding a string will
  134. // add some uppercase characters, but some backend services
  135. // expect it to be full lowercase. However lowercasing an encoded string
  136. // doesn't change the string value.
  137. return room.toLowerCase();
  138. }
  139. /**
  140. * Gets the (Web application) context root defined by a specific location (URI).
  141. *
  142. * @param {Object} location - The location (URI) which defines the (Web
  143. * application) context root.
  144. * @public
  145. * @returns {string} - The (Web application) context root defined by the
  146. * specified {@code location} (URI).
  147. */
  148. export function getLocationContextRoot({ pathname }: { pathname: string }) {
  149. const contextRootEndIndex = pathname.lastIndexOf('/');
  150. return (
  151. contextRootEndIndex === -1
  152. ? '/'
  153. : pathname.substring(0, contextRootEndIndex + 1));
  154. }
  155. /**
  156. * Constructs a new {@code Array} with URL parameter {@code String}s out of a
  157. * specific {@code Object}.
  158. *
  159. * @param {Object} obj - The {@code Object} to turn into URL parameter
  160. * {@code String}s.
  161. * @returns {Array<string>} The {@code Array} with URL parameter {@code String}s
  162. * constructed out of the specified {@code obj}.
  163. */
  164. function _objectToURLParamsArray(obj = {}) {
  165. const params = [];
  166. for (const key in obj) { // eslint-disable-line guard-for-in
  167. try {
  168. params.push(
  169. `${key}=${encodeURIComponent(JSON.stringify(obj[key]))}`);
  170. } catch (e) {
  171. console.warn(`Error encoding ${key}: ${e}`);
  172. }
  173. }
  174. return params;
  175. }
  176. /**
  177. * Parses a specific URI string into an object with the well-known properties of
  178. * the {@link Location} and/or {@link URL} interfaces implemented by Web
  179. * browsers. The parsing attempts to be in accord with IETF's RFC 3986.
  180. *
  181. * @param {string} str - The URI string to parse.
  182. * @public
  183. * @returns {{
  184. * hash: string,
  185. * host: (string|undefined),
  186. * hostname: (string|undefined),
  187. * pathname: string,
  188. * port: (string|undefined),
  189. * protocol: (string|undefined),
  190. * search: string
  191. * }}
  192. */
  193. export function parseStandardURIString(str: string) {
  194. /* eslint-disable no-param-reassign */
  195. const obj: Object = {
  196. toString: _standardURIToString
  197. };
  198. let regex;
  199. let match: Array<string> | null;
  200. // XXX A URI string as defined by RFC 3986 does not contain any whitespace.
  201. // Usually, a browser will have already encoded any whitespace. In order to
  202. // avoid potential later problems related to whitespace in URI, strip any
  203. // whitespace. Anyway, the Jitsi Meet app is not known to utilize unencoded
  204. // whitespace so the stripping is deemed safe.
  205. str = str.replace(/\s/g, '');
  206. // protocol
  207. regex = new RegExp(URI_PROTOCOL_PATTERN, 'gi');
  208. match = regex.exec(str);
  209. if (match) {
  210. obj.protocol = match[1].toLowerCase();
  211. str = str.substring(regex.lastIndex);
  212. }
  213. // authority
  214. regex = new RegExp(`^${_URI_AUTHORITY_PATTERN}`, 'gi');
  215. match = regex.exec(str);
  216. if (match) {
  217. let authority: string = match[1].substring(/* // */ 2);
  218. str = str.substring(regex.lastIndex);
  219. // userinfo
  220. const userinfoEndIndex = authority.indexOf('@');
  221. if (userinfoEndIndex !== -1) {
  222. authority = authority.substring(userinfoEndIndex + 1);
  223. }
  224. obj.host = authority;
  225. // port
  226. const portBeginIndex = authority.lastIndexOf(':');
  227. if (portBeginIndex !== -1) {
  228. obj.port = authority.substring(portBeginIndex + 1);
  229. authority = authority.substring(0, portBeginIndex);
  230. }
  231. // hostname
  232. obj.hostname = authority;
  233. }
  234. // pathname
  235. regex = new RegExp(`^${_URI_PATH_PATTERN}`, 'gi');
  236. match = regex.exec(str);
  237. let pathname: ?string;
  238. if (match) {
  239. pathname = match[1];
  240. str = str.substring(regex.lastIndex);
  241. }
  242. if (pathname) {
  243. pathname.startsWith('/') || (pathname = `/${pathname}`);
  244. } else {
  245. pathname = '/';
  246. }
  247. obj.pathname = pathname;
  248. // query
  249. if (str.startsWith('?')) {
  250. let hashBeginIndex = str.indexOf('#', 1);
  251. if (hashBeginIndex === -1) {
  252. hashBeginIndex = str.length;
  253. }
  254. obj.search = str.substring(0, hashBeginIndex);
  255. str = str.substring(hashBeginIndex);
  256. } else {
  257. obj.search = ''; // Google Chrome
  258. }
  259. // fragment
  260. obj.hash = str.startsWith('#') ? str : '';
  261. /* eslint-enable no-param-reassign */
  262. return obj;
  263. }
  264. /**
  265. * Parses a specific URI which (supposedly) references a Jitsi Meet resource
  266. * (location).
  267. *
  268. * @param {(string|undefined)} uri - The URI to parse which (supposedly)
  269. * references a Jitsi Meet resource (location).
  270. * @public
  271. * @returns {{
  272. * contextRoot: string,
  273. * hash: string,
  274. * host: string,
  275. * hostname: string,
  276. * pathname: string,
  277. * port: string,
  278. * protocol: string,
  279. * room: (string|undefined),
  280. * search: string
  281. * }}
  282. */
  283. export function parseURIString(uri: ?string) {
  284. if (typeof uri !== 'string') {
  285. return undefined;
  286. }
  287. const obj = parseStandardURIString(_fixURIStringScheme(uri));
  288. // XXX While the components/segments of pathname are URI encoded, Jitsi Meet
  289. // on the client and/or server sides still don't support certain characters.
  290. obj.pathname = obj.pathname.split('/').map(pathPart => _fixPathPart(pathPart))
  291. .join('/');
  292. // Add the properties that are specific to a Jitsi Meet resource (location)
  293. // such as contextRoot, room:
  294. // contextRoot
  295. obj.contextRoot = getLocationContextRoot(obj);
  296. // The room (name) is the last component/segment of pathname.
  297. const { pathname } = obj;
  298. const contextRootEndIndex = pathname.lastIndexOf('/');
  299. obj.room = pathname.substring(contextRootEndIndex + 1) || undefined;
  300. if (contextRootEndIndex > 1) {
  301. // The part of the pathname from the beginning to the room name is the tenant.
  302. obj.tenant = pathname.substring(1, contextRootEndIndex);
  303. }
  304. return obj;
  305. }
  306. /**
  307. * Implements {@code href} and {@code toString} for the {@code Object} returned
  308. * by {@link #parseStandardURIString}.
  309. *
  310. * @param {Object} [thiz] - An {@code Object} returned by
  311. * {@code #parseStandardURIString} if any; otherwise, it is presumed that the
  312. * function is invoked on such an instance.
  313. * @returns {string}
  314. */
  315. function _standardURIToString(thiz: ?Object) {
  316. // eslint-disable-next-line no-invalid-this
  317. const { hash, host, pathname, protocol, search } = thiz || this;
  318. let str = '';
  319. protocol && (str += protocol);
  320. // TODO userinfo
  321. host && (str += `//${host}`);
  322. str += pathname || '/';
  323. search && (str += search);
  324. hash && (str += hash);
  325. return str;
  326. }
  327. /**
  328. * Sometimes we receive strings that we don't know if already percent-encoded, or not, due to the
  329. * various sources we get URLs or room names. This function encapsulates the decoding in a safe way.
  330. *
  331. * @param {string} text - The text to decode.
  332. * @returns {string}
  333. */
  334. export function safeDecodeURIComponent(text: string) {
  335. try {
  336. return decodeURIComponent(text);
  337. } catch (e) {
  338. // The text wasn't encoded.
  339. }
  340. return text;
  341. }
  342. /**
  343. * Attempts to return a {@code String} representation of a specific
  344. * {@code Object} which is supposed to represent a URL. Obviously, if a
  345. * {@code String} is specified, it is returned. If a {@code URL} is specified,
  346. * its {@code URL#href} is returned. Additionally, an {@code Object} similar to
  347. * the one accepted by the constructor of Web's ExternalAPI is supported on both
  348. * mobile/React Native and Web/React.
  349. *
  350. * @param {Object|string} obj - The URL to return a {@code String}
  351. * representation of.
  352. * @returns {string} - A {@code String} representation of the specified
  353. * {@code obj} which is supposed to represent a URL.
  354. */
  355. export function toURLString(obj: ?(Object | string)): ?string {
  356. let str;
  357. switch (typeof obj) {
  358. case 'object':
  359. if (obj) {
  360. if (obj instanceof URL) {
  361. str = obj.href;
  362. } else {
  363. str = urlObjectToString(obj);
  364. }
  365. }
  366. break;
  367. case 'string':
  368. str = String(obj);
  369. break;
  370. }
  371. return str;
  372. }
  373. /**
  374. * Attempts to return a {@code String} representation of a specific
  375. * {@code Object} similar to the one accepted by the constructor
  376. * of Web's ExternalAPI.
  377. *
  378. * @param {Object} o - The URL to return a {@code String} representation of.
  379. * @returns {string} - A {@code String} representation of the specified
  380. * {@code Object}.
  381. */
  382. export function urlObjectToString(o: Object): ?string {
  383. // First normalize the given url. It come as o.url or split into o.serverURL
  384. // and o.room.
  385. let tmp;
  386. if (o.serverURL && o.room) {
  387. tmp = new URL(o.room, o.serverURL).toString();
  388. } else if (o.room) {
  389. tmp = o.room;
  390. } else {
  391. tmp = o.url || '';
  392. }
  393. const url = parseStandardURIString(_fixURIStringScheme(tmp));
  394. // protocol
  395. if (!url.protocol) {
  396. let protocol: ?string = o.protocol || o.scheme;
  397. if (protocol) {
  398. // Protocol is supposed to be the scheme and the final ':'. Anyway,
  399. // do not make a fuss if the final ':' is not there.
  400. protocol.endsWith(':') || (protocol += ':');
  401. url.protocol = protocol;
  402. }
  403. }
  404. // authority & pathname
  405. let { pathname } = url;
  406. if (!url.host) {
  407. // Web's ExternalAPI domain
  408. //
  409. // It may be host/hostname and pathname with the latter denoting the
  410. // tenant.
  411. const domain: ?string = o.domain || o.host || o.hostname;
  412. if (domain) {
  413. const { host, hostname, pathname: contextRoot, port }
  414. = parseStandardURIString(
  415. // XXX The value of domain in supposed to be host/hostname
  416. // and, optionally, pathname. Make sure it is not taken for
  417. // a pathname only.
  418. _fixURIStringScheme(`${APP_LINK_SCHEME}//${domain}`));
  419. // authority
  420. if (host) {
  421. url.host = host;
  422. url.hostname = hostname;
  423. url.port = port;
  424. }
  425. // pathname
  426. pathname === '/' && contextRoot !== '/' && (pathname = contextRoot);
  427. }
  428. }
  429. // pathname
  430. // Web's ExternalAPI roomName
  431. const room = o.roomName || o.room;
  432. if (room
  433. && (url.pathname.endsWith('/')
  434. || !url.pathname.endsWith(`/${room}`))) {
  435. pathname.endsWith('/') || (pathname += '/');
  436. pathname += room;
  437. }
  438. url.pathname = pathname;
  439. // query/search
  440. // Web's ExternalAPI jwt
  441. const { jwt } = o;
  442. if (jwt) {
  443. let { search } = url;
  444. if (search.indexOf('?jwt=') === -1 && search.indexOf('&jwt=') === -1) {
  445. search.startsWith('?') || (search = `?${search}`);
  446. search.length === 1 || (search += '&');
  447. search += `jwt=${jwt}`;
  448. url.search = search;
  449. }
  450. }
  451. // fragment/hash
  452. let { hash } = url;
  453. for (const urlPrefix of [ 'config', 'interfaceConfig', 'devices', 'userInfo', 'appData' ]) {
  454. const urlParamsArray
  455. = _objectToURLParamsArray(
  456. o[`${urlPrefix}Overwrite`]
  457. || o[urlPrefix]
  458. || o[`${urlPrefix}Override`]);
  459. if (urlParamsArray.length) {
  460. let urlParamsString
  461. = `${urlPrefix}.${urlParamsArray.join(`&${urlPrefix}.`)}`;
  462. if (hash.length) {
  463. urlParamsString = `&${urlParamsString}`;
  464. } else {
  465. hash = '#';
  466. }
  467. hash += urlParamsString;
  468. }
  469. }
  470. url.hash = hash;
  471. return url.toString() || undefined;
  472. }
  473. /**
  474. * Adds hash params to URL.
  475. *
  476. * @param {URL} url - The URL.
  477. * @param {Object} hashParamsToAdd - A map with the parameters to be set.
  478. * @returns {URL} - The new URL.
  479. */
  480. export function addHashParamsToURL(url: URL, hashParamsToAdd: Object = {}) {
  481. const params = parseURLParams(url);
  482. const urlParamsArray = _objectToURLParamsArray({
  483. ...params,
  484. ...hashParamsToAdd
  485. });
  486. if (urlParamsArray.length) {
  487. url.hash = `#${urlParamsArray.join('&')}`;
  488. }
  489. return url;
  490. }
  491. /**
  492. * Returns the decoded URI.
  493. *
  494. * @param {string} uri - The URI to decode.
  495. * @returns {string}
  496. */
  497. export function getDecodedURI(uri: string) {
  498. return decodeURI(uri.replace(/^https?:\/\//i, ''));
  499. }