expo-auth-session 3.3.1 → 3.4.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.
package/CHANGELOG.md CHANGED
@@ -10,9 +10,11 @@
10
10
 
11
11
  ### 💡 Others
12
12
 
13
- ## 3.3.1 — 2021-06-23
13
+ ## 3.4.0 — 2021-09-28
14
14
 
15
- _This version does not introduce any user-facing changes._
15
+ ### 🎉 New features
16
+
17
+ - Update JS code to read manifest2 when manifest is not available. ([#13602](https://github.com/expo/expo/pull/13602) by [@wschurman](https://github.com/wschurman))
16
18
 
17
19
  ## 3.3.0 — 2021-06-16
18
20
 
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
 
10
10
  # Installation in managed Expo projects
11
11
 
12
- For managed [managed](https://docs.expo.io/versions/latest/introduction/managed-vs-bare/) Expo projects, please follow the installation instructions in the [API documentation for the latest stable release](https://docs.expo.io/versions/latest/sdk/auth-session).
12
+ For [managed](https://docs.expo.io/versions/latest/introduction/managed-vs-bare/) Expo projects, please follow the installation instructions in the [API documentation for the latest stable release](https://docs.expo.io/versions/latest/sdk/auth-session).
13
13
 
14
14
  # Installation in bare React Native projects
15
15
 
@@ -14,8 +14,23 @@ let _authLock = false;
14
14
  * [Section 4.1.1](https://tools.ietf.org/html/rfc6749#section-4.1.1)
15
15
  */
16
16
  export class AuthRequest {
17
+ /**
18
+ * Used for protection against [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12).
19
+ */
20
+ state;
21
+ url = null;
22
+ codeVerifier;
23
+ codeChallenge;
24
+ responseType;
25
+ clientId;
26
+ extraParams;
27
+ usePKCE;
28
+ codeChallengeMethod;
29
+ redirectUri;
30
+ scopes;
31
+ clientSecret;
32
+ prompt;
17
33
  constructor(request) {
18
- this.url = null;
19
34
  this.responseType = request.responseType ?? ResponseType.Code;
20
35
  this.clientId = request.clientId;
21
36
  this.redirectUri = request.redirectUri;
@@ -1 +1 @@
1
- {"version":3,"file":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AAK,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACzC;QAED,MAAM,KAAK,GAAG,WAAW,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QACnD,0BAA0B;QAC1B,IAAI,CAAC,GAAG,GAAG,GAAG,SAAS,CAAC,qBAAqB,IAAI,KAAK,EAAE,CAAC;QACzD,OAAO,IAAI,CAAC,GAAG,CAAC;IAClB,CAAC;IAEO,KAAK,CAAC,sBAAsB;QAClC,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,OAAO;SACR;QAED,kEAAkE;QAClE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;QAEpE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;CACF","sourcesContent":["import * as WebBrowser from 'expo-web-browser';\nimport invariant from 'invariant';\nimport { Platform } from 'react-native';\n\nimport {\n AuthRequestConfig,\n AuthRequestPromptOptions,\n CodeChallengeMethod,\n ResponseType,\n Prompt,\n} from './AuthRequest.types';\nimport { AuthSessionResult } from './AuthSession.types';\nimport { DiscoveryDocument } from './Discovery';\nimport { AuthError } from './Errors';\nimport * as PKCE from './PKCE';\nimport * as QueryParams from './QueryParams';\nimport sessionUrlProvider from './SessionUrlProvider';\nimport { TokenResponse } from './TokenRequest';\n\nlet _authLock: boolean = false;\n\ntype AuthDiscoveryDocument = Pick<DiscoveryDocument, 'authorizationEndpoint'>;\n\n/**\n * Implements an authorization request.\n *\n * [Section 4.1.1](https://tools.ietf.org/html/rfc6749#section-4.1.1)\n */\nexport class AuthRequest implements Omit<AuthRequestConfig, 'state'> {\n /**\n * Used for protection against [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12).\n */\n public state: string;\n public url: string | null = null;\n public codeVerifier?: string;\n public codeChallenge?: string;\n\n readonly responseType: ResponseType | string;\n readonly clientId: string;\n readonly extraParams: Record<string, string>;\n readonly usePKCE?: boolean;\n readonly codeChallengeMethod: CodeChallengeMethod;\n readonly redirectUri: string;\n readonly scopes?: string[];\n readonly clientSecret?: string;\n readonly prompt?: Prompt;\n\n constructor(request: AuthRequestConfig) {\n this.responseType = request.responseType ?? ResponseType.Code;\n this.clientId = request.clientId;\n this.redirectUri = request.redirectUri;\n this.scopes = request.scopes;\n this.clientSecret = request.clientSecret;\n this.prompt = request.prompt;\n this.state = request.state ?? PKCE.generateRandom(10);\n this.extraParams = request.extraParams ?? {};\n this.codeChallengeMethod = request.codeChallengeMethod ?? CodeChallengeMethod.S256;\n // PKCE defaults to true\n this.usePKCE = request.usePKCE ?? true;\n\n // Some warnings in development about potential confusing application code\n if (__DEV__) {\n if (this.prompt && this.extraParams.prompt) {\n console.warn(`\\`AuthRequest\\` \\`extraParams.prompt\\` will be overwritten by \\`prompt\\`.`);\n }\n if (this.clientSecret && this.extraParams.client_secret) {\n console.warn(\n `\\`AuthRequest\\` \\`extraParams.client_secret\\` will be overwritten by \\`clientSecret\\`.`\n );\n }\n if (this.codeChallengeMethod && this.extraParams.code_challenge_method) {\n console.warn(\n `\\`AuthRequest\\` \\`extraParams.code_challenge_method\\` will be overwritten by \\`codeChallengeMethod\\`.`\n );\n }\n }\n\n invariant(\n this.codeChallengeMethod !== CodeChallengeMethod.Plain,\n `\\`AuthRequest\\` does not support \\`CodeChallengeMethod.Plain\\` as it's not secure.`\n );\n invariant(\n this.redirectUri,\n `\\`AuthRequest\\` requires a valid \\`redirectUri\\`. Ex: ${Platform.select({\n web: 'https://yourwebsite.com/',\n default: 'com.your.app:/oauthredirect',\n })}`\n );\n }\n\n /**\n * Load and return a valid auth request based on the input config.\n */\n async getAuthRequestConfigAsync(): Promise<AuthRequestConfig> {\n if (this.usePKCE) {\n await this.ensureCodeIsSetupAsync();\n }\n\n return {\n responseType: this.responseType,\n clientId: this.clientId,\n redirectUri: this.redirectUri,\n scopes: this.scopes,\n clientSecret: this.clientSecret,\n codeChallenge: this.codeChallenge,\n codeChallengeMethod: this.codeChallengeMethod,\n prompt: this.prompt,\n state: this.state,\n extraParams: this.extraParams,\n usePKCE: this.usePKCE,\n };\n }\n\n /**\n * Prompt a user to authorize for a code.\n *\n * @param discovery\n * @param promptOptions\n */\n async promptAsync(\n discovery: AuthDiscoveryDocument,\n { url, proxyOptions, ...options }: AuthRequestPromptOptions = {}\n ): Promise<AuthSessionResult> {\n if (!url) {\n if (!this.url) {\n // Generate a new url\n return this.promptAsync(discovery, {\n ...options,\n url: await this.makeAuthUrlAsync(discovery),\n });\n }\n // Reuse the preloaded url\n url = this.url;\n }\n\n // Prevent accidentally starting to an empty url\n invariant(\n url,\n 'No authUrl provided to AuthSession.startAsync. An authUrl is required -- it points to the page where the user will be able to sign in.'\n );\n\n let startUrl: string = url!;\n let returnUrl: string = this.redirectUri;\n if (options.useProxy) {\n returnUrl = sessionUrlProvider.getDefaultReturnUrl(proxyOptions?.path, proxyOptions);\n startUrl = sessionUrlProvider.getStartUrl(url, returnUrl);\n }\n // Prevent multiple sessions from running at the same time, WebBrowser doesn't\n // support it this makes the behavior predictable.\n if (_authLock) {\n if (__DEV__) {\n console.warn(\n 'Attempted to call AuthSession.startAsync multiple times while already active. Only one AuthSession can be active at any given time.'\n );\n }\n\n return { type: 'locked' };\n }\n\n // About to start session, set lock\n _authLock = true;\n\n let result: WebBrowser.WebBrowserAuthSessionResult;\n try {\n const { useProxy, ...openOptions } = options;\n result = await WebBrowser.openAuthSessionAsync(startUrl, returnUrl, openOptions);\n } finally {\n _authLock = false;\n }\n\n if (result.type === 'opened') {\n // This should never happen\n throw new Error('An unexpected error occurred');\n }\n if (result.type !== 'success') {\n return { type: result.type };\n }\n\n return this.parseReturnUrl(result.url);\n }\n\n parseReturnUrl(url: string): AuthSessionResult {\n const { params, errorCode } = QueryParams.getQueryParams(url);\n const { state, error = errorCode } = params;\n\n let parsedError: AuthError | null = null;\n let authentication: TokenResponse | null = null;\n if (state !== this.state) {\n // This is a non-standard error\n parsedError = new AuthError({\n error: 'state_mismatch',\n error_description:\n 'Cross-Site request verification failed. Cached state and returned state do not match.',\n });\n } else if (error) {\n parsedError = new AuthError({ error, ...params });\n }\n if (params.access_token) {\n authentication = TokenResponse.fromQueryParams(params);\n }\n\n return {\n type: parsedError ? 'error' : 'success',\n error: parsedError,\n url,\n params,\n authentication,\n\n // Return errorCode for legacy\n errorCode,\n };\n }\n\n /**\n * Create the URL for authorization.\n *\n * @param discovery\n */\n async makeAuthUrlAsync(discovery: AuthDiscoveryDocument): Promise<string> {\n const request = await this.getAuthRequestConfigAsync();\n if (!request.state) throw new Error('Cannot make request URL without a valid `state` loaded');\n\n // Create a query string\n const params: Record<string, string> = {};\n\n if (request.codeChallenge) {\n params.code_challenge = request.codeChallenge;\n }\n\n // copy over extra params\n for (const extra in request.extraParams) {\n if (extra in request.extraParams) {\n params[extra] = request.extraParams[extra];\n }\n }\n\n if (request.usePKCE && request.codeChallengeMethod) {\n params.code_challenge_method = request.codeChallengeMethod;\n }\n\n if (request.clientSecret) {\n params.client_secret = request.clientSecret;\n }\n\n if (request.prompt) {\n params.prompt = request.prompt;\n }\n\n // These overwrite any extra params\n params.redirect_uri = request.redirectUri;\n params.client_id = request.clientId;\n params.response_type = request.responseType!;\n params.state = request.state;\n\n if (request.scopes?.length) {\n params.scope = request.scopes.join(' ');\n }\n\n const query = QueryParams.buildQueryString(params);\n // Store the URL for later\n this.url = `${discovery.authorizationEndpoint}?${query}`;\n return this.url;\n }\n\n private async ensureCodeIsSetupAsync(): Promise<void> {\n if (this.codeVerifier) {\n return;\n }\n\n // This method needs to be resolved like all other native methods.\n const { codeVerifier, codeChallenge } = await PKCE.buildCodeAsync();\n\n this.codeVerifier = codeVerifier;\n this.codeChallenge = codeChallenge;\n }\n}\n"]}
1
+ {"version":3,"file":"AuthRequest.js","sourceRoot":"","sources":["../src/AuthRequest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,UAAU,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,OAAO,CAAC,YAAa,CAAC;QAC7C,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAE7B,IAAI,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE;YAC1B,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACzC;QAED,MAAM,KAAK,GAAG,WAAW,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QACnD,0BAA0B;QAC1B,IAAI,CAAC,GAAG,GAAG,GAAG,SAAS,CAAC,qBAAqB,IAAI,KAAK,EAAE,CAAC;QACzD,OAAO,IAAI,CAAC,GAAG,CAAC;IAClB,CAAC;IAEO,KAAK,CAAC,sBAAsB;QAClC,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,OAAO;SACR;QAED,kEAAkE;QAClE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;QAEpE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;CACF","sourcesContent":["import * as WebBrowser from 'expo-web-browser';\nimport invariant from 'invariant';\nimport { Platform } from 'react-native';\n\nimport {\n AuthRequestConfig,\n AuthRequestPromptOptions,\n CodeChallengeMethod,\n ResponseType,\n Prompt,\n} from './AuthRequest.types';\nimport { AuthSessionResult } from './AuthSession.types';\nimport { DiscoveryDocument } from './Discovery';\nimport { AuthError } from './Errors';\nimport * as PKCE from './PKCE';\nimport * as QueryParams from './QueryParams';\nimport sessionUrlProvider from './SessionUrlProvider';\nimport { TokenResponse } from './TokenRequest';\n\nlet _authLock: boolean = false;\n\ntype AuthDiscoveryDocument = Pick<DiscoveryDocument, 'authorizationEndpoint'>;\n\n/**\n * Implements an authorization request.\n *\n * [Section 4.1.1](https://tools.ietf.org/html/rfc6749#section-4.1.1)\n */\nexport class AuthRequest implements Omit<AuthRequestConfig, 'state'> {\n /**\n * Used for protection against [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12).\n */\n public state: string;\n public url: string | null = null;\n public codeVerifier?: string;\n public codeChallenge?: string;\n\n readonly responseType: ResponseType | string;\n readonly clientId: string;\n readonly extraParams: Record<string, string>;\n readonly usePKCE?: boolean;\n readonly codeChallengeMethod: CodeChallengeMethod;\n readonly redirectUri: string;\n readonly scopes?: string[];\n readonly clientSecret?: string;\n readonly prompt?: Prompt;\n\n constructor(request: AuthRequestConfig) {\n this.responseType = request.responseType ?? ResponseType.Code;\n this.clientId = request.clientId;\n this.redirectUri = request.redirectUri;\n this.scopes = request.scopes;\n this.clientSecret = request.clientSecret;\n this.prompt = request.prompt;\n this.state = request.state ?? PKCE.generateRandom(10);\n this.extraParams = request.extraParams ?? {};\n this.codeChallengeMethod = request.codeChallengeMethod ?? CodeChallengeMethod.S256;\n // PKCE defaults to true\n this.usePKCE = request.usePKCE ?? true;\n\n // Some warnings in development about potential confusing application code\n if (__DEV__) {\n if (this.prompt && this.extraParams.prompt) {\n console.warn(`\\`AuthRequest\\` \\`extraParams.prompt\\` will be overwritten by \\`prompt\\`.`);\n }\n if (this.clientSecret && this.extraParams.client_secret) {\n console.warn(\n `\\`AuthRequest\\` \\`extraParams.client_secret\\` will be overwritten by \\`clientSecret\\`.`\n );\n }\n if (this.codeChallengeMethod && this.extraParams.code_challenge_method) {\n console.warn(\n `\\`AuthRequest\\` \\`extraParams.code_challenge_method\\` will be overwritten by \\`codeChallengeMethod\\`.`\n );\n }\n }\n\n invariant(\n this.codeChallengeMethod !== CodeChallengeMethod.Plain,\n `\\`AuthRequest\\` does not support \\`CodeChallengeMethod.Plain\\` as it's not secure.`\n );\n invariant(\n this.redirectUri,\n `\\`AuthRequest\\` requires a valid \\`redirectUri\\`. Ex: ${Platform.select({\n web: 'https://yourwebsite.com/',\n default: 'com.your.app:/oauthredirect',\n })}`\n );\n }\n\n /**\n * Load and return a valid auth request based on the input config.\n */\n async getAuthRequestConfigAsync(): Promise<AuthRequestConfig> {\n if (this.usePKCE) {\n await this.ensureCodeIsSetupAsync();\n }\n\n return {\n responseType: this.responseType,\n clientId: this.clientId,\n redirectUri: this.redirectUri,\n scopes: this.scopes,\n clientSecret: this.clientSecret,\n codeChallenge: this.codeChallenge,\n codeChallengeMethod: this.codeChallengeMethod,\n prompt: this.prompt,\n state: this.state,\n extraParams: this.extraParams,\n usePKCE: this.usePKCE,\n };\n }\n\n /**\n * Prompt a user to authorize for a code.\n *\n * @param discovery\n * @param promptOptions\n */\n async promptAsync(\n discovery: AuthDiscoveryDocument,\n { url, proxyOptions, ...options }: AuthRequestPromptOptions = {}\n ): Promise<AuthSessionResult> {\n if (!url) {\n if (!this.url) {\n // Generate a new url\n return this.promptAsync(discovery, {\n ...options,\n url: await this.makeAuthUrlAsync(discovery),\n });\n }\n // Reuse the preloaded url\n url = this.url;\n }\n\n // Prevent accidentally starting to an empty url\n invariant(\n url,\n 'No authUrl provided to AuthSession.startAsync. An authUrl is required -- it points to the page where the user will be able to sign in.'\n );\n\n let startUrl: string = url!;\n let returnUrl: string = this.redirectUri;\n if (options.useProxy) {\n returnUrl = sessionUrlProvider.getDefaultReturnUrl(proxyOptions?.path, proxyOptions);\n startUrl = sessionUrlProvider.getStartUrl(url, returnUrl);\n }\n // Prevent multiple sessions from running at the same time, WebBrowser doesn't\n // support it this makes the behavior predictable.\n if (_authLock) {\n if (__DEV__) {\n console.warn(\n 'Attempted to call AuthSession.startAsync multiple times while already active. Only one AuthSession can be active at any given time.'\n );\n }\n\n return { type: 'locked' };\n }\n\n // About to start session, set lock\n _authLock = true;\n\n let result: WebBrowser.WebBrowserAuthSessionResult;\n try {\n const { useProxy, ...openOptions } = options;\n result = await WebBrowser.openAuthSessionAsync(startUrl, returnUrl, openOptions);\n } finally {\n _authLock = false;\n }\n\n if (result.type === 'opened') {\n // This should never happen\n throw new Error('An unexpected error occurred');\n }\n if (result.type !== 'success') {\n return { type: result.type };\n }\n\n return this.parseReturnUrl(result.url);\n }\n\n parseReturnUrl(url: string): AuthSessionResult {\n const { params, errorCode } = QueryParams.getQueryParams(url);\n const { state, error = errorCode } = params;\n\n let parsedError: AuthError | null = null;\n let authentication: TokenResponse | null = null;\n if (state !== this.state) {\n // This is a non-standard error\n parsedError = new AuthError({\n error: 'state_mismatch',\n error_description:\n 'Cross-Site request verification failed. Cached state and returned state do not match.',\n });\n } else if (error) {\n parsedError = new AuthError({ error, ...params });\n }\n if (params.access_token) {\n authentication = TokenResponse.fromQueryParams(params);\n }\n\n return {\n type: parsedError ? 'error' : 'success',\n error: parsedError,\n url,\n params,\n authentication,\n\n // Return errorCode for legacy\n errorCode,\n };\n }\n\n /**\n * Create the URL for authorization.\n *\n * @param discovery\n */\n async makeAuthUrlAsync(discovery: AuthDiscoveryDocument): Promise<string> {\n const request = await this.getAuthRequestConfigAsync();\n if (!request.state) throw new Error('Cannot make request URL without a valid `state` loaded');\n\n // Create a query string\n const params: Record<string, string> = {};\n\n if (request.codeChallenge) {\n params.code_challenge = request.codeChallenge;\n }\n\n // copy over extra params\n for (const extra in request.extraParams) {\n if (extra in request.extraParams) {\n params[extra] = request.extraParams[extra];\n }\n }\n\n if (request.usePKCE && request.codeChallengeMethod) {\n params.code_challenge_method = request.codeChallengeMethod;\n }\n\n if (request.clientSecret) {\n params.client_secret = request.clientSecret;\n }\n\n if (request.prompt) {\n params.prompt = request.prompt;\n }\n\n // These overwrite any extra params\n params.redirect_uri = request.redirectUri;\n params.client_id = request.clientId;\n params.response_type = request.responseType!;\n params.state = request.state;\n\n if (request.scopes?.length) {\n params.scope = request.scopes.join(' ');\n }\n\n const query = QueryParams.buildQueryString(params);\n // Store the URL for later\n this.url = `${discovery.authorizationEndpoint}?${query}`;\n return this.url;\n }\n\n private async ensureCodeIsSetupAsync(): Promise<void> {\n if (this.codeVerifier) {\n return;\n }\n\n // This method needs to be resolved like all other native methods.\n const { codeVerifier, codeChallenge } = await PKCE.buildCodeAsync();\n\n this.codeVerifier = codeVerifier;\n this.codeChallenge = codeChallenge;\n }\n}\n"]}
@@ -10,7 +10,7 @@ export function useAutoDiscovery(issuerOrDiscovery) {
10
10
  const [discovery, setDiscovery] = useState(null);
11
11
  useEffect(() => {
12
12
  let isAllowed = true;
13
- resolveDiscoveryAsync(issuerOrDiscovery).then(discovery => {
13
+ resolveDiscoveryAsync(issuerOrDiscovery).then((discovery) => {
14
14
  if (isAllowed) {
15
15
  setDiscovery(discovery);
16
16
  }
@@ -24,9 +24,7 @@ export function useAutoDiscovery(issuerOrDiscovery) {
24
24
  export function useLoadedAuthRequest(config, discovery, AuthRequestInstance) {
25
25
  const [request, setRequest] = useState(null);
26
26
  const scopeString = useMemo(() => config.scopes?.join(','), [config.scopes]);
27
- const extraParamsString = useMemo(() => JSON.stringify(config.extraParams || {}), [
28
- config.extraParams,
29
- ]);
27
+ const extraParamsString = useMemo(() => JSON.stringify(config.extraParams || {}), [config.extraParams]);
30
28
  useEffect(() => {
31
29
  let isMounted = true;
32
30
  if (discovery) {
@@ -1 +1 @@
1
- {"version":3,"file":"AuthRequestHooks.js","sourceRoot":"","sources":["../src/AuthRequestHooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAElE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG5C,OAAO,EAAwC,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAE1F;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,iBAAoC;IACnE,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,GAAG,QAAQ,CAA2B,IAAI,CAAC,CAAC;IAE3E,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,SAAS,GAAG,IAAI,CAAC;QACrB,qBAAqB,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;YACxD,IAAI,SAAS,EAAE;gBACb,YAAY,CA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AAO,EAAE,SAAS,CAAC,CAAC;IACvE,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { useCallback, useMemo, useEffect, useState } from 'react';\n\nimport { AuthRequest } from './AuthRequest';\nimport { AuthRequestConfig, AuthRequestPromptOptions } from './AuthRequest.types';\nimport { AuthSessionResult } from './AuthSession.types';\nimport { DiscoveryDocument, IssuerOrDiscovery, resolveDiscoveryAsync } from './Discovery';\n\n/**\n * Fetch the discovery document from an OpenID Connect issuer.\n *\n * @param issuerOrDiscovery\n */\nexport function useAutoDiscovery(issuerOrDiscovery: IssuerOrDiscovery): DiscoveryDocument | null {\n const [discovery, setDiscovery] = useState<DiscoveryDocument | null>(null);\n\n useEffect(() => {\n let isAllowed = true;\n resolveDiscoveryAsync(issuerOrDiscovery).then(discovery => {\n if (isAllowed) {\n setDiscovery(discovery);\n }\n });\n\n return () => {\n isAllowed = false;\n };\n }, [issuerOrDiscovery]);\n\n return discovery;\n}\n\nexport function useLoadedAuthRequest(\n config: AuthRequestConfig,\n discovery: DiscoveryDocument | null,\n AuthRequestInstance: typeof AuthRequest\n): AuthRequest | null {\n const [request, setRequest] = useState<AuthRequest | null>(null);\n const scopeString = useMemo(() => config.scopes?.join(','), [config.scopes]);\n const extraParamsString = useMemo(() => JSON.stringify(config.extraParams || {}), [\n config.extraParams,\n ]);\n useEffect(\n () => {\n let isMounted = true;\n\n if (discovery) {\n const request = new AuthRequestInstance(config);\n request.makeAuthUrlAsync(discovery).then(() => {\n if (isMounted) {\n // @ts-ignore\n setRequest(request);\n }\n });\n }\n return () => {\n isMounted = false;\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n discovery?.authorizationEndpoint,\n config.clientId,\n config.redirectUri,\n config.responseType,\n config.prompt,\n config.clientSecret,\n config.codeChallenge,\n config.state,\n config.usePKCE,\n scopeString,\n extraParamsString,\n ]\n );\n return request;\n}\n\ntype PromptMethod = (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>;\n\nexport function useAuthRequestResult(\n request: AuthRequest | null,\n discovery: DiscoveryDocument | null,\n customOptions: AuthRequestPromptOptions = {}\n): [AuthSessionResult | null, PromptMethod] {\n const [result, setResult] = useState<AuthSessionResult | null>(null);\n\n const promptAsync = useCallback(\n async ({ windowFeatures = {}, ...options }: AuthRequestPromptOptions = {}) => {\n if (!discovery || !request) {\n throw new Error('Cannot prompt to authenticate until the request has finished loading.');\n }\n const inputOptions = {\n ...customOptions,\n ...options,\n windowFeatures: {\n ...(customOptions.windowFeatures ?? {}),\n ...windowFeatures,\n },\n };\n const result = await request?.promptAsync(discovery, inputOptions);\n setResult(result);\n return result;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [request?.url, discovery?.authorizationEndpoint]\n );\n\n return [result, promptAsync];\n}\n\n/**\n * Load an authorization request.\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes then the response will be fulfilled.\n *\n * @param config\n * @param discovery\n */\nexport function useAuthRequest(\n config: AuthRequestConfig,\n discovery: DiscoveryDocument | null\n): [\n AuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const request = useLoadedAuthRequest(config, discovery, AuthRequest);\n const [result, promptAsync] = useAuthRequestResult(request, discovery);\n return [request, result, promptAsync];\n}\n"]}
1
+ {"version":3,"file":"AuthRequestHooks.js","sourceRoot":"","sources":["../src/AuthRequestHooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAElE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG5C,OAAO,EAAwC,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAE1F;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,iBAAoC;IACnE,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,GAAG,QAAQ,CAA2B,IA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AOG;AACH,MAAM,UAAU,cAAc,CAC5B,MAAyB,EACzB,SAAmC;IAMnC,MAAM,OAAO,GAAG,oBAAoB,CAAC,MAAM,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC;IACrE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GAAG,oBAAoB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACvE,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { useCallback, useMemo, useEffect, useState } from 'react';\n\nimport { AuthRequest } from './AuthRequest';\nimport { AuthRequestConfig, AuthRequestPromptOptions } from './AuthRequest.types';\nimport { AuthSessionResult } from './AuthSession.types';\nimport { DiscoveryDocument, IssuerOrDiscovery, resolveDiscoveryAsync } from './Discovery';\n\n/**\n * Fetch the discovery document from an OpenID Connect issuer.\n *\n * @param issuerOrDiscovery\n */\nexport function useAutoDiscovery(issuerOrDiscovery: IssuerOrDiscovery): DiscoveryDocument | null {\n const [discovery, setDiscovery] = useState<DiscoveryDocument | null>(null);\n\n useEffect(() => {\n let isAllowed = true;\n resolveDiscoveryAsync(issuerOrDiscovery).then((discovery) => {\n if (isAllowed) {\n setDiscovery(discovery);\n }\n });\n\n return () => {\n isAllowed = false;\n };\n }, [issuerOrDiscovery]);\n\n return discovery;\n}\n\nexport function useLoadedAuthRequest(\n config: AuthRequestConfig,\n discovery: DiscoveryDocument | null,\n AuthRequestInstance: typeof AuthRequest\n): AuthRequest | null {\n const [request, setRequest] = useState<AuthRequest | null>(null);\n const scopeString = useMemo(() => config.scopes?.join(','), [config.scopes]);\n const extraParamsString = useMemo(\n () => JSON.stringify(config.extraParams || {}),\n [config.extraParams]\n );\n useEffect(\n () => {\n let isMounted = true;\n\n if (discovery) {\n const request = new AuthRequestInstance(config);\n request.makeAuthUrlAsync(discovery).then(() => {\n if (isMounted) {\n // @ts-ignore\n setRequest(request);\n }\n });\n }\n return () => {\n isMounted = false;\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n discovery?.authorizationEndpoint,\n config.clientId,\n config.redirectUri,\n config.responseType,\n config.prompt,\n config.clientSecret,\n config.codeChallenge,\n config.state,\n config.usePKCE,\n scopeString,\n extraParamsString,\n ]\n );\n return request;\n}\n\ntype PromptMethod = (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>;\n\nexport function useAuthRequestResult(\n request: AuthRequest | null,\n discovery: DiscoveryDocument | null,\n customOptions: AuthRequestPromptOptions = {}\n): [AuthSessionResult | null, PromptMethod] {\n const [result, setResult] = useState<AuthSessionResult | null>(null);\n\n const promptAsync = useCallback(\n async ({ windowFeatures = {}, ...options }: AuthRequestPromptOptions = {}) => {\n if (!discovery || !request) {\n throw new Error('Cannot prompt to authenticate until the request has finished loading.');\n }\n const inputOptions = {\n ...customOptions,\n ...options,\n windowFeatures: {\n ...(customOptions.windowFeatures ?? {}),\n ...windowFeatures,\n },\n };\n const result = await request?.promptAsync(discovery, inputOptions);\n setResult(result);\n return result;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [request?.url, discovery?.authorizationEndpoint]\n );\n\n return [result, promptAsync];\n}\n\n/**\n * Load an authorization request.\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes then the response will be fulfilled.\n *\n * @param config\n * @param discovery\n */\nexport function useAuthRequest(\n config: AuthRequestConfig,\n discovery: DiscoveryDocument | null\n): [\n AuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const request = useLoadedAuthRequest(config, discovery, AuthRequest);\n const [result, promptAsync] = useAuthRequestResult(request, discovery);\n return [request, result, promptAsync];\n}\n"]}
@@ -6,7 +6,7 @@ import { DiscoveryDocument, fetchDiscoveryAsync, Issuer, IssuerOrDiscovery, Prov
6
6
  import { generateHexStringAsync } from './PKCE';
7
7
  export declare function startAsync(options: AuthSessionOptions): Promise<AuthSessionResult>;
8
8
  export declare function dismiss(): void;
9
- export declare const getDefaultReturnUrl: (urlPath?: string | undefined, options?: Pick<Linking.CreateURLOptions, "scheme" | "isTripleSlashed"> | undefined) => string;
9
+ export declare const getDefaultReturnUrl: (urlPath?: string | undefined, options?: Omit<Linking.CreateURLOptions, "queryParams"> | undefined) => string;
10
10
  /**
11
11
  * @deprecated Use `makeRedirectUri({ path, useProxy })` instead.
12
12
  *
@@ -1,6 +1,6 @@
1
- import { Platform } from '@unimodules/core';
2
1
  import Constants, { ExecutionEnvironment } from 'expo-constants';
3
2
  import * as Linking from 'expo-linking';
3
+ import { Platform } from 'expo-modules-core';
4
4
  import { dismissAuthSession, openAuthSessionAsync } from 'expo-web-browser';
5
5
  import { AuthRequest } from './AuthRequest';
6
6
  import { CodeChallengeMethod, Prompt, ResponseType, } from './AuthRequest.types';
@@ -1 +1 @@
1
- {"version":3,"file":"AuthSession.js","sourceRoot":"","sources":["../src/AuthSession.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,SAAS,EAAE,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAE5E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAGL,mBAAmB,EACnB,MAAM,EACN,YAAY,GACb,MAAM,qBAAqB,CAAC;AAM7B,OAAO,EAEL,mBAAmB,EAInB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AAEtD,IAAI,SAAS,GAAG,KAAK,CAAC;AAEtB,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAA2B;IAC1D,MAAM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sourcesContent":["import { Platform } from '@unimodules/core';\nimport Constants, { ExecutionEnvironment } from 'expo-constants';\nimport * as Linking from 'expo-linking';\nimport { dismissAuthSession, openAuthSessionAsync } from 'expo-web-browser';\n\nimport { AuthRequest } from './AuthRequest';\nimport {\n AuthRequestConfig,\n AuthRequestPromptOptions,\n CodeChallengeMethod,\n Prompt,\n ResponseType,\n} from './AuthRequest.types';\nimport {\n AuthSessionOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n} from './AuthSession.types';\nimport {\n DiscoveryDocument,\n fetchDiscoveryAsync,\n Issuer,\n IssuerOrDiscovery,\n ProviderMetadata,\n resolveDiscoveryAsync,\n} from './Discovery';\nimport { generateHexStringAsync } from './PKCE';\nimport { getQueryParams } from './QueryParams';\nimport sessionUrlProvider from './SessionUrlProvider';\n\nlet _authLock = false;\n\nexport async function startAsync(options: AuthSessionOptions): Promise<AuthSessionResult> {\n const authUrl = options.authUrl;\n // Prevent accidentally starting to an empty url\n if (!authUrl) {\n throw new Error(\n 'No authUrl provided to AuthSession.startAsync. An authUrl is required -- it points to the page where the user will be able to sign in.'\n );\n }\n // Prevent multiple sessions from running at the same time, WebBrowser doesn't\n // support it this makes the behavior predictable.\n if (_authLock) {\n if (__DEV__) {\n console.warn(\n 'Attempted to call AuthSession.startAsync multiple times while already active. Only one AuthSession can be active at any given time.'\n );\n }\n\n return { type: 'locked' };\n }\n\n const returnUrl = options.returnUrl || sessionUrlProvider.getDefaultReturnUrl();\n const startUrl = sessionUrlProvider.getStartUrl(authUrl, returnUrl);\n const showInRecents = options.showInRecents || false;\n\n // About to start session, set lock\n _authLock = true;\n\n let result;\n try {\n result = await _openWebBrowserAsync(startUrl, returnUrl, showInRecents);\n } finally {\n // WebBrowser session complete, unset lock\n _authLock = false;\n }\n\n // Handle failures\n if (!result) {\n throw new Error('Unexpected missing AuthSession result');\n }\n if (!result.url) {\n if (result.type) {\n return result;\n } else {\n throw new Error('Unexpected AuthSession result with missing type');\n }\n }\n\n const { params, errorCode } = getQueryParams(result.url);\n\n return {\n type: errorCode ? 'error' : 'success',\n params,\n errorCode,\n authentication: null,\n url: result.url,\n };\n}\n\nexport function dismiss() {\n dismissAuthSession();\n}\n\nexport const getDefaultReturnUrl = sessionUrlProvider.getDefaultReturnUrl;\n\n/**\n * @deprecated Use `makeRedirectUri({ path, useProxy })` instead.\n *\n * @param path\n */\nexport function getRedirectUrl(path?: string): string {\n return sessionUrlProvider.getRedirectUrl(path);\n}\n\n/**\n * Create a redirect url for the current platform.\n *\n * - **Web:** Generates a path based on the current \\`window.location\\`. For production web apps you should hard code the URL.\n * - **Managed:** Uses the `scheme` property of your `app.config.js` or `app.json`.\n * - **Proxy:** Uses auth.expo.io as the base URL for the path. This only works in Expo client and standalone environments.\n * - **Bare workflow:** Provide either the `scheme` or a manual `native` property to use.\n *\n * @param options Additional options for configuring the path.\n *\n * @example\n * ```ts\n * const redirectUri = makeRedirectUri({\n * scheme: 'my-scheme',\n * path: 'redirect'\n * });\n * // Custom app: my-scheme://redirect\n * // Expo Go: exp://127.0.0.1:19000/--/redirect\n * // Web dev: https://localhost:19006/redirect\n * // Web prod: https://yourwebsite.com/redirect\n *\n * const redirectUri2 = makeRedirectUri({\n * scheme: 'scheme2',\n * preferLocalhost: true,\n * isTripleSlashed: true,\n * });\n * // Custom app: scheme2:///\n * // Expo Go: exp://localhost:19000\n * // Web dev: https://localhost:19006\n * // Web prod: https://yourwebsite.com\n * ```\n *\n * const redirectUri3 = makeRedirectUri({\n * useProxy: true,\n * });\n * // Custom app: https://auth.expo.io/@username/slug\n * // Expo Go: https://auth.expo.io/@username/slug\n * // Web dev: https://localhost:19006\n * // Web prod: https://yourwebsite.com\n * ```\n */\nexport function makeRedirectUri({\n native,\n scheme,\n isTripleSlashed,\n queryParams,\n path,\n preferLocalhost,\n useProxy,\n}: AuthSessionRedirectUriOptions = {}): string {\n if (\n Platform.OS !== 'web' &&\n native &&\n [ExecutionEnvironment.Standalone, ExecutionEnvironment.Bare].includes(\n Constants.executionEnvironment\n )\n ) {\n // Should use the user-defined native scheme in standalone builds\n return native;\n }\n if (!useProxy || Platform.OS === 'web') {\n const url = Linking.createURL(path || '', {\n isTripleSlashed,\n scheme,\n queryParams,\n });\n\n if (preferLocalhost) {\n const ipAddress = url.match(\n /\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/\n );\n // Only replace if an IP address exists\n if (ipAddress?.length) {\n const [protocol, path] = url.split(ipAddress[0]);\n return `${protocol}localhost${path}`;\n }\n }\n\n return url;\n }\n // Attempt to use the proxy\n return sessionUrlProvider.getRedirectUrl(path);\n}\n\n/**\n * Build an `AuthRequest` and load it before returning.\n *\n * @param config\n * @param issuerOrDiscovery\n */\nexport async function loadAsync(\n config: AuthRequestConfig,\n issuerOrDiscovery: IssuerOrDiscovery\n): Promise<AuthRequest> {\n const request = new AuthRequest(config);\n const discovery = await resolveDiscoveryAsync(issuerOrDiscovery);\n await request.makeAuthUrlAsync(discovery);\n return request;\n}\n\nasync function _openWebBrowserAsync(startUrl: string, returnUrl: string, showInRecents: boolean) {\n // $FlowIssue: Flow thinks the awaited result can be a promise\n const result = await openAuthSessionAsync(startUrl, returnUrl, { showInRecents });\n if (result.type === 'cancel' || result.type === 'dismiss') {\n return { type: result.type };\n }\n\n return result;\n}\n\nexport { useAutoDiscovery, useAuthRequest } from './AuthRequestHooks';\nexport { AuthError, TokenError } from './Errors';\n\nexport {\n AuthSessionOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n AuthRequest,\n AuthRequestConfig,\n AuthRequestPromptOptions,\n CodeChallengeMethod,\n DiscoveryDocument,\n Issuer,\n IssuerOrDiscovery,\n Prompt,\n ProviderMetadata,\n ResponseType,\n resolveDiscoveryAsync,\n fetchDiscoveryAsync,\n generateHexStringAsync,\n};\n\nexport {\n // Token classes\n TokenResponse,\n AccessTokenRequest,\n RefreshTokenRequest,\n RevokeTokenRequest,\n // Token methods\n revokeAsync,\n refreshAsync,\n exchangeCodeAsync,\n fetchUserInfoAsync,\n} from './TokenRequest';\n\n// Token types\nexport * from './TokenRequest.types';\n"]}
1
+ {"version":3,"file":"AuthSession.js","sourceRoot":"","sources":["../src/AuthSession.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAE5E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAGL,mBAAmB,EACnB,MAAM,EACN,YAAY,GACb,MAAM,qBAAqB,CAAC;AAM7B,OAAO,EAEL,mBAAmB,EAInB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AAEtD,IAAI,SAAS,GAAG,KAAK,CAAC;AAEtB,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAA2B;IAC1D,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAChC,gDAAgD;IAChD,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CACb,wIAAwI,CACzI,CAAC;KACH;IACD,8EAA8E;IAC9E,kDAAkD;IAClD,IAAI,SAAS,EAAE;QACb,IAAI,OAAO,EAAE;YACX,OAAO,CAAC,IAAI,CACV,qIAAqI,CACtI,CAAC;SACH;QAED,OAAO,EAAE,IAAI,EAAE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AC,iBAAiB,CAAC,CAAC;IACjE,MAAM,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;IAC1C,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,KAAK,UAAU,oBAAoB,CAAC,QAAgB,EAAE,SAAiB,EAAE,aAAsB;IAC7F,8DAA8D;IAC9D,MAAM,MAAM,GAAG,MAAM,oBAAoB,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,CAAC,CAAC;IAClF,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE;QACzD,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;KAC9B;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEjD,OAAO,EAIL,WAAW,EAGX,mBAAmB,EAInB,MAAM,EAEN,YAAY,EACZ,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,GACvB,CAAC;AAEF,OAAO;AACL,gBAAgB;AAChB,aAAa,EACb,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB;AAClB,gBAAgB;AAChB,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AAExB,cAAc;AACd,cAAc,sBAAsB,CAAC","sourcesContent":["import Constants, { ExecutionEnvironment } from 'expo-constants';\nimport * as Linking from 'expo-linking';\nimport { Platform } from 'expo-modules-core';\nimport { dismissAuthSession, openAuthSessionAsync } from 'expo-web-browser';\n\nimport { AuthRequest } from './AuthRequest';\nimport {\n AuthRequestConfig,\n AuthRequestPromptOptions,\n CodeChallengeMethod,\n Prompt,\n ResponseType,\n} from './AuthRequest.types';\nimport {\n AuthSessionOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n} from './AuthSession.types';\nimport {\n DiscoveryDocument,\n fetchDiscoveryAsync,\n Issuer,\n IssuerOrDiscovery,\n ProviderMetadata,\n resolveDiscoveryAsync,\n} from './Discovery';\nimport { generateHexStringAsync } from './PKCE';\nimport { getQueryParams } from './QueryParams';\nimport sessionUrlProvider from './SessionUrlProvider';\n\nlet _authLock = false;\n\nexport async function startAsync(options: AuthSessionOptions): Promise<AuthSessionResult> {\n const authUrl = options.authUrl;\n // Prevent accidentally starting to an empty url\n if (!authUrl) {\n throw new Error(\n 'No authUrl provided to AuthSession.startAsync. An authUrl is required -- it points to the page where the user will be able to sign in.'\n );\n }\n // Prevent multiple sessions from running at the same time, WebBrowser doesn't\n // support it this makes the behavior predictable.\n if (_authLock) {\n if (__DEV__) {\n console.warn(\n 'Attempted to call AuthSession.startAsync multiple times while already active. Only one AuthSession can be active at any given time.'\n );\n }\n\n return { type: 'locked' };\n }\n\n const returnUrl = options.returnUrl || sessionUrlProvider.getDefaultReturnUrl();\n const startUrl = sessionUrlProvider.getStartUrl(authUrl, returnUrl);\n const showInRecents = options.showInRecents || false;\n\n // About to start session, set lock\n _authLock = true;\n\n let result;\n try {\n result = await _openWebBrowserAsync(startUrl, returnUrl, showInRecents);\n } finally {\n // WebBrowser session complete, unset lock\n _authLock = false;\n }\n\n // Handle failures\n if (!result) {\n throw new Error('Unexpected missing AuthSession result');\n }\n if (!result.url) {\n if (result.type) {\n return result;\n } else {\n throw new Error('Unexpected AuthSession result with missing type');\n }\n }\n\n const { params, errorCode } = getQueryParams(result.url);\n\n return {\n type: errorCode ? 'error' : 'success',\n params,\n errorCode,\n authentication: null,\n url: result.url,\n };\n}\n\nexport function dismiss() {\n dismissAuthSession();\n}\n\nexport const getDefaultReturnUrl = sessionUrlProvider.getDefaultReturnUrl;\n\n/**\n * @deprecated Use `makeRedirectUri({ path, useProxy })` instead.\n *\n * @param path\n */\nexport function getRedirectUrl(path?: string): string {\n return sessionUrlProvider.getRedirectUrl(path);\n}\n\n/**\n * Create a redirect url for the current platform.\n *\n * - **Web:** Generates a path based on the current \\`window.location\\`. For production web apps you should hard code the URL.\n * - **Managed:** Uses the `scheme` property of your `app.config.js` or `app.json`.\n * - **Proxy:** Uses auth.expo.io as the base URL for the path. This only works in Expo client and standalone environments.\n * - **Bare workflow:** Provide either the `scheme` or a manual `native` property to use.\n *\n * @param options Additional options for configuring the path.\n *\n * @example\n * ```ts\n * const redirectUri = makeRedirectUri({\n * scheme: 'my-scheme',\n * path: 'redirect'\n * });\n * // Custom app: my-scheme://redirect\n * // Expo Go: exp://127.0.0.1:19000/--/redirect\n * // Web dev: https://localhost:19006/redirect\n * // Web prod: https://yourwebsite.com/redirect\n *\n * const redirectUri2 = makeRedirectUri({\n * scheme: 'scheme2',\n * preferLocalhost: true,\n * isTripleSlashed: true,\n * });\n * // Custom app: scheme2:///\n * // Expo Go: exp://localhost:19000\n * // Web dev: https://localhost:19006\n * // Web prod: https://yourwebsite.com\n * ```\n *\n * const redirectUri3 = makeRedirectUri({\n * useProxy: true,\n * });\n * // Custom app: https://auth.expo.io/@username/slug\n * // Expo Go: https://auth.expo.io/@username/slug\n * // Web dev: https://localhost:19006\n * // Web prod: https://yourwebsite.com\n * ```\n */\nexport function makeRedirectUri({\n native,\n scheme,\n isTripleSlashed,\n queryParams,\n path,\n preferLocalhost,\n useProxy,\n}: AuthSessionRedirectUriOptions = {}): string {\n if (\n Platform.OS !== 'web' &&\n native &&\n [ExecutionEnvironment.Standalone, ExecutionEnvironment.Bare].includes(\n Constants.executionEnvironment\n )\n ) {\n // Should use the user-defined native scheme in standalone builds\n return native;\n }\n if (!useProxy || Platform.OS === 'web') {\n const url = Linking.createURL(path || '', {\n isTripleSlashed,\n scheme,\n queryParams,\n });\n\n if (preferLocalhost) {\n const ipAddress = url.match(\n /\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/\n );\n // Only replace if an IP address exists\n if (ipAddress?.length) {\n const [protocol, path] = url.split(ipAddress[0]);\n return `${protocol}localhost${path}`;\n }\n }\n\n return url;\n }\n // Attempt to use the proxy\n return sessionUrlProvider.getRedirectUrl(path);\n}\n\n/**\n * Build an `AuthRequest` and load it before returning.\n *\n * @param config\n * @param issuerOrDiscovery\n */\nexport async function loadAsync(\n config: AuthRequestConfig,\n issuerOrDiscovery: IssuerOrDiscovery\n): Promise<AuthRequest> {\n const request = new AuthRequest(config);\n const discovery = await resolveDiscoveryAsync(issuerOrDiscovery);\n await request.makeAuthUrlAsync(discovery);\n return request;\n}\n\nasync function _openWebBrowserAsync(startUrl: string, returnUrl: string, showInRecents: boolean) {\n // $FlowIssue: Flow thinks the awaited result can be a promise\n const result = await openAuthSessionAsync(startUrl, returnUrl, { showInRecents });\n if (result.type === 'cancel' || result.type === 'dismiss') {\n return { type: result.type };\n }\n\n return result;\n}\n\nexport { useAutoDiscovery, useAuthRequest } from './AuthRequestHooks';\nexport { AuthError, TokenError } from './Errors';\n\nexport {\n AuthSessionOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n AuthRequest,\n AuthRequestConfig,\n AuthRequestPromptOptions,\n CodeChallengeMethod,\n DiscoveryDocument,\n Issuer,\n IssuerOrDiscovery,\n Prompt,\n ProviderMetadata,\n ResponseType,\n resolveDiscoveryAsync,\n fetchDiscoveryAsync,\n generateHexStringAsync,\n};\n\nexport {\n // Token classes\n TokenResponse,\n AccessTokenRequest,\n RefreshTokenRequest,\n RevokeTokenRequest,\n // Token methods\n revokeAsync,\n refreshAsync,\n exchangeCodeAsync,\n fetchUserInfoAsync,\n} from './TokenRequest';\n\n// Token types\nexport * from './TokenRequest.types';\n"]}
package/build/Errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CodedError } from '@unimodules/core';
1
+ import { CodedError } from 'expo-modules-core';
2
2
  /**
3
3
  * Server response error.
4
4
  */
package/build/Errors.js CHANGED
@@ -1,4 +1,4 @@
1
- import { CodedError } from '@unimodules/core';
1
+ import { CodedError } from 'expo-modules-core';
2
2
  const errorCodeMessages = {
3
3
  // https://tools.ietf.org/html/rfc6749#section-4.1.2.1
4
4
  // https://openid.net/specs/openid-connect-core-1_0.html#AuthError
@@ -35,6 +35,21 @@ const errorCodeMessages = {
35
35
  * [Section 4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)
36
36
  */
37
37
  export class ResponseError extends CodedError {
38
+ /**
39
+ * Used to assist the client developer in
40
+ * understanding the error that occurred.
41
+ */
42
+ description;
43
+ /**
44
+ * A URI identifying a human-readable web page with
45
+ * information about the error, used to provide the client
46
+ * developer with additional information about the error.
47
+ */
48
+ uri;
49
+ /**
50
+ * Raw results of the error.
51
+ */
52
+ params;
38
53
  constructor(params, errorCodeType) {
39
54
  const { error, error_description, error_uri } = params;
40
55
  const message = errorCodeMessages[errorCodeType][error];
@@ -58,6 +73,10 @@ export class ResponseError extends CodedError {
58
73
  * [Section 5.2](https://tools.ietf.org/html/rfc6749#section-5.2)
59
74
  */
60
75
  export class AuthError extends ResponseError {
76
+ /**
77
+ * Required only if state is used in the initial request
78
+ */
79
+ state;
61
80
  constructor(response) {
62
81
  super(response, 'auth');
63
82
  this.state = response.state;
@@ -1 +1 @@
1
- {"version":3,"file":"Errors.js","sourceRoot":"","sources":["../src/Errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AA2B9C,MAAM,iBAAiB,GAAG;IACxB,sDAAsD;IACtD,kEAAkE;IAClE,IAAI,EAAE;QACJ,YAAY;QACZ,eAAe,EAAE,mJAAmJ;QACpK,mBAAmB,EAAE,kFAAkF;QACvG,aAAa,EAAE,gEAAgE;QAC/E,yBAAyB,EAAE,8FAA8F;QACzH,aAAa,EAAE,wDAAwD;QACvE,YAAY,EACV,qPAAq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AC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,SAAU,SAAQ,aAAa;IAM1C,YAAY,QAAyB;QACnC,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAC9B,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,UAAW,SAAQ,aAAa;IAC3C,YAAY,QAA6B;QACvC,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC3B,CAAC;CACF","sourcesContent":["import { CodedError } from '@unimodules/core';\n\n/**\n * Server response error.\n */\nexport interface ResponseErrorConfig extends Record<string, any> {\n /**\n * Error code\n */\n error: string;\n /**\n * Additional message\n */\n error_description?: string;\n /**\n * URI for more info on the error\n */\n error_uri?: string;\n}\n\nexport interface AuthErrorConfig extends ResponseErrorConfig {\n /**\n * Required only if state is used in the initial request\n */\n state?: string;\n}\n\nconst errorCodeMessages = {\n // https://tools.ietf.org/html/rfc6749#section-4.1.2.1\n // https://openid.net/specs/openid-connect-core-1_0.html#AuthError\n auth: {\n // OAuth 2.0\n invalid_request: `The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.`,\n unauthorized_client: `The client is not authorized to request an authorization code using this method.`,\n access_denied: `The resource owner or authorization server denied the request.`,\n unsupported_response_type: `The authorization server does not support obtaining an authorization code using this method.`,\n invalid_scope: 'The requested scope is invalid, unknown, or malformed.',\n server_error:\n 'The authorization server encountered an unexpected condition that prevented it from fulfilling the request. (This error code is needed because a 500 Internal Server Error HTTP status code cannot be returned to the client via an HTTP redirect.)',\n temporarily_unavailable:\n 'The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server. (This error code is needed because a 503 Service Unavailable HTTP status code cannot be returned to the client via an HTTP redirect.)',\n // Open ID Connect error codes\n interaction_required:\n 'Auth server requires user interaction of some form to proceed. This error may be returned when the prompt parameter value in the auth request is none, but the auth request cannot be completed without displaying a user interface for user interaction.',\n login_required:\n 'Auth server requires user authentication. This error may be returned when the prompt parameter value in the auth request is none, but the auth request cannot be completed without displaying a user interface for user authentication.',\n account_selection_required:\n 'User is required to select a session at the auth server. The user may be authenticated at the auth server with different associated accounts, but the user did not select a session. This error may be returned when the prompt parameter value in the auth request is `none`, but the auth request cannot be completed without displaying a user interface to prompt for a session to use.',\n consent_required:\n 'Auth server requires user consent. This error may be returned when the prompt parameter value in the auth request is none, but the auth request cannot be completed without displaying a user interface for user consent.',\n invalid_request_uri:\n 'The `request_uri` in the auth request returns an error or contains invalid data.',\n invalid_request_object: 'The request parameter contains an invalid request object.',\n request_not_supported:\n 'The OP does not support use of the `request` parameter defined in Section 6. (https://openid.net/specs/openid-connect-core-1_0.html#JWTRequests)',\n request_uri_not_supported:\n 'The OP does not support use of the `request_uri` parameter defined in Section 6. (https://openid.net/specs/openid-connect-core-1_0.html#JWTRequests)',\n registration_not_supported:\n 'The OP does not support use of the `registration` parameter defined in Section 7.2.1. (https://openid.net/specs/openid-connect-core-1_0.html#RegistrationParameter)',\n },\n // https://tools.ietf.org/html/rfc6749#section-5.2\n token: {\n invalid_request: `The request is missing a required parameter, includes an unsupported parameter value (other than grant type), repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed.`,\n invalid_client: `Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). The authorization server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported. If the client attempted to authenticate via the \"Authorization\" request header field, the authorization server MUST respond with an HTTP 401 (Unauthorized) status code and include the \"WWW-Authenticate\" response header field matching the authentication scheme used by the client.`,\n invalid_grant: `The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.`,\n unauthorized_client: `The authenticated client is not authorized to use this authorization grant type.`,\n unsupported_grant_type: `The authorization grant type is not supported by the authorization server.`,\n },\n};\n\n/**\n * [Section 4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)\n */\nexport class ResponseError extends CodedError {\n /**\n * Used to assist the client developer in\n * understanding the error that occurred.\n */\n description?: string;\n /**\n * A URI identifying a human-readable web page with\n * information about the error, used to provide the client\n * developer with additional information about the error.\n */\n uri?: string;\n /**\n * Raw results of the error.\n */\n params: Record<string, string>;\n\n constructor(params: ResponseErrorConfig, errorCodeType: string) {\n const { error, error_description, error_uri } = params;\n const message = errorCodeMessages[errorCodeType][error];\n let errorMessage: string;\n if (message) {\n errorMessage = message + (error_description ? `\\nMore info: ${error_description}` : '');\n } else if (error_description) {\n errorMessage = error_description;\n } else {\n errorMessage = 'An unknown error occurred';\n }\n super(error, errorMessage);\n this.description = error_description ?? message;\n this.uri = error_uri;\n this.params = params;\n }\n}\n\n/**\n * [Section 5.2](https://tools.ietf.org/html/rfc6749#section-5.2)\n */\nexport class AuthError extends ResponseError {\n /**\n * Required only if state is used in the initial request\n */\n state?: string;\n\n constructor(response: AuthErrorConfig) {\n super(response, 'auth');\n this.state = response.state;\n }\n}\n\n/**\n * [Section 4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)\n */\nexport class TokenError extends ResponseError {\n constructor(response: ResponseErrorConfig) {\n super(response, 'token');\n }\n}\n"]}
1
+ {"version":3,"file":"Errors.js","sourceRoot":"","sources":["../src/Errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AA2B/C,MAAM,iBAAiB,GAAG;IACxB,sDAAsD;IACtD,kEAAkE;IAClE,IAAI,EAAE;QACJ,YAAY;QACZ,eAAe,EAAE,mJAAmJ;QACpK,mBAAmB,EAAE,kFAAkF;QACvG,aAAa,EAAE,gEAAgE;QAC/E,yBAAyB,EAAE,8FAA8F;QACzH,aAAa,EAAE,wDAAwD;QACvE,YAAY,EACV,qPAAqP;QACvP,uBAAuB,EACrB,wQAAwQ;QAC1Q,8BAA8B;QAC9B,oBAAoB,EAClB,2PAA2P;QAC7P,cAAc,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AAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,SAAU,SAAQ,aAAa;IAC1C;;OAEG;IACH,KAAK,CAAU;IAEf,YAAY,QAAyB;QACnC,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAC9B,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,UAAW,SAAQ,aAAa;IAC3C,YAAY,QAA6B;QACvC,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC3B,CAAC;CACF","sourcesContent":["import { CodedError } from 'expo-modules-core';\n\n/**\n * Server response error.\n */\nexport interface ResponseErrorConfig extends Record<string, any> {\n /**\n * Error code\n */\n error: string;\n /**\n * Additional message\n */\n error_description?: string;\n /**\n * URI for more info on the error\n */\n error_uri?: string;\n}\n\nexport interface AuthErrorConfig extends ResponseErrorConfig {\n /**\n * Required only if state is used in the initial request\n */\n state?: string;\n}\n\nconst errorCodeMessages = {\n // https://tools.ietf.org/html/rfc6749#section-4.1.2.1\n // https://openid.net/specs/openid-connect-core-1_0.html#AuthError\n auth: {\n // OAuth 2.0\n invalid_request: `The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.`,\n unauthorized_client: `The client is not authorized to request an authorization code using this method.`,\n access_denied: `The resource owner or authorization server denied the request.`,\n unsupported_response_type: `The authorization server does not support obtaining an authorization code using this method.`,\n invalid_scope: 'The requested scope is invalid, unknown, or malformed.',\n server_error:\n 'The authorization server encountered an unexpected condition that prevented it from fulfilling the request. (This error code is needed because a 500 Internal Server Error HTTP status code cannot be returned to the client via an HTTP redirect.)',\n temporarily_unavailable:\n 'The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server. (This error code is needed because a 503 Service Unavailable HTTP status code cannot be returned to the client via an HTTP redirect.)',\n // Open ID Connect error codes\n interaction_required:\n 'Auth server requires user interaction of some form to proceed. This error may be returned when the prompt parameter value in the auth request is none, but the auth request cannot be completed without displaying a user interface for user interaction.',\n login_required:\n 'Auth server requires user authentication. This error may be returned when the prompt parameter value in the auth request is none, but the auth request cannot be completed without displaying a user interface for user authentication.',\n account_selection_required:\n 'User is required to select a session at the auth server. The user may be authenticated at the auth server with different associated accounts, but the user did not select a session. This error may be returned when the prompt parameter value in the auth request is `none`, but the auth request cannot be completed without displaying a user interface to prompt for a session to use.',\n consent_required:\n 'Auth server requires user consent. This error may be returned when the prompt parameter value in the auth request is none, but the auth request cannot be completed without displaying a user interface for user consent.',\n invalid_request_uri:\n 'The `request_uri` in the auth request returns an error or contains invalid data.',\n invalid_request_object: 'The request parameter contains an invalid request object.',\n request_not_supported:\n 'The OP does not support use of the `request` parameter defined in Section 6. (https://openid.net/specs/openid-connect-core-1_0.html#JWTRequests)',\n request_uri_not_supported:\n 'The OP does not support use of the `request_uri` parameter defined in Section 6. (https://openid.net/specs/openid-connect-core-1_0.html#JWTRequests)',\n registration_not_supported:\n 'The OP does not support use of the `registration` parameter defined in Section 7.2.1. (https://openid.net/specs/openid-connect-core-1_0.html#RegistrationParameter)',\n },\n // https://tools.ietf.org/html/rfc6749#section-5.2\n token: {\n invalid_request: `The request is missing a required parameter, includes an unsupported parameter value (other than grant type), repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed.`,\n invalid_client: `Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). The authorization server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported. If the client attempted to authenticate via the \"Authorization\" request header field, the authorization server MUST respond with an HTTP 401 (Unauthorized) status code and include the \"WWW-Authenticate\" response header field matching the authentication scheme used by the client.`,\n invalid_grant: `The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.`,\n unauthorized_client: `The authenticated client is not authorized to use this authorization grant type.`,\n unsupported_grant_type: `The authorization grant type is not supported by the authorization server.`,\n },\n};\n\n/**\n * [Section 4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)\n */\nexport class ResponseError extends CodedError {\n /**\n * Used to assist the client developer in\n * understanding the error that occurred.\n */\n description?: string;\n /**\n * A URI identifying a human-readable web page with\n * information about the error, used to provide the client\n * developer with additional information about the error.\n */\n uri?: string;\n /**\n * Raw results of the error.\n */\n params: Record<string, string>;\n\n constructor(params: ResponseErrorConfig, errorCodeType: string) {\n const { error, error_description, error_uri } = params;\n const message = errorCodeMessages[errorCodeType][error];\n let errorMessage: string;\n if (message) {\n errorMessage = message + (error_description ? `\\nMore info: ${error_description}` : '');\n } else if (error_description) {\n errorMessage = error_description;\n } else {\n errorMessage = 'An unknown error occurred';\n }\n super(error, errorMessage);\n this.description = error_description ?? message;\n this.uri = error_uri;\n this.params = params;\n }\n}\n\n/**\n * [Section 5.2](https://tools.ietf.org/html/rfc6749#section-5.2)\n */\nexport class AuthError extends ResponseError {\n /**\n * Required only if state is used in the initial request\n */\n state?: string;\n\n constructor(response: AuthErrorConfig) {\n super(response, 'auth');\n this.state = response.state;\n }\n}\n\n/**\n * [Section 4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)\n */\nexport class TokenError extends ResponseError {\n constructor(response: ResponseErrorConfig) {\n super(response, 'token');\n }\n}\n"]}
package/build/Fetch.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Platform } from '@unimodules/core';
1
+ import { Platform } from 'expo-modules-core';
2
2
  import qs from 'qs';
3
3
  // TODO(Bacon): pending react-native-adapter publish after sdk 38
4
4
  const isDOMAvailable = Platform.OS === 'web' &&
@@ -1 +1 @@
1
- {"version":3,"file":"Fetch.js","sourceRoot":"","sources":["../src/Fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,CAAC;AAepB,iEAAiE;AACjE,MAAM,cAAc,GAClB,QAAQ,CAAC,EAAE,KAAK,KAAK;IACrB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,CAAC,CAAC,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;QACpD,kFAAkF;QAClF,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,2CAA2C,CAAC;KACzE;IAED,8EAA8E;IAC9E,MAAM,YAAY,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAEvD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IAEpD,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IACzD,IAAI,cAAc,IAAI,WAAW,EAAE,QAAQ,CAAC,kBAAkB,CAAC,EAAE;QAC/D,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;KACxB;IACD,2DAA2D;IAC3D,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import { Platform } from '@unimodules/core';\nimport qs from 'qs';\n\nexport type Headers = Record<string, string> & {\n 'Content-Type': string;\n Authorization?: string;\n Accept?: string;\n};\n\nexport type FetchRequest = {\n headers?: Headers;\n body?: Record<string, string>;\n dataType?: string;\n method?: string;\n};\n\n// TODO(Bacon): pending react-native-adapter publish after sdk 38\nconst isDOMAvailable =\n Platform.OS === 'web' &&\n typeof window !== 'undefined' &&\n !!window.document?.createElement &&\n // eslint-disable-next-line no-undef\n typeof URL !== 'undefined';\n\nexport async function requestAsync<T>(requestUrl: string, fetchRequest: FetchRequest): Promise<T> {\n if (Platform.OS === 'web' && !isDOMAvailable) {\n // @ts-ignore\n return;\n }\n // eslint-disable-next-line no-undef\n const url = new URL(requestUrl);\n\n const request: Omit<RequestInit, 'headers'> & { headers: HeadersInit } = {\n method: fetchRequest.method,\n mode: 'cors',\n headers: {},\n };\n\n const isJsonDataType = fetchRequest.dataType?.toLowerCase() === 'json';\n\n if (fetchRequest.headers) {\n for (const i in fetchRequest.headers) {\n if (i in fetchRequest.headers) {\n request.headers[i] = fetchRequest.headers[i] as string;\n }\n }\n }\n\n if (fetchRequest.body) {\n if (fetchRequest.method?.toUpperCase() === 'POST') {\n request.body = qs.stringify(fetchRequest.body);\n } else {\n for (const key of Object.keys(fetchRequest.body)) {\n url.searchParams.append(key, fetchRequest.body[key]);\n }\n }\n }\n\n if (isJsonDataType && !('Accept' in request.headers)) {\n // NOTE: Github authentication will return XML if this includes the standard `*/*`\n request.headers['Accept'] = 'application/json, text/javascript; q=0.01';\n }\n\n // Fix a problem with React Native `URL` causing a trailing slash to be added.\n const correctedUrl = url.toString().replace(/\\/$/, '');\n\n const response = await fetch(correctedUrl, request);\n\n const contentType = response.headers.get('content-type');\n if (isJsonDataType || contentType?.includes('application/json')) {\n return response.json();\n }\n // @ts-ignore: Type 'string' is not assignable to type 'T'.\n return response.text();\n}\n"]}
1
+ {"version":3,"file":"Fetch.js","sourceRoot":"","sources":["../src/Fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,MAAM,IAAI,CAAC;AAepB,iEAAiE;AACjE,MAAM,cAAc,GAClB,QAAQ,CAAC,EAAE,KAAK,KAAK;IACrB,OAAO,MAAM,KAAK,WAAW;IAC7B,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE,aAAa;IAChC,oCAAoC;IACpC,OAAO,GAAG,KAAK,WAAW,CAAC;AAE7B,MAAM,CAAC,KAAK,UAAU,YAAY,CAAI,UAAkB,EAAE,YAA0B;IAClF,IAAI,QAAQ,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC,cAAc,EAAE;QAC5C,aAAa;QACb,OAAO;KACR;IACD,oCAAoC;IACpC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;IAEhC,MAAM,OAAO,GAA4D;QACvE,MAAM,EAAE,YAAY,CAAC,MAAM;QAC3B,IAAI,EAAE,MAAM;QACZ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CAAC,kBAAkB,CAAC,EAAE;QAC/D,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;KACxB;IACD,2DAA2D;IAC3D,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import { Platform } from 'expo-modules-core';\nimport qs from 'qs';\n\nexport type Headers = Record<string, string> & {\n 'Content-Type': string;\n Authorization?: string;\n Accept?: string;\n};\n\nexport type FetchRequest = {\n headers?: Headers;\n body?: Record<string, string>;\n dataType?: string;\n method?: string;\n};\n\n// TODO(Bacon): pending react-native-adapter publish after sdk 38\nconst isDOMAvailable =\n Platform.OS === 'web' &&\n typeof window !== 'undefined' &&\n !!window.document?.createElement &&\n // eslint-disable-next-line no-undef\n typeof URL !== 'undefined';\n\nexport async function requestAsync<T>(requestUrl: string, fetchRequest: FetchRequest): Promise<T> {\n if (Platform.OS === 'web' && !isDOMAvailable) {\n // @ts-ignore\n return;\n }\n // eslint-disable-next-line no-undef\n const url = new URL(requestUrl);\n\n const request: Omit<RequestInit, 'headers'> & { headers: HeadersInit } = {\n method: fetchRequest.method,\n mode: 'cors',\n headers: {},\n };\n\n const isJsonDataType = fetchRequest.dataType?.toLowerCase() === 'json';\n\n if (fetchRequest.headers) {\n for (const i in fetchRequest.headers) {\n if (i in fetchRequest.headers) {\n request.headers[i] = fetchRequest.headers[i] as string;\n }\n }\n }\n\n if (fetchRequest.body) {\n if (fetchRequest.method?.toUpperCase() === 'POST') {\n request.body = qs.stringify(fetchRequest.body);\n } else {\n for (const key of Object.keys(fetchRequest.body)) {\n url.searchParams.append(key, fetchRequest.body[key]);\n }\n }\n }\n\n if (isJsonDataType && !('Accept' in request.headers)) {\n // NOTE: Github authentication will return XML if this includes the standard `*/*`\n request.headers['Accept'] = 'application/json, text/javascript; q=0.01';\n }\n\n // Fix a problem with React Native `URL` causing a trailing slash to be added.\n const correctedUrl = url.toString().replace(/\\/$/, '');\n\n const response = await fetch(correctedUrl, request);\n\n const contentType = response.headers.get('content-type');\n if (isJsonDataType || contentType?.includes('application/json')) {\n return response.json();\n }\n // @ts-ignore: Type 'string' is not assignable to type 'T'.\n return response.text();\n}\n"]}
package/build/PKCE.js CHANGED
@@ -21,10 +21,7 @@ function convertBufferToString(buffer) {
21
21
  return state.join('');
22
22
  }
23
23
  function convertToUrlSafeString(b64) {
24
- return b64
25
- .replace(/\+/g, '-')
26
- .replace(/\//g, '_')
27
- .replace(/=/g, '');
24
+ return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
28
25
  }
29
26
  export function generateRandom(size) {
30
27
  const buffer = new Uint8Array(size);
package/build/PKCE.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"PKCE.js","sourceRoot":"","sources":["../src/PKCE.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,MAAM,OAAO,GAAG,gEAAgE,CAAC;AAEjF,SAAS,eAAe,CAAC,KAAiB;IACxC,MAAM,MAAM,GAAG,KAAK,CAAC;IACrB,yCAAyC;IACzC,IAAI,KAAK,CAAC,UAAU,KAAK,KAAK,CAAC,MAAM;QAAE,KAAK,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAE5E,MAAM,KAAK,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAElD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAE3D,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,qBAAqB,CAAC,MAAkB;IAC/C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC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,CAAC,YAAY,CAAC,CAAC;IAE/D,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC;AACzC,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,IAAY;IACvD,MAAM,KAAK,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC;IACnC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC,qBAAqB,CAAC,MAAM,EAAE,KAAK,EAAE;QACxF,QAAQ,EAAE,MAAM,CAAC,cAAc,CAAC,GAAG;KACpC,CAAC,CAAC;IACH,OAAO,sBAAsB,CAAC,MAAM,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import * as Crypto from 'expo-crypto';\nimport * as Random from 'expo-random';\nimport invariant from 'invariant';\n\nconst CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\nfunction getRandomValues(input: Uint8Array): Uint8Array {\n const output = input;\n // Get access to the underlying raw bytes\n if (input.byteLength !== input.length) input = new Uint8Array(input.buffer);\n\n const bytes = Random.getRandomBytes(input.length);\n\n for (let i = 0; i < bytes.length; i++) input[i] = bytes[i];\n\n return output;\n}\n\nfunction convertBufferToString(buffer: Uint8Array): string {\n const state: string[] = [];\n for (let i = 0; i < buffer.byteLength; i += 1) {\n const index = buffer[i] % CHARSET.length;\n state.push(CHARSET[index]);\n }\n return state.join('');\n}\n\nfunction convertToUrlSafeString(b64: string): string {\n return b64\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '');\n}\n\nexport function generateRandom(size: number): string {\n const buffer = new Uint8Array(size);\n getRandomValues(buffer);\n return convertBufferToString(buffer);\n}\n\n/**\n * Proof key for Code Exchange by OAuth Public Clients (RFC 7636), Section 4.1\n * [Section 4.1](https://tools.ietf.org/html/rfc7636#section-4.1)\n */\nexport async function deriveChallengeAsync(code: string): Promise<string> {\n // 43 is the minimum, and 128 is the maximum.\n invariant(code.length > 42 && code.length < 129, 'Invalid code length for PKCE.');\n\n const buffer = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, code, {\n encoding: Crypto.CryptoEncoding.BASE64,\n });\n return convertToUrlSafeString(buffer);\n}\n\nexport async function buildCodeAsync(\n size: number = 128\n): Promise<{ codeChallenge: string; codeVerifier: string }> {\n // This method needs to be resolved like all other native methods.\n const codeVerifier = generateRandom(size);\n const codeChallenge = await deriveChallengeAsync(codeVerifier);\n\n return { codeVerifier, codeChallenge };\n}\n\n/**\n * Digest a random string with hex encoding, useful for creating `nonce`s.\n */\nexport async function generateHexStringAsync(size: number): Promise<string> {\n const value = generateRandom(size);\n const buffer = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, value, {\n encoding: Crypto.CryptoEncoding.HEX,\n });\n return convertToUrlSafeString(buffer);\n}\n"]}
1
+ {"version":3,"file":"PKCE.js","sourceRoot":"","sources":["../src/PKCE.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,MAAM,OAAO,GAAG,gEAAgE,CAAC;AAEjF,SAAS,eAAe,CAAC,KAAiB;IACxC,MAAM,MAAM,GAAG,KAAK,CAAC;IACrB,yCAAyC;IACzC,IAAI,KAAK,CAAC,UAAU,KAAK,KAAK,CAAC,MAAM;QAAE,KAAK,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAE5E,MAAM,KAAK,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAElD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAE3D,OAAO,MAA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K,UAAU,cAAc,CAClC,OAAe,GAAG;IAElB,kEAAkE;IAClE,MAAM,YAAY,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC;IAC1C,MAAM,aAAa,GAAG,MAAM,oBAAoB,CAAC,YAAY,CAAC,CAAC;IAE/D,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC;AACzC,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,IAAY;IACvD,MAAM,KAAK,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC;IACnC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC,qBAAqB,CAAC,MAAM,EAAE,KAAK,EAAE;QACxF,QAAQ,EAAE,MAAM,CAAC,cAAc,CAAC,GAAG;KACpC,CAAC,CAAC;IACH,OAAO,sBAAsB,CAAC,MAAM,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import * as Crypto from 'expo-crypto';\nimport * as Random from 'expo-random';\nimport invariant from 'invariant';\n\nconst CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\nfunction getRandomValues(input: Uint8Array): Uint8Array {\n const output = input;\n // Get access to the underlying raw bytes\n if (input.byteLength !== input.length) input = new Uint8Array(input.buffer);\n\n const bytes = Random.getRandomBytes(input.length);\n\n for (let i = 0; i < bytes.length; i++) input[i] = bytes[i];\n\n return output;\n}\n\nfunction convertBufferToString(buffer: Uint8Array): string {\n const state: string[] = [];\n for (let i = 0; i < buffer.byteLength; i += 1) {\n const index = buffer[i] % CHARSET.length;\n state.push(CHARSET[index]);\n }\n return state.join('');\n}\n\nfunction convertToUrlSafeString(b64: string): string {\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\nexport function generateRandom(size: number): string {\n const buffer = new Uint8Array(size);\n getRandomValues(buffer);\n return convertBufferToString(buffer);\n}\n\n/**\n * Proof key for Code Exchange by OAuth Public Clients (RFC 7636), Section 4.1\n * [Section 4.1](https://tools.ietf.org/html/rfc7636#section-4.1)\n */\nexport async function deriveChallengeAsync(code: string): Promise<string> {\n // 43 is the minimum, and 128 is the maximum.\n invariant(code.length > 42 && code.length < 129, 'Invalid code length for PKCE.');\n\n const buffer = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, code, {\n encoding: Crypto.CryptoEncoding.BASE64,\n });\n return convertToUrlSafeString(buffer);\n}\n\nexport async function buildCodeAsync(\n size: number = 128\n): Promise<{ codeChallenge: string; codeVerifier: string }> {\n // This method needs to be resolved like all other native methods.\n const codeVerifier = generateRandom(size);\n const codeChallenge = await deriveChallengeAsync(codeVerifier);\n\n return { codeVerifier, codeChallenge };\n}\n\n/**\n * Digest a random string with hex encoding, useful for creating `nonce`s.\n */\nexport async function generateHexStringAsync(size: number): Promise<string> {\n const value = generateRandom(size);\n const buffer = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, value, {\n encoding: Crypto.CryptoEncoding.HEX,\n });\n return convertToUrlSafeString(buffer);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"QueryParams.js","sourceRoot":"","sources":["../src/QueryParams.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,MAAM,UAAU,gBAAgB,CAAC,KAA6B;IAC5D,OAAO,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,UAAU,cAAc,CAC5B,GAAW;IAEX,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IACtB,MAAM,gBAAgB,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7C,MAAM,WAAW,GAAG,gBAAgB,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAElE,kCAAkC;IAClC,MAAM,YAAY,GAAG,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,CAAC;IAEnE,+BAA+B;IAC/B,MAAM,SAAS,GAAG,CAAC,YAAY,CAAC,SAAS,IAAI,IAAI,CAAkB,CAAC;IACpE,SAAS,CACP,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,IAAI,EACnD,yDAAyD,CAC1D,CAAC;IACF,OAAO,YAAY,CAAC,SAAS,CAAC;IAE9B,0BAA0B;IAC1B,IAAI,UAAU,GAAG,EAAE,CAAC;IACpB,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE;QACZ,UAAU,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;KAC7B;IAED,wBAAwB;IACxB,MAAM,MAAM,GAAG;QACb,GAAG,YAAY;QACf,GAAG,UAAU;KACd,CAAC;IAEF,OAAO;QACL,SAAS;QACT,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["import invariant from 'invariant';\nimport qs from 'qs';\n\nexport function buildQueryString(input: Record<string, string>): string {\n return qs.stringify(input);\n}\n\nexport function getQueryParams(\n url: string\n): { errorCode: string | null; params: { [key: string]: string } } {\n const parts = url.split('#');\n const hash = parts[1];\n const partsWithoutHash = parts[0].split('?');\n const queryString = partsWithoutHash[partsWithoutHash.length - 1];\n\n // Get query string (?hello=world)\n const parsedSearch = qs.parse(queryString, { parseArrays: false });\n\n // Pull errorCode off of params\n const errorCode = (parsedSearch.errorCode ?? null) as string | null;\n invariant(\n typeof errorCode === 'string' || errorCode === null,\n `The \"errorCode\" parameter must be a string if specified`\n );\n delete parsedSearch.errorCode;\n\n // Get hash (#abc=example)\n let parsedHash = {};\n if (parts[1]) {\n parsedHash = qs.parse(hash);\n }\n\n // Merge search and hash\n const params = {\n ...parsedSearch,\n ...parsedHash,\n };\n\n return {\n error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,CAAC","sourcesContent":["import invariant from 'invariant';\nimport qs from 'qs';\n\nexport function buildQueryString(input: Record<string, string>): string {\n return qs.stringify(input);\n}\n\nexport function getQueryParams(url: string): {\n errorCode: string | null;\n params: { [key: string]: string };\n} {\n const parts = url.split('#');\n const hash = parts[1];\n const partsWithoutHash = parts[0].split('?');\n const queryString = partsWithoutHash[partsWithoutHash.length - 1];\n\n // Get query string (?hello=world)\n const parsedSearch = qs.parse(queryString, { parseArrays: false });\n\n // Pull errorCode off of params\n const errorCode = (parsedSearch.errorCode ?? null) as string | null;\n invariant(\n typeof errorCode === 'string' || errorCode === null,\n `The \"errorCode\" parameter must be a string if specified`\n );\n delete parsedSearch.errorCode;\n\n // Get hash (#abc=example)\n let parsedHash = {};\n if (parts[1]) {\n parsedHash = qs.parse(hash);\n }\n\n // Merge search and hash\n const params = {\n ...parsedSearch,\n ...parsedHash,\n };\n\n return {\n errorCode,\n params,\n };\n}\n"]}
@@ -3,8 +3,9 @@ import Constants, { ExecutionEnvironment } from 'expo-constants';
3
3
  import * as Linking from 'expo-linking';
4
4
  import { resolveScheme } from 'expo-linking/build/Schemes';
5
5
  import qs from 'qs';
6
- const { manifest } = Constants;
7
6
  export class SessionUrlProvider {
7
+ static BASE_URL = `https://auth.expo.io`;
8
+ static SESSION_PATH = 'expo-auth-session';
8
9
  getDefaultReturnUrl(urlPath, options) {
9
10
  const queryParams = SessionUrlProvider.getHostAddressQueryParams();
10
11
  let path = SessionUrlProvider.SESSION_PATH;
@@ -39,7 +40,9 @@ export class SessionUrlProvider {
39
40
  return '';
40
41
  }
41
42
  }
42
- const legacyExpoProjectId = manifest?.originalFullName || manifest?.id;
43
+ const legacyExpoProjectId = Constants.manifest?.originalFullName ||
44
+ Constants.manifest2?.extra?.expoClient?.originalFullName ||
45
+ Constants.manifest?.id;
43
46
  if (!legacyExpoProjectId) {
44
47
  let nextSteps = '';
45
48
  if (__DEV__) {
@@ -62,7 +65,7 @@ export class SessionUrlProvider {
62
65
  return redirectUrl;
63
66
  }
64
67
  static getHostAddressQueryParams() {
65
- let hostUri = Constants.manifest?.hostUri;
68
+ let hostUri = Constants.manifest?.hostUri ?? Constants.manifest2?.extra?.expoClient?.hostUri;
66
69
  if (!hostUri &&
67
70
  (ExecutionEnvironment.StoreClient === Constants.executionEnvironment || resolveScheme({}))) {
68
71
  if (!Constants.linkingUri) {
@@ -74,6 +77,9 @@ export class SessionUrlProvider {
74
77
  hostUri = SessionUrlProvider.removeScheme(Constants.linkingUri).replace(/\/--(\/.*)?$/, '');
75
78
  }
76
79
  }
80
+ if (!hostUri) {
81
+ return undefined;
82
+ }
77
83
  const uriParts = hostUri?.split('?');
78
84
  try {
79
85
  return qs.parse(uriParts?.[1]);
@@ -93,7 +99,5 @@ export class SessionUrlProvider {
93
99
  return url.replace(/^\//, '');
94
100
  }
95
101
  }
96
- SessionUrlProvider.BASE_URL = `https://auth.expo.io`;
97
- SessionUrlProvider.SESSION_PATH = 'expo-auth-session';
98
102
  export default new SessionUrlProvider();
99
103
  //# sourceMappingURL=SessionUrlProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"SessionUrlProvider.js","sourceRoot":"","sources":["../src/SessionUrlProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAC5D,OAAO,SAAS,EAAE,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAgB,MAAM,IAAI,CAAC;AAElC,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAC;AAE/B,MAAM,OAAO,kBAAkB;IAI7B,mBAAmB,CAAC,OAAgB,EAAE,OAA+C;QACnF,MAAM,WAAW,GAAG,kBAAkB,CAAC,yBAAyB,EAAE,CAAC;QACnE,IAAI,IAAI,GAAG,kBAAkB,CAAC,YAAY,CAA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,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE;YAChC,OAAO,CAAC,IAAI,CACV,+HAA+H,GAAG,6TAA6T,CAChc,CAAC;SACH;IACH,CAAC;IAEO,MAAM,CAAC,YAAY,CAAC,GAAW;QACrC,OAAO,GAAG,CAAC,OAAO,CAAC,uBAAuB,EAAE,EAAE,CAAC,CAAC;IAClD,CAAC;IAEO,MAAM,CAAC,kBAAkB,CAAC,GAAW;QAC3C,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAChC,CAAC;;AAxGuB,2BAAQ,GAAG,sBAAsB,CAAC;AAClC,+BAAY,GAAG,mBAAmB,CAAC;AA0G7D,eAAe,IAAI,kBAAkB,EAAE,CAAC","sourcesContent":["import { Platform } from '@unimodules/react-native-adapter';\nimport Constants, { ExecutionEnvironment } from 'expo-constants';\nimport * as Linking from 'expo-linking';\nimport { CreateURLOptions } from 'expo-linking';\nimport { resolveScheme } from 'expo-linking/build/Schemes';\nimport qs, { ParsedQs } from 'qs';\n\nconst { manifest } = Constants;\n\nexport class SessionUrlProvider {\n private static readonly BASE_URL = `https://auth.expo.io`;\n private static readonly SESSION_PATH = 'expo-auth-session';\n\n getDefaultReturnUrl(urlPath?: string, options?: Omit<CreateURLOptions, 'queryParams'>): string {\n const queryParams = SessionUrlProvider.getHostAddressQueryParams();\n let path = SessionUrlProvider.SESSION_PATH;\n if (urlPath) {\n path = [path, SessionUrlProvider.removeLeadingSlash(urlPath)].filter(Boolean).join('/');\n }\n\n return Linking.createURL(path, {\n // The redirect URL doesn't matter for the proxy as long as it's valid, so silence warnings if needed.\n scheme: options?.scheme ?? resolveScheme({ isSilent: true }),\n queryParams,\n isTripleSlashed: options?.isTripleSlashed,\n });\n }\n\n getStartUrl(authUrl: string, returnUrl: string): string {\n if (Platform.OS === 'web' && !Platform.isDOMAvailable) {\n // Return nothing in SSR envs\n return '';\n }\n const queryString = qs.stringify({\n authUrl,\n returnUrl,\n });\n\n return `${this.getRedirectUrl()}/start?${queryString}`;\n }\n\n getRedirectUrl(urlPath?: string): string {\n if (Platform.OS === 'web') {\n if (Platform.isDOMAvailable) {\n return [window.location.origin, urlPath].filter(Boolean).join('/');\n } else {\n // Return nothing in SSR envs\n return '';\n }\n }\n\n const legacyExpoProjectId = manifest?.originalFullName || manifest?.id;\n\n if (!legacyExpoProjectId) {\n let nextSteps = '';\n if (__DEV__) {\n if (Constants.executionEnvironment === ExecutionEnvironment.Bare) {\n nextSteps =\n ' Please ensure you have the latest version of expo-constants installed and rebuild your native app. You can verify that originalFullName is defined by running `expo config --type public` and inspecting the output.';\n } else if (Constants.executionEnvironment === ExecutionEnvironment.StoreClient) {\n nextSteps =\n ' Please report this as a bug with the contents of `expo config --type public`.';\n }\n }\n throw new Error(\n 'Cannot use AuthSession proxy because the project ID is not defined.' + nextSteps\n );\n }\n\n const redirectUrl = `${SessionUrlProvider.BASE_URL}/${legacyExpoProjectId}`;\n if (__DEV__) {\n SessionUrlProvider.warnIfAnonymous(legacyExpoProjectId, redirectUrl);\n // TODO: Verify with the dev server that the manifest is up to date.\n }\n return redirectUrl;\n }\n\n private static getHostAddressQueryParams(): ParsedQs | undefined {\n let hostUri: string = Constants.manifest?.hostUri;\n if (\n !hostUri &&\n (ExecutionEnvironment.StoreClient === Constants.executionEnvironment || resolveScheme({}))\n ) {\n if (!Constants.linkingUri) {\n hostUri = '';\n } else {\n // we're probably not using up-to-date xdl, so just fake it for now\n // we have to remove the /--/ on the end since this will be inserted again later\n hostUri = SessionUrlProvider.removeScheme(Constants.linkingUri).replace(/\\/--(\\/.*)?$/, '');\n }\n }\n\n const uriParts = hostUri?.split('?');\n try {\n return qs.parse(uriParts?.[1]);\n } catch {}\n\n return undefined;\n }\n\n private static warnIfAnonymous(id, url): void {\n if (id.startsWith('@anonymous/')) {\n console.warn(\n `You are not currently signed in to Expo on your development machine. As a result, the redirect URL for AuthSession will be \"${url}\". If you are using an OAuth provider that requires adding redirect URLs to an allow list, we recommend that you do not add this URL -- instead, you should sign in to Expo to acquire a unique redirect URL. Additionally, if you do decide to publish this app using Expo, you will need to register an account to do it.`\n );\n }\n }\n\n private static removeScheme(url: string) {\n return url.replace(/^[a-zA-Z0-9+.-]+:\\/\\//, '');\n }\n\n private static removeLeadingSlash(url: string) {\n return url.replace(/^\\//, '');\n }\n}\n\nexport default new SessionUrlProvider();\n"]}
1
+ {"version":3,"file":"SessionUrlProvider.js","sourceRoot":"","sources":["../src/SessionUrlProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAC5D,OAAO,SAAS,EAAE,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAgB,MAAM,IAAI,CAAC;AAElC,MAAM,OAAO,kBAAkB;IACrB,MAAM,CAAU,QAAQ,GAAG,sBAAsB,CAAC;IAClD,MAAM,CAAU,YAAY,GAAG,mBAAmB,CAAC;IAE3D,mBAAmB,CAAC,OAAgB,EAAE,OAA+C;QACnF,MAAM,WAAW,GAAG,kBAAkB,CAAC,yBAAyB,EAAE,CAAC;QACnE,IAAI,IAAI,GAAG,kBAAkB,CAAC,YAAY,CAAC;QAC3C,IAAI,OAAO,EAAE;YACX,IAAI,GAAG,CAAC,IAAI,EAAE,kBAAkB,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACzF;QAED,OAAO,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE;YAC7B,sGAAsG;YACtG,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,aAAa,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;YAC5D,WAAW;YACX,eAAe,EAAE,OAAO,EAAE,eAAe;SAC1C,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O,CAAC,uBAAuB,EAAE,EAAE,CAAC,CAAC;IAClD,CAAC;IAEO,MAAM,CAAC,kBAAkB,CAAC,GAAW;QAC3C,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAChC,CAAC;;AAGH,eAAe,IAAI,kBAAkB,EAAE,CAAC","sourcesContent":["import { Platform } from '@unimodules/react-native-adapter';\nimport Constants, { ExecutionEnvironment } from 'expo-constants';\nimport * as Linking from 'expo-linking';\nimport { CreateURLOptions } from 'expo-linking';\nimport { resolveScheme } from 'expo-linking/build/Schemes';\nimport qs, { ParsedQs } from 'qs';\n\nexport class SessionUrlProvider {\n private static readonly BASE_URL = `https://auth.expo.io`;\n private static readonly SESSION_PATH = 'expo-auth-session';\n\n getDefaultReturnUrl(urlPath?: string, options?: Omit<CreateURLOptions, 'queryParams'>): string {\n const queryParams = SessionUrlProvider.getHostAddressQueryParams();\n let path = SessionUrlProvider.SESSION_PATH;\n if (urlPath) {\n path = [path, SessionUrlProvider.removeLeadingSlash(urlPath)].filter(Boolean).join('/');\n }\n\n return Linking.createURL(path, {\n // The redirect URL doesn't matter for the proxy as long as it's valid, so silence warnings if needed.\n scheme: options?.scheme ?? resolveScheme({ isSilent: true }),\n queryParams,\n isTripleSlashed: options?.isTripleSlashed,\n });\n }\n\n getStartUrl(authUrl: string, returnUrl: string): string {\n if (Platform.OS === 'web' && !Platform.isDOMAvailable) {\n // Return nothing in SSR envs\n return '';\n }\n const queryString = qs.stringify({\n authUrl,\n returnUrl,\n });\n\n return `${this.getRedirectUrl()}/start?${queryString}`;\n }\n\n getRedirectUrl(urlPath?: string): string {\n if (Platform.OS === 'web') {\n if (Platform.isDOMAvailable) {\n return [window.location.origin, urlPath].filter(Boolean).join('/');\n } else {\n // Return nothing in SSR envs\n return '';\n }\n }\n\n const legacyExpoProjectId =\n Constants.manifest?.originalFullName ||\n Constants.manifest2?.extra?.expoClient?.originalFullName ||\n Constants.manifest?.id;\n\n if (!legacyExpoProjectId) {\n let nextSteps = '';\n if (__DEV__) {\n if (Constants.executionEnvironment === ExecutionEnvironment.Bare) {\n nextSteps =\n ' Please ensure you have the latest version of expo-constants installed and rebuild your native app. You can verify that originalFullName is defined by running `expo config --type public` and inspecting the output.';\n } else if (Constants.executionEnvironment === ExecutionEnvironment.StoreClient) {\n nextSteps =\n ' Please report this as a bug with the contents of `expo config --type public`.';\n }\n }\n throw new Error(\n 'Cannot use AuthSession proxy because the project ID is not defined.' + nextSteps\n );\n }\n\n const redirectUrl = `${SessionUrlProvider.BASE_URL}/${legacyExpoProjectId}`;\n if (__DEV__) {\n SessionUrlProvider.warnIfAnonymous(legacyExpoProjectId, redirectUrl);\n // TODO: Verify with the dev server that the manifest is up to date.\n }\n return redirectUrl;\n }\n\n private static getHostAddressQueryParams(): ParsedQs | undefined {\n let hostUri: string | undefined =\n Constants.manifest?.hostUri ?? Constants.manifest2?.extra?.expoClient?.hostUri;\n if (\n !hostUri &&\n (ExecutionEnvironment.StoreClient === Constants.executionEnvironment || resolveScheme({}))\n ) {\n if (!Constants.linkingUri) {\n hostUri = '';\n } else {\n // we're probably not using up-to-date xdl, so just fake it for now\n // we have to remove the /--/ on the end since this will be inserted again later\n hostUri = SessionUrlProvider.removeScheme(Constants.linkingUri).replace(/\\/--(\\/.*)?$/, '');\n }\n }\n\n if (!hostUri) {\n return undefined;\n }\n\n const uriParts = hostUri?.split('?');\n try {\n return qs.parse(uriParts?.[1]);\n } catch {}\n\n return undefined;\n }\n\n private static warnIfAnonymous(id, url): void {\n if (id.startsWith('@anonymous/')) {\n console.warn(\n `You are not currently signed in to Expo on your development machine. As a result, the redirect URL for AuthSession will be \"${url}\". If you are using an OAuth provider that requires adding redirect URLs to an allow list, we recommend that you do not add this URL -- instead, you should sign in to Expo to acquire a unique redirect URL. Additionally, if you do decide to publish this app using Expo, you will need to register an account to do it.`\n );\n }\n }\n\n private static removeScheme(url: string) {\n return url.replace(/^[a-zA-Z0-9+.-]+:\\/\\//, '');\n }\n\n private static removeLeadingSlash(url: string) {\n return url.replace(/^\\//, '');\n }\n}\n\nexport default new SessionUrlProvider();\n"]}
@@ -16,16 +16,6 @@ export function getCurrentTimeInSeconds() {
16
16
  * [Section 5.1](https://tools.ietf.org/html/rfc6749#section-5.1)
17
17
  */
18
18
  export class TokenResponse {
19
- constructor(response) {
20
- this.accessToken = response.accessToken;
21
- this.tokenType = response.tokenType ?? 'bearer';
22
- this.expiresIn = response.expiresIn;
23
- this.refreshToken = response.refreshToken;
24
- this.scope = response.scope;
25
- this.state = response.state;
26
- this.idToken = response.idToken;
27
- this.issuedAt = response.issuedAt ?? getCurrentTimeInSeconds();
28
- }
29
19
  /**
30
20
  * Determines whether a token refresh request must be made to refresh the tokens
31
21
  *
@@ -67,6 +57,24 @@ export class TokenResponse {
67
57
  issuedAt: params.issued_at,
68
58
  });
69
59
  }
60
+ accessToken;
61
+ tokenType;
62
+ expiresIn;
63
+ refreshToken;
64
+ scope;
65
+ state;
66
+ idToken;
67
+ issuedAt;
68
+ constructor(response) {
69
+ this.accessToken = response.accessToken;
70
+ this.tokenType = response.tokenType ?? 'bearer';
71
+ this.expiresIn = response.expiresIn;
72
+ this.refreshToken = response.refreshToken;
73
+ this.scope = response.scope;
74
+ this.state = response.state;
75
+ this.idToken = response.idToken;
76
+ this.issuedAt = response.issuedAt ?? getCurrentTimeInSeconds();
77
+ }
70
78
  applyResponseConfig(response) {
71
79
  this.accessToken = response.accessToken ?? this.accessToken;
72
80
  this.tokenType = response.tokenType ?? this.tokenType ?? 'bearer';
@@ -107,6 +115,7 @@ export class TokenResponse {
107
115
  }
108
116
  }
109
117
  class Request {
118
+ request;
110
119
  constructor(request) {
111
120
  this.request = request;
112
121
  }
@@ -124,6 +133,11 @@ class Request {
124
133
  * A generic token request.
125
134
  */
126
135
  class TokenRequest extends Request {
136
+ grantType;
137
+ clientId;
138
+ clientSecret;
139
+ scopes;
140
+ extraParams;
127
141
  constructor(request, grantType) {
128
142
  super(request);
129
143
  this.grantType = grantType;
@@ -194,6 +208,8 @@ class TokenRequest extends Request {
194
208
  * [Section 4.1.3](https://tools.ietf.org/html/rfc6749#section-4.1.3)
195
209
  */
196
210
  export class AccessTokenRequest extends TokenRequest {
211
+ code;
212
+ redirectUri;
197
213
  constructor(options) {
198
214
  invariant(options.redirectUri, `\`AccessTokenRequest\` requires a valid \`redirectUri\` (it must also match the one used in the auth request). Example: ${Platform.select({
199
215
  web: 'https://yourwebsite.com/redirect',
@@ -232,6 +248,7 @@ export class AccessTokenRequest extends TokenRequest {
232
248
  * [Section 6](https://tools.ietf.org/html/rfc6749#section-6)
233
249
  */
234
250
  export class RefreshTokenRequest extends TokenRequest {
251
+ refreshToken;
235
252
  constructor(options) {
236
253
  invariant(options.refreshToken, `\`RefreshTokenRequest\` requires a valid \`refreshToken\`.`);
237
254
  super(options, GrantType.RefreshToken);
@@ -261,6 +278,10 @@ export class RefreshTokenRequest extends TokenRequest {
261
278
  * [Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1)
262
279
  */
263
280
  export class RevokeTokenRequest extends Request {
281
+ clientId;
282
+ clientSecret;
283
+ token;
284
+ tokenTypeHint;
264
285
  constructor(request) {
265
286
  super(request);
266
287
  invariant(request.token, `\`RevokeTokenRequest\` requires a valid \`token\` to revoke.`);
@@ -1 +1 @@
1
- {"version":3,"file":"TokenRequest.js","sourceRoot":"","sources":["../src/TokenRequest.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,KAAK,MAAM,MAAM,UAAU,CAAC;AAEnC,OAAO,EAAuB,UAAU,EAAE,MAAM,UAAU,CAAC;AAC3D,OAAO,EAAW,YAAY,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAEL,SAAS,GAQV,MAAM,sBAAsB,CAAC;AAE9B;;GAEG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,IAAI,CAAC,KAA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,YAAY,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CACzB,MAAgC,EAChC,SAAsE;IAEtE,MAAM,OAAO,GAAG,IAAI,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAC/C,OAAO,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAA0C,EAC1C,SAAoE;IAEpE,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE;QAC/B,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;KAC/F;IACD,OAAO,YAAY,CAAsB,SAAS,CAAC,gBAAgB,EAAE;QACnE,OAAO,EAAE;YACP,cAAc,EAAE,mCAAmC;YACnD,aAAa,EAAE,UAAU,MAAM,CAAC,WAAW,EAAE;SAC9C;QACD,QAAQ,EAAE,MAAM;QAChB,MAAM,EAAE,KAAK;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import invariant from 'invariant';\nimport { Platform } from 'react-native';\n\nimport * as Base64 from './Base64';\nimport * as ServiceConfig from './Discovery';\nimport { ResponseErrorConfig, TokenError } from './Errors';\nimport { Headers, requestAsync } from './Fetch';\nimport {\n AccessTokenRequestConfig,\n GrantType,\n RefreshTokenRequestConfig,\n RevokeTokenRequestConfig,\n ServerTokenResponseConfig,\n TokenRequestConfig,\n TokenResponseConfig,\n TokenType,\n TokenTypeHint,\n} from './TokenRequest.types';\n\n/**\n * Returns the current time in seconds.\n */\nexport function getCurrentTimeInSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n/**\n * Token Response.\n *\n * [Section 5.1](https://tools.ietf.org/html/rfc6749#section-5.1)\n */\nexport class TokenResponse implements TokenResponseConfig {\n /**\n * Determines whether a token refresh request must be made to refresh the tokens\n *\n * @param token\n * @param secondsMargin\n */\n static isTokenFresh(\n token: Pick<TokenResponse, 'expiresIn' | 'issuedAt'>,\n /**\n * -10 minutes in seconds\n */\n secondsMargin: number = 60 * 10 * -1\n ): boolean {\n if (!token) {\n return false;\n }\n if (token.expiresIn) {\n const now = getCurrentTimeInSeconds();\n return now < token.issuedAt + token.expiresIn + secondsMargin;\n }\n // if there is no expiration time but we have an access token, it is assumed to never expire\n return true;\n }\n /**\n * Creates a `TokenResponse` from query parameters returned from an `AuthRequest`.\n *\n * @param params\n */\n static fromQueryParams(params: Record<string, string>): TokenResponse {\n return new TokenResponse({\n accessToken: params.access_token,\n refreshToken: params.refresh_token,\n scope: params.scope,\n state: params.state,\n idToken: params.id_token,\n // @ts-ignore: Expected specific string\n tokenType: params.token_type,\n // @ts-ignore: Expected number\n expiresIn: params.expires_in,\n // @ts-ignore: Expected number\n issuedAt: params.issued_at,\n });\n }\n\n accessToken: string;\n tokenType: TokenType;\n expiresIn?: number;\n refreshToken?: string;\n scope?: string;\n state?: string;\n idToken?: string;\n issuedAt: number;\n\n constructor(response: TokenResponseConfig) {\n this.accessToken = response.accessToken;\n this.tokenType = response.tokenType ?? 'bearer';\n this.expiresIn = response.expiresIn;\n this.refreshToken = response.refreshToken;\n this.scope = response.scope;\n this.state = response.state;\n this.idToken = response.idToken;\n this.issuedAt = response.issuedAt ?? getCurrentTimeInSeconds();\n }\n\n private applyResponseConfig(response: TokenResponseConfig) {\n this.accessToken = response.accessToken ?? this.accessToken;\n this.tokenType = response.tokenType ?? this.tokenType ?? 'bearer';\n this.expiresIn = response.expiresIn ?? this.expiresIn;\n this.refreshToken = response.refreshToken ?? this.refreshToken;\n this.scope = response.scope ?? this.scope;\n this.state = response.state ?? this.state;\n this.idToken = response.idToken ?? this.idToken;\n this.issuedAt = response.issuedAt ?? this.issuedAt ?? getCurrentTimeInSeconds();\n }\n\n getRequestConfig(): TokenResponseConfig {\n return {\n accessToken: this.accessToken,\n idToken: this.idToken,\n refreshToken: this.refreshToken,\n scope: this.scope,\n state: this.state,\n tokenType: this.tokenType,\n issuedAt: this.issuedAt,\n expiresIn: this.expiresIn,\n };\n }\n\n async refreshAsync(\n config: Omit<TokenRequestConfig, 'grantType' | 'refreshToken'>,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>\n ): Promise<TokenResponse> {\n const request = new RefreshTokenRequest({\n ...config,\n refreshToken: this.refreshToken,\n });\n const response = await request.performAsync(discovery);\n // Custom: reuse the refresh token if one wasn't returned\n response.refreshToken = response.refreshToken ?? this.refreshToken;\n const json = response.getRequestConfig();\n this.applyResponseConfig(json);\n return this;\n }\n\n shouldRefresh(): boolean {\n // no refresh token available and token has expired\n return !(TokenResponse.isTokenFresh(this) || !this.refreshToken);\n }\n}\n\nclass Request<T, B> {\n constructor(protected request: T) {}\n\n async performAsync(discovery: ServiceConfig.DiscoveryDocument): Promise<B> {\n throw new Error('performAsync must be extended');\n }\n\n getRequestConfig(): T {\n throw new Error('getRequestConfig must be extended');\n }\n\n getQueryBody(): Record<string, string> {\n throw new Error('getQueryBody must be extended');\n }\n}\n\n/**\n * A generic token request.\n */\nclass TokenRequest<T extends TokenRequestConfig> extends Request<T, TokenResponse> {\n readonly clientId: string;\n readonly clientSecret?: string;\n readonly scopes?: string[];\n readonly extraParams?: Record<string, string>;\n\n constructor(request, public grantType: GrantType) {\n super(request);\n this.clientId = request.clientId;\n this.clientSecret = request.clientSecret;\n this.extraParams = request.extraParams;\n this.scopes = request.scopes;\n }\n\n getHeaders(): Headers {\n const headers: Headers = { 'Content-Type': 'application/x-www-form-urlencoded' };\n if (typeof this.clientSecret !== 'undefined') {\n // If client secret exists, it should be converted to base64\n // https://tools.ietf.org/html/rfc6749#section-2.3.1\n const encodedClientId = encodeURIComponent(this.clientId);\n const encodedClientSecret = encodeURIComponent(this.clientSecret);\n const credentials = `${encodedClientId}:${encodedClientSecret}`;\n const basicAuth = Base64.encodeNoWrap(credentials);\n headers.Authorization = `Basic ${basicAuth}`;\n }\n\n return headers;\n }\n\n async performAsync(discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>) {\n // redirect URI must not be nil\n invariant(\n discovery.tokenEndpoint,\n `Cannot invoke \\`performAsync()\\` without a valid tokenEndpoint`\n );\n const response = await requestAsync<ServerTokenResponseConfig | ResponseErrorConfig>(\n discovery.tokenEndpoint,\n {\n dataType: 'json',\n method: 'POST',\n headers: this.getHeaders(),\n body: this.getQueryBody(),\n }\n );\n\n if ('error' in response) {\n throw new TokenError(response);\n }\n\n return new TokenResponse({\n accessToken: response.access_token,\n tokenType: response.token_type,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token,\n scope: response.scope,\n idToken: response.id_token,\n issuedAt: response.issued_at,\n });\n }\n\n getQueryBody() {\n const queryBody: Record<string, string> = {\n grant_type: this.grantType,\n };\n\n if (!this.clientSecret) {\n // Only add the client ID if client secret is not present, otherwise pass the client id with the secret in the request body.\n queryBody.client_id = this.clientId;\n }\n\n if (this.scopes) {\n queryBody.scope = this.scopes.join(' ');\n }\n\n if (this.extraParams) {\n for (const extra in this.extraParams) {\n if (extra in this.extraParams && !(extra in queryBody)) {\n queryBody[extra] = this.extraParams[extra];\n }\n }\n }\n return queryBody;\n }\n}\n\n/**\n * Access token request. Exchange an authorization code for a user access token.\n *\n * [Section 4.1.3](https://tools.ietf.org/html/rfc6749#section-4.1.3)\n */\nexport class AccessTokenRequest extends TokenRequest<AccessTokenRequestConfig>\n implements AccessTokenRequestConfig {\n readonly code: string;\n readonly redirectUri: string;\n\n constructor(options: AccessTokenRequestConfig) {\n invariant(\n options.redirectUri,\n `\\`AccessTokenRequest\\` requires a valid \\`redirectUri\\` (it must also match the one used in the auth request). Example: ${Platform.select(\n {\n web: 'https://yourwebsite.com/redirect',\n default: 'myapp://redirect',\n }\n )}`\n );\n\n invariant(\n options.code,\n `\\`AccessTokenRequest\\` requires a valid authorization \\`code\\`. This is what's received from the authorization server after an auth request.`\n );\n super(options, GrantType.AuthorizationCode);\n this.code = options.code;\n this.redirectUri = options.redirectUri;\n }\n\n getQueryBody() {\n const queryBody: Record<string, string> = super.getQueryBody();\n\n if (this.redirectUri) {\n queryBody.redirect_uri = this.redirectUri;\n }\n\n if (this.code) {\n queryBody.code = this.code;\n }\n\n return queryBody;\n }\n\n getRequestConfig() {\n return {\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n grantType: this.grantType,\n code: this.code,\n redirectUri: this.redirectUri,\n extraParams: this.extraParams,\n scopes: this.scopes,\n };\n }\n}\n\n/**\n * Refresh request.\n *\n * [Section 6](https://tools.ietf.org/html/rfc6749#section-6)\n */\nexport class RefreshTokenRequest extends TokenRequest<RefreshTokenRequestConfig>\n implements RefreshTokenRequestConfig {\n readonly refreshToken?: string;\n\n constructor(options: RefreshTokenRequestConfig) {\n invariant(options.refreshToken, `\\`RefreshTokenRequest\\` requires a valid \\`refreshToken\\`.`);\n super(options, GrantType.RefreshToken);\n this.refreshToken = options.refreshToken;\n }\n\n getQueryBody() {\n const queryBody = super.getQueryBody();\n\n if (this.refreshToken) {\n queryBody.refresh_token = this.refreshToken;\n }\n\n return queryBody;\n }\n\n getRequestConfig() {\n return {\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n grantType: this.grantType,\n refreshToken: this.refreshToken,\n extraParams: this.extraParams,\n scopes: this.scopes,\n };\n }\n}\n\n/**\n * Revocation request for a given token.\n *\n * [Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1)\n */\nexport class RevokeTokenRequest extends Request<RevokeTokenRequestConfig, boolean>\n implements RevokeTokenRequestConfig {\n readonly clientId?: string;\n readonly clientSecret?: string;\n readonly token: string;\n readonly tokenTypeHint?: TokenTypeHint;\n\n constructor(request: RevokeTokenRequestConfig) {\n super(request);\n invariant(request.token, `\\`RevokeTokenRequest\\` requires a valid \\`token\\` to revoke.`);\n this.clientId = request.clientId;\n this.clientSecret = request.clientSecret;\n this.token = request.token;\n this.tokenTypeHint = request.tokenTypeHint;\n }\n\n getHeaders(): Headers {\n const headers: Headers = { 'Content-Type': 'application/x-www-form-urlencoded' };\n if (typeof this.clientSecret !== 'undefined' && this.clientId) {\n // If client secret exists, it should be converted to base64\n // https://tools.ietf.org/html/rfc6749#section-2.3.1\n const encodedClientId = encodeURIComponent(this.clientId);\n const encodedClientSecret = encodeURIComponent(this.clientSecret);\n const credentials = `${encodedClientId}:${encodedClientSecret}`;\n const basicAuth = Base64.encodeNoWrap(credentials);\n headers.Authorization = `Basic ${basicAuth}`;\n }\n\n return headers;\n }\n\n /**\n * Perform a token revocation request.\n *\n * @param discovery The `revocationEndpoint` for a provider.\n */\n async performAsync(discovery: Pick<ServiceConfig.DiscoveryDocument, 'revocationEndpoint'>) {\n invariant(\n discovery.revocationEndpoint,\n `Cannot invoke \\`performAsync()\\` without a valid revocationEndpoint`\n );\n await requestAsync<boolean>(discovery.revocationEndpoint, {\n method: 'POST',\n headers: this.getHeaders(),\n body: this.getQueryBody(),\n });\n\n return true;\n }\n\n getRequestConfig() {\n return {\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n token: this.token,\n tokenTypeHint: this.tokenTypeHint,\n };\n }\n\n getQueryBody(): Record<string, string> {\n const queryBody: Record<string, string> = { token: this.token };\n if (this.tokenTypeHint) {\n queryBody.token_type_hint = this.tokenTypeHint;\n }\n // Include client creds https://tools.ietf.org/html/rfc6749#section-2.3.1\n if (this.clientId) {\n queryBody.client_id = this.clientId;\n }\n if (this.clientSecret) {\n queryBody.client_secret = this.clientSecret;\n }\n return queryBody;\n }\n}\n\n/**\n * Exchange an auth code for an access token that can be used to get data from the provider.\n *\n * @param config\n * @param discovery The `tokenEndpoint` for a provider.\n */\nexport function exchangeCodeAsync(\n config: AccessTokenRequestConfig,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>\n): Promise<TokenResponse> {\n const request = new AccessTokenRequest(config);\n return request.performAsync(discovery);\n}\n\n/**\n * Refresh an access token. Often this just requires the `refreshToken` and `scopes` parameters.\n *\n * [Section 6](https://tools.ietf.org/html/rfc6749#section-6)\n *\n * @param config\n * @param discovery The `tokenEndpoint` for a provider.\n */\nexport function refreshAsync(\n config: RefreshTokenRequestConfig,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>\n): Promise<TokenResponse> {\n const request = new RefreshTokenRequest(config);\n return request.performAsync(discovery);\n}\n\n/**\n * Revoke a token with a provider.\n * This makes the token unusable, effectively requiring the user to login again.\n *\n * @param config\n * @param discovery The `revocationEndpoint` for a provider.\n */\nexport function revokeAsync(\n config: RevokeTokenRequestConfig,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'revocationEndpoint'>\n): Promise<boolean> {\n const request = new RevokeTokenRequest(config);\n return request.performAsync(discovery);\n}\n\n/**\n * Fetch generic user info from the provider's OpenID Connect `userInfoEndpoint` (if supported).\n *\n * [UserInfo](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo)\n *\n * @param config The `accessToken` for a user, returned from a code exchange or auth request.\n * @param discovery The `userInfoEndpoint` for a provider.\n */\nexport function fetchUserInfoAsync(\n config: Pick<TokenResponse, 'accessToken'>,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'userInfoEndpoint'>\n): Promise<Record<string, any>> {\n if (!discovery.userInfoEndpoint) {\n throw new Error('User info endpoint is not defined in the service config discovery document');\n }\n return requestAsync<Record<string, any>>(discovery.userInfoEndpoint, {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${config.accessToken}`,\n },\n dataType: 'json',\n method: 'GET',\n });\n}\n"]}
1
+ {"version":3,"file":"TokenRequest.js","sourceRoot":"","sources":["../src/TokenRequest.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,KAAK,MAAM,MAAM,UAAU,CAAC;AAEnC,OAAO,EAAuB,UAAU,EAAE,MAAM,UAAU,CAAC;AAC3D,OAAO,EAAW,YAAY,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAEL,SAAS,GAQV,MAAM,s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AAG,IAAI,CAAC,YAAY,CAAC;SAC7C;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAC/B,MAAgC,EAChC,SAAiE;IAEjE,MAAM,OAAO,GAAG,IAAI,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAC/C,OAAO,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAiC,EACjC,SAAiE;IAEjE,MAAM,OAAO,GAAG,IAAI,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAChD,OAAO,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CACzB,MAAgC,EAChC,SAAsE;IAEtE,MAAM,OAAO,GAAG,IAAI,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAC/C,OAAO,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAA0C,EAC1C,SAAoE;IAEpE,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE;QAC/B,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;KAC/F;IACD,OAAO,YAAY,CAAsB,SAAS,CAAC,gBAAgB,EAAE;QACnE,OAAO,EAAE;YACP,cAAc,EAAE,mCAAmC;YACnD,aAAa,EAAE,UAAU,MAAM,CAAC,WAAW,EAAE;SAC9C;QACD,QAAQ,EAAE,MAAM;QAChB,MAAM,EAAE,KAAK;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import invariant from 'invariant';\nimport { Platform } from 'react-native';\n\nimport * as Base64 from './Base64';\nimport * as ServiceConfig from './Discovery';\nimport { ResponseErrorConfig, TokenError } from './Errors';\nimport { Headers, requestAsync } from './Fetch';\nimport {\n AccessTokenRequestConfig,\n GrantType,\n RefreshTokenRequestConfig,\n RevokeTokenRequestConfig,\n ServerTokenResponseConfig,\n TokenRequestConfig,\n TokenResponseConfig,\n TokenType,\n TokenTypeHint,\n} from './TokenRequest.types';\n\n/**\n * Returns the current time in seconds.\n */\nexport function getCurrentTimeInSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n/**\n * Token Response.\n *\n * [Section 5.1](https://tools.ietf.org/html/rfc6749#section-5.1)\n */\nexport class TokenResponse implements TokenResponseConfig {\n /**\n * Determines whether a token refresh request must be made to refresh the tokens\n *\n * @param token\n * @param secondsMargin\n */\n static isTokenFresh(\n token: Pick<TokenResponse, 'expiresIn' | 'issuedAt'>,\n /**\n * -10 minutes in seconds\n */\n secondsMargin: number = 60 * 10 * -1\n ): boolean {\n if (!token) {\n return false;\n }\n if (token.expiresIn) {\n const now = getCurrentTimeInSeconds();\n return now < token.issuedAt + token.expiresIn + secondsMargin;\n }\n // if there is no expiration time but we have an access token, it is assumed to never expire\n return true;\n }\n /**\n * Creates a `TokenResponse` from query parameters returned from an `AuthRequest`.\n *\n * @param params\n */\n static fromQueryParams(params: Record<string, string>): TokenResponse {\n return new TokenResponse({\n accessToken: params.access_token,\n refreshToken: params.refresh_token,\n scope: params.scope,\n state: params.state,\n idToken: params.id_token,\n // @ts-ignore: Expected specific string\n tokenType: params.token_type,\n // @ts-ignore: Expected number\n expiresIn: params.expires_in,\n // @ts-ignore: Expected number\n issuedAt: params.issued_at,\n });\n }\n\n accessToken: string;\n tokenType: TokenType;\n expiresIn?: number;\n refreshToken?: string;\n scope?: string;\n state?: string;\n idToken?: string;\n issuedAt: number;\n\n constructor(response: TokenResponseConfig) {\n this.accessToken = response.accessToken;\n this.tokenType = response.tokenType ?? 'bearer';\n this.expiresIn = response.expiresIn;\n this.refreshToken = response.refreshToken;\n this.scope = response.scope;\n this.state = response.state;\n this.idToken = response.idToken;\n this.issuedAt = response.issuedAt ?? getCurrentTimeInSeconds();\n }\n\n private applyResponseConfig(response: TokenResponseConfig) {\n this.accessToken = response.accessToken ?? this.accessToken;\n this.tokenType = response.tokenType ?? this.tokenType ?? 'bearer';\n this.expiresIn = response.expiresIn ?? this.expiresIn;\n this.refreshToken = response.refreshToken ?? this.refreshToken;\n this.scope = response.scope ?? this.scope;\n this.state = response.state ?? this.state;\n this.idToken = response.idToken ?? this.idToken;\n this.issuedAt = response.issuedAt ?? this.issuedAt ?? getCurrentTimeInSeconds();\n }\n\n getRequestConfig(): TokenResponseConfig {\n return {\n accessToken: this.accessToken,\n idToken: this.idToken,\n refreshToken: this.refreshToken,\n scope: this.scope,\n state: this.state,\n tokenType: this.tokenType,\n issuedAt: this.issuedAt,\n expiresIn: this.expiresIn,\n };\n }\n\n async refreshAsync(\n config: Omit<TokenRequestConfig, 'grantType' | 'refreshToken'>,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>\n ): Promise<TokenResponse> {\n const request = new RefreshTokenRequest({\n ...config,\n refreshToken: this.refreshToken,\n });\n const response = await request.performAsync(discovery);\n // Custom: reuse the refresh token if one wasn't returned\n response.refreshToken = response.refreshToken ?? this.refreshToken;\n const json = response.getRequestConfig();\n this.applyResponseConfig(json);\n return this;\n }\n\n shouldRefresh(): boolean {\n // no refresh token available and token has expired\n return !(TokenResponse.isTokenFresh(this) || !this.refreshToken);\n }\n}\n\nclass Request<T, B> {\n constructor(protected request: T) {}\n\n async performAsync(discovery: ServiceConfig.DiscoveryDocument): Promise<B> {\n throw new Error('performAsync must be extended');\n }\n\n getRequestConfig(): T {\n throw new Error('getRequestConfig must be extended');\n }\n\n getQueryBody(): Record<string, string> {\n throw new Error('getQueryBody must be extended');\n }\n}\n\n/**\n * A generic token request.\n */\nclass TokenRequest<T extends TokenRequestConfig> extends Request<T, TokenResponse> {\n readonly clientId: string;\n readonly clientSecret?: string;\n readonly scopes?: string[];\n readonly extraParams?: Record<string, string>;\n\n constructor(request, public grantType: GrantType) {\n super(request);\n this.clientId = request.clientId;\n this.clientSecret = request.clientSecret;\n this.extraParams = request.extraParams;\n this.scopes = request.scopes;\n }\n\n getHeaders(): Headers {\n const headers: Headers = { 'Content-Type': 'application/x-www-form-urlencoded' };\n if (typeof this.clientSecret !== 'undefined') {\n // If client secret exists, it should be converted to base64\n // https://tools.ietf.org/html/rfc6749#section-2.3.1\n const encodedClientId = encodeURIComponent(this.clientId);\n const encodedClientSecret = encodeURIComponent(this.clientSecret);\n const credentials = `${encodedClientId}:${encodedClientSecret}`;\n const basicAuth = Base64.encodeNoWrap(credentials);\n headers.Authorization = `Basic ${basicAuth}`;\n }\n\n return headers;\n }\n\n async performAsync(discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>) {\n // redirect URI must not be nil\n invariant(\n discovery.tokenEndpoint,\n `Cannot invoke \\`performAsync()\\` without a valid tokenEndpoint`\n );\n const response = await requestAsync<ServerTokenResponseConfig | ResponseErrorConfig>(\n discovery.tokenEndpoint,\n {\n dataType: 'json',\n method: 'POST',\n headers: this.getHeaders(),\n body: this.getQueryBody(),\n }\n );\n\n if ('error' in response) {\n throw new TokenError(response);\n }\n\n return new TokenResponse({\n accessToken: response.access_token,\n tokenType: response.token_type,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token,\n scope: response.scope,\n idToken: response.id_token,\n issuedAt: response.issued_at,\n });\n }\n\n getQueryBody() {\n const queryBody: Record<string, string> = {\n grant_type: this.grantType,\n };\n\n if (!this.clientSecret) {\n // Only add the client ID if client secret is not present, otherwise pass the client id with the secret in the request body.\n queryBody.client_id = this.clientId;\n }\n\n if (this.scopes) {\n queryBody.scope = this.scopes.join(' ');\n }\n\n if (this.extraParams) {\n for (const extra in this.extraParams) {\n if (extra in this.extraParams && !(extra in queryBody)) {\n queryBody[extra] = this.extraParams[extra];\n }\n }\n }\n return queryBody;\n }\n}\n\n/**\n * Access token request. Exchange an authorization code for a user access token.\n *\n * [Section 4.1.3](https://tools.ietf.org/html/rfc6749#section-4.1.3)\n */\nexport class AccessTokenRequest\n extends TokenRequest<AccessTokenRequestConfig>\n implements AccessTokenRequestConfig\n{\n readonly code: string;\n readonly redirectUri: string;\n\n constructor(options: AccessTokenRequestConfig) {\n invariant(\n options.redirectUri,\n `\\`AccessTokenRequest\\` requires a valid \\`redirectUri\\` (it must also match the one used in the auth request). Example: ${Platform.select(\n {\n web: 'https://yourwebsite.com/redirect',\n default: 'myapp://redirect',\n }\n )}`\n );\n\n invariant(\n options.code,\n `\\`AccessTokenRequest\\` requires a valid authorization \\`code\\`. This is what's received from the authorization server after an auth request.`\n );\n super(options, GrantType.AuthorizationCode);\n this.code = options.code;\n this.redirectUri = options.redirectUri;\n }\n\n getQueryBody() {\n const queryBody: Record<string, string> = super.getQueryBody();\n\n if (this.redirectUri) {\n queryBody.redirect_uri = this.redirectUri;\n }\n\n if (this.code) {\n queryBody.code = this.code;\n }\n\n return queryBody;\n }\n\n getRequestConfig() {\n return {\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n grantType: this.grantType,\n code: this.code,\n redirectUri: this.redirectUri,\n extraParams: this.extraParams,\n scopes: this.scopes,\n };\n }\n}\n\n/**\n * Refresh request.\n *\n * [Section 6](https://tools.ietf.org/html/rfc6749#section-6)\n */\nexport class RefreshTokenRequest\n extends TokenRequest<RefreshTokenRequestConfig>\n implements RefreshTokenRequestConfig\n{\n readonly refreshToken?: string;\n\n constructor(options: RefreshTokenRequestConfig) {\n invariant(options.refreshToken, `\\`RefreshTokenRequest\\` requires a valid \\`refreshToken\\`.`);\n super(options, GrantType.RefreshToken);\n this.refreshToken = options.refreshToken;\n }\n\n getQueryBody() {\n const queryBody = super.getQueryBody();\n\n if (this.refreshToken) {\n queryBody.refresh_token = this.refreshToken;\n }\n\n return queryBody;\n }\n\n getRequestConfig() {\n return {\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n grantType: this.grantType,\n refreshToken: this.refreshToken,\n extraParams: this.extraParams,\n scopes: this.scopes,\n };\n }\n}\n\n/**\n * Revocation request for a given token.\n *\n * [Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1)\n */\nexport class RevokeTokenRequest\n extends Request<RevokeTokenRequestConfig, boolean>\n implements RevokeTokenRequestConfig\n{\n readonly clientId?: string;\n readonly clientSecret?: string;\n readonly token: string;\n readonly tokenTypeHint?: TokenTypeHint;\n\n constructor(request: RevokeTokenRequestConfig) {\n super(request);\n invariant(request.token, `\\`RevokeTokenRequest\\` requires a valid \\`token\\` to revoke.`);\n this.clientId = request.clientId;\n this.clientSecret = request.clientSecret;\n this.token = request.token;\n this.tokenTypeHint = request.tokenTypeHint;\n }\n\n getHeaders(): Headers {\n const headers: Headers = { 'Content-Type': 'application/x-www-form-urlencoded' };\n if (typeof this.clientSecret !== 'undefined' && this.clientId) {\n // If client secret exists, it should be converted to base64\n // https://tools.ietf.org/html/rfc6749#section-2.3.1\n const encodedClientId = encodeURIComponent(this.clientId);\n const encodedClientSecret = encodeURIComponent(this.clientSecret);\n const credentials = `${encodedClientId}:${encodedClientSecret}`;\n const basicAuth = Base64.encodeNoWrap(credentials);\n headers.Authorization = `Basic ${basicAuth}`;\n }\n\n return headers;\n }\n\n /**\n * Perform a token revocation request.\n *\n * @param discovery The `revocationEndpoint` for a provider.\n */\n async performAsync(discovery: Pick<ServiceConfig.DiscoveryDocument, 'revocationEndpoint'>) {\n invariant(\n discovery.revocationEndpoint,\n `Cannot invoke \\`performAsync()\\` without a valid revocationEndpoint`\n );\n await requestAsync<boolean>(discovery.revocationEndpoint, {\n method: 'POST',\n headers: this.getHeaders(),\n body: this.getQueryBody(),\n });\n\n return true;\n }\n\n getRequestConfig() {\n return {\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n token: this.token,\n tokenTypeHint: this.tokenTypeHint,\n };\n }\n\n getQueryBody(): Record<string, string> {\n const queryBody: Record<string, string> = { token: this.token };\n if (this.tokenTypeHint) {\n queryBody.token_type_hint = this.tokenTypeHint;\n }\n // Include client creds https://tools.ietf.org/html/rfc6749#section-2.3.1\n if (this.clientId) {\n queryBody.client_id = this.clientId;\n }\n if (this.clientSecret) {\n queryBody.client_secret = this.clientSecret;\n }\n return queryBody;\n }\n}\n\n/**\n * Exchange an auth code for an access token that can be used to get data from the provider.\n *\n * @param config\n * @param discovery The `tokenEndpoint` for a provider.\n */\nexport function exchangeCodeAsync(\n config: AccessTokenRequestConfig,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>\n): Promise<TokenResponse> {\n const request = new AccessTokenRequest(config);\n return request.performAsync(discovery);\n}\n\n/**\n * Refresh an access token. Often this just requires the `refreshToken` and `scopes` parameters.\n *\n * [Section 6](https://tools.ietf.org/html/rfc6749#section-6)\n *\n * @param config\n * @param discovery The `tokenEndpoint` for a provider.\n */\nexport function refreshAsync(\n config: RefreshTokenRequestConfig,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>\n): Promise<TokenResponse> {\n const request = new RefreshTokenRequest(config);\n return request.performAsync(discovery);\n}\n\n/**\n * Revoke a token with a provider.\n * This makes the token unusable, effectively requiring the user to login again.\n *\n * @param config\n * @param discovery The `revocationEndpoint` for a provider.\n */\nexport function revokeAsync(\n config: RevokeTokenRequestConfig,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'revocationEndpoint'>\n): Promise<boolean> {\n const request = new RevokeTokenRequest(config);\n return request.performAsync(discovery);\n}\n\n/**\n * Fetch generic user info from the provider's OpenID Connect `userInfoEndpoint` (if supported).\n *\n * [UserInfo](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo)\n *\n * @param config The `accessToken` for a user, returned from a code exchange or auth request.\n * @param discovery The `userInfoEndpoint` for a provider.\n */\nexport function fetchUserInfoAsync(\n config: Pick<TokenResponse, 'accessToken'>,\n discovery: Pick<ServiceConfig.DiscoveryDocument, 'userInfoEndpoint'>\n): Promise<Record<string, any>> {\n if (!discovery.userInfoEndpoint) {\n throw new Error('User info endpoint is not defined in the service config discovery document');\n }\n return requestAsync<Record<string, any>>(discovery.userInfoEndpoint, {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${config.accessToken}`,\n },\n dataType: 'json',\n method: 'GET',\n });\n}\n"]}
@@ -14,6 +14,7 @@ export const discovery = {
14
14
  tokenEndpoint: 'https://graph.facebook.com/v6.0/oauth/access_token',
15
15
  };
16
16
  class FacebookAuthRequest extends AuthRequest {
17
+ nonce;
17
18
  constructor({ language,
18
19
  // Account selection cannot be reliably emulated on Facebook.
19
20
  extraParams = {}, clientSecret, ...config }) {
@@ -1 +1 @@
1
- {"version":3,"file":"Facebook.js","sourceRoot":"","sources":["../../src/providers/Facebook.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAGxC,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EACL,WAAW,EAKX,eAAe,EACf,YAAY,GACb,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvE,MAAM,QAAQ,GAAG;IACf,cAAc,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;IAC3C,kFAAkF;IAClF,aAAa,EAAE,CAAC,gBAAgB,EAAE,OAAO,CAAC;CAC3C,CAAC;AAEF,MAAM,CAAC,MAAM,SAAS,GAAsB;IAC1C,qBAAqB,EAAE,4CAA4C;IACnE,aAAa,EAAE,oDAAoD;CACpE,CAAC;AASF,MAAM,mBAAoB,SAAQ,WAAW;IAG3C,YAAY,EACV,QAAQ;IACR,6DAA6D;IAC7D,WAAW,GAAG,EAAE,EAChB,YAAY,EACZ,GAAG,MAAM,EACiB;QAC1B,MAAM,WAAW,GAA2B;YAC1C,OAAO,EAAE,OAAO;YAChB,GAA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AAC;IAE1C,MAAM,OAAO,GAAG,oBAAoB,CAClC;QACE,GAAG,MAAM;QACT,WAAW;QACX,QAAQ;QACR,WAAW;KACZ,EACD,SAAS,EACT,mBAAmB,CACpB,CAAC;IAEF,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GAAG,oBAAoB,CAAC,OAAO,EAAE,SAAS,EAAE;QACrE,cAAc,EAAE,QAAQ,CAAC,cAAc;QACvC,QAAQ;KACT,CAAC,CAAC;IAEH,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { useMemo } from 'react';\nimport { Platform } from 'react-native';\n\nimport { AuthRequestConfig } from '../AuthRequest.types';\nimport { useAuthRequestResult, useLoadedAuthRequest } from '../AuthRequestHooks';\nimport {\n AuthRequest,\n AuthRequestPromptOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n DiscoveryDocument,\n makeRedirectUri,\n ResponseType,\n} from '../AuthSession';\nimport { generateHexStringAsync } from '../PKCE';\nimport { ProviderAuthRequestConfig } from './Provider.types';\nimport { applyRequiredScopes, useProxyEnabled } from './ProviderUtils';\n\nconst settings = {\n windowFeatures: { width: 700, height: 600 },\n // These are required for Firebase to work properly which is a reasonable default.\n minimumScopes: ['public_profile', 'email'],\n};\n\nexport const discovery: DiscoveryDocument = {\n authorizationEndpoint: 'https://www.facebook.com/v6.0/dialog/oauth',\n tokenEndpoint: 'https://graph.facebook.com/v6.0/oauth/access_token',\n};\n\nexport interface FacebookAuthRequestConfig extends ProviderAuthRequestConfig {\n webClientId?: string;\n iosClientId?: string;\n androidClientId?: string;\n expoClientId?: string;\n}\n\nclass FacebookAuthRequest extends AuthRequest {\n nonce?: string;\n\n constructor({\n language,\n // Account selection cannot be reliably emulated on Facebook.\n extraParams = {},\n clientSecret,\n ...config\n }: FacebookAuthRequestConfig) {\n const inputParams: Record<string, string> = {\n display: 'popup',\n ...extraParams,\n };\n if (language) {\n inputParams.locale = language;\n }\n\n // Apply the default scopes\n const scopes = applyRequiredScopes(config.scopes, settings.minimumScopes);\n let inputClientSecret: string | undefined;\n // Facebook will throw if you attempt to use the client secret\n if (config.responseType && config.responseType !== ResponseType.Code) {\n // TODO: maybe warn that you shouldn't store the client secret on the client\n inputClientSecret = clientSecret;\n }\n // Default to implicit auth\n if (!config.responseType) {\n config.responseType = ResponseType.Token;\n }\n super({\n ...config,\n clientSecret: inputClientSecret,\n scopes,\n extraParams: inputParams,\n });\n }\n\n /**\n * Load and return a valid auth request based on the input config.\n */\n async getAuthRequestConfigAsync(): Promise<AuthRequestConfig> {\n const { extraParams = {}, ...config } = await super.getAuthRequestConfigAsync();\n if (!extraParams.nonce && !this.nonce) {\n if (!this.nonce) {\n this.nonce = await generateHexStringAsync(16);\n }\n extraParams.auth_nonce = this.nonce;\n }\n return {\n ...config,\n extraParams,\n };\n }\n}\n\n/**\n * Load an authorization request.\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes then the response will be fulfilled.\n *\n * - [Get Started](https://docs.expo.io/guides/authentication/#facebook)\n *\n * @param config\n * @param discovery\n */\nexport function useAuthRequest(\n config: Partial<FacebookAuthRequestConfig> = {},\n redirectUriOptions: Partial<AuthSessionRedirectUriOptions> = {}\n): [\n FacebookAuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const useProxy = useProxyEnabled(redirectUriOptions);\n\n const clientId = useMemo((): string => {\n const propertyName = useProxy\n ? 'expoClientId'\n : Platform.select({\n ios: 'iosClientId',\n android: 'androidClientId',\n default: 'webClientId',\n });\n return config[propertyName as any] ?? config.clientId;\n }, [\n useProxy,\n config.expoClientId,\n config.iosClientId,\n config.androidClientId,\n config.webClientId,\n config.clientId,\n ]);\n\n const redirectUri = useMemo((): string => {\n if (typeof config.redirectUri !== 'undefined') {\n return config.redirectUri;\n }\n\n return makeRedirectUri({\n // The redirect URI should be created using fb + client ID on native.\n native: `fb${clientId}://authorize`,\n useProxy,\n ...redirectUriOptions,\n });\n }, [useProxy, clientId, config.redirectUri, redirectUriOptions]);\n\n const extraParams = useMemo((): FacebookAuthRequestConfig['extraParams'] => {\n const output = config.extraParams ? { ...config.extraParams } : {};\n\n if (config.language) {\n output.locale = config.language;\n }\n return output;\n }, [config.extraParams, config.language]);\n\n const request = useLoadedAuthRequest(\n {\n ...config,\n extraParams,\n clientId,\n redirectUri,\n },\n discovery,\n FacebookAuthRequest\n );\n\n const [result, promptAsync] = useAuthRequestResult(request, discovery, {\n windowFeatures: settings.windowFeatures,\n useProxy,\n });\n\n return [request, result, promptAsync];\n}\n"]}
1
+ {"version":3,"file":"Facebook.js","sourceRoot":"","sources":["../../src/providers/Facebook.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAGxC,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EACL,WAAW,EAKX,eAAe,EACf,YAAY,GACb,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvE,MAAM,QAAQ,GAAG;IACf,cAAc,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;IAC3C,kFAAkF;IAClF,aAAa,EAAE,CAAC,gBAAgB,EAAE,OAAO,CAAC;CAC3C,CAAC;AAEF,MAAM,CAAC,MAAM,SAAS,GAAsB;IAC1C,qBAAqB,EAAE,4CAA4C;IACnE,aAAa,EAAE,oDAAoD;CACpE,CAAC;AASF,MAAM,mBAAoB,SAAQ,WAAW;IAC3C,KAAK,CAAU;IAEf,YAAY,EACV,QAAQ;IACR,6DAA6D;IAC7D,WAAW,GAAG,EAAE,EAChB,YAAY,EACZ,GAA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,CAAC,EAAE,CAAC,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;IAE1C,MAAM,OAAO,GAAG,oBAAoB,CAClC;QACE,GAAG,MAAM;QACT,WAAW;QACX,QAAQ;QACR,WAAW;KACZ,EACD,SAAS,EACT,mBAAmB,CACpB,CAAC;IAEF,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GAAG,oBAAoB,CAAC,OAAO,EAAE,SAAS,EAAE;QACrE,cAAc,EAAE,QAAQ,CAAC,cAAc;QACvC,QAAQ;KACT,CAAC,CAAC;IAEH,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { useMemo } from 'react';\nimport { Platform } from 'react-native';\n\nimport { AuthRequestConfig } from '../AuthRequest.types';\nimport { useAuthRequestResult, useLoadedAuthRequest } from '../AuthRequestHooks';\nimport {\n AuthRequest,\n AuthRequestPromptOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n DiscoveryDocument,\n makeRedirectUri,\n ResponseType,\n} from '../AuthSession';\nimport { generateHexStringAsync } from '../PKCE';\nimport { ProviderAuthRequestConfig } from './Provider.types';\nimport { applyRequiredScopes, useProxyEnabled } from './ProviderUtils';\n\nconst settings = {\n windowFeatures: { width: 700, height: 600 },\n // These are required for Firebase to work properly which is a reasonable default.\n minimumScopes: ['public_profile', 'email'],\n};\n\nexport const discovery: DiscoveryDocument = {\n authorizationEndpoint: 'https://www.facebook.com/v6.0/dialog/oauth',\n tokenEndpoint: 'https://graph.facebook.com/v6.0/oauth/access_token',\n};\n\nexport interface FacebookAuthRequestConfig extends ProviderAuthRequestConfig {\n webClientId?: string;\n iosClientId?: string;\n androidClientId?: string;\n expoClientId?: string;\n}\n\nclass FacebookAuthRequest extends AuthRequest {\n nonce?: string;\n\n constructor({\n language,\n // Account selection cannot be reliably emulated on Facebook.\n extraParams = {},\n clientSecret,\n ...config\n }: FacebookAuthRequestConfig) {\n const inputParams: Record<string, string> = {\n display: 'popup',\n ...extraParams,\n };\n if (language) {\n inputParams.locale = language;\n }\n\n // Apply the default scopes\n const scopes = applyRequiredScopes(config.scopes, settings.minimumScopes);\n let inputClientSecret: string | undefined;\n // Facebook will throw if you attempt to use the client secret\n if (config.responseType && config.responseType !== ResponseType.Code) {\n // TODO: maybe warn that you shouldn't store the client secret on the client\n inputClientSecret = clientSecret;\n }\n // Default to implicit auth\n if (!config.responseType) {\n config.responseType = ResponseType.Token;\n }\n super({\n ...config,\n clientSecret: inputClientSecret,\n scopes,\n extraParams: inputParams,\n });\n }\n\n /**\n * Load and return a valid auth request based on the input config.\n */\n async getAuthRequestConfigAsync(): Promise<AuthRequestConfig> {\n const { extraParams = {}, ...config } = await super.getAuthRequestConfigAsync();\n if (!extraParams.nonce && !this.nonce) {\n if (!this.nonce) {\n this.nonce = await generateHexStringAsync(16);\n }\n extraParams.auth_nonce = this.nonce;\n }\n return {\n ...config,\n extraParams,\n };\n }\n}\n\n/**\n * Load an authorization request.\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes then the response will be fulfilled.\n *\n * - [Get Started](https://docs.expo.io/guides/authentication/#facebook)\n *\n * @param config\n * @param discovery\n */\nexport function useAuthRequest(\n config: Partial<FacebookAuthRequestConfig> = {},\n redirectUriOptions: Partial<AuthSessionRedirectUriOptions> = {}\n): [\n FacebookAuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const useProxy = useProxyEnabled(redirectUriOptions);\n\n const clientId = useMemo((): string => {\n const propertyName = useProxy\n ? 'expoClientId'\n : Platform.select({\n ios: 'iosClientId',\n android: 'androidClientId',\n default: 'webClientId',\n });\n return config[propertyName as any] ?? config.clientId;\n }, [\n useProxy,\n config.expoClientId,\n config.iosClientId,\n config.androidClientId,\n config.webClientId,\n config.clientId,\n ]);\n\n const redirectUri = useMemo((): string => {\n if (typeof config.redirectUri !== 'undefined') {\n return config.redirectUri;\n }\n\n return makeRedirectUri({\n // The redirect URI should be created using fb + client ID on native.\n native: `fb${clientId}://authorize`,\n useProxy,\n ...redirectUriOptions,\n });\n }, [useProxy, clientId, config.redirectUri, redirectUriOptions]);\n\n const extraParams = useMemo((): FacebookAuthRequestConfig['extraParams'] => {\n const output = config.extraParams ? { ...config.extraParams } : {};\n\n if (config.language) {\n output.locale = config.language;\n }\n return output;\n }, [config.extraParams, config.language]);\n\n const request = useLoadedAuthRequest(\n {\n ...config,\n extraParams,\n clientId,\n redirectUri,\n },\n discovery,\n FacebookAuthRequest\n );\n\n const [result, promptAsync] = useAuthRequestResult(request, discovery, {\n windowFeatures: settings.windowFeatures,\n useProxy,\n });\n\n return [request, result, promptAsync];\n}\n"]}
@@ -20,6 +20,7 @@ export const discovery = {
20
20
  userInfoEndpoint: 'https://openidconnect.googleapis.com/v1/userinfo',
21
21
  };
22
22
  class GoogleAuthRequest extends AuthRequest {
23
+ nonce;
23
24
  constructor({ language, loginHint, selectAccount, extraParams = {}, clientSecret, ...config }) {
24
25
  const inputParams = {
25
26
  ...extraParams,
@@ -148,6 +149,7 @@ export function useAuthRequest(config = {}, redirectUriOptions = {}) {
148
149
  native: `${Application.applicationId}:/oauthredirect`,
149
150
  useProxy,
150
151
  ...redirectUriOptions,
152
+ // native: `com.googleusercontent.apps.${guid}:/oauthredirect`,
151
153
  });
152
154
  }, [useProxy, config.redirectUri, redirectUriOptions]);
153
155
  const extraParams = useMemo(() => {
@@ -198,7 +200,7 @@ export function useAuthRequest(config = {}, redirectUriOptions = {}) {
198
200
  code_verifier: request.codeVerifier,
199
201
  },
200
202
  });
201
- exchangeRequest.performAsync(discovery).then(authentication => {
203
+ exchangeRequest.performAsync(discovery).then((authentication) => {
202
204
  if (isMounted) {
203
205
  setFullResult({
204
206
  ...result,
@@ -1 +1 @@
1
- {"version":3,"file":"Google.js","sourceRoot":"","sources":["../../src/providers/Google.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,WAAW,MAAM,k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D;oBACzD,aAAa,EAAE,OAAO,CAAC,YAAY;iBACpC;aACF,CAAC,CAAC;YACH,eAAe,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE;gBAC5D,IAAI,SAAS,EAAE;oBACb,aAAa,CAAC;wBACZ,GAAG,MAAM;wBACT,MAAM,EAAE;4BACN,0GAA0G;4BAC1G,QAAQ,EAAE,cAAc,CAAC,OAAO;4BAChC,YAAY,EAAE,cAAc,CAAC,WAAW;4BACxC,GAAG,MAAM,CAAC,MAAM;yBACjB;wBACD,cAAc;qBACf,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC,CAAC;SACJ;aAAM;YACL,aAAa,CAAC,MAAM,CAAC,CAAC;SACvB;QACD,OAAO,GAAG,EAAE;YACV,SAAS,GAAG,KAAK,CAAC;QACpB,CAAC,CAAC;IACJ,CAAC,EAAE;QACD,QAAQ;QACR,WAAW;QACX,sBAAsB;QACtB,MAAM,CAAC,YAAY;QACnB,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC;QACxB,OAAO,EAAE,YAAY;QACrB,MAAM;KACP,CAAC,CAAC;IAEH,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import * as Application from 'expo-application';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Platform } from 'react-native';\n\nimport { useAuthRequestResult, useLoadedAuthRequest } from '../AuthRequestHooks';\nimport {\n AuthRequest,\n AuthRequestConfig,\n AuthRequestPromptOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n DiscoveryDocument,\n generateHexStringAsync,\n makeRedirectUri,\n Prompt,\n ResponseType,\n} from '../AuthSession';\nimport { AccessTokenRequest } from '../TokenRequest';\nimport { ProviderAuthRequestConfig } from './Provider.types';\nimport { applyRequiredScopes, invariantClientId, useProxyEnabled } from './ProviderUtils';\n\nconst settings = {\n windowFeatures: { width: 515, height: 680 },\n minimumScopes: [\n 'openid',\n 'https://www.googleapis.com/auth/userinfo.profile',\n 'https://www.googleapis.com/auth/userinfo.email',\n ],\n};\n\nexport const discovery: DiscoveryDocument = {\n authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenEndpoint: 'https://oauth2.googleapis.com/token',\n revocationEndpoint: 'https://oauth2.googleapis.com/revoke',\n userInfoEndpoint: 'https://openidconnect.googleapis.com/v1/userinfo',\n};\n\nexport interface GoogleAuthRequestConfig extends ProviderAuthRequestConfig {\n /**\n * If the user's email address is known ahead of time, it can be supplied to be the default option.\n * If the user has approved access for this app in the past then auth may return without any further interaction.\n */\n loginHint?: string;\n /**\n * When `true`, the service will allow the user to switch between accounts (if possible). Defaults to `false`.\n */\n selectAccount?: boolean;\n /**\n * Proxy client ID for use in the Expo client on iOS and Android.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: Web Application\n * - **URIs**: https://auth.expo.io\n * - **Authorized redirect URIs**: https://auth.expo.io/@your-username/your-project-slug\n */\n expoClientId?: string;\n /**\n * Expo web client ID for use in the browser.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: Web Application\n * - Give it a name (e.g. \"Web App\").\n * - **URIs** (Authorized JavaScript origins): https://localhost:19006 & https://yourwebsite.com\n * - **Authorized redirect URIs**: https://localhost:19006 & https://yourwebsite.com\n * - To test this be sure to start your app with `expo start:web --https`.\n */\n webClientId?: string;\n /**\n * iOS native client ID for use in standalone, bare workflow, and custom clients.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: iOS Application\n * - Give it a name (e.g. \"iOS App\").\n * - **Bundle ID**: Must match the value of `ios.bundleIdentifier` in your `app.json`.\n * - Your app needs to conform to the URI scheme matching your bundle identifier.\n * - _Standalone_: Automatically added, do nothing.\n * - _Bare workflow_: Run `npx uri-scheme add <your bundle id> --ios`\n * - To test this you can:\n * 1. Eject to bare: `expo eject` and run `yarn ios`\n * 2. Create a custom client: `expo client:ios`\n * 3. Build a production IPA: `expo build:ios`\n * - Whenever you change the values in `app.json` you'll need to rebuild the native app.\n */\n iosClientId?: string;\n /**\n * Android native client ID for use in standalone, and bare workflow.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: Android Application\n * - Give it a name (e.g. \"Android App\").\n * - **Package name**: Must match the value of `android.package` in your `app.json`.\n * - Your app needs to conform to the URI scheme matching your `android.package` (ex. `com.myname.mycoolapp:/`).\n * - _Standalone_: Automatically added, do nothing.\n * - _Bare workflow_: Run `npx uri-scheme add <your android.package> --android`\n * - **Signing-certificate fingerprint**:\n * - Run `expo credentials:manager -p android` then select \"Update upload Keystore\" -> \"Generate new keystore\" -> \"Go back to experience overview\"\n * - Copy your \"Google Certificate Fingerprint\", it will output a string that looks like `A1:B2:C3` but longer.\n * - To test this you can:\n * 1. Eject to bare: `expo eject` and run `yarn ios`\n * 2. Build a production IPA: `expo build:android`\n */\n androidClientId?: string;\n /**\n * Should the hook automatically exchange the response code for an authentication token.\n *\n * Defaults to true on installed apps (iOS, Android) when `ResponseType.Code` is used (default).\n */\n shouldAutoExchangeCode?: boolean;\n}\n\nclass GoogleAuthRequest extends AuthRequest {\n nonce?: string;\n\n constructor({\n language,\n loginHint,\n selectAccount,\n extraParams = {},\n clientSecret,\n ...config\n }: GoogleAuthRequestConfig) {\n const inputParams = {\n ...extraParams,\n };\n if (language) inputParams.hl = language;\n if (loginHint) inputParams.login_hint = loginHint;\n if (selectAccount) inputParams.prompt = Prompt.SelectAccount;\n\n // Apply the default scopes\n const scopes = applyRequiredScopes(config.scopes, settings.minimumScopes);\n const isImplicit =\n config.responseType === ResponseType.Token || config.responseType === ResponseType.IdToken;\n if (isImplicit) {\n // PKCE must be disabled in implicit mode.\n config.usePKCE = false;\n }\n let inputClientSecret: string | undefined;\n // Google will throw if you attempt to use the client secret\n if (config.responseType && config.responseType !== ResponseType.Code) {\n // TODO: maybe warn that you shouldn't store the client secret on the client\n inputClientSecret = clientSecret;\n }\n super({\n ...config,\n clientSecret: inputClientSecret,\n scopes,\n extraParams: inputParams,\n });\n }\n\n /**\n * Load and return a valid auth request based on the input config.\n */\n async getAuthRequestConfigAsync(): Promise<AuthRequestConfig> {\n const { extraParams = {}, ...config } = await super.getAuthRequestConfigAsync();\n if (config.responseType === ResponseType.IdToken && !extraParams.nonce && !this.nonce) {\n if (!this.nonce) {\n this.nonce = await generateHexStringAsync(16);\n }\n extraParams.nonce = this.nonce;\n }\n return {\n ...config,\n extraParams,\n };\n }\n}\n\n/**\n * Load an authorization request with an ID Token for authentication with Firebase.\n *\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes then the response will be fulfilled.\n *\n * The id token can be retrieved with `response.params.id_token`.\n *\n * - [Get Started](https://docs.expo.io/guides/authentication/#google)\n *\n * @param config\n * @param redirectUriOptions\n */\nexport function useIdTokenAuthRequest(\n config: Partial<GoogleAuthRequestConfig>,\n redirectUriOptions: Partial<AuthSessionRedirectUriOptions> = {}\n): [\n GoogleAuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const useProxy = useProxyEnabled(redirectUriOptions);\n\n const isWebAuth = useProxy || Platform.OS === 'web';\n\n return useAuthRequest(\n {\n ...config,\n responseType:\n // If the client secret is provided then code can be used\n !config.clientSecret &&\n // When web auth is used, we can request the `id_token` directly without exchanging a code.\n isWebAuth\n ? ResponseType.IdToken\n : undefined,\n },\n { ...redirectUriOptions, useProxy }\n );\n}\n\n/**\n * Load an authorization request.\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes, then the response will be fulfilled.\n *\n * - [Get Started](https://docs.expo.io/guides/authentication/#google)\n *\n * @param config\n * @param redirectUriOptions\n */\nexport function useAuthRequest(\n config: Partial<GoogleAuthRequestConfig> = {},\n redirectUriOptions: Partial<AuthSessionRedirectUriOptions> = {}\n): [\n GoogleAuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const useProxy = useProxyEnabled(redirectUriOptions);\n\n const clientId = useMemo((): string => {\n const propertyName = useProxy\n ? 'expoClientId'\n : Platform.select({\n ios: 'iosClientId',\n android: 'androidClientId',\n default: 'webClientId',\n });\n\n const clientId = config[propertyName as any] ?? config.clientId;\n invariantClientId(propertyName, clientId, 'Google');\n return clientId;\n }, [\n useProxy,\n config.expoClientId,\n config.iosClientId,\n config.androidClientId,\n config.webClientId,\n config.clientId,\n ]);\n\n const responseType = useMemo(() => {\n // Allow overrides.\n if (typeof config.responseType !== 'undefined') {\n return config.responseType;\n }\n // You can only use `response_token=code` on installed apps (iOS, Android without proxy).\n // Installed apps can auto exchange without a client secret and get the token and id-token (Firebase).\n const isInstalledApp = Platform.OS !== 'web' && !useProxy;\n // If the user provided the client secret (they shouldn't!) then use code exchange by default.\n if (config.clientSecret || isInstalledApp) {\n return ResponseType.Code;\n }\n // This seems the most pragmatic option since it can result in a full authentication on web and proxy platforms as expected.\n return ResponseType.Token;\n }, [config.responseType, config.clientSecret, useProxy]);\n\n const redirectUri = useMemo((): string => {\n if (typeof config.redirectUri !== 'undefined') {\n return config.redirectUri;\n }\n\n return makeRedirectUri({\n native: `${Application.applicationId}:/oauthredirect`,\n useProxy,\n ...redirectUriOptions,\n // native: `com.googleusercontent.apps.${guid}:/oauthredirect`,\n });\n }, [useProxy, config.redirectUri, redirectUriOptions]);\n\n const extraParams = useMemo((): GoogleAuthRequestConfig['extraParams'] => {\n const output = config.extraParams ? { ...config.extraParams } : {};\n\n if (config.language) {\n output.hl = output.language;\n }\n if (config.loginHint) {\n output.login_hint = output.loginHint;\n }\n if (config.selectAccount) {\n output.prompt = Prompt.SelectAccount;\n }\n return output;\n }, [config.extraParams, config.language, config.loginHint, config.selectAccount]);\n\n const request = useLoadedAuthRequest(\n {\n ...config,\n responseType,\n extraParams,\n clientId,\n redirectUri,\n },\n discovery,\n GoogleAuthRequest\n );\n\n const [result, promptAsync] = useAuthRequestResult(request, discovery, {\n useProxy,\n windowFeatures: settings.windowFeatures,\n });\n\n const [fullResult, setFullResult] = useState<AuthSessionResult | null>(null);\n\n const shouldAutoExchangeCode = useMemo(() => {\n // allow overrides\n if (typeof config.shouldAutoExchangeCode !== 'undefined') {\n return config.shouldAutoExchangeCode;\n }\n\n // has a code to exchange and doesn't have an authentication yet.\n const couldAutoExchange =\n result?.type === 'success' && result.params.code && !result.authentication;\n\n return couldAutoExchange;\n }, [config.shouldAutoExchangeCode, result?.type]);\n\n useEffect(() => {\n let isMounted = true;\n if (shouldAutoExchangeCode && result?.type === 'success') {\n const exchangeRequest = new AccessTokenRequest({\n clientId,\n clientSecret: config.clientSecret,\n redirectUri,\n scopes: config.scopes,\n code: result.params.code,\n extraParams: {\n // @ts-ignore: allow for instances where PKCE is disabled\n code_verifier: request.codeVerifier,\n },\n });\n exchangeRequest.performAsync(discovery).then(authentication => {\n if (isMounted) {\n setFullResult({\n ...result,\n params: {\n // @ts-ignore: provide a singular interface for getting the id_token across all workflows that request it.\n id_token: authentication.idToken,\n access_token: authentication.accessToken,\n ...result.params,\n },\n authentication,\n });\n }\n });\n } else {\n setFullResult(result);\n }\n return () => {\n isMounted = false;\n };\n }, [\n clientId,\n redirectUri,\n shouldAutoExchangeCode,\n config.clientSecret,\n config.scopes?.join(','),\n request?.codeVerifier,\n result,\n ]);\n\n return [request, fullResult, promptAsync];\n}\n"]}
1
+ {"version":3,"file":"Google.js","sourceRoot":"","sources":["../../src/providers/Google.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EACL,WAAW,EAMX,sBAAsB,EACtB,eAAe,EACf,MAAM,EACN,YAAY,GACb,MAAM,gBAAgB,CAA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Ac,CAAC,OAAO;4BAChC,YAAY,EAAE,cAAc,CAAC,WAAW;4BACxC,GAAG,MAAM,CAAC,MAAM;yBACjB;wBACD,cAAc;qBACf,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC,CAAC;SACJ;aAAM;YACL,aAAa,CAAC,MAAM,CAAC,CAAC;SACvB;QACD,OAAO,GAAG,EAAE;YACV,SAAS,GAAG,KAAK,CAAC;QACpB,CAAC,CAAC;IACJ,CAAC,EAAE;QACD,QAAQ;QACR,WAAW;QACX,sBAAsB;QACtB,MAAM,CAAC,YAAY;QACnB,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC;QACxB,OAAO,EAAE,YAAY;QACrB,MAAM;KACP,CAAC,CAAC;IAEH,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import * as Application from 'expo-application';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Platform } from 'react-native';\n\nimport { useAuthRequestResult, useLoadedAuthRequest } from '../AuthRequestHooks';\nimport {\n AuthRequest,\n AuthRequestConfig,\n AuthRequestPromptOptions,\n AuthSessionRedirectUriOptions,\n AuthSessionResult,\n DiscoveryDocument,\n generateHexStringAsync,\n makeRedirectUri,\n Prompt,\n ResponseType,\n} from '../AuthSession';\nimport { AccessTokenRequest } from '../TokenRequest';\nimport { ProviderAuthRequestConfig } from './Provider.types';\nimport { applyRequiredScopes, invariantClientId, useProxyEnabled } from './ProviderUtils';\n\nconst settings = {\n windowFeatures: { width: 515, height: 680 },\n minimumScopes: [\n 'openid',\n 'https://www.googleapis.com/auth/userinfo.profile',\n 'https://www.googleapis.com/auth/userinfo.email',\n ],\n};\n\nexport const discovery: DiscoveryDocument = {\n authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenEndpoint: 'https://oauth2.googleapis.com/token',\n revocationEndpoint: 'https://oauth2.googleapis.com/revoke',\n userInfoEndpoint: 'https://openidconnect.googleapis.com/v1/userinfo',\n};\n\nexport interface GoogleAuthRequestConfig extends ProviderAuthRequestConfig {\n /**\n * If the user's email address is known ahead of time, it can be supplied to be the default option.\n * If the user has approved access for this app in the past then auth may return without any further interaction.\n */\n loginHint?: string;\n /**\n * When `true`, the service will allow the user to switch between accounts (if possible). Defaults to `false`.\n */\n selectAccount?: boolean;\n /**\n * Proxy client ID for use in the Expo client on iOS and Android.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: Web Application\n * - **URIs**: https://auth.expo.io\n * - **Authorized redirect URIs**: https://auth.expo.io/@your-username/your-project-slug\n */\n expoClientId?: string;\n /**\n * Expo web client ID for use in the browser.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: Web Application\n * - Give it a name (e.g. \"Web App\").\n * - **URIs** (Authorized JavaScript origins): https://localhost:19006 & https://yourwebsite.com\n * - **Authorized redirect URIs**: https://localhost:19006 & https://yourwebsite.com\n * - To test this be sure to start your app with `expo start:web --https`.\n */\n webClientId?: string;\n /**\n * iOS native client ID for use in standalone, bare workflow, and custom clients.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: iOS Application\n * - Give it a name (e.g. \"iOS App\").\n * - **Bundle ID**: Must match the value of `ios.bundleIdentifier` in your `app.json`.\n * - Your app needs to conform to the URI scheme matching your bundle identifier.\n * - _Standalone_: Automatically added, do nothing.\n * - _Bare workflow_: Run `npx uri-scheme add <your bundle id> --ios`\n * - To test this you can:\n * 1. Eject to bare: `expo eject` and run `yarn ios`\n * 2. Create a custom client: `expo client:ios`\n * 3. Build a production IPA: `expo build:ios`\n * - Whenever you change the values in `app.json` you'll need to rebuild the native app.\n */\n iosClientId?: string;\n /**\n * Android native client ID for use in standalone, and bare workflow.\n *\n * This Google Client ID must be setup as follows:\n *\n * - **Application Type**: Android Application\n * - Give it a name (e.g. \"Android App\").\n * - **Package name**: Must match the value of `android.package` in your `app.json`.\n * - Your app needs to conform to the URI scheme matching your `android.package` (ex. `com.myname.mycoolapp:/`).\n * - _Standalone_: Automatically added, do nothing.\n * - _Bare workflow_: Run `npx uri-scheme add <your android.package> --android`\n * - **Signing-certificate fingerprint**:\n * - Run `expo credentials:manager -p android` then select \"Update upload Keystore\" -> \"Generate new keystore\" -> \"Go back to experience overview\"\n * - Copy your \"Google Certificate Fingerprint\", it will output a string that looks like `A1:B2:C3` but longer.\n * - To test this you can:\n * 1. Eject to bare: `expo eject` and run `yarn ios`\n * 2. Build a production IPA: `expo build:android`\n */\n androidClientId?: string;\n /**\n * Should the hook automatically exchange the response code for an authentication token.\n *\n * Defaults to true on installed apps (iOS, Android) when `ResponseType.Code` is used (default).\n */\n shouldAutoExchangeCode?: boolean;\n}\n\nclass GoogleAuthRequest extends AuthRequest {\n nonce?: string;\n\n constructor({\n language,\n loginHint,\n selectAccount,\n extraParams = {},\n clientSecret,\n ...config\n }: GoogleAuthRequestConfig) {\n const inputParams = {\n ...extraParams,\n };\n if (language) inputParams.hl = language;\n if (loginHint) inputParams.login_hint = loginHint;\n if (selectAccount) inputParams.prompt = Prompt.SelectAccount;\n\n // Apply the default scopes\n const scopes = applyRequiredScopes(config.scopes, settings.minimumScopes);\n const isImplicit =\n config.responseType === ResponseType.Token || config.responseType === ResponseType.IdToken;\n if (isImplicit) {\n // PKCE must be disabled in implicit mode.\n config.usePKCE = false;\n }\n let inputClientSecret: string | undefined;\n // Google will throw if you attempt to use the client secret\n if (config.responseType && config.responseType !== ResponseType.Code) {\n // TODO: maybe warn that you shouldn't store the client secret on the client\n inputClientSecret = clientSecret;\n }\n super({\n ...config,\n clientSecret: inputClientSecret,\n scopes,\n extraParams: inputParams,\n });\n }\n\n /**\n * Load and return a valid auth request based on the input config.\n */\n async getAuthRequestConfigAsync(): Promise<AuthRequestConfig> {\n const { extraParams = {}, ...config } = await super.getAuthRequestConfigAsync();\n if (config.responseType === ResponseType.IdToken && !extraParams.nonce && !this.nonce) {\n if (!this.nonce) {\n this.nonce = await generateHexStringAsync(16);\n }\n extraParams.nonce = this.nonce;\n }\n return {\n ...config,\n extraParams,\n };\n }\n}\n\n/**\n * Load an authorization request with an ID Token for authentication with Firebase.\n *\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes then the response will be fulfilled.\n *\n * The id token can be retrieved with `response.params.id_token`.\n *\n * - [Get Started](https://docs.expo.io/guides/authentication/#google)\n *\n * @param config\n * @param redirectUriOptions\n */\nexport function useIdTokenAuthRequest(\n config: Partial<GoogleAuthRequestConfig>,\n redirectUriOptions: Partial<AuthSessionRedirectUriOptions> = {}\n): [\n GoogleAuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const useProxy = useProxyEnabled(redirectUriOptions);\n\n const isWebAuth = useProxy || Platform.OS === 'web';\n\n return useAuthRequest(\n {\n ...config,\n responseType:\n // If the client secret is provided then code can be used\n !config.clientSecret &&\n // When web auth is used, we can request the `id_token` directly without exchanging a code.\n isWebAuth\n ? ResponseType.IdToken\n : undefined,\n },\n { ...redirectUriOptions, useProxy }\n );\n}\n\n/**\n * Load an authorization request.\n * Returns a loaded request, a response, and a prompt method.\n * When the prompt method completes, then the response will be fulfilled.\n *\n * - [Get Started](https://docs.expo.io/guides/authentication/#google)\n *\n * @param config\n * @param redirectUriOptions\n */\nexport function useAuthRequest(\n config: Partial<GoogleAuthRequestConfig> = {},\n redirectUriOptions: Partial<AuthSessionRedirectUriOptions> = {}\n): [\n GoogleAuthRequest | null,\n AuthSessionResult | null,\n (options?: AuthRequestPromptOptions) => Promise<AuthSessionResult>\n] {\n const useProxy = useProxyEnabled(redirectUriOptions);\n\n const clientId = useMemo((): string => {\n const propertyName = useProxy\n ? 'expoClientId'\n : Platform.select({\n ios: 'iosClientId',\n android: 'androidClientId',\n default: 'webClientId',\n });\n\n const clientId = config[propertyName as any] ?? config.clientId;\n invariantClientId(propertyName, clientId, 'Google');\n return clientId;\n }, [\n useProxy,\n config.expoClientId,\n config.iosClientId,\n config.androidClientId,\n config.webClientId,\n config.clientId,\n ]);\n\n const responseType = useMemo(() => {\n // Allow overrides.\n if (typeof config.responseType !== 'undefined') {\n return config.responseType;\n }\n // You can only use `response_token=code` on installed apps (iOS, Android without proxy).\n // Installed apps can auto exchange without a client secret and get the token and id-token (Firebase).\n const isInstalledApp = Platform.OS !== 'web' && !useProxy;\n // If the user provided the client secret (they shouldn't!) then use code exchange by default.\n if (config.clientSecret || isInstalledApp) {\n return ResponseType.Code;\n }\n // This seems the most pragmatic option since it can result in a full authentication on web and proxy platforms as expected.\n return ResponseType.Token;\n }, [config.responseType, config.clientSecret, useProxy]);\n\n const redirectUri = useMemo((): string => {\n if (typeof config.redirectUri !== 'undefined') {\n return config.redirectUri;\n }\n\n return makeRedirectUri({\n native: `${Application.applicationId}:/oauthredirect`,\n useProxy,\n ...redirectUriOptions,\n // native: `com.googleusercontent.apps.${guid}:/oauthredirect`,\n });\n }, [useProxy, config.redirectUri, redirectUriOptions]);\n\n const extraParams = useMemo((): GoogleAuthRequestConfig['extraParams'] => {\n const output = config.extraParams ? { ...config.extraParams } : {};\n\n if (config.language) {\n output.hl = output.language;\n }\n if (config.loginHint) {\n output.login_hint = output.loginHint;\n }\n if (config.selectAccount) {\n output.prompt = Prompt.SelectAccount;\n }\n return output;\n }, [config.extraParams, config.language, config.loginHint, config.selectAccount]);\n\n const request = useLoadedAuthRequest(\n {\n ...config,\n responseType,\n extraParams,\n clientId,\n redirectUri,\n },\n discovery,\n GoogleAuthRequest\n );\n\n const [result, promptAsync] = useAuthRequestResult(request, discovery, {\n useProxy,\n windowFeatures: settings.windowFeatures,\n });\n\n const [fullResult, setFullResult] = useState<AuthSessionResult | null>(null);\n\n const shouldAutoExchangeCode = useMemo(() => {\n // allow overrides\n if (typeof config.shouldAutoExchangeCode !== 'undefined') {\n return config.shouldAutoExchangeCode;\n }\n\n // has a code to exchange and doesn't have an authentication yet.\n const couldAutoExchange =\n result?.type === 'success' && result.params.code && !result.authentication;\n\n return couldAutoExchange;\n }, [config.shouldAutoExchangeCode, result?.type]);\n\n useEffect(() => {\n let isMounted = true;\n if (shouldAutoExchangeCode && result?.type === 'success') {\n const exchangeRequest = new AccessTokenRequest({\n clientId,\n clientSecret: config.clientSecret,\n redirectUri,\n scopes: config.scopes,\n code: result.params.code,\n extraParams: {\n // @ts-ignore: allow for instances where PKCE is disabled\n code_verifier: request.codeVerifier,\n },\n });\n exchangeRequest.performAsync(discovery).then((authentication) => {\n if (isMounted) {\n setFullResult({\n ...result,\n params: {\n // @ts-ignore: provide a singular interface for getting the id_token across all workflows that request it.\n id_token: authentication.idToken,\n access_token: authentication.accessToken,\n ...result.params,\n },\n authentication,\n });\n }\n });\n } else {\n setFullResult(result);\n }\n return () => {\n isMounted = false;\n };\n }, [\n clientId,\n redirectUri,\n shouldAutoExchangeCode,\n config.clientSecret,\n config.scopes?.join(','),\n request?.codeVerifier,\n result,\n ]);\n\n return [request, fullResult, promptAsync];\n}\n"]}
@@ -20,8 +20,6 @@ export function invariantClientId(idName, value, providerName) {
20
20
  throw new Error(`Client Id property \`${idName}\` must be defined to use ${providerName} auth on this platform.`);
21
21
  }
22
22
  export function useProxyEnabled(redirectUriOptions) {
23
- return useMemo(() => redirectUriOptions.useProxy ?? shouldUseProxy(), [
24
- redirectUriOptions.useProxy,
25
- ]);
23
+ return useMemo(() => redirectUriOptions.useProxy ?? shouldUseProxy(), [redirectUriOptions.useProxy]);
26
24
  }
27
25
  //# sourceMappingURL=ProviderUtils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ProviderUtils.js","sourceRoot":"","sources":["../../src/providers/ProviderUtils.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAIxC,MAAM,UAAU,mBAAmB,CAAC,SAAmB,EAAE,EAAE,cAAwB;IACjF,sDAAsD;IACtD,oBAAoB;IACpB,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,MAAM,EAAE,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;AACtD,CAAC;AAED,oCAAoC;AACpC,MAAM,UAAU,cAAc;IAC5B,OAAO,QAAQ,CAAC,MAAM,CAAC;QACrB,GAAG,EAAE,KAAK;QACV,oCAAoC;QACpC,OAAO,EAAE,SAAS,CAAC,oBAAoB,KAAK,oBAAoB,CAAC,WAAW;KAC7E,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAc,EAAE,KAAU,EAAE,YAAoB;IAChF,IAAI,OAAO,KAAK,KAAK,WAAW;QAC9B,8BAA8B;QAC9B,MAAM,IAAI,KAAK,CACb,wBAAwB,MAAM,6BAA6B,YAAY,yBAAyB,CACjG,CAAC;AACN,CAAC;AAED,MAAM,UAAU,eAAe,CAC7B,kBAAmE;IAEnE,OAAO,OAAO,CAAC,GAAG,EAAE,CAAC,kBAAkB,CAAC,QAAQ,IAAI,cAAc,EAAE,EAAE;QACpE,kBAAkB,CAAC,QAAQ;KAC5B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import Constants, { ExecutionEnvironment } from 'expo-constants';\nimport { useMemo } from 'react';\nimport { Platform } from 'react-native';\n\nimport { AuthSessionRedirectUriOptions } from '../AuthSession';\n\nexport function applyRequiredScopes(scopes: string[] = [], requiredScopes: string[]): string[] {\n // Add the required scopes for returning profile data.\n // Remove duplicates\n return [...new Set([...scopes, ...requiredScopes])];\n}\n\n// Only natively in the Expo client.\nexport function shouldUseProxy(): boolean {\n return Platform.select({\n web: false,\n // Use the proxy in the Expo client.\n default: Constants.executionEnvironment === ExecutionEnvironment.StoreClient,\n });\n}\n\nexport function invariantClientId(idName: string, value: any, providerName: string) {\n if (typeof value === 'undefined')\n // TODO(Bacon): Add learn more\n throw new Error(\n `Client Id property \\`${idName}\\` must be defined to use ${providerName} auth on this platform.`\n );\n}\n\nexport function useProxyEnabled(\n redirectUriOptions: Pick<AuthSessionRedirectUriOptions, 'useProxy'>\n): boolean {\n return useMemo(() => redirectUriOptions.useProxy ?? shouldUseProxy(), [\n redirectUriOptions.useProxy,\n ]);\n}\n"]}
1
+ {"version":3,"file":"ProviderUtils.js","sourceRoot":"","sources":["../../src/providers/ProviderUtils.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAIxC,MAAM,UAAU,mBAAmB,CAAC,SAAmB,EAAE,EAAE,cAAwB;IACjF,sDAAsD;IACtD,oBAAoB;IACpB,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,MAAM,EAAE,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;AACtD,CAAC;AAED,oCAAoC;AACpC,MAAM,UAAU,cAAc;IAC5B,OAAO,QAAQ,CAAC,MAAM,CAAC;QACrB,GAAG,EAAE,KAAK;QACV,oCAAoC;QACpC,OAAO,EAAE,SAAS,CAAC,oBAAoB,KAAK,oBAAoB,CAAC,WAAW;KAC7E,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAc,EAAE,KAAU,EAAE,YAAoB;IAChF,IAAI,OAAO,KAAK,KAAK,WAAW;QAC9B,8BAA8B;QAC9B,MAAM,IAAI,KAAK,CACb,wBAAwB,MAAM,6BAA6B,YAAY,yBAAyB,CACjG,CAAC;AACN,CAAC;AAED,MAAM,UAAU,eAAe,CAC7B,kBAAmE;IAEnE,OAAO,OAAO,CACZ,GAAG,EAAE,CAAC,kBAAkB,CAAC,QAAQ,IAAI,cAAc,EAAE,EACrD,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["import Constants, { ExecutionEnvironment } from 'expo-constants';\nimport { useMemo } from 'react';\nimport { Platform } from 'react-native';\n\nimport { AuthSessionRedirectUriOptions } from '../AuthSession';\n\nexport function applyRequiredScopes(scopes: string[] = [], requiredScopes: string[]): string[] {\n // Add the required scopes for returning profile data.\n // Remove duplicates\n return [...new Set([...scopes, ...requiredScopes])];\n}\n\n// Only natively in the Expo client.\nexport function shouldUseProxy(): boolean {\n return Platform.select({\n web: false,\n // Use the proxy in the Expo client.\n default: Constants.executionEnvironment === ExecutionEnvironment.StoreClient,\n });\n}\n\nexport function invariantClientId(idName: string, value: any, providerName: string) {\n if (typeof value === 'undefined')\n // TODO(Bacon): Add learn more\n throw new Error(\n `Client Id property \\`${idName}\\` must be defined to use ${providerName} auth on this platform.`\n );\n}\n\nexport function useProxyEnabled(\n redirectUriOptions: Pick<AuthSessionRedirectUriOptions, 'useProxy'>\n): boolean {\n return useMemo(\n () => redirectUriOptions.useProxy ?? shouldUseProxy(),\n [redirectUriOptions.useProxy]\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-auth-session",
3
- "version": "3.3.1",
3
+ "version": "3.4.0",
4
4
  "description": "Expo module for browser-based authentication",
5
5
  "main": "build/AuthSession.js",
6
6
  "types": "build/AuthSession.d.ts",
@@ -32,12 +32,12 @@
32
32
  },
33
33
  "author": "650 Industries, Inc.",
34
34
  "license": "MIT",
35
- "homepage": "https://docs.expo.io/versions/latest/sdk/auth-session",
35
+ "homepage": "https://docs.expo.dev/versions/latest/sdk/auth-session",
36
36
  "dependencies": {
37
- "expo-constants": "~11.0.1",
38
- "expo-crypto": "~9.2.0",
39
- "expo-linking": "~2.3.1",
40
- "expo-web-browser": "~9.2.0",
37
+ "expo-constants": "~12.0.0",
38
+ "expo-crypto": "~10.0.0",
39
+ "expo-linking": "~2.4.0",
40
+ "expo-web-browser": "~10.0.0",
41
41
  "invariant": "^2.2.4",
42
42
  "qs": "6.9.1"
43
43
  },
@@ -56,5 +56,5 @@
56
56
  "jest": {
57
57
  "preset": "expo-module-scripts"
58
58
  },
59
- "gitHead": "7f0e39e0f45a4ade0ddb603d50983fad2e831908"
59
+ "gitHead": "1fffde73411ee7a642b98f1506a8de921805d52b"
60
60
  }
@@ -15,7 +15,7 @@ export function useAutoDiscovery(issuerOrDiscovery: IssuerOrDiscovery): Discover
15
15
 
16
16
  useEffect(() => {
17
17
  let isAllowed = true;
18
- resolveDiscoveryAsync(issuerOrDiscovery).then(discovery => {
18
+ resolveDiscoveryAsync(issuerOrDiscovery).then((discovery) => {
19
19
  if (isAllowed) {
20
20
  setDiscovery(discovery);
21
21
  }
@@ -36,9 +36,10 @@ export function useLoadedAuthRequest(
36
36
  ): AuthRequest | null {
37
37
  const [request, setRequest] = useState<AuthRequest | null>(null);
38
38
  const scopeString = useMemo(() => config.scopes?.join(','), [config.scopes]);
39
- const extraParamsString = useMemo(() => JSON.stringify(config.extraParams || {}), [
40
- config.extraParams,
41
- ]);
39
+ const extraParamsString = useMemo(
40
+ () => JSON.stringify(config.extraParams || {}),
41
+ [config.extraParams]
42
+ );
42
43
  useEffect(
43
44
  () => {
44
45
  let isMounted = true;
@@ -1,6 +1,6 @@
1
- import { Platform } from '@unimodules/core';
2
1
  import Constants, { ExecutionEnvironment } from 'expo-constants';
3
2
  import * as Linking from 'expo-linking';
3
+ import { Platform } from 'expo-modules-core';
4
4
  import { dismissAuthSession, openAuthSessionAsync } from 'expo-web-browser';
5
5
 
6
6
  import { AuthRequest } from './AuthRequest';
package/src/Errors.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CodedError } from '@unimodules/core';
1
+ import { CodedError } from 'expo-modules-core';
2
2
 
3
3
  /**
4
4
  * Server response error.
package/src/Fetch.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Platform } from '@unimodules/core';
1
+ import { Platform } from 'expo-modules-core';
2
2
  import qs from 'qs';
3
3
 
4
4
  export type Headers = Record<string, string> & {
package/src/PKCE.ts CHANGED
@@ -26,10 +26,7 @@ function convertBufferToString(buffer: Uint8Array): string {
26
26
  }
27
27
 
28
28
  function convertToUrlSafeString(b64: string): string {
29
- return b64
30
- .replace(/\+/g, '-')
31
- .replace(/\//g, '_')
32
- .replace(/=/g, '');
29
+ return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
33
30
  }
34
31
 
35
32
  export function generateRandom(size: number): string {
@@ -5,9 +5,10 @@ export function buildQueryString(input: Record<string, string>): string {
5
5
  return qs.stringify(input);
6
6
  }
7
7
 
8
- export function getQueryParams(
9
- url: string
10
- ): { errorCode: string | null; params: { [key: string]: string } } {
8
+ export function getQueryParams(url: string): {
9
+ errorCode: string | null;
10
+ params: { [key: string]: string };
11
+ } {
11
12
  const parts = url.split('#');
12
13
  const hash = parts[1];
13
14
  const partsWithoutHash = parts[0].split('?');
@@ -5,8 +5,6 @@ import { CreateURLOptions } from 'expo-linking';
5
5
  import { resolveScheme } from 'expo-linking/build/Schemes';
6
6
  import qs, { ParsedQs } from 'qs';
7
7
 
8
- const { manifest } = Constants;
9
-
10
8
  export class SessionUrlProvider {
11
9
  private static readonly BASE_URL = `https://auth.expo.io`;
12
10
  private static readonly SESSION_PATH = 'expo-auth-session';
@@ -49,7 +47,10 @@ export class SessionUrlProvider {
49
47
  }
50
48
  }
51
49
 
52
- const legacyExpoProjectId = manifest?.originalFullName || manifest?.id;
50
+ const legacyExpoProjectId =
51
+ Constants.manifest?.originalFullName ||
52
+ Constants.manifest2?.extra?.expoClient?.originalFullName ||
53
+ Constants.manifest?.id;
53
54
 
54
55
  if (!legacyExpoProjectId) {
55
56
  let nextSteps = '';
@@ -76,7 +77,8 @@ export class SessionUrlProvider {
76
77
  }
77
78
 
78
79
  private static getHostAddressQueryParams(): ParsedQs | undefined {
79
- let hostUri: string = Constants.manifest?.hostUri;
80
+ let hostUri: string | undefined =
81
+ Constants.manifest?.hostUri ?? Constants.manifest2?.extra?.expoClient?.hostUri;
80
82
  if (
81
83
  !hostUri &&
82
84
  (ExecutionEnvironment.StoreClient === Constants.executionEnvironment || resolveScheme({}))
@@ -90,6 +92,10 @@ export class SessionUrlProvider {
90
92
  }
91
93
  }
92
94
 
95
+ if (!hostUri) {
96
+ return undefined;
97
+ }
98
+
93
99
  const uriParts = hostUri?.split('?');
94
100
  try {
95
101
  return qs.parse(uriParts?.[1]);
@@ -249,8 +249,10 @@ class TokenRequest<T extends TokenRequestConfig> extends Request<T, TokenRespons
249
249
  *
250
250
  * [Section 4.1.3](https://tools.ietf.org/html/rfc6749#section-4.1.3)
251
251
  */
252
- export class AccessTokenRequest extends TokenRequest<AccessTokenRequestConfig>
253
- implements AccessTokenRequestConfig {
252
+ export class AccessTokenRequest
253
+ extends TokenRequest<AccessTokenRequestConfig>
254
+ implements AccessTokenRequestConfig
255
+ {
254
256
  readonly code: string;
255
257
  readonly redirectUri: string;
256
258
 
@@ -306,8 +308,10 @@ export class AccessTokenRequest extends TokenRequest<AccessTokenRequestConfig>
306
308
  *
307
309
  * [Section 6](https://tools.ietf.org/html/rfc6749#section-6)
308
310
  */
309
- export class RefreshTokenRequest extends TokenRequest<RefreshTokenRequestConfig>
310
- implements RefreshTokenRequestConfig {
311
+ export class RefreshTokenRequest
312
+ extends TokenRequest<RefreshTokenRequestConfig>
313
+ implements RefreshTokenRequestConfig
314
+ {
311
315
  readonly refreshToken?: string;
312
316
 
313
317
  constructor(options: RefreshTokenRequestConfig) {
@@ -343,8 +347,10 @@ export class RefreshTokenRequest extends TokenRequest<RefreshTokenRequestConfig>
343
347
  *
344
348
  * [Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1)
345
349
  */
346
- export class RevokeTokenRequest extends Request<RevokeTokenRequestConfig, boolean>
347
- implements RevokeTokenRequestConfig {
350
+ export class RevokeTokenRequest
351
+ extends Request<RevokeTokenRequestConfig, boolean>
352
+ implements RevokeTokenRequestConfig
353
+ {
348
354
  readonly clientId?: string;
349
355
  readonly clientSecret?: string;
350
356
  readonly token: string;
@@ -341,7 +341,7 @@ export function useAuthRequest(
341
341
  code_verifier: request.codeVerifier,
342
342
  },
343
343
  });
344
- exchangeRequest.performAsync(discovery).then(authentication => {
344
+ exchangeRequest.performAsync(discovery).then((authentication) => {
345
345
  if (isMounted) {
346
346
  setFullResult({
347
347
  ...result,
@@ -30,7 +30,8 @@ export function invariantClientId(idName: string, value: any, providerName: stri
30
30
  export function useProxyEnabled(
31
31
  redirectUriOptions: Pick<AuthSessionRedirectUriOptions, 'useProxy'>
32
32
  ): boolean {
33
- return useMemo(() => redirectUriOptions.useProxy ?? shouldUseProxy(), [
34
- redirectUriOptions.useProxy,
35
- ]);
33
+ return useMemo(
34
+ () => redirectUriOptions.useProxy ?? shouldUseProxy(),
35
+ [redirectUriOptions.useProxy]
36
+ );
36
37
  }