From 8b44d71934d88b8952c7376e0fcc9c98c47093ea Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 30 Oct 2023 12:19:26 +0200 Subject: [PATCH 01/26] Just trying to show how a uniformed API can help improve the use of the library and handling error scenarios --- src/index.ts | 7 ++++--- src/types.ts | 5 +++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index 9930bcc..5525bb0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ import { sha256, trimURL, } from './utils' +import type { ApiResponse, AuthToken } from './types' // re-usable gql response fragment const userFragment = @@ -389,7 +390,7 @@ export class Authorizer { return await res.json() } - signup = async (data: Types.SignupInput): Promise => { + signup = async (data: Types.SignupInput): Promise> => { try { const res = await this.graphqlQuery({ query: ` @@ -398,9 +399,9 @@ export class Authorizer { variables: { data }, }) - return res.signup + return { ok: true, response: res.signup, error: undefined } } catch (err) { - throw new Error(err) + return { ok: false, response: undefined, error: err } } } diff --git a/src/types.ts b/src/types.ts index bfe4551..eb521b4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,8 @@ +export interface ApiResponse { + ok: boolean + error: Error | undefined + response: T | undefined +} export interface ConfigType { authorizerURL: string redirectURL: string From 7af66cc30af6b96d898c4392debec831c3611b22 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 30 Oct 2023 12:58:50 +0200 Subject: [PATCH 02/26] modify tests for signup --- __test__/index.test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/__test__/index.test.js b/__test__/index.test.js index d1b1bac..6892b91 100644 --- a/__test__/index.test.js +++ b/__test__/index.test.js @@ -17,7 +17,8 @@ describe('signup success', () => { password, confirm_password: password, }) - expect(signupRes.message.length).not.toEqual(0) + expect(signupRes?.ok).toEqual(true) + expect(signupRes?.response.message.length).not.toEqual(0) }) it('should verify email', async () => { @@ -47,7 +48,7 @@ describe('signup success', () => { const verifyEmailRes = await authRef.verifyEmail({ token: item.token }) - expect(verifyEmailRes.access_token.length).not.toEqual(0) + expect(verifyEmailRes?response.access_token.length).not.toEqual(0) }) }) From 43ff1209c1a8b40e5b8a454f9bebad212e6415d6 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 30 Oct 2023 19:04:23 +0200 Subject: [PATCH 03/26] fix with linter --- __test__/index.test.js | 1 + src/index.ts | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/__test__/index.test.js b/__test__/index.test.js index 6892b91..c2b27af 100644 --- a/__test__/index.test.js +++ b/__test__/index.test.js @@ -1,3 +1,4 @@ +// @ts-nocheck const { Authorizer } = require('../lib') const authRef = new Authorizer({ diff --git a/src/index.ts b/src/index.ts index 7021c46..089af21 100644 --- a/src/index.ts +++ b/src/index.ts @@ -421,9 +421,18 @@ export class Authorizer { variables: { data }, }) - return { ok: true, response: res.signup, error: undefined } - } catch (err) { - return { ok: false, response: undefined, error: err } + return { + ok: true, + response: res.signup, + error: undefined, + } + } + catch (err) { + return { + ok: false, + response: undefined, + error: err, + } } } From 407e979b748e88260cfe215e32f40f2b5ccb41c9 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Wed, 1 Nov 2023 16:21:17 +0200 Subject: [PATCH 04/26] modify all functions to use the unified response API --- .gitignore | 3 +- __test__/index.test.js | 59 +++++----- src/index.ts | 245 +++++++++++++++++++++++------------------ 3 files changed, 167 insertions(+), 140 deletions(-) diff --git a/.gitignore b/.gitignore index a778076..eb892a1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ node_modules dist lib -package-lock.json \ No newline at end of file +package-lock.json +.idea diff --git a/__test__/index.test.js b/__test__/index.test.js index c2b27af..7dd554a 100644 --- a/__test__/index.test.js +++ b/__test__/index.test.js @@ -19,7 +19,7 @@ describe('signup success', () => { confirm_password: password, }) expect(signupRes?.ok).toEqual(true) - expect(signupRes?.response.message.length).not.toEqual(0) + expect(signupRes?.response?.message?.length).not.toEqual(0) }) it('should verify email', async () => { @@ -49,33 +49,32 @@ describe('signup success', () => { const verifyEmailRes = await authRef.verifyEmail({ token: item.token }) - expect(verifyEmailRes?response.access_token.length).not.toEqual(0) + expect(verifyEmailRes?.response?.access_token?.length).toBeGreaterThan(0) }) }) describe('login failures', () => { it('should throw password invalid error', async () => { - try { - await authRef.login({ + + const resp= await authRef.login({ email, password: `${password}test`, }) - } catch (e) { - expect(e.message).toContain('bad user credentials') - } + + expect(resp?.error?.message).toContain('bad user credentials') }) it('should throw password invalid role', async () => { - try { - await authRef.login({ - email, - password, - roles: ['admin'], - }) - } catch (e) { - expect(e.message).toMatch('invalid role') - } + + const resp = await authRef.login({ + email, + password, + roles: ['admin'], + }) + expect(resp.error?.message).toMatch('invalid role') + expect(resp.ok).toBeFalsy() }) + }) describe('forgot password success', () => { @@ -83,7 +82,7 @@ describe('forgot password success', () => { const forgotPasswordRes = await authRef.forgotPassword({ email, }) - expect(forgotPasswordRes.message.length).not.toEqual(0) + expect(forgotPasswordRes?.error?.message?.length).not.toEqual(0) }) it('should reset password', async () => { @@ -118,7 +117,7 @@ describe('forgot password success', () => { password, confirm_password: password, }) - expect(resetPasswordRes.message.length).not.toEqual(0) + expect(resetPasswordRes?.error?.message?.length).not.toEqual(0) } }) }) @@ -131,10 +130,10 @@ describe('login success', () => { password, scope: ['openid', 'profile', 'email', 'offline_access'], }) - expect(loginRes.access_token.length).not.toEqual(0) - expect(loginRes.refresh_token.length).not.toEqual(0) - expect(loginRes.expires_in).not.toEqual(0) - expect(loginRes.id_token.length).not.toEqual(0) + expect(loginRes?.response?.access_token.length).not.toEqual(0) + expect(loginRes?.response?.refresh_token.length).not.toEqual(0) + expect(loginRes?.response?.expires_in).not.toEqual(0) + expect(loginRes?.response?.id_token.length).not.toEqual(0) }) it('should validate jwt token', async () => { @@ -142,7 +141,7 @@ describe('login success', () => { token_type: 'access_token', token: loginRes.access_token, }) - expect(validateRes.is_valid).toEqual(true) + expect(validateRes?.response?.is_valid).toEqual(true) }) it('should update profile successfully', async () => { @@ -154,14 +153,14 @@ describe('login success', () => { Authorization: `Bearer ${loginRes.access_token}`, } ) - expect(updateProfileRes.message.length).not.toEqual(0) + expect(updateProfileRes?.error?.message?.length).not.toEqual(0) }) it('should fetch profile successfully', async () => { const profileRes = await authRef.getProfile({ Authorization: `Bearer ${loginRes.access_token}`, }) - expect(profileRes.given_name).toMatch('bob') + expect(profileRes?.response?.given_name).toMatch('bob') }) it('should validate get token', async () => { @@ -169,7 +168,7 @@ describe('login success', () => { grant_type: 'refresh_token', refresh_token: loginRes.refresh_token, }) - expect(tokenRes.access_token.length).not.toEqual(0) + expect(tokenRes?.response?.access_token.length).not.toEqual(0) }) it('should deactivate account', async () => { @@ -177,15 +176,15 @@ describe('login success', () => { const deactivateRes = await authRef.deactivateAccount({ Authorization: `Bearer ${loginRes.access_token}`, }) - expect(deactivateRes.message.length).not.toEqual(0) + expect(deactivateRes?.error?.message?.length).not.toEqual(0) }) it('should throw error while accessing profile after deactivation', async () => { - await expect( + const resp=await authRef.getProfile({ Authorization: `Bearer ${loginRes.access_token}`, }) - ).rejects.toThrow('Error: unauthorized') + expect(resp?.error?.message).toEqual('Error: unauthorized') }) it('should clear data', async () => { @@ -212,7 +211,7 @@ describe('magic login success', () => { email, }) - expect(magicLinkLoginRes.message.length).not.toEqual(0) + expect(magicLinkLoginRes?.error?.message?.length).not.toEqual(0) }) it('should verify email', async () => { diff --git a/src/index.ts b/src/index.ts index 089af21..fc7d31b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,24 +12,34 @@ import { sha256, trimURL, } from './utils' -import type { ApiResponse, AuthToken } from './types' +import type { + ApiResponse, + AuthToken, + AuthorizeResponse, + ConfigType, + GetTokenResponse, + MetaData, + User, + ValidateJWTTokenResponse, ValidateSessionResponse, +} from './types' // re-usable gql response fragment const userFragment = 'id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data' -const authTokenFragment = `message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user { ${userFragment} }` +const authTokenFragment = `message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${userFragment}}` // set fetch based on window object. Cross fetch have issues with umd build const getFetcher = () => (hasWindow() ? window.fetch : crossFetch) export * from './types' + export class Authorizer { // class variable - config: Types.ConfigType + config: ConfigType codeVerifier: string // constructor - constructor(config: Types.ConfigType) { + constructor(config: ConfigType) { if (!config) throw new Error('Configuration is required') @@ -42,7 +52,8 @@ export class Authorizer { if (!config.redirectURL && !config.redirectURL.trim()) throw new Error('Invalid redirectURL') - else this.config.redirectURL = trimURL(config.redirectURL) + else + this.config.redirectURL = trimURL(config.redirectURL) this.config.extraHeaders = { ...(config.extraHeaders || {}), @@ -52,9 +63,9 @@ export class Authorizer { this.config.clientID = config.clientID.trim() } - authorize = async (data: Types.AuthorizeInput) => { + authorize = async (data: Types.AuthorizeInput): Promise | ApiResponse> => { if (!hasWindow()) - throw new Error('this feature is only supported in browser') + return this.errorResponse(new Error('this feature is only supported in browser')) const scopes = ['openid', 'profile', 'email'] if (data.use_refresh_token) @@ -83,7 +94,7 @@ export class Authorizer { if (requestData.response_mode !== 'web_message') { window.location.replace(authorizeURL) - return + return this.okResponse(undefined) } try { @@ -95,12 +106,12 @@ export class Authorizer { if (data.response_type === Types.ResponseTypes.Code) { // get token and return it - const token = await this.getToken({ code: iframeRes.code }) - return token + const tokenResp: ApiResponse = await this.getToken({ code: iframeRes.code }) + return tokenResp.ok ? this.okResponse(tokenResp.response) : this.errorResponse(tokenResp.error!) } // this includes access_token, id_token & refresh_token(optionally) - return iframeRes + return this.okResponse(iframeRes) } catch (err) { if (err.error) { @@ -111,30 +122,36 @@ export class Authorizer { ) } - throw err + return this.errorResponse(err) } } - browserLogin = async (): Promise => { + browserLogin = async (): Promise> => { try { - const token = await this.getSession() - return token + const tokenResp: ApiResponse = await this.getSession() + return tokenResp.ok ? this.okResponse(tokenResp.response) : this.errorResponse(tokenResp.error!) } catch (err) { - if (!hasWindow()) - throw new Error('browserLogin is only supported for browsers') + if (!hasWindow()) { + return { + ok: false, + response: undefined, + error: new Error('browserLogin is only supported for browsers'), + } + } window.location.replace( `${this.config.authorizerURL}/app?state=${encode( JSON.stringify(this.config), )}&redirect_uri=${this.config.redirectURL}`, ) + return this.errorResponse(err) } } forgotPassword = async ( data: Types.ForgotPasswordInput, - ): Promise => { + ): Promise> => { if (!data.state) data.state = encode(createRandomString()) @@ -142,53 +159,53 @@ export class Authorizer { data.redirect_uri = this.config.redirectURL try { - const forgotPasswordRes = await this.graphqlQuery({ + const forgotPasswordResp = await this.graphqlQuery({ query: 'mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }', variables: { data, }, }) - return forgotPasswordRes.forgot_password + return this.okResponse(forgotPasswordResp?.forgot_password) } catch (error) { - throw new Error(error) + return this.errorResponse(error) } } - getMetaData = async (): Promise => { + getMetaData = async (): Promise> => { try { const res = await this.graphqlQuery({ query: 'query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }', }) - return res.meta + return this.okResponse(res.meta) } - catch (err) { - throw new Error(err) + catch (error) { + return this.errorResponse(error) } } - getProfile = async (headers?: Types.Headers): Promise => { + getProfile = async (headers?: Types.Headers): Promise> => { try { const profileRes = await this.graphqlQuery({ query: `query { profile { ${userFragment} } }`, headers, }) - return profileRes.profile + return this.okResponse(profileRes.profile) } catch (error) { - throw new Error(error) + return this.errorResponse(error) } } - // this is used to verify / get session using cookie by default. If using nodejs pass authorization header + // this is used to verify / get session using cookie by default. If using node.js pass authorization header getSession = async ( headers?: Types.Headers, params?: Types.SessionQueryInput, - ): Promise => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: `query getSession($params: SessionQueryInput){session(params: $params) { ${authTokenFragment} } }`, @@ -197,24 +214,24 @@ export class Authorizer { params, }, }) - return res.session + return this.okResponse(res.session) } catch (err) { - throw new Error(err) + return this.errorResponse(err) } } getToken = async ( data: Types.GetTokenInput, - ): Promise => { + ): Promise> => { if (!data.grant_type) data.grant_type = 'authorization_code' if (data.grant_type === 'refresh_token' && !data.refresh_token) - throw new Error('Invalid refresh_token') + return this.errorResponse(new Error('Invalid refresh_token')) if (data.grant_type === 'authorization_code' && !this.codeVerifier) - throw new Error('Invalid code verifier') + return this.errorResponse(new Error('Invalid code verifier')) const requestData = { client_id: this.config.clientID, @@ -237,43 +254,16 @@ export class Authorizer { const json = await res.json() if (res.status >= 400) - throw new Error(json) + return this.errorResponse(new Error(json)) - return json + return this.okResponse(json) } catch (err) { - throw new Error(err) - } - } - - // helper to execute graphql queries - // takes in any query or mutation string as input - graphqlQuery = async (data: Types.GraphqlQueryInput) => { - const fetcher = getFetcher() - const res = await fetcher(`${this.config.authorizerURL}/graphql`, { - method: 'POST', - body: JSON.stringify({ - query: data.query, - variables: data.variables || {}, - }), - headers: { - ...this.config.extraHeaders, - ...(data.headers || {}), - }, - credentials: 'include', - }) - - const json = await res.json() - - if (json.errors && json.errors.length) { - console.error(json.errors) - throw new Error(json.errors[0].message) + return this.errorResponse(err) } - - return json.data } - login = async (data: Types.LoginInput): Promise => { + login = async (data: Types.LoginInput): Promise> => { try { const res = await this.graphqlQuery({ query: ` @@ -282,29 +272,30 @@ export class Authorizer { variables: { data }, }) - return res.login + return this.okResponse(res.login) } catch (err) { - throw new Error(err) + return this.errorResponse(new Error(err)) } } - logout = async (headers?: Types.Headers): Promise => { + logout = async (headers?: Types.Headers): Promise> => { try { const res = await this.graphqlQuery({ query: ' mutation { logout { message } } ', headers, }) - return res.logout + return this.okResponse(res.response) } catch (err) { console.error(err) + return this.errorResponse(err) } } magicLinkLogin = async ( data: Types.MagicLinkLoginInput, - ): Promise => { + ): Promise> => { try { if (!data.state) data.state = encode(createRandomString()) @@ -319,10 +310,10 @@ export class Authorizer { variables: { data }, }) - return res.magic_link_login + return this.okResponse(res.magic_link_login) } catch (err) { - throw new Error(err) + return this.errorResponse(err) } } @@ -359,7 +350,7 @@ export class Authorizer { resendOtp = async ( data: Types.ResendOtpInput, - ): Promise => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: ` @@ -368,16 +359,16 @@ export class Authorizer { variables: { data }, }) - return res.resend_otp + return this.okResponse(res.resend_otp) } catch (err) { - throw new Error(err) + return this.errorResponse(err) } } resetPassword = async ( data: Types.ResetPasswordInput, - ): Promise => { + ): Promise> => { try { const resetPasswordRes = await this.graphqlQuery({ query: @@ -386,16 +377,16 @@ export class Authorizer { data, }, }) - return resetPasswordRes.reset_password + return this.okResponse(resetPasswordRes.reset_password) } catch (error) { - throw new Error(error) + return this.errorResponse(error) } } revokeToken = async (data: { refresh_token: string }) => { if (!data.refresh_token && !data.refresh_token.trim()) - throw new Error('Invalid refresh_token') + return this.errorResponse(new Error('Invalid refresh_token')) const fetcher = getFetcher() const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, { @@ -409,7 +400,8 @@ export class Authorizer { }), }) - return await res.json() + const responseData = await res.json() + return this.okResponse(responseData) } signup = async (data: Types.SignupInput): Promise> => { @@ -421,25 +413,17 @@ export class Authorizer { variables: { data }, }) - return { - ok: true, - response: res.signup, - error: undefined, - } + return this.okResponse(res.signup) } catch (err) { - return { - ok: false, - response: undefined, - error: err, - } + return this.errorResponse(err) } } updateProfile = async ( data: Types.UpdateProfileInput, headers?: Types.Headers, - ): Promise => { + ): Promise> => { try { const updateProfileRes = await this.graphqlQuery({ query: @@ -450,31 +434,31 @@ export class Authorizer { }, }) - return updateProfileRes.update_profile + return this.okResponse(updateProfileRes.update_profile) } catch (error) { - throw new Error(error) + return this.errorResponse(new Error(error)) } } deactivateAccount = async ( headers?: Types.Headers, - ): Promise => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: 'mutation deactivateAccount { deactivate_account { message } }', headers, }) - return res.deactivate_account + return this.okResponse(res.deactivate_account) } catch (error) { - throw new Error(error) + return this.errorResponse(error) } } validateJWTToken = async ( params?: Types.ValidateJWTTokenInput, - ): Promise => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: @@ -484,16 +468,16 @@ export class Authorizer { }, }) - return res.validate_jwt_token + return this.okResponse(res.validate_jwt_token) } catch (error) { - throw new Error(error) + return this.errorResponse(error) } } validateSession = async ( params?: Types.ValidateSessionInput, - ): Promise => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: @@ -503,16 +487,16 @@ export class Authorizer { }, }) - return res.validate_session + return this.okResponse(res.validate_session) } catch (error) { - throw new Error(error) + return this.errorResponse(error) } } verifyEmail = async ( data: Types.VerifyEmailInput, - ): Promise => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: ` @@ -521,16 +505,16 @@ export class Authorizer { variables: { data }, }) - return res.verify_email + return this.okResponse(res.verify_email) } catch (err) { - throw new Error(err) + return this.errorResponse(err) } } verifyOtp = async ( data: Types.VerifyOtpInput, - ): Promise => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: ` @@ -539,10 +523,53 @@ export class Authorizer { variables: { data }, }) - return res.verify_otp + return this.okResponse(res.verify_otp) } catch (err) { - throw new Error(err) + return this.errorResponse(err) + } + } + + // helper to execute graphql queries + // takes in any query or mutation string as input + private graphqlQuery = async (data: Types.GraphqlQueryInput) => { + const fetcher = getFetcher() + const res = await fetcher(`${this.config.authorizerURL}/graphql`, { + method: 'POST', + body: JSON.stringify({ + query: data.query, + variables: data.variables || {}, + }), + headers: { + ...this.config.extraHeaders, + ...(data.headers || {}), + }, + credentials: 'include', + }) + + const json = await res.json() + + if (json.errors && json.errors.length) { + console.error(json.errors) + throw new Error(json.errors[0].message) + } + + return json.data + } + + private errorResponse = (error: Error): ApiResponse => { + return { + ok: false, + response: undefined, + error, + } + } + + private okResponse = (response: any): ApiResponse => { + return { + ok: true, + response, + error: undefined, } } } From 042a42b680d9721f22622ec818e2072e61af4796 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 14:30:40 +0200 Subject: [PATCH 05/26] bump version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index c2bf7bd..be6b570 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@authorizerdev/authorizer-js", - "version": "1.2.11", + "version": "2.2.11", "packageManager": "pnpm@7.28.0", "author": "Lakhan Samani", "license": "MIT", From 3d56ab57b8b15521e7e0b09803e1d22a671936ab Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 14:50:03 +0200 Subject: [PATCH 06/26] update clashing response name --- package.json | 2 +- src/types.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index be6b570..32ec490 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@authorizerdev/authorizer-js", - "version": "2.2.11", + "version": "2.2.12", "packageManager": "pnpm@7.28.0", "author": "Lakhan Samani", "license": "MIT", diff --git a/src/types.ts b/src/types.ts index f3f8286..3eb1257 100644 --- a/src/types.ts +++ b/src/types.ts @@ -43,7 +43,7 @@ export interface AuthToken { should_show_mobile_otp_screen?: boolean } -export interface Response { +export interface GenericResponse { message: string } From 8882921ea8314c61eedbbcdf016dab561a8cac6e Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 14:50:03 +0200 Subject: [PATCH 07/26] update clashing response name # Conflicts: # package.json --- src/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/types.ts b/src/types.ts index f3f8286..3eb1257 100644 --- a/src/types.ts +++ b/src/types.ts @@ -43,7 +43,7 @@ export interface AuthToken { should_show_mobile_otp_screen?: boolean } -export interface Response { +export interface GenericResponse { message: string } From 5340f1c00e5501120d028fb539487fc930b8bcfb Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:11:39 +0200 Subject: [PATCH 08/26] updated tests --- __test__/index.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/__test__/index.test.js b/__test__/index.test.js index 7dd554a..0e2be15 100644 --- a/__test__/index.test.js +++ b/__test__/index.test.js @@ -158,7 +158,7 @@ describe('login success', () => { it('should fetch profile successfully', async () => { const profileRes = await authRef.getProfile({ - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, }) expect(profileRes?.response?.given_name).toMatch('bob') }) From 9c47fc4cb2706a5fb815ebe5b717b66d7952f748 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:11:39 +0200 Subject: [PATCH 09/26] updated tests --- __test__/index.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/__test__/index.test.js b/__test__/index.test.js index 7dd554a..0e2be15 100644 --- a/__test__/index.test.js +++ b/__test__/index.test.js @@ -158,7 +158,7 @@ describe('login success', () => { it('should fetch profile successfully', async () => { const profileRes = await authRef.getProfile({ - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, }) expect(profileRes?.response?.given_name).toMatch('bob') }) From e849bc669f7159b69a911abc30d8ddec5de0b170 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:15:46 +0200 Subject: [PATCH 10/26] update Response to genericResponse, to differentiate from the Http Response Object --- src/index.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index 18a3d99..f847329 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,7 +20,7 @@ import type { GetTokenResponse, MetaData, User, - ValidateJWTTokenResponse, ValidateSessionResponse, + ValidateJWTTokenResponse, ValidateSessionResponse, GenericResponse } from './types' // re-usable gql response fragment @@ -350,7 +350,7 @@ export class Authorizer { resendOtp = async ( data: Types.ResendOtpInput, - ): Promise> => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: ` @@ -368,7 +368,7 @@ export class Authorizer { resetPassword = async ( data: Types.ResetPasswordInput, - ): Promise> => { + ): Promise> => { try { const resetPasswordRes = await this.graphqlQuery({ query: @@ -423,7 +423,7 @@ export class Authorizer { updateProfile = async ( data: Types.UpdateProfileInput, headers?: Types.Headers, - ): Promise> => { + ): Promise> => { try { const updateProfileRes = await this.graphqlQuery({ query: @@ -443,7 +443,7 @@ export class Authorizer { deactivateAccount = async ( headers?: Types.Headers, - ): Promise> => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: 'mutation deactivateAccount { deactivate_account { message } }', From 85d7d423f463608149411dbdab4e9e5a4fd39da9 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:15:46 +0200 Subject: [PATCH 11/26] update Response to genericResponse, to differentiate from the Http Response Object --- src/index.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index 18a3d99..f847329 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,7 +20,7 @@ import type { GetTokenResponse, MetaData, User, - ValidateJWTTokenResponse, ValidateSessionResponse, + ValidateJWTTokenResponse, ValidateSessionResponse, GenericResponse } from './types' // re-usable gql response fragment @@ -350,7 +350,7 @@ export class Authorizer { resendOtp = async ( data: Types.ResendOtpInput, - ): Promise> => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: ` @@ -368,7 +368,7 @@ export class Authorizer { resetPassword = async ( data: Types.ResetPasswordInput, - ): Promise> => { + ): Promise> => { try { const resetPasswordRes = await this.graphqlQuery({ query: @@ -423,7 +423,7 @@ export class Authorizer { updateProfile = async ( data: Types.UpdateProfileInput, headers?: Types.Headers, - ): Promise> => { + ): Promise> => { try { const updateProfileRes = await this.graphqlQuery({ query: @@ -443,7 +443,7 @@ export class Authorizer { deactivateAccount = async ( headers?: Types.Headers, - ): Promise> => { + ): Promise> => { try { const res = await this.graphqlQuery({ query: 'mutation deactivateAccount { deactivate_account { message } }', From e33b6845c60450ae2578cdad39f041d5593bf120 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:21:08 +0200 Subject: [PATCH 12/26] update test --- __test__/index.test.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/__test__/index.test.js b/__test__/index.test.js index 0e2be15..a786356 100644 --- a/__test__/index.test.js +++ b/__test__/index.test.js @@ -139,7 +139,7 @@ describe('login success', () => { it('should validate jwt token', async () => { const validateRes = await authRef.validateJWTToken({ token_type: 'access_token', - token: loginRes.access_token, + token: loginRes?.response?.access_token, }) expect(validateRes?.response?.is_valid).toEqual(true) }) @@ -150,7 +150,7 @@ describe('login success', () => { given_name: 'bob', }, { - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, } ) expect(updateProfileRes?.error?.message?.length).not.toEqual(0) @@ -166,15 +166,15 @@ describe('login success', () => { it('should validate get token', async () => { const tokenRes = await authRef.getToken({ grant_type: 'refresh_token', - refresh_token: loginRes.refresh_token, + refresh_token: loginRes?.response?.refresh_token, }) expect(tokenRes?.response?.access_token.length).not.toEqual(0) }) it('should deactivate account', async () => { - console.log(`loginRes.access_token`, loginRes.access_token) + console.log(`loginRes?.response?.access_token`, loginRes?.response?.access_token) const deactivateRes = await authRef.deactivateAccount({ - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, }) expect(deactivateRes?.error?.message?.length).not.toEqual(0) }) @@ -182,7 +182,7 @@ describe('login success', () => { it('should throw error while accessing profile after deactivation', async () => { const resp=await authRef.getProfile({ - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, }) expect(resp?.error?.message).toEqual('Error: unauthorized') }) From 27c5f83516a6373ed114a4b520da02dfe8e89a9d Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:21:08 +0200 Subject: [PATCH 13/26] update test --- __test__/index.test.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/__test__/index.test.js b/__test__/index.test.js index 0e2be15..a786356 100644 --- a/__test__/index.test.js +++ b/__test__/index.test.js @@ -139,7 +139,7 @@ describe('login success', () => { it('should validate jwt token', async () => { const validateRes = await authRef.validateJWTToken({ token_type: 'access_token', - token: loginRes.access_token, + token: loginRes?.response?.access_token, }) expect(validateRes?.response?.is_valid).toEqual(true) }) @@ -150,7 +150,7 @@ describe('login success', () => { given_name: 'bob', }, { - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, } ) expect(updateProfileRes?.error?.message?.length).not.toEqual(0) @@ -166,15 +166,15 @@ describe('login success', () => { it('should validate get token', async () => { const tokenRes = await authRef.getToken({ grant_type: 'refresh_token', - refresh_token: loginRes.refresh_token, + refresh_token: loginRes?.response?.refresh_token, }) expect(tokenRes?.response?.access_token.length).not.toEqual(0) }) it('should deactivate account', async () => { - console.log(`loginRes.access_token`, loginRes.access_token) + console.log(`loginRes?.response?.access_token`, loginRes?.response?.access_token) const deactivateRes = await authRef.deactivateAccount({ - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, }) expect(deactivateRes?.error?.message?.length).not.toEqual(0) }) @@ -182,7 +182,7 @@ describe('login success', () => { it('should throw error while accessing profile after deactivation', async () => { const resp=await authRef.getProfile({ - Authorization: `Bearer ${loginRes.access_token}`, + Authorization: `Bearer ${loginRes?.response?.access_token}`, }) expect(resp?.error?.message).toEqual('Error: unauthorized') }) From efcd2e98658f2e4f427dcc176309fdf396e17dee Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:23:19 +0200 Subject: [PATCH 14/26] bump --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 32ec490..1e1f9b3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@authorizerdev/authorizer-js", - "version": "2.2.12", + "version": "2.2.13", "packageManager": "pnpm@7.28.0", "author": "Lakhan Samani", "license": "MIT", From 610c26e8efd7655c8d409411d9175b6259ba0508 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:25:43 +0200 Subject: [PATCH 15/26] change Response to GenericResponse in Api methods --- src/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index f847329..011d265 100644 --- a/src/index.ts +++ b/src/index.ts @@ -151,7 +151,7 @@ export class Authorizer { forgotPassword = async ( data: Types.ForgotPasswordInput, - ): Promise> => { + ): Promise> => { if (!data.state) data.state = encode(createRandomString()) @@ -279,7 +279,7 @@ export class Authorizer { } } - logout = async (headers?: Types.Headers): Promise> => { + logout = async (headers?: Types.Headers): Promise> => { try { const res = await this.graphqlQuery({ query: ' mutation { logout { message } } ', @@ -295,7 +295,7 @@ export class Authorizer { magicLinkLogin = async ( data: Types.MagicLinkLoginInput, - ): Promise> => { + ): Promise> => { try { if (!data.state) data.state = encode(createRandomString()) From 5d423d4376b29c8e495c1a4a87c8600b207dc125 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:25:43 +0200 Subject: [PATCH 16/26] change Response to GenericResponse in Api methods --- src/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index f847329..011d265 100644 --- a/src/index.ts +++ b/src/index.ts @@ -151,7 +151,7 @@ export class Authorizer { forgotPassword = async ( data: Types.ForgotPasswordInput, - ): Promise> => { + ): Promise> => { if (!data.state) data.state = encode(createRandomString()) @@ -279,7 +279,7 @@ export class Authorizer { } } - logout = async (headers?: Types.Headers): Promise> => { + logout = async (headers?: Types.Headers): Promise> => { try { const res = await this.graphqlQuery({ query: ' mutation { logout { message } } ', @@ -295,7 +295,7 @@ export class Authorizer { magicLinkLogin = async ( data: Types.MagicLinkLoginInput, - ): Promise> => { + ): Promise> => { try { if (!data.state) data.state = encode(createRandomString()) From 251b6c4223eab72170446ec158e446c862615e4b Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 3 Nov 2023 15:28:44 +0200 Subject: [PATCH 17/26] include lib in github branch use --- .gitignore | 2 +- lib/authorizer.min.js | 14 +++ lib/constants.d.ts | 3 + lib/index.d.ts | 34 +++++++ lib/index.js | 13 +++ lib/index.mjs | 13 +++ lib/types.d.ts | 205 ++++++++++++++++++++++++++++++++++++++++++ lib/utils.d.ts | 13 +++ 8 files changed, 296 insertions(+), 1 deletion(-) create mode 100644 lib/authorizer.min.js create mode 100644 lib/constants.d.ts create mode 100644 lib/index.d.ts create mode 100644 lib/index.js create mode 100644 lib/index.mjs create mode 100644 lib/types.d.ts create mode 100644 lib/utils.d.ts diff --git a/.gitignore b/.gitignore index eb892a1..ec8a0e0 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,6 @@ .DS_Store node_modules dist -lib + package-lock.json .idea diff --git a/lib/authorizer.min.js b/lib/authorizer.min.js new file mode 100644 index 0000000..61117fc --- /dev/null +++ b/lib/authorizer.min.js @@ -0,0 +1,14 @@ +var authorizerdev=(()=>{var le=Object.create;var U=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,we=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var j=(o,e,t)=>e in o?U(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,A=(o,e)=>{for(var t in e||(e={}))G.call(e,t)&&j(o,t,e[t]);if(J)for(var t of J(e))be.call(e,t)&&j(o,t,e[t]);return o},W=(o,e)=>ye(o,_e(e)),n=(o,e)=>U(o,"name",{value:e,configurable:!0});var Re=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ve=(o,e)=>{for(var t in e)U(o,t,{get:e[t],enumerable:!0})},Z=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of ge(e))!G.call(o,c)&&c!==t&&U(o,c,{get:()=>e[c],enumerable:!(i=me(e,c))||i.enumerable});return o};var Ee=(o,e,t)=>(t=o!=null?le(we(o)):{},Z(e||!o||!o.__esModule?U(t,"default",{value:o,enumerable:!0}):t,o)),Te=o=>Z(U({},"__esModule",{value:!0}),o);var f=(o,e,t)=>(j(o,typeof e!="symbol"?e+"":e,t),t);var d=(o,e,t)=>new Promise((i,c)=>{var u=w=>{try{g(t.next(w))}catch(m){c(m)}},_=w=>{try{g(t.throw(w))}catch(m){c(m)}},g=w=>w.done?i(w.value):Promise.resolve(w.value).then(u,_);g((t=t.apply(o,e)).next())});var Y=Re((R,K)=>{var X=typeof self!="undefined"?self:R,$=function(){function o(){this.fetch=!1,this.DOMException=X.DOMException}return n(o,"F"),o.prototype=X,new o}();(function(o){var e=function(t){var i={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(r){return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function c(r){return r&&DataView.prototype.isPrototypeOf(r)}if(n(c,"isDataView"),i.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],_=ArrayBuffer.isView||function(r){return r&&u.indexOf(Object.prototype.toString.call(r))>-1};function g(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(r))throw new TypeError("Invalid character in header field name");return r.toLowerCase()}n(g,"normalizeName");function w(r){return typeof r!="string"&&(r=String(r)),r}n(w,"normalizeValue");function m(r){var s={next:function(){var a=r.shift();return{done:a===void 0,value:a}}};return i.iterable&&(s[Symbol.iterator]=function(){return s}),s}n(m,"iteratorFor");function p(r){this.map={},r instanceof p?r.forEach(function(s,a){this.append(a,s)},this):Array.isArray(r)?r.forEach(function(s){this.append(s[0],s[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(s){this.append(s,r[s])},this)}n(p,"Headers"),p.prototype.append=function(r,s){r=g(r),s=w(s);var a=this.map[r];this.map[r]=a?a+", "+s:s},p.prototype.delete=function(r){delete this.map[g(r)]},p.prototype.get=function(r){return r=g(r),this.has(r)?this.map[r]:null},p.prototype.has=function(r){return this.map.hasOwnProperty(g(r))},p.prototype.set=function(r,s){this.map[g(r)]=w(s)},p.prototype.forEach=function(r,s){for(var a in this.map)this.map.hasOwnProperty(a)&&r.call(s,this.map[a],a,this)},p.prototype.keys=function(){var r=[];return this.forEach(function(s,a){r.push(a)}),m(r)},p.prototype.values=function(){var r=[];return this.forEach(function(s){r.push(s)}),m(r)},p.prototype.entries=function(){var r=[];return this.forEach(function(s,a){r.push([a,s])}),m(r)},i.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function D(r){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}n(D,"consumed");function N(r){return new Promise(function(s,a){r.onload=function(){s(r.result)},r.onerror=function(){a(r.error)}})}n(N,"fileReaderReady");function ie(r){var s=new FileReader,a=N(s);return s.readAsArrayBuffer(r),a}n(ie,"readBlobAsArrayBuffer");function ae(r){var s=new FileReader,a=N(s);return s.readAsText(r),a}n(ae,"readBlobAsText");function ce(r){for(var s=new Uint8Array(r),a=new Array(s.length),y=0;y-1?s:r}n(he,"normalizeMethod");function E(r,s){s=s||{};var a=s.body;if(r instanceof E){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,s.headers||(this.headers=new p(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!a&&r._bodyInit!=null&&(a=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=s.credentials||this.credentials||"same-origin",(s.headers||!this.headers)&&(this.headers=new p(s.headers)),this.method=he(s.method||this.method||"GET"),this.mode=s.mode||this.mode||null,this.signal=s.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}n(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function fe(r){var s=new FormData;return r.trim().split("&").forEach(function(a){if(a){var y=a.split("="),l=y.shift().replace(/\+/g," "),h=y.join("=").replace(/\+/g," ");s.append(decodeURIComponent(l),decodeURIComponent(h))}}),s}n(fe,"decode");function de(r){var s=new p,a=r.replace(/\r?\n[\t ]+/g," ");return a.split(/\r?\n/).forEach(function(y){var l=y.split(":"),h=l.shift().trim();if(h){var x=l.join(":").trim();s.append(h,x)}}),s}n(de,"parseHeaders"),V.call(E.prototype);function b(r,s){s||(s={}),this.type="default",this.status=s.status===void 0?200:s.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in s?s.statusText:"OK",this.headers=new p(s.headers),this.url=s.url||"",this._initBody(r)}n(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var r=new b(null,{status:0,statusText:""});return r.type="error",r};var pe=[301,302,303,307,308];b.redirect=function(r,s){if(pe.indexOf(s)===-1)throw new RangeError("Invalid status code");return new b(null,{status:s,headers:{location:r}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(r){t.DOMException=function(s,a){this.message=s,this.name=a;var y=Error(s);this.stack=y.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function P(r,s){return new Promise(function(a,y){var l=new E(r,s);if(l.signal&&l.signal.aborted)return y(new t.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function x(){h.abort()}n(x,"abortXhr"),h.onload=function(){var L={status:h.status,statusText:h.statusText,headers:de(h.getAllResponseHeaders()||"")};L.url="responseURL"in h?h.responseURL:L.headers.get("X-Request-URL");var C="response"in h?h.response:h.responseText;a(new b(C,L))},h.onerror=function(){y(new TypeError("Network request failed"))},h.ontimeout=function(){y(new TypeError("Network request failed"))},h.onabort=function(){y(new t.DOMException("Aborted","AbortError"))},h.open(l.method,l.url,!0),l.credentials==="include"?h.withCredentials=!0:l.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&i.blob&&(h.responseType="blob"),l.headers.forEach(function(L,C){h.setRequestHeader(C,L)}),l.signal&&(l.signal.addEventListener("abort",x),h.onreadystatechange=function(){h.readyState===4&&l.signal.removeEventListener("abort",x)}),h.send(typeof l._bodyInit=="undefined"?null:l._bodyInit)})}return n(P,"fetch"),P.polyfill=!0,o.fetch||(o.fetch=P,o.Headers=p,o.Request=E,o.Response=b),t.Headers=p,t.Request=E,t.Response=b,t.fetch=P,Object.defineProperty(t,"__esModule",{value:!0}),t}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var O=$;R=O.fetch;R.default=O.fetch;R.fetch=O.fetch;R.Headers=O.Headers;R.Request=O.Request;R.Response=O.Response;K.exports=R});var Ie={};ve(Ie,{Authorizer:()=>B,OAuthProviders:()=>S,ResponseTypes:()=>I});var ne=Ee(Y());var S;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin"})(S||(S={}));var I;(function(o){o.Code="code",o.Token="token"})(I||(I={}));var T=n(()=>typeof window!="undefined","hasWindow"),M=n(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=n(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=n(()=>{let o=ee();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),k=n(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=ee();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(c=>e+=o[c%o.length]),e},"createRandomString"),v=n(o=>T()?btoa(o):Buffer.from(o).toString("base64"),"encode");var re=n(o=>Object.keys(o).filter(e=>typeof o[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),te=n(o=>d(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,i)=>{e.oncomplete=c=>{t(c.target.result)},e.onerror=c=>{i(c.error)},e.onabort=()=>{i(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Oe=n(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var oe=n(o=>{let e=new Uint8Array(o);return Oe(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),se=n((o,e,t=60)=>new Promise((i,c)=>{let u=window.document.createElement("iframe");u.setAttribute("id","authorizer-iframe"),u.setAttribute("width","0"),u.setAttribute("height","0"),u.style.display="none";let _,g=n(()=>{window.document.body.contains(u)&&(window.document.body.removeChild(u),window.removeEventListener("message",_,!1))},"removeIframe"),w=setTimeout(()=>{g()},t*1e3);_=n(function(m){if(m.origin!==e||!m.data||!m.data.response)return;let p=m.source;p&&p.close(),m.data.response.error?c(m.data.response):i(m.data.response),clearTimeout(w),window.removeEventListener("message",_,!1),setTimeout(g,2*1e3)},"iframeEventHandler"),window.addEventListener("message",_,!1),window.document.body.appendChild(u),u.setAttribute("src",o)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",q=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${H}}`,z=n(()=>T()?window.fetch:ne.default,"getFetcher"),B=class{constructor(e){f(this,"authorize",n(e=>d(this,null,function*(){if(!T())return this.errorResponse(new Error("this feature is only supported in browser"));let t=["openid","profile","email"];e.use_refresh_token&&t.push("offline_access");let i={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(k()),nonce:v(k()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===I.Code){this.codeVerifier=k();let u=yield te(this.codeVerifier),_=oe(u);i.code_challenge=_}let c=`${this.config.authorizerURL}/authorize?${re(i)}`;if(i.response_mode!=="web_message")return window.location.replace(c),this.okResponse(void 0);try{let u=yield se(c,this.config.authorizerURL,60);if(e.response_type===I.Code){let _=yield this.getToken({code:u.code});return _.ok?this.okResponse(_.response):this.errorResponse(_.error)}return this.okResponse(u)}catch(u){return u.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(u)}}),"authorize"));f(this,"browserLogin",n(()=>d(this,null,function*(){try{let e=yield this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}}),"browserLogin"));f(this,"forgotPassword",n(e=>d(this,null,function*(){e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let t=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(t==null?void 0:t.forgot_password)}catch(t){return this.errorResponse(t)}}),"forgotPassword"));f(this,"getMetaData",n(()=>d(this,null,function*(){try{let e=yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}}),"getMetaData"));f(this,"getProfile",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e});return this.okResponse(t.profile)}catch(t){return this.errorResponse(t)}}),"getProfile"));f(this,"getSession",n((e,t)=>d(this,null,function*(){try{let i=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${q} } }`,headers:e,variables:{params:t}});return this.okResponse(i.session)}catch(i){return this.errorResponse(i)}}),"getSession"));f(this,"getToken",n(e=>d(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let c=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:A({},this.config.extraHeaders),credentials:"include"}),u=yield c.json();return c.status>=400?this.errorResponse(new Error(u)):this.okResponse(u)}catch(i){return this.errorResponse(i)}}),"getToken"));f(this,"login",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation login($data: LoginInput!) { login(params: $data) { ${q}}} + `,variables:{data:e}});return this.okResponse(t.login)}catch(t){return this.errorResponse(new Error(t))}}),"login"));f(this,"logout",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(t.response)}catch(t){return console.error(t),this.errorResponse(t)}}),"logout"));f(this,"magicLinkLogin",n(e=>d(this,null,function*(){try{e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let t=yield this.graphqlQuery({query:` + mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} + `,variables:{data:e}});return this.okResponse(t.magic_link_login)}catch(t){return this.errorResponse(t)}}),"magicLinkLogin"));f(this,"oauthLogin",n((e,t,i,c)=>d(this,null,function*(){let u=c;if(u||(u=v(k())),!Object.values(S).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!T())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(u+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${i||this.config.redirectURL}&state=${u}`)}),"oauthLogin"));f(this,"resendOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} + `,variables:{data:e}});return this.okResponse(t.resend_otp)}catch(t){return this.errorResponse(t)}}),"resendOtp"));f(this,"resetPassword",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(t.reset_password)}catch(t){return this.errorResponse(t)}}),"resetPassword"));f(this,"revokeToken",n(e=>d(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let c=yield(yield z()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:A({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(c)}),"revokeToken"));f(this,"signup",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation signup($data: SignUpInput!) { signup(params: $data) { ${q}}} + `,variables:{data:e}});return this.okResponse(t.signup)}catch(t){return this.errorResponse(t)}}),"signup"));f(this,"updateProfile",n((e,t)=>d(this,null,function*(){try{let i=yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:e}});return this.okResponse(i.update_profile)}catch(i){return this.errorResponse(new Error(i))}}),"updateProfile"));f(this,"deactivateAccount",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(t.deactivate_account)}catch(t){return this.errorResponse(t)}}),"deactivateAccount"));f(this,"validateJWTToken",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(t.validate_jwt_token)}catch(t){return this.errorResponse(t)}}),"validateJWTToken"));f(this,"validateSession",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${H} } } }`,variables:{params:e}});return this.okResponse(t.validate_session)}catch(t){return this.errorResponse(t)}}),"validateSession"));f(this,"verifyEmail",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${q}}} + `,variables:{data:e}});return this.okResponse(t.verify_email)}catch(t){return this.errorResponse(t)}}),"verifyEmail"));f(this,"verifyOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${q}}} + `,variables:{data:e}});return this.okResponse(t.verify_otp)}catch(t){return this.errorResponse(t)}}),"verifyOtp"));f(this,"graphqlQuery",n(e=>d(this,null,function*(){let c=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:A(A({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();if(c.errors&&c.errors.length)throw console.error(c.errors),new Error(c.errors[0].message);return c.data}),"graphqlQuery"));f(this,"errorResponse",n(e=>({ok:!1,response:void 0,error:e}),"errorResponse"));f(this,"okResponse",n(e=>({ok:!0,response:e,error:void 0}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=M(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=M(e.redirectURL),this.config.extraHeaders=W(A({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};n(B,"Authorizer");return Te(Ie);})(); +window.__TAURI__ = authorizerdev diff --git a/lib/constants.d.ts b/lib/constants.d.ts new file mode 100644 index 0000000..f300904 --- /dev/null +++ b/lib/constants.d.ts @@ -0,0 +1,3 @@ +export declare const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60; +export declare const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2; +export declare const AUTHORIZE_IFRAME_TIMEOUT = 5; diff --git a/lib/index.d.ts b/lib/index.d.ts new file mode 100644 index 0000000..17c4e88 --- /dev/null +++ b/lib/index.d.ts @@ -0,0 +1,34 @@ +import * as Types from './types'; +import type { ApiResponse, AuthToken, AuthorizeResponse, ConfigType, GetTokenResponse, MetaData, User, ValidateJWTTokenResponse, ValidateSessionResponse, GenericResponse } from './types'; +export * from './types'; +export declare class Authorizer { + config: ConfigType; + codeVerifier: string; + constructor(config: ConfigType); + authorize: (data: Types.AuthorizeInput) => Promise | ApiResponse>; + browserLogin: () => Promise>; + forgotPassword: (data: Types.ForgotPasswordInput) => Promise>; + getMetaData: () => Promise>; + getProfile: (headers?: Types.Headers) => Promise>; + getSession: (headers?: Types.Headers, params?: Types.SessionQueryInput) => Promise>; + getToken: (data: Types.GetTokenInput) => Promise>; + login: (data: Types.LoginInput) => Promise>; + logout: (headers?: Types.Headers) => Promise>; + magicLinkLogin: (data: Types.MagicLinkLoginInput) => Promise>; + oauthLogin: (oauthProvider: string, roles?: string[], redirect_uri?: string, state?: string) => Promise; + resendOtp: (data: Types.ResendOtpInput) => Promise>; + resetPassword: (data: Types.ResetPasswordInput) => Promise>; + revokeToken: (data: { + refresh_token: string; + }) => Promise>; + signup: (data: Types.SignupInput) => Promise>; + updateProfile: (data: Types.UpdateProfileInput, headers?: Types.Headers) => Promise>; + deactivateAccount: (headers?: Types.Headers) => Promise>; + validateJWTToken: (params?: Types.ValidateJWTTokenInput) => Promise>; + validateSession: (params?: Types.ValidateSessionInput) => Promise>; + verifyEmail: (data: Types.VerifyEmailInput) => Promise>; + verifyOtp: (data: Types.VerifyOtpInput) => Promise>; + private graphqlQuery; + private errorResponse; + private okResponse; +} diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..58f8c13 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,13 @@ +var S=Object.create;var l=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var i=(t,e)=>l(t,"name",{value:e,configurable:!0});var z=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},v=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of x(e))!A.call(t,s)&&s!==r&&l(t,s,{get:()=>e[s],enumerable:!(o=O(e,s))||o.enumerable});return t};var Q=(t,e,r)=>(r=t!=null?S(C(t)):{},v(e||!t||!t.__esModule?l(r,"default",{value:t,enumerable:!0}):r,t)),D=t=>v(l({},"__esModule",{value:!0}),t);var H={};z(H,{Authorizer:()=>g,OAuthProviders:()=>f,ResponseTypes:()=>d});module.exports=D(H);var I=Q(require("cross-fetch"));var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),y=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),U=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),j=i(()=>{let t=U();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=U();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(s=>e+=t[s%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var $=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),E=i(async t=>{let e=j().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,o)=>{e.oncomplete=s=>{r(s.target.result)},e.onerror=s=>{o(s.error)},e.onabort=()=>{o(new Error("The digest operation was aborted"))}}):await e},"sha256"),F=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var T=i(t=>{let e=new Uint8Array(t);return F(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),L=i((t,e,r=60)=>new Promise((o,s)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a,b=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",a,!1))},"removeIframe"),q=setTimeout(()=>{b()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let k=u.source;k&&k.close(),u.data.response.error?s(u.data.response):o(u.data.response),clearTimeout(q),window.removeEventListener("message",a,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(n),n.setAttribute("src",t)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",_=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${R}}`,w=i(()=>p()?window.fetch:I.default,"getFetcher"),g=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=y(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let o={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let n=await E(this.codeVerifier),a=T(n);o.code_challenge=a}let s=`${this.config.authorizerURL}/authorize?${$(o)}`;if(o.response_mode!=="web_message")return window.location.replace(s),this.okResponse(void 0);try{let n=await L(s,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:n.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${_} } }`,headers:e,variables:{params:r}});return this.okResponse(o.session)}catch(o){return this.errorResponse(o)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let s=await w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),n=await s.json();return s.status>=400?this.errorResponse(new Error(n)):this.okResponse(n)}catch(o){return this.errorResponse(o)}};login=async e=>{try{let r=await this.graphqlQuery({query:` + mutation login($data: LoginInput!) { login(params: $data) { ${_}}} + `,variables:{data:e}});return this.okResponse(r.login)}catch(r){return this.errorResponse(new Error(r))}};logout=async e=>{try{let r=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(r.response)}catch(r){return console.error(r),this.errorResponse(r)}};magicLinkLogin=async e=>{try{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=await this.graphqlQuery({query:` + mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} + `,variables:{data:e}});return this.okResponse(r.magic_link_login)}catch(r){return this.errorResponse(r)}};oauthLogin=async(e,r,o,s)=>{let n=s;if(n||(n=c(h())),!Object.values(f).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");r&&r.length&&(n+=`&roles=${r.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${o||this.config.redirectURL}&state=${n}`)};resendOtp=async e=>{try{let r=await this.graphqlQuery({query:` + mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} + `,variables:{data:e}});return this.okResponse(r.resend_otp)}catch(r){return this.errorResponse(r)}};resetPassword=async e=>{try{let r=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r.reset_password)}catch(r){return this.errorResponse(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let s=await(await w()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(s)};signup=async e=>{try{let r=await this.graphqlQuery({query:` + mutation signup($data: SignUpInput!) { signup(params: $data) { ${_}}} + `,variables:{data:e}});return this.okResponse(r.signup)}catch(r){return this.errorResponse(r)}};updateProfile=async(e,r)=>{try{let o=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}});return this.okResponse(o.update_profile)}catch(o){return this.errorResponse(new Error(o))}};deactivateAccount=async e=>{try{let r=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(r.deactivate_account)}catch(r){return this.errorResponse(r)}};validateJWTToken=async e=>{try{let r=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(r.validate_jwt_token)}catch(r){return this.errorResponse(r)}};validateSession=async e=>{try{let r=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:e}});return this.okResponse(r.validate_session)}catch(r){return this.errorResponse(r)}};verifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` + mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${_}}} + `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};verifyOtp=async e=>{try{let r=await this.graphqlQuery({query:` + mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${_}}} + `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let s=await(await w()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(s.errors&&s.errors.length)throw console.error(s.errors),new Error(s.errors[0].message);return s.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(g,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes}); diff --git a/lib/index.mjs b/lib/index.mjs new file mode 100644 index 0000000..7b8bc58 --- /dev/null +++ b/lib/index.mjs @@ -0,0 +1,13 @@ +var L=Object.defineProperty;var i=(t,e)=>L(t,"name",{value:e,configurable:!0});import x from"cross-fetch";var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),g=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),S=i(()=>{let t=k();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=k();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(n=>e+=t[n%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var v=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),U=i(async t=>{let e=S().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,s)=>{e.oncomplete=n=>{r(n.target.result)},e.onerror=n=>{s(n.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await e},"sha256"),O=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var $=i(t=>{let e=new Uint8Array(t);return O(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),E=i((t,e,r=60)=>new Promise((s,n)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a,R=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",a,!1))},"removeIframe"),T=setTimeout(()=>{R()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let b=u.source;b&&b.close(),u.data.response.error?n(u.data.response):s(u.data.response),clearTimeout(T),window.removeEventListener("message",a,!1),setTimeout(R,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(o),o.setAttribute("src",t)}),"executeIframe");var w="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",l=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${w}}`,m=i(()=>p()?window.fetch:x,"getFetcher"),y=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=g(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=g(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let o=await U(this.codeVerifier),a=$(o);s.code_challenge=a}let n=`${this.config.authorizerURL}/authorize?${v(s)}`;if(s.response_mode!=="web_message")return window.location.replace(n),this.okResponse(void 0);try{let o=await E(n,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:o.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let s=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:e,variables:{params:r}});return this.okResponse(s.session)}catch(s){return this.errorResponse(s)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let n=await m()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),o=await n.json();return n.status>=400?this.errorResponse(new Error(o)):this.okResponse(o)}catch(s){return this.errorResponse(s)}};login=async e=>{try{let r=await this.graphqlQuery({query:` + mutation login($data: LoginInput!) { login(params: $data) { ${l}}} + `,variables:{data:e}});return this.okResponse(r.login)}catch(r){return this.errorResponse(new Error(r))}};logout=async e=>{try{let r=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(r.response)}catch(r){return console.error(r),this.errorResponse(r)}};magicLinkLogin=async e=>{try{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=await this.graphqlQuery({query:` + mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} + `,variables:{data:e}});return this.okResponse(r.magic_link_login)}catch(r){return this.errorResponse(r)}};oauthLogin=async(e,r,s,n)=>{let o=n;if(o||(o=c(h())),!Object.values(f).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");r&&r.length&&(o+=`&roles=${r.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${o}`)};resendOtp=async e=>{try{let r=await this.graphqlQuery({query:` + mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} + `,variables:{data:e}});return this.okResponse(r.resend_otp)}catch(r){return this.errorResponse(r)}};resetPassword=async e=>{try{let r=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r.reset_password)}catch(r){return this.errorResponse(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let n=await(await m()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(n)};signup=async e=>{try{let r=await this.graphqlQuery({query:` + mutation signup($data: SignUpInput!) { signup(params: $data) { ${l}}} + `,variables:{data:e}});return this.okResponse(r.signup)}catch(r){return this.errorResponse(r)}};updateProfile=async(e,r)=>{try{let s=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}});return this.okResponse(s.update_profile)}catch(s){return this.errorResponse(new Error(s))}};deactivateAccount=async e=>{try{let r=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(r.deactivate_account)}catch(r){return this.errorResponse(r)}};validateJWTToken=async e=>{try{let r=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(r.validate_jwt_token)}catch(r){return this.errorResponse(r)}};validateSession=async e=>{try{let r=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${w} } } }`,variables:{params:e}});return this.okResponse(r.validate_session)}catch(r){return this.errorResponse(r)}};verifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` + mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${l}}} + `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};verifyOtp=async e=>{try{let r=await this.graphqlQuery({query:` + mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${l}}} + `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let n=await(await m()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(n.errors&&n.errors.length)throw console.error(n.errors),new Error(n.errors[0].message);return n.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(y,"Authorizer");export{y as Authorizer,f as OAuthProviders,d as ResponseTypes}; diff --git a/lib/types.d.ts b/lib/types.d.ts new file mode 100644 index 0000000..81ed256 --- /dev/null +++ b/lib/types.d.ts @@ -0,0 +1,205 @@ +export interface ApiResponse { + ok: boolean; + error: Error | undefined; + response: T | undefined; +} +export interface ConfigType { + authorizerURL: string; + redirectURL: string; + clientID: string; + extraHeaders?: Record; +} +export interface User { + id: string; + email: string; + preferred_username: string; + email_verified: boolean; + signup_methods: string; + given_name?: string | null; + family_name?: string | null; + middle_name?: string | null; + nickname?: string | null; + picture?: string | null; + gender?: string | null; + birthdate?: string | null; + phone_number?: string | null; + phone_number_verified?: boolean | null; + roles?: string[]; + created_at: number; + updated_at: number; + is_multi_factor_auth_enabled?: boolean; + app_data?: Record; +} +export interface AuthToken { + message?: string; + access_token: string; + expires_in: number; + id_token: string; + refresh_token?: string; + user?: User; + should_show_email_otp_screen?: boolean; + should_show_mobile_otp_screen?: boolean; +} +export interface GenericResponse { + message: string; +} +export type Headers = Record; +export interface LoginInput { + email?: string; + phone_number?: string; + password: string; + roles?: string[]; + scope?: string[]; + state?: string; +} +export interface SignupInput { + email?: string; + password: string; + confirm_password: string; + given_name?: string; + family_name?: string; + middle_name?: string; + nickname?: string; + picture?: string; + gender?: string; + birthdate?: string; + phone_number?: string; + roles?: string[]; + scope?: string[]; + redirect_uri?: string; + is_multi_factor_auth_enabled?: boolean; + state?: string; + app_data?: Record; +} +export interface MagicLinkLoginInput { + email: string; + roles?: string[]; + scopes?: string[]; + state?: string; + redirect_uri?: string; +} +export interface VerifyEmailInput { + token: string; + state?: string; +} +export interface VerifyOtpInput { + email?: string; + phone_number?: string; + otp: string; + state?: string; +} +export interface ResendOtpInput { + email?: string; + phone_number?: string; +} +export interface GraphqlQueryInput { + query: string; + variables?: Record; + headers?: Headers; +} +export interface MetaData { + version: string; + client_id: string; + is_google_login_enabled: boolean; + is_facebook_login_enabled: boolean; + is_github_login_enabled: boolean; + is_linkedin_login_enabled: boolean; + is_apple_login_enabled: boolean; + is_twitter_login_enabled: boolean; + is_microsoft_login_enabled: boolean; + is_email_verification_enabled: boolean; + is_basic_authentication_enabled: boolean; + is_magic_link_login_enabled: boolean; + is_sign_up_enabled: boolean; + is_strong_password_enabled: boolean; +} +export interface UpdateProfileInput { + old_password?: string; + new_password?: string; + confirm_new_password?: string; + email?: string; + given_name?: string; + family_name?: string; + middle_name?: string; + nickname?: string; + gender?: string; + birthdate?: string; + phone_number?: string; + picture?: string; + is_multi_factor_auth_enabled?: boolean; + app_data?: Record; +} +export interface ForgotPasswordInput { + email: string; + state?: string; + redirect_uri?: string; +} +export interface ResetPasswordInput { + token: string; + password: string; + confirm_password: string; +} +export interface SessionQueryInput { + roles?: string[]; +} +export interface IsValidJWTQueryInput { + jwt: string; + roles?: string[]; +} +export interface ValidJWTResponse { + valid: string; + message: string; +} +export declare enum OAuthProviders { + Apple = "apple", + Github = "github", + Google = "google", + Facebook = "facebook", + LinkedIn = "linkedin" +} +export declare enum ResponseTypes { + Code = "code", + Token = "token" +} +export interface AuthorizeInput { + response_type: ResponseTypes; + use_refresh_token?: boolean; + response_mode?: string; +} +export interface AuthorizeResponse { + state: string; + code?: string; + error?: string; + error_description?: string; +} +export interface RevokeTokenInput { + refresh_token: string; +} +export interface GetTokenInput { + code?: string; + grant_type?: string; + refresh_token?: string; +} +export interface GetTokenResponse { + access_token: string; + expires_in: number; + id_token: string; + refresh_token?: string; +} +export interface ValidateJWTTokenInput { + token_type: 'access_token' | 'id_token' | 'refresh_token'; + token: string; + roles?: string[]; +} +export interface ValidateJWTTokenResponse { + is_valid: boolean; + claims: Record; +} +export interface ValidateSessionInput { + cookie?: string; + roles?: string[]; +} +export interface ValidateSessionResponse { + is_valid: boolean; + user: User; +} diff --git a/lib/utils.d.ts b/lib/utils.d.ts new file mode 100644 index 0000000..74d8245 --- /dev/null +++ b/lib/utils.d.ts @@ -0,0 +1,13 @@ +import { AuthorizeResponse } from './types'; +export declare const hasWindow: () => boolean; +export declare const trimURL: (url: string) => string; +export declare const getCrypto: () => Crypto | null; +export declare const getCryptoSubtle: () => any; +export declare const createRandomString: () => string; +export declare const encode: (value: string) => string; +export declare const decode: (value: string) => string; +export declare const createQueryParams: (params: any) => string; +export declare const sha256: (s: string) => Promise; +export declare const urlDecodeB64: (input: string) => string; +export declare const bufferToBase64UrlEncoded: (input: number[] | Uint8Array) => string; +export declare const executeIframe: (authorizeUrl: string, eventOrigin: string, timeoutInSeconds?: number) => Promise; From 3dd6bc2febefe1d029e77e4c62db52bb27cd6caf Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 10 Nov 2023 14:57:12 +0200 Subject: [PATCH 18/26] add method for resending verification email --- lib/authorizer.min.js | 18 +-- lib/constants.d.ts | 3 - lib/index.d.ts | 254 ++++++++++++++++++++++++++++++++++++++---- lib/index.js | 6 +- lib/index.mjs | 8 +- lib/types.d.ts | 205 ---------------------------------- lib/utils.d.ts | 13 --- src/index.ts | 22 +++- src/types.ts | 5 + 9 files changed, 276 insertions(+), 258 deletions(-) delete mode 100644 lib/constants.d.ts delete mode 100644 lib/types.d.ts delete mode 100644 lib/utils.d.ts diff --git a/lib/authorizer.min.js b/lib/authorizer.min.js index 61117fc..b8b267d 100644 --- a/lib/authorizer.min.js +++ b/lib/authorizer.min.js @@ -1,14 +1,16 @@ -var authorizerdev=(()=>{var le=Object.create;var U=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,we=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var j=(o,e,t)=>e in o?U(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,A=(o,e)=>{for(var t in e||(e={}))G.call(e,t)&&j(o,t,e[t]);if(J)for(var t of J(e))be.call(e,t)&&j(o,t,e[t]);return o},W=(o,e)=>ye(o,_e(e)),n=(o,e)=>U(o,"name",{value:e,configurable:!0});var Re=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ve=(o,e)=>{for(var t in e)U(o,t,{get:e[t],enumerable:!0})},Z=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of ge(e))!G.call(o,c)&&c!==t&&U(o,c,{get:()=>e[c],enumerable:!(i=me(e,c))||i.enumerable});return o};var Ee=(o,e,t)=>(t=o!=null?le(we(o)):{},Z(e||!o||!o.__esModule?U(t,"default",{value:o,enumerable:!0}):t,o)),Te=o=>Z(U({},"__esModule",{value:!0}),o);var f=(o,e,t)=>(j(o,typeof e!="symbol"?e+"":e,t),t);var d=(o,e,t)=>new Promise((i,c)=>{var u=w=>{try{g(t.next(w))}catch(m){c(m)}},_=w=>{try{g(t.throw(w))}catch(m){c(m)}},g=w=>w.done?i(w.value):Promise.resolve(w.value).then(u,_);g((t=t.apply(o,e)).next())});var Y=Re((R,K)=>{var X=typeof self!="undefined"?self:R,$=function(){function o(){this.fetch=!1,this.DOMException=X.DOMException}return n(o,"F"),o.prototype=X,new o}();(function(o){var e=function(t){var i={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(r){return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function c(r){return r&&DataView.prototype.isPrototypeOf(r)}if(n(c,"isDataView"),i.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],_=ArrayBuffer.isView||function(r){return r&&u.indexOf(Object.prototype.toString.call(r))>-1};function g(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(r))throw new TypeError("Invalid character in header field name");return r.toLowerCase()}n(g,"normalizeName");function w(r){return typeof r!="string"&&(r=String(r)),r}n(w,"normalizeValue");function m(r){var s={next:function(){var a=r.shift();return{done:a===void 0,value:a}}};return i.iterable&&(s[Symbol.iterator]=function(){return s}),s}n(m,"iteratorFor");function p(r){this.map={},r instanceof p?r.forEach(function(s,a){this.append(a,s)},this):Array.isArray(r)?r.forEach(function(s){this.append(s[0],s[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(s){this.append(s,r[s])},this)}n(p,"Headers"),p.prototype.append=function(r,s){r=g(r),s=w(s);var a=this.map[r];this.map[r]=a?a+", "+s:s},p.prototype.delete=function(r){delete this.map[g(r)]},p.prototype.get=function(r){return r=g(r),this.has(r)?this.map[r]:null},p.prototype.has=function(r){return this.map.hasOwnProperty(g(r))},p.prototype.set=function(r,s){this.map[g(r)]=w(s)},p.prototype.forEach=function(r,s){for(var a in this.map)this.map.hasOwnProperty(a)&&r.call(s,this.map[a],a,this)},p.prototype.keys=function(){var r=[];return this.forEach(function(s,a){r.push(a)}),m(r)},p.prototype.values=function(){var r=[];return this.forEach(function(s){r.push(s)}),m(r)},p.prototype.entries=function(){var r=[];return this.forEach(function(s,a){r.push([a,s])}),m(r)},i.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function D(r){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}n(D,"consumed");function N(r){return new Promise(function(s,a){r.onload=function(){s(r.result)},r.onerror=function(){a(r.error)}})}n(N,"fileReaderReady");function ie(r){var s=new FileReader,a=N(s);return s.readAsArrayBuffer(r),a}n(ie,"readBlobAsArrayBuffer");function ae(r){var s=new FileReader,a=N(s);return s.readAsText(r),a}n(ae,"readBlobAsText");function ce(r){for(var s=new Uint8Array(r),a=new Array(s.length),y=0;y-1?s:r}n(he,"normalizeMethod");function E(r,s){s=s||{};var a=s.body;if(r instanceof E){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,s.headers||(this.headers=new p(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!a&&r._bodyInit!=null&&(a=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=s.credentials||this.credentials||"same-origin",(s.headers||!this.headers)&&(this.headers=new p(s.headers)),this.method=he(s.method||this.method||"GET"),this.mode=s.mode||this.mode||null,this.signal=s.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}n(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function fe(r){var s=new FormData;return r.trim().split("&").forEach(function(a){if(a){var y=a.split("="),l=y.shift().replace(/\+/g," "),h=y.join("=").replace(/\+/g," ");s.append(decodeURIComponent(l),decodeURIComponent(h))}}),s}n(fe,"decode");function de(r){var s=new p,a=r.replace(/\r?\n[\t ]+/g," ");return a.split(/\r?\n/).forEach(function(y){var l=y.split(":"),h=l.shift().trim();if(h){var x=l.join(":").trim();s.append(h,x)}}),s}n(de,"parseHeaders"),V.call(E.prototype);function b(r,s){s||(s={}),this.type="default",this.status=s.status===void 0?200:s.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in s?s.statusText:"OK",this.headers=new p(s.headers),this.url=s.url||"",this._initBody(r)}n(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var r=new b(null,{status:0,statusText:""});return r.type="error",r};var pe=[301,302,303,307,308];b.redirect=function(r,s){if(pe.indexOf(s)===-1)throw new RangeError("Invalid status code");return new b(null,{status:s,headers:{location:r}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(r){t.DOMException=function(s,a){this.message=s,this.name=a;var y=Error(s);this.stack=y.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function P(r,s){return new Promise(function(a,y){var l=new E(r,s);if(l.signal&&l.signal.aborted)return y(new t.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function x(){h.abort()}n(x,"abortXhr"),h.onload=function(){var L={status:h.status,statusText:h.statusText,headers:de(h.getAllResponseHeaders()||"")};L.url="responseURL"in h?h.responseURL:L.headers.get("X-Request-URL");var C="response"in h?h.response:h.responseText;a(new b(C,L))},h.onerror=function(){y(new TypeError("Network request failed"))},h.ontimeout=function(){y(new TypeError("Network request failed"))},h.onabort=function(){y(new t.DOMException("Aborted","AbortError"))},h.open(l.method,l.url,!0),l.credentials==="include"?h.withCredentials=!0:l.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&i.blob&&(h.responseType="blob"),l.headers.forEach(function(L,C){h.setRequestHeader(C,L)}),l.signal&&(l.signal.addEventListener("abort",x),h.onreadystatechange=function(){h.readyState===4&&l.signal.removeEventListener("abort",x)}),h.send(typeof l._bodyInit=="undefined"?null:l._bodyInit)})}return n(P,"fetch"),P.polyfill=!0,o.fetch||(o.fetch=P,o.Headers=p,o.Request=E,o.Response=b),t.Headers=p,t.Request=E,t.Response=b,t.fetch=P,Object.defineProperty(t,"__esModule",{value:!0}),t}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var O=$;R=O.fetch;R.default=O.fetch;R.fetch=O.fetch;R.Headers=O.Headers;R.Request=O.Request;R.Response=O.Response;K.exports=R});var Ie={};ve(Ie,{Authorizer:()=>B,OAuthProviders:()=>S,ResponseTypes:()=>I});var ne=Ee(Y());var S;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin"})(S||(S={}));var I;(function(o){o.Code="code",o.Token="token"})(I||(I={}));var T=n(()=>typeof window!="undefined","hasWindow"),M=n(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=n(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=n(()=>{let o=ee();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),k=n(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=ee();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(c=>e+=o[c%o.length]),e},"createRandomString"),v=n(o=>T()?btoa(o):Buffer.from(o).toString("base64"),"encode");var re=n(o=>Object.keys(o).filter(e=>typeof o[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),te=n(o=>d(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,i)=>{e.oncomplete=c=>{t(c.target.result)},e.onerror=c=>{i(c.error)},e.onabort=()=>{i(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Oe=n(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var oe=n(o=>{let e=new Uint8Array(o);return Oe(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),se=n((o,e,t=60)=>new Promise((i,c)=>{let u=window.document.createElement("iframe");u.setAttribute("id","authorizer-iframe"),u.setAttribute("width","0"),u.setAttribute("height","0"),u.style.display="none";let _,g=n(()=>{window.document.body.contains(u)&&(window.document.body.removeChild(u),window.removeEventListener("message",_,!1))},"removeIframe"),w=setTimeout(()=>{g()},t*1e3);_=n(function(m){if(m.origin!==e||!m.data||!m.data.response)return;let p=m.source;p&&p.close(),m.data.response.error?c(m.data.response):i(m.data.response),clearTimeout(w),window.removeEventListener("message",_,!1),setTimeout(g,2*1e3)},"iframeEventHandler"),window.addEventListener("message",_,!1),window.document.body.appendChild(u),u.setAttribute("src",o)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",q=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${H}}`,z=n(()=>T()?window.fetch:ne.default,"getFetcher"),B=class{constructor(e){f(this,"authorize",n(e=>d(this,null,function*(){if(!T())return this.errorResponse(new Error("this feature is only supported in browser"));let t=["openid","profile","email"];e.use_refresh_token&&t.push("offline_access");let i={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(k()),nonce:v(k()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===I.Code){this.codeVerifier=k();let u=yield te(this.codeVerifier),_=oe(u);i.code_challenge=_}let c=`${this.config.authorizerURL}/authorize?${re(i)}`;if(i.response_mode!=="web_message")return window.location.replace(c),this.okResponse(void 0);try{let u=yield se(c,this.config.authorizerURL,60);if(e.response_type===I.Code){let _=yield this.getToken({code:u.code});return _.ok?this.okResponse(_.response):this.errorResponse(_.error)}return this.okResponse(u)}catch(u){return u.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(u)}}),"authorize"));f(this,"browserLogin",n(()=>d(this,null,function*(){try{let e=yield this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}}),"browserLogin"));f(this,"forgotPassword",n(e=>d(this,null,function*(){e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let t=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(t==null?void 0:t.forgot_password)}catch(t){return this.errorResponse(t)}}),"forgotPassword"));f(this,"getMetaData",n(()=>d(this,null,function*(){try{let e=yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}}),"getMetaData"));f(this,"getProfile",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e});return this.okResponse(t.profile)}catch(t){return this.errorResponse(t)}}),"getProfile"));f(this,"getSession",n((e,t)=>d(this,null,function*(){try{let i=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${q} } }`,headers:e,variables:{params:t}});return this.okResponse(i.session)}catch(i){return this.errorResponse(i)}}),"getSession"));f(this,"getToken",n(e=>d(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let c=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:A({},this.config.extraHeaders),credentials:"include"}),u=yield c.json();return c.status>=400?this.errorResponse(new Error(u)):this.okResponse(u)}catch(i){return this.errorResponse(i)}}),"getToken"));f(this,"login",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` - mutation login($data: LoginInput!) { login(params: $data) { ${q}}} +var authorizerdev=(()=>{var le=Object.create;var U=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,we=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var j=(o,e,t)=>e in o?U(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,A=(o,e)=>{for(var t in e||(e={}))G.call(e,t)&&j(o,t,e[t]);if(J)for(var t of J(e))be.call(e,t)&&j(o,t,e[t]);return o},W=(o,e)=>ye(o,_e(e)),n=(o,e)=>U(o,"name",{value:e,configurable:!0});var Re=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ve=(o,e)=>{for(var t in e)U(o,t,{get:e[t],enumerable:!0})},Z=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of ge(e))!G.call(o,c)&&c!==t&&U(o,c,{get:()=>e[c],enumerable:!(i=me(e,c))||i.enumerable});return o};var Ee=(o,e,t)=>(t=o!=null?le(we(o)):{},Z(e||!o||!o.__esModule?U(t,"default",{value:o,enumerable:!0}):t,o)),Te=o=>Z(U({},"__esModule",{value:!0}),o);var f=(o,e,t)=>(j(o,typeof e!="symbol"?e+"":e,t),t);var d=(o,e,t)=>new Promise((i,c)=>{var u=w=>{try{g(t.next(w))}catch(m){c(m)}},_=w=>{try{g(t.throw(w))}catch(m){c(m)}},g=w=>w.done?i(w.value):Promise.resolve(w.value).then(u,_);g((t=t.apply(o,e)).next())});var Y=Re((R,K)=>{var X=typeof self!="undefined"?self:R,$=function(){function o(){this.fetch=!1,this.DOMException=X.DOMException}return n(o,"F"),o.prototype=X,new o}();(function(o){var e=function(t){var i={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(r){return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function c(r){return r&&DataView.prototype.isPrototypeOf(r)}if(n(c,"isDataView"),i.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],_=ArrayBuffer.isView||function(r){return r&&u.indexOf(Object.prototype.toString.call(r))>-1};function g(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(r))throw new TypeError("Invalid character in header field name");return r.toLowerCase()}n(g,"normalizeName");function w(r){return typeof r!="string"&&(r=String(r)),r}n(w,"normalizeValue");function m(r){var s={next:function(){var a=r.shift();return{done:a===void 0,value:a}}};return i.iterable&&(s[Symbol.iterator]=function(){return s}),s}n(m,"iteratorFor");function p(r){this.map={},r instanceof p?r.forEach(function(s,a){this.append(a,s)},this):Array.isArray(r)?r.forEach(function(s){this.append(s[0],s[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(s){this.append(s,r[s])},this)}n(p,"Headers"),p.prototype.append=function(r,s){r=g(r),s=w(s);var a=this.map[r];this.map[r]=a?a+", "+s:s},p.prototype.delete=function(r){delete this.map[g(r)]},p.prototype.get=function(r){return r=g(r),this.has(r)?this.map[r]:null},p.prototype.has=function(r){return this.map.hasOwnProperty(g(r))},p.prototype.set=function(r,s){this.map[g(r)]=w(s)},p.prototype.forEach=function(r,s){for(var a in this.map)this.map.hasOwnProperty(a)&&r.call(s,this.map[a],a,this)},p.prototype.keys=function(){var r=[];return this.forEach(function(s,a){r.push(a)}),m(r)},p.prototype.values=function(){var r=[];return this.forEach(function(s){r.push(s)}),m(r)},p.prototype.entries=function(){var r=[];return this.forEach(function(s,a){r.push([a,s])}),m(r)},i.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function D(r){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}n(D,"consumed");function N(r){return new Promise(function(s,a){r.onload=function(){s(r.result)},r.onerror=function(){a(r.error)}})}n(N,"fileReaderReady");function ie(r){var s=new FileReader,a=N(s);return s.readAsArrayBuffer(r),a}n(ie,"readBlobAsArrayBuffer");function ae(r){var s=new FileReader,a=N(s);return s.readAsText(r),a}n(ae,"readBlobAsText");function ce(r){for(var s=new Uint8Array(r),a=new Array(s.length),y=0;y-1?s:r}n(he,"normalizeMethod");function E(r,s){s=s||{};var a=s.body;if(r instanceof E){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,s.headers||(this.headers=new p(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!a&&r._bodyInit!=null&&(a=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=s.credentials||this.credentials||"same-origin",(s.headers||!this.headers)&&(this.headers=new p(s.headers)),this.method=he(s.method||this.method||"GET"),this.mode=s.mode||this.mode||null,this.signal=s.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}n(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function fe(r){var s=new FormData;return r.trim().split("&").forEach(function(a){if(a){var y=a.split("="),l=y.shift().replace(/\+/g," "),h=y.join("=").replace(/\+/g," ");s.append(decodeURIComponent(l),decodeURIComponent(h))}}),s}n(fe,"decode");function de(r){var s=new p,a=r.replace(/\r?\n[\t ]+/g," ");return a.split(/\r?\n/).forEach(function(y){var l=y.split(":"),h=l.shift().trim();if(h){var x=l.join(":").trim();s.append(h,x)}}),s}n(de,"parseHeaders"),V.call(E.prototype);function b(r,s){s||(s={}),this.type="default",this.status=s.status===void 0?200:s.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in s?s.statusText:"OK",this.headers=new p(s.headers),this.url=s.url||"",this._initBody(r)}n(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var r=new b(null,{status:0,statusText:""});return r.type="error",r};var pe=[301,302,303,307,308];b.redirect=function(r,s){if(pe.indexOf(s)===-1)throw new RangeError("Invalid status code");return new b(null,{status:s,headers:{location:r}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(r){t.DOMException=function(s,a){this.message=s,this.name=a;var y=Error(s);this.stack=y.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function P(r,s){return new Promise(function(a,y){var l=new E(r,s);if(l.signal&&l.signal.aborted)return y(new t.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function x(){h.abort()}n(x,"abortXhr"),h.onload=function(){var L={status:h.status,statusText:h.statusText,headers:de(h.getAllResponseHeaders()||"")};L.url="responseURL"in h?h.responseURL:L.headers.get("X-Request-URL");var C="response"in h?h.response:h.responseText;a(new b(C,L))},h.onerror=function(){y(new TypeError("Network request failed"))},h.ontimeout=function(){y(new TypeError("Network request failed"))},h.onabort=function(){y(new t.DOMException("Aborted","AbortError"))},h.open(l.method,l.url,!0),l.credentials==="include"?h.withCredentials=!0:l.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&i.blob&&(h.responseType="blob"),l.headers.forEach(function(L,C){h.setRequestHeader(C,L)}),l.signal&&(l.signal.addEventListener("abort",x),h.onreadystatechange=function(){h.readyState===4&&l.signal.removeEventListener("abort",x)}),h.send(typeof l._bodyInit=="undefined"?null:l._bodyInit)})}return n(P,"fetch"),P.polyfill=!0,o.fetch||(o.fetch=P,o.Headers=p,o.Request=E,o.Response=b),t.Headers=p,t.Request=E,t.Response=b,t.fetch=P,Object.defineProperty(t,"__esModule",{value:!0}),t}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var I=$;R=I.fetch;R.default=I.fetch;R.fetch=I.fetch;R.Headers=I.Headers;R.Request=I.Request;R.Response=I.Response;K.exports=R});var Oe={};ve(Oe,{Authorizer:()=>B,OAuthProviders:()=>q,ResponseTypes:()=>O});var ne=Ee(Y());var q;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin"})(q||(q={}));var O;(function(o){o.Code="code",o.Token="token"})(O||(O={}));var T=n(()=>typeof window!="undefined","hasWindow"),M=n(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=n(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=n(()=>{let o=ee();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),k=n(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=ee();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(c=>e+=o[c%o.length]),e},"createRandomString"),v=n(o=>T()?btoa(o):Buffer.from(o).toString("base64"),"encode");var re=n(o=>Object.keys(o).filter(e=>typeof o[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),te=n(o=>d(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,i)=>{e.oncomplete=c=>{t(c.target.result)},e.onerror=c=>{i(c.error)},e.onabort=()=>{i(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Ie=n(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var oe=n(o=>{let e=new Uint8Array(o);return Ie(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),se=n((o,e,t=60)=>new Promise((i,c)=>{let u=window.document.createElement("iframe");u.setAttribute("id","authorizer-iframe"),u.setAttribute("width","0"),u.setAttribute("height","0"),u.style.display="none";let _,g=n(()=>{window.document.body.contains(u)&&(window.document.body.removeChild(u),window.removeEventListener("message",_,!1))},"removeIframe"),w=setTimeout(()=>{g()},t*1e3);_=n(function(m){if(m.origin!==e||!m.data||!m.data.response)return;let p=m.source;p&&p.close(),m.data.response.error?c(m.data.response):i(m.data.response),clearTimeout(w),window.removeEventListener("message",_,!1),setTimeout(g,2*1e3)},"iframeEventHandler"),window.addEventListener("message",_,!1),window.document.body.appendChild(u),u.setAttribute("src",o)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",S=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${H}}`,z=n(()=>T()?window.fetch:ne.default,"getFetcher"),B=class{constructor(e){f(this,"authorize",n(e=>d(this,null,function*(){if(!T())return this.errorResponse(new Error("this feature is only supported in browser"));let t=["openid","profile","email"];e.use_refresh_token&&t.push("offline_access");let i={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(k()),nonce:v(k()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===O.Code){this.codeVerifier=k();let u=yield te(this.codeVerifier),_=oe(u);i.code_challenge=_}let c=`${this.config.authorizerURL}/authorize?${re(i)}`;if(i.response_mode!=="web_message")return window.location.replace(c),this.okResponse(void 0);try{let u=yield se(c,this.config.authorizerURL,60);if(e.response_type===O.Code){let _=yield this.getToken({code:u.code});return _.ok?this.okResponse(_.response):this.errorResponse(_.error)}return this.okResponse(u)}catch(u){return u.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(u)}}),"authorize"));f(this,"browserLogin",n(()=>d(this,null,function*(){try{let e=yield this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}}),"browserLogin"));f(this,"forgotPassword",n(e=>d(this,null,function*(){e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let t=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(t==null?void 0:t.forgot_password)}catch(t){return this.errorResponse(t)}}),"forgotPassword"));f(this,"getMetaData",n(()=>d(this,null,function*(){try{let e=yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}}),"getMetaData"));f(this,"getProfile",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e});return this.okResponse(t.profile)}catch(t){return this.errorResponse(t)}}),"getProfile"));f(this,"getSession",n((e,t)=>d(this,null,function*(){try{let i=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${S} } }`,headers:e,variables:{params:t}});return this.okResponse(i.session)}catch(i){return this.errorResponse(i)}}),"getSession"));f(this,"getToken",n(e=>d(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let c=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:A({},this.config.extraHeaders),credentials:"include"}),u=yield c.json();return c.status>=400?this.errorResponse(new Error(u)):this.okResponse(u)}catch(i){return this.errorResponse(i)}}),"getToken"));f(this,"login",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation login($data: LoginInput!) { login(params: $data) { ${S}}} `,variables:{data:e}});return this.okResponse(t.login)}catch(t){return this.errorResponse(new Error(t))}}),"login"));f(this,"logout",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(t.response)}catch(t){return console.error(t),this.errorResponse(t)}}),"logout"));f(this,"magicLinkLogin",n(e=>d(this,null,function*(){try{e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let t=yield this.graphqlQuery({query:` mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(t.magic_link_login)}catch(t){return this.errorResponse(t)}}),"magicLinkLogin"));f(this,"oauthLogin",n((e,t,i,c)=>d(this,null,function*(){let u=c;if(u||(u=v(k())),!Object.values(S).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!T())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(u+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${i||this.config.redirectURL}&state=${u}`)}),"oauthLogin"));f(this,"resendOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + `,variables:{data:e}});return this.okResponse(t.magic_link_login)}catch(t){return this.errorResponse(t)}}),"magicLinkLogin"));f(this,"oauthLogin",n((e,t,i,c)=>d(this,null,function*(){let u=c;if(u||(u=v(k())),!Object.values(q).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!T())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(u+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${i||this.config.redirectURL}&state=${u}`)}),"oauthLogin"));f(this,"resendOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} `,variables:{data:e}});return this.okResponse(t.resend_otp)}catch(t){return this.errorResponse(t)}}),"resendOtp"));f(this,"resetPassword",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(t.reset_password)}catch(t){return this.errorResponse(t)}}),"resetPassword"));f(this,"revokeToken",n(e=>d(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let c=yield(yield z()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:A({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(c)}),"revokeToken"));f(this,"signup",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` - mutation signup($data: SignUpInput!) { signup(params: $data) { ${q}}} + mutation signup($data: SignUpInput!) { signup(params: $data) { ${S}}} `,variables:{data:e}});return this.okResponse(t.signup)}catch(t){return this.errorResponse(t)}}),"signup"));f(this,"updateProfile",n((e,t)=>d(this,null,function*(){try{let i=yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:e}});return this.okResponse(i.update_profile)}catch(i){return this.errorResponse(new Error(i))}}),"updateProfile"));f(this,"deactivateAccount",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(t.deactivate_account)}catch(t){return this.errorResponse(t)}}),"deactivateAccount"));f(this,"validateJWTToken",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(t.validate_jwt_token)}catch(t){return this.errorResponse(t)}}),"validateJWTToken"));f(this,"validateSession",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${H} } } }`,variables:{params:e}});return this.okResponse(t.validate_session)}catch(t){return this.errorResponse(t)}}),"validateSession"));f(this,"verifyEmail",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` - mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${q}}} - `,variables:{data:e}});return this.okResponse(t.verify_email)}catch(t){return this.errorResponse(t)}}),"verifyEmail"));f(this,"verifyOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` - mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${q}}} - `,variables:{data:e}});return this.okResponse(t.verify_otp)}catch(t){return this.errorResponse(t)}}),"verifyOtp"));f(this,"graphqlQuery",n(e=>d(this,null,function*(){let c=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:A(A({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();if(c.errors&&c.errors.length)throw console.error(c.errors),new Error(c.errors[0].message);return c.data}),"graphqlQuery"));f(this,"errorResponse",n(e=>({ok:!1,response:void 0,error:e}),"errorResponse"));f(this,"okResponse",n(e=>({ok:!0,response:e,error:void 0}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=M(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=M(e.redirectURL),this.config.extraHeaders=W(A({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};n(B,"Authorizer");return Te(Ie);})(); + mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${S}}} + `,variables:{data:e}});return this.okResponse(t.verify_email)}catch(t){return this.errorResponse(t)}}),"verifyEmail"));f(this,"resendVerifyEmail",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} + `,variables:{data:e}});return this.okResponse(t.verify_email)}catch(t){return this.errorResponse(t)}}),"resendVerifyEmail"));f(this,"verifyOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${S}}} + `,variables:{data:e}});return this.okResponse(t.verify_otp)}catch(t){return this.errorResponse(t)}}),"verifyOtp"));f(this,"graphqlQuery",n(e=>d(this,null,function*(){let c=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:A(A({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();if(c.errors&&c.errors.length)throw console.error(c.errors),new Error(c.errors[0].message);return c.data}),"graphqlQuery"));f(this,"errorResponse",n(e=>({ok:!1,response:void 0,error:e}),"errorResponse"));f(this,"okResponse",n(e=>({ok:!0,response:e,error:void 0}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=M(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=M(e.redirectURL),this.config.extraHeaders=W(A({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};n(B,"Authorizer");return Te(Oe);})(); window.__TAURI__ = authorizerdev diff --git a/lib/constants.d.ts b/lib/constants.d.ts deleted file mode 100644 index f300904..0000000 --- a/lib/constants.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export declare const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60; -export declare const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2; -export declare const AUTHORIZE_IFRAME_TIMEOUT = 5; diff --git a/lib/index.d.ts b/lib/index.d.ts index 17c4e88..cc36d10 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -1,34 +1,244 @@ -import * as Types from './types'; -import type { ApiResponse, AuthToken, AuthorizeResponse, ConfigType, GetTokenResponse, MetaData, User, ValidateJWTTokenResponse, ValidateSessionResponse, GenericResponse } from './types'; -export * from './types'; -export declare class Authorizer { +interface ApiResponse { + ok: boolean; + error: Error | undefined; + response: T | undefined; +} +interface ConfigType { + authorizerURL: string; + redirectURL: string; + clientID: string; + extraHeaders?: Record; +} +interface User { + id: string; + email: string; + preferred_username: string; + email_verified: boolean; + signup_methods: string; + given_name?: string | null; + family_name?: string | null; + middle_name?: string | null; + nickname?: string | null; + picture?: string | null; + gender?: string | null; + birthdate?: string | null; + phone_number?: string | null; + phone_number_verified?: boolean | null; + roles?: string[]; + created_at: number; + updated_at: number; + is_multi_factor_auth_enabled?: boolean; + app_data?: Record; +} +interface AuthToken { + message?: string; + access_token: string; + expires_in: number; + id_token: string; + refresh_token?: string; + user?: User; + should_show_email_otp_screen?: boolean; + should_show_mobile_otp_screen?: boolean; +} +interface GenericResponse { + message: string; +} +type Headers = Record; +interface LoginInput { + email?: string; + phone_number?: string; + password: string; + roles?: string[]; + scope?: string[]; + state?: string; +} +interface SignupInput { + email?: string; + password: string; + confirm_password: string; + given_name?: string; + family_name?: string; + middle_name?: string; + nickname?: string; + picture?: string; + gender?: string; + birthdate?: string; + phone_number?: string; + roles?: string[]; + scope?: string[]; + redirect_uri?: string; + is_multi_factor_auth_enabled?: boolean; + state?: string; + app_data?: Record; +} +interface MagicLinkLoginInput { + email: string; + roles?: string[]; + scopes?: string[]; + state?: string; + redirect_uri?: string; +} +interface VerifyEmailInput { + token: string; + state?: string; +} +interface ResendVerifyEmailInput { + email: string; + identifier: string; +} +interface VerifyOtpInput { + email?: string; + phone_number?: string; + otp: string; + state?: string; +} +interface ResendOtpInput { + email?: string; + phone_number?: string; +} +interface GraphqlQueryInput { + query: string; + variables?: Record; + headers?: Headers; +} +interface MetaData { + version: string; + client_id: string; + is_google_login_enabled: boolean; + is_facebook_login_enabled: boolean; + is_github_login_enabled: boolean; + is_linkedin_login_enabled: boolean; + is_apple_login_enabled: boolean; + is_twitter_login_enabled: boolean; + is_microsoft_login_enabled: boolean; + is_email_verification_enabled: boolean; + is_basic_authentication_enabled: boolean; + is_magic_link_login_enabled: boolean; + is_sign_up_enabled: boolean; + is_strong_password_enabled: boolean; +} +interface UpdateProfileInput { + old_password?: string; + new_password?: string; + confirm_new_password?: string; + email?: string; + given_name?: string; + family_name?: string; + middle_name?: string; + nickname?: string; + gender?: string; + birthdate?: string; + phone_number?: string; + picture?: string; + is_multi_factor_auth_enabled?: boolean; + app_data?: Record; +} +interface ForgotPasswordInput { + email: string; + state?: string; + redirect_uri?: string; +} +interface ResetPasswordInput { + token: string; + password: string; + confirm_password: string; +} +interface SessionQueryInput { + roles?: string[]; +} +interface IsValidJWTQueryInput { + jwt: string; + roles?: string[]; +} +interface ValidJWTResponse { + valid: string; + message: string; +} +declare enum OAuthProviders { + Apple = "apple", + Github = "github", + Google = "google", + Facebook = "facebook", + LinkedIn = "linkedin" +} +declare enum ResponseTypes { + Code = "code", + Token = "token" +} +interface AuthorizeInput { + response_type: ResponseTypes; + use_refresh_token?: boolean; + response_mode?: string; +} +interface AuthorizeResponse { + state: string; + code?: string; + error?: string; + error_description?: string; +} +interface RevokeTokenInput { + refresh_token: string; +} +interface GetTokenInput { + code?: string; + grant_type?: string; + refresh_token?: string; +} +interface GetTokenResponse { + access_token: string; + expires_in: number; + id_token: string; + refresh_token?: string; +} +interface ValidateJWTTokenInput { + token_type: 'access_token' | 'id_token' | 'refresh_token'; + token: string; + roles?: string[]; +} +interface ValidateJWTTokenResponse { + is_valid: boolean; + claims: Record; +} +interface ValidateSessionInput { + cookie?: string; + roles?: string[]; +} +interface ValidateSessionResponse { + is_valid: boolean; + user: User; +} + +declare class Authorizer { config: ConfigType; codeVerifier: string; constructor(config: ConfigType); - authorize: (data: Types.AuthorizeInput) => Promise | ApiResponse>; + authorize: (data: AuthorizeInput) => Promise | ApiResponse>; browserLogin: () => Promise>; - forgotPassword: (data: Types.ForgotPasswordInput) => Promise>; + forgotPassword: (data: ForgotPasswordInput) => Promise>; getMetaData: () => Promise>; - getProfile: (headers?: Types.Headers) => Promise>; - getSession: (headers?: Types.Headers, params?: Types.SessionQueryInput) => Promise>; - getToken: (data: Types.GetTokenInput) => Promise>; - login: (data: Types.LoginInput) => Promise>; - logout: (headers?: Types.Headers) => Promise>; - magicLinkLogin: (data: Types.MagicLinkLoginInput) => Promise>; + getProfile: (headers?: Headers) => Promise>; + getSession: (headers?: Headers, params?: SessionQueryInput) => Promise>; + getToken: (data: GetTokenInput) => Promise>; + login: (data: LoginInput) => Promise>; + logout: (headers?: Headers) => Promise>; + magicLinkLogin: (data: MagicLinkLoginInput) => Promise>; oauthLogin: (oauthProvider: string, roles?: string[], redirect_uri?: string, state?: string) => Promise; - resendOtp: (data: Types.ResendOtpInput) => Promise>; - resetPassword: (data: Types.ResetPasswordInput) => Promise>; + resendOtp: (data: ResendOtpInput) => Promise>; + resetPassword: (data: ResetPasswordInput) => Promise>; revokeToken: (data: { refresh_token: string; - }) => Promise>; - signup: (data: Types.SignupInput) => Promise>; - updateProfile: (data: Types.UpdateProfileInput, headers?: Types.Headers) => Promise>; - deactivateAccount: (headers?: Types.Headers) => Promise>; - validateJWTToken: (params?: Types.ValidateJWTTokenInput) => Promise>; - validateSession: (params?: Types.ValidateSessionInput) => Promise>; - verifyEmail: (data: Types.VerifyEmailInput) => Promise>; - verifyOtp: (data: Types.VerifyOtpInput) => Promise>; + }) => Promise>; + signup: (data: SignupInput) => Promise>; + updateProfile: (data: UpdateProfileInput, headers?: Headers) => Promise>; + deactivateAccount: (headers?: Headers) => Promise>; + validateJWTToken: (params?: ValidateJWTTokenInput) => Promise>; + validateSession: (params?: ValidateSessionInput) => Promise>; + verifyEmail: (data: VerifyEmailInput) => Promise>; + resendVerifyEmail: (data: ResendVerifyEmailInput) => Promise>; + verifyOtp: (data: VerifyOtpInput) => Promise>; private graphqlQuery; private errorResponse; private okResponse; } + +export { ApiResponse, AuthToken, AuthorizeInput, AuthorizeResponse, Authorizer, ConfigType, ForgotPasswordInput, GenericResponse, GetTokenInput, GetTokenResponse, GraphqlQueryInput, Headers, IsValidJWTQueryInput, LoginInput, MagicLinkLoginInput, MetaData, OAuthProviders, ResendOtpInput, ResendVerifyEmailInput, ResetPasswordInput, ResponseTypes, RevokeTokenInput, SessionQueryInput, SignupInput, UpdateProfileInput, User, ValidJWTResponse, ValidateJWTTokenInput, ValidateJWTTokenResponse, ValidateSessionInput, ValidateSessionResponse, VerifyEmailInput, VerifyOtpInput }; diff --git a/lib/index.js b/lib/index.js index 58f8c13..cb56832 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,4 +1,4 @@ -var S=Object.create;var l=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var i=(t,e)=>l(t,"name",{value:e,configurable:!0});var z=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},v=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of x(e))!A.call(t,s)&&s!==r&&l(t,s,{get:()=>e[s],enumerable:!(o=O(e,s))||o.enumerable});return t};var Q=(t,e,r)=>(r=t!=null?S(C(t)):{},v(e||!t||!t.__esModule?l(r,"default",{value:t,enumerable:!0}):r,t)),D=t=>v(l({},"__esModule",{value:!0}),t);var H={};z(H,{Authorizer:()=>g,OAuthProviders:()=>f,ResponseTypes:()=>d});module.exports=D(H);var I=Q(require("cross-fetch"));var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),y=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),U=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),j=i(()=>{let t=U();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=U();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(s=>e+=t[s%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var $=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),E=i(async t=>{let e=j().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,o)=>{e.oncomplete=s=>{r(s.target.result)},e.onerror=s=>{o(s.error)},e.onabort=()=>{o(new Error("The digest operation was aborted"))}}):await e},"sha256"),F=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var T=i(t=>{let e=new Uint8Array(t);return F(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),L=i((t,e,r=60)=>new Promise((o,s)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a,b=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",a,!1))},"removeIframe"),q=setTimeout(()=>{b()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let k=u.source;k&&k.close(),u.data.response.error?s(u.data.response):o(u.data.response),clearTimeout(q),window.removeEventListener("message",a,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(n),n.setAttribute("src",t)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",_=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${R}}`,w=i(()=>p()?window.fetch:I.default,"getFetcher"),g=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=y(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let o={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let n=await E(this.codeVerifier),a=T(n);o.code_challenge=a}let s=`${this.config.authorizerURL}/authorize?${$(o)}`;if(o.response_mode!=="web_message")return window.location.replace(s),this.okResponse(void 0);try{let n=await L(s,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:n.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${_} } }`,headers:e,variables:{params:r}});return this.okResponse(o.session)}catch(o){return this.errorResponse(o)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let s=await w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),n=await s.json();return s.status>=400?this.errorResponse(new Error(n)):this.okResponse(n)}catch(o){return this.errorResponse(o)}};login=async e=>{try{let r=await this.graphqlQuery({query:` +var S=Object.create;var l=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var i=(t,e)=>l(t,"name",{value:e,configurable:!0});var Q=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},v=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of x(e))!A.call(t,s)&&s!==r&&l(t,s,{get:()=>e[s],enumerable:!(o=O(e,s))||o.enumerable});return t};var z=(t,e,r)=>(r=t!=null?S(C(t)):{},v(e||!t||!t.__esModule?l(r,"default",{value:t,enumerable:!0}):r,t)),D=t=>v(l({},"__esModule",{value:!0}),t);var F={};Q(F,{Authorizer:()=>m,OAuthProviders:()=>f,ResponseTypes:()=>d});module.exports=D(F);var q=z(require("cross-fetch"));var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),g=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),E=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),j=i(()=>{let t=E();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=E();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(s=>e+=t[s%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var $=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),U=i(async t=>{let e=j().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,o)=>{e.oncomplete=s=>{r(s.target.result)},e.onerror=s=>{o(s.error)},e.onabort=()=>{o(new Error("The digest operation was aborted"))}}):await e},"sha256"),V=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var T=i(t=>{let e=new Uint8Array(t);return V(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),L=i((t,e,r=60)=>new Promise((o,s)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a,b=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",a,!1))},"removeIframe"),I=setTimeout(()=>{b()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let k=u.source;k&&k.close(),u.data.response.error?s(u.data.response):o(u.data.response),clearTimeout(I),window.removeEventListener("message",a,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(n),n.setAttribute("src",t)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",_=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${R}}`,w=i(()=>p()?window.fetch:q.default,"getFetcher"),m=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=g(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=g(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let o={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let n=await U(this.codeVerifier),a=T(n);o.code_challenge=a}let s=`${this.config.authorizerURL}/authorize?${$(o)}`;if(o.response_mode!=="web_message")return window.location.replace(s),this.okResponse(void 0);try{let n=await L(s,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:n.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${_} } }`,headers:e,variables:{params:r}});return this.okResponse(o.session)}catch(o){return this.errorResponse(o)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let s=await w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),n=await s.json();return s.status>=400?this.errorResponse(new Error(n)):this.okResponse(n)}catch(o){return this.errorResponse(o)}};login=async e=>{try{let r=await this.graphqlQuery({query:` mutation login($data: LoginInput!) { login(params: $data) { ${_}}} `,variables:{data:e}});return this.okResponse(r.login)}catch(r){return this.errorResponse(new Error(r))}};logout=async e=>{try{let r=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(r.response)}catch(r){return console.error(r),this.errorResponse(r)}};magicLinkLogin=async e=>{try{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=await this.graphqlQuery({query:` mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} @@ -8,6 +8,8 @@ var S=Object.create;var l=Object.defineProperty;var O=Object.getOwnPropertyDescr mutation signup($data: SignUpInput!) { signup(params: $data) { ${_}}} `,variables:{data:e}});return this.okResponse(r.signup)}catch(r){return this.errorResponse(r)}};updateProfile=async(e,r)=>{try{let o=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}});return this.okResponse(o.update_profile)}catch(o){return this.errorResponse(new Error(o))}};deactivateAccount=async e=>{try{let r=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(r.deactivate_account)}catch(r){return this.errorResponse(r)}};validateJWTToken=async e=>{try{let r=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(r.validate_jwt_token)}catch(r){return this.errorResponse(r)}};validateSession=async e=>{try{let r=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:e}});return this.okResponse(r.validate_session)}catch(r){return this.errorResponse(r)}};verifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${_}}} + `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};resendVerifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` + mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};verifyOtp=async e=>{try{let r=await this.graphqlQuery({query:` mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${_}}} - `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let s=await(await w()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(s.errors&&s.errors.length)throw console.error(s.errors),new Error(s.errors[0].message);return s.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(g,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes}); + `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let s=await(await w()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(s.errors&&s.errors.length)throw console.error(s.errors),new Error(s.errors[0].message);return s.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(m,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes}); diff --git a/lib/index.mjs b/lib/index.mjs index 7b8bc58..6c74016 100644 --- a/lib/index.mjs +++ b/lib/index.mjs @@ -1,13 +1,15 @@ -var L=Object.defineProperty;var i=(t,e)=>L(t,"name",{value:e,configurable:!0});import x from"cross-fetch";var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),g=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),S=i(()=>{let t=k();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=k();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(n=>e+=t[n%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var v=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),U=i(async t=>{let e=S().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,s)=>{e.oncomplete=n=>{r(n.target.result)},e.onerror=n=>{s(n.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await e},"sha256"),O=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var $=i(t=>{let e=new Uint8Array(t);return O(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),E=i((t,e,r=60)=>new Promise((s,n)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a,R=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",a,!1))},"removeIframe"),T=setTimeout(()=>{R()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let b=u.source;b&&b.close(),u.data.response.error?n(u.data.response):s(u.data.response),clearTimeout(T),window.removeEventListener("message",a,!1),setTimeout(R,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(o),o.setAttribute("src",t)}),"executeIframe");var w="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",l=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${w}}`,m=i(()=>p()?window.fetch:x,"getFetcher"),y=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=g(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=g(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let o=await U(this.codeVerifier),a=$(o);s.code_challenge=a}let n=`${this.config.authorizerURL}/authorize?${v(s)}`;if(s.response_mode!=="web_message")return window.location.replace(n),this.okResponse(void 0);try{let o=await E(n,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:o.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let s=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:e,variables:{params:r}});return this.okResponse(s.session)}catch(s){return this.errorResponse(s)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let n=await m()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),o=await n.json();return n.status>=400?this.errorResponse(new Error(o)):this.okResponse(o)}catch(s){return this.errorResponse(s)}};login=async e=>{try{let r=await this.graphqlQuery({query:` +var L=Object.defineProperty;var i=(t,e)=>L(t,"name",{value:e,configurable:!0});import x from"cross-fetch";var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),m=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),S=i(()=>{let t=k();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=k();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(n=>e+=t[n%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var v=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),E=i(async t=>{let e=S().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,s)=>{e.oncomplete=n=>{r(n.target.result)},e.onerror=n=>{s(n.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await e},"sha256"),O=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var $=i(t=>{let e=new Uint8Array(t);return O(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),U=i((t,e,r=60)=>new Promise((s,n)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a,R=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",a,!1))},"removeIframe"),T=setTimeout(()=>{R()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let b=u.source;b&&b.close(),u.data.response.error?n(u.data.response):s(u.data.response),clearTimeout(T),window.removeEventListener("message",a,!1),setTimeout(R,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(o),o.setAttribute("src",t)}),"executeIframe");var w="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",l=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${w}}`,y=i(()=>p()?window.fetch:x,"getFetcher"),g=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=m(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=m(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let o=await E(this.codeVerifier),a=$(o);s.code_challenge=a}let n=`${this.config.authorizerURL}/authorize?${v(s)}`;if(s.response_mode!=="web_message")return window.location.replace(n),this.okResponse(void 0);try{let o=await U(n,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:o.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let s=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:e,variables:{params:r}});return this.okResponse(s.session)}catch(s){return this.errorResponse(s)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let n=await y()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),o=await n.json();return n.status>=400?this.errorResponse(new Error(o)):this.okResponse(o)}catch(s){return this.errorResponse(s)}};login=async e=>{try{let r=await this.graphqlQuery({query:` mutation login($data: LoginInput!) { login(params: $data) { ${l}}} `,variables:{data:e}});return this.okResponse(r.login)}catch(r){return this.errorResponse(new Error(r))}};logout=async e=>{try{let r=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(r.response)}catch(r){return console.error(r),this.errorResponse(r)}};magicLinkLogin=async e=>{try{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=await this.graphqlQuery({query:` mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} `,variables:{data:e}});return this.okResponse(r.magic_link_login)}catch(r){return this.errorResponse(r)}};oauthLogin=async(e,r,s,n)=>{let o=n;if(o||(o=c(h())),!Object.values(f).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");r&&r.length&&(o+=`&roles=${r.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${o}`)};resendOtp=async e=>{try{let r=await this.graphqlQuery({query:` mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(r.resend_otp)}catch(r){return this.errorResponse(r)}};resetPassword=async e=>{try{let r=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r.reset_password)}catch(r){return this.errorResponse(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let n=await(await m()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(n)};signup=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:e}});return this.okResponse(r.resend_otp)}catch(r){return this.errorResponse(r)}};resetPassword=async e=>{try{let r=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r.reset_password)}catch(r){return this.errorResponse(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let n=await(await y()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(n)};signup=async e=>{try{let r=await this.graphqlQuery({query:` mutation signup($data: SignUpInput!) { signup(params: $data) { ${l}}} `,variables:{data:e}});return this.okResponse(r.signup)}catch(r){return this.errorResponse(r)}};updateProfile=async(e,r)=>{try{let s=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}});return this.okResponse(s.update_profile)}catch(s){return this.errorResponse(new Error(s))}};deactivateAccount=async e=>{try{let r=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(r.deactivate_account)}catch(r){return this.errorResponse(r)}};validateJWTToken=async e=>{try{let r=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(r.validate_jwt_token)}catch(r){return this.errorResponse(r)}};validateSession=async e=>{try{let r=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${w} } } }`,variables:{params:e}});return this.okResponse(r.validate_session)}catch(r){return this.errorResponse(r)}};verifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${l}}} + `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};resendVerifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` + mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};verifyOtp=async e=>{try{let r=await this.graphqlQuery({query:` mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${l}}} - `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let n=await(await m()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(n.errors&&n.errors.length)throw console.error(n.errors),new Error(n.errors[0].message);return n.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(y,"Authorizer");export{y as Authorizer,f as OAuthProviders,d as ResponseTypes}; + `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let n=await(await y()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(n.errors&&n.errors.length)throw console.error(n.errors),new Error(n.errors[0].message);return n.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(g,"Authorizer");export{g as Authorizer,f as OAuthProviders,d as ResponseTypes}; diff --git a/lib/types.d.ts b/lib/types.d.ts deleted file mode 100644 index 81ed256..0000000 --- a/lib/types.d.ts +++ /dev/null @@ -1,205 +0,0 @@ -export interface ApiResponse { - ok: boolean; - error: Error | undefined; - response: T | undefined; -} -export interface ConfigType { - authorizerURL: string; - redirectURL: string; - clientID: string; - extraHeaders?: Record; -} -export interface User { - id: string; - email: string; - preferred_username: string; - email_verified: boolean; - signup_methods: string; - given_name?: string | null; - family_name?: string | null; - middle_name?: string | null; - nickname?: string | null; - picture?: string | null; - gender?: string | null; - birthdate?: string | null; - phone_number?: string | null; - phone_number_verified?: boolean | null; - roles?: string[]; - created_at: number; - updated_at: number; - is_multi_factor_auth_enabled?: boolean; - app_data?: Record; -} -export interface AuthToken { - message?: string; - access_token: string; - expires_in: number; - id_token: string; - refresh_token?: string; - user?: User; - should_show_email_otp_screen?: boolean; - should_show_mobile_otp_screen?: boolean; -} -export interface GenericResponse { - message: string; -} -export type Headers = Record; -export interface LoginInput { - email?: string; - phone_number?: string; - password: string; - roles?: string[]; - scope?: string[]; - state?: string; -} -export interface SignupInput { - email?: string; - password: string; - confirm_password: string; - given_name?: string; - family_name?: string; - middle_name?: string; - nickname?: string; - picture?: string; - gender?: string; - birthdate?: string; - phone_number?: string; - roles?: string[]; - scope?: string[]; - redirect_uri?: string; - is_multi_factor_auth_enabled?: boolean; - state?: string; - app_data?: Record; -} -export interface MagicLinkLoginInput { - email: string; - roles?: string[]; - scopes?: string[]; - state?: string; - redirect_uri?: string; -} -export interface VerifyEmailInput { - token: string; - state?: string; -} -export interface VerifyOtpInput { - email?: string; - phone_number?: string; - otp: string; - state?: string; -} -export interface ResendOtpInput { - email?: string; - phone_number?: string; -} -export interface GraphqlQueryInput { - query: string; - variables?: Record; - headers?: Headers; -} -export interface MetaData { - version: string; - client_id: string; - is_google_login_enabled: boolean; - is_facebook_login_enabled: boolean; - is_github_login_enabled: boolean; - is_linkedin_login_enabled: boolean; - is_apple_login_enabled: boolean; - is_twitter_login_enabled: boolean; - is_microsoft_login_enabled: boolean; - is_email_verification_enabled: boolean; - is_basic_authentication_enabled: boolean; - is_magic_link_login_enabled: boolean; - is_sign_up_enabled: boolean; - is_strong_password_enabled: boolean; -} -export interface UpdateProfileInput { - old_password?: string; - new_password?: string; - confirm_new_password?: string; - email?: string; - given_name?: string; - family_name?: string; - middle_name?: string; - nickname?: string; - gender?: string; - birthdate?: string; - phone_number?: string; - picture?: string; - is_multi_factor_auth_enabled?: boolean; - app_data?: Record; -} -export interface ForgotPasswordInput { - email: string; - state?: string; - redirect_uri?: string; -} -export interface ResetPasswordInput { - token: string; - password: string; - confirm_password: string; -} -export interface SessionQueryInput { - roles?: string[]; -} -export interface IsValidJWTQueryInput { - jwt: string; - roles?: string[]; -} -export interface ValidJWTResponse { - valid: string; - message: string; -} -export declare enum OAuthProviders { - Apple = "apple", - Github = "github", - Google = "google", - Facebook = "facebook", - LinkedIn = "linkedin" -} -export declare enum ResponseTypes { - Code = "code", - Token = "token" -} -export interface AuthorizeInput { - response_type: ResponseTypes; - use_refresh_token?: boolean; - response_mode?: string; -} -export interface AuthorizeResponse { - state: string; - code?: string; - error?: string; - error_description?: string; -} -export interface RevokeTokenInput { - refresh_token: string; -} -export interface GetTokenInput { - code?: string; - grant_type?: string; - refresh_token?: string; -} -export interface GetTokenResponse { - access_token: string; - expires_in: number; - id_token: string; - refresh_token?: string; -} -export interface ValidateJWTTokenInput { - token_type: 'access_token' | 'id_token' | 'refresh_token'; - token: string; - roles?: string[]; -} -export interface ValidateJWTTokenResponse { - is_valid: boolean; - claims: Record; -} -export interface ValidateSessionInput { - cookie?: string; - roles?: string[]; -} -export interface ValidateSessionResponse { - is_valid: boolean; - user: User; -} diff --git a/lib/utils.d.ts b/lib/utils.d.ts deleted file mode 100644 index 74d8245..0000000 --- a/lib/utils.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { AuthorizeResponse } from './types'; -export declare const hasWindow: () => boolean; -export declare const trimURL: (url: string) => string; -export declare const getCrypto: () => Crypto | null; -export declare const getCryptoSubtle: () => any; -export declare const createRandomString: () => string; -export declare const encode: (value: string) => string; -export declare const decode: (value: string) => string; -export declare const createQueryParams: (params: any) => string; -export declare const sha256: (s: string) => Promise; -export declare const urlDecodeB64: (input: string) => string; -export declare const bufferToBase64UrlEncoded: (input: number[] | Uint8Array) => string; -export declare const executeIframe: (authorizeUrl: string, eventOrigin: string, timeoutInSeconds?: number) => Promise; diff --git a/src/index.ts b/src/index.ts index 011d265..619891a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,10 +17,10 @@ import type { AuthToken, AuthorizeResponse, ConfigType, + GenericResponse, GetTokenResponse, MetaData, - User, - ValidateJWTTokenResponse, ValidateSessionResponse, GenericResponse + ResendVerifyEmailInput, User, ValidateJWTTokenResponse, ValidateSessionResponse, } from './types' // re-usable gql response fragment @@ -511,6 +511,24 @@ export class Authorizer { } } + resendVerifyEmail = async ( + data: ResendVerifyEmailInput, + ): Promise> => { + try { + const res = await this.graphqlQuery({ + query: ` + mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} + `, + variables: { data }, + }) + + return this.okResponse(res.verify_email) + } + catch (err) { + return this.errorResponse(err) + } + } + verifyOtp = async ( data: Types.VerifyOtpInput, ): Promise> => { diff --git a/src/types.ts b/src/types.ts index 3eb1257..da6bad5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -91,6 +91,11 @@ export interface VerifyEmailInput { state?: string } +export interface ResendVerifyEmailInput { + email: string + identifier: string +} + export interface VerifyOtpInput { email?: string phone_number?: string From 7504c57ab26ca3b106145c7c7a3eed5364cdced0 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 10 Nov 2023 15:18:42 +0200 Subject: [PATCH 19/26] trying package version bump --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1e1f9b3..511535a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@authorizerdev/authorizer-js", - "version": "2.2.13", + "version": "2.2.15", "packageManager": "pnpm@7.28.0", "author": "Lakhan Samani", "license": "MIT", From 489812f73c051f8bdf02b5dad5042090a3b26476 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Fri, 24 Nov 2023 15:53:48 +0200 Subject: [PATCH 20/26] lint fix copied over --- .gitignore | 1 + src/index.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index eb892a1..5978ff3 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ dist lib package-lock.json .idea +.history diff --git a/src/index.ts b/src/index.ts index 011d265..ab86cd1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,10 +17,10 @@ import type { AuthToken, AuthorizeResponse, ConfigType, + GenericResponse, GetTokenResponse, MetaData, - User, - ValidateJWTTokenResponse, ValidateSessionResponse, GenericResponse + User, ValidateJWTTokenResponse, ValidateSessionResponse, } from './types' // re-usable gql response fragment From ac79e5bae29643f4d83d8db87cd7d18902b92715 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Sun, 26 Nov 2023 19:06:46 +0200 Subject: [PATCH 21/26] include lib in gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index fe8285e..5978ff3 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ .DS_Store node_modules dist - +lib package-lock.json .idea .history From ae3d10f17931e1b24d31e5dfd8f216b3fc08814e Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 27 Nov 2023 13:13:26 +0200 Subject: [PATCH 22/26] As per recommendations, make errors of type Error[], change response to data, return grapqhl matching type from graphql Query call --- lib/authorizer.min.js | 16 +++---- lib/index.d.ts | 10 ++-- lib/index.js | 24 +++++----- lib/index.mjs | 16 +++---- src/index.ts | 105 +++++++++++++++++++++--------------------- src/types.ts | 8 +++- 6 files changed, 94 insertions(+), 85 deletions(-) diff --git a/lib/authorizer.min.js b/lib/authorizer.min.js index b8b267d..b6ab640 100644 --- a/lib/authorizer.min.js +++ b/lib/authorizer.min.js @@ -1,16 +1,16 @@ -var authorizerdev=(()=>{var le=Object.create;var U=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,we=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var j=(o,e,t)=>e in o?U(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,A=(o,e)=>{for(var t in e||(e={}))G.call(e,t)&&j(o,t,e[t]);if(J)for(var t of J(e))be.call(e,t)&&j(o,t,e[t]);return o},W=(o,e)=>ye(o,_e(e)),n=(o,e)=>U(o,"name",{value:e,configurable:!0});var Re=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ve=(o,e)=>{for(var t in e)U(o,t,{get:e[t],enumerable:!0})},Z=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of ge(e))!G.call(o,c)&&c!==t&&U(o,c,{get:()=>e[c],enumerable:!(i=me(e,c))||i.enumerable});return o};var Ee=(o,e,t)=>(t=o!=null?le(we(o)):{},Z(e||!o||!o.__esModule?U(t,"default",{value:o,enumerable:!0}):t,o)),Te=o=>Z(U({},"__esModule",{value:!0}),o);var f=(o,e,t)=>(j(o,typeof e!="symbol"?e+"":e,t),t);var d=(o,e,t)=>new Promise((i,c)=>{var u=w=>{try{g(t.next(w))}catch(m){c(m)}},_=w=>{try{g(t.throw(w))}catch(m){c(m)}},g=w=>w.done?i(w.value):Promise.resolve(w.value).then(u,_);g((t=t.apply(o,e)).next())});var Y=Re((R,K)=>{var X=typeof self!="undefined"?self:R,$=function(){function o(){this.fetch=!1,this.DOMException=X.DOMException}return n(o,"F"),o.prototype=X,new o}();(function(o){var e=function(t){var i={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(r){return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function c(r){return r&&DataView.prototype.isPrototypeOf(r)}if(n(c,"isDataView"),i.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],_=ArrayBuffer.isView||function(r){return r&&u.indexOf(Object.prototype.toString.call(r))>-1};function g(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(r))throw new TypeError("Invalid character in header field name");return r.toLowerCase()}n(g,"normalizeName");function w(r){return typeof r!="string"&&(r=String(r)),r}n(w,"normalizeValue");function m(r){var s={next:function(){var a=r.shift();return{done:a===void 0,value:a}}};return i.iterable&&(s[Symbol.iterator]=function(){return s}),s}n(m,"iteratorFor");function p(r){this.map={},r instanceof p?r.forEach(function(s,a){this.append(a,s)},this):Array.isArray(r)?r.forEach(function(s){this.append(s[0],s[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(s){this.append(s,r[s])},this)}n(p,"Headers"),p.prototype.append=function(r,s){r=g(r),s=w(s);var a=this.map[r];this.map[r]=a?a+", "+s:s},p.prototype.delete=function(r){delete this.map[g(r)]},p.prototype.get=function(r){return r=g(r),this.has(r)?this.map[r]:null},p.prototype.has=function(r){return this.map.hasOwnProperty(g(r))},p.prototype.set=function(r,s){this.map[g(r)]=w(s)},p.prototype.forEach=function(r,s){for(var a in this.map)this.map.hasOwnProperty(a)&&r.call(s,this.map[a],a,this)},p.prototype.keys=function(){var r=[];return this.forEach(function(s,a){r.push(a)}),m(r)},p.prototype.values=function(){var r=[];return this.forEach(function(s){r.push(s)}),m(r)},p.prototype.entries=function(){var r=[];return this.forEach(function(s,a){r.push([a,s])}),m(r)},i.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function D(r){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}n(D,"consumed");function N(r){return new Promise(function(s,a){r.onload=function(){s(r.result)},r.onerror=function(){a(r.error)}})}n(N,"fileReaderReady");function ie(r){var s=new FileReader,a=N(s);return s.readAsArrayBuffer(r),a}n(ie,"readBlobAsArrayBuffer");function ae(r){var s=new FileReader,a=N(s);return s.readAsText(r),a}n(ae,"readBlobAsText");function ce(r){for(var s=new Uint8Array(r),a=new Array(s.length),y=0;y-1?s:r}n(he,"normalizeMethod");function E(r,s){s=s||{};var a=s.body;if(r instanceof E){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,s.headers||(this.headers=new p(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!a&&r._bodyInit!=null&&(a=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=s.credentials||this.credentials||"same-origin",(s.headers||!this.headers)&&(this.headers=new p(s.headers)),this.method=he(s.method||this.method||"GET"),this.mode=s.mode||this.mode||null,this.signal=s.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}n(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function fe(r){var s=new FormData;return r.trim().split("&").forEach(function(a){if(a){var y=a.split("="),l=y.shift().replace(/\+/g," "),h=y.join("=").replace(/\+/g," ");s.append(decodeURIComponent(l),decodeURIComponent(h))}}),s}n(fe,"decode");function de(r){var s=new p,a=r.replace(/\r?\n[\t ]+/g," ");return a.split(/\r?\n/).forEach(function(y){var l=y.split(":"),h=l.shift().trim();if(h){var x=l.join(":").trim();s.append(h,x)}}),s}n(de,"parseHeaders"),V.call(E.prototype);function b(r,s){s||(s={}),this.type="default",this.status=s.status===void 0?200:s.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in s?s.statusText:"OK",this.headers=new p(s.headers),this.url=s.url||"",this._initBody(r)}n(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var r=new b(null,{status:0,statusText:""});return r.type="error",r};var pe=[301,302,303,307,308];b.redirect=function(r,s){if(pe.indexOf(s)===-1)throw new RangeError("Invalid status code");return new b(null,{status:s,headers:{location:r}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(r){t.DOMException=function(s,a){this.message=s,this.name=a;var y=Error(s);this.stack=y.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function P(r,s){return new Promise(function(a,y){var l=new E(r,s);if(l.signal&&l.signal.aborted)return y(new t.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function x(){h.abort()}n(x,"abortXhr"),h.onload=function(){var L={status:h.status,statusText:h.statusText,headers:de(h.getAllResponseHeaders()||"")};L.url="responseURL"in h?h.responseURL:L.headers.get("X-Request-URL");var C="response"in h?h.response:h.responseText;a(new b(C,L))},h.onerror=function(){y(new TypeError("Network request failed"))},h.ontimeout=function(){y(new TypeError("Network request failed"))},h.onabort=function(){y(new t.DOMException("Aborted","AbortError"))},h.open(l.method,l.url,!0),l.credentials==="include"?h.withCredentials=!0:l.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&i.blob&&(h.responseType="blob"),l.headers.forEach(function(L,C){h.setRequestHeader(C,L)}),l.signal&&(l.signal.addEventListener("abort",x),h.onreadystatechange=function(){h.readyState===4&&l.signal.removeEventListener("abort",x)}),h.send(typeof l._bodyInit=="undefined"?null:l._bodyInit)})}return n(P,"fetch"),P.polyfill=!0,o.fetch||(o.fetch=P,o.Headers=p,o.Request=E,o.Response=b),t.Headers=p,t.Request=E,t.Response=b,t.fetch=P,Object.defineProperty(t,"__esModule",{value:!0}),t}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var I=$;R=I.fetch;R.default=I.fetch;R.fetch=I.fetch;R.Headers=I.Headers;R.Request=I.Request;R.Response=I.Response;K.exports=R});var Oe={};ve(Oe,{Authorizer:()=>B,OAuthProviders:()=>q,ResponseTypes:()=>O});var ne=Ee(Y());var q;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin"})(q||(q={}));var O;(function(o){o.Code="code",o.Token="token"})(O||(O={}));var T=n(()=>typeof window!="undefined","hasWindow"),M=n(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=n(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=n(()=>{let o=ee();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),k=n(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=ee();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(c=>e+=o[c%o.length]),e},"createRandomString"),v=n(o=>T()?btoa(o):Buffer.from(o).toString("base64"),"encode");var re=n(o=>Object.keys(o).filter(e=>typeof o[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),te=n(o=>d(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,i)=>{e.oncomplete=c=>{t(c.target.result)},e.onerror=c=>{i(c.error)},e.onabort=()=>{i(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Ie=n(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var oe=n(o=>{let e=new Uint8Array(o);return Ie(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),se=n((o,e,t=60)=>new Promise((i,c)=>{let u=window.document.createElement("iframe");u.setAttribute("id","authorizer-iframe"),u.setAttribute("width","0"),u.setAttribute("height","0"),u.style.display="none";let _,g=n(()=>{window.document.body.contains(u)&&(window.document.body.removeChild(u),window.removeEventListener("message",_,!1))},"removeIframe"),w=setTimeout(()=>{g()},t*1e3);_=n(function(m){if(m.origin!==e||!m.data||!m.data.response)return;let p=m.source;p&&p.close(),m.data.response.error?c(m.data.response):i(m.data.response),clearTimeout(w),window.removeEventListener("message",_,!1),setTimeout(g,2*1e3)},"iframeEventHandler"),window.addEventListener("message",_,!1),window.document.body.appendChild(u),u.setAttribute("src",o)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",S=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${H}}`,z=n(()=>T()?window.fetch:ne.default,"getFetcher"),B=class{constructor(e){f(this,"authorize",n(e=>d(this,null,function*(){if(!T())return this.errorResponse(new Error("this feature is only supported in browser"));let t=["openid","profile","email"];e.use_refresh_token&&t.push("offline_access");let i={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(k()),nonce:v(k()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===O.Code){this.codeVerifier=k();let u=yield te(this.codeVerifier),_=oe(u);i.code_challenge=_}let c=`${this.config.authorizerURL}/authorize?${re(i)}`;if(i.response_mode!=="web_message")return window.location.replace(c),this.okResponse(void 0);try{let u=yield se(c,this.config.authorizerURL,60);if(e.response_type===O.Code){let _=yield this.getToken({code:u.code});return _.ok?this.okResponse(_.response):this.errorResponse(_.error)}return this.okResponse(u)}catch(u){return u.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(u)}}),"authorize"));f(this,"browserLogin",n(()=>d(this,null,function*(){try{let e=yield this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}}),"browserLogin"));f(this,"forgotPassword",n(e=>d(this,null,function*(){e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let t=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(t==null?void 0:t.forgot_password)}catch(t){return this.errorResponse(t)}}),"forgotPassword"));f(this,"getMetaData",n(()=>d(this,null,function*(){try{let e=yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}}),"getMetaData"));f(this,"getProfile",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e});return this.okResponse(t.profile)}catch(t){return this.errorResponse(t)}}),"getProfile"));f(this,"getSession",n((e,t)=>d(this,null,function*(){try{let i=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${S} } }`,headers:e,variables:{params:t}});return this.okResponse(i.session)}catch(i){return this.errorResponse(i)}}),"getSession"));f(this,"getToken",n(e=>d(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let c=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:A({},this.config.extraHeaders),credentials:"include"}),u=yield c.json();return c.status>=400?this.errorResponse(new Error(u)):this.okResponse(u)}catch(i){return this.errorResponse(i)}}),"getToken"));f(this,"login",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` +var authorizerdev=(()=>{var fe=Object.create;var U=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,we=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var F=(n,e,o)=>e in n?U(n,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[e]=o,A=(n,e)=>{for(var o in e||(e={}))G.call(e,o)&&F(n,o,e[o]);if(J)for(var o of J(e))be.call(e,o)&&F(n,o,e[o]);return n},W=(n,e)=>ye(n,_e(e)),a=(n,e)=>U(n,"name",{value:e,configurable:!0});var Re=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ve=(n,e)=>{for(var o in e)U(n,o,{get:e[o],enumerable:!0})},Z=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ge(e))!G.call(n,r)&&r!==o&&U(n,r,{get:()=>e[r],enumerable:!(s=me(e,r))||s.enumerable});return n};var Ee=(n,e,o)=>(o=n!=null?fe(we(n)):{},Z(e||!n||!n.__esModule?U(o,"default",{value:n,enumerable:!0}):o,n)),Te=n=>Z(U({},"__esModule",{value:!0}),n);var d=(n,e,o)=>(F(n,typeof e!="symbol"?e+"":e,o),o);var l=(n,e,o)=>new Promise((s,r)=>{var c=w=>{try{g(o.next(w))}catch(m){r(m)}},_=w=>{try{g(o.throw(w))}catch(m){r(m)}},g=w=>w.done?s(w.value):Promise.resolve(w.value).then(c,_);g((o=o.apply(n,e)).next())});var Y=Re((R,K)=>{var X=typeof self!="undefined"?self:R,$=function(){function n(){this.fetch=!1,this.DOMException=X.DOMException}return a(n,"F"),n.prototype=X,new n}();(function(n){var e=function(o){var s={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function r(t){return t&&DataView.prototype.isPrototypeOf(t)}if(a(r,"isDataView"),s.arrayBuffer)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],_=ArrayBuffer.isView||function(t){return t&&c.indexOf(Object.prototype.toString.call(t))>-1};function g(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}a(g,"normalizeName");function w(t){return typeof t!="string"&&(t=String(t)),t}a(w,"normalizeValue");function m(t){var i={next:function(){var h=t.shift();return{done:h===void 0,value:h}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}a(m,"iteratorFor");function p(t){this.map={},t instanceof p?t.forEach(function(i,h){this.append(h,i)},this):Array.isArray(t)?t.forEach(function(i){this.append(i[0],i[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(i){this.append(i,t[i])},this)}a(p,"Headers"),p.prototype.append=function(t,i){t=g(t),i=w(i);var h=this.map[t];this.map[t]=h?h+", "+i:i},p.prototype.delete=function(t){delete this.map[g(t)]},p.prototype.get=function(t){return t=g(t),this.has(t)?this.map[t]:null},p.prototype.has=function(t){return this.map.hasOwnProperty(g(t))},p.prototype.set=function(t,i){this.map[g(t)]=w(i)},p.prototype.forEach=function(t,i){for(var h in this.map)this.map.hasOwnProperty(h)&&t.call(i,this.map[h],h,this)},p.prototype.keys=function(){var t=[];return this.forEach(function(i,h){t.push(h)}),m(t)},p.prototype.values=function(){var t=[];return this.forEach(function(i){t.push(i)}),m(t)},p.prototype.entries=function(){var t=[];return this.forEach(function(i,h){t.push([h,i])}),m(t)},s.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function D(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}a(D,"consumed");function N(t){return new Promise(function(i,h){t.onload=function(){i(t.result)},t.onerror=function(){h(t.error)}})}a(N,"fileReaderReady");function ie(t){var i=new FileReader,h=N(i);return i.readAsArrayBuffer(t),h}a(ie,"readBlobAsArrayBuffer");function ae(t){var i=new FileReader,h=N(i);return i.readAsText(t),h}a(ae,"readBlobAsText");function ce(t){for(var i=new Uint8Array(t),h=new Array(i.length),y=0;y-1?i:t}a(ue,"normalizeMethod");function E(t,i){i=i||{};var h=i.body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,i.headers||(this.headers=new p(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!h&&t._bodyInit!=null&&(h=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new p(i.headers)),this.method=ue(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&h)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(h)}a(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function de(t){var i=new FormData;return t.trim().split("&").forEach(function(h){if(h){var y=h.split("="),f=y.shift().replace(/\+/g," "),u=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(f),decodeURIComponent(u))}}),i}a(de,"decode");function le(t){var i=new p,h=t.replace(/\r?\n[\t ]+/g," ");return h.split(/\r?\n/).forEach(function(y){var f=y.split(":"),u=f.shift().trim();if(u){var x=f.join(":").trim();i.append(u,x)}}),i}a(le,"parseHeaders"),V.call(E.prototype);function b(t,i){i||(i={}),this.type="default",this.status=i.status===void 0?200:i.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in i?i.statusText:"OK",this.headers=new p(i.headers),this.url=i.url||"",this._initBody(t)}a(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var t=new b(null,{status:0,statusText:""});return t.type="error",t};var pe=[301,302,303,307,308];b.redirect=function(t,i){if(pe.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:t}})},o.DOMException=n.DOMException;try{new o.DOMException}catch(t){o.DOMException=function(i,h){this.message=i,this.name=h;var y=Error(i);this.stack=y.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function P(t,i){return new Promise(function(h,y){var f=new E(t,i);if(f.signal&&f.signal.aborted)return y(new o.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function x(){u.abort()}a(x,"abortXhr"),u.onload=function(){var L={status:u.status,statusText:u.statusText,headers:le(u.getAllResponseHeaders()||"")};L.url="responseURL"in u?u.responseURL:L.headers.get("X-Request-URL");var C="response"in u?u.response:u.responseText;h(new b(C,L))},u.onerror=function(){y(new TypeError("Network request failed"))},u.ontimeout=function(){y(new TypeError("Network request failed"))},u.onabort=function(){y(new o.DOMException("Aborted","AbortError"))},u.open(f.method,f.url,!0),f.credentials==="include"?u.withCredentials=!0:f.credentials==="omit"&&(u.withCredentials=!1),"responseType"in u&&s.blob&&(u.responseType="blob"),f.headers.forEach(function(L,C){u.setRequestHeader(C,L)}),f.signal&&(f.signal.addEventListener("abort",x),u.onreadystatechange=function(){u.readyState===4&&f.signal.removeEventListener("abort",x)}),u.send(typeof f._bodyInit=="undefined"?null:f._bodyInit)})}return a(P,"fetch"),P.polyfill=!0,n.fetch||(n.fetch=P,n.Headers=p,n.Request=E,n.Response=b),o.Headers=p,o.Request=E,o.Response=b,o.fetch=P,Object.defineProperty(o,"__esModule",{value:!0}),o}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var I=$;R=I.fetch;R.default=I.fetch;R.fetch=I.fetch;R.Headers=I.Headers;R.Request=I.Request;R.Response=I.Response;K.exports=R});var Oe={};ve(Oe,{Authorizer:()=>B,OAuthProviders:()=>q,ResponseTypes:()=>O});var ne=Ee(Y());var q;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin"})(q||(q={}));var O;(function(n){n.Code="code",n.Token="token"})(O||(O={}));var T=a(()=>typeof window!="undefined","hasWindow"),M=a(n=>{let e=n.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=a(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=a(()=>{let n=ee();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),k=a(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",o=ee();return o&&Array.from(o.getRandomValues(new Uint8Array(43))).forEach(r=>e+=n[r%n.length]),e},"createRandomString"),v=a(n=>T()?btoa(n):Buffer.from(n).toString("base64"),"encode");var re=a(n=>Object.keys(n).filter(e=>typeof n[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`).join("&"),"createQueryParams"),te=a(n=>l(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((o,s)=>{e.oncomplete=r=>{o(r.target.result)},e.onerror=r=>{s(r.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Ie=a(n=>{let e={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,o=>e[o])},"urlEncodeB64");var oe=a(n=>{let e=new Uint8Array(n);return Ie(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),se=a((n,e,o=60)=>new Promise((s,r)=>{let c=window.document.createElement("iframe");c.setAttribute("id","authorizer-iframe"),c.setAttribute("width","0"),c.setAttribute("height","0"),c.style.display="none";let _,g=a(()=>{window.document.body.contains(c)&&(window.document.body.removeChild(c),window.removeEventListener("message",_,!1))},"removeIframe"),w=setTimeout(()=>{g()},o*1e3);_=a(function(m){if(m.origin!==e||!m.data||!m.data.response)return;let p=m.source;p&&p.close(),m.data.response.error?r(m.data.response):s(m.data.response),clearTimeout(w),window.removeEventListener("message",_,!1),setTimeout(g,2*1e3)},"iframeEventHandler"),window.addEventListener("message",_,!1),window.document.body.appendChild(c),c.setAttribute("src",n)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",S=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${H}}`,z=a(()=>T()?window.fetch:ne.default,"getFetcher"),B=class{constructor(e){d(this,"authorize",a(e=>l(this,null,function*(){if(!T())return this.errorResponse([new Error("this feature is only supported in browser")]);let o=["openid","profile","email"];e.use_refresh_token&&o.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(k()),nonce:v(k()),response_type:e.response_type,scope:o.join(" "),client_id:this.config.clientID};if(e.response_type===O.Code){this.codeVerifier=k();let c=yield te(this.codeVerifier),_=oe(c);s.code_challenge=_}let r=`${this.config.authorizerURL}/authorize?${re(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let c=yield se(r,this.config.authorizerURL,60);if(e.response_type===O.Code){let _=yield this.getToken({code:c.code});return _.ok?this.okResponse(_.data):this.errorResponse(_.errors)}return this.okResponse(c)}catch(c){return c.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(c)}}),"authorize"));d(this,"browserLogin",a(()=>l(this,null,function*(){try{let e=yield this.getSession();return e.ok?this.okResponse(e.data):this.errorResponse(e.errors)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}}),"browserLogin"));d(this,"forgotPassword",a(e=>l(this,null,function*(){var o;e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let s=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}}),"forgotPassword"));d(this,"getMetaData",a(()=>l(this,null,function*(){var e;try{let o=yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return(e=o==null?void 0:o.errors)!=null&&e.length?this.errorResponse(o.errors):this.okResponse(o.data.meta)}catch(o){return this.errorResponse([o])}}),"getMetaData"));d(this,"getProfile",a(e=>l(this,null,function*(){var o;try{let s=yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}}),"getProfile"));d(this,"getSession",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${S} } }`,headers:e,variables:{params:o}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.session)}catch(c){return this.errorResponse(c)}}),"getSession"));d(this,"getToken",a(e=>l(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let o={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let r=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(o),headers:A({},this.config.extraHeaders),credentials:"include"}),c=yield r.json();return r.status>=400?this.errorResponse([new Error(c)]):this.okResponse(c)}catch(s){return this.errorResponse(s)}}),"getToken"));d(this,"login",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` mutation login($data: LoginInput!) { login(params: $data) { ${S}}} - `,variables:{data:e}});return this.okResponse(t.login)}catch(t){return this.errorResponse(new Error(t))}}),"login"));f(this,"logout",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(t.response)}catch(t){return console.error(t),this.errorResponse(t)}}),"logout"));f(this,"magicLinkLogin",n(e=>d(this,null,function*(){try{e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let t=yield this.graphqlQuery({query:` + `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.login)}catch(r){return this.errorResponse([new Error(r)])}}),"login"));d(this,"logout",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.response)}catch(r){return console.error(r),this.errorResponse([r])}}),"logout"));d(this,"magicLinkLogin",a(e=>l(this,null,function*(){var o,s;try{e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=yield this.graphqlQuery({query:` mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(t.magic_link_login)}catch(t){return this.errorResponse(t)}}),"magicLinkLogin"));f(this,"oauthLogin",n((e,t,i,c)=>d(this,null,function*(){let u=c;if(u||(u=v(k())),!Object.values(q).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!T())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(u+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${i||this.config.redirectURL}&state=${u}`)}),"oauthLogin"));f(this,"resendOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.magic_link_login)}catch(r){return this.errorResponse([r])}}),"magicLinkLogin"));d(this,"oauthLogin",a((e,o,s,r)=>l(this,null,function*(){let c=r;if(c||(c=v(k())),!Object.values(q).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!T())throw new Error("oauthLogin is only supported for browsers");o&&o.length&&(c+=`&roles=${o.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${c}`)}),"oauthLogin"));d(this,"resendOtp",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(t.resend_otp)}catch(t){return this.errorResponse(t)}}),"resendOtp"));f(this,"resetPassword",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(t.reset_password)}catch(t){return this.errorResponse(t)}}),"resetPassword"));f(this,"revokeToken",n(e=>d(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let c=yield(yield z()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:A({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(c)}),"revokeToken"));f(this,"signup",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_otp)}catch(r){return this.errorResponse([r])}}),"resendOtp"));d(this,"resetPassword",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.reset_password)}catch(r){return this.errorResponse([r])}}),"resetPassword"));d(this,"revokeToken",a(e=>l(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let r=yield(yield z()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:A({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(r)}),"revokeToken"));d(this,"signup",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` mutation signup($data: SignUpInput!) { signup(params: $data) { ${S}}} - `,variables:{data:e}});return this.okResponse(t.signup)}catch(t){return this.errorResponse(t)}}),"signup"));f(this,"updateProfile",n((e,t)=>d(this,null,function*(){try{let i=yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:e}});return this.okResponse(i.update_profile)}catch(i){return this.errorResponse(new Error(i))}}),"updateProfile"));f(this,"deactivateAccount",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(t.deactivate_account)}catch(t){return this.errorResponse(t)}}),"deactivateAccount"));f(this,"validateJWTToken",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(t.validate_jwt_token)}catch(t){return this.errorResponse(t)}}),"validateJWTToken"));f(this,"validateSession",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${H} } } }`,variables:{params:e}});return this.okResponse(t.validate_session)}catch(t){return this.errorResponse(t)}}),"validateSession"));f(this,"verifyEmail",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.signup)}catch(r){return this.errorResponse([r])}}),"signup"));d(this,"updateProfile",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:o,variables:{data:e}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.update_profile)}catch(c){return this.errorResponse([c])}}),"updateProfile"));d(this,"deactivateAccount",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.deactivate_account)}catch(r){return this.errorResponse([r])}}),"deactivateAccount"));d(this,"validateJWTToken",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_jwt_token)}catch(r){return this.errorResponse([r])}}),"validateJWTToken"));d(this,"validateSession",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${H} } } }`,variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_session)}catch(r){return this.errorResponse([r])}}),"validateSession"));d(this,"verifyEmail",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${S}}} - `,variables:{data:e}});return this.okResponse(t.verify_email)}catch(t){return this.errorResponse(t)}}),"verifyEmail"));f(this,"resendVerifyEmail",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"verifyEmail"));d(this,"resendVerifyEmail",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(t.verify_email)}catch(t){return this.errorResponse(t)}}),"resendVerifyEmail"));f(this,"verifyOtp",n(e=>d(this,null,function*(){try{let t=yield this.graphqlQuery({query:` + `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"resendVerifyEmail"));d(this,"verifyOtp",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${S}}} - `,variables:{data:e}});return this.okResponse(t.verify_otp)}catch(t){return this.errorResponse(t)}}),"verifyOtp"));f(this,"graphqlQuery",n(e=>d(this,null,function*(){let c=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:A(A({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();if(c.errors&&c.errors.length)throw console.error(c.errors),new Error(c.errors[0].message);return c.data}),"graphqlQuery"));f(this,"errorResponse",n(e=>({ok:!1,response:void 0,error:e}),"errorResponse"));f(this,"okResponse",n(e=>({ok:!0,response:e,error:void 0}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=M(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=M(e.redirectURL),this.config.extraHeaders=W(A({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};n(B,"Authorizer");return Te(Oe);})(); + `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}}),"verifyOtp"));d(this,"graphqlQuery",a(e=>l(this,null,function*(){var c;let r=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:A(A({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();return(c=r==null?void 0:r.errors)!=null&&c.length?(console.error(r.errors),{data:void 0,errors:r.errors}):{data:r.data,errors:[]}}),"graphqlQuery"));d(this,"errorResponse",a(e=>({ok:!1,data:void 0,errors:e}),"errorResponse"));d(this,"okResponse",a(e=>({ok:!0,data:e,errors:[]}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=M(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=M(e.redirectURL),this.config.extraHeaders=W(A({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};a(B,"Authorizer");return Te(Oe);})(); window.__TAURI__ = authorizerdev diff --git a/lib/index.d.ts b/lib/index.d.ts index cc36d10..b169a06 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -1,7 +1,11 @@ +interface GrapQlResponseType { + data: any | undefined; + errors: Error[]; +} interface ApiResponse { ok: boolean; - error: Error | undefined; - response: T | undefined; + errors: Error[]; + data: T | undefined; } interface ConfigType { authorizerURL: string; @@ -241,4 +245,4 @@ declare class Authorizer { private okResponse; } -export { ApiResponse, AuthToken, AuthorizeInput, AuthorizeResponse, Authorizer, ConfigType, ForgotPasswordInput, GenericResponse, GetTokenInput, GetTokenResponse, GraphqlQueryInput, Headers, IsValidJWTQueryInput, LoginInput, MagicLinkLoginInput, MetaData, OAuthProviders, ResendOtpInput, ResendVerifyEmailInput, ResetPasswordInput, ResponseTypes, RevokeTokenInput, SessionQueryInput, SignupInput, UpdateProfileInput, User, ValidJWTResponse, ValidateJWTTokenInput, ValidateJWTTokenResponse, ValidateSessionInput, ValidateSessionResponse, VerifyEmailInput, VerifyOtpInput }; +export { ApiResponse, AuthToken, AuthorizeInput, AuthorizeResponse, Authorizer, ConfigType, ForgotPasswordInput, GenericResponse, GetTokenInput, GetTokenResponse, GrapQlResponseType, GraphqlQueryInput, Headers, IsValidJWTQueryInput, LoginInput, MagicLinkLoginInput, MetaData, OAuthProviders, ResendOtpInput, ResendVerifyEmailInput, ResetPasswordInput, ResponseTypes, RevokeTokenInput, SessionQueryInput, SignupInput, UpdateProfileInput, User, ValidJWTResponse, ValidateJWTTokenInput, ValidateJWTTokenResponse, ValidateSessionInput, ValidateSessionResponse, VerifyEmailInput, VerifyOtpInput }; diff --git a/lib/index.js b/lib/index.js index cb56832..f1e6d5b 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,15 +1,15 @@ -var S=Object.create;var l=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var i=(t,e)=>l(t,"name",{value:e,configurable:!0});var Q=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},v=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of x(e))!A.call(t,s)&&s!==r&&l(t,s,{get:()=>e[s],enumerable:!(o=O(e,s))||o.enumerable});return t};var z=(t,e,r)=>(r=t!=null?S(C(t)):{},v(e||!t||!t.__esModule?l(r,"default",{value:t,enumerable:!0}):r,t)),D=t=>v(l({},"__esModule",{value:!0}),t);var F={};Q(F,{Authorizer:()=>m,OAuthProviders:()=>f,ResponseTypes:()=>d});module.exports=D(F);var q=z(require("cross-fetch"));var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),g=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),E=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),j=i(()=>{let t=E();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=E();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(s=>e+=t[s%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var $=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),U=i(async t=>{let e=j().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,o)=>{e.oncomplete=s=>{r(s.target.result)},e.onerror=s=>{o(s.error)},e.onabort=()=>{o(new Error("The digest operation was aborted"))}}):await e},"sha256"),V=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var T=i(t=>{let e=new Uint8Array(t);return V(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),L=i((t,e,r=60)=>new Promise((o,s)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a,b=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",a,!1))},"removeIframe"),I=setTimeout(()=>{b()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let k=u.source;k&&k.close(),u.data.response.error?s(u.data.response):o(u.data.response),clearTimeout(I),window.removeEventListener("message",a,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(n),n.setAttribute("src",t)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",_=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${R}}`,w=i(()=>p()?window.fetch:q.default,"getFetcher"),m=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=g(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=g(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let o={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let n=await U(this.codeVerifier),a=T(n);o.code_challenge=a}let s=`${this.config.authorizerURL}/authorize?${$(o)}`;if(o.response_mode!=="web_message")return window.location.replace(s),this.okResponse(void 0);try{let n=await L(s,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:n.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${_} } }`,headers:e,variables:{params:r}});return this.okResponse(o.session)}catch(o){return this.errorResponse(o)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let s=await w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),n=await s.json();return s.status>=400?this.errorResponse(new Error(n)):this.okResponse(n)}catch(o){return this.errorResponse(o)}};login=async e=>{try{let r=await this.graphqlQuery({query:` - mutation login($data: LoginInput!) { login(params: $data) { ${_}}} - `,variables:{data:e}});return this.okResponse(r.login)}catch(r){return this.errorResponse(new Error(r))}};logout=async e=>{try{let r=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(r.response)}catch(r){return console.error(r),this.errorResponse(r)}};magicLinkLogin=async e=>{try{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=await this.graphqlQuery({query:` +var S=Object.create;var l=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var i=(o,r)=>l(o,"name",{value:r,configurable:!0});var Q=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},v=(o,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of x(r))!A.call(o,e)&&e!==t&&l(o,e,{get:()=>r[e],enumerable:!(s=O(r,e))||s.enumerable});return o};var z=(o,r,t)=>(t=o!=null?S(C(o)):{},v(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),D=o=>v(l({},"__esModule",{value:!0}),o);var P={};Q(P,{Authorizer:()=>_,OAuthProviders:()=>g,ResponseTypes:()=>d});module.exports=D(P);var q=z(require("cross-fetch"));var g;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin"})(g||(g={}));var d;(function(o){o.Code="code",o.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),y=i(o=>{let r=o.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),$=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),j=i(()=>{let o=$();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",t=$();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(e=>r+=o[e%o.length]),r},"createRandomString"),c=i(o=>p()?btoa(o):Buffer.from(o).toString("base64"),"encode");var U=i(o=>Object.keys(o).filter(r=>typeof o[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(o[r])}`).join("&"),"createQueryParams"),E=i(async o=>{let r=j().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{r.oncomplete=e=>{t(e.target.result)},r.onerror=e=>{s(e.error)},r.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await r},"sha256"),F=i(o=>{let r={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>r[t])},"urlEncodeB64");var T=i(o=>{let r=new Uint8Array(o);return F(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),L=i((o,r,t=60)=>new Promise((s,e)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a,b=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",a,!1))},"removeIframe"),I=setTimeout(()=>{b()},t*1e3);a=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let k=h.source;k&&k.close(),h.data.response.error?e(h.data.response):s(h.data.response),clearTimeout(I),window.removeEventListener("message",a,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(n),n.setAttribute("src",o)}),"executeIframe");var w="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",f=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${w}}`,R=i(()=>p()?window.fetch:q.default,"getFetcher"),_=class{constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(r.authorizerURL&&(this.config.authorizerURL=y(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let t=["openid","profile","email"];r.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:t.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let n=await E(this.codeVerifier),a=T(n);s.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${U(s)}`;if(s.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let n=await L(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:n.code});return a.ok?this.okResponse(a.data):this.errorResponse(a.errors)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let r=await this.getSession();return r.ok?this.okResponse(r.data):this.errorResponse(r.errors)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{ok:!1,data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var t;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let s=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:r}});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}};getMetaData=async()=>{var r;try{let t=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return(r=t==null?void 0:t.errors)!=null&&r.length?this.errorResponse(t.errors):this.okResponse(t.data.meta)}catch(t){return this.errorResponse([t])}};getProfile=async r=>{var t;try{let s=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:r});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}};getSession=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${f} } }`,headers:r,variables:{params:t}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.session)}catch(n){return this.errorResponse(n)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let t={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await R()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:{...this.config.extraHeaders},credentials:"include"}),n=await e.json();return e.status>=400?this.errorResponse([new Error(n)]):this.okResponse(n)}catch(s){return this.errorResponse(s)}};login=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` + mutation login($data: LoginInput!) { login(params: $data) { ${f}}} + `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var t,s;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.response)}catch(e){return console.error(e),this.errorResponse([e])}};magicLinkLogin=async r=>{var t,s;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=await this.graphqlQuery({query:` mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(r.magic_link_login)}catch(r){return this.errorResponse(r)}};oauthLogin=async(e,r,o,s)=>{let n=s;if(n||(n=c(h())),!Object.values(f).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");r&&r.length&&(n+=`&roles=${r.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${o||this.config.redirectURL}&state=${n}`)};resendOtp=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.magic_link_login)}catch(e){return this.errorResponse([e])}};oauthLogin=async(r,t,s,e)=>{let n=e;if(n||(n=c(u())),!Object.values(g).includes(r))throw new Error(`only following oauth providers are supported: ${Object.values(r).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(n+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${r}?redirect_uri=${s||this.config.redirectURL}&state=${n}`)};resendOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(r.resend_otp)}catch(r){return this.errorResponse(r)}};resetPassword=async e=>{try{let r=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r.reset_password)}catch(r){return this.errorResponse(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let s=await(await w()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(s)};signup=async e=>{try{let r=await this.graphqlQuery({query:` - mutation signup($data: SignUpInput!) { signup(params: $data) { ${_}}} - `,variables:{data:e}});return this.okResponse(r.signup)}catch(r){return this.errorResponse(r)}};updateProfile=async(e,r)=>{try{let o=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}});return this.okResponse(o.update_profile)}catch(o){return this.errorResponse(new Error(o))}};deactivateAccount=async e=>{try{let r=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(r.deactivate_account)}catch(r){return this.errorResponse(r)}};validateJWTToken=async e=>{try{let r=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(r.validate_jwt_token)}catch(r){return this.errorResponse(r)}};validateSession=async e=>{try{let r=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:e}});return this.okResponse(r.validate_session)}catch(r){return this.errorResponse(r)}};verifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` - mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${_}}} - `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};resendVerifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.resend_otp)}catch(e){return this.errorResponse([e])}};resetPassword=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.reset_password)}catch(e){return this.errorResponse([e])}};revokeToken=async r=>{if(!r.refresh_token&&!r.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let e=await(await R()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:r.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(e)};signup=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` + mutation signup($data: SignUpInput!) { signup(params: $data) { ${f}}} + `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.signup)}catch(e){return this.errorResponse([e])}};updateProfile=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:r}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.update_profile)}catch(n){return this.errorResponse([n])}};deactivateAccount=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.deactivate_account)}catch(e){return this.errorResponse([e])}};validateJWTToken=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_jwt_token)}catch(e){return this.errorResponse([e])}};validateSession=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${w} } } }`,variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_session)}catch(e){return this.errorResponse([e])}};verifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` + mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${f}}} + `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};resendVerifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};verifyOtp=async e=>{try{let r=await this.graphqlQuery({query:` - mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${_}}} - `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let s=await(await w()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(s.errors&&s.errors.length)throw console.error(s.errors),new Error(s.errors[0].message);return s.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(m,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes}); + `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` + mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${f}}} + `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var n;let e=await(await R()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(n=e==null?void 0:e.errors)!=null&&n.length?(console.error(e.errors),{data:void 0,errors:e.errors}):{data:e.data,errors:[]}};errorResponse=r=>({ok:!1,data:void 0,errors:r});okResponse=r=>({ok:!0,data:r,errors:[]})};i(_,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes}); diff --git a/lib/index.mjs b/lib/index.mjs index 6c74016..4857278 100644 --- a/lib/index.mjs +++ b/lib/index.mjs @@ -1,15 +1,15 @@ -var L=Object.defineProperty;var i=(t,e)=>L(t,"name",{value:e,configurable:!0});import x from"cross-fetch";var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var d;(function(t){t.Code="code",t.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),m=i(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),S=i(()=>{let t=k();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=i(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=k();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(n=>e+=t[n%t.length]),e},"createRandomString"),c=i(t=>p()?btoa(t):Buffer.from(t).toString("base64"),"encode");var v=i(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),E=i(async t=>{let e=S().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,s)=>{e.oncomplete=n=>{r(n.target.result)},e.onerror=n=>{s(n.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await e},"sha256"),O=i(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var $=i(t=>{let e=new Uint8Array(t);return O(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),U=i((t,e,r=60)=>new Promise((s,n)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a,R=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",a,!1))},"removeIframe"),T=setTimeout(()=>{R()},r*1e3);a=i(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let b=u.source;b&&b.close(),u.data.response.error?n(u.data.response):s(u.data.response),clearTimeout(T),window.removeEventListener("message",a,!1),setTimeout(R,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(o),o.setAttribute("src",t)}),"executeIframe");var w="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",l=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${w}}`,y=i(()=>p()?window.fetch:x,"getFetcher"),g=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=m(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=m(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse(new Error("this feature is only supported in browser"));let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(h()),nonce:c(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=h();let o=await E(this.codeVerifier),a=$(o);s.code_challenge=a}let n=`${this.config.authorizerURL}/authorize?${v(s)}`;if(s.response_mode!=="web_message")return window.location.replace(n),this.okResponse(void 0);try{let o=await U(n,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:o.code});return a.ok?this.okResponse(a.response):this.errorResponse(a.error)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let e=await this.getSession();return e.ok?this.okResponse(e.response):this.errorResponse(e.error)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,response:void 0,error:new Error("browserLogin is only supported for browsers")}}};forgotPassword=async e=>{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r==null?void 0:r.forgot_password)}catch(r){return this.errorResponse(r)}};getMetaData=async()=>{try{let e=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return this.okResponse(e.meta)}catch(e){return this.errorResponse(e)}};getProfile=async e=>{try{let r=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:e});return this.okResponse(r.profile)}catch(r){return this.errorResponse(r)}};getSession=async(e,r)=>{try{let s=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:e,variables:{params:r}});return this.okResponse(s.session)}catch(s){return this.errorResponse(s)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse(new Error("Invalid refresh_token"));if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse(new Error("Invalid code verifier"));let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let n=await y()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),o=await n.json();return n.status>=400?this.errorResponse(new Error(o)):this.okResponse(o)}catch(s){return this.errorResponse(s)}};login=async e=>{try{let r=await this.graphqlQuery({query:` +var L=Object.defineProperty;var i=(n,r)=>L(n,"name",{value:r,configurable:!0});import x from"cross-fetch";var g;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin"})(g||(g={}));var d;(function(n){n.Code="code",n.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),_=i(n=>{let r=n.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),S=i(()=>{let n=k();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",s=k();return s&&Array.from(s.getRandomValues(new Uint8Array(43))).forEach(e=>r+=n[e%n.length]),r},"createRandomString"),c=i(n=>p()?btoa(n):Buffer.from(n).toString("base64"),"encode");var v=i(n=>Object.keys(n).filter(r=>typeof n[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(n[r])}`).join("&"),"createQueryParams"),$=i(async n=>{let r=S().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((s,t)=>{r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{t(e.error)},r.onabort=()=>{t(new Error("The digest operation was aborted"))}}):await r},"sha256"),O=i(n=>{let r={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,s=>r[s])},"urlEncodeB64");var U=i(n=>{let r=new Uint8Array(n);return O(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),E=i((n,r,s=60)=>new Promise((t,e)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a,w=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",a,!1))},"removeIframe"),T=setTimeout(()=>{w()},s*1e3);a=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let b=h.source;b&&b.close(),h.data.response.error?e(h.data.response):t(h.data.response),clearTimeout(T),window.removeEventListener("message",a,!1),setTimeout(w,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(o),o.setAttribute("src",n)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",l=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${R}}`,m=i(()=>p()?window.fetch:x,"getFetcher"),y=class{constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(r.authorizerURL&&(this.config.authorizerURL=_(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=_(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let s=["openid","profile","email"];r.use_refresh_token&&s.push("offline_access");let t={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:s.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let o=await $(this.codeVerifier),a=U(o);t.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${v(t)}`;if(t.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let o=await E(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:o.code});return a.ok?this.okResponse(a.data):this.errorResponse(a.errors)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let r=await this.getSession();return r.ok?this.okResponse(r.data):this.errorResponse(r.errors)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{ok:!1,data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var s;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let t=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:r}});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t==null?void 0:t.data.forgot_password)}catch(t){return this.errorResponse([t])}};getMetaData=async()=>{var r;try{let s=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return(r=s==null?void 0:s.errors)!=null&&r.length?this.errorResponse(s.errors):this.okResponse(s.data.meta)}catch(s){return this.errorResponse([s])}};getProfile=async r=>{var s;try{let t=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:r});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t.data.profile)}catch(t){return this.errorResponse([t])}};getSession=async(r,s)=>{var t,e;try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:r,variables:{params:s}});return(t=o==null?void 0:o.errors)!=null&&t.length?this.errorResponse(o.errors):this.okResponse((e=o.data)==null?void 0:e.session)}catch(o){return this.errorResponse(o)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let s={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await m()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(s),headers:{...this.config.extraHeaders},credentials:"include"}),o=await e.json();return e.status>=400?this.errorResponse([new Error(o)]):this.okResponse(o)}catch(t){return this.errorResponse(t)}};login=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` mutation login($data: LoginInput!) { login(params: $data) { ${l}}} - `,variables:{data:e}});return this.okResponse(r.login)}catch(r){return this.errorResponse(new Error(r))}};logout=async e=>{try{let r=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return this.okResponse(r.response)}catch(r){return console.error(r),this.errorResponse(r)}};magicLinkLogin=async e=>{try{e.state||(e.state=c(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var s,t;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.response)}catch(e){return console.error(e),this.errorResponse([e])}};magicLinkLogin=async r=>{var s,t;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=await this.graphqlQuery({query:` mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(r.magic_link_login)}catch(r){return this.errorResponse(r)}};oauthLogin=async(e,r,s,n)=>{let o=n;if(o||(o=c(h())),!Object.values(f).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");r&&r.length&&(o+=`&roles=${r.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${o}`)};resendOtp=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.magic_link_login)}catch(e){return this.errorResponse([e])}};oauthLogin=async(r,s,t,e)=>{let o=e;if(o||(o=c(u())),!Object.values(g).includes(r))throw new Error(`only following oauth providers are supported: ${Object.values(r).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");s&&s.length&&(o+=`&roles=${s.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${r}?redirect_uri=${t||this.config.redirectURL}&state=${o}`)};resendOtp=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(r.resend_otp)}catch(r){return this.errorResponse(r)}};resetPassword=async e=>{try{let r=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return this.okResponse(r.reset_password)}catch(r){return this.errorResponse(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse(new Error("Invalid refresh_token"));let n=await(await y()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(n)};signup=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.resend_otp)}catch(e){return this.errorResponse([e])}};resetPassword=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.reset_password)}catch(e){return this.errorResponse([e])}};revokeToken=async r=>{if(!r.refresh_token&&!r.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let e=await(await m()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:r.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(e)};signup=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` mutation signup($data: SignUpInput!) { signup(params: $data) { ${l}}} - `,variables:{data:e}});return this.okResponse(r.signup)}catch(r){return this.errorResponse(r)}};updateProfile=async(e,r)=>{try{let s=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}});return this.okResponse(s.update_profile)}catch(s){return this.errorResponse(new Error(s))}};deactivateAccount=async e=>{try{let r=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return this.okResponse(r.deactivate_account)}catch(r){return this.errorResponse(r)}};validateJWTToken=async e=>{try{let r=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return this.okResponse(r.validate_jwt_token)}catch(r){return this.errorResponse(r)}};validateSession=async e=>{try{let r=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${w} } } }`,variables:{params:e}});return this.okResponse(r.validate_session)}catch(r){return this.errorResponse(r)}};verifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.signup)}catch(e){return this.errorResponse([e])}};updateProfile=async(r,s)=>{var t,e;try{let o=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:s,variables:{data:r}});return(t=o==null?void 0:o.errors)!=null&&t.length?this.errorResponse(o.errors):this.okResponse((e=o.data)==null?void 0:e.update_profile)}catch(o){return this.errorResponse([o])}};deactivateAccount=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:r});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.deactivate_account)}catch(e){return this.errorResponse([e])}};validateJWTToken=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.validate_jwt_token)}catch(e){return this.errorResponse([e])}};validateSession=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.validate_session)}catch(e){return this.errorResponse([e])}};verifyEmail=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${l}}} - `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};resendVerifyEmail=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_email)}catch(e){return this.errorResponse([e])}};resendVerifyEmail=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} - `,variables:{data:e}});return this.okResponse(r.verify_email)}catch(r){return this.errorResponse(r)}};verifyOtp=async e=>{try{let r=await this.graphqlQuery({query:` + `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${l}}} - `,variables:{data:e}});return this.okResponse(r.verify_otp)}catch(r){return this.errorResponse(r)}};graphqlQuery=async e=>{let n=await(await y()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(n.errors&&n.errors.length)throw console.error(n.errors),new Error(n.errors[0].message);return n.data};errorResponse=e=>({ok:!1,response:void 0,error:e});okResponse=e=>({ok:!0,response:e,error:void 0})};i(g,"Authorizer");export{g as Authorizer,f as OAuthProviders,d as ResponseTypes}; + `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var o;let e=await(await m()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(o=e==null?void 0:e.errors)!=null&&o.length?(console.error(e.errors),{data:void 0,errors:e.errors}):{data:e.data,errors:[]}};errorResponse=r=>({ok:!1,data:void 0,errors:r});okResponse=r=>({ok:!0,data:r,errors:[]})};i(y,"Authorizer");export{y as Authorizer,g as OAuthProviders,d as ResponseTypes}; diff --git a/src/index.ts b/src/index.ts index 619891a..60fde67 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,6 +19,7 @@ import type { ConfigType, GenericResponse, GetTokenResponse, + GrapQlResponseType, MetaData, ResendVerifyEmailInput, User, ValidateJWTTokenResponse, ValidateSessionResponse, } from './types' @@ -65,7 +66,7 @@ export class Authorizer { authorize = async (data: Types.AuthorizeInput): Promise | ApiResponse> => { if (!hasWindow()) - return this.errorResponse(new Error('this feature is only supported in browser')) + return this.errorResponse([new Error('this feature is only supported in browser')]) const scopes = ['openid', 'profile', 'email'] if (data.use_refresh_token) @@ -107,7 +108,7 @@ export class Authorizer { if (data.response_type === Types.ResponseTypes.Code) { // get token and return it const tokenResp: ApiResponse = await this.getToken({ code: iframeRes.code }) - return tokenResp.ok ? this.okResponse(tokenResp.response) : this.errorResponse(tokenResp.error!) + return tokenResp.ok ? this.okResponse(tokenResp.data) : this.errorResponse(tokenResp.errors) } // this includes access_token, id_token & refresh_token(optionally) @@ -129,14 +130,14 @@ export class Authorizer { browserLogin = async (): Promise> => { try { const tokenResp: ApiResponse = await this.getSession() - return tokenResp.ok ? this.okResponse(tokenResp.response) : this.errorResponse(tokenResp.error!) + return tokenResp.ok ? this.okResponse(tokenResp.data) : this.errorResponse(tokenResp.errors) } catch (err) { if (!hasWindow()) { return { ok: false, - response: undefined, - error: new Error('browserLogin is only supported for browsers'), + data: undefined, + errors: [new Error('browserLogin is only supported for browsers')], } } @@ -166,10 +167,10 @@ export class Authorizer { data, }, }) - return this.okResponse(forgotPasswordResp?.forgot_password) + return forgotPasswordResp?.errors?.length ? this.errorResponse(forgotPasswordResp.errors) : this.okResponse(forgotPasswordResp?.data.forgot_password) } catch (error) { - return this.errorResponse(error) + return this.errorResponse([error]) } } @@ -180,10 +181,10 @@ export class Authorizer { 'query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }', }) - return this.okResponse(res.meta) + return res?.errors?.length ? this.errorResponse(res.errors): this.okResponse(res.data.meta) } catch (error) { - return this.errorResponse(error) + return this.errorResponse([error]) } } @@ -194,10 +195,10 @@ export class Authorizer { headers, }) - return this.okResponse(profileRes.profile) + return profileRes?.errors?.length ? this.errorResponse(profileRes.errors): this.okResponse(profileRes.data.profile) } catch (error) { - return this.errorResponse(error) + return this.errorResponse([error]) } } @@ -214,7 +215,7 @@ export class Authorizer { params, }, }) - return this.okResponse(res.session) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.session) } catch (err) { return this.errorResponse(err) @@ -228,10 +229,10 @@ export class Authorizer { data.grant_type = 'authorization_code' if (data.grant_type === 'refresh_token' && !data.refresh_token) - return this.errorResponse(new Error('Invalid refresh_token')) + return this.errorResponse([new Error('Invalid refresh_token')]) if (data.grant_type === 'authorization_code' && !this.codeVerifier) - return this.errorResponse(new Error('Invalid code verifier')) + return this.errorResponse([new Error('Invalid code verifier')]) const requestData = { client_id: this.config.clientID, @@ -254,7 +255,7 @@ export class Authorizer { const json = await res.json() if (res.status >= 400) - return this.errorResponse(new Error(json)) + return this.errorResponse([new Error(json)]) return this.okResponse(json) } @@ -272,10 +273,10 @@ export class Authorizer { variables: { data }, }) - return this.okResponse(res.login) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.login) } catch (err) { - return this.errorResponse(new Error(err)) + return this.errorResponse([new Error(err)]) } } @@ -285,11 +286,11 @@ export class Authorizer { query: ' mutation { logout { message } } ', headers, }) - return this.okResponse(res.response) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.response) } catch (err) { console.error(err) - return this.errorResponse(err) + return this.errorResponse([err]) } } @@ -310,10 +311,10 @@ export class Authorizer { variables: { data }, }) - return this.okResponse(res.magic_link_login) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.magic_link_login) } catch (err) { - return this.errorResponse(err) + return this.errorResponse([err]) } } @@ -359,10 +360,10 @@ export class Authorizer { variables: { data }, }) - return this.okResponse(res.resend_otp) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.resend_otp) } catch (err) { - return this.errorResponse(err) + return this.errorResponse([err]) } } @@ -377,16 +378,16 @@ export class Authorizer { data, }, }) - return this.okResponse(resetPasswordRes.reset_password) + return resetPasswordRes?.errors?.length ? this.errorResponse(resetPasswordRes.errors) : this.okResponse(resetPasswordRes.data?.reset_password) } catch (error) { - return this.errorResponse(error) + return this.errorResponse([error]) } } revokeToken = async (data: { refresh_token: string }) => { if (!data.refresh_token && !data.refresh_token.trim()) - return this.errorResponse(new Error('Invalid refresh_token')) + return this.errorResponse([new Error('Invalid refresh_token')]) const fetcher = getFetcher() const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, { @@ -413,10 +414,10 @@ export class Authorizer { variables: { data }, }) - return this.okResponse(res.signup) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.signup) } catch (err) { - return this.errorResponse(err) + return this.errorResponse([err]) } } @@ -434,10 +435,10 @@ export class Authorizer { }, }) - return this.okResponse(updateProfileRes.update_profile) + return updateProfileRes?.errors?.length ? this.errorResponse(updateProfileRes.errors) : this.okResponse(updateProfileRes.data?.update_profile) } catch (error) { - return this.errorResponse(new Error(error)) + return this.errorResponse([error]) } } @@ -449,10 +450,10 @@ export class Authorizer { query: 'mutation deactivateAccount { deactivate_account { message } }', headers, }) - return this.okResponse(res.deactivate_account) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.deactivate_account) } catch (error) { - return this.errorResponse(error) + return this.errorResponse([error]) } } @@ -468,10 +469,10 @@ export class Authorizer { }, }) - return this.okResponse(res.validate_jwt_token) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.validate_jwt_token) } catch (error) { - return this.errorResponse(error) + return this.errorResponse([error]) } } @@ -486,10 +487,10 @@ export class Authorizer { }, }) - return this.okResponse(res.validate_session) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.validate_session) } catch (error) { - return this.errorResponse(error) + return this.errorResponse([error]) } } @@ -504,10 +505,10 @@ export class Authorizer { variables: { data }, }) - return this.okResponse(res.verify_email) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.verify_email) } catch (err) { - return this.errorResponse(err) + return this.errorResponse([err]) } } @@ -522,10 +523,10 @@ export class Authorizer { variables: { data }, }) - return this.okResponse(res.verify_email) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.verify_email) } catch (err) { - return this.errorResponse(err) + return this.errorResponse([err]) } } @@ -540,16 +541,16 @@ export class Authorizer { variables: { data }, }) - return this.okResponse(res.verify_otp) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.verify_otp) } catch (err) { - return this.errorResponse(err) + return this.errorResponse([err]) } } // helper to execute graphql queries // takes in any query or mutation string as input - private graphqlQuery = async (data: Types.GraphqlQueryInput) => { + private graphqlQuery = async (data: Types.GraphqlQueryInput):Promise => { const fetcher = getFetcher() const res = await fetcher(`${this.config.authorizerURL}/graphql`, { method: 'POST', @@ -566,27 +567,27 @@ export class Authorizer { const json = await res.json() - if (json.errors && json.errors.length) { + if (json?.errors?.length) { console.error(json.errors) - throw new Error(json.errors[0].message) + return {data:undefined,errors:json.errors} } - return json.data + return {data:json.data,errors:[]} } - private errorResponse = (error: Error): ApiResponse => { + private errorResponse = (errors: Error[]): ApiResponse => { return { ok: false, - response: undefined, - error, + data: undefined, + errors, } } - private okResponse = (response: any): ApiResponse => { + private okResponse = (data: any): ApiResponse => { return { ok: true, - response, - error: undefined, + data, + errors:[], } } } diff --git a/src/types.ts b/src/types.ts index da6bad5..3716575 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,11 @@ +export interface GrapQlResponseType{ + data:any | undefined, + errors:Error[] +} export interface ApiResponse { ok: boolean - error: Error | undefined - response: T | undefined + errors: Error[] + data: T | undefined } export interface ConfigType { authorizerURL: string From 8d05e35e77558c3a98f609cde5da0572286dc2bd Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 27 Nov 2023 13:15:43 +0200 Subject: [PATCH 23/26] fix with linter --- src/index.ts | 14 +++++++------- src/types.ts | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index 60fde67..232566c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -181,7 +181,7 @@ export class Authorizer { 'query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }', }) - return res?.errors?.length ? this.errorResponse(res.errors): this.okResponse(res.data.meta) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data.meta) } catch (error) { return this.errorResponse([error]) @@ -195,7 +195,7 @@ export class Authorizer { headers, }) - return profileRes?.errors?.length ? this.errorResponse(profileRes.errors): this.okResponse(profileRes.data.profile) + return profileRes?.errors?.length ? this.errorResponse(profileRes.errors) : this.okResponse(profileRes.data.profile) } catch (error) { return this.errorResponse([error]) @@ -311,7 +311,7 @@ export class Authorizer { variables: { data }, }) - return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.magic_link_login) + return res?.errors?.length ? this.errorResponse(res.errors) : this.okResponse(res.data?.magic_link_login) } catch (err) { return this.errorResponse([err]) @@ -550,7 +550,7 @@ export class Authorizer { // helper to execute graphql queries // takes in any query or mutation string as input - private graphqlQuery = async (data: Types.GraphqlQueryInput):Promise => { + private graphqlQuery = async (data: Types.GraphqlQueryInput): Promise => { const fetcher = getFetcher() const res = await fetcher(`${this.config.authorizerURL}/graphql`, { method: 'POST', @@ -569,10 +569,10 @@ export class Authorizer { if (json?.errors?.length) { console.error(json.errors) - return {data:undefined,errors:json.errors} + return { data: undefined, errors: json.errors } } - return {data:json.data,errors:[]} + return { data: json.data, errors: [] } } private errorResponse = (errors: Error[]): ApiResponse => { @@ -587,7 +587,7 @@ export class Authorizer { return { ok: true, data, - errors:[], + errors: [], } } } diff --git a/src/types.ts b/src/types.ts index 3716575..ad69cd2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,6 +1,6 @@ -export interface GrapQlResponseType{ - data:any | undefined, - errors:Error[] +export interface GrapQlResponseType { + data: any | undefined + errors: Error[] } export interface ApiResponse { ok: boolean From 53dc974aa0f73ac31c16bfd84eb1cc008359c1ae Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 27 Nov 2023 13:20:26 +0200 Subject: [PATCH 24/26] remove ok property --- lib/index.d.ts | 257 +++++-------------------------------------------- src/index.ts | 7 +- src/types.ts | 1 - 3 files changed, 24 insertions(+), 241 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index b169a06..7126e55 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -1,248 +1,35 @@ -interface GrapQlResponseType { - data: any | undefined; - errors: Error[]; -} -interface ApiResponse { - ok: boolean; - errors: Error[]; - data: T | undefined; -} -interface ConfigType { - authorizerURL: string; - redirectURL: string; - clientID: string; - extraHeaders?: Record; -} -interface User { - id: string; - email: string; - preferred_username: string; - email_verified: boolean; - signup_methods: string; - given_name?: string | null; - family_name?: string | null; - middle_name?: string | null; - nickname?: string | null; - picture?: string | null; - gender?: string | null; - birthdate?: string | null; - phone_number?: string | null; - phone_number_verified?: boolean | null; - roles?: string[]; - created_at: number; - updated_at: number; - is_multi_factor_auth_enabled?: boolean; - app_data?: Record; -} -interface AuthToken { - message?: string; - access_token: string; - expires_in: number; - id_token: string; - refresh_token?: string; - user?: User; - should_show_email_otp_screen?: boolean; - should_show_mobile_otp_screen?: boolean; -} -interface GenericResponse { - message: string; -} -type Headers = Record; -interface LoginInput { - email?: string; - phone_number?: string; - password: string; - roles?: string[]; - scope?: string[]; - state?: string; -} -interface SignupInput { - email?: string; - password: string; - confirm_password: string; - given_name?: string; - family_name?: string; - middle_name?: string; - nickname?: string; - picture?: string; - gender?: string; - birthdate?: string; - phone_number?: string; - roles?: string[]; - scope?: string[]; - redirect_uri?: string; - is_multi_factor_auth_enabled?: boolean; - state?: string; - app_data?: Record; -} -interface MagicLinkLoginInput { - email: string; - roles?: string[]; - scopes?: string[]; - state?: string; - redirect_uri?: string; -} -interface VerifyEmailInput { - token: string; - state?: string; -} -interface ResendVerifyEmailInput { - email: string; - identifier: string; -} -interface VerifyOtpInput { - email?: string; - phone_number?: string; - otp: string; - state?: string; -} -interface ResendOtpInput { - email?: string; - phone_number?: string; -} -interface GraphqlQueryInput { - query: string; - variables?: Record; - headers?: Headers; -} -interface MetaData { - version: string; - client_id: string; - is_google_login_enabled: boolean; - is_facebook_login_enabled: boolean; - is_github_login_enabled: boolean; - is_linkedin_login_enabled: boolean; - is_apple_login_enabled: boolean; - is_twitter_login_enabled: boolean; - is_microsoft_login_enabled: boolean; - is_email_verification_enabled: boolean; - is_basic_authentication_enabled: boolean; - is_magic_link_login_enabled: boolean; - is_sign_up_enabled: boolean; - is_strong_password_enabled: boolean; -} -interface UpdateProfileInput { - old_password?: string; - new_password?: string; - confirm_new_password?: string; - email?: string; - given_name?: string; - family_name?: string; - middle_name?: string; - nickname?: string; - gender?: string; - birthdate?: string; - phone_number?: string; - picture?: string; - is_multi_factor_auth_enabled?: boolean; - app_data?: Record; -} -interface ForgotPasswordInput { - email: string; - state?: string; - redirect_uri?: string; -} -interface ResetPasswordInput { - token: string; - password: string; - confirm_password: string; -} -interface SessionQueryInput { - roles?: string[]; -} -interface IsValidJWTQueryInput { - jwt: string; - roles?: string[]; -} -interface ValidJWTResponse { - valid: string; - message: string; -} -declare enum OAuthProviders { - Apple = "apple", - Github = "github", - Google = "google", - Facebook = "facebook", - LinkedIn = "linkedin" -} -declare enum ResponseTypes { - Code = "code", - Token = "token" -} -interface AuthorizeInput { - response_type: ResponseTypes; - use_refresh_token?: boolean; - response_mode?: string; -} -interface AuthorizeResponse { - state: string; - code?: string; - error?: string; - error_description?: string; -} -interface RevokeTokenInput { - refresh_token: string; -} -interface GetTokenInput { - code?: string; - grant_type?: string; - refresh_token?: string; -} -interface GetTokenResponse { - access_token: string; - expires_in: number; - id_token: string; - refresh_token?: string; -} -interface ValidateJWTTokenInput { - token_type: 'access_token' | 'id_token' | 'refresh_token'; - token: string; - roles?: string[]; -} -interface ValidateJWTTokenResponse { - is_valid: boolean; - claims: Record; -} -interface ValidateSessionInput { - cookie?: string; - roles?: string[]; -} -interface ValidateSessionResponse { - is_valid: boolean; - user: User; -} - -declare class Authorizer { +import * as Types from './types'; +import type { ApiResponse, AuthToken, AuthorizeResponse, ConfigType, GenericResponse, GetTokenResponse, MetaData, ResendVerifyEmailInput, User, ValidateJWTTokenResponse, ValidateSessionResponse } from './types'; +export * from './types'; +export declare class Authorizer { config: ConfigType; codeVerifier: string; constructor(config: ConfigType); - authorize: (data: AuthorizeInput) => Promise | ApiResponse>; + authorize: (data: Types.AuthorizeInput) => Promise | ApiResponse>; browserLogin: () => Promise>; - forgotPassword: (data: ForgotPasswordInput) => Promise>; + forgotPassword: (data: Types.ForgotPasswordInput) => Promise>; getMetaData: () => Promise>; - getProfile: (headers?: Headers) => Promise>; - getSession: (headers?: Headers, params?: SessionQueryInput) => Promise>; - getToken: (data: GetTokenInput) => Promise>; - login: (data: LoginInput) => Promise>; - logout: (headers?: Headers) => Promise>; - magicLinkLogin: (data: MagicLinkLoginInput) => Promise>; + getProfile: (headers?: Types.Headers) => Promise>; + getSession: (headers?: Types.Headers, params?: Types.SessionQueryInput) => Promise>; + getToken: (data: Types.GetTokenInput) => Promise>; + login: (data: Types.LoginInput) => Promise>; + logout: (headers?: Types.Headers) => Promise>; + magicLinkLogin: (data: Types.MagicLinkLoginInput) => Promise>; oauthLogin: (oauthProvider: string, roles?: string[], redirect_uri?: string, state?: string) => Promise; - resendOtp: (data: ResendOtpInput) => Promise>; - resetPassword: (data: ResetPasswordInput) => Promise>; + resendOtp: (data: Types.ResendOtpInput) => Promise>; + resetPassword: (data: Types.ResetPasswordInput) => Promise>; revokeToken: (data: { refresh_token: string; - }) => Promise>; - signup: (data: SignupInput) => Promise>; - updateProfile: (data: UpdateProfileInput, headers?: Headers) => Promise>; - deactivateAccount: (headers?: Headers) => Promise>; - validateJWTToken: (params?: ValidateJWTTokenInput) => Promise>; - validateSession: (params?: ValidateSessionInput) => Promise>; - verifyEmail: (data: VerifyEmailInput) => Promise>; + }) => Promise>; + signup: (data: Types.SignupInput) => Promise>; + updateProfile: (data: Types.UpdateProfileInput, headers?: Types.Headers) => Promise>; + deactivateAccount: (headers?: Types.Headers) => Promise>; + validateJWTToken: (params?: Types.ValidateJWTTokenInput) => Promise>; + validateSession: (params?: Types.ValidateSessionInput) => Promise>; + verifyEmail: (data: Types.VerifyEmailInput) => Promise>; resendVerifyEmail: (data: ResendVerifyEmailInput) => Promise>; - verifyOtp: (data: VerifyOtpInput) => Promise>; + verifyOtp: (data: Types.VerifyOtpInput) => Promise>; private graphqlQuery; private errorResponse; private okResponse; } - -export { ApiResponse, AuthToken, AuthorizeInput, AuthorizeResponse, Authorizer, ConfigType, ForgotPasswordInput, GenericResponse, GetTokenInput, GetTokenResponse, GrapQlResponseType, GraphqlQueryInput, Headers, IsValidJWTQueryInput, LoginInput, MagicLinkLoginInput, MetaData, OAuthProviders, ResendOtpInput, ResendVerifyEmailInput, ResetPasswordInput, ResponseTypes, RevokeTokenInput, SessionQueryInput, SignupInput, UpdateProfileInput, User, ValidJWTResponse, ValidateJWTTokenInput, ValidateJWTTokenResponse, ValidateSessionInput, ValidateSessionResponse, VerifyEmailInput, VerifyOtpInput }; diff --git a/src/index.ts b/src/index.ts index 232566c..6e856bb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -108,7 +108,7 @@ export class Authorizer { if (data.response_type === Types.ResponseTypes.Code) { // get token and return it const tokenResp: ApiResponse = await this.getToken({ code: iframeRes.code }) - return tokenResp.ok ? this.okResponse(tokenResp.data) : this.errorResponse(tokenResp.errors) + return tokenResp.errors.length ? this.errorResponse(tokenResp.errors) : this.okResponse(tokenResp.data) } // this includes access_token, id_token & refresh_token(optionally) @@ -130,12 +130,11 @@ export class Authorizer { browserLogin = async (): Promise> => { try { const tokenResp: ApiResponse = await this.getSession() - return tokenResp.ok ? this.okResponse(tokenResp.data) : this.errorResponse(tokenResp.errors) + return tokenResp.errors.length ? this.errorResponse(tokenResp.errors) : this.okResponse(tokenResp.data) } catch (err) { if (!hasWindow()) { return { - ok: false, data: undefined, errors: [new Error('browserLogin is only supported for browsers')], } @@ -577,7 +576,6 @@ export class Authorizer { private errorResponse = (errors: Error[]): ApiResponse => { return { - ok: false, data: undefined, errors, } @@ -585,7 +583,6 @@ export class Authorizer { private okResponse = (data: any): ApiResponse => { return { - ok: true, data, errors: [], } diff --git a/src/types.ts b/src/types.ts index ad69cd2..0d89189 100644 --- a/src/types.ts +++ b/src/types.ts @@ -3,7 +3,6 @@ export interface GrapQlResponseType { errors: Error[] } export interface ApiResponse { - ok: boolean errors: Error[] data: T | undefined } From c65fca4b087cca0e084b05c98c5de6be97c080e9 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 27 Nov 2023 17:44:33 +0200 Subject: [PATCH 25/26] remove lib folders from PR --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 5978ff3..d97a3cc 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ node_modules dist lib +lib/* package-lock.json .idea .history From c45a548f60e28d5482a03697b09085223b02a328 Mon Sep 17 00:00:00 2001 From: ShiftLabs Date: Mon, 27 Nov 2023 18:12:18 +0200 Subject: [PATCH 26/26] remove lib folder --- lib/authorizer.min.js | 16 ---------------- lib/index.d.ts | 35 ----------------------------------- lib/index.js | 15 --------------- lib/index.mjs | 15 --------------- 4 files changed, 81 deletions(-) delete mode 100644 lib/authorizer.min.js delete mode 100644 lib/index.d.ts delete mode 100644 lib/index.js delete mode 100644 lib/index.mjs diff --git a/lib/authorizer.min.js b/lib/authorizer.min.js deleted file mode 100644 index b6ab640..0000000 --- a/lib/authorizer.min.js +++ /dev/null @@ -1,16 +0,0 @@ -var authorizerdev=(()=>{var fe=Object.create;var U=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,we=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var F=(n,e,o)=>e in n?U(n,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[e]=o,A=(n,e)=>{for(var o in e||(e={}))G.call(e,o)&&F(n,o,e[o]);if(J)for(var o of J(e))be.call(e,o)&&F(n,o,e[o]);return n},W=(n,e)=>ye(n,_e(e)),a=(n,e)=>U(n,"name",{value:e,configurable:!0});var Re=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ve=(n,e)=>{for(var o in e)U(n,o,{get:e[o],enumerable:!0})},Z=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ge(e))!G.call(n,r)&&r!==o&&U(n,r,{get:()=>e[r],enumerable:!(s=me(e,r))||s.enumerable});return n};var Ee=(n,e,o)=>(o=n!=null?fe(we(n)):{},Z(e||!n||!n.__esModule?U(o,"default",{value:n,enumerable:!0}):o,n)),Te=n=>Z(U({},"__esModule",{value:!0}),n);var d=(n,e,o)=>(F(n,typeof e!="symbol"?e+"":e,o),o);var l=(n,e,o)=>new Promise((s,r)=>{var c=w=>{try{g(o.next(w))}catch(m){r(m)}},_=w=>{try{g(o.throw(w))}catch(m){r(m)}},g=w=>w.done?s(w.value):Promise.resolve(w.value).then(c,_);g((o=o.apply(n,e)).next())});var Y=Re((R,K)=>{var X=typeof self!="undefined"?self:R,$=function(){function n(){this.fetch=!1,this.DOMException=X.DOMException}return a(n,"F"),n.prototype=X,new n}();(function(n){var e=function(o){var s={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function r(t){return t&&DataView.prototype.isPrototypeOf(t)}if(a(r,"isDataView"),s.arrayBuffer)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],_=ArrayBuffer.isView||function(t){return t&&c.indexOf(Object.prototype.toString.call(t))>-1};function g(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}a(g,"normalizeName");function w(t){return typeof t!="string"&&(t=String(t)),t}a(w,"normalizeValue");function m(t){var i={next:function(){var h=t.shift();return{done:h===void 0,value:h}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}a(m,"iteratorFor");function p(t){this.map={},t instanceof p?t.forEach(function(i,h){this.append(h,i)},this):Array.isArray(t)?t.forEach(function(i){this.append(i[0],i[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(i){this.append(i,t[i])},this)}a(p,"Headers"),p.prototype.append=function(t,i){t=g(t),i=w(i);var h=this.map[t];this.map[t]=h?h+", "+i:i},p.prototype.delete=function(t){delete this.map[g(t)]},p.prototype.get=function(t){return t=g(t),this.has(t)?this.map[t]:null},p.prototype.has=function(t){return this.map.hasOwnProperty(g(t))},p.prototype.set=function(t,i){this.map[g(t)]=w(i)},p.prototype.forEach=function(t,i){for(var h in this.map)this.map.hasOwnProperty(h)&&t.call(i,this.map[h],h,this)},p.prototype.keys=function(){var t=[];return this.forEach(function(i,h){t.push(h)}),m(t)},p.prototype.values=function(){var t=[];return this.forEach(function(i){t.push(i)}),m(t)},p.prototype.entries=function(){var t=[];return this.forEach(function(i,h){t.push([h,i])}),m(t)},s.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function D(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}a(D,"consumed");function N(t){return new Promise(function(i,h){t.onload=function(){i(t.result)},t.onerror=function(){h(t.error)}})}a(N,"fileReaderReady");function ie(t){var i=new FileReader,h=N(i);return i.readAsArrayBuffer(t),h}a(ie,"readBlobAsArrayBuffer");function ae(t){var i=new FileReader,h=N(i);return i.readAsText(t),h}a(ae,"readBlobAsText");function ce(t){for(var i=new Uint8Array(t),h=new Array(i.length),y=0;y-1?i:t}a(ue,"normalizeMethod");function E(t,i){i=i||{};var h=i.body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,i.headers||(this.headers=new p(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!h&&t._bodyInit!=null&&(h=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new p(i.headers)),this.method=ue(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&h)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(h)}a(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function de(t){var i=new FormData;return t.trim().split("&").forEach(function(h){if(h){var y=h.split("="),f=y.shift().replace(/\+/g," "),u=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(f),decodeURIComponent(u))}}),i}a(de,"decode");function le(t){var i=new p,h=t.replace(/\r?\n[\t ]+/g," ");return h.split(/\r?\n/).forEach(function(y){var f=y.split(":"),u=f.shift().trim();if(u){var x=f.join(":").trim();i.append(u,x)}}),i}a(le,"parseHeaders"),V.call(E.prototype);function b(t,i){i||(i={}),this.type="default",this.status=i.status===void 0?200:i.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in i?i.statusText:"OK",this.headers=new p(i.headers),this.url=i.url||"",this._initBody(t)}a(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var t=new b(null,{status:0,statusText:""});return t.type="error",t};var pe=[301,302,303,307,308];b.redirect=function(t,i){if(pe.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:t}})},o.DOMException=n.DOMException;try{new o.DOMException}catch(t){o.DOMException=function(i,h){this.message=i,this.name=h;var y=Error(i);this.stack=y.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function P(t,i){return new Promise(function(h,y){var f=new E(t,i);if(f.signal&&f.signal.aborted)return y(new o.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function x(){u.abort()}a(x,"abortXhr"),u.onload=function(){var L={status:u.status,statusText:u.statusText,headers:le(u.getAllResponseHeaders()||"")};L.url="responseURL"in u?u.responseURL:L.headers.get("X-Request-URL");var C="response"in u?u.response:u.responseText;h(new b(C,L))},u.onerror=function(){y(new TypeError("Network request failed"))},u.ontimeout=function(){y(new TypeError("Network request failed"))},u.onabort=function(){y(new o.DOMException("Aborted","AbortError"))},u.open(f.method,f.url,!0),f.credentials==="include"?u.withCredentials=!0:f.credentials==="omit"&&(u.withCredentials=!1),"responseType"in u&&s.blob&&(u.responseType="blob"),f.headers.forEach(function(L,C){u.setRequestHeader(C,L)}),f.signal&&(f.signal.addEventListener("abort",x),u.onreadystatechange=function(){u.readyState===4&&f.signal.removeEventListener("abort",x)}),u.send(typeof f._bodyInit=="undefined"?null:f._bodyInit)})}return a(P,"fetch"),P.polyfill=!0,n.fetch||(n.fetch=P,n.Headers=p,n.Request=E,n.Response=b),o.Headers=p,o.Request=E,o.Response=b,o.fetch=P,Object.defineProperty(o,"__esModule",{value:!0}),o}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var I=$;R=I.fetch;R.default=I.fetch;R.fetch=I.fetch;R.Headers=I.Headers;R.Request=I.Request;R.Response=I.Response;K.exports=R});var Oe={};ve(Oe,{Authorizer:()=>B,OAuthProviders:()=>q,ResponseTypes:()=>O});var ne=Ee(Y());var q;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin"})(q||(q={}));var O;(function(n){n.Code="code",n.Token="token"})(O||(O={}));var T=a(()=>typeof window!="undefined","hasWindow"),M=a(n=>{let e=n.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=a(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=a(()=>{let n=ee();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),k=a(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",o=ee();return o&&Array.from(o.getRandomValues(new Uint8Array(43))).forEach(r=>e+=n[r%n.length]),e},"createRandomString"),v=a(n=>T()?btoa(n):Buffer.from(n).toString("base64"),"encode");var re=a(n=>Object.keys(n).filter(e=>typeof n[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`).join("&"),"createQueryParams"),te=a(n=>l(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((o,s)=>{e.oncomplete=r=>{o(r.target.result)},e.onerror=r=>{s(r.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Ie=a(n=>{let e={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,o=>e[o])},"urlEncodeB64");var oe=a(n=>{let e=new Uint8Array(n);return Ie(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),se=a((n,e,o=60)=>new Promise((s,r)=>{let c=window.document.createElement("iframe");c.setAttribute("id","authorizer-iframe"),c.setAttribute("width","0"),c.setAttribute("height","0"),c.style.display="none";let _,g=a(()=>{window.document.body.contains(c)&&(window.document.body.removeChild(c),window.removeEventListener("message",_,!1))},"removeIframe"),w=setTimeout(()=>{g()},o*1e3);_=a(function(m){if(m.origin!==e||!m.data||!m.data.response)return;let p=m.source;p&&p.close(),m.data.response.error?r(m.data.response):s(m.data.response),clearTimeout(w),window.removeEventListener("message",_,!1),setTimeout(g,2*1e3)},"iframeEventHandler"),window.addEventListener("message",_,!1),window.document.body.appendChild(c),c.setAttribute("src",n)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",S=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${H}}`,z=a(()=>T()?window.fetch:ne.default,"getFetcher"),B=class{constructor(e){d(this,"authorize",a(e=>l(this,null,function*(){if(!T())return this.errorResponse([new Error("this feature is only supported in browser")]);let o=["openid","profile","email"];e.use_refresh_token&&o.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(k()),nonce:v(k()),response_type:e.response_type,scope:o.join(" "),client_id:this.config.clientID};if(e.response_type===O.Code){this.codeVerifier=k();let c=yield te(this.codeVerifier),_=oe(c);s.code_challenge=_}let r=`${this.config.authorizerURL}/authorize?${re(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let c=yield se(r,this.config.authorizerURL,60);if(e.response_type===O.Code){let _=yield this.getToken({code:c.code});return _.ok?this.okResponse(_.data):this.errorResponse(_.errors)}return this.okResponse(c)}catch(c){return c.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(c)}}),"authorize"));d(this,"browserLogin",a(()=>l(this,null,function*(){try{let e=yield this.getSession();return e.ok?this.okResponse(e.data):this.errorResponse(e.errors)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{ok:!1,data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}}),"browserLogin"));d(this,"forgotPassword",a(e=>l(this,null,function*(){var o;e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let s=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}}),"forgotPassword"));d(this,"getMetaData",a(()=>l(this,null,function*(){var e;try{let o=yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return(e=o==null?void 0:o.errors)!=null&&e.length?this.errorResponse(o.errors):this.okResponse(o.data.meta)}catch(o){return this.errorResponse([o])}}),"getMetaData"));d(this,"getProfile",a(e=>l(this,null,function*(){var o;try{let s=yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}}),"getProfile"));d(this,"getSession",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${S} } }`,headers:e,variables:{params:o}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.session)}catch(c){return this.errorResponse(c)}}),"getSession"));d(this,"getToken",a(e=>l(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let o={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let r=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(o),headers:A({},this.config.extraHeaders),credentials:"include"}),c=yield r.json();return r.status>=400?this.errorResponse([new Error(c)]):this.okResponse(c)}catch(s){return this.errorResponse(s)}}),"getToken"));d(this,"login",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` - mutation login($data: LoginInput!) { login(params: $data) { ${S}}} - `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.login)}catch(r){return this.errorResponse([new Error(r)])}}),"login"));d(this,"logout",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.response)}catch(r){return console.error(r),this.errorResponse([r])}}),"logout"));d(this,"magicLinkLogin",a(e=>l(this,null,function*(){var o,s;try{e.state||(e.state=v(k())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=yield this.graphqlQuery({query:` - mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} - `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.magic_link_login)}catch(r){return this.errorResponse([r])}}),"magicLinkLogin"));d(this,"oauthLogin",a((e,o,s,r)=>l(this,null,function*(){let c=r;if(c||(c=v(k())),!Object.values(q).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!T())throw new Error("oauthLogin is only supported for browsers");o&&o.length&&(c+=`&roles=${o.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${c}`)}),"oauthLogin"));d(this,"resendOtp",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` - mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} - `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_otp)}catch(r){return this.errorResponse([r])}}),"resendOtp"));d(this,"resetPassword",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.reset_password)}catch(r){return this.errorResponse([r])}}),"resetPassword"));d(this,"revokeToken",a(e=>l(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let r=yield(yield z()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:A({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(r)}),"revokeToken"));d(this,"signup",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` - mutation signup($data: SignUpInput!) { signup(params: $data) { ${S}}} - `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.signup)}catch(r){return this.errorResponse([r])}}),"signup"));d(this,"updateProfile",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:o,variables:{data:e}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.update_profile)}catch(c){return this.errorResponse([c])}}),"updateProfile"));d(this,"deactivateAccount",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.deactivate_account)}catch(r){return this.errorResponse([r])}}),"deactivateAccount"));d(this,"validateJWTToken",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_jwt_token)}catch(r){return this.errorResponse([r])}}),"validateJWTToken"));d(this,"validateSession",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${H} } } }`,variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_session)}catch(r){return this.errorResponse([r])}}),"validateSession"));d(this,"verifyEmail",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` - mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${S}}} - `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"verifyEmail"));d(this,"resendVerifyEmail",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` - mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} - `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"resendVerifyEmail"));d(this,"verifyOtp",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:` - mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${S}}} - `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}}),"verifyOtp"));d(this,"graphqlQuery",a(e=>l(this,null,function*(){var c;let r=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:A(A({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();return(c=r==null?void 0:r.errors)!=null&&c.length?(console.error(r.errors),{data:void 0,errors:r.errors}):{data:r.data,errors:[]}}),"graphqlQuery"));d(this,"errorResponse",a(e=>({ok:!1,data:void 0,errors:e}),"errorResponse"));d(this,"okResponse",a(e=>({ok:!0,data:e,errors:[]}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=M(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=M(e.redirectURL),this.config.extraHeaders=W(A({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};a(B,"Authorizer");return Te(Oe);})(); -window.__TAURI__ = authorizerdev diff --git a/lib/index.d.ts b/lib/index.d.ts deleted file mode 100644 index 7126e55..0000000 --- a/lib/index.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -import * as Types from './types'; -import type { ApiResponse, AuthToken, AuthorizeResponse, ConfigType, GenericResponse, GetTokenResponse, MetaData, ResendVerifyEmailInput, User, ValidateJWTTokenResponse, ValidateSessionResponse } from './types'; -export * from './types'; -export declare class Authorizer { - config: ConfigType; - codeVerifier: string; - constructor(config: ConfigType); - authorize: (data: Types.AuthorizeInput) => Promise | ApiResponse>; - browserLogin: () => Promise>; - forgotPassword: (data: Types.ForgotPasswordInput) => Promise>; - getMetaData: () => Promise>; - getProfile: (headers?: Types.Headers) => Promise>; - getSession: (headers?: Types.Headers, params?: Types.SessionQueryInput) => Promise>; - getToken: (data: Types.GetTokenInput) => Promise>; - login: (data: Types.LoginInput) => Promise>; - logout: (headers?: Types.Headers) => Promise>; - magicLinkLogin: (data: Types.MagicLinkLoginInput) => Promise>; - oauthLogin: (oauthProvider: string, roles?: string[], redirect_uri?: string, state?: string) => Promise; - resendOtp: (data: Types.ResendOtpInput) => Promise>; - resetPassword: (data: Types.ResetPasswordInput) => Promise>; - revokeToken: (data: { - refresh_token: string; - }) => Promise>; - signup: (data: Types.SignupInput) => Promise>; - updateProfile: (data: Types.UpdateProfileInput, headers?: Types.Headers) => Promise>; - deactivateAccount: (headers?: Types.Headers) => Promise>; - validateJWTToken: (params?: Types.ValidateJWTTokenInput) => Promise>; - validateSession: (params?: Types.ValidateSessionInput) => Promise>; - verifyEmail: (data: Types.VerifyEmailInput) => Promise>; - resendVerifyEmail: (data: ResendVerifyEmailInput) => Promise>; - verifyOtp: (data: Types.VerifyOtpInput) => Promise>; - private graphqlQuery; - private errorResponse; - private okResponse; -} diff --git a/lib/index.js b/lib/index.js deleted file mode 100644 index f1e6d5b..0000000 --- a/lib/index.js +++ /dev/null @@ -1,15 +0,0 @@ -var S=Object.create;var l=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var i=(o,r)=>l(o,"name",{value:r,configurable:!0});var Q=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},v=(o,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of x(r))!A.call(o,e)&&e!==t&&l(o,e,{get:()=>r[e],enumerable:!(s=O(r,e))||s.enumerable});return o};var z=(o,r,t)=>(t=o!=null?S(C(o)):{},v(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),D=o=>v(l({},"__esModule",{value:!0}),o);var P={};Q(P,{Authorizer:()=>_,OAuthProviders:()=>g,ResponseTypes:()=>d});module.exports=D(P);var q=z(require("cross-fetch"));var g;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin"})(g||(g={}));var d;(function(o){o.Code="code",o.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),y=i(o=>{let r=o.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),$=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),j=i(()=>{let o=$();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",t=$();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(e=>r+=o[e%o.length]),r},"createRandomString"),c=i(o=>p()?btoa(o):Buffer.from(o).toString("base64"),"encode");var U=i(o=>Object.keys(o).filter(r=>typeof o[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(o[r])}`).join("&"),"createQueryParams"),E=i(async o=>{let r=j().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{r.oncomplete=e=>{t(e.target.result)},r.onerror=e=>{s(e.error)},r.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await r},"sha256"),F=i(o=>{let r={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>r[t])},"urlEncodeB64");var T=i(o=>{let r=new Uint8Array(o);return F(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),L=i((o,r,t=60)=>new Promise((s,e)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a,b=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",a,!1))},"removeIframe"),I=setTimeout(()=>{b()},t*1e3);a=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let k=h.source;k&&k.close(),h.data.response.error?e(h.data.response):s(h.data.response),clearTimeout(I),window.removeEventListener("message",a,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(n),n.setAttribute("src",o)}),"executeIframe");var w="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",f=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${w}}`,R=i(()=>p()?window.fetch:q.default,"getFetcher"),_=class{constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(r.authorizerURL&&(this.config.authorizerURL=y(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let t=["openid","profile","email"];r.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:t.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let n=await E(this.codeVerifier),a=T(n);s.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${U(s)}`;if(s.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let n=await L(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:n.code});return a.ok?this.okResponse(a.data):this.errorResponse(a.errors)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let r=await this.getSession();return r.ok?this.okResponse(r.data):this.errorResponse(r.errors)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{ok:!1,data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var t;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let s=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:r}});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}};getMetaData=async()=>{var r;try{let t=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return(r=t==null?void 0:t.errors)!=null&&r.length?this.errorResponse(t.errors):this.okResponse(t.data.meta)}catch(t){return this.errorResponse([t])}};getProfile=async r=>{var t;try{let s=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:r});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}};getSession=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${f} } }`,headers:r,variables:{params:t}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.session)}catch(n){return this.errorResponse(n)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let t={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await R()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:{...this.config.extraHeaders},credentials:"include"}),n=await e.json();return e.status>=400?this.errorResponse([new Error(n)]):this.okResponse(n)}catch(s){return this.errorResponse(s)}};login=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` - mutation login($data: LoginInput!) { login(params: $data) { ${f}}} - `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var t,s;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.response)}catch(e){return console.error(e),this.errorResponse([e])}};magicLinkLogin=async r=>{var t,s;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=await this.graphqlQuery({query:` - mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} - `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.magic_link_login)}catch(e){return this.errorResponse([e])}};oauthLogin=async(r,t,s,e)=>{let n=e;if(n||(n=c(u())),!Object.values(g).includes(r))throw new Error(`only following oauth providers are supported: ${Object.values(r).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(n+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${r}?redirect_uri=${s||this.config.redirectURL}&state=${n}`)};resendOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` - mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} - `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.resend_otp)}catch(e){return this.errorResponse([e])}};resetPassword=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.reset_password)}catch(e){return this.errorResponse([e])}};revokeToken=async r=>{if(!r.refresh_token&&!r.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let e=await(await R()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:r.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(e)};signup=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` - mutation signup($data: SignUpInput!) { signup(params: $data) { ${f}}} - `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.signup)}catch(e){return this.errorResponse([e])}};updateProfile=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:r}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.update_profile)}catch(n){return this.errorResponse([n])}};deactivateAccount=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.deactivate_account)}catch(e){return this.errorResponse([e])}};validateJWTToken=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_jwt_token)}catch(e){return this.errorResponse([e])}};validateSession=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${w} } } }`,variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_session)}catch(e){return this.errorResponse([e])}};verifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` - mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${f}}} - `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};resendVerifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` - mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} - `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:` - mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${f}}} - `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var n;let e=await(await R()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(n=e==null?void 0:e.errors)!=null&&n.length?(console.error(e.errors),{data:void 0,errors:e.errors}):{data:e.data,errors:[]}};errorResponse=r=>({ok:!1,data:void 0,errors:r});okResponse=r=>({ok:!0,data:r,errors:[]})};i(_,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes}); diff --git a/lib/index.mjs b/lib/index.mjs deleted file mode 100644 index 4857278..0000000 --- a/lib/index.mjs +++ /dev/null @@ -1,15 +0,0 @@ -var L=Object.defineProperty;var i=(n,r)=>L(n,"name",{value:r,configurable:!0});import x from"cross-fetch";var g;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin"})(g||(g={}));var d;(function(n){n.Code="code",n.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),_=i(n=>{let r=n.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),S=i(()=>{let n=k();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",s=k();return s&&Array.from(s.getRandomValues(new Uint8Array(43))).forEach(e=>r+=n[e%n.length]),r},"createRandomString"),c=i(n=>p()?btoa(n):Buffer.from(n).toString("base64"),"encode");var v=i(n=>Object.keys(n).filter(r=>typeof n[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(n[r])}`).join("&"),"createQueryParams"),$=i(async n=>{let r=S().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((s,t)=>{r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{t(e.error)},r.onabort=()=>{t(new Error("The digest operation was aborted"))}}):await r},"sha256"),O=i(n=>{let r={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,s=>r[s])},"urlEncodeB64");var U=i(n=>{let r=new Uint8Array(n);return O(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),E=i((n,r,s=60)=>new Promise((t,e)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a,w=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",a,!1))},"removeIframe"),T=setTimeout(()=>{w()},s*1e3);a=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let b=h.source;b&&b.close(),h.data.response.error?e(h.data.response):t(h.data.response),clearTimeout(T),window.removeEventListener("message",a,!1),setTimeout(w,2*1e3)},"iframeEventHandler"),window.addEventListener("message",a,!1),window.document.body.appendChild(o),o.setAttribute("src",n)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",l=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen user {${R}}`,m=i(()=>p()?window.fetch:x,"getFetcher"),y=class{constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(r.authorizerURL&&(this.config.authorizerURL=_(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=_(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let s=["openid","profile","email"];r.use_refresh_token&&s.push("offline_access");let t={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:s.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let o=await $(this.codeVerifier),a=U(o);t.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${v(t)}`;if(t.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let o=await E(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:o.code});return a.ok?this.okResponse(a.data):this.errorResponse(a.errors)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let r=await this.getSession();return r.ok?this.okResponse(r.data):this.errorResponse(r.errors)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{ok:!1,data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var s;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let t=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:r}});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t==null?void 0:t.data.forgot_password)}catch(t){return this.errorResponse([t])}};getMetaData=async()=>{var r;try{let s=await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"});return(r=s==null?void 0:s.errors)!=null&&r.length?this.errorResponse(s.errors):this.okResponse(s.data.meta)}catch(s){return this.errorResponse([s])}};getProfile=async r=>{var s;try{let t=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:r});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t.data.profile)}catch(t){return this.errorResponse([t])}};getSession=async(r,s)=>{var t,e;try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:r,variables:{params:s}});return(t=o==null?void 0:o.errors)!=null&&t.length?this.errorResponse(o.errors):this.okResponse((e=o.data)==null?void 0:e.session)}catch(o){return this.errorResponse(o)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let s={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await m()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(s),headers:{...this.config.extraHeaders},credentials:"include"}),o=await e.json();return e.status>=400?this.errorResponse([new Error(o)]):this.okResponse(o)}catch(t){return this.errorResponse(t)}};login=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` - mutation login($data: LoginInput!) { login(params: $data) { ${l}}} - `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var s,t;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.response)}catch(e){return console.error(e),this.errorResponse([e])}};magicLinkLogin=async r=>{var s,t;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=await this.graphqlQuery({query:` - mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }} - `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.magic_link_login)}catch(e){return this.errorResponse([e])}};oauthLogin=async(r,s,t,e)=>{let o=e;if(o||(o=c(u())),!Object.values(g).includes(r))throw new Error(`only following oauth providers are supported: ${Object.values(r).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");s&&s.length&&(o+=`&roles=${s.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${r}?redirect_uri=${t||this.config.redirectURL}&state=${o}`)};resendOtp=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` - mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }} - `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.resend_otp)}catch(e){return this.errorResponse([e])}};resetPassword=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.reset_password)}catch(e){return this.errorResponse([e])}};revokeToken=async r=>{if(!r.refresh_token&&!r.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let e=await(await m()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:r.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(e)};signup=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` - mutation signup($data: SignUpInput!) { signup(params: $data) { ${l}}} - `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.signup)}catch(e){return this.errorResponse([e])}};updateProfile=async(r,s)=>{var t,e;try{let o=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:s,variables:{data:r}});return(t=o==null?void 0:o.errors)!=null&&t.length?this.errorResponse(o.errors):this.okResponse((e=o.data)==null?void 0:e.update_profile)}catch(o){return this.errorResponse([o])}};deactivateAccount=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:r});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.deactivate_account)}catch(e){return this.errorResponse([e])}};validateJWTToken=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.validate_jwt_token)}catch(e){return this.errorResponse([e])}};validateSession=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.validate_session)}catch(e){return this.errorResponse([e])}};verifyEmail=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` - mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${l}}} - `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_email)}catch(e){return this.errorResponse([e])}};resendVerifyEmail=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` - mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }} - `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var s,t;try{let e=await this.graphqlQuery({query:` - mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${l}}} - `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var o;let e=await(await m()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(o=e==null?void 0:e.errors)!=null&&o.length?(console.error(e.errors),{data:void 0,errors:e.errors}):{data:e.data,errors:[]}};errorResponse=r=>({ok:!1,data:void 0,errors:r});okResponse=r=>({ok:!0,data:r,errors:[]})};i(y,"Authorizer");export{y as Authorizer,g as OAuthProviders,d as ResponseTypes};