SHA256
CORE/CONTENT test5593 и адаптация UI
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { preparePublicFile, R2_MAX_FILE_BYTES } from './file-preparation-service.js';
|
||||
import { validatePublicPiecesRoot } from './public-pieces-root.js';
|
||||
import { importPkcs8Ed25519, signBase64 } from './crypto-utils.js';
|
||||
import { 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';
|
||||
import { resolveUserFileUrl } from './user-file-server-service.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),
|
||||
};
|
||||
}
|
||||
|
||||
/** Avatars share the same PR/Base58 R2 namespace and upload protocol as other public files. */
|
||||
export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus = null, purpose = 'attachment' } = {}) {
|
||||
if (purpose === 'avatar' && (!(file instanceof Blob) || !file.size || file.size > 10 * 1024 * 1024
|
||||
|| !['image/webp', 'image/jpeg'].includes(file.type))) {
|
||||
throw new Error('Аватар должен быть оптимизированным WebP/JPEG размером до 10 МиБ');
|
||||
}
|
||||
return uploadR2PublicFile({ file, login, sessionId, wsUrl, onStatus });
|
||||
}
|
||||
|
||||
/** Canonical public object URL; avatars do not have a special prefix. */
|
||||
export function avatarR2Url(pr) {
|
||||
return publicR2Url(pr);
|
||||
}
|
||||
|
||||
export async function resolvePublicFileUrl({
|
||||
pr,
|
||||
sha256,
|
||||
authorLogin,
|
||||
solanaEndpoint,
|
||||
fallbackServerLogin = '',
|
||||
} = {}) {
|
||||
if (pr) {
|
||||
if (!validatePublicPiecesRoot(pr)) throw new Error('Некорректный Pieces Root');
|
||||
return resolveUserFileUrl({ login: authorLogin, id: pr, kind: 'public' });
|
||||
}
|
||||
// Сначала – сервер, к которому подключены сейчас (у большинства читателей он же сервер автора),
|
||||
// затем сервер сборки по умолчанию; только потом ищем сервер автора через его 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 || '');
|
||||
if (!validatePublicPiecesRoot(root)) throw new Error('Некорректный Pieces Root');
|
||||
return `https://files.shineup.me/${root}`;
|
||||
}
|
||||
Reference in New Issue
Block a user