Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,6 @@ dist
toruslabs-customauth-*
bundle.min.js
types2/
.DS_Store
.DS_Store

.npmrc
28 changes: 23 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"@toruslabs/http-helpers": "^9.0.0",
"@toruslabs/metadata-helpers": "^8.2.0",
"@toruslabs/session-manager": "^5.6.0",
"@toruslabs/torus.js": "^17.2.2",
"@toruslabs/torus.js": "^17.2.3",
"bowser": "^2.14.1",
"deepmerge": "^4.3.1",
"events": "^3.3.0",
Expand Down
55 changes: 35 additions & 20 deletions src/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { type KeyType, Torus, TorusKey } from "@toruslabs/torus.js";
import { createHandler } from "./handlers/HandlerFactory";
import { registerServiceWorker } from "./registerServiceWorker";
import SentryHandler from "./sentry";
import { SENTRY_TXNS, UX_MODE, UX_MODE_TYPE } from "./utils/enums";
import { serializeError } from "./utils/error";
import { AUTH_CONNECTION_TYPE, SENTRY_TXNS, UX_MODE, UX_MODE_TYPE } from "./utils/enums";
import { CustomAuthLoginError, CustomAuthLoginErrorPrefix, serializeError } from "./utils/error";
import { handleRedirectParameters, isFirefox, padUrlString } from "./utils/helpers";
import {
CustomAuthArgs,
Expand Down Expand Up @@ -153,10 +153,11 @@ export class CustomAuth {
}

async triggerLogin(args: CustomAuthLoginParams): Promise<TorusLoginResponse> {
const { authConnectionId, authConnection, clientId, jwtParams, hash, queryParameters, customState, groupedAuthConnectionId } = args;
if (!this.isInitialized) {
throw new Error("Not initialized yet");
}

const { authConnectionId, authConnection, clientId, jwtParams, hash, queryParameters, customState, groupedAuthConnectionId } = args;
const loginHandler: ILoginHandler = createHandler({
authConnection,
clientId,
Expand All @@ -173,24 +174,32 @@ export class CustomAuth {
});

let loginParams: LoginWindowResponse;
if (hash && queryParameters) {
const { error, hashParameters, instanceParameters } = handleRedirectParameters(hash, queryParameters);
if (error) throw new Error(error);
const { access_token: accessToken, id_token: idToken, tgAuthResult, ...rest } = hashParameters;
// State has to be last here otherwise it will be overwritten
loginParams = { accessToken, idToken: idToken || tgAuthResult || "", ...rest, state: instanceParameters };
} else {
this.sessionManager.clearOrphanedData();
if (this.config.uxMode === UX_MODE.REDIRECT) {
const sessionId = this.getSessionId(`torus_login_${loginHandler.nonce}`);
this.sessionManager.setSessionId(sessionId);
await this.sessionManager.createSession({ args });
try {
if (hash && queryParameters) {
const { error, hashParameters, instanceParameters } = handleRedirectParameters(hash, queryParameters);
if (error) throw new Error(error);
const { access_token: accessToken, id_token: idToken, tgAuthResult, ...rest } = hashParameters;
// State has to be last here otherwise it will be overwritten
loginParams = { accessToken, idToken: idToken || tgAuthResult || "", ...rest, state: instanceParameters };
} else {
this.sessionManager.clearOrphanedData();
if (this.config.uxMode === UX_MODE.REDIRECT) {
const sessionId = this.getSessionId(`torus_login_${loginHandler.nonce}`);
this.sessionManager.setSessionId(sessionId);
await this.sessionManager.createSession({ args });
}
loginParams = await loginHandler.handleLoginWindow({
locationReplaceOnRedirect: this.config.locationReplaceOnRedirect,
popupFeatures: this.config.popupFeatures,
});
if (this.config.uxMode === UX_MODE.REDIRECT) return null;
}
loginParams = await loginHandler.handleLoginWindow({
locationReplaceOnRedirect: this.config.locationReplaceOnRedirect,
popupFeatures: this.config.popupFeatures,
});
if (this.config.uxMode === UX_MODE.REDIRECT) return null;
} catch (error) {
log.error(error);

const serializedError = await serializeError(error);
const errorMessage = `${CustomAuthLoginErrorPrefix}${serializedError.message || ""}`;
throw new CustomAuthLoginError(errorMessage);
}

const userInfo = await loginHandler.getUserInfo(loginParams);
Expand All @@ -201,6 +210,8 @@ export class CustomAuth {
idToken: loginParams.idToken || loginParams.accessToken,
additionalParams: userInfo.extraConnectionParams,
groupedAuthConnectionId,
recordId: args.customState?.recordId,
authConnection: userInfo.authConnection,
});

return {
Expand All @@ -218,6 +229,8 @@ export class CustomAuth {
idToken: string;
additionalParams?: ExtraParams;
groupedAuthConnectionId?: string;
recordId?: string;
authConnection: AUTH_CONNECTION_TYPE;
}): Promise<TorusKey> {
const { authConnectionId, userId, idToken, additionalParams, groupedAuthConnectionId } = params;
const verifier = groupedAuthConnectionId || authConnectionId;
Expand Down Expand Up @@ -263,6 +276,8 @@ export class CustomAuth {
},
useDkg: this.config.useDkg,
checkCommitment: this.config.checkCommitment,
recordId: params.recordId,
authConnection: params.authConnection,
});
}
);
Expand Down
9 changes: 9 additions & 0 deletions src/utils/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,12 @@ export const serializeError = async (error: unknown): Promise<Error> => {
}
return err;
};

