SHA256
Вложения файлов со своего сервера доступа пользователя
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
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';
|
||||
|
||||
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('Не удалось определить HTTP-адрес сервера доступа.');
|
||||
}
|
||||
return parsed.origin;
|
||||
}
|
||||
|
||||
function publicFileUrl(serverBase, sha256) {
|
||||
const cleanSha = String(sha256 || '').trim().toLowerCase();
|
||||
if (!validateSha256Hex(cleanSha)) throw new Error('Некорректный 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('Нет активной пользовательской сессии.');
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
||||
if (!sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error('На устройстве нет session key для загрузки файла.');
|
||||
}
|
||||
if (sessionMaterial.sessionId && String(sessionMaterial.sessionId) !== cleanSessionId) {
|
||||
throw new Error('Сохранённый session key относится к другой сессии.');
|
||||
}
|
||||
return {
|
||||
sessionId: cleanSessionId,
|
||||
serverBase: wsUrlToHttpBase(wsUrl),
|
||||
privateKey: await importPkcs8Ed25519(sessionMaterial.sessionPrivPkcs8),
|
||||
};
|
||||
}
|
||||
|
||||
export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus = null } = {}) {
|
||||
if (!(file instanceof File)) throw new Error('Файл не выбран.');
|
||||
if (Number(file.size || 0) <= 0) throw new Error('Нельзя загрузить пустой файл.');
|
||||
|
||||
onStatus?.('Считаем 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?.('Проверяем, есть ли файл на сервере…');
|
||||
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?.('Загружаем на сервер доступа…');
|
||||
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({
|
||||
sha256,
|
||||
authorLogin,
|
||||
solanaEndpoint,
|
||||
fallbackServerLogin = '',
|
||||
} = {}) {
|
||||
const currentServerUrl = publicFileUrl(DEFAULT_SHINE_SERVER_HTTP, sha256);
|
||||
if (await publicFileExists(currentServerUrl)) {
|
||||
return currentServerUrl;
|
||||
}
|
||||
|
||||
const cleanLogin = String(authorLogin || '').trim().toLowerCase();
|
||||
if (!cleanLogin) throw new Error('Не указан автор server-вложения.');
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user