All files / src/services call-service.ts

100% Statements 39/39
100% Branches 4/4
100% Functions 11/11
100% Lines 39/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303                              2x                                                                                                                                                                                                                                                                               2x                           10x 10x 10x 10x 10x               2x 1x   1x     9x           9x 9x   2x       2x   8x 8x     11x   13x 13x 13x     5x                         5x     1x           1x               1x 1x             1x               1x 1x             1x                 1x 1x               1x     1x         1x         1x     1x 1x        
import { AnswerCallData } from '../models/answer-call-data';
import { CloseCallData } from '../models/close-call-data';
import { DialCallData } from '../models/dial-call-data';
import { IceCallData } from '../models/ice-call-data';
import { IceSource } from '../models/ice-source';
import { CallData } from '../models/infrasctructure/call-data';
import { CallMethodName } from '../models/infrasctructure/call-method-name';
import { CallRequest } from '../models/infrasctructure/call-request';
import { CallResponse } from '../models/infrasctructure/call-response';
import { OfferCallData } from '../models/offer-call-data';
import { UpdateCallData } from '../models/update-call-data';
import { ApiClient } from '../utils/api-client';
import { Base64 } from '../utils/base64';
import { Cryptography } from '../utils/cryptography';
import { Logger } from '../utils/logger';
import { newError } from '../utils/new-error';
import { Utf8 } from '../utils/utf8';
import { Subscription } from './push-service';
import { SessionService } from './session-service';
import { SignalRService } from './signalr-service';
import { TimeService } from './time-service';
 
/**
 * Configuration interface for the call service.
 * Defines properties needed for making API calls to the server.
 */
export type CallServiceConfig = {
    /**
     * URL of the server to send API calls to.
     * Used for HTTP and SignalR communication.
     */
    serverUrl?: string;
};
 
// Internal effective config for testability and browser API injection
// (not exported, just like PushServiceEffectiveConfig)
type CallServiceEffectiveConfig = CallServiceConfig & {
    navigator: Navigator;
};
 
/**
 * Service interface for making various types of signaling calls.
 * Provides methods for the WebRTC signaling process and connection management.
 */
export interface CallService {
    /**
     * Initializes the call service with the provided configuration.
     * Sets up the server URL for API calls.
     *
     * @param config - Configuration with server URL and optional browser API overrides
     */
    initialize(config: CallServiceEffectiveConfig): void;
 
    /**
     * Updates the server with the client's current status and subscription information.
     * Used to register the client for push notifications.
     *
     * @param publicKey - Public key of the client
     * @param subscription - Optional push notification subscription details
     * @returns Promise resolving to the server's response
     */
    update(publicKey: string, subscription?: Subscription): Promise<CallResponse>;
 
    /**
     * Initiates a dial request to a peer.
     * First step in establishing a WebRTC connection.
     *
     * @param publicKey - Public key of the sender
     * @param peerPublicKey - Public key of the peer to connect to
     * @param encryptionPublicKey - Public encryption key for secure communication
     * @returns Promise resolving to the server's response
     */
    dial(publicKey: string, peerPublicKey: string, encryptionPublicKey: string): Promise<CallResponse>;
 
    /**
     * Sends a WebRTC offer to a peer.
     * Contains the initial session description for establishing a connection.
     *
     * @param publicKey - Public key of the sender
     * @param peerPublicKey - Public key of the peer to connect to
     * @param encryptionPublicKey - Public encryption key for secure communication
     * @param encryptedData - Encrypted session description information
     * @returns Promise resolving to the server's response
     */
    offer(
        publicKey: string,
        peerPublicKey: string,
        encryptionPublicKey: string,
        encryptedData: Uint8Array,
    ): Promise<CallResponse>;
 
    /**
     * Sends a WebRTC answer to a peer.
     * Response to an offer with the local session description.
     *
     * @param publicKey - Public key of the sender
     * @param peerPublicKey - Public key of the peer to connect to
     * @param encryptionPublicKey - Public encryption key for secure communication
     * @param encryptedData - Encrypted session description information
     * @returns Promise resolving to the server's response
     */
    answer(
        publicKey: string,
        peerPublicKey: string,
        encryptionPublicKey: string,
        encryptedData: Uint8Array,
    ): Promise<CallResponse>;
 
    /**
     * Sends ICE (Interactive Connectivity Establishment) candidates to a peer.
     * Used to establish the optimal connection path between peers.
     *
     * @param publicKey - Public key of the sender
     * @param peerPublicKey - Public key of the peer to connect to
     * @param encryptionPublicKey - Public encryption key for secure communication
     * @param encryptedData - Encrypted ICE candidate information
     * @param source - Source of the ICE candidate (incoming or outgoing)
     * @returns Promise resolving to the server's response
     */
    ice(
        publicKey: string,
        peerPublicKey: string,
        encryptionPublicKey: string,
        encryptedData: Uint8Array,
        source: IceSource,
    ): Promise<CallResponse>;
 
    /**
     * Sends a close request to terminate a connection with a peer.
     * Uses the Beacon API for reliable delivery even during page unload.
     *
     * @param publicKey - Public key of the sender
     * @param peerPublicKey - Public key of the peer to disconnect from
     */
    close(publicKey: string, peerPublicKey: string): void;
}
 
