api.tsx 23 KB

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