SHA256
Добавить лицензию CC0 1.0
This commit is contained in:
@@ -19,6 +19,7 @@ import {
|
||||
computeTorrentV2InfoHash,
|
||||
computeTorrentV2PieceRoot,
|
||||
} from './torrent-v2-service.js';
|
||||
import { resolveUserFileUrl, updatedUserFileUrlAfterError } from './user-file-server-service.js';
|
||||
|
||||
export const DM_FILE_CHUNK_BYTES = 8 * 1024 * 1024;
|
||||
const LEGACY_DM_FILE_CHUNK_BYTES = TORRENT_V2_PIECE_BYTES;
|
||||
@@ -29,7 +30,6 @@ const MANIFEST_VERSION = 2;
|
||||
const MANIFEST_SCHEME = 'SHINE-DM-CHUNKED-AES-256-GCM';
|
||||
const R2_MANIFEST_VERSION = 3;
|
||||
const R2_MANIFEST_SCHEME = 'SHINE-DM-R2-AES-256-GCM';
|
||||
const DM_R2_PUBLIC_BASE = 'https://dm-files.shineup.me';
|
||||
const DM_R2_OBJECT_MAX_BYTES = DM_FILE_CHUNK_BYTES + 16;
|
||||
const DM_R2_FILE_MAX_BYTES = 500 * 1024 * 1024;
|
||||
const ROOT_IV_TOKEN = 0xffffffffffffffffn;
|
||||
@@ -79,7 +79,7 @@ async function readErrorMessage(response) {
|
||||
function objectUrl(serverBase, id) {
|
||||
const base = String(serverBase || '').replace(/\/$/, '');
|
||||
// Старые вложения читаем с access-сервера, новые — с отдельного домена R2.
|
||||
const path = new URL(base).hostname === 'dm-files.shineup.me' ? '' : '/dm-files';
|
||||
const path = new URL(base).hostname.startsWith('dm-files.') ? '' : '/dm-files';
|
||||
return `${base}${path}/${encodeURIComponent(String(id || ''))}`;
|
||||
}
|
||||
|
||||
@@ -175,7 +175,13 @@ async function uploadEncryptedObject(bytes, context) {
|
||||
throw new Error(detail || `R2 DM prepare: HTTP ${prepare.status}`);
|
||||
}
|
||||
const answer = await prepare.json();
|
||||
const url = `${DM_R2_PUBLIC_BASE}/${fileId}`;
|
||||
// Сервер prepare — владелец R2, ссылка нужна лишь для HEAD проверки 412.
|
||||
const url = String(answer.fileUrl || '').trim();
|
||||
const fileUrl = new URL(url);
|
||||
if (fileUrl.protocol !== 'https:' || fileUrl.username || fileUrl.password || fileUrl.search
|
||||
|| fileUrl.hash || !fileUrl.pathname.endsWith(`/${fileId}`)) {
|
||||
throw new Error('Сервер вернул некорректный адрес R2');
|
||||
}
|
||||
if (!answer.exists) {
|
||||
if (!answer.uploadUrl || !answer.requiredHeaders) throw new Error('Сервер не вернул параметры загрузки R2');
|
||||
let result;
|
||||
@@ -203,7 +209,7 @@ async function uploadEncryptedObject(bytes, context) {
|
||||
async function fetchVerifiedObject(url, expectedId) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, { method: 'GET' });
|
||||
response = await fetch(url, { method: 'GET', credentials: 'omit', referrerPolicy: 'no-referrer' });
|
||||
} catch (error) {
|
||||
throw new Error(`Не удалось скачать зашифрованные данные: ${error?.message || 'network error'}`);
|
||||
}
|
||||
@@ -297,6 +303,7 @@ export async function encryptAndUploadDmFile({
|
||||
chunkSize: DM_FILE_CHUNK_BYTES, chunkCount,
|
||||
kind: String(kind || 'file') === 'voice' ? 'voice' : 'file',
|
||||
durationMs: Math.max(0, Math.floor(Number(durationMs || 0))),
|
||||
uploadedAtMs: Date.now(),
|
||||
};
|
||||
} finally {
|
||||
manifestBytes.fill(0);
|
||||
@@ -310,10 +317,52 @@ export async function encryptAndUploadDmFile({
|
||||
}
|
||||
}
|
||||
|
||||
/** Получение зашифрованного манифеста v3 без BitTorrent-метаданных. */
|
||||
export const DM_FILE_RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export function isDmFileExpired(attachment, messageTimestampMs = 0) {
|
||||
// v1/v2: legacy-хранилище не имеет 14-дневного R2 lifecycle.
|
||||
if (Number(attachment?.version || 1) < 3) return false;
|
||||
const timestamp = Number(attachment?.uploadedAtMs || attachment?.messageTimestampMs || messageTimestampMs || 0);
|
||||
return Number.isFinite(timestamp) && timestamp > 0 && Date.now() - timestamp >= DM_FILE_RETENTION_MS;
|
||||
}
|
||||
|
||||
function assertDmFileNotExpired(attachment) {
|
||||
if (isDmFileExpired(attachment)) throw new Error('DM_FILE_EXPIRED');
|
||||
}
|
||||
|
||||
function v3ObjectUrl(base, id) {
|
||||
return `${String(base || '').replace(/\/$/, '')}/${encodeURIComponent(String(id || ''))}`;
|
||||
}
|
||||
|
||||
async function v3RootUrl(attachment) {
|
||||
// Для исторических v3 URL оставляем как источник; новый v3 содержит только hash/id.
|
||||
if (attachment?.url) return String(attachment.url);
|
||||
if (!attachment?.senderLogin) throw new Error('Неизвестен отправитель DM-файла');
|
||||
return resolveUserFileUrl({ login: attachment.senderLogin, id: attachment.id, kind: 'dm' });
|
||||
}
|
||||
|
||||
async function fetchV3ObjectWithRefresh(url, id, attachment) {
|
||||
try {
|
||||
return { bytes: await fetchVerifiedObject(url, id), url };
|
||||
} catch (error) {
|
||||
if (!attachment?.senderLogin || String(error?.message || '').includes('SHA-256')) throw error;
|
||||
let updated;
|
||||
try {
|
||||
updated = await updatedUserFileUrlAfterError({
|
||||
login: attachment.senderLogin, id, kind: 'dm', previousUrl: url,
|
||||
});
|
||||
} catch { throw error; }
|
||||
if (!updated) throw error;
|
||||
return { bytes: await fetchVerifiedObject(updated, id), url: updated };
|
||||
}
|
||||
}
|
||||
|
||||
/** Получение зашифрованного манифеста v3 без BitTorrent-метаданных. */
|
||||
async function loadV3RootManifest(attachment) {
|
||||
const id = String(attachment?.id || '').trim();
|
||||
const url = String(attachment?.url || '').trim();
|
||||
assertDmFileNotExpired(attachment);
|
||||
const url = await v3RootUrl(attachment);
|
||||
const key = base64UrlToBytes(String(attachment?.keyB64Url || ''));
|
||||
const ivPrefix = base64UrlToBytes(String(attachment?.ivPrefixB64Url || ''));
|
||||
if (!id || !url || key.byteLength !== 32 || ivPrefix.byteLength !== 4) {
|
||||
@@ -325,7 +374,8 @@ async function loadV3RootManifest(attachment) {
|
||||
const iv = rootIv(ivPrefix);
|
||||
const aad = rootAad(ivPrefix);
|
||||
try {
|
||||
encrypted = await fetchVerifiedObject(url, id);
|
||||
const found = await fetchV3ObjectWithRefresh(url, id, attachment);
|
||||
encrypted = found.bytes;
|
||||
plain = await decryptBytesAesGcm(encrypted, key, iv, aad);
|
||||
const manifest = decodeJson(plain);
|
||||
const size = Number(manifest?.fileSize);
|
||||
@@ -346,7 +396,7 @@ async function loadV3RootManifest(attachment) {
|
||||
throw new Error('Повреждены ссылки на части файла');
|
||||
}
|
||||
}
|
||||
return { manifest, key, ivPrefix, serverBase: objectBaseFromUrl(url) };
|
||||
return { manifest, key, ivPrefix, serverBase: objectBaseFromUrl(found.url) };
|
||||
} catch (error) {
|
||||
key.fill(0); ivPrefix.fill(0);
|
||||
throw error;
|
||||
@@ -363,7 +413,9 @@ async function decryptV3ToSink(attachment, sink, { onProgress = null } = {}) {
|
||||
let processedBytes = 0;
|
||||
try {
|
||||
for (const item of context.manifest.chunks) {
|
||||
const encrypted = await fetchVerifiedObject(objectUrl(context.serverBase, item.id), item.id);
|
||||
const found = await fetchV3ObjectWithRefresh(v3ObjectUrl(context.serverBase, item.id), item.id, attachment);
|
||||
const encrypted = found.bytes;
|
||||
context.serverBase = objectBaseFromUrl(found.url);
|
||||
const iv = chunkIv(context.ivPrefix, item.i);
|
||||
const aad = chunkAad(context.ivPrefix, item.i);
|
||||
let plain = null;
|
||||
@@ -625,6 +677,7 @@ function saveBlob(blob, name) {
|
||||
}
|
||||
|
||||
export async function decryptDmFileToBlob(attachment = {}, options = {}) {
|
||||
assertDmFileNotExpired(attachment);
|
||||
if (Number(attachment?.version || 1) < 2) {
|
||||
const plain = await downloadV1(attachment);
|
||||
const blob = new Blob([plain], { type: String(attachment?.mime || 'application/octet-stream') });
|
||||
@@ -639,6 +692,7 @@ export async function decryptDmFileToBlob(attachment = {}, options = {}) {
|
||||
}
|
||||
|
||||
export async function downloadAndDecryptDmFile(attachment = {}, { onProgress = null } = {}) {
|
||||
assertDmFileNotExpired(attachment);
|
||||
if (Number(attachment?.version || 1) < 2) {
|
||||
const plain = await downloadV1(attachment);
|
||||
const blob = new Blob([plain], { type: String(attachment?.mime || 'application/octet-stream') });
|
||||
|
||||
Reference in New Issue
Block a user