Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
7.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import type {ApplicationID, UserID} from '@app/api/BrandedTypes';
import {
	BatchBuilder,
	deleteOneOrMany,
	executeConditional,
	fetchMany,
	fetchOne,
	upsertOne,
} from '@app/api/database/CassandraQueryExecution';
import type {
	OAuth2AccessTokenByUserRow,
	OAuth2AccessTokenRow,
	OAuth2AuthorizationCodeRow,
	OAuth2RefreshTokenByUserRow,
	OAuth2RefreshTokenRow,
} from '@app/api/database/types/OAuth2Types';
import {OAuth2AccessToken} from '@app/api/models/OAuth2AccessToken';
import {OAuth2AuthorizationCode} from '@app/api/models/OAuth2AuthorizationCode';
import {OAuth2RefreshToken} from '@app/api/models/OAuth2RefreshToken';
import {ACCESS_TOKEN_TTL_SECONDS, AUTHORIZATION_CODE_TTL_SECONDS} from '@app/api/oauth/OAuth2TokenConstants';
import {
	OAuth2AccessTokens,
	OAuth2AccessTokensByUser,
	OAuth2AuthorizationCodes,
	OAuth2RefreshTokens,
	OAuth2RefreshTokensByUser,
} from '@app/api/Tables';

function isAccessTokenExpired(createdAt: Date): boolean {
	return Date.now() - createdAt.getTime() > ACCESS_TOKEN_TTL_SECONDS * 1000;
}

function isAuthorizationCodeExpired(createdAt: Date): boolean {
	return Date.now() - createdAt.getTime() > AUTHORIZATION_CODE_TTL_SECONDS * 1000;
}

const TOKEN_DELETE_BATCH_STATEMENTS = 60;

const SELECT_AUTHORIZATION_CODE = OAuth2AuthorizationCodes.selectCql({
	where: OAuth2AuthorizationCodes.where.eq('code'),
});
const SELECT_ACCESS_TOKEN = OAuth2AccessTokens.selectCql({
	where: OAuth2AccessTokens.where.eq('token_'),
});
const SELECT_ACCESS_TOKENS_BY_USER = OAuth2AccessTokensByUser.selectCql({
	columns: ['token_'],
	where: OAuth2AccessTokensByUser.where.eq('user_id'),
});
const SELECT_REFRESH_TOKEN = OAuth2RefreshTokens.selectCql({
	where: OAuth2RefreshTokens.where.eq('token_'),
});
const SELECT_REFRESH_TOKENS_BY_USER = OAuth2RefreshTokensByUser.selectCql({
	columns: ['token_'],
	where: OAuth2RefreshTokensByUser.where.eq('user_id'),
});

export class OAuth2TokenRepository {
	async createAuthorizationCode(data: OAuth2AuthorizationCodeRow): Promise<OAuth2AuthorizationCode> {
		await upsertOne(OAuth2AuthorizationCodes.insertWithTtl(data, AUTHORIZATION_CODE_TTL_SECONDS));
		return new OAuth2AuthorizationCode(data);
	}

	async getAuthorizationCode(code: string): Promise<OAuth2AuthorizationCode | null> {
		const row = await fetchOne<OAuth2AuthorizationCodeRow>(SELECT_AUTHORIZATION_CODE, {code});
		if (!row) {
			return null;
		}
		if (isAuthorizationCodeExpired(row.created_at)) {
			return null;
		}
		return new OAuth2AuthorizationCode(row);
	}

	async deleteAuthorizationCode(code: string): Promise<void> {
		await deleteOneOrMany(OAuth2AuthorizationCodes.deleteByPk({code}));
	}

	async consumeAuthorizationCode(code: string, applicationId: ApplicationID): Promise<boolean> {
		return executeConditional(OAuth2AuthorizationCodes.conditionalDeleteByPk({code}, {application_id: applicationId}));
	}

	async createAccessToken(data: OAuth2AccessTokenRow): Promise<OAuth2AccessToken> {
		const batch = new BatchBuilder();
		batch.addPrepared(OAuth2AccessTokens.insertWithTtl(data, ACCESS_TOKEN_TTL_SECONDS));
		batch.addPrepared(
			OAuth2AccessTokensByUser.insertWithTtl(
				{
					user_id: data.user_id,
					token_: data.token_,
				},
				ACCESS_TOKEN_TTL_SECONDS,
			),
		);
		await batch.execute();
		return new OAuth2AccessToken(data);
	}

	async getAccessToken(token: string): Promise<OAuth2AccessToken | null> {
		const row = await fetchOne<OAuth2AccessTokenRow>(SELECT_ACCESS_TOKEN, {token_: token});
		if (!row) {
			return null;
		}
		if (isAccessTokenExpired(row.created_at)) {
			return null;
		}
		return new OAuth2AccessToken(row);
	}