/**
 * Factory function that creates and returns an implementation of the CallService interface.
 * Manages the signaling process for WebRTC connections.
 *
 * @param logger - Logger instance for error and debugging information
 * @param timeService - Service for managing time synchronization
 * @param sessionService - Service for accessing session information
 * @param apiClient - Client for making HTTP API calls
 * @param signalRService - Service for real-time SignalR communication
 * @param base64 - Utility for Base64 encoding/decoding
 * @param utf8 - Utility for UTF-8 encoding/decoding
 * @param cryptography - Cryptography service for signing operations
 * @returns An implementation of the CallService interface
 */
export function getCallService(
    logger: Logger,
    timeService: TimeService,
    sessionService: SessionService,
    apiClient: ApiClient,
    signalRService: SignalRService,
    base64: Base64,
    utf8: Utf8,
    cryptography: Cryptography,
): CallService {
    let serverUrl: string | undefined;
    let navigator: Navigator;
 
    function getBase64Signature(data: any): string {
        const dataString = JSON.stringify(data);
        const dataBytes = utf8.decode(dataString);
        const signatureSecretKey = sessionService.signingKeyPair.secretKey;
        const dataSignature = cryptography.sign(dataBytes, signatureSecretKey);
        return base64.encode(dataSignature);
    }
 
    async function signAndSend<TypeData extends CallData>(
        method: CallMethodName,
        data: TypeData,
    ): Promise<CallResponse> {
        async function sendViaApi<TypeData extends CallData>(request: CallRequest<TypeData>): Promise<CallResponse> {
            if (!serverUrl) {
                throw newError(logger, '[call-service] Server URL is missing.');
            }
            return await apiClient.call(serverUrl, request);
        }
 
        const request = {
            a: method,
            b: data,
            c: getBase64Signature(data),
        };
        let response: CallResponse;
        try {
            response = await signalRService.call(request);
        } catch (error) {
            logger.warn(
                `[call-service] Error while sending call '${request.a}' via signalR. Trying to use http API.`,
                error,
            );
            response = await sendViaApi<TypeData>(request);
        }
        timeService.serverTime = response.timestamp;
        return response;
    }
 
    return {
        initialize(config: CallServiceEffectiveConfig): void {
            serverUrl = config.serverUrl;
            navigator = config.navigator;
            logger.debug('[call-service] Initialized.');
        },
        async update(publicKey: string, subscription?: Subscription): Promise<CallResponse> {
            const data: UpdateCallData = {
                a: publicKey,
                b: !!subscription
                    ? {
                          a: subscription.endpoint,
                          b: subscription.expirationTime,
                          c: {
                              a: subscription.keys.p256dh,
                              b: subscription.keys.auth,
                          },
                      }
                    : undefined,
            };
            return await signAndSend<UpdateCallData>('update', data);
        },
        async dial(publicKey: string, peerPublicKey: string, encryptionPublicKeyBase64: string): Promise<CallResponse> {
            const data: DialCallData = {
                a: publicKey,
                b: timeService.serverTime,
                c: peerPublicKey,
                d: encryptionPublicKeyBase64,
            };
            return await signAndSend<DialCallData>('dial', data);
        },
        async offer(
            publicKey: string,
            peerPublicKey: string,
            encryptionPublicKeyBase64: string,
            encryptedData: Uint8Array,
        ): Promise<CallResponse> {
            const encryptedDataBase64 = base64.encode(encryptedData);
            const data: OfferCallData = {
                a: publicKey,
                b: timeService.serverTime,
                c: peerPublicKey,
                d: encryptionPublicKeyBase64,
                e: encryptedDataBase64,
            };
            return await signAndSend<OfferCallData>('offer', data);
        },
        async answer(
            publicKey: string,
            peerPublicKey: string,
            encryptionPublicKeyBase64: string,
            encryptedData: Uint8Array,
        ): Promise<CallResponse> {
            const encryptedDataBase64 = base64.encode(encryptedData);
            const data: AnswerCallData = {
                a: publicKey,
                b: timeService.serverTime,
                c: peerPublicKey,
                d: encryptionPublicKeyBase64,
                e: encryptedDataBase64,
            };
            return await signAndSend<AnswerCallData>('answer', data);
        },
        async ice(
            publicKey: string,
            peerPublicKey: string,
            encryptionPublicKeyBase64: string,
            encryptedData: Uint8Array,
            source: IceSource,
        ): Promise<CallResponse> {
            const encryptedDataBase64 = base64.encode(encryptedData);
            const data: IceCallData = {
                a: publicKey,
                b: timeService.serverTime,
                c: peerPublicKey,
                d: encryptionPublicKeyBase64,
                e: encryptedDataBase64,
                f: source,
            };
            return await signAndSend<IceCallData>('ice', data);
        },
        close(publicKey: string, peerPublicKey: string): void {
            const data: CloseCallData = {
                a: publicKey,
                b: timeService.serverTime,
                c: peerPublicKey,
            };
            const request: CallRequest<CloseCallData> = {
                a: 'close',
                b: data,
                c: getBase64Signature(data),
            };
            const headers = {
                type: 'application/json',
            };
            const blob = new Blob([JSON.stringify(request)], headers);
            navigator.sendBeacon(`${serverUrl}/api/v1/call`, blob);
        },
    };
}