api.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. import {browserHistory} from 'react-router';
  2. import * as Sentry from '@sentry/react';
  3. import Cookies from 'js-cookie';
  4. import * as qs from 'query-string';
  5. import {redirectToProject} from 'sentry/actionCreators/redirectToProject';
  6. import {openSudo} from 'sentry/actionCreators/sudoModal';
  7. import {EXPERIMENTAL_SPA} from 'sentry/constants';
  8. import {
  9. PROJECT_MOVED,
  10. SUDO_REQUIRED,
  11. SUPERUSER_REQUIRED,
  12. } from 'sentry/constants/apiErrorCodes';
  13. import controlsilopatterns from 'sentry/data/controlsiloUrlPatterns';
  14. import {metric} from 'sentry/utils/analytics';
  15. import getCsrfToken from 'sentry/utils/getCsrfToken';
  16. import {uniqueId} from 'sentry/utils/guid';
  17. import RequestError from 'sentry/utils/requestError/requestError';
  18. import {sanitizePath} from 'sentry/utils/requestError/sanitizePath';
  19. import ConfigStore from './stores/configStore';
  20. import OrganizationStore from './stores/organizationStore';
  21. export class Request {
  22. /**
  23. * Is the request still in flight
  24. */
  25. alive: boolean;
  26. /**
  27. * Promise which will be resolved when the request has completed
  28. */
  29. requestPromise: Promise<Response>;
  30. /**
  31. * AbortController to cancel the in-flight request. This will not be set in
  32. * unsupported browsers.
  33. */
  34. aborter?: AbortController;
  35. constructor(requestPromise: Promise<Response>, aborter?: AbortController) {
  36. this.requestPromise = requestPromise;
  37. this.aborter = aborter;
  38. this.alive = true;
  39. }
  40. cancel() {
  41. this.alive = false;
  42. this.aborter?.abort();
  43. metric('app.api.request-abort', 1);
  44. }
  45. }
  46. export type ApiResult<Data = any> = [
  47. data: Data,
  48. statusText: string | undefined,
  49. resp: ResponseMeta | undefined,
  50. ];
  51. export type ResponseMeta<R = any> = {
  52. /**
  53. * Get a header value from the response
  54. */
  55. getResponseHeader: (header: string) => string | null;
  56. /**
  57. * The response body decoded from json
  58. */
  59. responseJSON: R;
  60. /**
  61. * The string value of the response
  62. */
  63. responseText: string;
  64. /**
  65. * The response status code
  66. */
  67. status: Response['status'];
  68. /**
  69. * The response status code text
  70. */
  71. statusText: Response['statusText'];
  72. };
  73. /**
  74. * Check if the requested method does not require CSRF tokens
  75. */
  76. function csrfSafeMethod(method?: string): boolean {
  77. // these HTTP methods do not require CSRF protection
  78. return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method ?? '');
  79. }
  80. /**
  81. * Check if we a request is going to the same or similar origin.
  82. * similar origins are those that share an ancestor. Example `sentry.sentry.io` and `us.sentry.io`
  83. * are similar origins, but sentry.sentry.io and sentry.example.io are not.
  84. */
  85. export function isSimilarOrigin(target: string, origin: string): boolean {
  86. const targetUrl = new URL(target, origin);
  87. const originUrl = new URL(origin);
  88. // If one of the domains is a child of the other.
  89. if (
  90. originUrl.hostname.endsWith(targetUrl.hostname) ||
  91. targetUrl.hostname.endsWith(originUrl.hostname)
  92. ) {
  93. return true;
  94. }
  95. // Check if the target and origin are on sibiling subdomains.
  96. const targetHost = targetUrl.hostname.split('.');
  97. const originHost = originUrl.hostname.split('.');
  98. // Remove the subdomains. If don't have at least 2 segments we aren't subdomains.
  99. targetHost.shift();
  100. originHost.shift();
  101. if (targetHost.length < 2 || originHost.length < 2) {
  102. return false;
  103. }
  104. return targetHost.join('.') === originHost.join('.');
  105. }
  106. // TODO: Need better way of identifying anonymous pages that don't trigger redirect
  107. const ALLOWED_ANON_PAGES = [
  108. /^\/accept\//,
  109. /^\/share\//,
  110. /^\/auth\/login\//,
  111. /^\/join-request\//,
  112. /^\/unsubscribe\//,
  113. ];
  114. /**
  115. * Return true if we should skip calling the normal error handler
  116. */
  117. const globalErrorHandlers: ((resp: ResponseMeta) => boolean)[] = [];
  118. export const initApiClientErrorHandling = () =>
  119. globalErrorHandlers.push((resp: ResponseMeta) => {
  120. const pageAllowsAnon = ALLOWED_ANON_PAGES.find(regex =>
  121. regex.test(window.location.pathname)
  122. );
  123. // Ignore error unless it is a 401
  124. if (!resp || resp.status !== 401 || pageAllowsAnon) {
  125. return false;
  126. }
  127. const code = resp?.responseJSON?.detail?.code;
  128. const extra = resp?.responseJSON?.detail?.extra;
  129. // 401s can also mean sudo is required or it's a request that is allowed to fail
  130. // Ignore if these are the cases
  131. if (
  132. [
  133. 'sudo-required',
  134. 'ignore',
  135. '2fa-required',
  136. 'app-connect-authentication-error',
  137. ].includes(code)
  138. ) {
  139. return false;
  140. }
  141. // If user must login via SSO, redirect to org login page
  142. if (code === 'sso-required') {
  143. window.location.assign(extra.loginUrl);
  144. return true;
  145. }
  146. if (code === 'member-disabled-over-limit') {
  147. browserHistory.replace(extra.next);
  148. return true;
  149. }
  150. // Otherwise, the user has become unauthenticated. Send them to auth
  151. Cookies.set('session_expired', '1');
  152. if (EXPERIMENTAL_SPA) {
  153. browserHistory.replace('/auth/login/');
  154. } else {
  155. window.location.reload();
  156. }
  157. return true;
  158. });
  159. /**
  160. * Construct a full request URL
  161. */
  162. function buildRequestUrl(baseUrl: string, path: string, options: RequestOptions) {
  163. let params: string;
  164. try {
  165. params = qs.stringify(options.query ?? []);
  166. } catch (err) {
  167. Sentry.withScope(scope => {
  168. scope.setExtra('path', path);
  169. scope.setExtra('query', options.query);
  170. Sentry.captureException(err);
  171. });
  172. throw err;
  173. }
  174. // Append the baseUrl if required
  175. let fullUrl = path.includes(baseUrl) ? path : baseUrl + path;
  176. // Apply path and domain transforms for hybrid-cloud
  177. fullUrl = resolveHostname(fullUrl, options.host);
  178. // Append query parameters
  179. if (params) {
  180. fullUrl += fullUrl.includes('?') ? `&${params}` : `?${params}`;
  181. }
  182. return fullUrl;
  183. }
  184. /**
  185. * Check if the API response says project has been renamed. If so, redirect
  186. * user to new project slug
  187. */
  188. // TODO(ts): refine this type later
  189. export function hasProjectBeenRenamed(response: ResponseMeta) {
  190. const code = response?.responseJSON?.detail?.code;
  191. // XXX(billy): This actually will never happen because we can't intercept the 302
  192. // jQuery ajax will follow the redirect by default...
  193. //
  194. // TODO(epurkhiser): We use fetch now, is the above comment still true?
  195. if (code !== PROJECT_MOVED) {
  196. return false;
  197. }
  198. const slug = response?.responseJSON?.detail?.extra?.slug;
  199. redirectToProject(slug);
  200. return true;
  201. }
  202. // TODO(ts): move this somewhere
  203. export type APIRequestMethod = 'POST' | 'GET' | 'DELETE' | 'PUT';
  204. type FunctionCallback<Args extends any[] = any[]> = (...args: Args) => void;
  205. export type RequestCallbacks = {
  206. /**
  207. * Callback for the request completing (success or error)
  208. */
  209. complete?: (resp: ResponseMeta, textStatus: string) => void;
  210. /**
  211. * Callback for the request failing with an error
  212. */
  213. // TODO(ts): Update this when sentry is mostly migrated to TS
  214. error?: FunctionCallback;
  215. /**
  216. * Callback for the request completing successfully
  217. */
  218. success?: (data: any, textStatus?: string, resp?: ResponseMeta) => void;
  219. };
  220. export type RequestOptions = RequestCallbacks & {
  221. /**
  222. * Values to attach to the body of the request.
  223. */
  224. data?: any;
  225. /**
  226. * Headers add to the request.
  227. */
  228. headers?: Record<string, string>;
  229. /**
  230. * The host the request should be made to.
  231. */
  232. host?: string;
  233. /**
  234. * The HTTP method to use when making the API request
  235. */
  236. method?: APIRequestMethod;
  237. /**
  238. * Because of the async nature of API requests, errors will happen outside of
  239. * the stack that initated the request. a preservedError can be passed to
  240. * coalesce the stacks together.
  241. */
  242. preservedError?: Error;
  243. /**
  244. * Query parameters to add to the requested URL.
  245. */
  246. query?: Record<string, any>;
  247. /**
  248. * By default, requests will be aborted anytime api.clear() is called,
  249. * which is commonly used on unmounts. When skipAbort is true, the
  250. * request is opted out of this behavior. Useful for when you still
  251. * want to cache a request on unmount.
  252. */
  253. skipAbort?: boolean;
  254. };
  255. type ClientOptions = {
  256. /**
  257. * The base URL path to prepend to API request URIs.
  258. */
  259. baseUrl?: string;
  260. /**
  261. * Credentials policy to apply to each request
  262. */
  263. credentials?: RequestCredentials;
  264. /**
  265. * Base set of headers to apply to each request
  266. */
  267. headers?: HeadersInit;
  268. };
  269. type HandleRequestErrorOptions = {
  270. id: string;
  271. path: string;
  272. requestOptions: Readonly<RequestOptions>;
  273. };
  274. /**
  275. * The API client is used to make HTTP requests to Sentry's backend.
  276. *
  277. * This is they preferred way to talk to the backend.
  278. */
  279. export class Client {
  280. baseUrl: string;
  281. activeRequests: Record<string, Request>;
  282. headers: HeadersInit;
  283. credentials?: RequestCredentials;
  284. static JSON_HEADERS = {
  285. Accept: 'application/json; charset=utf-8',
  286. 'Content-Type': 'application/json',
  287. };
  288. constructor(options: ClientOptions = {}) {
  289. this.baseUrl = options.baseUrl ?? '/api/0';
  290. this.headers = options.headers ?? Client.JSON_HEADERS;
  291. this.activeRequests = {};
  292. this.credentials = options.credentials ?? 'include';
  293. }
  294. wrapCallback<T extends any[]>(
  295. id: string,
  296. func: FunctionCallback<T> | undefined,
  297. cleanup: boolean = false
  298. ) {
  299. return (...args: T) => {
  300. const req = this.activeRequests[id];
  301. if (cleanup === true) {
  302. delete this.activeRequests[id];
  303. }
  304. if (!req?.alive) {
  305. return undefined;
  306. }
  307. // Check if API response is a 302 -- means project slug was renamed and user
  308. // needs to be redirected
  309. // @ts-expect-error
  310. if (hasProjectBeenRenamed(...args)) {
  311. return undefined;
  312. }
  313. // Call success callback
  314. return func?.apply(req, args);
  315. };
  316. }
  317. /**
  318. * Attempt to cancel all active fetch requests
  319. */
  320. clear() {
  321. Object.values(this.activeRequests).forEach(r => r.cancel());
  322. }
  323. handleRequestError(
  324. {id, path, requestOptions}: HandleRequestErrorOptions,
  325. response: ResponseMeta,
  326. textStatus: string,
  327. errorThrown: string
  328. ) {
  329. const code = response?.responseJSON?.detail?.code;
  330. const isSudoRequired = code === SUDO_REQUIRED || code === SUPERUSER_REQUIRED;
  331. let didSuccessfullyRetry = false;
  332. if (isSudoRequired) {
  333. openSudo({
  334. isSuperuser: code === SUPERUSER_REQUIRED,
  335. sudo: code === SUDO_REQUIRED,
  336. retryRequest: async () => {
  337. try {
  338. const data = await this.requestPromise(path, requestOptions);
  339. requestOptions.success?.(data);
  340. didSuccessfullyRetry = true;
  341. } catch (err) {
  342. requestOptions.error?.(err);
  343. }
  344. },
  345. onClose: () =>
  346. // If modal was closed, then forward the original response
  347. !didSuccessfullyRetry && requestOptions.error?.(response),
  348. });
  349. return;
  350. }
  351. // Call normal error callback
  352. const errorCb = this.wrapCallback<[ResponseMeta, string, string]>(
  353. id,
  354. requestOptions.error
  355. );
  356. errorCb?.(response, textStatus, errorThrown);
  357. }
  358. /**
  359. * Initate a request to the backend API.
  360. *
  361. * Consider using `requestPromise` for the async Promise version of this method.
  362. */
  363. request(path: string, options: Readonly<RequestOptions> = {}): Request {
  364. const method = options.method || (options.data ? 'POST' : 'GET');
  365. let fullUrl = buildRequestUrl(this.baseUrl, path, options);
  366. let data = options.data;
  367. if (data !== undefined && method !== 'GET' && !(data instanceof FormData)) {
  368. data = JSON.stringify(data);
  369. }
  370. // TODO(epurkhiser): Mimicking the old jQuery API, data could be a string /
  371. // object for GET requets. jQuery just sticks it onto the URL as query
  372. // parameters
  373. if (method === 'GET' && data) {
  374. const queryString = typeof data === 'string' ? data : qs.stringify(data);
  375. if (queryString.length > 0) {
  376. fullUrl = fullUrl + (fullUrl.includes('?') ? '&' : '?') + queryString;
  377. }
  378. }
  379. const id = uniqueId();
  380. const startMarker = `api-request-start-${id}`;
  381. metric.mark({name: startMarker});
  382. /**
  383. * Called when the request completes with a 2xx status
  384. */
  385. const successHandler = (
  386. resp: ResponseMeta,
  387. textStatus: string,
  388. responseData: any
  389. ) => {
  390. metric.measure({
  391. name: 'app.api.request-success',
  392. start: startMarker,
  393. data: {status: resp?.status},
  394. });
  395. if (options.success !== undefined) {
  396. this.wrapCallback<[any, string, ResponseMeta]>(id, options.success)(
  397. responseData,
  398. textStatus,
  399. resp
  400. );
  401. }
  402. };
  403. /**
  404. * Called when the request is non-2xx
  405. */
  406. const errorHandler = (
  407. resp: ResponseMeta,
  408. textStatus: string,
  409. errorThrown: string
  410. ) => {
  411. metric.measure({
  412. name: 'app.api.request-error',
  413. start: startMarker,
  414. data: {status: resp?.status},
  415. });
  416. this.handleRequestError(
  417. {id, path, requestOptions: options},
  418. resp,
  419. textStatus,
  420. errorThrown
  421. );
  422. };
  423. /**
  424. * Called when the request completes
  425. */
  426. const completeHandler = (resp: ResponseMeta, textStatus: string) =>
  427. this.wrapCallback<[ResponseMeta, string]>(
  428. id,
  429. options.complete,
  430. true
  431. )(resp, textStatus);
  432. // AbortController is optional, though most browser should support it.
  433. const aborter =
  434. typeof AbortController !== 'undefined' && !options.skipAbort
  435. ? new AbortController()
  436. : undefined;
  437. // GET requests may not have a body
  438. const body = method !== 'GET' ? data : undefined;
  439. const requestHeaders = new Headers({...this.headers, ...options.headers});
  440. // Do not set the X-CSRFToken header when making a request outside of the
  441. // current domain. Because we use subdomains we loosely compare origins
  442. if (!csrfSafeMethod(method) && isSimilarOrigin(fullUrl, window.location.origin)) {
  443. requestHeaders.set('X-CSRFToken', getCsrfToken());
  444. }
  445. const fetchRequest = fetch(fullUrl, {
  446. method,
  447. body,
  448. headers: requestHeaders,
  449. credentials: this.credentials,
  450. signal: aborter?.signal,
  451. });
  452. // XXX(epurkhiser): We migrated off of jquery, so for now we have a
  453. // compatibility layer which mimics that of the jquery response objects.
  454. fetchRequest
  455. .then(
  456. async response => {
  457. // The Response's body can only be resolved/used at most once.
  458. // So we clone the response so we can resolve the body content as text content.
  459. // Response objects need to be cloned before its body can be used.
  460. let responseJSON: any;
  461. let responseText: any;
  462. const {status, statusText} = response;
  463. let {ok} = response;
  464. let errorReason = 'Request not OK'; // the default error reason
  465. let twoHundredErrorReason;
  466. // Try to get text out of the response no matter the status
  467. try {
  468. responseText = await response.text();
  469. } catch (error) {
  470. twoHundredErrorReason = 'Failed awaiting response.text()';
  471. ok = false;
  472. if (error.name === 'AbortError') {
  473. errorReason = 'Request was aborted';
  474. } else {
  475. errorReason = error.toString();
  476. }
  477. }
  478. const responseContentType = response.headers.get('content-type');
  479. const isResponseJSON = responseContentType?.includes('json');
  480. const wasExpectingJson =
  481. requestHeaders.get('Accept') === Client.JSON_HEADERS.Accept;
  482. const isStatus3XX = status >= 300 && status < 400;
  483. if (status !== 204 && !isStatus3XX) {
  484. try {
  485. responseJSON = JSON.parse(responseText);
  486. } catch (error) {
  487. twoHundredErrorReason = 'Failed trying to parse responseText';
  488. if (error.name === 'AbortError') {
  489. ok = false;
  490. errorReason = 'Request was aborted';
  491. } else if (isResponseJSON && error instanceof SyntaxError) {
  492. // If the MIME type is `application/json` but decoding failed,
  493. // this should be an error.
  494. ok = false;
  495. errorReason = 'JSON parse error';
  496. } else if (
  497. // Empty responses from POST 201 requests are valid
  498. responseText?.length > 0 &&
  499. wasExpectingJson &&
  500. error instanceof SyntaxError
  501. ) {
  502. // Was expecting json but was returned something else. Possibly HTML.
  503. // Ideally this would not be a 200, but we should reject the promise
  504. ok = false;
  505. errorReason = 'JSON parse error. Possibly returned HTML';
  506. }
  507. }
  508. }
  509. const responseMeta: ResponseMeta = {
  510. status,
  511. statusText,
  512. responseJSON,
  513. responseText,
  514. getResponseHeader: (header: string) => response.headers.get(header),
  515. };
  516. // Respect the response content-type header
  517. const responseData = isResponseJSON ? responseJSON : responseText;
  518. if (ok) {
  519. successHandler(responseMeta, statusText, responseData);
  520. } else {
  521. // There's no reason we should be here with a 200 response, but we get
  522. // tons of events from this codepath with a 200 status nonetheless.
  523. // Until we know why, let's do what is essentially some very fancy print debugging.
  524. if (status === 200 && responseText) {
  525. const parameterizedPath = sanitizePath(path);
  526. const message = '200 treated as error';
  527. const scope = new Sentry.Scope();
  528. scope.setTags({endpoint: `${method} ${parameterizedPath}`, errorReason});
  529. scope.setExtras({
  530. twoHundredErrorReason,
  531. responseJSON,
  532. responseText,
  533. responseContentType,
  534. errorReason,
  535. });
  536. // Make sure all of these errors group, so we don't produce a bunch of noise
  537. scope.setFingerprint([message]);
  538. Sentry.captureException(
  539. new Error(`${message}: ${method} ${parameterizedPath}`),
  540. scope
  541. );
  542. }
  543. const shouldSkipErrorHandler =
  544. globalErrorHandlers.map(handler => handler(responseMeta)).filter(Boolean)
  545. .length > 0;
  546. if (!shouldSkipErrorHandler) {
  547. errorHandler(responseMeta, statusText, errorReason);
  548. }
  549. }
  550. completeHandler(responseMeta, statusText);
  551. },
  552. () => {
  553. // Ignore failed fetch calls or errors in the fetch request itself (e.g. cancelled requests)
  554. // Not related to errors in responses
  555. }
  556. )
  557. .catch(error => {
  558. // eslint-disable-next-line no-console
  559. console.error(error);
  560. Sentry.captureException(error);
  561. });
  562. const request = new Request(fetchRequest, aborter);
  563. this.activeRequests[id] = request;
  564. return request;
  565. }
  566. requestPromise<IncludeAllArgsType extends boolean>(
  567. path: string,
  568. {
  569. includeAllArgs,
  570. ...options
  571. }: {includeAllArgs?: IncludeAllArgsType} & Readonly<RequestOptions> = {}
  572. ): Promise<IncludeAllArgsType extends true ? ApiResult : any> {
  573. // Create an error object here before we make any async calls so that we
  574. // have a helpful stack trace if it errors
  575. //
  576. // This *should* get logged to Sentry only if the promise rejection is not handled
  577. // (since SDK captures unhandled rejections). Ideally we explicitly ignore rejection
  578. // or handle with a user friendly error message
  579. const preservedError = new Error('API Request Error');
  580. return new Promise((resolve, reject) =>
  581. this.request(path, {
  582. ...options,
  583. preservedError,
  584. success: (data, textStatus, resp) => {
  585. if (includeAllArgs) {
  586. resolve([data, textStatus, resp] as any);
  587. } else {
  588. resolve(data);
  589. }
  590. },
  591. error: (resp: ResponseMeta) => {
  592. const errorObjectToUse = new RequestError(
  593. options.method,
  594. path,
  595. preservedError,
  596. resp
  597. );
  598. // Although `this.request` logs all error responses, this error object can
  599. // potentially be logged by Sentry's unhandled rejection handler
  600. reject(errorObjectToUse);
  601. },
  602. })
  603. );
  604. }
  605. }
  606. export function resolveHostname(path: string, hostname?: string): string {
  607. const storeState = OrganizationStore.get();
  608. const configLinks = ConfigStore.get('links');
  609. hostname = hostname ?? '';
  610. if (!hostname && storeState.organization?.features.includes('frontend-domainsplit')) {
  611. // /_admin/ is special: since it doesn't update OrganizationStore, it's
  612. // commonly the case that requests will be made for data which does not
  613. // exist in the same region as the one in configLinks.regionUrl. Because of
  614. // this we want to explicitly default those requests to be proxied through
  615. // the control silo which can handle region resolution in exchange for a
  616. // bit of latency.
  617. const isAdmin = window.location.pathname.startsWith('/_admin/');
  618. const isControlSilo = detectControlSiloPath(path);
  619. if (!isAdmin && !isControlSilo && configLinks.regionUrl) {
  620. hostname = configLinks.regionUrl;
  621. }
  622. if (isControlSilo && configLinks.sentryUrl) {
  623. hostname = configLinks.sentryUrl;
  624. }
  625. }
  626. // If we're making a request to the applications' root
  627. // domain, we can drop the domain as webpack devserver will add one.
  628. // TODO(hybridcloud) This can likely be removed when sentry.types.region.Region.to_url()
  629. // loses the monolith mode condition.
  630. if (window.__SENTRY_DEV_UI && hostname === configLinks.sentryUrl) {
  631. hostname = '';
  632. }
  633. // When running as yarn dev-ui we can't spread requests across domains because
  634. // of CORS. Instead we extract the subdomain from the hostname
  635. // and prepend the URL with `/region/$name` so that webpack-devserver proxy
  636. // can route requests to the regions.
  637. if (hostname && window.__SENTRY_DEV_UI) {
  638. const domainpattern = /https?\:\/\/([^.]*)\.sentry\.io/;
  639. const domainmatch = hostname.match(domainpattern);
  640. if (domainmatch) {
  641. hostname = '';
  642. path = `/region/${domainmatch[1]}${path}`;
  643. }
  644. }
  645. if (hostname) {
  646. path = `${hostname}${path}`;
  647. }
  648. return path;
  649. }
  650. function detectControlSiloPath(path: string): boolean {
  651. // We sometimes include querystrings in paths.
  652. // Using URL() to avoid handrolling URL parsing
  653. const url = new URL(path, 'https://sentry.io');
  654. path = url.pathname;
  655. path = path.startsWith('/') ? path.substring(1) : path;
  656. for (const pattern of controlsilopatterns) {
  657. if (pattern.test(path)) {
  658. return true;
  659. }
  660. }
  661. return false;
  662. }