	async deleteAllAccessTokensForUser(userId: UserID): Promise<void> {
		const tokens = await fetchMany<OAuth2AccessTokenByUserRow>(SELECT_ACCESS_TOKENS_BY_USER, {
			user_id: userId,
		});
		if (tokens.length === 0) {
			return;
		}
		const batch = new BatchBuilder();
		for (const tokenRow of tokens) {
			batch.addPrepared(OAuth2AccessTokens.deleteByPk({token_: tokenRow.token_}));
			batch.addPrepared(OAuth2AccessTokensByUser.deleteByPk({user_id: userId, token_: tokenRow.token_}));
		}
		await batch.executeChunked(TOKEN_DELETE_BATCH_STATEMENTS, true);
	}

	async createRefreshToken(data: OAuth2RefreshTokenRow): Promise<OAuth2RefreshToken> {
		const batch = new BatchBuilder();
		batch.addPrepared(OAuth2RefreshTokens.insert(data));
		batch.addPrepared(
			OAuth2RefreshTokensByUser.insert({
				user_id: data.user_id,
				token_: data.token_,
			}),
		);
		await batch.execute();
		return new OAuth2RefreshToken(data);
	}

	async getRefreshToken(token: string): Promise<OAuth2RefreshToken | null> {
		const row = await fetchOne<OAuth2RefreshTokenRow>(SELECT_REFRESH_TOKEN, {token_: token});
		return row ? new OAuth2RefreshToken(row) : null;
	}

	async consumeRefreshToken(token: string, applicationId: ApplicationID, userId: UserID): Promise<boolean> {
		const consumed = await executeConditional(
			OAuth2RefreshTokens.conditionalDeleteByPk({token_: token}, {application_id: applicationId, user_id: userId}),
		);
		if (consumed) {
			await deleteOneOrMany(OAuth2RefreshTokensByUser.deleteByPk({user_id: userId, token_: token}));
		}
		return consumed;
	}

	async deleteAllRefreshTokensForUser(userId: UserID): Promise<void> {
		const tokens = await fetchMany<OAuth2RefreshTokenByUserRow>(SELECT_REFRESH_TOKENS_BY_USER, {
			user_id: userId,
		});
		if (tokens.length === 0) {
			return;
		}
		const batch = new BatchBuilder();
		for (const tokenRow of tokens) {
			batch.addPrepared(OAuth2RefreshTokens.deleteByPk({token_: tokenRow.token_}));
			batch.addPrepared(OAuth2RefreshTokensByUser.deleteByPk({user_id: userId, token_: tokenRow.token_}));
		}
		await batch.executeChunked(TOKEN_DELETE_BATCH_STATEMENTS, true);
	}

	async listRefreshTokensForUser(userId: UserID): Promise<Array<OAuth2RefreshToken>> {
		const tokenRefs = await fetchMany<OAuth2RefreshTokenByUserRow>(SELECT_REFRESH_TOKENS_BY_USER, {
			user_id: userId,
		});
		if (tokenRefs.length === 0) {
			return [];
		}
		const tokens: Array<OAuth2RefreshToken> = [];
		const staleRefs: Array<string> = [];
		for (const tokenRef of tokenRefs) {
			const row = await fetchOne<OAuth2RefreshTokenRow>(SELECT_REFRESH_TOKEN, {token_: tokenRef.token_});
			if (row) {
				tokens.push(new OAuth2RefreshToken(row));
			} else {
				staleRefs.push(tokenRef.token_);
			}
		}
		if (staleRefs.length > 0) {
			const batch = new BatchBuilder();
			for (const staleToken of staleRefs) {
				batch.addPrepared(OAuth2RefreshTokensByUser.deleteByPk({user_id: userId, token_: staleToken}));
			}
			await batch.execute();
		}
		return tokens;
	}

	async deleteAllTokensForUserAndApplication(userId: UserID, applicationId: ApplicationID): Promise<void> {
		const accessTokenRefs = await fetchMany<OAuth2AccessTokenByUserRow>(SELECT_ACCESS_TOKENS_BY_USER, {
			user_id: userId,
		});
		const refreshTokenRefs = await fetchMany<OAuth2RefreshTokenByUserRow>(SELECT_REFRESH_TOKENS_BY_USER, {
			user_id: userId,
		});
		const batch = new BatchBuilder();
		for (const tokenRef of accessTokenRefs) {
			const row = await fetchOne<OAuth2AccessTokenRow>(SELECT_ACCESS_TOKEN, {token_: tokenRef.token_});
			if (row && row.application_id === applicationId) {
				batch.addPrepared(OAuth2AccessTokens.deleteByPk({token_: tokenRef.token_}));
				batch.addPrepared(OAuth2AccessTokensByUser.deleteByPk({user_id: userId, token_: tokenRef.token_}));
			}
		}
		for (const tokenRef of refreshTokenRefs) {
			const row = await fetchOne<OAuth2RefreshTokenRow>(SELECT_REFRESH_TOKEN, {token_: tokenRef.token_});
			if (row && row.application_id === applicationId) {
				batch.addPrepared(OAuth2RefreshTokens.deleteByPk({token_: tokenRef.token_}));
				batch.addPrepared(OAuth2RefreshTokensByUser.deleteByPk({user_id: userId, token_: tokenRef.token_}));
			}
		}
		await batch.execute();
	}
}