All files / backend/helpers/gigachat canaryToken.ts

100% Statements 34/34
100% Branches 18/18
100% Functions 3/3
100% Lines 33/33

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                                                            1x         12x 5x     7x 7x   7x 1x       6x   3x 3x 37x         6x 6x 1x           5x 5x 5x 47x 47x 47x     5x     1x 3x         3x 2x 2x       3x     1x 5x         5x 3x 3x       5x    
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
/**
 * Преобразует 8-значный цифровой код в строку из N символов с использованием заданного пула символов.
 *
 * @param {string} originalCode - 8-символьная строка цифр
 * @param {string} symbolPool - строка с символами для кодирования (например, длинной 100)
 * @param {string} [N] - длина выходной строки (если не задан, вычисляется автоматически)
 *
 * @returns {string} Строка из N символов из заданного пула
 *
 * @throws {Error} Ошибка при формировании токена
 *
 * @example
 * generateCanaryToken("01234567", "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", 4) => "EUor"
 */
export const generateCanaryToken = (
  originalCode: string,
  symbolPool: string,
  N?: number
) => {
  if (!originalCode || !/^\d{8}$/.test(originalCode)) {
    throw new Error('КЭ AI -агента не задан или содержит ошибку');
  }
 
  const number = parseInt(originalCode, 10);
  const base = symbolPool.trim().length;
 
  if (base === 0) {
    throw new Error('Не задан пул символов для формирования токенов'); //
  }
 
  // Если И не задан, вычисляем минимальную необходимую длинну
  if (N === undefined) {
    // Вычисляем минимальное N, при котором base^N >= 10^8
    N = 1;
    while (base ** N < 10 ** 8) {
      N += 1;
    }
  }
 
  // Проверяем, что число в допустимом диапазоне
  const maxValue = base ** N - 1;
  if (number > maxValue) {
    throw new Error(
      `Число ${number} превышает максимальное значение ${maxValue} для ${N} символов с пулом из ${base} символов`
    );
  }
 
  // Преобразуем в систему счисления с оснванием base
  const result = [];
  let n = number;
  for (let i = 0; i < N; i++) {
    const remainder = n % base;
    n = Math.floor(n / base);
    result.push(symbolPool[remainder]);
  }
 
  return result.reverse().join('');
};
 
export const validateCannaryTokenSymbolsPool = (tokenPool: any) => {
  const result = {
    success: true,
    error: null
  };
 
  if (!(typeof tokenPool === 'string' && tokenPool.trim().length > 0)) {
    result.success = false;
    result.error =
      'Переменная "VUE_APP_GIGACHAT_CANARY_TOKEN_POOL" должна содержать строку с символами.';
  }
 
  return result;
};
 
export const validateGigachatAgentCI = (ci: any) => {
  const result = {
    success: true,
    error: null
  };
 
  if (!(typeof ci === 'string' && /^\d{8}$/.test(ci.slice(-8)))) {
    result.success = false;
    result.error =
      'Переменная "VUE_APP_GIGACHAT_AGENT_CI" должна содержать строку с CI (КЭ) AI-агента (GigaChat) c цифровым идентификатором из 8 цифр (Пример - CI12345678).';
  }
 
  return result;
};