Spaces:
Paused
Paused
Update server.js
Browse files
server.js
CHANGED
|
@@ -32,7 +32,6 @@ const IV_LEN = 12;
|
|
| 32 |
const TAG_LEN = 16;
|
| 33 |
const OVERHEAD = IV_LEN + TAG_LEN;
|
| 34 |
|
| 35 |
-
// --- ENV ---
|
| 36 |
const IMGBB_API_KEY = process.env.IMGBB_API_KEY;
|
| 37 |
const SESSION_SECRET = process.env.SESSION_SECRET;
|
| 38 |
const ADMIN_USER = process.env.ADMIN_USER || 'admin';
|
|
@@ -42,18 +41,15 @@ if (!IMGBB_API_KEY || !SESSION_SECRET) {
|
|
| 42 |
process.exit(1);
|
| 43 |
}
|
| 44 |
|
| 45 |
-
// --- DATABASE INSTANCE ---
|
| 46 |
const db = new Database(DB_PATH);
|
| 47 |
db.pragma('journal_mode = WAL');
|
| 48 |
db.pragma('busy_timeout = 5000');
|
| 49 |
|
| 50 |
-
// --- CRYPTO UTILS ---
|
| 51 |
const scryptAsync = promisify(scrypt);
|
| 52 |
async function deriveKey(password, salt) { return scryptAsync(password, salt, KEY_LEN); }
|
| 53 |
function encryptChunk(dataBuffer, key) { const iv = randomBytes(IV_LEN); const cipher = createCipheriv('aes-256-gcm', key, iv); const encrypted = Buffer.concat([cipher.update(dataBuffer), cipher.final()]); const tag = cipher.getAuthTag(); return Buffer.concat([iv, encrypted, tag]); }
|
| 54 |
function decryptChunk(encBuffer, key) { if (encBuffer.length < OVERHEAD) throw new Error('Buffer trop court'); const iv = encBuffer.subarray(0, IV_LEN); const tag = encBuffer.subarray(encBuffer.length - TAG_LEN); const data = encBuffer.subarray(IV_LEN, encBuffer.length - TAG_LEN); const decipher = createDecipheriv('aes-256-gcm', key, iv); decipher.setAuthTag(tag); return Buffer.concat([decipher.update(data), decipher.final()]); }
|
| 55 |
|
| 56 |
-
// --- PNG STEGANOGRAPHY ---
|
| 57 |
function bufferToPng(buffer) {
|
| 58 |
const byteLen = buffer.length;
|
| 59 |
const pixelsNeeded = Math.ceil(byteLen / 3);
|
|
@@ -61,7 +57,6 @@ function bufferToPng(buffer) {
|
|
| 61 |
const height = Math.ceil(pixelsNeeded / width);
|
| 62 |
const rgbBuffer = Buffer.alloc(width * height * 3);
|
| 63 |
buffer.copy(rgbBuffer);
|
| 64 |
-
// ✅ withMetadata(false) empêche sharp d'injecter des profils ICC qui corrompraient les octets
|
| 65 |
return sharp(rgbBuffer, { raw: { width, height, channels: 3 } }).png({ compressionLevel: 9, palette: false }).withMetadata(false).toBuffer();
|
| 66 |
}
|
| 67 |
async function pngToBuffer(pngBuffer, expectedLen) {
|
|
@@ -69,88 +64,28 @@ async function pngToBuffer(pngBuffer, expectedLen) {
|
|
| 69 |
const rgb = Buffer.alloc(info.width * info.height * 3);
|
| 70 |
let j = 0;
|
| 71 |
for (let i = 0; i < data.length; i += 4) {
|
| 72 |
-
if (j + 2 < rgb.length) {
|
| 73 |
-
rgb[j++] = data[i];
|
| 74 |
-
rgb[j++] = data[i+1];
|
| 75 |
-
rgb[j++] = data[i+2];
|
| 76 |
-
}
|
| 77 |
}
|
| 78 |
-
// ✅ On retourne exactement la longueur attendue, ignorant le padding de l'image
|
| 79 |
return rgb.subarray(0, expectedLen);
|
| 80 |
}
|
| 81 |
|
| 82 |
-
// ==========================================
|
| 83 |
-
// SCHÉMA DE BASE
|
| 84 |
-
// ==========================================
|
| 85 |
db.exec(`
|
| 86 |
-
CREATE TABLE IF NOT EXISTS users (
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
is_admin INTEGER DEFAULT 0,
|
| 92 |
-
tos_accepted INTEGER DEFAULT 0,
|
| 93 |
-
created_at INTEGER DEFAULT (strftime('%s','now'))
|
| 94 |
-
);
|
| 95 |
-
CREATE TABLE IF NOT EXISTS folders (
|
| 96 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 97 |
-
parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE,
|
| 98 |
-
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 99 |
-
name TEXT NOT NULL,
|
| 100 |
-
created_at INTEGER DEFAULT (strftime('%s','now')),
|
| 101 |
-
UNIQUE(parent_id, owner_id, name)
|
| 102 |
-
);
|
| 103 |
-
CREATE TABLE IF NOT EXISTS files (
|
| 104 |
-
id TEXT PRIMARY KEY,
|
| 105 |
-
folder_id INTEGER REFERENCES folders(id) ON DELETE SET NULL,
|
| 106 |
-
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 107 |
-
name TEXT NOT NULL,
|
| 108 |
-
mime TEXT NOT NULL,
|
| 109 |
-
size INTEGER NOT NULL,
|
| 110 |
-
chunk_count INTEGER DEFAULT 1,
|
| 111 |
-
status TEXT DEFAULT 'pending',
|
| 112 |
-
progress REAL DEFAULT 0,
|
| 113 |
-
error_msg TEXT,
|
| 114 |
-
encryption_key_hash TEXT NOT NULL,
|
| 115 |
-
master_key_enc BLOB,
|
| 116 |
-
created_at INTEGER DEFAULT (strftime('%s','now')),
|
| 117 |
-
updated_at INTEGER DEFAULT (strftime('%s','now'))
|
| 118 |
-
);
|
| 119 |
-
CREATE TABLE IF NOT EXISTS file_chunks (
|
| 120 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 121 |
-
file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE,
|
| 122 |
-
chunk_index INTEGER NOT NULL,
|
| 123 |
-
imgbb_url TEXT,
|
| 124 |
-
imgbb_delete_url TEXT,
|
| 125 |
-
imgbb_id TEXT,
|
| 126 |
-
size INTEGER NOT NULL,
|
| 127 |
-
encrypted_len INTEGER NOT NULL,
|
| 128 |
-
UNIQUE(file_id, chunk_index)
|
| 129 |
-
);
|
| 130 |
-
CREATE TABLE IF NOT EXISTS share_links (
|
| 131 |
-
token TEXT PRIMARY KEY,
|
| 132 |
-
file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE,
|
| 133 |
-
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 134 |
-
type TEXT NOT NULL,
|
| 135 |
-
created_at INTEGER DEFAULT (strftime('%s','now')),
|
| 136 |
-
expires_at INTEGER
|
| 137 |
-
);
|
| 138 |
CREATE INDEX IF NOT EXISTS idx_files_owner ON files(owner_id);
|
| 139 |
CREATE INDEX IF NOT EXISTS idx_chunks_file ON file_chunks(file_id);
|
| 140 |
`);
|
| 141 |
|
| 142 |
-
// ==========================================
|
| 143 |
-
// MIGRATIONS
|
| 144 |
-
// ==========================================
|
| 145 |
function runMigrations() {
|
| 146 |
console.log('🔍 Vérification migrations BDD...');
|
| 147 |
-
|
| 148 |
const usersCols = db.prepare("PRAGMA table_info(users)").all().map(c => c.name);
|
| 149 |
if (!usersCols.includes('tos_accepted')) {
|
| 150 |
console.log('🔧 Migration: ALTER TABLE users ADD COLUMN tos_accepted');
|
| 151 |
db.exec(`ALTER TABLE users ADD COLUMN tos_accepted INTEGER DEFAULT 0;`);
|
| 152 |
}
|
| 153 |
-
|
| 154 |
const filesCols = db.prepare("PRAGMA table_info(files)").all().map(c => c.name);
|
| 155 |
const filesDefs = [
|
| 156 |
{ name: 'folder_id', def: 'INTEGER REFERENCES folders(id) ON DELETE SET NULL' },
|
|
@@ -162,7 +97,6 @@ function runMigrations() {
|
|
| 162 |
{ name: 'chunk_count', def: 'INTEGER DEFAULT 1' },
|
| 163 |
{ name: 'updated_at', def: 'INTEGER DEFAULT 0' },
|
| 164 |
];
|
| 165 |
-
|
| 166 |
let updatedAdded = false;
|
| 167 |
for (const col of filesDefs) {
|
| 168 |
if (!filesCols.includes(col.name)) {
|
|
@@ -171,32 +105,18 @@ function runMigrations() {
|
|
| 171 |
if (col.name === 'updated_at') updatedAdded = true;
|
| 172 |
}
|
| 173 |
}
|
| 174 |
-
|
| 175 |
if (updatedAdded) {
|
| 176 |
-
console.log('🔧 Migration: Initialisation updated_at sur les lignes existantes');
|
| 177 |
db.exec(`UPDATE files SET updated_at = strftime('%s','now') WHERE updated_at = 0;`);
|
| 178 |
}
|
| 179 |
-
|
| 180 |
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(t => t.name);
|
| 181 |
-
|
| 182 |
-
if (!tables.includes('
|
| 183 |
-
console.log('🔧 Migration: CREATE TABLE folders');
|
| 184 |
-
db.exec(`CREATE TABLE folders (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), UNIQUE(parent_id, owner_id, name));`);
|
| 185 |
-
}
|
| 186 |
-
if (!tables.includes('share_links')) {
|
| 187 |
-
console.log('🔧 Migration: CREATE TABLE share_links');
|
| 188 |
-
db.exec(`CREATE TABLE share_links (token TEXT PRIMARY KEY, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), expires_at INTEGER);`);
|
| 189 |
-
}
|
| 190 |
-
|
| 191 |
const sessionsCols = tables.includes('sessions') ? db.prepare("PRAGMA table_info(sessions)").all().map(c => c.name) : [];
|
| 192 |
if (tables.includes('sessions') && (!sessionsCols.includes('data') || !sessionsCols.includes('expires_at'))) {
|
| 193 |
-
console.log('🔧 Migration: Reconstruction table sessions (colonnes manquantes)');
|
| 194 |
db.exec(`DROP TABLE sessions; CREATE TABLE sessions (sid TEXT PRIMARY KEY, data TEXT NOT NULL, expires_at INTEGER NOT NULL); CREATE INDEX idx_sessions_expires ON sessions(expires_at);`);
|
| 195 |
} else if (!tables.includes('sessions')) {
|
| 196 |
-
console.log('🔧 Migration: CREATE TABLE sessions');
|
| 197 |
db.exec(`CREATE TABLE sessions (sid TEXT PRIMARY KEY, data TEXT NOT NULL, expires_at INTEGER NOT NULL); CREATE INDEX idx_sessions_expires ON sessions(expires_at);`);
|
| 198 |
}
|
| 199 |
-
|
| 200 |
console.log('✅ Migrations terminées.');
|
| 201 |
}
|
| 202 |
runMigrations();
|
|
@@ -204,32 +124,12 @@ runMigrations();
|
|
| 204 |
db.exec(`
|
| 205 |
CREATE INDEX IF NOT EXISTS idx_files_folder ON files(folder_id);
|
| 206 |
DROP TRIGGER IF EXISTS update_file_ts;
|
| 207 |
-
CREATE TRIGGER update_file_ts AFTER UPDATE ON files
|
| 208 |
-
BEGIN
|
| 209 |
-
UPDATE files SET updated_at = strftime('%s','now') WHERE id = NEW.id;
|
| 210 |
-
END;
|
| 211 |
`);
|
| 212 |
|
| 213 |
-
// --- SESSION STORE ---
|
| 214 |
class SQLiteStore extends session.Store {
|
| 215 |
-
get(sid, cb) {
|
| 216 |
-
|
| 217 |
-
const r = db.prepare('SELECT data, expires_at FROM sessions WHERE sid=?').get(sid);
|
| 218 |
-
if(!r) return cb(null, null);
|
| 219 |
-
if(r.expires_at < Date.now()){
|
| 220 |
-
db.prepare('DELETE FROM sessions WHERE sid=?').run(sid);
|
| 221 |
-
return cb(null, null);
|
| 222 |
-
}
|
| 223 |
-
cb(null, JSON.parse(r.data));
|
| 224 |
-
} catch(e){ cb(e); }
|
| 225 |
-
}
|
| 226 |
-
set(sid, sess, cb) {
|
| 227 |
-
try {
|
| 228 |
-
const exp = sess.cookie?.expires ? new Date(sess.cookie.expires).getTime() : Date.now() + 30*24*60*60*1000;
|
| 229 |
-
db.prepare('INSERT OR REPLACE INTO sessions(sid,data,expires_at) VALUES(?,?,?)').run(sid, JSON.stringify(sess), exp);
|
| 230 |
-
cb(null);
|
| 231 |
-
} catch(e){ cb(e); }
|
| 232 |
-
}
|
| 233 |
destroy(sid, cb) { try { db.prepare('DELETE FROM sessions WHERE sid=?').run(sid); cb(null); } catch(e){ cb(e); } }
|
| 234 |
clear(cb) { try { db.prepare('DELETE FROM sessions').run(); cb(null); } catch(e){ cb(e); } }
|
| 235 |
length(cb) { try { const r = db.prepare('SELECT COUNT(*) as c FROM sessions').get(); cb(null, r.c); } catch(e){ cb(e); } }
|
|
@@ -237,7 +137,6 @@ class SQLiteStore extends session.Store {
|
|
| 237 |
}
|
| 238 |
const sessionStore = new SQLiteStore();
|
| 239 |
|
| 240 |
-
// --- ADMIN INIT ---
|
| 241 |
const adminRow = db.prepare('SELECT * FROM users WHERE username=?').get(ADMIN_USER);
|
| 242 |
if (!adminRow) {
|
| 243 |
const salt = randomBytes(16);
|
|
@@ -246,78 +145,37 @@ if (!adminRow) {
|
|
| 246 |
console.log(`👑 Admin: ${ADMIN_USER} / Pass: ${process.env.ADMIN_PASS || 'ChangeMeNow!'}`);
|
| 247 |
}
|
| 248 |
|
| 249 |
-
// --- EXPRESS ---
|
| 250 |
const app = express();
|
| 251 |
app.set('trust proxy', 1);
|
| 252 |
app.use(express.json({ limit: '50mb' }));
|
| 253 |
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
|
| 254 |
-
app.use(session({
|
| 255 |
-
secret: SESSION_SECRET,
|
| 256 |
-
store: sessionStore,
|
| 257 |
-
resave: false,
|
| 258 |
-
saveUninitialized: false,
|
| 259 |
-
cookie: { secure: false, httpOnly: true, maxAge: 30*24*60*60*1000, sameSite: 'lax' }
|
| 260 |
-
}));
|
| 261 |
|
| 262 |
const requireAuth = (req, res, next) => { if(!req.session.userId) return res.status(401).json({error:'Non authentifié'}); next(); };
|
| 263 |
const requireTos = (req, res, next) => { if(!req.session.tosAccepted) return res.status(403).json({error:'CGU non acceptées', needTos:true}); next(); };
|
| 264 |
|
| 265 |
-
|
| 266 |
-
class ByteLRUCache extends LRUCache { constructor(){ super({maxSize:CACHE_MAX_BYTES, sizeCalculation:v=>v.size}); } async getOrLoad(key, loader){ if(this.has(key)) return this.get(key).data; const data=await loader(); this.set(key,{data,size:data.length,time:Date.now()}); return data; } }
|
| 267 |
const fileCache = new ByteLRUCache();
|
| 268 |
-
setInterval(()=>{ const m=process.memoryUsage(); if(m.rss>13*1024*1024*1024){
|
| 269 |
|
| 270 |
-
// --- NSFW WASM ---
|
| 271 |
let nsfwModel=null;
|
| 272 |
-
async function loadNsfwModel(){
|
| 273 |
-
try{
|
| 274 |
-
await tf.setBackend('wasm');
|
| 275 |
-
tf.wasm.setWasmPaths('/app/tfjs_wasm/','tfjs-backend-wasm.wasm');
|
| 276 |
-
await tf.ready();
|
| 277 |
-
nsfwModel=await nsfwjs.load('/app/tfjs_wasm/',{type:'mobilenet_v2',size:224});
|
| 278 |
-
console.log('🛡️ NSFW WASM chargé');
|
| 279 |
-
}catch(e){ console.error('❌ NSFW load fail:',e.message); }
|
| 280 |
-
}
|
| 281 |
loadNsfwModel();
|
| 282 |
|
| 283 |
-
async function checkNsfw(buf){
|
| 284 |
-
if(!nsfwModel) return {safe:true};
|
| 285 |
-
try{
|
| 286 |
-
const t=tf.node.decodeImage(buf,3).resizeNearestNeighbor([224,224]).expandDims(0);
|
| 287 |
-
const p=await nsfwModel.classify(t);
|
| 288 |
-
t.dispose();
|
| 289 |
-
const porn=p.find(x=>x.className==='Porn'||x.className==='Sexual Activity')?.probability||0;
|
| 290 |
-
const hentai=p.find(x=>x.className==='Hentai')?.probability||0;
|
| 291 |
-
if(porn>0.85||hentai>0.9) return {safe:false,reason:`NSFW (P:${porn.toFixed(2)} H:${hentai.toFixed(2)})`};
|
| 292 |
-
return {safe:true};
|
| 293 |
-
}catch(e){ return {safe:true}; }
|
| 294 |
-
}
|
| 295 |
-
|
| 296 |
-
// --- UPLOAD QUEUE ---
|
| 297 |
class UploadQueue{ constructor(c){ this.c=c; this.r=0; this.q=[]; } add(t){ return new Promise((res,rej)=>{ this.q.push({t,res,rej}); this.proc(); }); } async proc(){ if(this.r>=this.c||!this.q.length) return; this.r++; const {t,res,rej}=this.q.shift(); try{ res(await t()); }catch(e){ rej(e); }finally{ this.r--; this.proc(); } } }
|
| 298 |
const uploadQueue=new UploadQueue(MAX_CONCURRENT_UPLOADS);
|
| 299 |
|
| 300 |
-
//
|
| 301 |
-
async function imgbbUpload(buf){
|
| 302 |
-
const f=new FormData();
|
| 303 |
-
f.append('image',buf.toString('base64'));
|
| 304 |
-
const {data}=await axios.post(`https://api.imgbb.com/1/upload?key=${IMGBB_API_KEY}`,f,{headers:f.getHeaders(),timeout:120000,maxContentLength:Infinity,maxBodyLength:Infinity});
|
| 305 |
-
if(!data.success) throw new Error(data.error?.message||'ImgBB fail');
|
| 306 |
-
return {url:data.data.url,deleteUrl:data.data.delete_url,id:data.data.id};
|
| 307 |
-
}
|
| 308 |
async function imgbbDelete(u){ try{await axios.get(u,{timeout:10000});}catch(_){} }
|
| 309 |
|
| 310 |
-
// --- KEY MGMT ---
|
| 311 |
const SERVER_MASTER_KEY=createHash('sha256').update(SESSION_SECRET+'|PixelDriveMaster').digest();
|
| 312 |
function encryptMasterKey(k){ const iv=randomBytes(12); const c=createCipheriv('aes-256-gcm',SERVER_MASTER_KEY,iv); return Buffer.concat([iv,c.update(k),c.final(),c.getAuthTag()]); }
|
| 313 |
function decryptMasterKey(b){ const iv=b.subarray(0,12), tag=b.subarray(-16), d=b.subarray(12,-16); const dc=createDecipheriv('aes-256-gcm',SERVER_MASTER_KEY,iv); dc.setAuthTag(tag); return Buffer.concat([dc.update(d),dc.final()]); }
|
| 314 |
async function getMasterKey(uid,fid){ const r=db.prepare('SELECT master_key_enc FROM files WHERE id=? AND owner_id=?').get(fid,uid); if(!r?.master_key_enc) throw new Error('Clé manquante'); return decryptMasterKey(r.master_key_enc); }
|
| 315 |
|
| 316 |
-
// --- THUMB ---
|
| 317 |
async function genThumb(fid,mime,key){
|
| 318 |
if(!mime.startsWith('image/')&&!mime.startsWith('video/')) return;
|
| 319 |
try{
|
| 320 |
-
// ✅ CORRECTION : Utilisation de c.size + OVERHEAD pour ignorer le padding de l'image
|
| 321 |
const c=db.prepare('SELECT imgbb_url, size FROM file_chunks WHERE file_id=? AND chunk_index=0').get(fid);
|
| 322 |
if(!c) return;
|
| 323 |
const {data}=await axios.get(c.imgbb_url,{responseType:'arraybuffer',timeout:30000});
|
|
@@ -330,17 +188,11 @@ async function genThumb(fid,mime,key){
|
|
| 330 |
}catch(e){ console.warn(`Thumb ${fid}:`,e.message); }
|
| 331 |
}
|
| 332 |
|
| 333 |
-
// --- STREAM DOWNLOAD ---
|
| 334 |
async function streamFile(res,file,key,range){
|
| 335 |
-
// ✅ CORRECTION : Sélection de 'size' au lieu de 'encrypted_len'
|
| 336 |
const chunks=db.prepare('SELECT chunk_index,imgbb_url,size FROM file_chunks WHERE file_id=? ORDER BY chunk_index').all(file.id);
|
| 337 |
const total=file.size;
|
| 338 |
let s=0,e=total-1;
|
| 339 |
-
if(range){
|
| 340 |
-
const p=range.replace('bytes=','').split('-');
|
| 341 |
-
s=parseInt(p[0]);
|
| 342 |
-
e=p[1]?parseInt(p[1]):total-1;
|
| 343 |
-
}
|
| 344 |
if(s >=total||e >=total) return res.status(416).send('Range Not Satisfiable');
|
| 345 |
res.set({'Content-Type':file.mime,'Content-Length':e-s+1,'Accept-Ranges':'bytes','Content-Disposition': `inline; filename="${encodeURIComponent(file.name)}"` });
|
| 346 |
if(range){res.status(206);res.set('Content-Range', `bytes ${s}-${e}/${total}`);}
|
|
@@ -354,7 +206,6 @@ async function streamFile(res,file,key,range){
|
|
| 354 |
let dec=fileCache.get(ck)?.data;
|
| 355 |
if(!dec){
|
| 356 |
const {data}=await axios.get(c.imgbb_url,{responseType:'arraybuffer',timeout:60000});
|
| 357 |
-
// ✅ CORRECTION : Extraction de la longueur exacte du chiffré (sans le padding de l'image)
|
| 358 |
const enc=await pngToBuffer(Buffer.from(data), c.size + OVERHEAD);
|
| 359 |
dec=decryptChunk(enc,key);
|
| 360 |
fileCache.set(ck,{data:dec,size:dec.length});
|
|
@@ -369,14 +220,12 @@ async function streamFile(res,file,key,range){
|
|
| 369 |
res.end();
|
| 370 |
}
|
| 371 |
|
| 372 |
-
// --- SSE ---
|
| 373 |
const sseClients=new Map();
|
| 374 |
function broadcast(fid,d){ const cs=sseClients.get(fid); if(cs){ const p=`data: ${JSON.stringify(d)}\n\n`; for(const r of cs) r.write(p); } }
|
| 375 |
|
| 376 |
// ==========================================
|
| 377 |
// ROUTES
|
| 378 |
// ==========================================
|
| 379 |
-
// Auth
|
| 380 |
app.post('/api/register',async(req,res)=>{const{u,p,t}=req.body;if(!u||!p||!t)return res.status(400).json({error:'Champs manquants'});if(db.prepare('SELECT 1 FROM users WHERE username=?').get(u))return res.status(409).json({error:'Existe'});const s=randomBytes(16);const h=await deriveKey(p,s);db.prepare('INSERT INTO users(username,password_hash,salt,tos_accepted) VALUES(?,?,?,1)').run(u,h,s);res.json({ok:true});});
|
| 381 |
app.post('/api/login',async(req,res)=>{const{u,p}=req.body;const usr=db.prepare('SELECT * FROM users WHERE username=?').get(u);if(!usr)return res.status(401).json({error:'Invalide'});const h=await deriveKey(p,usr.salt);if(!h.equals(usr.password_hash))return res.status(401).json({error:'Invalide'});req.session.userId=usr.id;req.session.isAdmin=!!usr.is_admin;req.session.tosAccepted=!!usr.tos_accepted;req.session.username=usr.username;res.json({ok:true,user:{id:usr.id,username:usr.username,isAdmin:!!usr.is_admin,tosAccepted:!!usr.tos_accepted}});});
|
| 382 |
app.post('/api/logout', (req,res)=>req.session.destroy(()=>res.json({ok:true})));
|
|
@@ -384,15 +233,12 @@ app.get('/api/me',(req,res)=>req.session.userId?res.json({id:req.session.userId,
|
|
| 384 |
app.get('/api/tos',(_,res)=>res.send(`PIXELDRIVE CGU\n1. RESPONSABILITÉ TOTALE\n2. AUCUNE GARANTIE (Projet test)\n3. INTERDITS: Illégal, NSFW, Abus\n4. CHIFFRÉ AES-256-GCM + Filtre NSFW Local\n5. ACCEPTATION = Responsabilité légale`));
|
| 385 |
app.post('/api/tos/accept',requireAuth,(req,res)=>{db.prepare('UPDATE users SET tos_accepted=1 WHERE id=?').run(req.session.userId);req.session.tosAccepted=true;res.json({ok:true});});
|
| 386 |
|
| 387 |
-
// Folders
|
| 388 |
app.get('/api/folders',requireAuth,(req,res)=>{const p=req.query.parent_id?parseInt(req.query.parent_id):null;res.json(db.prepare('SELECT * FROM folders WHERE owner_id=? AND parent_id IS ?').all(req.session.userId,p));});
|
| 389 |
app.post('/api/folders',requireAuth,requireTos,(req,res)=>{const{n,p}=req.body;if(!n)return res.status(400).json({error:'Nom requis'});try{const i=db.prepare('INSERT INTO folders(name,parent_id,owner_id) VALUES(?,?,?)').run(n,p||null,req.session.userId);res.json({id:i.lastInsertRowid,name:n,parent_id:p});}catch(e){res.status(409).json({error:'Existe'});}});
|
| 390 |
app.delete('/api/folders/:id',requireAuth,(req,res)=>{db.prepare('DELETE FROM folders WHERE id=? AND owner_id=?').run(req.params.id,req.session.userId);res.json({ok:true});});
|
| 391 |
|
| 392 |
-
// Files
|
| 393 |
app.get('/api/files',requireAuth,(req,res)=>{const f=req.query.folder_id?parseInt(req.query.folder_id):null;res.json(db.prepare('SELECT * FROM files WHERE owner_id=? AND folder_id IS ? ORDER BY name COLLATE NOCASE').all(req.session.userId,f));});
|
| 394 |
|
| 395 |
-
// Upload
|
| 396 |
const upload=multer({dest:TEMP_DIR,limits:{fileSize:5*1024*1024*1024}});
|
| 397 |
app.post('/api/files/upload',requireAuth,requireTos,upload.single('file'),async(req,res)=>{if(!req.file)return res.status(400).json({error:'Fichier manquant'});const fid=uuidv4(),fpath=req.file.path,fsize=req.file.size,cc=Math.ceil(fsize/CHUNK_SIZE),mk=randomBytes(KEY_LEN),kh=createHash('sha256').update(mk).digest('hex'),mke=encryptMasterKey(mk),fidParam=req.body.folder_id?parseInt(req.body.folder_id):null;db.prepare(`INSERT INTO files(id,folder_id,owner_id,name,mime,size,chunk_count,status,encryption_key_hash,master_key_enc) VALUES(?,?,?,?,?,?,?,'pending',?,?)`).run(fid,fidParam,req.session.userId,req.file.originalname,req.file.mimetype,fsize,cc,kh,mke);const stmt=db.prepare('INSERT INTO file_chunks(file_id,chunk_index,size,encrypted_len) VALUES(?,?,?,?)');const tx=db.transaction((arr)=>{for(const c of arr)stmt.run(...c);});const cd=[];for(let i=0;i<cc;i++){const sz=Math.min(CHUNK_SIZE,fsize-i*CHUNK_SIZE);cd.push([fid,i,sz,sz+OVERHEAD]);}tx(cd);res.json({fileId:fid,status:'pending',chunkCount:cc});uploadQueue.add(()=>processUpload(fid,fpath,mk,cc,req.file.mimetype));});
|
| 398 |
|
|
@@ -400,40 +246,71 @@ async function processUpload(fid,path,mk,cc,mime){try{db.prepare("UPDATE files S
|
|
| 400 |
|
| 401 |
function readChunk(p,o,l){return new Promise((res,rej)=>{const s=createReadStream(p,{start:o,end:o+l-1}),c=[];s.on('data',d=>c.push(d)).on('end',()=>res(Buffer.concat(c,l))).on('error',rej);});}
|
| 402 |
|
| 403 |
-
// Download
|
| 404 |
app.get('/api/files/:id/download',requireAuth,async(req,res)=>{const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);if(!f)return res.status(404).json({error:'Introuvable'});if(f.status!=='ready')return res.status(409).json({error:'Pas prêt',status:f.status});const k=await getMasterKey(req.session.userId,f.id);await streamFile(res,f,k,req.headers.range);});
|
| 405 |
|
| 406 |
-
//
|
| 407 |
-
app.
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
|
| 415 |
-
// Delete
|
| 416 |
app.delete('/api/files/:id',requireAuth,async(req,res)=>{const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);if(!f)return res.status(404).json({error:'Introuvable'});const cs=db.prepare('SELECT imgbb_delete_url FROM file_chunks WHERE file_id=?').all(f.id);for(const c of cs)if(c.imgbb_delete_url)await imgbbDelete(c.imgbb_delete_url);db.prepare('DELETE FROM files WHERE id=?').run(f.id);fileCache.delete(`chunk:${f.id}:0`);try{unlinkSync(join(THUMB_DIR,`${f.id}.jpg`));}catch(_){}res.json({ok:true});});
|
| 417 |
|
| 418 |
-
// Thumb
|
| 419 |
app.get('/api/files/:id/thumb',requireAuth,(req,res)=>{const p=join(THUMB_DIR,`${req.params.id}.jpg`);if(existsSync(p))return res.sendFile(p);res.set('Content-Type','image/svg+xml');res.send(`<svg xmlns="http://www.w3.org/2000/svg" width="256" height="144"><rect fill="#2a2a3e" width="100%" height="100%"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#666" font-family="sans-serif" font-size="16">FILE</text></svg>`);});
|
| 420 |
|
| 421 |
-
// SSE
|
| 422 |
app.get('/api/files/:id/progress',requireAuth,(req,res)=>{res.set({'Content-Type':'text/event-stream','Cache-Control':'no-cache','Connection':'keep-alive'});res.flushHeaders();const id=req.params.id;if(!sseClients.has(id))sseClients.set(id,new Set());sseClients.get(id).add(res);req.on('close',()=>sseClients.get(id)?.delete(res));});
|
| 423 |
|
| 424 |
-
// Admin
|
| 425 |
app.get('/api/admin/users',requireAuth,(req,res)=>{if(!req.session.isAdmin)return res.status(403).json({error:'Admin only'});res.json(db.prepare('SELECT id,username,is_admin,tos_accepted,created_at FROM users').all());});
|
| 426 |
-
|
| 427 |
-
// Health
|
| 428 |
app.get('/health',(_,res)=>res.json({ok:true,cache:fileCache.size,mem:process.memoryUsage()}));
|
| 429 |
|
| 430 |
-
// SPA
|
| 431 |
app.use(express.static(__dirname));
|
| 432 |
app.get('*',(_,res)=>res.sendFile(join(__dirname,'public.html')));
|
| 433 |
|
| 434 |
-
// ==========================================
|
| 435 |
-
// START
|
| 436 |
-
// ==========================================
|
| 437 |
const server=app.listen(PORT,'0.0.0.0',()=>console.log(`🚀 PixelDrive v3.2 on http://0.0.0.0:${PORT} | Cache: 12GB LRU`));
|
| 438 |
process.on('SIGTERM',()=>{console.log('SIGTERM');server.close(()=>process.exit(0));});
|
| 439 |
|
|
|
|
| 32 |
const TAG_LEN = 16;
|
| 33 |
const OVERHEAD = IV_LEN + TAG_LEN;
|
| 34 |
|
|
|
|
| 35 |
const IMGBB_API_KEY = process.env.IMGBB_API_KEY;
|
| 36 |
const SESSION_SECRET = process.env.SESSION_SECRET;
|
| 37 |
const ADMIN_USER = process.env.ADMIN_USER || 'admin';
|
|
|
|
| 41 |
process.exit(1);
|
| 42 |
}
|
| 43 |
|
|
|
|
| 44 |
const db = new Database(DB_PATH);
|
| 45 |
db.pragma('journal_mode = WAL');
|
| 46 |
db.pragma('busy_timeout = 5000');
|
| 47 |
|
|
|
|
| 48 |
const scryptAsync = promisify(scrypt);
|
| 49 |
async function deriveKey(password, salt) { return scryptAsync(password, salt, KEY_LEN); }
|
| 50 |
function encryptChunk(dataBuffer, key) { const iv = randomBytes(IV_LEN); const cipher = createCipheriv('aes-256-gcm', key, iv); const encrypted = Buffer.concat([cipher.update(dataBuffer), cipher.final()]); const tag = cipher.getAuthTag(); return Buffer.concat([iv, encrypted, tag]); }
|
| 51 |
function decryptChunk(encBuffer, key) { if (encBuffer.length < OVERHEAD) throw new Error('Buffer trop court'); const iv = encBuffer.subarray(0, IV_LEN); const tag = encBuffer.subarray(encBuffer.length - TAG_LEN); const data = encBuffer.subarray(IV_LEN, encBuffer.length - TAG_LEN); const decipher = createDecipheriv('aes-256-gcm', key, iv); decipher.setAuthTag(tag); return Buffer.concat([decipher.update(data), decipher.final()]); }
|
| 52 |
|
|
|
|
| 53 |
function bufferToPng(buffer) {
|
| 54 |
const byteLen = buffer.length;
|
| 55 |
const pixelsNeeded = Math.ceil(byteLen / 3);
|
|
|
|
| 57 |
const height = Math.ceil(pixelsNeeded / width);
|
| 58 |
const rgbBuffer = Buffer.alloc(width * height * 3);
|
| 59 |
buffer.copy(rgbBuffer);
|
|
|
|
| 60 |
return sharp(rgbBuffer, { raw: { width, height, channels: 3 } }).png({ compressionLevel: 9, palette: false }).withMetadata(false).toBuffer();
|
| 61 |
}
|
| 62 |
async function pngToBuffer(pngBuffer, expectedLen) {
|
|
|
|
| 64 |
const rgb = Buffer.alloc(info.width * info.height * 3);
|
| 65 |
let j = 0;
|
| 66 |
for (let i = 0; i < data.length; i += 4) {
|
| 67 |
+
if (j + 2 < rgb.length) { rgb[j++] = data[i]; rgb[j++] = data[i+1]; rgb[j++] = data[i+2]; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
}
|
|
|
|
| 69 |
return rgb.subarray(0, expectedLen);
|
| 70 |
}
|
| 71 |
|
|
|
|
|
|
|
|
|
|
| 72 |
db.exec(`
|
| 73 |
+
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash BLOB NOT NULL, salt BLOB NOT NULL, is_admin INTEGER DEFAULT 0, tos_accepted INTEGER DEFAULT 0, created_at INTEGER DEFAULT (strftime('%s','now')));
|
| 74 |
+
CREATE TABLE IF NOT EXISTS folders (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), UNIQUE(parent_id, owner_id, name));
|
| 75 |
+
CREATE TABLE IF NOT EXISTS files (id TEXT PRIMARY KEY, folder_id INTEGER REFERENCES folders(id) ON DELETE SET NULL, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, mime TEXT NOT NULL, size INTEGER NOT NULL, chunk_count INTEGER DEFAULT 1, status TEXT DEFAULT 'pending', progress REAL DEFAULT 0, error_msg TEXT, encryption_key_hash TEXT NOT NULL, master_key_enc BLOB, created_at INTEGER DEFAULT (strftime('%s','now')), updated_at INTEGER DEFAULT (strftime('%s','now')));
|
| 76 |
+
CREATE TABLE IF NOT EXISTS file_chunks (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, chunk_index INTEGER NOT NULL, imgbb_url TEXT, imgbb_delete_url TEXT, imgbb_id TEXT, size INTEGER NOT NULL, encrypted_len INTEGER NOT NULL, UNIQUE(file_id, chunk_index));
|
| 77 |
+
CREATE TABLE IF NOT EXISTS share_links (token TEXT PRIMARY KEY, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), expires_at INTEGER);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
CREATE INDEX IF NOT EXISTS idx_files_owner ON files(owner_id);
|
| 79 |
CREATE INDEX IF NOT EXISTS idx_chunks_file ON file_chunks(file_id);
|
| 80 |
`);
|
| 81 |
|
|
|
|
|
|
|
|
|
|
| 82 |
function runMigrations() {
|
| 83 |
console.log('🔍 Vérification migrations BDD...');
|
|
|
|
| 84 |
const usersCols = db.prepare("PRAGMA table_info(users)").all().map(c => c.name);
|
| 85 |
if (!usersCols.includes('tos_accepted')) {
|
| 86 |
console.log('🔧 Migration: ALTER TABLE users ADD COLUMN tos_accepted');
|
| 87 |
db.exec(`ALTER TABLE users ADD COLUMN tos_accepted INTEGER DEFAULT 0;`);
|
| 88 |
}
|
|
|
|
| 89 |
const filesCols = db.prepare("PRAGMA table_info(files)").all().map(c => c.name);
|
| 90 |
const filesDefs = [
|
| 91 |
{ name: 'folder_id', def: 'INTEGER REFERENCES folders(id) ON DELETE SET NULL' },
|
|
|
|
| 97 |
{ name: 'chunk_count', def: 'INTEGER DEFAULT 1' },
|
| 98 |
{ name: 'updated_at', def: 'INTEGER DEFAULT 0' },
|
| 99 |
];
|
|
|
|
| 100 |
let updatedAdded = false;
|
| 101 |
for (const col of filesDefs) {
|
| 102 |
if (!filesCols.includes(col.name)) {
|
|
|
|
| 105 |
if (col.name === 'updated_at') updatedAdded = true;
|
| 106 |
}
|
| 107 |
}
|
|
|
|
| 108 |
if (updatedAdded) {
|
|
|
|
| 109 |
db.exec(`UPDATE files SET updated_at = strftime('%s','now') WHERE updated_at = 0;`);
|
| 110 |
}
|
|
|
|
| 111 |
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(t => t.name);
|
| 112 |
+
if (!tables.includes('folders')) db.exec(`CREATE TABLE folders (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), UNIQUE(parent_id, owner_id, name));`);
|
| 113 |
+
if (!tables.includes('share_links')) db.exec(`CREATE TABLE share_links (token TEXT PRIMARY KEY, file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, created_at INTEGER DEFAULT (strftime('%s','now')), expires_at INTEGER);`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
const sessionsCols = tables.includes('sessions') ? db.prepare("PRAGMA table_info(sessions)").all().map(c => c.name) : [];
|
| 115 |
if (tables.includes('sessions') && (!sessionsCols.includes('data') || !sessionsCols.includes('expires_at'))) {
|
|
|
|
| 116 |
db.exec(`DROP TABLE sessions; CREATE TABLE sessions (sid TEXT PRIMARY KEY, data TEXT NOT NULL, expires_at INTEGER NOT NULL); CREATE INDEX idx_sessions_expires ON sessions(expires_at);`);
|
| 117 |
} else if (!tables.includes('sessions')) {
|
|
|
|
| 118 |
db.exec(`CREATE TABLE sessions (sid TEXT PRIMARY KEY, data TEXT NOT NULL, expires_at INTEGER NOT NULL); CREATE INDEX idx_sessions_expires ON sessions(expires_at);`);
|
| 119 |
}
|
|
|
|
| 120 |
console.log('✅ Migrations terminées.');
|
| 121 |
}
|
| 122 |
runMigrations();
|
|
|
|
| 124 |
db.exec(`
|
| 125 |
CREATE INDEX IF NOT EXISTS idx_files_folder ON files(folder_id);
|
| 126 |
DROP TRIGGER IF EXISTS update_file_ts;
|
| 127 |
+
CREATE TRIGGER update_file_ts AFTER UPDATE ON files BEGIN UPDATE files SET updated_at = strftime('%s','now') WHERE id = NEW.id; END;
|
|
|
|
|
|
|
|
|
|
| 128 |
`);
|
| 129 |
|
|
|
|
| 130 |
class SQLiteStore extends session.Store {
|
| 131 |
+
get(sid, cb) { try { const r = db.prepare('SELECT data, expires_at FROM sessions WHERE sid=?').get(sid); if(!r) return cb(null, null); if(r.expires_at < Date.now()){ db.prepare('DELETE FROM sessions WHERE sid=?').run(sid); return cb(null, null); } cb(null, JSON.parse(r.data)); } catch(e){ cb(e); } }
|
| 132 |
+
set(sid, sess, cb) { try { const exp = sess.cookie?.expires ? new Date(sess.cookie.expires).getTime() : Date.now() + 30*24*60*60*1000; db.prepare('INSERT OR REPLACE INTO sessions(sid,data,expires_at) VALUES(?,?,?)').run(sid, JSON.stringify(sess), exp); cb(null); } catch(e){ cb(e); } }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
destroy(sid, cb) { try { db.prepare('DELETE FROM sessions WHERE sid=?').run(sid); cb(null); } catch(e){ cb(e); } }
|
| 134 |
clear(cb) { try { db.prepare('DELETE FROM sessions').run(); cb(null); } catch(e){ cb(e); } }
|
| 135 |
length(cb) { try { const r = db.prepare('SELECT COUNT(*) as c FROM sessions').get(); cb(null, r.c); } catch(e){ cb(e); } }
|
|
|
|
| 137 |
}
|
| 138 |
const sessionStore = new SQLiteStore();
|
| 139 |
|
|
|
|
| 140 |
const adminRow = db.prepare('SELECT * FROM users WHERE username=?').get(ADMIN_USER);
|
| 141 |
if (!adminRow) {
|
| 142 |
const salt = randomBytes(16);
|
|
|
|
| 145 |
console.log(`👑 Admin: ${ADMIN_USER} / Pass: ${process.env.ADMIN_PASS || 'ChangeMeNow!'}`);
|
| 146 |
}
|
| 147 |
|
|
|
|
| 148 |
const app = express();
|
| 149 |
app.set('trust proxy', 1);
|
| 150 |
app.use(express.json({ limit: '50mb' }));
|
| 151 |
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
|
| 152 |
+
app.use(session({ secret: SESSION_SECRET, store: sessionStore, resave: false, saveUninitialized: false, cookie: { secure: false, httpOnly: true, maxAge: 30*24*60*60*1000, sameSite: 'lax' } }));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
const requireAuth = (req, res, next) => { if(!req.session.userId) return res.status(401).json({error:'Non authentifié'}); next(); };
|
| 155 |
const requireTos = (req, res, next) => { if(!req.session.tosAccepted) return res.status(403).json({error:'CGU non acceptées', needTos:true}); next(); };
|
| 156 |
|
| 157 |
+
class ByteLRUCache extends LRUCache { constructor(){ super({maxSize:CACHE_MAX_BYTES, sizeCalculation:v=>v.size}); } }
|
|
|
|
| 158 |
const fileCache = new ByteLRUCache();
|
| 159 |
+
setInterval(()=>{ const m=process.memoryUsage(); if(m.rss>13*1024*1024*1024){ fileCache.clear(); if(global.gc) global.gc(); } }, 30000);
|
| 160 |
|
|
|
|
| 161 |
let nsfwModel=null;
|
| 162 |
+
async function loadNsfwModel(){ try{ await tf.setBackend('wasm'); tf.wasm.setWasmPaths('/app/tfjs_wasm/','tfjs-backend-wasm.wasm'); await tf.ready(); nsfwModel=await nsfwjs.load('/app/tfjs_wasm/',{type:'mobilenet_v2',size:224}); console.log('🛡️ NSFW WASM chargé'); }catch(e){ console.error('❌ NSFW load fail:',e.message); } }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
loadNsfwModel();
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
class UploadQueue{ constructor(c){ this.c=c; this.r=0; this.q=[]; } add(t){ return new Promise((res,rej)=>{ this.q.push({t,res,rej}); this.proc(); }); } async proc(){ if(this.r>=this.c||!this.q.length) return; this.r++; const {t,res,rej}=this.q.shift(); try{ res(await t()); }catch(e){ rej(e); }finally{ this.r--; this.proc(); } } }
|
| 166 |
const uploadQueue=new UploadQueue(MAX_CONCURRENT_UPLOADS);
|
| 167 |
|
| 168 |
+
async function imgbbUpload(buf){ const f=new FormData(); f.append('image',buf.toString('base64')); const {data}=await axios.post(`https://api.imgbb.com/1/upload?key=${IMGBB_API_KEY}`,f,{headers:f.getHeaders(),timeout:120000,maxContentLength:Infinity,maxBodyLength:Infinity}); if(!data.success) throw new Error(data.error?.message||'ImgBB fail'); return {url:data.data.url,deleteUrl:data.data.delete_url,id:data.data.id}; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
async function imgbbDelete(u){ try{await axios.get(u,{timeout:10000});}catch(_){} }
|
| 170 |
|
|
|
|
| 171 |
const SERVER_MASTER_KEY=createHash('sha256').update(SESSION_SECRET+'|PixelDriveMaster').digest();
|
| 172 |
function encryptMasterKey(k){ const iv=randomBytes(12); const c=createCipheriv('aes-256-gcm',SERVER_MASTER_KEY,iv); return Buffer.concat([iv,c.update(k),c.final(),c.getAuthTag()]); }
|
| 173 |
function decryptMasterKey(b){ const iv=b.subarray(0,12), tag=b.subarray(-16), d=b.subarray(12,-16); const dc=createDecipheriv('aes-256-gcm',SERVER_MASTER_KEY,iv); dc.setAuthTag(tag); return Buffer.concat([dc.update(d),dc.final()]); }
|
| 174 |
async function getMasterKey(uid,fid){ const r=db.prepare('SELECT master_key_enc FROM files WHERE id=? AND owner_id=?').get(fid,uid); if(!r?.master_key_enc) throw new Error('Clé manquante'); return decryptMasterKey(r.master_key_enc); }
|
| 175 |
|
|
|
|
| 176 |
async function genThumb(fid,mime,key){
|
| 177 |
if(!mime.startsWith('image/')&&!mime.startsWith('video/')) return;
|
| 178 |
try{
|
|
|
|
| 179 |
const c=db.prepare('SELECT imgbb_url, size FROM file_chunks WHERE file_id=? AND chunk_index=0').get(fid);
|
| 180 |
if(!c) return;
|
| 181 |
const {data}=await axios.get(c.imgbb_url,{responseType:'arraybuffer',timeout:30000});
|
|
|
|
| 188 |
}catch(e){ console.warn(`Thumb ${fid}:`,e.message); }
|
| 189 |
}
|
| 190 |
|
|
|
|
| 191 |
async function streamFile(res,file,key,range){
|
|
|
|
| 192 |
const chunks=db.prepare('SELECT chunk_index,imgbb_url,size FROM file_chunks WHERE file_id=? ORDER BY chunk_index').all(file.id);
|
| 193 |
const total=file.size;
|
| 194 |
let s=0,e=total-1;
|
| 195 |
+
if(range){ const p=range.replace('bytes=','').split('-'); s=parseInt(p[0]); e=p[1]?parseInt(p[1]):total-1; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
if(s >=total||e >=total) return res.status(416).send('Range Not Satisfiable');
|
| 197 |
res.set({'Content-Type':file.mime,'Content-Length':e-s+1,'Accept-Ranges':'bytes','Content-Disposition': `inline; filename="${encodeURIComponent(file.name)}"` });
|
| 198 |
if(range){res.status(206);res.set('Content-Range', `bytes ${s}-${e}/${total}`);}
|
|
|
|
| 206 |
let dec=fileCache.get(ck)?.data;
|
| 207 |
if(!dec){
|
| 208 |
const {data}=await axios.get(c.imgbb_url,{responseType:'arraybuffer',timeout:60000});
|
|
|
|
| 209 |
const enc=await pngToBuffer(Buffer.from(data), c.size + OVERHEAD);
|
| 210 |
dec=decryptChunk(enc,key);
|
| 211 |
fileCache.set(ck,{data:dec,size:dec.length});
|
|
|
|
| 220 |
res.end();
|
| 221 |
}
|
| 222 |
|
|
|
|
| 223 |
const sseClients=new Map();
|
| 224 |
function broadcast(fid,d){ const cs=sseClients.get(fid); if(cs){ const p=`data: ${JSON.stringify(d)}\n\n`; for(const r of cs) r.write(p); } }
|
| 225 |
|
| 226 |
// ==========================================
|
| 227 |
// ROUTES
|
| 228 |
// ==========================================
|
|
|
|
| 229 |
app.post('/api/register',async(req,res)=>{const{u,p,t}=req.body;if(!u||!p||!t)return res.status(400).json({error:'Champs manquants'});if(db.prepare('SELECT 1 FROM users WHERE username=?').get(u))return res.status(409).json({error:'Existe'});const s=randomBytes(16);const h=await deriveKey(p,s);db.prepare('INSERT INTO users(username,password_hash,salt,tos_accepted) VALUES(?,?,?,1)').run(u,h,s);res.json({ok:true});});
|
| 230 |
app.post('/api/login',async(req,res)=>{const{u,p}=req.body;const usr=db.prepare('SELECT * FROM users WHERE username=?').get(u);if(!usr)return res.status(401).json({error:'Invalide'});const h=await deriveKey(p,usr.salt);if(!h.equals(usr.password_hash))return res.status(401).json({error:'Invalide'});req.session.userId=usr.id;req.session.isAdmin=!!usr.is_admin;req.session.tosAccepted=!!usr.tos_accepted;req.session.username=usr.username;res.json({ok:true,user:{id:usr.id,username:usr.username,isAdmin:!!usr.is_admin,tosAccepted:!!usr.tos_accepted}});});
|
| 231 |
app.post('/api/logout', (req,res)=>req.session.destroy(()=>res.json({ok:true})));
|
|
|
|
| 233 |
app.get('/api/tos',(_,res)=>res.send(`PIXELDRIVE CGU\n1. RESPONSABILITÉ TOTALE\n2. AUCUNE GARANTIE (Projet test)\n3. INTERDITS: Illégal, NSFW, Abus\n4. CHIFFRÉ AES-256-GCM + Filtre NSFW Local\n5. ACCEPTATION = Responsabilité légale`));
|
| 234 |
app.post('/api/tos/accept',requireAuth,(req,res)=>{db.prepare('UPDATE users SET tos_accepted=1 WHERE id=?').run(req.session.userId);req.session.tosAccepted=true;res.json({ok:true});});
|
| 235 |
|
|
|
|
| 236 |
app.get('/api/folders',requireAuth,(req,res)=>{const p=req.query.parent_id?parseInt(req.query.parent_id):null;res.json(db.prepare('SELECT * FROM folders WHERE owner_id=? AND parent_id IS ?').all(req.session.userId,p));});
|
| 237 |
app.post('/api/folders',requireAuth,requireTos,(req,res)=>{const{n,p}=req.body;if(!n)return res.status(400).json({error:'Nom requis'});try{const i=db.prepare('INSERT INTO folders(name,parent_id,owner_id) VALUES(?,?,?)').run(n,p||null,req.session.userId);res.json({id:i.lastInsertRowid,name:n,parent_id:p});}catch(e){res.status(409).json({error:'Existe'});}});
|
| 238 |
app.delete('/api/folders/:id',requireAuth,(req,res)=>{db.prepare('DELETE FROM folders WHERE id=? AND owner_id=?').run(req.params.id,req.session.userId);res.json({ok:true});});
|
| 239 |
|
|
|
|
| 240 |
app.get('/api/files',requireAuth,(req,res)=>{const f=req.query.folder_id?parseInt(req.query.folder_id):null;res.json(db.prepare('SELECT * FROM files WHERE owner_id=? AND folder_id IS ? ORDER BY name COLLATE NOCASE').all(req.session.userId,f));});
|
| 241 |
|
|
|
|
| 242 |
const upload=multer({dest:TEMP_DIR,limits:{fileSize:5*1024*1024*1024}});
|
| 243 |
app.post('/api/files/upload',requireAuth,requireTos,upload.single('file'),async(req,res)=>{if(!req.file)return res.status(400).json({error:'Fichier manquant'});const fid=uuidv4(),fpath=req.file.path,fsize=req.file.size,cc=Math.ceil(fsize/CHUNK_SIZE),mk=randomBytes(KEY_LEN),kh=createHash('sha256').update(mk).digest('hex'),mke=encryptMasterKey(mk),fidParam=req.body.folder_id?parseInt(req.body.folder_id):null;db.prepare(`INSERT INTO files(id,folder_id,owner_id,name,mime,size,chunk_count,status,encryption_key_hash,master_key_enc) VALUES(?,?,?,?,?,?,?,'pending',?,?)`).run(fid,fidParam,req.session.userId,req.file.originalname,req.file.mimetype,fsize,cc,kh,mke);const stmt=db.prepare('INSERT INTO file_chunks(file_id,chunk_index,size,encrypted_len) VALUES(?,?,?,?)');const tx=db.transaction((arr)=>{for(const c of arr)stmt.run(...c);});const cd=[];for(let i=0;i<cc;i++){const sz=Math.min(CHUNK_SIZE,fsize-i*CHUNK_SIZE);cd.push([fid,i,sz,sz+OVERHEAD]);}tx(cd);res.json({fileId:fid,status:'pending',chunkCount:cc});uploadQueue.add(()=>processUpload(fid,fpath,mk,cc,req.file.mimetype));});
|
| 244 |
|
|
|
|
| 246 |
|
| 247 |
function readChunk(p,o,l){return new Promise((res,rej)=>{const s=createReadStream(p,{start:o,end:o+l-1}),c=[];s.on('data',d=>c.push(d)).on('end',()=>res(Buffer.concat(c,l))).on('error',rej);});}
|
| 248 |
|
|
|
|
| 249 |
app.get('/api/files/:id/download',requireAuth,async(req,res)=>{const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);if(!f)return res.status(404).json({error:'Introuvable'});if(f.status!=='ready')return res.status(409).json({error:'Pas prêt',status:f.status});const k=await getMasterKey(req.session.userId,f.id);await streamFile(res,f,k,req.headers.range);});
|
| 250 |
|
| 251 |
+
// ✅ NOUVELLE ROUTE : Génère tous les liens de partage d'un coup
|
| 252 |
+
app.post('/api/files/:id/share', requireAuth, async(req,res)=>{
|
| 253 |
+
const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);
|
| 254 |
+
if(!f||f.status!=='ready') return res.status(404).json({error:'Fichier non disponible'});
|
| 255 |
+
|
| 256 |
+
const previewToken = uuidv4();
|
| 257 |
+
const downloadToken = uuidv4();
|
| 258 |
+
const expires = Date.now() + 7*24*3600000; // 7 jours
|
| 259 |
+
|
| 260 |
+
// ✅ CORRECTION SQL : Utilisation de paramètres au lieu de guillemets doubles
|
| 261 |
+
db.prepare("INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)").run(previewToken, f.id, req.session.userId, 'embed', expires);
|
| 262 |
+
db.prepare("INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)").run(downloadToken, f.id, req.session.userId, 'download', expires);
|
| 263 |
+
|
| 264 |
+
res.json({
|
| 265 |
+
preview: `/s/${previewToken}`,
|
| 266 |
+
download: `/d/${downloadToken}`,
|
| 267 |
+
expires: expires
|
| 268 |
+
});
|
| 269 |
+
});
|
| 270 |
+
|
| 271 |
+
// Ancienne route preview conservée pour compatibilité
|
| 272 |
+
app.get('/api/files/:id/preview',requireAuth,async(req,res)=>{
|
| 273 |
+
const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);
|
| 274 |
+
if(!f||f.status!=='ready')return res.status(404).json({error:'Pas prêt'});
|
| 275 |
+
const t=uuidv4();
|
| 276 |
+
db.prepare("INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)").run(t,f.id,req.session.userId,'embed',Date.now()+3600000);
|
| 277 |
+
res.json({url:`/s/${t}`});
|
| 278 |
+
});
|
| 279 |
+
|
| 280 |
+
// ✅ CORRECTION SQL : WHERE type='embed' avec paramètre
|
| 281 |
+
app.get('/s/:token',async(req,res)=>{
|
| 282 |
+
const l=db.prepare('SELECT * FROM share_links WHERE token=? AND type=? AND (expires_at IS NULL OR expires_at>?)').get(req.params.token,'embed',Date.now());
|
| 283 |
+
if(!l)return res.status(404).send(html('Lien invalide/expiré'));
|
| 284 |
+
const f=db.prepare('SELECT * FROM files WHERE id=?').get(l.file_id);
|
| 285 |
+
if(!f)return res.status(404).send(html('Fichier supprimé'));
|
| 286 |
+
const dt=uuidv4();
|
| 287 |
+
db.prepare("INSERT INTO share_links(token,file_id,owner_id,type,expires_at) VALUES(?,?,?,?,?)").run(dt,f.id,l.owner_id,'download',Date.now()+3600000);
|
| 288 |
+
const v=f.mime.startsWith('video/'),a=f.mime.startsWith('audio/'),i=f.mime.startsWith('image/'),p=f.mime==='application/pdf';
|
| 289 |
+
res.send(html(`<title>${f.name}</title><style>body{margin:0;background:#000;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;font-family:sans-serif;overflow:hidden}.wrap{max-width:90vw;max-height:90vh;text-align:center}video,audio{max-width:100%;max-height:80vh;background:#111}img{max-width:100%;max-height:80vh}.info{margin-top:1rem;opacity:.8}a{color:#4da3ff}</style><div class="wrap">${v?`<video controls autoplay playsinline src="/d/${dt}"></video>`:''}${a?`<audio controls src="/d/${dt}"></audio>`:''}${i?`<img src="/d/${dt}" alt="${f.name}">`:''}${p?`<iframe src="/d/${dt}" style="width:100%;height:80vh;border:none"></iframe>`:''}<div class="info">${f.name} • ${(f.size/1e6).toFixed(1)} MB • <a href="/d/${dt}" download>Télécharger</a></div></div>`));
|
| 290 |
+
});
|
| 291 |
+
|
| 292 |
+
// ✅ CORRECTION SQL : WHERE type='download' avec paramètre
|
| 293 |
+
app.get('/d/:token',async(req,res)=>{
|
| 294 |
+
const l=db.prepare('SELECT * FROM share_links WHERE token=? AND type=? AND (expires_at IS NULL OR expires_at>?)').get(req.params.token,'download',Date.now());
|
| 295 |
+
if(!l)return res.status(404).json({error:'Invalide'});
|
| 296 |
+
const f=db.prepare('SELECT * FROM files WHERE id=?').get(l.file_id);
|
| 297 |
+
if(!f||f.status!=='ready')return res.status(404).json({error:'Indisponible'});
|
| 298 |
+
const mk=decryptMasterKey(db.prepare('SELECT master_key_enc FROM files WHERE id=?').get(f.id).master_key_enc);
|
| 299 |
+
await streamFile(res,f,mk,req.headers.range);
|
| 300 |
+
});
|
| 301 |
|
|
|
|
| 302 |
app.delete('/api/files/:id',requireAuth,async(req,res)=>{const f=db.prepare('SELECT * FROM files WHERE id=? AND owner_id=?').get(req.params.id,req.session.userId);if(!f)return res.status(404).json({error:'Introuvable'});const cs=db.prepare('SELECT imgbb_delete_url FROM file_chunks WHERE file_id=?').all(f.id);for(const c of cs)if(c.imgbb_delete_url)await imgbbDelete(c.imgbb_delete_url);db.prepare('DELETE FROM files WHERE id=?').run(f.id);fileCache.delete(`chunk:${f.id}:0`);try{unlinkSync(join(THUMB_DIR,`${f.id}.jpg`));}catch(_){}res.json({ok:true});});
|
| 303 |
|
|
|
|
| 304 |
app.get('/api/files/:id/thumb',requireAuth,(req,res)=>{const p=join(THUMB_DIR,`${req.params.id}.jpg`);if(existsSync(p))return res.sendFile(p);res.set('Content-Type','image/svg+xml');res.send(`<svg xmlns="http://www.w3.org/2000/svg" width="256" height="144"><rect fill="#2a2a3e" width="100%" height="100%"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#666" font-family="sans-serif" font-size="16">FILE</text></svg>`);});
|
| 305 |
|
|
|
|
| 306 |
app.get('/api/files/:id/progress',requireAuth,(req,res)=>{res.set({'Content-Type':'text/event-stream','Cache-Control':'no-cache','Connection':'keep-alive'});res.flushHeaders();const id=req.params.id;if(!sseClients.has(id))sseClients.set(id,new Set());sseClients.get(id).add(res);req.on('close',()=>sseClients.get(id)?.delete(res));});
|
| 307 |
|
|
|
|
| 308 |
app.get('/api/admin/users',requireAuth,(req,res)=>{if(!req.session.isAdmin)return res.status(403).json({error:'Admin only'});res.json(db.prepare('SELECT id,username,is_admin,tos_accepted,created_at FROM users').all());});
|
|
|
|
|
|
|
| 309 |
app.get('/health',(_,res)=>res.json({ok:true,cache:fileCache.size,mem:process.memoryUsage()}));
|
| 310 |
|
|
|
|
| 311 |
app.use(express.static(__dirname));
|
| 312 |
app.get('*',(_,res)=>res.sendFile(join(__dirname,'public.html')));
|
| 313 |
|
|
|
|
|
|
|
|
|
|
| 314 |
const server=app.listen(PORT,'0.0.0.0',()=>console.log(`🚀 PixelDrive v3.2 on http://0.0.0.0:${PORT} | Cache: 12GB LRU`));
|
| 315 |
process.on('SIGTERM',()=>{console.log('SIGTERM');server.close(()=>process.exit(0));});
|
| 316 |
|