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.ts 18KB

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