File size: 16,498 Bytes
0f84d64 82f6446 0f84d64 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | import crypto from 'crypto';
import fs from 'fs/promises';
import path from 'path';
import { loadEncryptedJson, saveEncryptedJson, readEncryptedFile, writeEncryptedFile } from './cryptoUtils.js';
const DATA_ROOT = '/data/media';
const INDEX_FILE = path.join(DATA_ROOT, 'index.json');
const BLOBS_DIR = path.join(DATA_ROOT, 'blobs');
const TRASH_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
const GUEST_RETENTION_MS = 24 * 60 * 60 * 1000;
const MEDIA_QUOTA_BYTES = 5 * 1024 * 1024 * 1024;
const state = {
loaded: false,
index: {
entries: {},
},
};
function nowIso() {
return new Date().toISOString();
}
function ownerKey(owner) {
return `${owner.type}:${owner.id}`;
}
function ensureOwner(owner) {
if (!owner?.type || !owner?.id) throw new Error('Invalid media owner');
return owner;
}
function normalizeName(name, fallback = 'Untitled') {
const clean = String(name || '').trim().replace(/[\\/:*?"<>|]+/g, '_');
return clean || fallback;
}
function extensionFromName(name = '') {
const ext = path.extname(String(name || '')).toLowerCase();
return ext.startsWith('.') ? ext.slice(1) : ext;
}
function inferKind(name, mimeType = '') {
const mime = String(mimeType || '').toLowerCase();
const ext = extensionFromName(name);
if (mime.startsWith('image/') || ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'].includes(ext)) return 'image';
if (mime.startsWith('video/') || ['mp4', 'webm', 'mov'].includes(ext)) return 'video';
if (mime.startsWith('audio/') || ['mp3', 'wav', 'ogg', 'm4a'].includes(ext)) return 'audio';
if (mime === 'text/html' || ['html', 'htm'].includes(ext)) return 'rich_text';
if (mime.startsWith('text/') || ['txt', 'md', 'json', 'js', 'ts', 'css', 'py', 'html', 'xml', 'csv', 'rtf'].includes(ext)) return 'text';
return 'file';
}
function guessMimeType(name, fallbackKind = 'file') {
const ext = extensionFromName(name);
switch (ext) {
case 'txt': return 'text/plain';
case 'md': return 'text/markdown';
case 'json': return 'application/json';
case 'html':
case 'htm': return 'text/html';
case 'css': return 'text/css';
case 'js': return 'application/javascript';
case 'ts': return 'text/plain';
case 'svg': return 'image/svg+xml';
case 'png': return 'image/png';
case 'jpg':
case 'jpeg': return 'image/jpeg';
case 'gif': return 'image/gif';
case 'webp': return 'image/webp';
case 'mp4': return 'video/mp4';
case 'webm': return 'video/webm';
case 'mp3': return 'audio/mpeg';
case 'wav': return 'audio/wav';
case 'ogg': return 'audio/ogg';
case 'csv': return 'text/csv';
default:
if (fallbackKind === 'rich_text') return 'text/html';
if (fallbackKind === 'text') return 'text/plain';
return 'application/octet-stream';
}
}
async function ensureLoaded() {
if (state.loaded) return;
const stored = await loadEncryptedJson(INDEX_FILE);
state.index = {
entries: stored?.entries || {},
};
state.loaded = true;
await purgeExpiredInternal();
}
async function saveIndex() {
await saveEncryptedJson(INDEX_FILE, state.index);
}
function getEntry(id) {
return state.index.entries[id] || null;
}
function canAccess(entry, owner) {
return !!entry && entry.ownerType === owner.type && entry.ownerId === owner.id;
}
function sanitizeEntry(entry) {
return {
id: entry.id,
type: entry.type,
name: entry.name,
parentId: entry.parentId || null,
ownerType: entry.ownerType,
ownerId: entry.ownerId,
mimeType: entry.mimeType || null,
kind: entry.kind || null,
size: entry.size || 0,
source: entry.source || null,
createdAt: entry.createdAt,
updatedAt: entry.updatedAt,
trashedAt: entry.trashedAt || null,
purgeAt: entry.purgeAt || null,
sessionIds: entry.sessionIds || [],
deletedByAssistant: !!entry.deletedByAssistant,
};
}
function blobPathFor(id) {
return path.join(BLOBS_DIR, `${id}.bin`);
}
function buildAad(entry) {
return `media:${entry.id}:${entry.ownerType}:${entry.ownerId}`;
}
function isOwnedFile(entry, owner) {
return entry?.type === 'file' && entry.ownerType === owner.type && entry.ownerId === owner.id;
}
function getChildren(owner, parentId, includeTrash = true) {
return Object.values(state.index.entries).filter((entry) =>
entry.ownerType === owner.type &&
entry.ownerId === owner.id &&
(entry.parentId || null) === (parentId || null) &&
(includeTrash || !entry.trashedAt)
);
}
function collectDescendantIds(owner, rootId, acc = new Set()) {
acc.add(rootId);
const children = getChildren(owner, rootId, true);
for (const child of children) {
collectDescendantIds(owner, child.id, acc);
}
return [...acc];
}
function resolveParentFolder(owner, parentId) {
if (!parentId) return null;
const parent = getEntry(parentId);
if (!parent || !canAccess(parent, owner) || parent.type !== 'folder') return null;
return parent.id;
}
function wouldCreateCycle(owner, entryId, candidateParentId) {
let currentId = candidateParentId || null;
while (currentId) {
if (currentId === entryId) return true;
const current = getEntry(currentId);
if (!current || !canAccess(current, owner)) return false;
currentId = current.parentId || null;
}
return false;
}
function createQuotaError(owner, usage) {
const err = new Error('Cloud storage limit reached. Delete files or empty trash to free space.');
err.code = 'media:quota_exceeded';
err.status = 413;
err.usage = usage || null;
err.owner = owner;
return err;
}
function computeUsage(owner) {
const files = Object.values(state.index.entries).filter((entry) => isOwnedFile(entry, owner));
const totalBytes = files.reduce((sum, entry) => sum + (entry.size || 0), 0);
const trashBytes = files.reduce((sum, entry) => sum + (entry.trashedAt ? (entry.size || 0) : 0), 0);
const activeBytes = totalBytes - trashBytes;
const quotaBytes = MEDIA_QUOTA_BYTES;
return {
quotaBytes,
totalBytes,
activeBytes,
trashBytes,
remainingBytes: Math.max(0, quotaBytes - totalBytes),
percentUsed: quotaBytes > 0 ? Math.min(100, (totalBytes / quotaBytes) * 100) : 0,
fileCount: files.length,
trashFileCount: files.filter((entry) => !!entry.trashedAt).length,
};
}
function assertQuotaAvailable(owner, additionalBytes = 0) {
const usage = computeUsage(owner);
if ((usage.totalBytes + Math.max(0, additionalBytes)) > usage.quotaBytes) {
throw createQuotaError(owner, usage);
}
return usage;
}
async function purgeEntry(id) {
const entry = getEntry(id);
if (!entry) return;
if (entry.type === 'file') {
await fs.rm(blobPathFor(id), { force: true }).catch(() => {});
}
delete state.index.entries[id];
}
async function purgeExpiredInternal() {
const now = Date.now();
let changed = false;
for (const entry of Object.values(state.index.entries)) {
const shouldPurge =
(entry.purgeAt && new Date(entry.purgeAt).getTime() <= now) ||
(entry.expiresAt && new Date(entry.expiresAt).getTime() <= now);
if (!shouldPurge) continue;
for (const id of collectDescendantIds({ type: entry.ownerType, id: entry.ownerId }, entry.id)) {
await purgeEntry(id);
}
changed = true;
}
if (changed) await saveIndex();
}
setInterval(() => {
purgeExpiredInternal().catch((err) => console.error('mediaStore cleanup failed:', err));
}, 6 * 60 * 60 * 1000);
export const mediaStore = {
async list(owner, { view = 'active', parentId = null } = {}) {
ensureOwner(owner);
await ensureLoaded();
const includeTrash = view === 'trash';
const items = getChildren(owner, parentId, true)
.filter((entry) => includeTrash ? !!entry.trashedAt : !entry.trashedAt)
.sort((a, b) => {
if (a.type !== b.type) return a.type === 'folder' ? -1 : 1;
return new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime();
})
.map(sanitizeEntry);
const breadcrumbs = [];
let currentId = parentId;
while (currentId) {
const entry = getEntry(currentId);
if (!entry || !canAccess(entry, owner)) break;
breadcrumbs.unshift({ id: entry.id, name: entry.name });
currentId = entry.parentId || null;
}
return { items, breadcrumbs, usage: computeUsage(owner) };
},
async get(owner, id) {
ensureOwner(owner);
await ensureLoaded();
const entry = getEntry(id);
if (!canAccess(entry, owner)) return null;
return sanitizeEntry(entry);
},
async listAll(owner, { view = 'all' } = {}) {
ensureOwner(owner);
await ensureLoaded();
const items = Object.values(state.index.entries)
.filter((entry) => canAccess(entry, owner))
.filter((entry) => {
if (view === 'active') return !entry.trashedAt;
if (view === 'trash') return !!entry.trashedAt;
return true;
})
.sort((a, b) => new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime())
.map(sanitizeEntry);
return { items, usage: computeUsage(owner) };
},
async storeBuffer(owner, {
name,
mimeType,
buffer,
parentId = null,
sessionId = null,
source = 'upload',
kind = null,
deletedByAssistant = false,
}) {
ensureOwner(owner);
await ensureLoaded();
assertQuotaAvailable(owner, Buffer.byteLength(buffer));
const entryId = crypto.randomUUID();
const resolvedParentId = resolveParentFolder(owner, parentId);
const fileName = normalizeName(name, 'Untitled');
const inferredKind = kind || inferKind(fileName, mimeType);
const entry = {
id: entryId,
type: 'file',
name: fileName,
ownerType: owner.type,
ownerId: owner.id,
mimeType: mimeType || guessMimeType(fileName, inferredKind),
kind: inferredKind,
size: buffer.byteLength,
parentId: resolvedParentId,
source,
createdAt: nowIso(),
updatedAt: nowIso(),
trashedAt: null,
purgeAt: null,
sessionIds: sessionId ? [sessionId] : [],
expiresAt: owner.type === 'guest' ? new Date(Date.now() + GUEST_RETENTION_MS).toISOString() : null,
deletedByAssistant,
};
await writeEncryptedFile(blobPathFor(entry.id), Buffer.from(buffer), buildAad(entry));
state.index.entries[entry.id] = entry;
await saveIndex();
return sanitizeEntry(entry);
},
async createFolder(owner, { name, parentId = null }) {
ensureOwner(owner);
await ensureLoaded();
const resolvedParentId = resolveParentFolder(owner, parentId);
const folder = {
id: crypto.randomUUID(),
type: 'folder',
name: normalizeName(name, 'New Folder'),
ownerType: owner.type,
ownerId: owner.id,
parentId: resolvedParentId,
createdAt: nowIso(),
updatedAt: nowIso(),
trashedAt: null,
purgeAt: null,
sessionIds: [],
expiresAt: owner.type === 'guest' ? new Date(Date.now() + GUEST_RETENTION_MS).toISOString() : null,
};
state.index.entries[folder.id] = folder;
await saveIndex();
return sanitizeEntry(folder);
},
async createDocument(owner, {
name,
parentId = null,
richText = false,
content = '',
source = 'upload',
sessionId = null,
}) {
const normalizedName = normalizeName(
name,
richText ? 'Untitled Document.html' : 'Untitled Document.txt'
);
return this.storeBuffer(owner, {
name: normalizedName,
mimeType: richText ? 'text/html' : 'text/plain',
buffer: Buffer.from(content || (richText ? '<p></p>' : ''), 'utf8'),
parentId,
sessionId,
source,
kind: richText ? 'rich_text' : 'text',
});
},
async readBuffer(owner, id) {
ensureOwner(owner);
await ensureLoaded();
const entry = getEntry(id);
if (!entry || entry.type !== 'file' || !canAccess(entry, owner)) return null;
return {
entry: sanitizeEntry(entry),
buffer: await readEncryptedFile(blobPathFor(id), buildAad(entry)),
};
},
async readText(owner, id) {
const loaded = await this.readBuffer(owner, id);
if (!loaded) return null;
return {
entry: loaded.entry,
text: loaded.buffer.toString('utf8'),
};
},
async updateContent(owner, id, { buffer, name = null, mimeType = null, kind = null }) {
ensureOwner(owner);
await ensureLoaded();
const entry = getEntry(id);
if (!entry || entry.type !== 'file' || !canAccess(entry, owner)) return null;
const nextSize = Buffer.byteLength(buffer);
const delta = nextSize - (entry.size || 0);
if (delta > 0) assertQuotaAvailable(owner, delta);
if (name) entry.name = normalizeName(name, entry.name);
if (mimeType) entry.mimeType = mimeType;
if (kind) entry.kind = kind;
entry.size = nextSize;
entry.updatedAt = nowIso();
await writeEncryptedFile(blobPathFor(entry.id), Buffer.from(buffer), buildAad(entry));
await saveIndex();
return sanitizeEntry(entry);
},
async rename(owner, id, name) {
ensureOwner(owner);
await ensureLoaded();
const entry = getEntry(id);
if (!entry || !canAccess(entry, owner)) return null;
entry.name = normalizeName(name, entry.name || 'Untitled');
entry.updatedAt = nowIso();
await saveIndex();
return sanitizeEntry(entry);
},
async move(owner, ids, parentId = null) {
ensureOwner(owner);
await ensureLoaded();
const destinationId = parentId ? resolveParentFolder(owner, parentId) : null;
if (parentId && !destinationId) throw new Error('Invalid destination folder');
const updated = [];
for (const id of ids || []) {
const entry = getEntry(id);
if (!entry || !canAccess(entry, owner)) continue;
if (destinationId === entry.id) continue;
if (wouldCreateCycle(owner, entry.id, destinationId)) continue;
entry.parentId = destinationId;
entry.updatedAt = nowIso();
updated.push(sanitizeEntry(entry));
}
if (updated.length) await saveIndex();
return updated;
},
async moveToTrash(owner, ids) {
ensureOwner(owner);
await ensureLoaded();
const trashed = [];
const now = nowIso();
const purgeAt = new Date(Date.now() + TRASH_RETENTION_MS).toISOString();
for (const id of ids || []) {
const entry = getEntry(id);
if (!entry || !canAccess(entry, owner)) continue;
for (const targetId of collectDescendantIds(owner, id)) {
const target = getEntry(targetId);
if (!target) continue;
target.trashedAt = now;
target.purgeAt = purgeAt;
target.updatedAt = now;
trashed.push(sanitizeEntry(target));
}
}
if (trashed.length) await saveIndex();
return trashed;
},
async restore(owner, ids) {
ensureOwner(owner);
await ensureLoaded();
const restored = [];
for (const id of ids || []) {
const entry = getEntry(id);
if (!entry || !canAccess(entry, owner)) continue;
for (const targetId of collectDescendantIds(owner, id)) {
const target = getEntry(targetId);
if (!target) continue;
target.trashedAt = null;
target.purgeAt = null;
target.updatedAt = nowIso();
restored.push(sanitizeEntry(target));
}
}
if (restored.length) await saveIndex();
return restored;
},
async deleteForever(owner, ids) {
ensureOwner(owner);
await ensureLoaded();
const removedIds = new Set();
for (const id of ids || []) {
const entry = getEntry(id);
if (!entry || !canAccess(entry, owner)) continue;
for (const targetId of collectDescendantIds(owner, id)) {
removedIds.add(targetId);
}
}
for (const targetId of removedIds) {
await purgeEntry(targetId);
}
if (removedIds.size) await saveIndex();
return [...removedIds];
},
async attachToSession(owner, ids, sessionId) {
ensureOwner(owner);
if (!sessionId) return [];
await ensureLoaded();
const updated = [];
for (const id of ids || []) {
const entry = getEntry(id);
if (!entry || !canAccess(entry, owner)) continue;
entry.sessionIds = [...new Set([...(entry.sessionIds || []), sessionId])];
entry.updatedAt = nowIso();
updated.push(sanitizeEntry(entry));
}
if (updated.length) await saveIndex();
return updated;
},
async getUsage(owner) {
ensureOwner(owner);
await ensureLoaded();
return computeUsage(owner);
},
};
|