export const CustomAuthLoginErrorPrefix = "CustomAuthLoginError: login failure.";

export class CustomAuthLoginError extends Error {
constructor(message: string) {
super(message);
this.name = "CustomAuthLoginError";
}
}
30 changes: 30 additions & 0 deletions test/unit/error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";

import { CustomAuthLoginError, CustomAuthLoginErrorPrefix, serializeError } from "../../src/utils/error";

describe("error utils", () => {
describe("serializeError", () => {
it("returns the original Error instance", async () => {
const originalError = new Error("popup blocked");

const serializedError = await serializeError(originalError);

expect(serializedError).toBe(originalError);
});
});

describe("CustomAuthLoginError", () => {
it("exports the expected login error prefix", () => {
expect(CustomAuthLoginErrorPrefix).toBe("CustomAuthLoginError: login failure.");
});

it("creates a named error that preserves the message", () => {
const error = new CustomAuthLoginError(`${CustomAuthLoginErrorPrefix} popup blocked`);

expect(error).toBeInstanceOf(Error);
expect(error).toBeInstanceOf(CustomAuthLoginError);
expect(error.name).toBe("CustomAuthLoginError");
expect(error.message).toBe("CustomAuthLoginError: login failure. popup blocked");
});
});
});
23 changes: 23 additions & 0 deletions test/unit/login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { createHandler } from "../../src/handlers/HandlerFactory";
import { UX_MODE } from "../../src/utils/enums";
import { CustomAuthLoginError, CustomAuthLoginErrorPrefix } from "../../src/utils/error";
import type { CustomAuthArgs, ILoginHandler, LoginWindowResponse, TorusConnectionResponse } from "../../src/utils/interfaces";

vi.mock("@toruslabs/torus.js", () => {
Expand Down Expand Up @@ -186,6 +187,28 @@ describe("CustomAuth", () => {

expect(setSessionIdSpy.mock.calls[0][0]).toBe(firstSessionId);
});

it("wraps login window failures in CustomAuthLoginError", async () => {
const CustomAuth = await getCustomAuth();
const handler = mockLoginHandler({
handleLoginWindow: vi.fn().mockRejectedValue(new Error("Popup blocked")),
});
vi.mocked(createHandler).mockReturnValue(handler);

const auth = new CustomAuth({ ...BASE_ARGS, uxMode: UX_MODE.REDIRECT });
auth.isInitialized = true;

const error = await auth
.triggerLogin({
authConnection: "google",
authConnectionId: "google-verifier",
clientId: "google-client-id",
})
.catch((err) => err);

expect(error).toBeInstanceOf(CustomAuthLoginError);
expect(error.message).toBe(`${CustomAuthLoginErrorPrefix}Popup blocked`);
});
});

describe("triggerLogin – popup mode with hash/queryParameters", () => {
Expand Down
Loading