@esri/arcgis-rest-auth 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"auth.umd.min.js","sources":["../../src/fetch-token.ts","../../src/ApplicationSession.ts","../../src/ApiKey.ts","../../src/generate-token.ts","../../src/federation-utils.ts","../../src/validate-app-access.ts","../../src/UserSession.ts","../../src/app-tokens.ts"],"sourcesContent":["/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n request,\n IRequestOptions,\n ITokenRequestOptions\n} from \"@esri/arcgis-rest-request\";\n\ninterface IFetchTokenRawResponse {\n access_token: string;\n expires_in: number;\n username: string;\n ssl?: boolean;\n refresh_token?: string;\n}\n\nexport interface IFetchTokenResponse {\n token: string;\n expires: Date;\n username: string;\n ssl: boolean;\n refreshToken?: string;\n}\n\nexport function fetchToken(\n url: string,\n requestOptions: ITokenRequestOptions\n): Promise<IFetchTokenResponse> {\n const options: IRequestOptions = requestOptions;\n // we generate a response, so we can't return the raw response\n options.rawResponse = false;\n\n return request(url, options).then((response: IFetchTokenRawResponse) => {\n const r: IFetchTokenResponse = {\n token: response.access_token,\n username: response.username,\n expires: new Date(\n // convert seconds in response to milliseconds and add the value to the current time to calculate a static expiration timestamp\n Date.now() + (response.expires_in * 1000 - 1000)\n ),\n ssl: response.ssl === true\n };\n if (response.refresh_token) {\n r.refreshToken = response.refresh_token;\n }\n\n return r;\n });\n}\n","/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n IAuthenticationManager,\n ITokenRequestOptions\n} from \"@esri/arcgis-rest-request\";\nimport { fetchToken } from \"./fetch-token\";\n\nexport interface IApplicationSessionOptions {\n /**\n * Client ID of your application. Can be obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n clientId: string;\n\n /**\n * A Client Secret is also obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise. Treat it like a password.\n */\n clientSecret: string;\n\n /**\n * OAuth 2.0 access token from a previous application session.\n */\n token?: string;\n\n /**\n * Expiration date for the `token`\n */\n expires?: Date;\n\n /**\n * URL of ArcGIS REST base, defaults to \"https://www.arcgis.com/sharing/rest\"\n */\n portal?: string;\n\n /**\n * Duration of requested tokens in minutes. defaults to 7200 (5 days).\n */\n duration?: number;\n}\n\n/**\n * ```js\n * import { ApplicationSession } from '@esri/arcgis-rest-auth';\n * const session = new ApplicationSession({\n * clientId: \"abc123\",\n * clientSecret: \"sshhhhhh\"\n * })\n * // visit https://developers.arcgis.com to generate your own clientid and secret\n * ```\n * You can use [App Login](/arcgis-rest-js/guides/node/) to access premium content and services in ArcGIS Online.\n *\n */\nexport class ApplicationSession implements IAuthenticationManager {\n public portal: string;\n private clientId: string;\n private clientSecret: string;\n private token: string;\n private expires: Date;\n private duration: number;\n\n /**\n * Internal object to keep track of pending token requests. Used to prevent\n * duplicate token requests.\n */\n private _pendingTokenRequest: Promise<string>;\n\n constructor(options: IApplicationSessionOptions) {\n this.clientId = options.clientId;\n this.clientSecret = options.clientSecret;\n this.token = options.token;\n this.expires = options.expires;\n this.portal = options.portal || \"https://www.arcgis.com/sharing/rest\";\n this.duration = options.duration || 7200;\n }\n\n // URL is not actually read or passed through.\n public getToken(\n url: string,\n requestOptions?: ITokenRequestOptions\n ): Promise<string> {\n if (this.token && this.expires && this.expires.getTime() > Date.now()) {\n return Promise.resolve(this.token);\n }\n\n if (this._pendingTokenRequest) {\n return this._pendingTokenRequest;\n }\n\n this._pendingTokenRequest = this.refreshToken(requestOptions);\n\n return this._pendingTokenRequest;\n }\n\n public refreshToken(requestOptions?: ITokenRequestOptions): Promise<string> {\n const options = {\n params: {\n client_id: this.clientId,\n client_secret: this.clientSecret,\n grant_type: \"client_credentials\",\n expiration: this.duration\n },\n ...requestOptions\n };\n return fetchToken(`${this.portal}/oauth2/token/`, options).then(\n response => {\n this._pendingTokenRequest = null;\n this.token = response.token;\n this.expires = response.expires;\n return response.token;\n }\n );\n }\n\n public refreshSession() {\n return this.refreshToken().then(() => this);\n }\n}\n","/* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n IAuthenticationManager,\n} from \"@esri/arcgis-rest-request\";\n\n/**\n * Options for the `ApiKey` constructor.\n */\nexport interface IApiKeyOptions {\n key: string;\n}\n\n/**\n * ```js\n * import { ApiKey } from '@esri/arcgis-rest-auth';\n * const apiKey = new ApiKey(\"...\");\n * ```\n * Used to authenticate with API Keys.\n */\nexport class ApiKey implements IAuthenticationManager {\n\n /**\n * The current portal the user is authenticated with.\n */\n public readonly portal: string;\n\n private key: string;\n\n constructor(options: IApiKeyOptions) {\n this.key = options.key;\n }\n\n /**\n * Gets a token (the API Key).\n */\n public getToken(url: string) {\n return Promise.resolve(this.key);\n }\n}\n","/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n request,\n IRequestOptions,\n ITokenRequestOptions,\n NODEJS_DEFAULT_REFERER_HEADER,\n} from \"@esri/arcgis-rest-request\";\n\nexport interface IGenerateTokenResponse {\n token: string;\n expires: number;\n ssl: boolean;\n}\n\nexport function generateToken(\n url: string,\n requestOptions: ITokenRequestOptions\n): Promise<IGenerateTokenResponse> {\n const options: IRequestOptions = requestOptions;\n\n /* istanbul ignore else */\n if (\n typeof window !== \"undefined\" &&\n window.location &&\n window.location.host\n ) {\n options.params.referer = window.location.host;\n } else {\n options.params.referer = NODEJS_DEFAULT_REFERER_HEADER;\n }\n\n return request(url, options);\n}\n","import { cleanUrl } from \"@esri/arcgis-rest-request\";\n/**\n * Used to test if a URL is an ArcGIS Online URL\n */\nconst arcgisOnlineUrlRegex = /^https?:\\/\\/(\\S+)\\.arcgis\\.com.+/;\n\n/**\n * Used to test if a URL is production ArcGIS Online Portal\n */\nconst arcgisOnlinePortalRegex = /^https?:\\/\\/(dev|devext|qa|qaext|www)\\.arcgis\\.com\\/sharing\\/rest+/;\n\n/**\n * Used to test if a URL is an ArcGIS Online Organization Portal\n */\nconst arcgisOnlineOrgPortalRegex = /^https?:\\/\\/(?:[a-z0-9-]+\\.maps(dev|devext|qa|qaext)?)?.arcgis\\.com\\/sharing\\/rest/;\n\nexport function isOnline(url: string): boolean {\n return arcgisOnlineUrlRegex.test(url);\n}\n\nexport function normalizeOnlinePortalUrl(portalUrl: string): string {\n if (!arcgisOnlineUrlRegex.test(portalUrl)) {\n return portalUrl;\n }\n\n switch (getOnlineEnvironment(portalUrl)) {\n case \"dev\":\n return \"https://devext.arcgis.com/sharing/rest\";\n case \"qa\":\n return \"https://qaext.arcgis.com/sharing/rest\";\n default:\n return \"https://www.arcgis.com/sharing/rest\";\n }\n}\n\nexport function getOnlineEnvironment(url: string): string {\n if (!arcgisOnlineUrlRegex.test(url)) {\n return null;\n }\n\n const match = url.match(arcgisOnlineUrlRegex);\n const subdomain = match[1].split(\".\").pop();\n\n if (subdomain.includes(\"dev\")) {\n return \"dev\";\n }\n\n if (subdomain.includes(\"qa\")) {\n return \"qa\";\n }\n\n return \"production\";\n}\n\nexport function isFederated(\n owningSystemUrl: string,\n portalUrl: string\n): boolean {\n const normalizedPortalUrl = cleanUrl(\n normalizeOnlinePortalUrl(portalUrl)\n ).replace(/https?:\\/\\//, \"\");\n\n const normalizedOwningSystemUrl = cleanUrl(owningSystemUrl).replace(\n /https?:\\/\\//,\n \"\"\n );\n\n return new RegExp(normalizedOwningSystemUrl, \"i\").test(normalizedPortalUrl);\n}\n\nexport function canUseOnlineToken(\n portalUrl: string,\n requestUrl: string\n): boolean {\n const portalIsOnline = isOnline(portalUrl);\n const requestIsOnline = isOnline(requestUrl);\n const portalEnv = getOnlineEnvironment(portalUrl);\n const requestEnv = getOnlineEnvironment(requestUrl);\n\n if (portalIsOnline && requestIsOnline && portalEnv === requestEnv) {\n return true;\n }\n\n return false;\n}\n","/* Copyright (c) 2018-2020 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport { IRequestOptions, request } from \"@esri/arcgis-rest-request\";\n\nexport interface IAppAccess {\n /**\n * Verifies that the token is valid and the user has access to\n * the specified app (clientId)\n */\n valid: boolean;\n /**\n * Should the app present the current user with a \"View Only\" mode\n */\n viewOnlyUserTypeApp: boolean;\n}\n\n/**\n * Validates that the user has access to the application\n * and if they user should be presented a \"View Only\" mode\n *\n * This is only needed/valid for Esri applications that are \"licensed\"\n * and shipped in ArcGIS Online or ArcGIS Enterprise. Most custom applications\n * should not need or use this.\n *\n * ```js\n * import { validateAppAccess } from '@esri/arcgis-rest-auth';\n *\n * return validateAppAccess('your-token', 'theClientId')\n * .then((result) => {\n * if (!result.value) {\n * // redirect or show some other ui\n * } else {\n * if (result.viewOnlyUserTypeApp) {\n * // use this to inform your app to show a \"View Only\" mode\n * }\n * }\n * })\n * .catch((err) => {\n * // two possible errors\n * // invalid clientId: {\"error\":{\"code\":400,\"messageCode\":\"GWM_0007\",\"message\":\"Invalid request\",\"details\":[]}}\n * // invalid token: {\"error\":{\"code\":498,\"message\":\"Invalid token.\",\"details\":[]}}\n * })\n * ```\n *\n * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within\n * an ArcGIS Enterprise installation. Custom applications can not use this.\n *\n * @param token platform token\n * @param clientId application client id\n * @param portal Optional\n */\nexport function validateAppAccess(\n token: string,\n clientId: string,\n portal = \"https://www.arcgis.com/sharing/rest\"\n): Promise<IAppAccess> {\n const url = `${portal}/oauth2/validateAppAccess`;\n const ro = {\n method: \"POST\",\n params: {\n f: \"json\",\n client_id: clientId,\n token,\n },\n } as IRequestOptions;\n return request(url, ro);\n}\n","/* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\n/**\n * /generateToken returns a token that cannot be refreshed.\n *\n * oauth2/token can return a token *and* a refreshToken.\n * up until the refreshToken expires, you can use it (and a clientId)\n * to fetch fresh credentials without a username and password.\n *\n * the catch is that this 'authorization_code' flow is only utilized\n * by server based OAuth 2 Node.js applications that call /authorize first.\n */\n\nimport * as http from \"http\";\nimport {\n request,\n IRequestOptions,\n ArcGISAuthError,\n IAuthenticationManager,\n ITokenRequestOptions,\n cleanUrl,\n encodeQueryString,\n decodeQueryString,\n} from \"@esri/arcgis-rest-request\";\nimport { IUser } from \"@esri/arcgis-rest-types\";\nimport { generateToken } from \"./generate-token\";\nimport { fetchToken, IFetchTokenResponse } from \"./fetch-token\";\nimport { canUseOnlineToken, isFederated } from \"./federation-utils\";\nimport { IAppAccess, validateAppAccess } from \"./validate-app-access\";\n\n/**\n * Internal utility for resolving a Promise from outside its constructor.\n *\n * See: http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/\n */\ninterface IDeferred<T> {\n promise: Promise<T>;\n resolve: (v: T) => void;\n reject: (v: any) => void;\n}\n\nexport type AuthenticationProvider =\n | \"arcgis\"\n | \"facebook\"\n | \"google\"\n | \"github\"\n | \"apple\";\n\n/**\n * Represents a [credential](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-Credential.html)\n * object used to access a secure ArcGIS resource.\n */\nexport interface ICredential {\n expires: number;\n server: string;\n ssl: boolean;\n token: string;\n userId: string;\n}\n\nfunction defer<T>(): IDeferred<T> {\n const deferred: any = {\n promise: null,\n resolve: null,\n reject: null,\n };\n\n deferred.promise = new Promise((resolve, reject) => {\n deferred.resolve = resolve;\n deferred.reject = reject;\n });\n\n return deferred as IDeferred<T>;\n}\n\n/**\n * Options for static OAuth 2.0 helper methods on `UserSession`.\n */\nexport interface IOAuth2Options {\n /**\n * Client ID of your application. Can be obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n clientId: string;\n\n /**\n * A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n redirectUri: string;\n\n /**\n * The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.\n */\n portal?: string;\n\n /**\n * ArcGIS Authentication is used by default. Specifying an alternative will take users directly to the corresponding provider's OAuth page.\n */\n\n provider?: AuthenticationProvider;\n\n /**\n * The requested validity in minutes for a token. Defaults to 20160 (two weeks).\n */\n expiration?: number;\n\n /**\n * Duration (in minutes) that a token will be valid. Defaults to 20160 (two weeks).\n *\n * @deprecated use 'expiration' instead\n */\n duration?: number;\n\n /**\n * Determines whether to open the authorization window in a new tab/window or in the current window.\n *\n * @browserOnly\n */\n popup?: boolean;\n\n /**\n * The window features passed to [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) when `popup` is true. Defaults to `height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes`\n *\n * @browserOnly\n */\n popupWindowFeatures?: string;\n\n /**\n * Duration (in minutes) that a refresh token will be valid.\n *\n * @nodeOnly\n */\n refreshTokenTTL?: number;\n\n /**\n * The locale assumed to render the login page.\n *\n * @browserOnly\n */\n locale?: string;\n\n /**\n * Applications can specify an opaque value for this parameter to correlate the authorization request sent with the received response. By default, clientId is used.\n *\n * @browserOnly\n */\n state?: string;\n\n [key: string]: any;\n}\n\n/**\n * Options for the `UserSession` constructor.\n */\nexport interface IUserSessionOptions {\n /**\n * Client ID of your application. Can be obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n clientId?: string;\n\n /**\n * A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n redirectUri?: string;\n\n /**\n * OAuth 2.0 refresh token from a previous user session.\n */\n refreshToken?: string;\n\n /**\n * Expiration date of the `refreshToken`\n */\n refreshTokenExpires?: Date;\n\n /**\n * The authenticated user's username. Guaranteed to be unique across ArcGIS Online or your instance of ArcGIS Enterprise.\n */\n username?: string;\n\n /**\n * Password for this user. Used in CLI apps where users cannot do OAuth 2.0.\n */\n password?: string;\n\n /**\n * OAuth 2.0 access token from a previous user session.\n */\n token?: string;\n\n /**\n * Expiration date for the `token`\n */\n tokenExpires?: Date;\n\n /**\n * The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.\n */\n portal?: string;\n\n /**\n * This value is set to true automatically if the ArcGIS Organization requires that requests be made over https.\n */\n ssl?: boolean;\n\n /**\n * ArcGIS Authentication is used by default. Specifying an alternative will take users directly to the corresponding provider's OAuth page.\n */\n provider?: AuthenticationProvider;\n\n /**\n * Duration of requested token validity in minutes. Used when requesting tokens with `username` and `password` or when validating the identity of unknown servers. Defaults to two weeks.\n */\n tokenDuration?: number;\n\n /**\n * Duration (in minutes) that a refresh token will be valid.\n */\n refreshTokenTTL?: number;\n\n /**\n * An unfederated ArcGIS Server instance known to recognize credentials supplied manually.\n * ```js\n * {\n * server: \"https://sampleserver6.arcgisonline.com/arcgis\",\n * token: \"SOSlV3v..\",\n * tokenExpires: new Date(1545415669763)\n * }\n * ```\n */\n server?: string;\n}\n\n/**\n * ```js\n * import { UserSession } from '@esri/arcgis-rest-auth';\n * UserSession.beginOAuth2({\n * // register an app of your own to create a unique clientId\n * clientId: \"abc123\",\n * redirectUri: 'https://yourapp.com/authenticate.html'\n * })\n * .then(session)\n * // or\n * new UserSession({\n * username: \"jsmith\",\n * password: \"123456\"\n * })\n * // or\n * UserSession.deserialize(cache)\n * ```\n * Used to authenticate both ArcGIS Online and ArcGIS Enterprise users. `UserSession` includes helper methods for [OAuth 2.0](/arcgis-rest-js/guides/browser-authentication/) in both browser and server applications.\n */\nexport class UserSession implements IAuthenticationManager {\n /**\n * The current ArcGIS Online or ArcGIS Enterprise `token`.\n */\n get token() {\n return this._token;\n }\n\n /**\n * The expiration time of the current `token`.\n */\n get tokenExpires() {\n return this._tokenExpires;\n }\n\n /**\n * The current token to ArcGIS Online or ArcGIS Enterprise.\n */\n get refreshToken() {\n return this._refreshToken;\n }\n\n /**\n * The expiration time of the current `refreshToken`.\n */\n get refreshTokenExpires() {\n return this._refreshTokenExpires;\n }\n\n /**\n * Deprecated, use `federatedServers` instead.\n *\n * @deprecated\n */\n get trustedServers() {\n console.log(\"DEPRECATED: use federatedServers instead\");\n return this.federatedServers;\n }\n\n /**\n * Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is `true` the\n * authentication window will open in a new tab/window and the function will return\n * Promise&lt;UserSession&gt;. Otherwise, the user will be redirected to the\n * authorization page in their current tab/window and the function will return `undefined`.\n *\n * @browserOnly\n */\n /* istanbul ignore next */\n public static beginOAuth2(\n options: IOAuth2Options,\n win: any = window\n ): Promise<UserSession> | undefined {\n if (options.duration) {\n console.log(\n \"DEPRECATED: 'duration' is deprecated - use 'expiration' instead\"\n );\n }\n\n const {\n portal,\n provider,\n clientId,\n expiration,\n redirectUri,\n popup,\n popupWindowFeatures,\n state,\n locale,\n params,\n }: IOAuth2Options = {\n ...{\n portal: \"https://www.arcgis.com/sharing/rest\",\n provider: \"arcgis\",\n expiration: 20160,\n popup: true,\n popupWindowFeatures:\n \"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes\",\n state: options.clientId,\n locale: \"\",\n },\n ...options,\n };\n let url: string;\n if (provider === \"arcgis\") {\n url = `${portal}/oauth2/authorize?client_id=${clientId}&response_type=token&expiration=${\n options.duration || expiration\n }&redirect_uri=${encodeURIComponent(\n redirectUri\n )}&state=${state}&locale=${locale}`;\n } else {\n url = `${portal}/oauth2/social/authorize?client_id=${clientId}&socialLoginProviderName=${provider}&autoAccountCreateForSocial=true&response_type=token&expiration=${\n options.duration || expiration\n }&redirect_uri=${encodeURIComponent(\n redirectUri\n )}&state=${state}&locale=${locale}`;\n }\n\n // append additional params\n if (params) {\n url = `${url}&${encodeQueryString(params)}`;\n }\n\n if (!popup) {\n win.location.href = url;\n return undefined;\n }\n\n const session = defer<UserSession>();\n\n win[`__ESRI_REST_AUTH_HANDLER_${clientId}`] = function (\n errorString: any,\n oauthInfoString: string\n ) {\n if (errorString) {\n const error = JSON.parse(errorString);\n session.reject(new ArcGISAuthError(error.errorMessage, error.error));\n return;\n }\n\n if (oauthInfoString) {\n const oauthInfo = JSON.parse(oauthInfoString);\n session.resolve(\n new UserSession({\n clientId,\n portal,\n ssl: oauthInfo.ssl,\n token: oauthInfo.token,\n tokenExpires: new Date(oauthInfo.expires),\n username: oauthInfo.username,\n })\n );\n }\n };\n\n win.open(url, \"oauth-window\", popupWindowFeatures);\n\n return session.promise;\n }\n\n /**\n * Completes a browser-based OAuth 2.0 sign in. If `options.popup` is `true` the user\n * will be returned to the previous window. Otherwise a new `UserSession`\n * will be returned. You must pass the same values for `options.popup` and\n * `options.portal` as you used in `beginOAuth2()`.\n *\n * @browserOnly\n */\n /* istanbul ignore next */\n public static completeOAuth2(options: IOAuth2Options, win: any = window) {\n const { portal, clientId, popup }: IOAuth2Options = {\n ...{ portal: \"https://www.arcgis.com/sharing/rest\", popup: true },\n ...options,\n };\n\n function completeSignIn(error: any, oauthInfo?: IFetchTokenResponse) {\n try {\n let handlerFn;\n const handlerFnName = `__ESRI_REST_AUTH_HANDLER_${clientId}`;\n\n if (popup) {\n // Guard b/c IE does not support window.opener\n if (win.opener) {\n if (win.opener.parent && win.opener.parent[handlerFnName]) {\n handlerFn = win.opener.parent[handlerFnName];\n } else if (win.opener && win.opener[handlerFnName]) {\n // support pop-out oauth from within an iframe\n handlerFn = win.opener[handlerFnName];\n }\n } else {\n // IE\n if (win !== win.parent && win.parent && win.parent[handlerFnName]) {\n handlerFn = win.parent[handlerFnName];\n }\n }\n // if we have a handler fn, call it and close the window\n if (handlerFn) {\n handlerFn(\n error ? JSON.stringify(error) : undefined,\n JSON.stringify(oauthInfo)\n );\n win.close();\n return undefined;\n }\n }\n } catch (e) {\n throw new ArcGISAuthError(\n `Unable to complete authentication. It's possible you specified popup based oAuth2 but no handler from \"beginOAuth2()\" present. This generally happens because the \"popup\" option differs between \"beginOAuth2()\" and \"completeOAuth2()\".`\n );\n }\n\n if (error) {\n throw new ArcGISAuthError(error.errorMessage, error.error);\n }\n\n return new UserSession({\n clientId,\n portal,\n ssl: oauthInfo.ssl,\n token: oauthInfo.token,\n tokenExpires: oauthInfo.expires,\n username: oauthInfo.username,\n });\n }\n\n const params = decodeQueryString(win.location.hash);\n\n if (!params.access_token) {\n let error;\n let errorMessage = \"Unknown error\";\n\n if (params.error) {\n error = params.error;\n errorMessage = params.error_description;\n }\n\n return completeSignIn({ error, errorMessage });\n }\n\n const token = params.access_token;\n const expires = new Date(\n Date.now() + parseInt(params.expires_in, 10) * 1000 - 60 * 1000\n );\n const username = params.username;\n const ssl = params.ssl === \"true\";\n\n return completeSignIn(undefined, {\n token,\n expires,\n ssl,\n username,\n });\n }\n\n /**\n * Request session information from the parent application\n *\n * When an application is embedded into another application via an IFrame, the embedded app can\n * use `window.postMessage` to request credentials from the host application. This function wraps\n * that behavior.\n *\n * The ArcGIS API for Javascript has this built into the Identity Manager as of the 4.19 release.\n *\n * Note: The parent application will not respond if the embedded app's origin is not:\n * - the same origin as the parent or *.arcgis.com (JSAPI)\n * - in the list of valid child origins (REST-JS)\n *\n *\n * @param parentOrigin origin of the parent frame. Passed into the embedded application as `parentOrigin` query param\n * @browserOnly\n */\n public static fromParent(parentOrigin: string, win?: any): Promise<any> {\n /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */\n if (!win && window) {\n win = window;\n }\n // Declare handler outside of promise scope so we can detach it\n let handler: (event: any) => void;\n // return a promise that will resolve when the handler receives\n // session information from the correct origin\n return new Promise((resolve, reject) => {\n // create an event handler that just wraps the parentMessageHandler\n handler = (event: any) => {\n // ensure we only listen to events from the parent\n if (event.source === win.parent && event.data) {\n try {\n return resolve(UserSession.parentMessageHandler(event));\n } catch (err) {\n return reject(err);\n }\n }\n };\n // add listener\n win.addEventListener(\"message\", handler, false);\n win.parent.postMessage(\n { type: \"arcgis:auth:requestCredential\" },\n parentOrigin\n );\n }).then((session) => {\n win.removeEventListener(\"message\", handler, false);\n return session;\n });\n }\n\n /**\n * Begins a new server-based OAuth 2.0 sign in. This will redirect the user to\n * the ArcGIS Online or ArcGIS Enterprise authorization page.\n *\n * @nodeOnly\n */\n public static authorize(\n options: IOAuth2Options,\n response: http.ServerResponse\n ) {\n if (options.duration) {\n console.log(\n \"DEPRECATED: 'duration' is deprecated - use 'expiration' instead\"\n );\n }\n const { portal, clientId, expiration, redirectUri }: IOAuth2Options = {\n ...{ portal: \"https://arcgis.com/sharing/rest\", expiration: 20160 },\n ...options,\n };\n\n response.writeHead(301, {\n Location: `${portal}/oauth2/authorize?client_id=${clientId}&expiration=${\n options.duration || expiration\n }&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}`,\n });\n\n response.end();\n }\n\n /**\n * Completes the server-based OAuth 2.0 sign in process by exchanging the `authorizationCode`\n * for a `access_token`.\n *\n * @nodeOnly\n */\n public static exchangeAuthorizationCode(\n options: IOAuth2Options,\n authorizationCode: string\n ): Promise<UserSession> {\n const { portal, clientId, redirectUri, refreshTokenTTL }: IOAuth2Options = {\n ...{\n portal: \"https://www.arcgis.com/sharing/rest\",\n refreshTokenTTL: 20160,\n },\n ...options,\n };\n\n return fetchToken(`${portal}/oauth2/token`, {\n params: {\n grant_type: \"authorization_code\",\n client_id: clientId,\n redirect_uri: redirectUri,\n code: authorizationCode,\n },\n }).then((response) => {\n return new UserSession({\n clientId,\n portal,\n ssl: response.ssl,\n redirectUri,\n refreshToken: response.refreshToken,\n refreshTokenTTL,\n refreshTokenExpires: new Date(\n Date.now() + (refreshTokenTTL - 1) * 60 * 1000\n ),\n token: response.token,\n tokenExpires: response.expires,\n username: response.username,\n });\n });\n }\n\n public static deserialize(str: string) {\n const options = JSON.parse(str);\n return new UserSession({\n clientId: options.clientId,\n refreshToken: options.refreshToken,\n refreshTokenExpires: new Date(options.refreshTokenExpires),\n username: options.username,\n password: options.password,\n token: options.token,\n tokenExpires: new Date(options.tokenExpires),\n portal: options.portal,\n ssl: options.ssl,\n tokenDuration: options.tokenDuration,\n redirectUri: options.redirectUri,\n refreshTokenTTL: options.refreshTokenTTL,\n });\n }\n\n /**\n * Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).\n *\n * ```js\n * UserSession.fromCredential({\n * userId: \"jsmith\",\n * token: \"secret\"\n * });\n * ```\n *\n * @returns UserSession\n */\n public static fromCredential(credential: ICredential) {\n // At ArcGIS Online 9.1, credentials no longer include the ssl and expires properties\n // Here, we provide default values for them to cover this condition\n const ssl = typeof credential.ssl !== \"undefined\" ? credential.ssl : true;\n const expires = credential.expires || Date.now() + 7200000; /* 2 hours */\n\n return new UserSession({\n portal: credential.server.includes(\"sharing/rest\")\n ? credential.server\n : credential.server + `/sharing/rest`,\n ssl,\n token: credential.token,\n username: credential.userId,\n tokenExpires: new Date(expires),\n });\n }\n\n /**\n * Handle the response from the parent\n * @param event DOM Event\n */\n private static parentMessageHandler(event: any): UserSession {\n if (event.data.type === \"arcgis:auth:credential\") {\n return UserSession.fromCredential(event.data.credential);\n }\n if (event.data.type === \"arcgis:auth:error\") {\n const err = new Error(event.data.error.message);\n err.name = event.data.error.name;\n throw err;\n } else {\n throw new Error(\"Unknown message type.\");\n }\n }\n\n /**\n * Client ID being used for authentication if provided in the `constructor`.\n */\n public readonly clientId: string;\n\n /**\n * The currently authenticated user if provided in the `constructor`.\n */\n public readonly username: string;\n\n /**\n * The currently authenticated user's password if provided in the `constructor`.\n */\n public readonly password: string;\n\n /**\n * The current portal the user is authenticated with.\n */\n public readonly portal: string;\n\n /**\n * This value is set to true automatically if the ArcGIS Organization requires that requests be made over https.\n */\n public readonly ssl: boolean;\n\n /**\n * The authentication provider to use.\n */\n public readonly provider: AuthenticationProvider;\n\n /**\n * Determines how long new tokens requested are valid.\n */\n public readonly tokenDuration: number;\n\n /**\n * A valid redirect URI for this application if provided in the `constructor`.\n */\n public readonly redirectUri: string;\n\n /**\n * Duration of new OAuth 2.0 refresh token validity (in minutes).\n */\n public readonly refreshTokenTTL: number;\n\n /**\n * An unfederated ArcGIS Server instance known to recognize credentials supplied manually.\n * ```js\n * {\n * server: \"https://sampleserver6.arcgisonline.com/arcgis\",\n * token: \"SOSlV3v..\",\n * tokenExpires: new Date(1545415669763)\n * }\n * ```\n */\n public readonly server: string;\n\n /**\n * Hydrated by a call to [getUser()](#getUser-summary).\n */\n private _user: IUser;\n\n /**\n * Hydrated by a call to [getPortal()](#getPortal-summary).\n */\n private _portalInfo: any;\n\n private _token: string;\n private _tokenExpires: Date;\n private _refreshToken: string;\n private _refreshTokenExpires: Date;\n private _pendingUserRequest: Promise<IUser>;\n private _pendingPortalRequest: Promise<any>;\n\n /**\n * Internal object to keep track of pending token requests. Used to prevent\n * duplicate token requests.\n */\n private _pendingTokenRequests: {\n [key: string]: Promise<string>;\n };\n\n /**\n * Internal list of tokens to 3rd party servers (federated servers) that have\n * been created via `generateToken`. The object key is the root URL of the server.\n */\n private federatedServers: {\n [key: string]: {\n token: string;\n expires: Date;\n };\n };\n\n /**\n * Internal list of 3rd party domains that should receive all cookies (credentials: \"include\").\n * Used to for PKI and IWA workflows in high security environments.\n */\n private trustedDomains: string[];\n\n private _hostHandler: any;\n\n constructor(options: IUserSessionOptions) {\n this.clientId = options.clientId;\n this._refreshToken = options.refreshToken;\n this._refreshTokenExpires = options.refreshTokenExpires;\n this.username = options.username;\n this.password = options.password;\n this._token = options.token;\n this._tokenExpires = options.tokenExpires;\n this.portal = options.portal\n ? cleanUrl(options.portal)\n : \"https://www.arcgis.com/sharing/rest\";\n this.ssl = options.ssl;\n this.provider = options.provider || \"arcgis\";\n this.tokenDuration = options.tokenDuration || 20160;\n this.redirectUri = options.redirectUri;\n this.refreshTokenTTL = options.refreshTokenTTL || 20160;\n this.server = options.server;\n\n this.federatedServers = {};\n this.trustedDomains = [];\n\n // if a non-federated server was passed explicitly, it should be trusted.\n if (options.server) {\n // if the url includes more than '/arcgis/', trim the rest\n const root = this.getServerRootUrl(options.server);\n\n this.federatedServers[root] = {\n token: options.token,\n expires: options.tokenExpires,\n };\n }\n this._pendingTokenRequests = {};\n }\n\n /**\n * Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).\n *\n * ```js\n * esriId.registerToken(session.toCredential());\n * ```\n *\n * @returns ICredential\n */\n public toCredential(): ICredential {\n return {\n expires: this.tokenExpires.getTime(),\n server: this.portal,\n ssl: this.ssl,\n token: this.token,\n userId: this.username,\n };\n }\n\n /**\n * Returns information about the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic.\n *\n * ```js\n * session.getUser()\n * .then(response => {\n * console.log(response.role); // \"org_admin\"\n * })\n * ```\n *\n * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.\n * @returns A Promise that will resolve with the data from the response.\n */\n public getUser(requestOptions?: IRequestOptions): Promise<IUser> {\n if (this._pendingUserRequest) {\n return this._pendingUserRequest;\n } else if (this._user) {\n return Promise.resolve(this._user);\n } else {\n const url = `${this.portal}/community/self`;\n\n const options = {\n httpMethod: \"GET\",\n authentication: this,\n ...requestOptions,\n rawResponse: false,\n } as IRequestOptions;\n\n this._pendingUserRequest = request(url, options).then((response) => {\n this._user = response;\n this._pendingUserRequest = null;\n return response;\n });\n\n return this._pendingUserRequest;\n }\n }\n\n /**\n * Returns information about the currently logged in user's [portal](https://developers.arcgis.com/rest/users-groups-and-items/portal-self.htm). Subsequent calls will *not* result in additional web traffic.\n *\n * ```js\n * session.getPortal()\n * .then(response => {\n * console.log(portal.name); // \"City of ...\"\n * })\n * ```\n *\n * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.\n * @returns A Promise that will resolve with the data from the response.\n */\n public getPortal(requestOptions?: IRequestOptions): Promise<any> {\n if (this._pendingPortalRequest) {\n return this._pendingPortalRequest;\n } else if (this._portalInfo) {\n return Promise.resolve(this._portalInfo);\n } else {\n const url = `${this.portal}/portals/self`;\n\n const options = {\n httpMethod: \"GET\",\n authentication: this,\n ...requestOptions,\n rawResponse: false,\n } as IRequestOptions;\n\n this._pendingPortalRequest = request(url, options).then((response) => {\n this._portalInfo = response;\n this._pendingPortalRequest = null;\n return response;\n });\n\n return this._pendingPortalRequest;\n }\n }\n\n /**\n * Returns the username for the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic. This is also used internally when a username is required for some requests but is not present in the options.\n *\n * * ```js\n * session.getUsername()\n * .then(response => {\n * console.log(response); // \"casey_jones\"\n * })\n * ```\n */\n public getUsername() {\n if (this.username) {\n return Promise.resolve(this.username);\n } else if (this._user) {\n return Promise.resolve(this._user.username);\n } else {\n return this.getUser().then((user) => {\n return user.username;\n });\n }\n }\n\n /**\n * Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and\n * the request is to an ArcGIS Online domain `token` will be used. If the request\n * is to the current `portal` the current `token` will also be used. However if\n * the request is to an unknown server we will validate the server with a request\n * to our current `portal`.\n */\n public getToken(url: string, requestOptions?: ITokenRequestOptions) {\n if (canUseOnlineToken(this.portal, url)) {\n return this.getFreshToken(requestOptions);\n } else if (new RegExp(this.portal, \"i\").test(url)) {\n return this.getFreshToken(requestOptions);\n } else {\n return this.getTokenForServer(url, requestOptions);\n }\n }\n\n /**\n * Get application access information for the current user\n * see `validateAppAccess` function for details\n *\n * @param clientId application client id\n */\n public validateAppAccess(clientId: string): Promise<IAppAccess> {\n return this.getToken(this.portal).then((token) => {\n return validateAppAccess(token, clientId);\n });\n }\n\n public toJSON(): IUserSessionOptions {\n return {\n clientId: this.clientId,\n refreshToken: this.refreshToken,\n refreshTokenExpires: this.refreshTokenExpires,\n username: this.username,\n password: this.password,\n token: this.token,\n tokenExpires: this.tokenExpires,\n portal: this.portal,\n ssl: this.ssl,\n tokenDuration: this.tokenDuration,\n redirectUri: this.redirectUri,\n refreshTokenTTL: this.refreshTokenTTL,\n };\n }\n\n public serialize() {\n return JSON.stringify(this);\n }\n /**\n * For a \"Host\" app that embeds other platform apps via iframes, after authenticating the user\n * and creating a UserSession, the app can then enable \"post message\" style authentication by calling\n * this method.\n *\n * Internally this adds an event listener on window for the `message` event\n *\n * @param validChildOrigins Array of origins that are allowed to request authentication from the host app\n */\n public enablePostMessageAuth(validChildOrigins: string[], win?: any): any {\n /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */\n if (!win && window) {\n win = window;\n }\n this._hostHandler = this.createPostMessageHandler(validChildOrigins);\n win.addEventListener(\"message\", this._hostHandler, false);\n }\n\n /**\n * For a \"Host\" app that has embedded other platform apps via iframes, when the host needs\n * to transition routes, it should call `UserSession.disablePostMessageAuth()` to remove\n * the event listener and prevent memory leaks\n */\n public disablePostMessageAuth(win?: any) {\n /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */\n if (!win && window) {\n win = window;\n }\n win.removeEventListener(\"message\", this._hostHandler, false);\n }\n\n /**\n * Manually refreshes the current `token` and `tokenExpires`.\n */\n public refreshSession(\n requestOptions?: ITokenRequestOptions\n ): Promise<UserSession> {\n // make sure subsequent calls to getUser() don't returned cached metadata\n this._user = null;\n\n if (this.username && this.password) {\n return this.refreshWithUsernameAndPassword(requestOptions);\n }\n\n if (this.clientId && this.refreshToken) {\n return this.refreshWithRefreshToken();\n }\n\n return Promise.reject(new ArcGISAuthError(\"Unable to refresh token.\"));\n }\n\n /**\n * Determines the root of the ArcGIS Server or Portal for a given URL.\n *\n * @param url the URl to determine the root url for.\n */\n public getServerRootUrl(url: string) {\n const [root] = cleanUrl(url).split(\n /\\/rest(\\/admin)?\\/services(?:\\/|#|\\?|$)/\n );\n const [match, protocol, domainAndPath] = root.match(/(https?:\\/\\/)(.+)/);\n const [domain, ...path] = domainAndPath.split(\"/\");\n\n // only the domain is lowercased because in some cases an org id might be\n // in the path which cannot be lowercased.\n return `${protocol}${domain.toLowerCase()}/${path.join(\"/\")}`;\n }\n\n /**\n * Returns the proper [`credentials`] option for `fetch` for a given domain.\n * See [trusted server](https://enterprise.arcgis.com/en/portal/latest/administer/windows/configure-security.htm#ESRI_SECTION1_70CC159B3540440AB325BE5D89DBE94A).\n * Used internally by underlying request methods to add support for specific security considerations.\n *\n * @param url The url of the request\n * @returns \"include\" or \"same-origin\"\n */\n public getDomainCredentials(url: string): RequestCredentials {\n if (!this.trustedDomains || !this.trustedDomains.length) {\n return \"same-origin\";\n }\n\n return this.trustedDomains.some((domainWithProtocol) => {\n return url.startsWith(domainWithProtocol);\n })\n ? \"include\"\n : \"same-origin\";\n }\n\n /**\n * Return a function that closes over the validOrigins array and\n * can be used as an event handler for the `message` event\n *\n * @param validOrigins Array of valid origins\n */\n private createPostMessageHandler(\n validOrigins: string[]\n ): (event: any) => void {\n // return a function that closes over the validOrigins and\n // has access to the credential\n return (event: any) => {\n // Verify that the origin is valid\n // Note: do not use regex's here. validOrigins is an array so we're checking that the event's origin\n // is in the array via exact match. More info about avoiding postMessage xss issues here\n // https://jlajara.gitlab.io/web/2020/07/17/Dom_XSS_PostMessage_2.html#tipsbypasses-in-postmessage-vulnerabilities\n const isValidOrigin = validOrigins.indexOf(event.origin) > -1;\n // JSAPI handles this slightly differently - instead of checking a list, it will respond if\n // event.origin === window.location.origin || event.origin.endsWith('.arcgis.com')\n // For Hub, and to enable cross domain debugging with port's in urls, we are opting to\n // use a list of valid origins\n\n // Ensure the message type is something we want to handle\n const isValidType = event.data.type === \"arcgis:auth:requestCredential\";\n\n const isTokenValid = this.tokenExpires.getTime() > Date.now();\n\n if (isValidOrigin && isValidType) {\n let msg = {};\n if (isTokenValid) {\n const credential = this.toCredential();\n // arcgis:auth:error with {name: \"\", message: \"\"}\n // the following line allows us to conform to our spec without changing other depended-on functionality\n // https://github.com/Esri/arcgis-rest-js/blob/master/packages/arcgis-rest-auth/post-message-auth-spec.md#arcgisauthcredential\n credential.server = credential.server.replace(\"/sharing/rest\", \"\");\n msg = { type: \"arcgis:auth:credential\", credential };\n } else {\n // Return an error\n msg = {\n type: \"arcgis:auth:error\",\n error: {\n name: \"tokenExpiredError\",\n message:\n \"Session token was expired, and not returned to the child application\",\n },\n };\n }\n event.source.postMessage(msg, event.origin);\n }\n };\n }\n\n /**\n * Validates that a given URL is properly federated with our current `portal`.\n * Attempts to use the internal `federatedServers` cache first.\n */\n private getTokenForServer(\n url: string,\n requestOptions?: ITokenRequestOptions\n ) {\n // requests to /rest/services/ and /rest/admin/services/ are both valid\n // Federated servers may have inconsistent casing, so lowerCase it\n const root = this.getServerRootUrl(url);\n const existingToken = this.federatedServers[root];\n\n if (\n existingToken &&\n existingToken.expires &&\n existingToken.expires.getTime() > Date.now()\n ) {\n return Promise.resolve(existingToken.token);\n }\n\n if (this._pendingTokenRequests[root]) {\n return this._pendingTokenRequests[root];\n }\n\n this._pendingTokenRequests[root] = this.fetchAuthorizedDomains().then(\n () => {\n return request(`${root}/rest/info`, {\n credentials: this.getDomainCredentials(url),\n })\n .then((response) => {\n if (response.owningSystemUrl) {\n /**\n * if this server is not owned by this portal\n * bail out with an error since we know we wont\n * be able to generate a token\n */\n if (!isFederated(response.owningSystemUrl, this.portal)) {\n throw new ArcGISAuthError(\n `${url} is not federated with ${this.portal}.`,\n \"NOT_FEDERATED\"\n );\n } else {\n /**\n * if the server is federated, use the relevant token endpoint.\n */\n return request(\n `${response.owningSystemUrl}/sharing/rest/info`,\n requestOptions\n );\n }\n } else if (\n response.authInfo &&\n this.federatedServers[root] !== undefined\n ) {\n /**\n * if its a stand-alone instance of ArcGIS Server that doesn't advertise\n * federation, but the root server url is recognized, use its built in token endpoint.\n */\n return Promise.resolve({\n authInfo: response.authInfo,\n });\n } else {\n throw new ArcGISAuthError(\n `${url} is not federated with any portal and is not explicitly trusted.`,\n \"NOT_FEDERATED\"\n );\n }\n })\n .then((response: any) => {\n return response.authInfo.tokenServicesUrl;\n })\n .then((tokenServicesUrl: string) => {\n // an expired token cant be used to generate a new token\n if (this.token && this.tokenExpires.getTime() > Date.now()) {\n return generateToken(tokenServicesUrl, {\n params: {\n token: this.token,\n serverUrl: url,\n expiration: this.tokenDuration,\n client: \"referer\",\n },\n });\n // generate an entirely fresh token if necessary\n } else {\n return generateToken(tokenServicesUrl, {\n params: {\n username: this.username,\n password: this.password,\n expiration: this.tokenDuration,\n client: \"referer\",\n },\n }).then((response: any) => {\n this._token = response.token;\n this._tokenExpires = new Date(response.expires);\n return response;\n });\n }\n })\n .then((response) => {\n this.federatedServers[root] = {\n expires: new Date(response.expires),\n token: response.token,\n };\n delete this._pendingTokenRequests[root];\n return response.token;\n });\n }\n );\n\n return this._pendingTokenRequests[root];\n }\n\n /**\n * Returns an unexpired token for the current `portal`.\n */\n private getFreshToken(requestOptions?: ITokenRequestOptions) {\n if (this.token && !this.tokenExpires) {\n return Promise.resolve(this.token);\n }\n\n if (\n this.token &&\n this.tokenExpires &&\n this.tokenExpires.getTime() > Date.now()\n ) {\n return Promise.resolve(this.token);\n }\n\n if (!this._pendingTokenRequests[this.portal]) {\n this._pendingTokenRequests[this.portal] = this.refreshSession(\n requestOptions\n ).then((session) => {\n this._pendingTokenRequests[this.portal] = null;\n return session.token;\n });\n }\n\n return this._pendingTokenRequests[this.portal];\n }\n\n /**\n * Refreshes the current `token` and `tokenExpires` with `username` and\n * `password`.\n */\n private refreshWithUsernameAndPassword(\n requestOptions?: ITokenRequestOptions\n ) {\n const options = {\n params: {\n username: this.username,\n password: this.password,\n expiration: this.tokenDuration,\n },\n ...requestOptions,\n };\n return generateToken(`${this.portal}/generateToken`, options).then(\n (response: any) => {\n this._token = response.token;\n this._tokenExpires = new Date(response.expires);\n return this;\n }\n );\n }\n\n /**\n * Refreshes the current `token` and `tokenExpires` with `refreshToken`.\n */\n private refreshWithRefreshToken(requestOptions?: ITokenRequestOptions) {\n if (\n this.refreshToken &&\n this.refreshTokenExpires &&\n this.refreshTokenExpires.getTime() < Date.now()\n ) {\n return this.refreshRefreshToken(requestOptions);\n }\n\n const options: ITokenRequestOptions = {\n params: {\n client_id: this.clientId,\n refresh_token: this.refreshToken,\n grant_type: \"refresh_token\",\n },\n ...requestOptions,\n };\n return fetchToken(`${this.portal}/oauth2/token`, options).then(\n (response) => {\n this._token = response.token;\n this._tokenExpires = response.expires;\n return this;\n }\n );\n }\n\n /**\n * Exchanges an unexpired `refreshToken` for a new one, also updates `token` and\n * `tokenExpires`.\n */\n private refreshRefreshToken(requestOptions?: ITokenRequestOptions) {\n const options: ITokenRequestOptions = {\n params: {\n client_id: this.clientId,\n refresh_token: this.refreshToken,\n redirect_uri: this.redirectUri,\n grant_type: \"exchange_refresh_token\",\n },\n ...requestOptions,\n };\n\n return fetchToken(`${this.portal}/oauth2/token`, options).then(\n (response) => {\n this._token = response.token;\n this._tokenExpires = response.expires;\n this._refreshToken = response.refreshToken;\n this._refreshTokenExpires = new Date(\n Date.now() + (this.refreshTokenTTL - 1) * 60 * 1000\n );\n return this;\n }\n );\n }\n\n /**\n * ensures that the authorizedCrossOriginDomains are obtained from the portal and cached\n * so we can check them later.\n *\n * @returns this\n */\n private fetchAuthorizedDomains() {\n // if this token is for a specific server or we don't have a portal\n // don't get the portal info because we cant get the authorizedCrossOriginDomains\n if (this.server || !this.portal) {\n return Promise.resolve(this);\n }\n\n return this.getPortal().then((portalInfo) => {\n /**\n * Specific domains can be configured as secure.esri.com or https://secure.esri.com this\n * normalizes to https://secure.esri.com so we can use startsWith later.\n */\n if (\n portalInfo.authorizedCrossOriginDomains &&\n portalInfo.authorizedCrossOriginDomains.length\n ) {\n this.trustedDomains = portalInfo.authorizedCrossOriginDomains\n .filter((d: string) => !d.startsWith(\"http://\"))\n .map((d: string) => {\n if (d.startsWith(\"https://\")) {\n return d;\n } else {\n return `https://${d}`;\n }\n });\n }\n return this;\n });\n }\n}\n","/* Copyright (c) 2018-2020 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport { IRequestOptions, request } from \"@esri/arcgis-rest-request\";\n\n/**\n * Request app-specific token, passing in the token for the current app.\n *\n * This call returns a token after performing the same checks made by validateAppAccess.\n * It returns an app-specific token of the signed-in user only if the user has access\n * to the app and the encrypted platform cookie is valid.\n *\n * A scenario where an app would use this is if it is iframed into another platform app\n * and receives credentials via postMessage. Those credentials contain a token that is\n * specific to the host app, so the embedded app would use `exchangeToken` to get one\n * that is specific to itself.\n *\n * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within\n * an ArcGIS Enterprise installation. Custom applications can not use this.\n *\n * @param token\n * @param clientId application\n * @param portal\n */\nexport function exchangeToken(\n token: string,\n clientId: string,\n portal = \"https://www.arcgis.com/sharing/rest\"\n): Promise<string> {\n const url = `${portal}/oauth2/exchangeToken`;\n const ro = {\n method: \"POST\",\n params: {\n f: \"json\",\n client_id: clientId,\n token,\n },\n } as IRequestOptions;\n // make the request and return the token\n return request(url, ro).then((response) => response.token);\n}\n\n/**\n * @internal\n * Response from the `platformSelf(...)` function.\n */\nexport interface IPlatformSelfResponse {\n /**\n * Username of the user the encrypted cookie was issued for\n */\n username: string;\n /**\n * Token the consuming application can use, It is tied to the\n * clientId used in the `platformSelf` call\n */\n token: string;\n /**\n * Token expiration, in seconds-from-now\n */\n expires_in: number;\n}\n\n/**\n * @internal\n * Request a token for a specific application using the esri_aopc encrypted cookie\n *\n * When a client app boots up, it will know its clientId and the redirectUri for use\n * in the normal /oauth/authorize pop-out oAuth flow.\n *\n * If the app sees an `esri_aopc` cookie (only set if the app is hosted on *.arcgis.com),\n * it can call the /oauth2/platformSelf end-point passing in the clientId and redirectUri\n * in headers, and it will receive back an app-specific token, assuming the user has\n * access to the app.\n *\n * Since there are scenarios where an app can boot using credentials/token from localstorage\n * but those credentials are not for the same user as the esri_aopc cookie, it is recommended that\n * an app check the returned username against any existing identity they may have loaded.\n *\n * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within\n * an ArcGIS Enterprise installation. Custom applications can not use this.\n *\n * ```js\n * // convert the encrypted platform cookie into a UserSession\n * import { platformSelf, UserSession } from '@esri/arcgis-rest-auth';\n *\n * const portal = 'https://www.arcgis.com/sharing/rest';\n * const clientId = 'YOURAPPCLIENTID';\n *\n * // exchange esri_aopc cookie\n * return platformSelf(clientId, 'https://your-app-redirect-uri', portal)\n * .then((response) => {\n * const currentTimestamp = new Date().getTime();\n * const tokenExpiresTimestamp = currentTimestamp + (response.expires_in * 1000);\n * // Construct the session and return it\n * return new UserSession({\n * portal,\n * clientId,\n * username: response.username,\n * token: response.token,\n * tokenExpires: new Date(tokenExpiresTimestamp),\n * ssl: true\n * });\n * })\n *\n * ```\n *\n *\n * @param clientId\n * @param redirectUri\n * @param portal\n */\nexport function platformSelf(\n clientId: string,\n redirectUri: string,\n portal = \"https://www.arcgis.com/sharing/rest\"\n): Promise<IPlatformSelfResponse> {\n // TEMPORARY: the f=json should not be needed, but currently is\n const url = `${portal}/oauth2/platformSelf?f=json`;\n const ro = {\n method: \"POST\",\n headers: {\n \"X-Esri-Auth-Client-Id\": clientId,\n \"X-Esri-Auth-Redirect-Uri\": redirectUri,\n },\n // Note: request has logic to include the cookie\n // for platformSelf calls w/ the X-Esri-Auth-Client-Id header\n params: {\n f: \"json\",\n },\n } as IRequestOptions;\n // make the request and return the token\n return request(url, ro);\n}\n"],"names":["fetchToken","url","requestOptions","options","rawResponse","request","then","response","r","token","access_token","username","expires","Date","now","expires_in","ssl","refresh_token","refreshToken","ApplicationSession","this","getTime","Promise","resolve","_pendingTokenRequest","params","client_id","clientId","client_secret","clientSecret","grant_type","expiration","duration","portal","_this","ApiKey","key","generateToken","window","location","host","referer","NODEJS_DEFAULT_REFERER_HEADER","arcgisOnlineUrlRegex","isOnline","test","getOnlineEnvironment","subdomain","match","split","pop","includes","isFederated","owningSystemUrl","portalUrl","normalizedPortalUrl","cleanUrl","normalizeOnlinePortalUrl","replace","normalizedOwningSystemUrl","RegExp","validateAppAccess","ro","method","f","Object","UserSession","_token","_tokenExpires","_refreshToken","_refreshTokenExpires","console","log","federatedServers","win","_a","provider","popup","popupWindowFeatures","state","locale","redirectUri","encodeURIComponent","encodeQueryString","deferred","session","promise","reject","errorString","oauthInfoString","error","JSON","parse","ArcGISAuthError","errorMessage","oauthInfo","tokenExpires","open","href","completeSignIn","handlerFn","handlerFnName","opener","parent","stringify","undefined","close","e","decodeQueryString","hash","error_description","parseInt","parentOrigin","handler","event","source","data","parentMessageHandler","err","addEventListener","postMessage","type","removeEventListener","writeHead","Location","end","authorizationCode","refreshTokenTTL","redirect_uri","code","refreshTokenExpires","str","password","tokenDuration","credential","server","userId","fromCredential","Error","message","name","_pendingUserRequest","_user","__assign","httpMethod","authentication","_pendingPortalRequest","_portalInfo","getUser","user","requestUrl","portalIsOnline","requestIsOnline","portalEnv","requestEnv","getFreshToken","getTokenForServer","getToken","validChildOrigins","_hostHandler","createPostMessageHandler","refreshWithUsernameAndPassword","refreshWithRefreshToken","protocol","_b","domain","path","toLowerCase","join","trustedDomains","length","some","domainWithProtocol","startsWith","validOrigins","isValidOrigin","indexOf","origin","isValidType","isTokenValid","msg","toCredential","root","getServerRootUrl","existingToken","_pendingTokenRequests","fetchAuthorizedDomains","credentials","getDomainCredentials","authInfo","tokenServicesUrl","serverUrl","client","refreshSession","refreshRefreshToken","getPortal","portalInfo","authorizedCrossOriginDomains","filter","d","map","headers","X-Esri-Auth-Client-Id","X-Esri-Auth-Redirect-Uri"],"mappings":";;;;;2iBAyBgBA,EACdC,EACAC,GAMA,OAFAC,EAAQC,aAAc,EAEfC,UAAQJ,EAAKE,GAASG,KAAK,SAACC,GACjC,IAAMC,EAAyB,CAC7BC,MAAOF,EAASG,aAChBC,SAAUJ,EAASI,SACnBC,QAAS,IAAIC,KAEXA,KAAKC,OAA+B,IAAtBP,EAASQ,WAAoB,MAE7CC,KAAsB,IAAjBT,EAASS,KAMhB,OAJIT,EAASU,gBACXT,EAAEU,aAAeX,EAASU,eAGrBT,WCkCFW,qBAAP,SACElB,EACAC,GAEA,OAAIkB,KAAKX,OAASW,KAAKR,SAAWQ,KAAKR,QAAQS,UAAYR,KAAKC,MACvDQ,QAAQC,QAAQH,KAAKX,OAG1BW,KAAKI,uBAITJ,KAAKI,qBAAuBJ,KAAKF,aAAahB,GAEvCkB,KAAKI,uBAGPL,yBAAP,SAAoBjB,GAApB,WACQC,KACJsB,OAAQ,CACNC,UAAWN,KAAKO,SAChBC,cAAeR,KAAKS,aACpBC,WAAY,qBACZC,WAAYX,KAAKY,WAEhB9B,GAEL,OAAOF,EAAcoB,KAAKa,wBAAwB9B,GAASG,KACzD,SAAAC,GAIE,OAHA2B,EAAKV,qBAAuB,KAC5BU,EAAKzB,MAAQF,EAASE,MACtByB,EAAKtB,QAAUL,EAAS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AAS,CACPC,wBAAyB/K,EACzBgL,2BAA4B1H,GAI9BxD,OAAQ,CACNuC,EAAG,SAIA3D,UAAQJ,EAAK6D"}
1
+ {"version":3,"file":"auth.umd.min.js","sources":["../../src/fetch-token.ts","../../src/ApplicationSession.ts","../../src/ApiKey.ts","../../src/generate-token.ts","../../src/federation-utils.ts","../../src/validate-app-access.ts","../../src/UserSession.ts","../../src/app-tokens.ts"],"sourcesContent":["/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n request,\n IRequestOptions,\n ITokenRequestOptions\n} from \"@esri/arcgis-rest-request\";\n\ninterface IFetchTokenRawResponse {\n access_token: string;\n expires_in: number;\n username: string;\n ssl?: boolean;\n refresh_token?: string;\n}\n\nexport interface IFetchTokenResponse {\n token: string;\n expires: Date;\n username: string;\n ssl: boolean;\n refreshToken?: string;\n}\n\nexport function fetchToken(\n url: string,\n requestOptions: ITokenRequestOptions\n): Promise<IFetchTokenResponse> {\n const options: IRequestOptions = requestOptions;\n // we generate a response, so we can't return the raw response\n options.rawResponse = false;\n\n return request(url, options).then((response: IFetchTokenRawResponse) => {\n const r: IFetchTokenResponse = {\n token: response.access_token,\n username: response.username,\n expires: new Date(\n // convert seconds in response to milliseconds and add the value to the current time to calculate a static expiration timestamp\n Date.now() + (response.expires_in * 1000 - 1000)\n ),\n ssl: response.ssl === true\n };\n if (response.refresh_token) {\n r.refreshToken = response.refresh_token;\n }\n\n return r;\n });\n}\n","/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n IAuthenticationManager,\n ITokenRequestOptions\n} from \"@esri/arcgis-rest-request\";\nimport { fetchToken } from \"./fetch-token\";\n\nexport interface IApplicationSessionOptions {\n /**\n * Client ID of your application. Can be obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n clientId: string;\n\n /**\n * A Client Secret is also obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise. Treat it like a password.\n */\n clientSecret: string;\n\n /**\n * OAuth 2.0 access token from a previous application session.\n */\n token?: string;\n\n /**\n * Expiration date for the `token`\n */\n expires?: Date;\n\n /**\n * URL of ArcGIS REST base, defaults to \"https://www.arcgis.com/sharing/rest\"\n */\n portal?: string;\n\n /**\n * Duration of requested tokens in minutes. defaults to 7200 (5 days).\n */\n duration?: number;\n}\n\n/**\n * ```js\n * import { ApplicationSession } from '@esri/arcgis-rest-auth';\n * const session = new ApplicationSession({\n * clientId: \"abc123\",\n * clientSecret: \"sshhhhhh\"\n * })\n * // visit https://developers.arcgis.com to generate your own clientid and secret\n * ```\n * You can use [App Login](/arcgis-rest-js/guides/node/) to access premium content and services in ArcGIS Online.\n *\n */\nexport class ApplicationSession implements IAuthenticationManager {\n public portal: string;\n private clientId: string;\n private clientSecret: string;\n private token: string;\n private expires: Date;\n private duration: number;\n\n /**\n * Internal object to keep track of pending token requests. Used to prevent\n * duplicate token requests.\n */\n private _pendingTokenRequest: Promise<string>;\n\n constructor(options: IApplicationSessionOptions) {\n this.clientId = options.clientId;\n this.clientSecret = options.clientSecret;\n this.token = options.token;\n this.expires = options.expires;\n this.portal = options.portal || \"https://www.arcgis.com/sharing/rest\";\n this.duration = options.duration || 7200;\n }\n\n // URL is not actually read or passed through.\n public getToken(\n url: string,\n requestOptions?: ITokenRequestOptions\n ): Promise<string> {\n if (this.token && this.expires && this.expires.getTime() > Date.now()) {\n return Promise.resolve(this.token);\n }\n\n if (this._pendingTokenRequest) {\n return this._pendingTokenRequest;\n }\n\n this._pendingTokenRequest = this.refreshToken(requestOptions);\n\n return this._pendingTokenRequest;\n }\n\n public refreshToken(requestOptions?: ITokenRequestOptions): Promise<string> {\n const options = {\n params: {\n client_id: this.clientId,\n client_secret: this.clientSecret,\n grant_type: \"client_credentials\",\n expiration: this.duration\n },\n ...requestOptions\n };\n return fetchToken(`${this.portal}/oauth2/token/`, options).then(\n response => {\n this._pendingTokenRequest = null;\n this.token = response.token;\n this.expires = response.expires;\n return response.token;\n }\n );\n }\n\n public refreshSession() {\n return this.refreshToken().then(() => this);\n }\n}\n","/* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n IAuthenticationManager,\n} from \"@esri/arcgis-rest-request\";\n\n/**\n * Options for the `ApiKey` constructor.\n */\nexport interface IApiKeyOptions {\n key: string;\n}\n\n/**\n * ```js\n * import { ApiKey } from '@esri/arcgis-rest-auth';\n * const apiKey = new ApiKey(\"...\");\n * ```\n * Used to authenticate with API Keys.\n */\nexport class ApiKey implements IAuthenticationManager {\n\n /**\n * The current portal the user is authenticated with.\n */\n public readonly portal: string;\n\n private key: string;\n\n constructor(options: IApiKeyOptions) {\n this.key = options.key;\n }\n\n /**\n * Gets a token (the API Key).\n */\n public getToken(url: string) {\n return Promise.resolve(this.key);\n }\n}\n","/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport {\n request,\n IRequestOptions,\n ITokenRequestOptions,\n NODEJS_DEFAULT_REFERER_HEADER,\n} from \"@esri/arcgis-rest-request\";\n\nexport interface IGenerateTokenResponse {\n token: string;\n expires: number;\n ssl: boolean;\n}\n\nexport function generateToken(\n url: string,\n requestOptions: ITokenRequestOptions\n): Promise<IGenerateTokenResponse> {\n const options: IRequestOptions = requestOptions;\n\n /* istanbul ignore else */\n if (\n typeof window !== \"undefined\" &&\n window.location &&\n window.location.host\n ) {\n options.params.referer = window.location.host;\n } else {\n options.params.referer = NODEJS_DEFAULT_REFERER_HEADER;\n }\n\n return request(url, options);\n}\n","import { cleanUrl } from \"@esri/arcgis-rest-request\";\n/**\n * Used to test if a URL is an ArcGIS Online URL\n */\nconst arcgisOnlineUrlRegex = /^https?:\\/\\/(\\S+)\\.arcgis\\.com.+/;\n\n/**\n * Used to test if a URL is production ArcGIS Online Portal\n */\nconst arcgisOnlinePortalRegex = /^https?:\\/\\/(dev|devext|qa|qaext|www)\\.arcgis\\.com\\/sharing\\/rest+/;\n\n/**\n * Used to test if a URL is an ArcGIS Online Organization Portal\n */\nconst arcgisOnlineOrgPortalRegex = /^https?:\\/\\/(?:[a-z0-9-]+\\.maps(dev|devext|qa|qaext)?)?.arcgis\\.com\\/sharing\\/rest/;\n\nexport function isOnline(url: string): boolean {\n return arcgisOnlineUrlRegex.test(url);\n}\n\nexport function normalizeOnlinePortalUrl(portalUrl: string): string {\n if (!arcgisOnlineUrlRegex.test(portalUrl)) {\n return portalUrl;\n }\n\n switch (getOnlineEnvironment(portalUrl)) {\n case \"dev\":\n return \"https://devext.arcgis.com/sharing/rest\";\n case \"qa\":\n return \"https://qaext.arcgis.com/sharing/rest\";\n default:\n return \"https://www.arcgis.com/sharing/rest\";\n }\n}\n\nexport function getOnlineEnvironment(url: string): string {\n if (!arcgisOnlineUrlRegex.test(url)) {\n return null;\n }\n\n const match = url.match(arcgisOnlineUrlRegex);\n const subdomain = match[1].split(\".\").pop();\n\n if (subdomain.includes(\"dev\")) {\n return \"dev\";\n }\n\n if (subdomain.includes(\"qa\")) {\n return \"qa\";\n }\n\n return \"production\";\n}\n\nexport function isFederated(\n owningSystemUrl: string,\n portalUrl: string\n): boolean {\n const normalizedPortalUrl = cleanUrl(\n normalizeOnlinePortalUrl(portalUrl)\n ).replace(/https?:\\/\\//, \"\");\n\n const normalizedOwningSystemUrl = cleanUrl(owningSystemUrl).replace(\n /https?:\\/\\//,\n \"\"\n );\n\n return new RegExp(normalizedOwningSystemUrl, \"i\").test(normalizedPortalUrl);\n}\n\nexport function canUseOnlineToken(\n portalUrl: string,\n requestUrl: string\n): boolean {\n const portalIsOnline = isOnline(portalUrl);\n const requestIsOnline = isOnline(requestUrl);\n const portalEnv = getOnlineEnvironment(portalUrl);\n const requestEnv = getOnlineEnvironment(requestUrl);\n\n if (portalIsOnline && requestIsOnline && portalEnv === requestEnv) {\n return true;\n }\n\n return false;\n}\n","/* Copyright (c) 2018-2020 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport { IRequestOptions, request } from \"@esri/arcgis-rest-request\";\n\nexport interface IAppAccess {\n /**\n * Verifies that the token is valid and the user has access to\n * the specified app (clientId)\n */\n valid: boolean;\n /**\n * Should the app present the current user with a \"View Only\" mode\n */\n viewOnlyUserTypeApp: boolean;\n}\n\n/**\n * Validates that the user has access to the application\n * and if they user should be presented a \"View Only\" mode\n *\n * This is only needed/valid for Esri applications that are \"licensed\"\n * and shipped in ArcGIS Online or ArcGIS Enterprise. Most custom applications\n * should not need or use this.\n *\n * ```js\n * import { validateAppAccess } from '@esri/arcgis-rest-auth';\n *\n * return validateAppAccess('your-token', 'theClientId')\n * .then((result) => {\n * if (!result.value) {\n * // redirect or show some other ui\n * } else {\n * if (result.viewOnlyUserTypeApp) {\n * // use this to inform your app to show a \"View Only\" mode\n * }\n * }\n * })\n * .catch((err) => {\n * // two possible errors\n * // invalid clientId: {\"error\":{\"code\":400,\"messageCode\":\"GWM_0007\",\"message\":\"Invalid request\",\"details\":[]}}\n * // invalid token: {\"error\":{\"code\":498,\"message\":\"Invalid token.\",\"details\":[]}}\n * })\n * ```\n *\n * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within\n * an ArcGIS Enterprise installation. Custom applications can not use this.\n *\n * @param token platform token\n * @param clientId application client id\n * @param portal Optional\n */\nexport function validateAppAccess(\n token: string,\n clientId: string,\n portal = \"https://www.arcgis.com/sharing/rest\"\n): Promise<IAppAccess> {\n const url = `${portal}/oauth2/validateAppAccess`;\n const ro = {\n method: \"POST\",\n params: {\n f: \"json\",\n client_id: clientId,\n token,\n },\n } as IRequestOptions;\n return request(url, ro);\n}\n","/* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\n/**\n * /generateToken returns a token that cannot be refreshed.\n *\n * oauth2/token can return a token *and* a refreshToken.\n * up until the refreshToken expires, you can use it (and a clientId)\n * to fetch fresh credentials without a username and password.\n *\n * the catch is that this 'authorization_code' flow is only utilized\n * by server based OAuth 2 Node.js applications that call /authorize first.\n */\n\nimport * as http from \"http\";\nimport {\n request,\n IRequestOptions,\n ArcGISAuthError,\n IAuthenticationManager,\n ITokenRequestOptions,\n cleanUrl,\n encodeQueryString,\n decodeQueryString,\n isNoCorsDomain,\n} from \"@esri/arcgis-rest-request\";\nimport { IUser } from \"@esri/arcgis-rest-types\";\nimport { generateToken } from \"./generate-token\";\nimport { fetchToken, IFetchTokenResponse } from \"./fetch-token\";\nimport { canUseOnlineToken, isFederated } from \"./federation-utils\";\nimport { IAppAccess, validateAppAccess } from \"./validate-app-access\";\n\n/**\n * Internal utility for resolving a Promise from outside its constructor.\n *\n * See: http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/\n */\ninterface IDeferred<T> {\n promise: Promise<T>;\n resolve: (v: T) => void;\n reject: (v: any) => void;\n}\n\nexport type AuthenticationProvider =\n | \"arcgis\"\n | \"facebook\"\n | \"google\"\n | \"github\"\n | \"apple\";\n\n/**\n * Represents a [credential](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-Credential.html)\n * object used to access a secure ArcGIS resource.\n */\nexport interface ICredential {\n expires: number;\n server: string;\n ssl: boolean;\n token: string;\n userId: string;\n}\n\nfunction defer<T>(): IDeferred<T> {\n const deferred: any = {\n promise: null,\n resolve: null,\n reject: null,\n };\n\n deferred.promise = new Promise((resolve, reject) => {\n deferred.resolve = resolve;\n deferred.reject = reject;\n });\n\n return deferred as IDeferred<T>;\n}\n\n/**\n * Options for static OAuth 2.0 helper methods on `UserSession`.\n */\nexport interface IOAuth2Options {\n /**\n * Client ID of your application. Can be obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n clientId: string;\n\n /**\n * A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n redirectUri: string;\n\n /**\n * The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.\n */\n portal?: string;\n\n /**\n * ArcGIS Authentication is used by default. Specifying an alternative will take users directly to the corresponding provider's OAuth page.\n */\n\n provider?: AuthenticationProvider;\n\n /**\n * The requested validity in minutes for a token. Defaults to 20160 (two weeks).\n */\n expiration?: number;\n\n /**\n * Duration (in minutes) that a token will be valid. Defaults to 20160 (two weeks).\n *\n * @deprecated use 'expiration' instead\n */\n duration?: number;\n\n /**\n * Determines whether to open the authorization window in a new tab/window or in the current window.\n *\n * @browserOnly\n */\n popup?: boolean;\n\n /**\n * The window features passed to [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) when `popup` is true. Defaults to `height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes`\n *\n * @browserOnly\n */\n popupWindowFeatures?: string;\n\n /**\n * Duration (in minutes) that a refresh token will be valid.\n *\n * @nodeOnly\n */\n refreshTokenTTL?: number;\n\n /**\n * The locale assumed to render the login page.\n *\n * @browserOnly\n */\n locale?: string;\n\n /**\n * Applications can specify an opaque value for this parameter to correlate the authorization request sent with the received response. By default, clientId is used.\n *\n * @browserOnly\n */\n state?: string;\n\n [key: string]: any;\n}\n\n/**\n * Options for the `UserSession` constructor.\n */\nexport interface IUserSessionOptions {\n /**\n * Client ID of your application. Can be obtained by registering an application\n * on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n clientId?: string;\n\n /**\n * A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),\n * [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.\n */\n redirectUri?: string;\n\n /**\n * OAuth 2.0 refresh token from a previous user session.\n */\n refreshToken?: string;\n\n /**\n * Expiration date of the `refreshToken`\n */\n refreshTokenExpires?: Date;\n\n /**\n * The authenticated user's username. Guaranteed to be unique across ArcGIS Online or your instance of ArcGIS Enterprise.\n */\n username?: string;\n\n /**\n * Password for this user. Used in CLI apps where users cannot do OAuth 2.0.\n */\n password?: string;\n\n /**\n * OAuth 2.0 access token from a previous user session.\n */\n token?: string;\n\n /**\n * Expiration date for the `token`\n */\n tokenExpires?: Date;\n\n /**\n * The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.\n */\n portal?: string;\n\n /**\n * This value is set to true automatically if the ArcGIS Organization requires that requests be made over https.\n */\n ssl?: boolean;\n\n /**\n * ArcGIS Authentication is used by default. Specifying an alternative will take users directly to the corresponding provider's OAuth page.\n */\n provider?: AuthenticationProvider;\n\n /**\n * Duration of requested token validity in minutes. Used when requesting tokens with `username` and `password` or when validating the identity of unknown servers. Defaults to two weeks.\n */\n tokenDuration?: number;\n\n /**\n * Duration (in minutes) that a refresh token will be valid.\n */\n refreshTokenTTL?: number;\n\n /**\n * An unfederated ArcGIS Server instance known to recognize credentials supplied manually.\n * ```js\n * {\n * server: \"https://sampleserver6.arcgisonline.com/arcgis\",\n * token: \"SOSlV3v..\",\n * tokenExpires: new Date(1545415669763)\n * }\n * ```\n */\n server?: string;\n}\n\n/**\n * ```js\n * import { UserSession } from '@esri/arcgis-rest-auth';\n * UserSession.beginOAuth2({\n * // register an app of your own to create a unique clientId\n * clientId: \"abc123\",\n * redirectUri: 'https://yourapp.com/authenticate.html'\n * })\n * .then(session)\n * // or\n * new UserSession({\n * username: \"jsmith\",\n * password: \"123456\"\n * })\n * // or\n * UserSession.deserialize(cache)\n * ```\n * Used to authenticate both ArcGIS Online and ArcGIS Enterprise users. `UserSession` includes helper methods for [OAuth 2.0](/arcgis-rest-js/guides/browser-authentication/) in both browser and server applications.\n */\nexport class UserSession implements IAuthenticationManager {\n /**\n * The current ArcGIS Online or ArcGIS Enterprise `token`.\n */\n get token() {\n return this._token;\n }\n\n /**\n * The expiration time of the current `token`.\n */\n get tokenExpires() {\n return this._tokenExpires;\n }\n\n /**\n * The current token to ArcGIS Online or ArcGIS Enterprise.\n */\n get refreshToken() {\n return this._refreshToken;\n }\n\n /**\n * The expiration time of the current `refreshToken`.\n */\n get refreshTokenExpires() {\n return this._refreshTokenExpires;\n }\n\n /**\n * Deprecated, use `federatedServers` instead.\n *\n * @deprecated\n */\n get trustedServers() {\n console.log(\"DEPRECATED: use federatedServers instead\");\n return this.federatedServers;\n }\n\n /**\n * Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is `true` the\n * authentication window will open in a new tab/window and the function will return\n * Promise&lt;UserSession&gt;. Otherwise, the user will be redirected to the\n * authorization page in their current tab/window and the function will return `undefined`.\n *\n * @browserOnly\n */\n /* istanbul ignore next */\n public static beginOAuth2(\n options: IOAuth2Options,\n win: any = window\n ): Promise<UserSession> | undefined {\n if (options.duration) {\n console.log(\n \"DEPRECATED: 'duration' is deprecated - use 'expiration' instead\"\n );\n }\n\n const {\n portal,\n provider,\n clientId,\n expiration,\n redirectUri,\n popup,\n popupWindowFeatures,\n state,\n locale,\n params,\n }: IOAuth2Options = {\n ...{\n portal: \"https://www.arcgis.com/sharing/rest\",\n provider: \"arcgis\",\n expiration: 20160,\n popup: true,\n popupWindowFeatures:\n \"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes\",\n state: options.clientId,\n locale: \"\",\n },\n ...options,\n };\n let url: string;\n if (provider === \"arcgis\") {\n url = `${portal}/oauth2/authorize?client_id=${clientId}&response_type=token&expiration=${\n options.duration || expiration\n }&redirect_uri=${encodeURIComponent(\n redirectUri\n )}&state=${state}&locale=${locale}`;\n } else {\n url = `${portal}/oauth2/social/authorize?client_id=${clientId}&socialLoginProviderName=${provider}&autoAccountCreateForSocial=true&response_type=token&expiration=${\n options.duration || expiration\n }&redirect_uri=${encodeURIComponent(\n redirectUri\n )}&state=${state}&locale=${locale}`;\n }\n\n // append additional params\n if (params) {\n url = `${url}&${encodeQueryString(params)}`;\n }\n\n if (!popup) {\n win.location.href = url;\n return undefined;\n }\n\n const session = defer<UserSession>();\n\n win[`__ESRI_REST_AUTH_HANDLER_${clientId}`] = function (\n errorString: any,\n oauthInfoString: string\n ) {\n if (errorString) {\n const error = JSON.parse(errorString);\n session.reject(new ArcGISAuthError(error.errorMessage, error.error));\n return;\n }\n\n if (oauthInfoString) {\n const oauthInfo = JSON.parse(oauthInfoString);\n session.resolve(\n new UserSession({\n clientId,\n portal,\n ssl: oauthInfo.ssl,\n token: oauthInfo.token,\n tokenExpires: new Date(oauthInfo.expires),\n username: oauthInfo.username,\n })\n );\n }\n };\n\n win.open(url, \"oauth-window\", popupWindowFeatures);\n\n return session.promise;\n }\n\n /**\n * Completes a browser-based OAuth 2.0 sign in. If `options.popup` is `true` the user\n * will be returned to the previous window. Otherwise a new `UserSession`\n * will be returned. You must pass the same values for `options.popup` and\n * `options.portal` as you used in `beginOAuth2()`.\n *\n * @browserOnly\n */\n /* istanbul ignore next */\n public static completeOAuth2(options: IOAuth2Options, win: any = window) {\n const { portal, clientId, popup }: IOAuth2Options = {\n ...{ portal: \"https://www.arcgis.com/sharing/rest\", popup: true },\n ...options,\n };\n\n function completeSignIn(error: any, oauthInfo?: IFetchTokenResponse) {\n try {\n let handlerFn;\n const handlerFnName = `__ESRI_REST_AUTH_HANDLER_${clientId}`;\n\n if (popup) {\n // Guard b/c IE does not support window.opener\n if (win.opener) {\n if (win.opener.parent && win.opener.parent[handlerFnName]) {\n handlerFn = win.opener.parent[handlerFnName];\n } else if (win.opener && win.opener[handlerFnName]) {\n // support pop-out oauth from within an iframe\n handlerFn = win.opener[handlerFnName];\n }\n } else {\n // IE\n if (win !== win.parent && win.parent && win.parent[handlerFnName]) {\n handlerFn = win.parent[handlerFnName];\n }\n }\n // if we have a handler fn, call it and close the window\n if (handlerFn) {\n handlerFn(\n error ? JSON.stringify(error) : undefined,\n JSON.stringify(oauthInfo)\n );\n win.close();\n return undefined;\n }\n }\n } catch (e) {\n throw new ArcGISAuthError(\n `Unable to complete authentication. It's possible you specified popup based oAuth2 but no handler from \"beginOAuth2()\" present. This generally happens because the \"popup\" option differs between \"beginOAuth2()\" and \"completeOAuth2()\".`\n );\n }\n\n if (error) {\n throw new ArcGISAuthError(error.errorMessage, error.error);\n }\n\n return new UserSession({\n clientId,\n portal,\n ssl: oauthInfo.ssl,\n token: oauthInfo.token,\n tokenExpires: oauthInfo.expires,\n username: oauthInfo.username,\n });\n }\n\n const params = decodeQueryString(win.location.hash);\n\n if (!params.access_token) {\n let error;\n let errorMessage = \"Unknown error\";\n\n if (params.error) {\n error = params.error;\n errorMessage = params.error_description;\n }\n\n return completeSignIn({ error, errorMessage });\n }\n\n const token = params.access_token;\n const expires = new Date(\n Date.now() + parseInt(params.expires_in, 10) * 1000 - 60 * 1000\n );\n const username = params.username;\n const ssl = params.ssl === \"true\";\n\n return completeSignIn(undefined, {\n token,\n expires,\n ssl,\n username,\n });\n }\n\n /**\n * Request session information from the parent application\n *\n * When an application is embedded into another application via an IFrame, the embedded app can\n * use `window.postMessage` to request credentials from the host application. This function wraps\n * that behavior.\n *\n * The ArcGIS API for Javascript has this built into the Identity Manager as of the 4.19 release.\n *\n * Note: The parent application will not respond if the embedded app's origin is not:\n * - the same origin as the parent or *.arcgis.com (JSAPI)\n * - in the list of valid child origins (REST-JS)\n *\n *\n * @param parentOrigin origin of the parent frame. Passed into the embedded application as `parentOrigin` query param\n * @browserOnly\n */\n public static fromParent(parentOrigin: string, win?: any): Promise<any> {\n /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */\n if (!win && window) {\n win = window;\n }\n // Declare handler outside of promise scope so we can detach it\n let handler: (event: any) => void;\n // return a promise that will resolve when the handler receives\n // session information from the correct origin\n return new Promise((resolve, reject) => {\n // create an event handler that just wraps the parentMessageHandler\n handler = (event: any) => {\n // ensure we only listen to events from the parent\n if (event.source === win.parent && event.data) {\n try {\n return resolve(UserSession.parentMessageHandler(event));\n } catch (err) {\n return reject(err);\n }\n }\n };\n // add listener\n win.addEventListener(\"message\", handler, false);\n win.parent.postMessage(\n { type: \"arcgis:auth:requestCredential\" },\n parentOrigin\n );\n }).then((session) => {\n win.removeEventListener(\"message\", handler, false);\n return session;\n });\n }\n\n /**\n * Begins a new server-based OAuth 2.0 sign in. This will redirect the user to\n * the ArcGIS Online or ArcGIS Enterprise authorization page.\n *\n * @nodeOnly\n */\n public static authorize(\n options: IOAuth2Options,\n response: http.ServerResponse\n ) {\n if (options.duration) {\n console.log(\n \"DEPRECATED: 'duration' is deprecated - use 'expiration' instead\"\n );\n }\n const { portal, clientId, expiration, redirectUri }: IOAuth2Options = {\n ...{ portal: \"https://arcgis.com/sharing/rest\", expiration: 20160 },\n ...options,\n };\n\n response.writeHead(301, {\n Location: `${portal}/oauth2/authorize?client_id=${clientId}&expiration=${\n options.duration || expiration\n }&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}`,\n });\n\n response.end();\n }\n\n /**\n * Completes the server-based OAuth 2.0 sign in process by exchanging the `authorizationCode`\n * for a `access_token`.\n *\n * @nodeOnly\n */\n public static exchangeAuthorizationCode(\n options: IOAuth2Options,\n authorizationCode: string\n ): Promise<UserSession> {\n const { portal, clientId, redirectUri, refreshTokenTTL }: IOAuth2Options = {\n ...{\n portal: \"https://www.arcgis.com/sharing/rest\",\n refreshTokenTTL: 20160,\n },\n ...options,\n };\n\n return fetchToken(`${portal}/oauth2/token`, {\n params: {\n grant_type: \"authorization_code\",\n client_id: clientId,\n redirect_uri: redirectUri,\n code: authorizationCode,\n },\n }).then((response) => {\n return new UserSession({\n clientId,\n portal,\n ssl: response.ssl,\n redirectUri,\n refreshToken: response.refreshToken,\n refreshTokenTTL,\n refreshTokenExpires: new Date(\n Date.now() + (refreshTokenTTL - 1) * 60 * 1000\n ),\n token: response.token,\n tokenExpires: response.expires,\n username: response.username,\n });\n });\n }\n\n public static deserialize(str: string) {\n const options = JSON.parse(str);\n return new UserSession({\n clientId: options.clientId,\n refreshToken: options.refreshToken,\n refreshTokenExpires: new Date(options.refreshTokenExpires),\n username: options.username,\n password: options.password,\n token: options.token,\n tokenExpires: new Date(options.tokenExpires),\n portal: options.portal,\n ssl: options.ssl,\n tokenDuration: options.tokenDuration,\n redirectUri: options.redirectUri,\n refreshTokenTTL: options.refreshTokenTTL,\n });\n }\n\n /**\n * Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).\n *\n * ```js\n * UserSession.fromCredential({\n * userId: \"jsmith\",\n * token: \"secret\"\n * });\n * ```\n *\n * @returns UserSession\n */\n public static fromCredential(credential: ICredential) {\n // At ArcGIS Online 9.1, credentials no longer include the ssl and expires properties\n // Here, we provide default values for them to cover this condition\n const ssl = typeof credential.ssl !== \"undefined\" ? credential.ssl : true;\n const expires = credential.expires || Date.now() + 7200000; /* 2 hours */\n\n return new UserSession({\n portal: credential.server.includes(\"sharing/rest\")\n ? credential.server\n : credential.server + `/sharing/rest`,\n ssl,\n token: credential.token,\n username: credential.userId,\n tokenExpires: new Date(expires),\n });\n }\n\n /**\n * Handle the response from the parent\n * @param event DOM Event\n */\n private static parentMessageHandler(event: any): UserSession {\n if (event.data.type === \"arcgis:auth:credential\") {\n return UserSession.fromCredential(event.data.credential);\n }\n if (event.data.type === \"arcgis:auth:error\") {\n const err = new Error(event.data.error.message);\n err.name = event.data.error.name;\n throw err;\n } else {\n throw new Error(\"Unknown message type.\");\n }\n }\n\n /**\n * Client ID being used for authentication if provided in the `constructor`.\n */\n public readonly clientId: string;\n\n /**\n * The currently authenticated user if provided in the `constructor`.\n */\n public readonly username: string;\n\n /**\n * The currently authenticated user's password if provided in the `constructor`.\n */\n public readonly password: string;\n\n /**\n * The current portal the user is authenticated with.\n */\n public readonly portal: string;\n\n /**\n * This value is set to true automatically if the ArcGIS Organization requires that requests be made over https.\n */\n public readonly ssl: boolean;\n\n /**\n * The authentication provider to use.\n */\n public readonly provider: AuthenticationProvider;\n\n /**\n * Determines how long new tokens requested are valid.\n */\n public readonly tokenDuration: number;\n\n /**\n * A valid redirect URI for this application if provided in the `constructor`.\n */\n public readonly redirectUri: string;\n\n /**\n * Duration of new OAuth 2.0 refresh token validity (in minutes).\n */\n public readonly refreshTokenTTL: number;\n\n /**\n * An unfederated ArcGIS Server instance known to recognize credentials supplied manually.\n * ```js\n * {\n * server: \"https://sampleserver6.arcgisonline.com/arcgis\",\n * token: \"SOSlV3v..\",\n * tokenExpires: new Date(1545415669763)\n * }\n * ```\n */\n public readonly server: string;\n\n /**\n * Hydrated by a call to [getUser()](#getUser-summary).\n */\n private _user: IUser;\n\n /**\n * Hydrated by a call to [getPortal()](#getPortal-summary).\n */\n private _portalInfo: any;\n\n private _token: string;\n private _tokenExpires: Date;\n private _refreshToken: string;\n private _refreshTokenExpires: Date;\n private _pendingUserRequest: Promise<IUser>;\n private _pendingPortalRequest: Promise<any>;\n\n /**\n * Internal object to keep track of pending token requests. Used to prevent\n * duplicate token requests.\n */\n private _pendingTokenRequests: {\n [key: string]: Promise<string>;\n };\n\n /**\n * Internal list of tokens to 3rd party servers (federated servers) that have\n * been created via `generateToken`. The object key is the root URL of the server.\n */\n private federatedServers: {\n [key: string]: {\n token: string;\n expires: Date;\n };\n };\n\n /**\n * Internal list of 3rd party domains that should receive all cookies (credentials: \"include\").\n * Used to for PKI and IWA workflows in high security environments.\n */\n private trustedDomains: string[];\n\n private _hostHandler: any;\n\n constructor(options: IUserSessionOptions) {\n this.clientId = options.clientId;\n this._refreshToken = options.refreshToken;\n this._refreshTokenExpires = options.refreshTokenExpires;\n this.username = options.username;\n this.password = options.password;\n this._token = options.token;\n this._tokenExpires = options.tokenExpires;\n this.portal = options.portal\n ? cleanUrl(options.portal)\n : \"https://www.arcgis.com/sharing/rest\";\n this.ssl = options.ssl;\n this.provider = options.provider || \"arcgis\";\n this.tokenDuration = options.tokenDuration || 20160;\n this.redirectUri = options.redirectUri;\n this.refreshTokenTTL = options.refreshTokenTTL || 20160;\n this.server = options.server;\n\n this.federatedServers = {};\n this.trustedDomains = [];\n\n // if a non-federated server was passed explicitly, it should be trusted.\n if (options.server) {\n // if the url includes more than '/arcgis/', trim the rest\n const root = this.getServerRootUrl(options.server);\n\n this.federatedServers[root] = {\n token: options.token,\n expires: options.tokenExpires,\n };\n }\n this._pendingTokenRequests = {};\n }\n\n /**\n * Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).\n *\n * ```js\n * esriId.registerToken(session.toCredential());\n * ```\n *\n * @returns ICredential\n */\n public toCredential(): ICredential {\n return {\n expires: this.tokenExpires.getTime(),\n server: this.portal,\n ssl: this.ssl,\n token: this.token,\n userId: this.username,\n };\n }\n\n /**\n * Returns information about the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic.\n *\n * ```js\n * session.getUser()\n * .then(response => {\n * console.log(response.role); // \"org_admin\"\n * })\n * ```\n *\n * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.\n * @returns A Promise that will resolve with the data from the response.\n */\n public getUser(requestOptions?: IRequestOptions): Promise<IUser> {\n if (this._pendingUserRequest) {\n return this._pendingUserRequest;\n } else if (this._user) {\n return Promise.resolve(this._user);\n } else {\n const url = `${this.portal}/community/self`;\n\n const options = {\n httpMethod: \"GET\",\n authentication: this,\n ...requestOptions,\n rawResponse: false,\n } as IRequestOptions;\n\n this._pendingUserRequest = request(url, options).then((response) => {\n this._user = response;\n this._pendingUserRequest = null;\n return response;\n });\n\n return this._pendingUserRequest;\n }\n }\n\n /**\n * Returns information about the currently logged in user's [portal](https://developers.arcgis.com/rest/users-groups-and-items/portal-self.htm). Subsequent calls will *not* result in additional web traffic.\n *\n * ```js\n * session.getPortal()\n * .then(response => {\n * console.log(portal.name); // \"City of ...\"\n * })\n * ```\n *\n * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.\n * @returns A Promise that will resolve with the data from the response.\n */\n public getPortal(requestOptions?: IRequestOptions): Promise<any> {\n if (this._pendingPortalRequest) {\n return this._pendingPortalRequest;\n } else if (this._portalInfo) {\n return Promise.resolve(this._portalInfo);\n } else {\n const url = `${this.portal}/portals/self`;\n\n const options = {\n httpMethod: \"GET\",\n authentication: this,\n ...requestOptions,\n rawResponse: false,\n } as IRequestOptions;\n\n this._pendingPortalRequest = request(url, options).then((response) => {\n this._portalInfo = response;\n this._pendingPortalRequest = null;\n return response;\n });\n\n return this._pendingPortalRequest;\n }\n }\n\n /**\n * Returns the username for the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic. This is also used internally when a username is required for some requests but is not present in the options.\n *\n * * ```js\n * session.getUsername()\n * .then(response => {\n * console.log(response); // \"casey_jones\"\n * })\n * ```\n */\n public getUsername() {\n if (this.username) {\n return Promise.resolve(this.username);\n } else if (this._user) {\n return Promise.resolve(this._user.username);\n } else {\n return this.getUser().then((user) => {\n return user.username;\n });\n }\n }\n\n /**\n * Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and\n * the request is to an ArcGIS Online domain `token` will be used. If the request\n * is to the current `portal` the current `token` will also be used. However if\n * the request is to an unknown server we will validate the server with a request\n * to our current `portal`.\n */\n public getToken(url: string, requestOptions?: ITokenRequestOptions) {\n if (canUseOnlineToken(this.portal, url)) {\n return this.getFreshToken(requestOptions);\n } else if (new RegExp(this.portal, \"i\").test(url)) {\n return this.getFreshToken(requestOptions);\n } else {\n return this.getTokenForServer(url, requestOptions);\n }\n }\n\n /**\n * Get application access information for the current user\n * see `validateAppAccess` function for details\n *\n * @param clientId application client id\n */\n public validateAppAccess(clientId: string): Promise<IAppAccess> {\n return this.getToken(this.portal).then((token) => {\n return validateAppAccess(token, clientId);\n });\n }\n\n public toJSON(): IUserSessionOptions {\n return {\n clientId: this.clientId,\n refreshToken: this.refreshToken,\n refreshTokenExpires: this.refreshTokenExpires,\n username: this.username,\n password: this.password,\n token: this.token,\n tokenExpires: this.tokenExpires,\n portal: this.portal,\n ssl: this.ssl,\n tokenDuration: this.tokenDuration,\n redirectUri: this.redirectUri,\n refreshTokenTTL: this.refreshTokenTTL,\n };\n }\n\n public serialize() {\n return JSON.stringify(this);\n }\n /**\n * For a \"Host\" app that embeds other platform apps via iframes, after authenticating the user\n * and creating a UserSession, the app can then enable \"post message\" style authentication by calling\n * this method.\n *\n * Internally this adds an event listener on window for the `message` event\n *\n * @param validChildOrigins Array of origins that are allowed to request authentication from the host app\n */\n public enablePostMessageAuth(validChildOrigins: string[], win?: any): any {\n /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */\n if (!win && window) {\n win = window;\n }\n this._hostHandler = this.createPostMessageHandler(validChildOrigins);\n win.addEventListener(\"message\", this._hostHandler, false);\n }\n\n /**\n * For a \"Host\" app that has embedded other platform apps via iframes, when the host needs\n * to transition routes, it should call `UserSession.disablePostMessageAuth()` to remove\n * the event listener and prevent memory leaks\n */\n public disablePostMessageAuth(win?: any) {\n /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */\n if (!win && window) {\n win = window;\n }\n win.removeEventListener(\"message\", this._hostHandler, false);\n }\n\n /**\n * Manually refreshes the current `token` and `tokenExpires`.\n */\n public refreshSession(\n requestOptions?: ITokenRequestOptions\n ): Promise<UserSession> {\n // make sure subsequent calls to getUser() don't returned cached metadata\n this._user = null;\n\n if (this.username && this.password) {\n return this.refreshWithUsernameAndPassword(requestOptions);\n }\n\n if (this.clientId && this.refreshToken) {\n return this.refreshWithRefreshToken();\n }\n\n return Promise.reject(new ArcGISAuthError(\"Unable to refresh token.\"));\n }\n\n /**\n * Determines the root of the ArcGIS Server or Portal for a given URL.\n *\n * @param url the URl to determine the root url for.\n */\n public getServerRootUrl(url: string) {\n const [root] = cleanUrl(url).split(\n /\\/rest(\\/admin)?\\/services(?:\\/|#|\\?|$)/\n );\n const [match, protocol, domainAndPath] = root.match(/(https?:\\/\\/)(.+)/);\n const [domain, ...path] = domainAndPath.split(\"/\");\n\n // only the domain is lowercased because in some cases an org id might be\n // in the path which cannot be lowercased.\n return `${protocol}${domain.toLowerCase()}/${path.join(\"/\")}`;\n }\n\n /**\n * Returns the proper [`credentials`] option for `fetch` for a given domain.\n * See [trusted server](https://enterprise.arcgis.com/en/portal/latest/administer/windows/configure-security.htm#ESRI_SECTION1_70CC159B3540440AB325BE5D89DBE94A).\n * Used internally by underlying request methods to add support for specific security considerations.\n *\n * @param url The url of the request\n * @returns \"include\" or \"same-origin\"\n */\n public getDomainCredentials(url: string): RequestCredentials {\n // if the url is in the noCorsDomains, we want to include credentials\n const shouldInclude = isNoCorsDomain(url);\n if (shouldInclude) {\n return \"include\";\n }\n\n if (!this.trustedDomains || !this.trustedDomains.length) {\n return \"same-origin\";\n }\n\n return this.trustedDomains.some((domainWithProtocol) => {\n return url.startsWith(domainWithProtocol);\n })\n ? \"include\"\n : \"same-origin\";\n }\n\n /**\n * Return a function that closes over the validOrigins array and\n * can be used as an event handler for the `message` event\n *\n * @param validOrigins Array of valid origins\n */\n private createPostMessageHandler(\n validOrigins: string[]\n ): (event: any) => void {\n // return a function that closes over the validOrigins and\n // has access to the credential\n return (event: any) => {\n // Verify that the origin is valid\n // Note: do not use regex's here. validOrigins is an array so we're checking that the event's origin\n // is in the array via exact match. More info about avoiding postMessage xss issues here\n // https://jlajara.gitlab.io/web/2020/07/17/Dom_XSS_PostMessage_2.html#tipsbypasses-in-postmessage-vulnerabilities\n const isValidOrigin = validOrigins.indexOf(event.origin) > -1;\n // JSAPI handles this slightly differently - instead of checking a list, it will respond if\n // event.origin === window.location.origin || event.origin.endsWith('.arcgis.com')\n // For Hub, and to enable cross domain debugging with port's in urls, we are opting to\n // use a list of valid origins\n\n // Ensure the message type is something we want to handle\n const isValidType = event.data.type === \"arcgis:auth:requestCredential\";\n\n const isTokenValid = this.tokenExpires.getTime() > Date.now();\n\n if (isValidOrigin && isValidType) {\n let msg = {};\n if (isTokenValid) {\n const credential = this.toCredential();\n // arcgis:auth:error with {name: \"\", message: \"\"}\n // the following line allows us to conform to our spec without changing other depended-on functionality\n // https://github.com/Esri/arcgis-rest-js/blob/master/packages/arcgis-rest-auth/post-message-auth-spec.md#arcgisauthcredential\n credential.server = credential.server.replace(\"/sharing/rest\", \"\");\n msg = { type: \"arcgis:auth:credential\", credential };\n } else {\n // Return an error\n msg = {\n type: \"arcgis:auth:error\",\n error: {\n name: \"tokenExpiredError\",\n message:\n \"Session token was expired, and not returned to the child application\",\n },\n };\n }\n event.source.postMessage(msg, event.origin);\n }\n };\n }\n\n /**\n * Validates that a given URL is properly federated with our current `portal`.\n * Attempts to use the internal `federatedServers` cache first.\n */\n private getTokenForServer(\n url: string,\n requestOptions?: ITokenRequestOptions\n ) {\n // requests to /rest/services/ and /rest/admin/services/ are both valid\n // Federated servers may have inconsistent casing, so lowerCase it\n const root = this.getServerRootUrl(url);\n const existingToken = this.federatedServers[root];\n\n if (\n existingToken &&\n existingToken.expires &&\n existingToken.expires.getTime() > Date.now()\n ) {\n return Promise.resolve(existingToken.token);\n }\n\n if (this._pendingTokenRequests[root]) {\n return this._pendingTokenRequests[root];\n }\n\n this._pendingTokenRequests[root] = this.fetchAuthorizedDomains().then(\n () => {\n return request(`${root}/rest/info`, {\n credentials: this.getDomainCredentials(url),\n })\n .then((response) => {\n if (response.owningSystemUrl) {\n /**\n * if this server is not owned by this portal\n * bail out with an error since we know we wont\n * be able to generate a token\n */\n if (!isFederated(response.owningSystemUrl, this.portal)) {\n throw new ArcGISAuthError(\n `${url} is not federated with ${this.portal}.`,\n \"NOT_FEDERATED\"\n );\n } else {\n /**\n * if the server is federated, use the relevant token endpoint.\n */\n return request(\n `${response.owningSystemUrl}/sharing/rest/info`,\n requestOptions\n );\n }\n } else if (\n response.authInfo &&\n this.federatedServers[root] !== undefined\n ) {\n /**\n * if its a stand-alone instance of ArcGIS Server that doesn't advertise\n * federation, but the root server url is recognized, use its built in token endpoint.\n */\n return Promise.resolve({\n authInfo: response.authInfo,\n });\n } else {\n throw new ArcGISAuthError(\n `${url} is not federated with any portal and is not explicitly trusted.`,\n \"NOT_FEDERATED\"\n );\n }\n })\n .then((response: any) => {\n return response.authInfo.tokenServicesUrl;\n })\n .then((tokenServicesUrl: string) => {\n // an expired token cant be used to generate a new token\n if (this.token && this.tokenExpires.getTime() > Date.now()) {\n return generateToken(tokenServicesUrl, {\n params: {\n token: this.token,\n serverUrl: url,\n expiration: this.tokenDuration,\n client: \"referer\",\n },\n });\n // generate an entirely fresh token if necessary\n } else {\n return generateToken(tokenServicesUrl, {\n params: {\n username: this.username,\n password: this.password,\n expiration: this.tokenDuration,\n client: \"referer\",\n },\n }).then((response: any) => {\n this._token = response.token;\n this._tokenExpires = new Date(response.expires);\n return response;\n });\n }\n })\n .then((response) => {\n this.federatedServers[root] = {\n expires: new Date(response.expires),\n token: response.token,\n };\n delete this._pendingTokenRequests[root];\n return response.token;\n });\n }\n );\n\n return this._pendingTokenRequests[root];\n }\n\n /**\n * Returns an unexpired token for the current `portal`.\n */\n private getFreshToken(requestOptions?: ITokenRequestOptions) {\n if (this.token && !this.tokenExpires) {\n return Promise.resolve(this.token);\n }\n\n if (\n this.token &&\n this.tokenExpires &&\n this.tokenExpires.getTime() > Date.now()\n ) {\n return Promise.resolve(this.token);\n }\n\n if (!this._pendingTokenRequests[this.portal]) {\n this._pendingTokenRequests[this.portal] = this.refreshSession(\n requestOptions\n ).then((session) => {\n this._pendingTokenRequests[this.portal] = null;\n return session.token;\n });\n }\n\n return this._pendingTokenRequests[this.portal];\n }\n\n /**\n * Refreshes the current `token` and `tokenExpires` with `username` and\n * `password`.\n */\n private refreshWithUsernameAndPassword(\n requestOptions?: ITokenRequestOptions\n ) {\n const options = {\n params: {\n username: this.username,\n password: this.password,\n expiration: this.tokenDuration,\n },\n ...requestOptions,\n };\n return generateToken(`${this.portal}/generateToken`, options).then(\n (response: any) => {\n this._token = response.token;\n this._tokenExpires = new Date(response.expires);\n return this;\n }\n );\n }\n\n /**\n * Refreshes the current `token` and `tokenExpires` with `refreshToken`.\n */\n private refreshWithRefreshToken(requestOptions?: ITokenRequestOptions) {\n if (\n this.refreshToken &&\n this.refreshTokenExpires &&\n this.refreshTokenExpires.getTime() < Date.now()\n ) {\n return this.refreshRefreshToken(requestOptions);\n }\n\n const options: ITokenRequestOptions = {\n params: {\n client_id: this.clientId,\n refresh_token: this.refreshToken,\n grant_type: \"refresh_token\",\n },\n ...requestOptions,\n };\n return fetchToken(`${this.portal}/oauth2/token`, options).then(\n (response) => {\n this._token = response.token;\n this._tokenExpires = response.expires;\n return this;\n }\n );\n }\n\n /**\n * Exchanges an unexpired `refreshToken` for a new one, also updates `token` and\n * `tokenExpires`.\n */\n private refreshRefreshToken(requestOptions?: ITokenRequestOptions) {\n const options: ITokenRequestOptions = {\n params: {\n client_id: this.clientId,\n refresh_token: this.refreshToken,\n redirect_uri: this.redirectUri,\n grant_type: \"exchange_refresh_token\",\n },\n ...requestOptions,\n };\n\n return fetchToken(`${this.portal}/oauth2/token`, options).then(\n (response) => {\n this._token = response.token;\n this._tokenExpires = response.expires;\n this._refreshToken = response.refreshToken;\n this._refreshTokenExpires = new Date(\n Date.now() + (this.refreshTokenTTL - 1) * 60 * 1000\n );\n return this;\n }\n );\n }\n\n /**\n * ensures that the authorizedCrossOriginDomains are obtained from the portal and cached\n * so we can check them later.\n *\n * @returns this\n */\n private fetchAuthorizedDomains() {\n // if this token is for a specific server or we don't have a portal\n // don't get the portal info because we cant get the authorizedCrossOriginDomains\n if (this.server || !this.portal) {\n return Promise.resolve(this);\n }\n\n return this.getPortal().then((portalInfo) => {\n /**\n * Specific domains can be configured as secure.esri.com or https://secure.esri.com this\n * normalizes to https://secure.esri.com so we can use startsWith later.\n */\n if (\n portalInfo.authorizedCrossOriginDomains &&\n portalInfo.authorizedCrossOriginDomains.length\n ) {\n this.trustedDomains = portalInfo.authorizedCrossOriginDomains\n .filter((d: string) => !d.startsWith(\"http://\"))\n .map((d: string) => {\n if (d.startsWith(\"https://\")) {\n return d;\n } else {\n return `https://${d}`;\n }\n });\n }\n return this;\n });\n }\n}\n","/* Copyright (c) 2018-2020 Environmental Systems Research Institute, Inc.\n * Apache-2.0 */\n\nimport { IRequestOptions, request } from \"@esri/arcgis-rest-request\";\n\n/**\n * Request app-specific token, passing in the token for the current app.\n *\n * This call returns a token after performing the same checks made by validateAppAccess.\n * It returns an app-specific token of the signed-in user only if the user has access\n * to the app and the encrypted platform cookie is valid.\n *\n * A scenario where an app would use this is if it is iframed into another platform app\n * and receives credentials via postMessage. Those credentials contain a token that is\n * specific to the host app, so the embedded app would use `exchangeToken` to get one\n * that is specific to itself.\n *\n * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within\n * an ArcGIS Enterprise installation. Custom applications can not use this.\n *\n * @param token\n * @param clientId application\n * @param portal\n */\nexport function exchangeToken(\n token: string,\n clientId: string,\n portal = \"https://www.arcgis.com/sharing/rest\"\n): Promise<string> {\n const url = `${portal}/oauth2/exchangeToken`;\n const ro = {\n method: \"POST\",\n params: {\n f: \"json\",\n client_id: clientId,\n token,\n },\n } as IRequestOptions;\n // make the request and return the token\n return request(url, ro).then((response) => response.token);\n}\n\n/**\n * @internal\n * Response from the `platformSelf(...)` function.\n */\nexport interface IPlatformSelfResponse {\n /**\n * Username of the user the encrypted cookie was issued for\n */\n username: string;\n /**\n * Token the consuming application can use, It is tied to the\n * clientId used in the `platformSelf` call\n */\n token: string;\n /**\n * Token expiration, in seconds-from-now\n */\n expires_in: number;\n}\n\n/**\n * @internal\n * Request a token for a specific application using the esri_aopc encrypted cookie\n *\n * When a client app boots up, it will know its clientId and the redirectUri for use\n * in the normal /oauth/authorize pop-out oAuth flow.\n *\n * If the app sees an `esri_aopc` cookie (only set if the app is hosted on *.arcgis.com),\n * it can call the /oauth2/platformSelf end-point passing in the clientId and redirectUri\n * in headers, and it will receive back an app-specific token, assuming the user has\n * access to the app.\n *\n * Since there are scenarios where an app can boot using credentials/token from localstorage\n * but those credentials are not for the same user as the esri_aopc cookie, it is recommended that\n * an app check the returned username against any existing identity they may have loaded.\n *\n * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within\n * an ArcGIS Enterprise installation. Custom applications can not use this.\n *\n * ```js\n * // convert the encrypted platform cookie into a UserSession\n * import { platformSelf, UserSession } from '@esri/arcgis-rest-auth';\n *\n * const portal = 'https://www.arcgis.com/sharing/rest';\n * const clientId = 'YOURAPPCLIENTID';\n *\n * // exchange esri_aopc cookie\n * return platformSelf(clientId, 'https://your-app-redirect-uri', portal)\n * .then((response) => {\n * const currentTimestamp = new Date().getTime();\n * const tokenExpiresTimestamp = currentTimestamp + (response.expires_in * 1000);\n * // Construct the session and return it\n * return new UserSession({\n * portal,\n * clientId,\n * username: response.username,\n * token: response.token,\n * tokenExpires: new Date(tokenExpiresTimestamp),\n * ssl: true\n * });\n * })\n *\n * ```\n *\n *\n * @param clientId\n * @param redirectUri\n * @param portal\n */\nexport function platformSelf(\n clientId: string,\n redirectUri: string,\n portal = \"https://www.arcgis.com/sharing/rest\"\n): Promise<IPlatformSelfResponse> {\n // TEMPORARY: the f=json should not be needed, but currently is\n const url = `${portal}/oauth2/platformSelf?f=json`;\n const ro = {\n method: \"POST\",\n headers: {\n \"X-Esri-Auth-Client-Id\": clientId,\n \"X-Esri-Auth-Redirect-Uri\": redirectUri,\n },\n // Note: request has logic to include the cookie\n // for platformSelf calls w/ the X-Esri-Auth-Client-Id header\n params: {\n f: \"json\",\n },\n } as IRequestOptions;\n // make the request and return the token\n return request(url, ro);\n}\n"],"names":["fetchToken","url","requestOptions","options","rawResponse","request","then","response","r","token","access_token","username","expires","Date","now","expires_in","ssl","refresh_token","refreshToken","ApplicationSession","this","getTime","Promise","resolve","_pendingTokenRequest","params","client_id","clientId","client_secret","clientSecret","grant_type","expiration","duration","portal","_this","ApiKey","key","generateToken","window","location","host","referer","NODEJS_DEFAULT_REFERER_HEADER","arcgisOnlineUrlRegex","isOnline","test","getOnlineEnvironment","subdomain","match","split","pop","includes","isFederated","owningSystemUrl","portalUrl","normalizedPortalUrl","cleanUrl","normalizeOnlinePortalUrl","replace","normalizedOwningSystemUrl","RegExp","validateAppAccess","ro","method","f","Object","UserSession","_token","_tokenExpires","_refreshToken","_refreshTokenExpires","console","log","federatedServers","win","_a","provider","popup","popupWindowFeatures","state","locale","redirectUri","encodeURIComponent","encodeQueryString","deferred","session","promise","reject","errorString","oauthInfoString","error","JSON","parse","ArcGISAuthError","errorMessage","oauthInfo","tokenExpires","open","href","completeSignIn","handlerFn","handlerFnName","opener","parent","stringify","undefined","close","e","decodeQueryString","hash","error_description","parseInt","parentOrigin","handler","event","source","data","parentMessageHandler","err","addEventListener","postMessage","type","removeEventListener","writeHead","Location","end","authorizationCode","refreshTokenTTL","redirect_uri","code","refreshTokenExpires","str","password","tokenDuration","credential","server","userId","fromCredential","Error","message","name","_pendingUserRequest","_user","__assign","httpMethod","authentication","_pendingPortalRequest","_portalInfo","getUser","user","requestUrl","portalIsOnline","requestIsOnline","portalEnv","requestEnv","getFreshToken","getTokenForServer","getToken","validChildOrigins","_hostHandler","createPostMessageHandler","refreshWithUsernameAndPassword","refreshWithRefreshToken","protocol","_b","domain","path","toLowerCase","join","isNoCorsDomain","trustedDomains","length","some","domainWithProtocol","startsWith","validOrigins","isValidOrigin","indexOf","origin","isValidType","isTokenValid","msg","toCredential","root","getServerRootUrl","existingToken","_pendingTokenRequests","fetchAuthorizedDomains","credentials","getDomainCredentials","authInfo","tokenServicesUrl","serverUrl","client","refreshSession","refreshRefreshToken","getPortal","portalInfo","authorizedCrossOriginDomains","filter","d","map","headers","X-Esri-Auth-Client-Id","X-Esri-Auth-Redirect-Uri"],"mappings":";;;;;2iBAyBgBA,EACdC,EACAC,GAMA,OAFAC,EAAQC,aAAc,EAEfC,UAAQJ,EAAKE,GAASG,KAAK,SAACC,GACjC,IAAMC,EAAyB,CAC7BC,MAAOF,EAASG,aAChBC,SAAUJ,EAASI,SACnBC,QAAS,IAAIC,KAEXA,KAAKC,OAA+B,IAAtBP,EAASQ,WAAoB,MAE7CC,KAAsB,IAAjBT,EAASS,KAMhB,OAJIT,EAASU,gBACXT,EAAEU,aAAeX,EAASU,eAGrBT,WCkCFW,qBAAP,SACElB,EACAC,GAEA,OAAIkB,KAAKX,OAASW,KAAKR,SAAWQ,KAAKR,QAAQS,UAAYR,KAAKC,MACvDQ,QAAQC,QAAQH,KAAKX,OAG1BW,KAAKI,uBAITJ,KAAKI,qBAAuBJ,KAAKF,aAAahB,GAEvCkB,KAAKI,uBAGPL,yBAAP,SAAoBjB,GAApB,WACQC,KACJsB,OAAQ,CACNC,UAAWN,KAAKO,SAChBC,cAAeR,KAAKS,aACpBC,WAAY,qBACZC,WAAYX,KAAKY,WAEhB9B,GAEL,OAAOF,EAAcoB,KAAKa,wBAAwB9B,GAASG,KACzD,SAAAC,GAIE,O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ASE,kEAyEpDkB,EACAsD,EACAhD,GAiBA,oBAjBAA,yCAGMhC,iCACA6D,EAAK,CACTC,OAAQ,OACR2I,QAAS,CACPC,wBAAyBhL,EACzBiL,2BAA4B3H,GAI9BxD,OAAQ,CACNuC,EAAG,SAIA3D,UAAQJ,EAAK6D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@esri/arcgis-rest-auth",
3
- "version": "3.7.0",
3
+ "version": "3.8.0",
4
4
  "description": "Authentication helpers for @esri/arcgis-rest-js.",
5
5
  "main": "dist/node/index.js",
6
6
  "unpkg": "dist/umd/auth.umd.js",
@@ -13,11 +13,11 @@
13
13
  "dist/**"
14
14
  ],
15
15
  "dependencies": {
16
- "@esri/arcgis-rest-types": "^3.7.0",
16
+ "@esri/arcgis-rest-types": "^3.8.0",
17
17
  "tslib": "^1.13.0"
18
18
  },
19
19
  "devDependencies": {
20
- "@esri/arcgis-rest-request": "^3.7.0"
20
+ "@esri/arcgis-rest-request": "^3.8.0"
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@esri/arcgis-rest-request": "^3.0.0"