signal-desktop/ts/util/validateConversation.ts

66 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-07-12 20:37:21 -04:00
// Copyright 2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import type { ValidateConversationType } from '../model-types.d';
import {
isDirectConversation,
isGroupV1,
isGroupV2,
} from './whatTypeOfConversation';
import { isServiceIdString } from '../types/ServiceId';
2022-07-12 20:37:21 -04:00
export function validateConversation(
attributes: ValidateConversationType
): string | null {
if (attributes.type !== 'private' && attributes.type !== 'group') {
return `Invalid conversation type: ${attributes.type}`;
}
2023-08-16 22:54:39 +02:00
if (!attributes.e164 && !attributes.serviceId && !attributes.groupId) {
return 'Missing one of e164, serviceId, or groupId';
2022-07-12 20:37:21 -04:00
}
const error = validateNumber(attributes) || validateServiceId(attributes);
2022-07-12 20:37:21 -04:00
if (error) {
return error;
}
if (
!isDirectConversation(attributes) &&
!isGroupV1(attributes) &&
!isGroupV2(attributes)
) {
return 'Conversation is not direct, groupv1 or groupv2';
}
2022-07-12 20:37:21 -04:00
return null;
}
function validateNumber(attributes: ValidateConversationType): string | null {
const { e164 } = attributes;
if (isDirectConversation(attributes) && e164) {
if (!/^\+[1-9][0-9]{0,18}$/.test(e164)) {
return 'Invalid E164';
2022-07-12 20:37:21 -04:00
}
return null;
2022-07-12 20:37:21 -04:00
}
return null;
}
function validateServiceId(
attributes: ValidateConversationType
): string | null {
2023-08-16 22:54:39 +02:00
if (isDirectConversation(attributes) && attributes.serviceId) {
if (isServiceIdString(attributes.serviceId)) {
2022-07-12 20:37:21 -04:00
return null;
}
return 'Invalid ServiceId';
2022-07-12 20:37:21 -04:00
}
return null;
}