SHA256
239 lines
9.5 KiB
JavaScript
239 lines
9.5 KiB
JavaScript
import { t } from '../i18n/index.js';
|
|
import { preparePublicFile, R2_MAX_FILE_BYTES } from './file-preparation-service.js';
|
|
import { importPkcs8Ed25519, signBase64 } from './crypto-utils.js';
|
|
import { sha256HexFromArrayBuffer, validateSha256Hex } from './arweave-file-service.js';
|
|
import { loadSessionMaterial } from './key-vault.js';
|
|
import {
|
|
DEFAULT_SHINE_SERVER_HTTP,
|
|
resolveShineServerForUserLogin,
|
|
} from './shine-server-resolver.js';
|
|
import { state } from '../state.js';
|
|
|
|
const ACCESS_SERVER_CACHE_TTL_MS = 60_000;
|
|
const accessServerCache = new Map();
|
|
|
|
async function publicFileExists(url) {
|
|
try {
|
|
const response = await fetch(url, { method: 'HEAD', cache: 'no-store' });
|
|
return response.ok;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function wsUrlToHttpBase(wsUrl = '') {
|
|
const parsed = new URL(String(wsUrl || ''), window.location.href);
|
|
if (parsed.protocol === 'wss:') parsed.protocol = 'https:';
|
|
else if (parsed.protocol === 'ws:') parsed.protocol = 'http:';
|
|
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
throw new Error(t('remaining.file_errors.could_not_determine_the_access_server_http_address'));
|
|
}
|
|
return parsed.origin;
|
|
}
|
|
|
|
function publicFileUrl(serverBase, sha256) {
|
|
const cleanSha = String(sha256 || '').trim().toLowerCase();
|
|
if (!validateSha256Hex(cleanSha)) throw new Error(t('remaining.file_errors.invalid_file_sha_256'));
|
|
return `${String(serverBase || '').replace(/\/$/, '')}/files/${cleanSha}`;
|
|
}
|
|
|
|
function uploadPreimage({ sessionId, sha256, size, timeMs }) {
|
|
return `PUBLIC_FILE_UPLOAD_V1:${sessionId}:${sha256}:${Number(size)}:${Number(timeMs)}`;
|
|
}
|
|
|
|
async function readErrorMessage(response) {
|
|
try {
|
|
const raw = String(await response.text()).trim();
|
|
if (!raw) return '';
|
|
try {
|
|
const payload = JSON.parse(raw);
|
|
return String(payload?.message || payload?.error || raw).trim();
|
|
} catch {
|
|
return raw;
|
|
}
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
async function createUploadContext({ login, sessionId, wsUrl }) {
|
|
const cleanLogin = String(login || '').trim();
|
|
const cleanSessionId = String(sessionId || '').trim();
|
|
if (!cleanLogin || !cleanSessionId) throw new Error(t('remaining.file_errors.no_active_user_session'));
|
|
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
|
if (!sessionMaterial?.sessionPrivPkcs8) {
|
|
throw new Error(t('remaining.file_errors.session_key_for_uploading_files_is_missing_on_this_dev'));
|
|
}
|
|
if (sessionMaterial.sessionId && String(sessionMaterial.sessionId) !== cleanSessionId) {
|
|
throw new Error(t('remaining.file_errors.saved_session_key_belongs_to_a_different_session'));
|
|
}
|
|
return {
|
|
sessionId: cleanSessionId,
|
|
serverBase: wsUrlToHttpBase(wsUrl),
|
|
privateKey: await importPkcs8Ed25519(sessionMaterial.sessionPrivPkcs8),
|
|
};
|
|
}
|
|
|
|
export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus = null, purpose = 'attachment' } = {}) {
|
|
if (purpose !== 'avatar') return uploadR2PublicFile({ file, login, sessionId, wsUrl, onStatus });
|
|
if (!(file instanceof File)) throw new Error(t('remaining.file_upload.no_file_selected'));
|
|
if (Number(file.size || 0) <= 0) throw new Error(t('remaining.file_upload.cannot_upload_an_empty_file'));
|
|
|
|
onStatus?.(t('remaining.file_upload.calculating_sha_256'));
|
|
const bytes = await file.arrayBuffer();
|
|
const sha256 = await sha256HexFromArrayBuffer(bytes);
|
|
const context = await createUploadContext({ login, sessionId, wsUrl });
|
|
const url = publicFileUrl(context.serverBase, sha256);
|
|
|
|
onStatus?.(t('remaining.file_upload.checking_whether_the_file_is_on_the_server'));
|
|
try {
|
|
const existing = await fetch(url, { method: 'HEAD', cache: 'no-store' });
|
|
if (existing.ok) {
|
|
const storedSize = Number(existing.headers.get('Content-Length') || -1);
|
|
if (storedSize < 0 || storedSize === file.size) {
|
|
return {
|
|
v: 1,
|
|
name: String(file.name || 'file'),
|
|
size: Number(file.size),
|
|
sha256,
|
|
ar: '',
|
|
uploadedAtMs: Date.now(),
|
|
alreadyExists: true,
|
|
};
|
|
}
|
|
}
|
|
} catch {
|
|
// HEAD — только оптимизация. PUT сам проверит hash и дедупликацию.
|
|
}
|
|
|
|
const timeMs = Date.now();
|
|
const signature = await signBase64(context.privateKey, uploadPreimage({
|
|
sessionId: context.sessionId,
|
|
sha256,
|
|
size: file.size,
|
|
timeMs,
|
|
}));
|
|
|
|
onStatus?.(t('remaining.file_upload.uploading_to_access_server'));
|
|
let response;
|
|
try {
|
|
response = await fetch(url, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/octet-stream',
|
|
'X-Shine-Session-Id': context.sessionId,
|
|
'X-Shine-Time-Ms': String(timeMs),
|
|
'X-Shine-Content-Length': String(file.size),
|
|
'X-Shine-Signature': signature,
|
|
},
|
|
body: bytes,
|
|
cache: 'no-store',
|
|
});
|
|
} catch (error) {
|
|
throw new Error(`Не удалось загрузить файл на сервер доступа: ${error?.message || 'network error'}`);
|
|
}
|
|
if (!response.ok) {
|
|
const detail = await readErrorMessage(response);
|
|
throw new Error(detail || `Сервер отклонил файл (HTTP ${response.status}).`);
|
|
}
|
|
|
|
let alreadyExists = false;
|
|
try {
|
|
const payload = await response.clone().json();
|
|
alreadyExists = Boolean(payload?.alreadyExists);
|
|
} catch {
|
|
// Успешного HTTP достаточно.
|
|
}
|
|
|
|
return {
|
|
v: 1,
|
|
name: String(file.name || 'file'),
|
|
size: Number(file.size),
|
|
sha256,
|
|
ar: '',
|
|
uploadedAtMs: Date.now(),
|
|
alreadyExists,
|
|
};
|
|
}
|
|
|
|
export async function resolvePublicFileUrl({
|
|
pr,
|
|
sha256,
|
|
authorLogin,
|
|
solanaEndpoint,
|
|
fallbackServerLogin = '',
|
|
} = {}) {
|
|
if (pr) return publicR2Url(pr);
|
|
// Сначала – сервер, к которому подключены сейчас (у большинства читателей он же сервер автора),
|
|
// затем сервер сборки по умолчанию; только потом ищем сервер автора через его PDA.
|
|
const nearbyBases = [...new Set([state.entrySettings?.shineServerHttp, DEFAULT_SHINE_SERVER_HTTP]
|
|
.map((base) => String(base || '').trim().replace(/\/$/, ''))
|
|
.filter(Boolean))];
|
|
for (const base of nearbyBases) {
|
|
const url = publicFileUrl(base, sha256);
|
|
if (await publicFileExists(url)) return url;
|
|
}
|
|
|
|
const cleanLogin = String(authorLogin || '').trim().toLowerCase();
|
|
if (!cleanLogin) throw new Error(t('remaining.file_errors.server_attachment_author_is_missing'));
|
|
const cacheKey = `${cleanLogin}|${String(solanaEndpoint || '').trim()}|${String(fallbackServerLogin || '').trim().toLowerCase()}`;
|
|
const cached = accessServerCache.get(cacheKey);
|
|
if (cached && Date.now() - cached.atMs < ACCESS_SERVER_CACHE_TTL_MS) {
|
|
return publicFileUrl(cached.httpBase, sha256);
|
|
}
|
|
const resolved = await resolveShineServerForUserLogin({
|
|
login: cleanLogin,
|
|
solanaEndpoint,
|
|
fallbackServerLogin,
|
|
});
|
|
accessServerCache.set(cacheKey, { atMs: Date.now(), httpBase: resolved.httpBase });
|
|
return publicFileUrl(resolved.httpBase, sha256);
|
|
}
|
|
|
|
/** Uploads one public attachment directly from the browser to Cloudflare R2. */
|
|
async function uploadR2PublicFile({ file, login, sessionId, wsUrl, onStatus }) {
|
|
if (!(file instanceof File) || file.size < 1) throw new Error('Выберите непустой файл');
|
|
if (file.size > R2_MAX_FILE_BYTES) throw new Error('Превышен лимит 500 МиБ');
|
|
onStatus?.('Подготовка файла…');
|
|
const prepared = await preparePublicFile(file);
|
|
const context = await createUploadContext({ login, sessionId, wsUrl });
|
|
const timeMs = Date.now();
|
|
const preimage = `PUBLIC_R2_PREPARE_V1:${context.sessionId}:${prepared.pr}:${prepared.size}:${prepared.mm}:${timeMs}`;
|
|
const signature = await signBase64(context.privateKey, preimage);
|
|
onStatus?.('Проверка файла в R2…');
|
|
const response = await fetch(`${context.serverBase}/api/files/prepare`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-Shine-Session-Id': context.sessionId,
|
|
'X-Shine-Time-Ms': String(timeMs),
|
|
'X-Shine-Signature': signature,
|
|
},
|
|
body: JSON.stringify({ pr: prepared.pr, size: prepared.size, mm: prepared.mm }),
|
|
});
|
|
if (!response.ok) throw new Error((await readErrorMessage(response)) || `R2 prepare HTTP ${response.status}`);
|
|
const payload = await response.json();
|
|
if (!payload.exists) {
|
|
if (!payload.uploadUrl) throw new Error('Сервер не предоставил адрес загрузки');
|
|
onStatus?.('Загрузка в Cloudflare R2…');
|
|
const put = await fetch(payload.uploadUrl, {
|
|
method: 'PUT',
|
|
headers: payload.requiredHeaders || { 'Content-Type': prepared.mm, 'If-None-Match': '*' },
|
|
body: file,
|
|
});
|
|
if (!put.ok && put.status !== 412) throw new Error(`Cloudflare R2: HTTP ${put.status}`);
|
|
if (put.status === 412) {
|
|
const check = await fetch(payload.fileUrl, { method: 'HEAD', cache: 'no-store' });
|
|
if (!check.ok || Number(check.headers.get('Content-Length')) !== file.size) throw new Error('Конфликт при загрузке объекта R2');
|
|
}
|
|
}
|
|
return { v: 1, name: prepared.name, size: prepared.size, pr: prepared.pr, mm: prepared.mm,
|
|
ar: '', uploadedAtMs: Date.now(), alreadyExists: Boolean(payload.exists) };
|
|
}
|
|
|
|
export function publicR2Url(pr) {
|
|
const root = String(pr || '').trim();
|
|
if (!/^[A-Za-z0-9_-]{43}$/.test(root)) throw new Error('Некорректный Pieces Root');
|
|
return `https://files.shineup.me/${root}`;
|
|
}
|