matterbridge-roborock-vacuum-plugin
Version:
Matterbridge Roborock Vacuum Plugin
61 lines • 2.44 kB
JavaScript
import { VERIFICATION_CODE_RATE_LIMIT_MS } from '../../constants/index.js';
import { AuthenticationError } from '../../errors/index.js';
/** Service for managing verification code requests and rate limiting. */
export class VerificationCodeService {
authGateway;
stateRepository;
logger;
constructor(authGateway, stateRepository, logger) {
this.authGateway = authGateway;
this.stateRepository = stateRepository;
this.logger = logger;
}
/** Request verification code to be sent to email. */
async requestVerificationCode(email) {
try {
this.logger.debug('Requesting verification code for email:', email);
await this.authGateway.requestVerificationCode(email);
}
catch (error) {
this.logger.error('Failed to request verification code:', { email, error });
throw new AuthenticationError('Failed to send verification code. Please check your email address and try again.', {
email,
originalError: error instanceof Error ? error.message : String(error),
});
}
}
/** Check if rate limit is active for verification code requests. */
async isRateLimited() {
const authState = await this.stateRepository.getAuthState();
if (!authState?.codeRequestedAt) {
return false;
}
const now = Date.now();
return now - authState.codeRequestedAt < VERIFICATION_CODE_RATE_LIMIT_MS;
}
/** Get remaining wait time in seconds before next code request. */
async getRemainingWaitTime() {
const authState = await this.stateRepository.getAuthState();
if (!authState?.codeRequestedAt) {
return 0;
}
const now = Date.now();
const elapsed = now - authState.codeRequestedAt;
if (elapsed >= VERIFICATION_CODE_RATE_LIMIT_MS) {
return 0;
}
return Math.ceil((VERIFICATION_CODE_RATE_LIMIT_MS - elapsed) / 1000);
}
/** Record that a verification code was requested. */
async recordCodeRequest(email) {
await this.stateRepository.saveAuthState({
email,
codeRequestedAt: Date.now(),
});
}
/** Clear verification code request state. */
async clearCodeRequestState() {
await this.stateRepository.clearAuthState();
}
}
//# sourceMappingURL=VerificationCodeService.js.map