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
3 changes: 3 additions & 0 deletions packages/api/src/EmbeddedChatApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ export default class EmbeddedChatApi {
this._authListener = (user: any) => {
if (user) {
this._applyCredentials(user);
} else {
this.sdk.rest.setCredentials(undefined);
}
};
this.auth.onAuthChange(this._authListener);
Expand Down Expand Up @@ -221,6 +223,7 @@ export default class EmbeddedChatApi {
"Auto-login failed:",
error instanceof Error ? error.message : error
);
throw error;
}
}

Expand Down
287 changes: 207 additions & 80 deletions packages/auth/src/RocketChatAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import loginWithOAuthServiceToken from "./loginWithOAuthServiceToken";
import loginWithResumeToken from "./loginWithResumeToken";
import { IRocketChatAuthOptions } from "./IRocketChatAuthOptions";
import { Api, ApiError } from "./Api";
import loginWithRocketChatOAuth from "./loginWithRocketChatOAuth";
import getRocketChatOAuthCredentials from "./loginWithRocketChatOAuth";
import handleSecureLogin from "./handleSecureLogin";
class RocketChatAuth {
host: string;
Expand All @@ -14,6 +14,44 @@ class RocketChatAuth {
deleteToken: () => Promise<void>;
saveToken: (token: string) => Promise<void>;
getToken: () => Promise<string>;
private sessionUpdate: Promise<unknown> = Promise.resolve();
private logoutVersion = 0;
private currentUserVersion = 0;
// Keep sessions here until Rocket.Chat confirms revocation.
private pendingRevocations = new Map<string, string>();
private interruptedRestoreError?: unknown;

private updateSession<T>(update: (version: number) => Promise<T>) {
const version = this.logoutVersion;
const run = () => update(version);
const result = this.sessionUpdate.then(run, run);
this.sessionUpdate = result;
return result;
}

private checkLoginVersion(version: number) {
if (version !== this.logoutVersion) {
throw new Error("Login was interrupted by logout.");
}
}

private startLogin(
request: () => Promise<any>,
version = this.logoutVersion
) {
return this.updateSession(async () => {
this.checkLoginVersion(version);
const { data } = await request();
return this.finishLogin(data, version);
});
}

private async finishLogin(data: any, version: number, resumedToken?: string) {
await this.persistUser(data, version, data?.authToken !== resumedToken);
this.checkLoginVersion(version);
return data;
}

constructor({
host,
saveToken,
Expand All @@ -36,7 +74,7 @@ class RocketChatAuth {
async onAuthChange(callback: (user: object | null) => void) {
this.authListeners.push(callback);
const user = await this.getCurrentUser();
if (this.authListeners.includes(callback)) {
if (this.authListeners.includes(callback) && user === this.currentUser) {
callback(user);
}
}
Expand All @@ -63,18 +101,9 @@ class RocketChatAuth {
password: string;
code?: string | number;
}) {
const response = await loginWithPassword(
{
api: this.api,
},
{
user,
password,
code,
}
return this.startLogin(() =>
loginWithPassword({ api: this.api }, { user, password, code })
);
this.setUser(response.data);
return this.currentUser;
}

/**
Expand All @@ -87,14 +116,9 @@ class RocketChatAuth {
service: string;
access_token: string;
}) {
const response = await loginWithOAuthServiceToken(
{
api: this.api,
},
credentials
return this.startLogin(() =>
loginWithOAuthServiceToken({ api: this.api }, credentials)
);
this.setUser(response.data);
return this.currentUser;
}

/**
Expand All @@ -105,12 +129,12 @@ class RocketChatAuth {
if (typeof window === "undefined") {
throw new Error("loginWithRocketChatOAuth can only be called in browser");
}
const response = await loginWithRocketChatOAuth({
api: this.api,
});
this.setUser(response.data);
this.notifyAuthListeners();
return this.currentUser;
const version = this.logoutVersion;
const credentials = await getRocketChatOAuthCredentials({ api: this.api });
return this.startLogin(async () => {
const response = await this.api.post("/api/v1/login", credentials);
return response.data;
}, version);
}

/**
Expand All @@ -119,16 +143,58 @@ class RocketChatAuth {
* @returns
*/
async loginWithResumeToken(resume: string) {
const response = await loginWithResumeToken(
{
api: this.api,
},
{
resume,
return this.updateSession((version) => this.resumeSession(resume, version));
}

private async readForRestore<T>(
request: Promise<T>,
version: number,
token?: string
) {
try {
return await request;
} catch (error) {
// Without the restored user ID, logout cannot confirm server-side revocation.
if (
version !== this.logoutVersion &&
(!token || token !== this.currentUser?.authToken) &&
!(error instanceof ApiError && error.response.status === 401)
) {
this.interruptedRestoreError = error;
}
);
this.setUser(response.data);
return this.currentUser;
throw error;
}
}

private async resumeSession(
token: string,
version: number,
expireInvalid = false
) {
let response;
try {
response = await this.readForRestore(
loginWithResumeToken({ api: this.api }, { resume: token }),
version,
token
);
} catch (error) {
if (
!expireInvalid ||
version !== this.logoutVersion ||
!(error instanceof ApiError && error.response.status === 401)
) {
throw error;
}
// The server rejected this token. Expire it before the next queued login.
try {
await this.deleteToken();
} finally {
this.clearCurrentUser();
}
return null;
}
return this.finishLogin(response.data, version, token);
}

/**
Expand All @@ -152,79 +218,140 @@ class RocketChatAuth {
* @returns
*/
async getCurrentUser(refresh = false) {
if (this.currentUser && this.currentUser.authToken) {
if (
refresh ||
new Date() >= new Date(this.lastFetched.getTime() + 3540000)
) {
// 59 minutes
try {
await this.loginWithResumeToken(this.currentUser.authToken);
} catch (e) {
if (e instanceof ApiError && e.response?.status === 401) {
// token cannot be refreshed as the resume token is no longer valid.
await this.logout();
}
}
const user = this.currentUser;
if (!user?.authToken || this.currentUserVersion !== this.logoutVersion)
return null;
if (!refresh && Date.now() < this.lastFetched.getTime() + 59 * 60_000)
return user;

return this.updateSession(async (version) => {
if (version !== this.logoutVersion) return null;
if (user !== this.currentUser) return this.currentUser;
try {
await this.resumeSession(user.authToken, version, true);
} catch (error) {
if (refresh) throw error;
}
}
return this.currentUser;
return version === this.logoutVersion ? this.currentUser : null;
});
}

/**
* Set current user
* @param user
*/
async setUser(user: object) {
this.lastFetched = new Date();
await this.updateSession((version) => this.persistUser(user, version));
}

private async persistUser(
user: object,
version: number,
newlyIssued = false
) {
if (!user || !("authToken" in user) || typeof user.authToken !== "string") {
throw new Error("The login response is missing the session token.");
}
const token = user.authToken;
try {
this.checkLoginVersion(version);
await this.saveToken(token);
this.checkLoginVersion(version);
} catch (error) {
if ("userId" in user && typeof user.userId === "string") {
if (version !== this.logoutVersion) {
this.pendingRevocations.set(token, user.userId);
} else if (newlyIssued && token !== this.currentUser?.authToken) {
try {
await this.revokeToken(token, user.userId);
} catch (revocationError) {
if (version !== this.logoutVersion)
this.pendingRevocations.set(token, user.userId);
throw new AggregateError(
[error, revocationError],
"Login failed and the new session could not be revoked."
);
}
}
}
throw error;
}
this.currentUser = user;
await this.save();
this.currentUserVersion = version;
this.lastFetched = new Date();
this.notifyAuthListeners();
}

async save() {
await this.saveToken(this.currentUser.authToken);
this.notifyAuthListeners();
await this.updateSession(async () => {
await this.saveToken(this.currentUser.authToken);
this.notifyAuthListeners();
});
}

/**
* Load current user from localStorage
*/
async load() {
try {
const token = await this.getToken();
if (token) {
const user = await this.loginWithResumeToken(token);
if (user) {
this.lastFetched = new Date();
await this.getCurrentUser();
}
await this.updateSession(async (version) => {
try {
const token = await this.readForRestore(this.getToken(), version);
if (token) await this.resumeSession(token, version);
} catch (error) {
if (version === this.logoutVersion) this.notifyAuthListeners();
if (!(error instanceof ApiError && error.response.status === 401))
throw error;
}
} catch (e) {
console.log("Failed to login user on initial load. Sign in.");
this.notifyAuthListeners();
}
});
}

/**
* Logout current user
*/
async logout() {
private async revokeToken(token: string, userId: string) {
try {
await this.api.post(`/api/v1/logout`, undefined, {
headers: {
"X-Auth-Token": this.currentUser.authToken,
"X-User-Id": this.currentUser.userId,
},
await this.api.post("/api/v1/logout", undefined, {
headers: { "X-Auth-Token": token, "X-User-Id": userId },
});
} catch (err) {
console.error(err);
} finally {
await this.deleteToken();
} catch (error) {
// An already expired token has no server session left to revoke.
if (!(error instanceof ApiError && error.response.status === 401)) {
throw error;
}
}
}

private clearCurrentUser() {
this.lastFetched = new Date(0);
this.currentUser = null;
this.notifyAuthListeners();
}

/**
* Logout current user
*/
async logout() {
this.logoutVersion++;
await this.updateSession(async () => {
const sessions = this.pendingRevocations;
if (this.currentUser) {
sessions.set(this.currentUser.authToken, this.currentUser.userId);
}
try {
const results = await Promise.allSettled([
...Array.from(sessions, async ([token, userId]) => {
await this.revokeToken(token, userId);
sessions.delete(token);
}),
this.deleteToken(),
]);
for (const result of results) {
if (result.status === "rejected") throw result.reason;
}
if (this.interruptedRestoreError) throw this.interruptedRestoreError;
} finally {
this.interruptedRestoreError = undefined;
this.clearCurrentUser();
}
});
}
}

export default RocketChatAuth;
Loading
Loading