diff --git a/packages/@magic-ext/oauth/src/index.ts b/packages/@magic-ext/oauth/src/index.ts index 958bd9c7c..ed4381627 100644 --- a/packages/@magic-ext/oauth/src/index.ts +++ b/packages/@magic-ext/oauth/src/index.ts @@ -31,6 +31,34 @@ export class OAuthExtension extends Extension.Internal<'oauth'> { }); } + public loginWithRedirectV2(configuration: OAuthRedirectConfiguration) { + return this.utils.createPromiEvent(async (resolve) => { + console.log('loginWithRedirectV2', configuration); + + const parseRedirectResult = this.utils.createJsonRpcRequestPayload('magic_oauth_login_with_redirect_start', [ + { + ...configuration, + apiKey: this.sdk.apiKey, + platform: 'web', + }, + ]); + + console.log('loginWithRedirectV2: rpc payload', parseRedirectResult); + + const result = await this.request(parseRedirectResult); + + console.log('loginWithRedirectV2: rpc result', result); + + // TODO: handle error like allowlist not matching + + if (result?.oauthAuthoriationURI) { + window.location.href = result.oauthAuthoriationURI; + } + + resolve(); + }); + } + public getRedirectResult() { const queryString = window.location.search; @@ -41,6 +69,20 @@ export class OAuthExtension extends Extension.Internal<'oauth'> { return getResult.call(this, queryString); } + + public getRedirectResultV2() { + console.log('getRedirectResultV2'); + const queryString = window.location.search; + + console.log('getRedirectResultV2', queryString); + + // Remove the query from the redirect callback as a precaution to prevent + // malicious parties from parsing it before we have a chance to use it. + const urlWithoutQuery = window.location.origin + window.location.pathname; + window.history.replaceState(null, '', urlWithoutQuery); + + return getResultV2.call(this, queryString); + } } const OAUTH_REDIRECT_METADATA_KEY = 'oauth_redirect_metadata'; @@ -119,4 +161,28 @@ function getResult(this: OAuthExtension, queryString: string) { }); } +function getResultV2(this: OAuthExtension, queryString: string) { + return this.utils.createPromiEvent(async (resolve, reject) => { + const parseRedirectResult = this.utils.createJsonRpcRequestPayload('magic_oauth_parse_redirect_verify', [ + queryString, + ]); + + // Parse the result, which may contain an OAuth-formatted error. + const resultOrError = await this.request(parseRedirectResult); + const maybeResult = resultOrError as OAuthRedirectResult; + const maybeError = resultOrError as OAuthRedirectError; + + if (maybeError.error) { + reject( + this.createError(maybeError.error, maybeError.error_description ?? 'An error occurred.', { + errorURI: maybeError.error_uri, + provider: maybeError.provider, + }), + ); + } + + resolve(maybeResult); + }); +} + export * from './types';