refactor progress

This commit is contained in:
Hampus Kraft
2026-02-17 12:22:36 +00:00
parent cb31608523
commit d5abd1a7e4
8257 changed files with 1190207 additions and 761040 deletions

View File

@@ -0,0 +1,23 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
export interface ISmsService {
startVerification(phone: string): Promise<void>;
checkVerification(phone: string, code: string): Promise<boolean>;
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import type {ISmsService} from '@fluxer/sms/src/ISmsService';
import type {ISmsProvider} from '@fluxer/sms/src/providers/ISmsProvider';
import {UnavailableSmsProvider} from '@fluxer/sms/src/providers/UnavailableSmsProvider';
export class SmsService implements ISmsService {
private readonly provider: ISmsProvider;
constructor(provider: ISmsProvider = new UnavailableSmsProvider()) {
this.provider = provider;
}
async startVerification(phone: string): Promise<void> {
await this.provider.startVerification(phone);
}
async checkVerification(phone: string, code: string): Promise<boolean> {
return this.provider.checkVerification(phone, code);
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import crypto from 'node:crypto';
import {
SMS_MASK_VISIBLE_PREFIX_LENGTH,
SMS_VERIFICATION_CACHE_PREFIX,
SMS_VERIFICATION_CODE_LENGTH,
SMS_VERIFICATION_MESSAGE_TEMPLATE,
} from '@fluxer/constants/src/SmsVerificationConstants';
export function buildSmsVerificationCacheKey(phone: string): string {
return `${SMS_VERIFICATION_CACHE_PREFIX}${phone}`;
}
export function generateSmsVerificationCode(): string {
const maxCodeValue = 10 ** SMS_VERIFICATION_CODE_LENGTH;
const value = crypto.randomInt(0, maxCodeValue);
return value.toString().padStart(SMS_VERIFICATION_CODE_LENGTH, '0');
}
export function buildSmsVerificationMessage(code: string, ttlSeconds: number): string {
const ttlMinutes = Math.max(1, Math.floor(ttlSeconds / 60));
return SMS_VERIFICATION_MESSAGE_TEMPLATE.replace('{code}', code).replace('{minutes}', String(ttlMinutes));
}
export function timingSafeEqualStrings(left: string, right: string): boolean {
const leftBuffer = Buffer.from(left);
const rightBuffer = Buffer.from(right);
if (leftBuffer.length !== rightBuffer.length) {
return false;
}
return crypto.timingSafeEqual(leftBuffer, rightBuffer);
}
export function maskPhoneNumber(phone: string): string {
if (phone.length <= SMS_MASK_VISIBLE_PREFIX_LENGTH) {
return `${phone}***`;
}
return `${phone.slice(0, SMS_MASK_VISIBLE_PREFIX_LENGTH)}***`;
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import {SmsVerificationUnavailableError} from '@fluxer/errors/src/domains/auth/SmsVerificationUnavailableError';
import {createMockLogger} from '@fluxer/logger/src/mock';
import {createSmsProvider} from '@fluxer/sms/src/providers/SmsProviderFactory';
import {describe, expect, it} from 'vitest';
describe('createSmsProvider', () => {
it('creates a test provider that accepts the configured code', async () => {
const provider = createSmsProvider({
mode: 'test',
logger: createMockLogger(),
verificationCode: '654321',
});
await expect(provider.startVerification('+15551234567')).resolves.toBeUndefined();
await expect(provider.checkVerification('+15551234567', '654321')).resolves.toBe(true);
await expect(provider.checkVerification('+15551234567', '123456')).resolves.toBe(false);
});
it('creates an unavailable provider that throws on verification checks', async () => {
const provider = createSmsProvider({
mode: 'unavailable',
logger: createMockLogger(),
});
await expect(provider.startVerification('+15551234567')).resolves.toBeUndefined();
await expect(provider.checkVerification('+15551234567', '123456')).rejects.toThrow(SmsVerificationUnavailableError);
});
it('creates a Twilio provider in twilio mode', async () => {
const provider = createSmsProvider({
mode: 'twilio',
config: {
accountSid: 'AC123',
authToken: 'twilio-secret',
verifyServiceSid: 'VA123',
},
logger: createMockLogger(),
fetchFn: async () => new Response(JSON.stringify({status: 'pending'}), {status: 200}),
});
await expect(provider.startVerification('+15551234567')).resolves.toBeUndefined();
});
});

View File

@@ -0,0 +1,129 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {SmsVerificationUnavailableError} from '@fluxer/errors/src/domains/auth/SmsVerificationUnavailableError';
import type {ISmsProvider} from '@fluxer/sms/src/providers/ISmsProvider';
import {UnavailableSmsProvider} from '@fluxer/sms/src/providers/UnavailableSmsProvider';
import {SmsService} from '@fluxer/sms/src/SmsService';
import {describe, expect, it} from 'vitest';
function createInMemoryProvider(): ISmsProvider & {
verifications: Map<string, string>;
startedVerifications: Array<string>;
} {
const verifications = new Map<string, string>();
const startedVerifications: Array<string> = [];
return {
verifications,
startedVerifications,
async startVerification(phone: string): Promise<void> {
startedVerifications.push(phone);
verifications.set(phone, '123456');
},
async checkVerification(phone: string, code: string): Promise<boolean> {
const storedCode = verifications.get(phone);
if (storedCode === code) {
verifications.delete(phone);
return true;
}
return false;
},
};
}
describe('SmsService', () => {
describe('with provider', () => {
it('starts verification through provider', async () => {
const provider = createInMemoryProvider();
const service = new SmsService(provider);
await service.startVerification('+15551234567');
expect(provider.startedVerifications).toContain('+15551234567');
expect(provider.verifications.has('+15551234567')).toBe(true);
});
it('checks verification through provider and returns true for valid code', async () => {
const provider = createInMemoryProvider();
const service = new SmsService(provider);
await service.startVerification('+15551234567');
const code = provider.verifications.get('+15551234567') ?? '';
const result = await service.checkVerification('+15551234567', code);
expect(result).toBe(true);
});
it('checks verification through provider and returns false for invalid code', async () => {
const provider = createInMemoryProvider();
const service = new SmsService(provider);
await service.startVerification('+15551234567');
const result = await service.checkVerification('+15551234567', 'wrong-code');
expect(result).toBe(false);
});
it('returns false for verification check on non-existent phone', async () => {
const provider = createInMemoryProvider();
const service = new SmsService(provider);
const result = await service.checkVerification('+15559999999', '123456');
expect(result).toBe(false);
});
});
describe('with unavailable provider', () => {
it('silently completes startVerification when provider is unavailable', async () => {
const service = new SmsService(new UnavailableSmsProvider());
await expect(service.startVerification('+15551234567')).resolves.toBeUndefined();
});
it('throws SmsVerificationUnavailableError when checking verification', async () => {
const service = new SmsService(new UnavailableSmsProvider());
await expect(service.checkVerification('+15551234567', '123456')).rejects.toThrow(
SmsVerificationUnavailableError,
);
});
it('defaults to unavailable provider when no provider is injected', async () => {
const service = new SmsService();
await expect(service.checkVerification('+15551234567', '123456')).rejects.toThrow(
SmsVerificationUnavailableError,
);
});
it('exposes the correct api error code when checking verification', async () => {
const service = new SmsService(new UnavailableSmsProvider());
await expect(service.checkVerification('+15551234567', '123456')).rejects.toMatchObject({
code: APIErrorCodes.SMS_VERIFICATION_UNAVAILABLE,
message: APIErrorCodes.SMS_VERIFICATION_UNAVAILABLE,
});
});
});
});

View File

@@ -0,0 +1,74 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import {createMockLogger} from '@fluxer/logger/src/mock';
import {TestSmsProvider} from '@fluxer/sms/src/providers/TestSmsProvider';
import {describe, expect, it} from 'vitest';
describe('TestSmsProvider', () => {
describe('startVerification', () => {
it('completes without error', async () => {
const logger = createMockLogger();
const provider = new TestSmsProvider({logger});
await expect(provider.startVerification('+15551234567')).resolves.toBeUndefined();
});
it('supports different phone number formats', async () => {
const logger = createMockLogger();
const provider = new TestSmsProvider({logger});
await expect(provider.startVerification('+14155552671')).resolves.toBeUndefined();
await expect(provider.startVerification('+447911123456')).resolves.toBeUndefined();
await expect(provider.startVerification('+81312345678')).resolves.toBeUndefined();
});
});
describe('checkVerification', () => {
it('returns true for the default valid code', async () => {
const logger = createMockLogger();
const provider = new TestSmsProvider({logger});
await provider.startVerification('+15551234567');
const result = await provider.checkVerification('+15551234567', '123456');
expect(result).toBe(true);
});
it('returns false for invalid codes', async () => {
const logger = createMockLogger();
const provider = new TestSmsProvider({logger});
await provider.startVerification('+15551234567');
expect(await provider.checkVerification('+15551234567', '000000')).toBe(false);
expect(await provider.checkVerification('+15551234567', '654321')).toBe(false);
expect(await provider.checkVerification('+15551234567', 'abcdef')).toBe(false);
expect(await provider.checkVerification('+15551234567', '')).toBe(false);
});
it('supports custom verification code overrides', async () => {
const logger = createMockLogger();
const provider = new TestSmsProvider({logger, verificationCode: '654321'});
expect(await provider.checkVerification('+15551111111', '123456')).toBe(false);
expect(await provider.checkVerification('+15551111111', '654321')).toBe(true);
});
});
});

View File

@@ -0,0 +1,112 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import {InvalidPhoneNumberError} from '@fluxer/errors/src/domains/auth/InvalidPhoneNumberError';
import {createMockLogger} from '@fluxer/logger/src/mock';
import {TwilioSmsProvider} from '@fluxer/sms/src/providers/TwilioSmsProvider';
import {describe, expect, it} from 'vitest';
interface TwilioRequest {
url: string;
authHeader: string;
body: string;
}
function getCapturedRequest(request: TwilioRequest | null): TwilioRequest {
if (!request) {
throw new Error('Expected Twilio request to be captured');
}
return request;
}
describe('TwilioSmsProvider', () => {
it('calls Twilio Verify start endpoint with expected payload', async () => {
let capturedRequest: TwilioRequest | null = null;
const fetchStub: typeof fetch = async (_input, init) => {
capturedRequest = {
url: String(_input),
authHeader: (init?.headers as Record<string, string>).Authorization,
body: init?.body as string,
};
return new Response(JSON.stringify({success: true}), {status: 200});
};
const provider = new TwilioSmsProvider({
config: {
accountSid: 'AC123',
authToken: 'twilio-secret',
verifyServiceSid: 'VA123',
},
logger: createMockLogger(),
fetchFn: fetchStub,
});
const phone = '+15551234567';
await provider.startVerification(phone);
const request = getCapturedRequest(capturedRequest);
expect(request.url).toBe('https://verify.twilio.com/v2/Services/VA123/Verifications');
expect(request.authHeader).toBe(`Basic ${Buffer.from('AC123:twilio-secret').toString('base64')}`);
expect(request.body).toContain('To=%2B15551234567');
expect(request.body).toContain('Channel=sms');
});
it('returns true when verification check is approved', async () => {
const provider = new TwilioSmsProvider({
config: {
accountSid: 'AC123',
authToken: 'twilio-secret',
verifyServiceSid: 'VA123',
},
logger: createMockLogger(),
fetchFn: async () => new Response(JSON.stringify({status: 'approved'}), {status: 200}),
});
const result = await provider.checkVerification('+15551234567', '123456');
expect(result).toBe(true);
});
it('returns false when verification check is rejected', async () => {
const provider = new TwilioSmsProvider({
config: {
accountSid: 'AC123',
authToken: 'twilio-secret',
verifyServiceSid: 'VA123',
},
logger: createMockLogger(),
fetchFn: async () => new Response(JSON.stringify({status: 'pending'}), {status: 200}),
});
expect(await provider.checkVerification('+15551234567', '123456')).toBe(false);
});
it('throws InvalidPhoneNumberError for Twilio invalid phone code', async () => {
const provider = new TwilioSmsProvider({
config: {
accountSid: 'AC123',
authToken: 'twilio-secret',
verifyServiceSid: 'VA123',
},
logger: createMockLogger(),
fetchFn: async () =>
new Response(JSON.stringify({code: 21211, message: 'Invalid To phone number'}), {status: 400}),
});
await expect(provider.startVerification('+15550000000')).rejects.toThrow(InvalidPhoneNumberError);
});
});

View File

@@ -0,0 +1,23 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
export interface ISmsProvider {
startVerification(phone: string): Promise<void>;
checkVerification(phone: string, code: string): Promise<boolean>;
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
import type {ISmsProvider} from '@fluxer/sms/src/providers/ISmsProvider';
import {TestSmsProvider} from '@fluxer/sms/src/providers/TestSmsProvider';
import {TwilioSmsProvider, type TwilioSmsProviderConfig} from '@fluxer/sms/src/providers/TwilioSmsProvider';
import {UnavailableSmsProvider} from '@fluxer/sms/src/providers/UnavailableSmsProvider';
interface BaseSmsProviderFactoryParams {
logger?: LoggerInterface;
}
interface CreateUnavailableSmsProviderParams extends BaseSmsProviderFactoryParams {
mode: 'unavailable';
}
interface CreateTestSmsProviderParams extends BaseSmsProviderFactoryParams {
mode: 'test';
verificationCode?: string;
}
interface CreateTwilioSmsProviderParams extends BaseSmsProviderFactoryParams {
mode: 'twilio';
config: TwilioSmsProviderConfig;
fetchFn?: typeof fetch;
}
export type CreateSmsProviderParams =
| CreateUnavailableSmsProviderParams
| CreateTestSmsProviderParams
| CreateTwilioSmsProviderParams;
export function createSmsProvider(params: CreateSmsProviderParams): ISmsProvider {
if (params.mode === 'test') {
return new TestSmsProvider({
logger: params.logger,
verificationCode: params.verificationCode,
});
}
if (params.mode === 'twilio') {
return new TwilioSmsProvider({
config: params.config,
logger: params.logger,
fetchFn: params.fetchFn,
});
}
return new UnavailableSmsProvider();
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import {SMS_TEST_VERIFICATION_CODE} from '@fluxer/constants/src/SmsVerificationConstants';
import {createLogger} from '@fluxer/logger/src/Logger';
import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
import type {ISmsProvider} from '@fluxer/sms/src/providers/ISmsProvider';
import {maskPhoneNumber} from '@fluxer/sms/src/SmsVerificationUtils';
interface TestSmsProviderOptions {
logger?: LoggerInterface;
verificationCode?: string;
}
export class TestSmsProvider implements ISmsProvider {
private readonly logger: LoggerInterface;
private readonly verificationCode: string;
constructor({logger, verificationCode}: TestSmsProviderOptions = {}) {
this.logger = logger ?? createLogger('@fluxer/sms/src', {environment: 'test'});
this.verificationCode = verificationCode ?? SMS_TEST_VERIFICATION_CODE;
}
async startVerification(phone: string): Promise<void> {
this.logger.info(
`[TestSmsProvider] Mock verification started for ${maskPhoneNumber(phone)}. Use code: ${this.verificationCode}`,
);
}
async checkVerification(phone: string, code: string): Promise<boolean> {
const isValid = code === this.verificationCode;
this.logger.info(
`[TestSmsProvider] Mock verification check for ${maskPhoneNumber(phone)} with code ${code}: ${isValid ? 'APPROVED' : 'REJECTED'}`,
);
return isValid;
}
}

View File

@@ -0,0 +1,128 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import {SMS_TWILIO_DEFAULT_VERIFY_API_URL} from '@fluxer/constants/src/SmsVerificationConstants';
import {InvalidPhoneNumberError} from '@fluxer/errors/src/domains/auth/InvalidPhoneNumberError';
import {createLogger} from '@fluxer/logger/src/Logger';
import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
import type {ISmsProvider} from '@fluxer/sms/src/providers/ISmsProvider';
import {maskPhoneNumber} from '@fluxer/sms/src/SmsVerificationUtils';
const TWILIO_INVALID_PHONE_ERROR_CODE = 21211;
interface TwilioErrorResponse {
code?: number;
message?: string;
}
interface TwilioVerificationCheckResponse {
status?: string;
}
export interface TwilioSmsProviderConfig {
accountSid: string;
authToken: string;
verifyServiceSid: string;
verifyApiUrl?: string;
}
interface TwilioSmsProviderDependencies {
config: TwilioSmsProviderConfig;
logger?: LoggerInterface;
fetchFn?: typeof fetch;
}
export class TwilioSmsProvider implements ISmsProvider {
private readonly verifyApiUrl: string;
private readonly logger: LoggerInterface;
private readonly config: TwilioSmsProviderConfig;
private readonly fetchFn: typeof fetch;
constructor({config, logger, fetchFn = fetch}: TwilioSmsProviderDependencies) {
this.verifyApiUrl = config.verifyApiUrl ?? SMS_TWILIO_DEFAULT_VERIFY_API_URL;
this.logger = logger ?? createLogger('@fluxer/sms/src');
this.config = config;
this.fetchFn = fetchFn;
}
async startVerification(phone: string): Promise<void> {
const response = await this.requestTwilio('Verifications', {
To: phone,
Channel: 'sms',
});
if (response.ok) {
return;
}
const body = await this.parseErrorBody(response);
if (body?.code === TWILIO_INVALID_PHONE_ERROR_CODE) {
throw new InvalidPhoneNumberError();
}
this.logger.error(
{
status: response.status,
code: body?.code,
message: body?.message,
phone: maskPhoneNumber(phone),
},
'[TwilioSmsProvider] Failed to start SMS verification',
);
throw new Error('Failed to start SMS verification');
}
async checkVerification(phone: string, code: string): Promise<boolean> {
const response = await this.requestTwilio('VerificationCheck', {
To: phone,
Code: code,
});
if (!response.ok) {
return false;
}
const body = (await response.json()) as TwilioVerificationCheckResponse;
return body.status === 'approved';
}
private async requestTwilio(
endpoint: 'Verifications' | 'VerificationCheck',
body: Record<string, string>,
): Promise<Response> {
const url = `${this.verifyApiUrl}/Services/${this.config.verifyServiceSid}/${endpoint}`;
const auth = Buffer.from(`${this.config.accountSid}:${this.config.authToken}`).toString('base64');
return this.fetchFn(url, {
method: 'POST',
headers: {
Authorization: `Basic ${auth}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(body).toString(),
});
}
private async parseErrorBody(response: Response): Promise<TwilioErrorResponse | null> {
try {
return (await response.json()) as TwilioErrorResponse;
} catch {
return null;
}
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright (C) 2026 Fluxer Contributors
*
* This file is part of Fluxer.
*
* Fluxer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fluxer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
*/
import {SmsVerificationUnavailableError} from '@fluxer/errors/src/domains/auth/SmsVerificationUnavailableError';
import type {ISmsProvider} from '@fluxer/sms/src/providers/ISmsProvider';
export class UnavailableSmsProvider implements ISmsProvider {
async startVerification(_phone: string): Promise<void> {
return;
}
async checkVerification(_phone: string, _code: string): Promise<boolean> {
throw new SmsVerificationUnavailableError();
}
}