SHA256
198 lines
7.5 KiB
JavaScript
198 lines
7.5 KiB
JavaScript
import { t } from '../i18n/index.js';
|
||
import {
|
||
decryptJsonWithStoragePwd,
|
||
encryptJsonWithStoragePwd,
|
||
} from './crypto-utils.js';
|
||
|
||
const DB_NAME = 'shine-ui-auth';
|
||
const DB_VERSION = 1;
|
||
const STORE_SECRETS = 'encrypted-secrets';
|
||
const STORE_SESSIONS = 'session-keys';
|
||
const FALLBACK_SECRETS_KEY = 'shine-ui-auth-secrets-fallback-v1';
|
||
const FALLBACK_SESSIONS_KEY = 'shine-ui-auth-sessions-fallback-v1';
|
||
|
||
// Некоторые браузеры/расширения временно ломают IndexedDB и возвращают
|
||
// только «UnknownError: Internal error». В памяти держим только текущие
|
||
// значения, а в localStorage — те же зашифрованные secrets и session material,
|
||
// которые раньше хранились в IndexedDB.
|
||
const memorySecrets = new Map();
|
||
const memorySessions = new Map();
|
||
|
||
function normalizeLoginStorageKey(login) {
|
||
return String(login || '').trim().toLowerCase();
|
||
}
|
||
|
||
function readFallbackRow(storageKey, login) {
|
||
try {
|
||
if (typeof localStorage === 'undefined') return null;
|
||
const rows = JSON.parse(localStorage.getItem(storageKey) || '{}');
|
||
return rows?.[normalizeLoginStorageKey(login)] || null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function writeFallbackRow(storageKey, login, row) {
|
||
try {
|
||
if (typeof localStorage === 'undefined') return;
|
||
const rows = JSON.parse(localStorage.getItem(storageKey) || '{}');
|
||
rows[normalizeLoginStorageKey(login)] = row;
|
||
localStorage.setItem(storageKey, JSON.stringify(rows));
|
||
} catch {
|
||
// Память остаётся последним fallback для текущей вкладки.
|
||
}
|
||
}
|
||
|
||
function deleteFallbackRows(storageKey) {
|
||
try { localStorage?.removeItem(storageKey); } catch {}
|
||
}
|
||
|
||
function sanitizePersistentSecrets(keys) {
|
||
const source = keys && typeof keys === 'object' ? keys : {};
|
||
const safe = { ...source };
|
||
// Recovery/root private key is intentionally ephemeral: it may exist in RAM
|
||
// during a protected operation, but must never be persisted on the device.
|
||
delete safe.rootKey;
|
||
return safe;
|
||
}
|
||
|
||
function openDb() {
|
||
return new Promise((resolve, reject) => {
|
||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||
request.onupgradeneeded = () => {
|
||
const db = request.result;
|
||
if (!db.objectStoreNames.contains(STORE_SECRETS)) {
|
||
db.createObjectStore(STORE_SECRETS, { keyPath: 'login' });
|
||
}
|
||
if (!db.objectStoreNames.contains(STORE_SESSIONS)) {
|
||
db.createObjectStore(STORE_SESSIONS, { keyPath: 'login' });
|
||
}
|
||
};
|
||
request.onsuccess = () => resolve(request.result);
|
||
request.onerror = () => reject(request.error || new Error(t('remaining.key_storage.indexeddb_is_unavailable')));
|
||
});
|
||
}
|
||
|
||
async function put(storeName, value) {
|
||
const db = await openDb();
|
||
await new Promise((resolve, reject) => {
|
||
const tx = db.transaction(storeName, 'readwrite');
|
||
tx.objectStore(storeName).put(value);
|
||
tx.oncomplete = () => resolve();
|
||
tx.onerror = () => reject(tx.error || new Error(t('remaining.key_storage.could_not_write_to_indexeddb')));
|
||
});
|
||
db.close();
|
||
}
|
||
|
||
async function get(storeName, key) {
|
||
const db = await openDb();
|
||
const result = await new Promise((resolve, reject) => {
|
||
const tx = db.transaction(storeName, 'readonly');
|
||
const req = tx.objectStore(storeName).get(key);
|
||
req.onsuccess = () => resolve(req.result || null);
|
||
req.onerror = () => reject(req.error || new Error(t('remaining.key_storage.could_not_read_from_indexeddb')));
|
||
});
|
||
db.close();
|
||
return result;
|
||
}
|
||
|
||
export async function saveEncryptedUserSecrets(login, storagePwd, keys) {
|
||
const safeKeys = sanitizePersistentSecrets(keys);
|
||
const encrypted = await encryptJsonWithStoragePwd(safeKeys, storagePwd);
|
||
const normalizedLogin = normalizeLoginStorageKey(login);
|
||
const row = {
|
||
login: normalizedLogin,
|
||
encrypted,
|
||
updatedAtMs: Date.now(),
|
||
};
|
||
memorySecrets.set(normalizedLogin, row);
|
||
try {
|
||
await put(STORE_SECRETS, row);
|
||
} catch {
|
||
writeFallbackRow(FALLBACK_SECRETS_KEY, normalizedLogin, row);
|
||
}
|
||
}
|
||
|
||
export async function loadEncryptedUserSecrets(login, storagePwd) {
|
||
const normalizedLogin = normalizeLoginStorageKey(login);
|
||
let row = null;
|
||
try { row = await get(STORE_SECRETS, normalizedLogin); } catch {}
|
||
row = row || memorySecrets.get(normalizedLogin) || readFallbackRow(FALLBACK_SECRETS_KEY, normalizedLogin);
|
||
if (!row?.encrypted && normalizedLogin !== String(login || '').trim()) {
|
||
try { row = await get(STORE_SECRETS, String(login || '').trim()); } catch {}
|
||
}
|
||
if (!row?.encrypted) {
|
||
throw new Error('На устройстве нет сохранённых ключей для этого логина');
|
||
}
|
||
|
||
const decrypted = await decryptJsonWithStoragePwd(row.encrypted, storagePwd);
|
||
const safe = sanitizePersistentSecrets(decrypted);
|
||
|
||
// Одноразовая очистка контейнеров, созданных старыми версиями UI, где rootKey
|
||
// мог быть сохранён. Перезаписываем тем же storagePwd уже без Recovery private key.
|
||
if (decrypted && typeof decrypted === 'object' && Object.prototype.hasOwnProperty.call(decrypted, 'rootKey')) {
|
||
const encrypted = await encryptJsonWithStoragePwd(safe, storagePwd);
|
||
const cleanedRow = {
|
||
login: normalizedLogin,
|
||
encrypted,
|
||
updatedAtMs: Date.now(),
|
||
};
|
||
memorySecrets.set(normalizedLogin, cleanedRow);
|
||
try { await put(STORE_SECRETS, cleanedRow); } catch { writeFallbackRow(FALLBACK_SECRETS_KEY, normalizedLogin, cleanedRow); }
|
||
}
|
||
|
||
return safe;
|
||
}
|
||
|
||
export async function updateEncryptedUserSecrets(login, storagePwd, updater) {
|
||
if (typeof updater !== 'function') {
|
||
throw new Error('updateEncryptedUserSecrets: updater должен быть функцией');
|
||
}
|
||
|
||
const current = await loadEncryptedUserSecrets(login, storagePwd);
|
||
const next = await updater(current);
|
||
if (!next || typeof next !== 'object') {
|
||
throw new Error('updateEncryptedUserSecrets: updater должен вернуть объект secrets');
|
||
}
|
||
const safe = sanitizePersistentSecrets(next);
|
||
await saveEncryptedUserSecrets(login, storagePwd, safe);
|
||
return safe;
|
||
}
|
||
|
||
export async function saveSessionMaterial(login, material) {
|
||
const normalizedLogin = normalizeLoginStorageKey(login);
|
||
const row = {
|
||
login: normalizedLogin,
|
||
...material,
|
||
updatedAtMs: Date.now(),
|
||
};
|
||
memorySessions.set(normalizedLogin, row);
|
||
try {
|
||
await put(STORE_SESSIONS, row);
|
||
} catch {
|
||
writeFallbackRow(FALLBACK_SESSIONS_KEY, normalizedLogin, row);
|
||
}
|
||
}
|
||
|
||
export async function loadSessionMaterial(login) {
|
||
const normalizedLogin = normalizeLoginStorageKey(login);
|
||
let row = null;
|
||
try { row = await get(STORE_SESSIONS, normalizedLogin); } catch {}
|
||
row = row || memorySessions.get(normalizedLogin) || readFallbackRow(FALLBACK_SESSIONS_KEY, normalizedLogin);
|
||
if (row || normalizedLogin === String(login || '').trim()) return row;
|
||
try { return await get(STORE_SESSIONS, String(login || '').trim()); } catch { return null; }
|
||
}
|
||
|
||
export async function clearClientAuthData() {
|
||
memorySecrets.clear();
|
||
memorySessions.clear();
|
||
deleteFallbackRows(FALLBACK_SECRETS_KEY);
|
||
deleteFallbackRows(FALLBACK_SESSIONS_KEY);
|
||
await new Promise((resolve, reject) => {
|
||
const request = indexedDB.deleteDatabase(DB_NAME);
|
||
request.onsuccess = () => resolve();
|
||
request.onerror = () => reject(request.error || new Error('Не удалось очистить IndexedDB'));
|
||
request.onblocked = () => reject(new Error('Очистка IndexedDB заблокирована открытыми соединениями'));
|
||
});
|
||
}
|