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
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
'use strict';
// The Files and Git panels: browse, view, edit, upload, download (folders as
// zip), delete inside a session folder; git status/diff/commit/push/pull for
// the repositories in it. Every path is checked to stay inside the folder,
// symlinks included.

const fs = require('fs');
const fsp = require('fs/promises');
const path = require('path');
const crypto = require('crypto');
const { execFile } = require('child_process');
const { pipeline } = require('stream/promises');
const { Transform } = require('stream');
const { ZipWriter } = require('./zip');
const { redactText } = require('./redact');

const MAX_LIST = 3000;
const MAX_VIEW_BYTES = 1024 * 1024;
const MAX_EDIT_BYTES = 2 * 1024 * 1024;
const MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
const MAX_ZIP_FILES = 20000;
const MAX_ZIP_BYTES = 2 * 1024 * 1024 * 1024;
const GIT_TIMEOUT_MS = 30000;
const GIT_NET_TIMEOUT_MS = 180000;
const MAX_DIFF_BYTES = 300 * 1024;
const ZIP_SKIP = new Set(['node_modules', '.venv', 'venv', '__pycache__', '.cache']);

function httpError(status, message) {
  const err = new Error(message);
  err.status = status;
  return err;
}

function cleanRel(rel) {
  const value = String(rel || '').replace(/\\/g, '/').replace(/^\/+/, '');
  if (value.includes('\0')) throw httpError(400, 'Geçersiz yol.');
  return value;
}

// Absolute path of rel inside root; the real path (after symlinks) must stay inside too.
function resolveInside(root, rel, { mustExist = true } = {}) {
  const base = path.resolve(root);
  const abs = path.resolve(base, cleanRel(rel));
  if (abs !== base && !abs.startsWith(base + path.sep)) throw httpError(400, 'Yol oturum klasörünün dışında.');
  let realBase = base;
  try {
    realBase = fs.realpathSync(base);
  } catch {
    // kok yoksa asagida bulunamadi doner
  }
  let probe = abs;
  if (!mustExist) {
    while (!fs.existsSync(probe) && probe !== base) probe = path.dirname(probe);
  }
  let real;
  try {
    real = fs.realpathSync(probe);
  } catch {
    throw httpError(404, 'Bulunamadı.');
  }
  if (real !== realBase && !real.startsWith(realBase + path.sep)) throw httpError(403, 'Bağlantı oturum klasörünün dışına çıkıyor.');
  return abs;
}

function relOf(root, abs) {
  return path.relative(path.resolve(root), abs).split(path.sep).join('/');
}

function looksText(buf) {
  if (buf.includes(0)) return false;
  try {
    new TextDecoder('utf-8', { fatal: true }).decode(buf);
    return true;
  } catch {
    return false;
  }
}

function sniffImage(buf) {
  if (!buf || buf.length < 12) return null;
  if (buf[0] === 0x89 && buf.toString('ascii', 1, 4) === 'PNG') return 'image/png';
  if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg';
  const six = buf.toString('ascii', 0, 6);
  if (six === 'GIF87a' || six === 'GIF89a') return 'image/gif';
  if (buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') return 'image/webp';
  return null;
}

function sniffAudio(buf) {
  if (!buf || buf.length < 12) return null;
  if (buf.toString('ascii', 0, 3) === 'ID3' || (buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0)) return 'audio/mpeg';
  if (buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WAVE') return 'audio/wav';
  if (buf.toString('ascii', 0, 4) === 'OggS') return 'audio/ogg';
  return null;
}

async function readHead(abs, n = 4096) {
  const fd = await fsp.open(abs, 'r');
  try {
    const buf = Buffer.alloc(n);
    const { bytesRead } = await fd.read(buf, 0, n, 0);
    return buf.subarray(0, bytesRead);
  } finally {
    await fd.close();
  }
}

async function list(root, rel) {
  const abs = resolveInside(root, rel);
  const stat = await fsp.stat(abs);
  if (!stat.isDirectory()) throw httpError(400, 'Klasör değil.');
  const dirents = await fsp.readdir(abs, { withFileTypes: true });
  const entries = [];
  for (const d of dirents.slice(0, MAX_LIST)) {
    const child = path.join(abs, d.name);
    let st = null;
    try {
      st = await fsp.stat(child);
    } catch {
      st = null;
    }
    entries.push({
      name: d.name,
      type: st && st.isDirectory() ? 'dir' : st && st.isFile() ? 'file' : d.isSymbolicLink() ? 'link' : 'other',
      size: st ? st.size : 0,
      mtime: st ? Math.round(st.mtimeMs) : 0,
    });
  }
  entries.sort((a, b) => (b.type === 'dir') - (a.type === 'dir') || a.name.localeCompare(b.name, 'tr'));
  return { path: relOf(root, abs), entries, truncated: dirents.length > MAX_LIST };
}

// What the viewer can show: text (with its mtime, for safe saving), an image or audio.
async function view(root, rel) {
  const abs = resolveInside(root, rel);
  const stat = await fsp.stat(abs);
  if (!stat.isFile()) throw httpError(400, 'Dosya değil.');
  const head = await readHead(abs);
  const image = sniffImage(head);
  if (image) return { kind: 'image', type: image, size: stat.size, mtime: Math.round(stat.mtimeMs) };
  const audio = sniffAudio(head);
  if (audio) return { kind: 'audio', type: audio, size: stat.size, mtime: Math.round(stat.mtimeMs) };
  if (stat.size <= MAX_VIEW_BYTES) {
    const buf = await fsp.readFile(abs);
    if (looksText(buf)) return { kind: 'text', text: buf.toString('utf8'), size: stat.size, mtime: Math.round(stat.mtimeMs), editable: stat.size <= MAX_EDIT_BYTES };
  }
  return { kind: 'binary', size: stat.size, mtime: Math.round(stat.mtimeMs) };
}

async function rawFile(root, rel) {
  const abs = resolveInside(root, rel);
  const stat = await fsp.stat(abs);
  if (!stat.isFile()) throw httpError(400, 'Dosya değil.');
  const head = await readHead(abs);
  return { abs, name: path.basename(abs), size: stat.size, image: sniffImage(head), audio: sniffAudio(head) };
}

// Saving from the editor; refuses when the file changed since it was opened.
async function save(root, rel, text, expectedMtime) {
  if (typeof text !== 'string') throw httpError(400, 'İçerik yok.');
  if (Buffer.byteLength(text) > MAX_EDIT_BYTES) throw httpError(413, 'Dosya düzenleyici için çok büyük.');
  const abs = resolveInside(root, rel, { mustExist: false });
  let stat = null;
  try {
    stat = await fsp.stat(abs);
  } catch {
    stat = null;
  }
  if (stat && !stat.isFile()) throw httpError(400, 'Dosya değil.');
  if (stat && expectedMtime && Math.abs(Math.round(stat.mtimeMs) - Number(expectedMtime)) > 1) {
    throw httpError(409, 'Dosya sen açtıktan sonra değişmiş (Claude düzenlemiş olabilir). Yeniden açıp tekrar dene.');
  }
  await fsp.mkdir(path.dirname(abs), { recursive: true });
  const tmp = `${abs}.agentweb-${crypto.randomBytes(4).toString('hex')}`;
  await fsp.writeFile(tmp, text);
  await fsp.rename(tmp, abs);
  const next = await fsp.stat(abs);
  return { path: relOf(root, abs), mtime: Math.round(next.mtimeMs), size: next.size };
}

function safeName(raw) {
  let name = String(raw || '').normalize('NFC').split(/[\\/]/).pop();
  name = name.replace(/[\u0000-\u001f\u007f:*?"<>|]/g, '_').trim();
  if (!name || name === '.' || name === '..') throw httpError(400, 'Geçersiz dosya adı.');
  return name.slice(0, 200);
}

async function upload(root, dirRel, fileName, req) {
  const declared = Number(req.headers['content-length']);
  if (declared > MAX_UPLOAD_BYTES) throw httpError(413, 'Dosya çok büyük (en fazla 200 MB).');
  const dir = resolveInside(root, dirRel);
  if (!fs.statSync(dir).isDirectory()) throw httpError(400, 'Klasör değil.');
  const name = safeName(fileName);
  const abs = path.join(dir, name);
  resolveInside(root, relOf(root, abs), { mustExist: false });
  const tmp = path.join(dir, `.yukleniyor-${crypto.randomUUID()}`);
  let size = 0;
  const meter = new Transform({
    transform(chunk, _enc, cb) {
      size += chunk.length;
      if (size > MAX_UPLOAD_BYTES) cb(httpError(413, 'Dosya çok büyük (en fazla 200 MB).'));
      else cb(null, chunk);
    },
  });
  try {
    await pipeline(req, meter, fs.createWriteStream(tmp, { flags: 'wx' }));
  } catch (err) {
    fs.rmSync(tmp, { force: true });
    throw err.status ? err : httpError(400, 'Yükleme yarıda kesildi.');
  }
  fs.renameSync(tmp, abs);
  return { path: relOf(root, abs), size };
}

async function mkdir(root, rel) {
  const abs = resolveInside(root, rel, { mustExist: false });
  await fsp.mkdir(abs, { recursive: true });
  return { path: relOf(root, abs) };
}

async function rename(root, from, to) {
  const src = resolveInside(root, from);
  const dest = resolveInside(root, to, { mustExist: false });
  if (fs.existsSync(dest)) throw httpError(409, 'Bu adda bir dosya zaten var.');
  if (src === path.resolve(root)) throw httpError(400, 'Oturum klasörü taşınamaz.');
  await fsp.mkdir(path.dirname(dest), { recursive: true });
  await fsp.rename(src, dest);
  return { path: relOf(root, dest) };
}

async function remove(root, rel) {
  const abs = resolveInside(root, rel);
  if (abs === path.resolve(root)) throw httpError(400, 'Oturum klasörünün kendisi silinemez.');
  await fsp.rm(abs, { recursive: true, force: true });
  return { ok: true };
}

// A folder as a zip (dependency/cache folders left out).
async function zipFolder(root, rel, res) {
  const abs = resolveInside(root, rel);
  const stat = await fsp.stat(abs);
  if (!stat.isDirectory()) throw httpError(400, 'Klasör değil.');
  const files = [];
  let bytes = 0;
  const walk = async (dir) => {
    const dirents = await fsp.readdir(dir, { withFileTypes: true });
    for (const d of dirents) {
      const child = path.join(dir, d.name);
      if (d.isDirectory()) {
        if (!ZIP_SKIP.has(d.name)) await walk(child);
      } else if (d.isFile()) {
        const st = await fsp.stat(child);
        files.push({ child, st });
        bytes += st.size;
        if (files.length > MAX_ZIP_FILES) throw httpError(413, `Klasörde çok fazla dosya var (en fazla ${MAX_ZIP_FILES}).`);
        if (bytes > MAX_ZIP_BYTES) throw httpError(413, 'Klasör zip için çok büyük (en fazla 2 GB).');
      }
    }
  };
  await walk(abs);
  const base = path.basename(abs) || 'klasor';
  res.attachment(`${base}.zip`);
  res.type('application/zip');
  const zip = new ZipWriter(res);
  for (const { child, st } of files) {
    await zip.addFile(`${base}/${path.relative(abs, child).split(path.sep).join('/')}`, child, st.mtime);
  }
  await zip.finish();
}

// ---- git ----

function git(cwd, args, env, timeout = GIT_TIMEOUT_MS) {
  return new Promise((resolve) => {
    execFile(
      'git',
      args,
      { cwd, env: { ...env, GIT_TERMINAL_PROMPT: '0', GIT_PAGER: 'cat', LC_ALL: 'C.UTF-8' }, timeout, maxBuffer: 8 * 1024 * 1024 },
      (err, stdout, stderr) => {
        resolve({ ok: !err, code: err ? err.code : 0, stdout: String(stdout || ''), stderr: redactText(String(stderr || '')).trim(), killed: !!(err && err.killed) });
      }
    );
  });
}

// Repositories in the session folder: the folder itself and up to two levels below.
async function repos(root) {
  const out = [];
  const check = (abs) => {
    if (fs.existsSync(path.join(abs, '.git'))) out.push(relOf(root, abs) || '.');
  };
  const base = path.resolve(root);
  check(base);
  const scan = async (dir, depth) => {
    if (depth > 2) return;
    let dirents;
    try {
      dirents = await fsp.readdir(dir, { withFileTypes: true });
    } catch {
      return;
    }
    for (const d of dirents) {
      if (!d.isDirectory() || d.name.startsWith('.') || ZIP_SKIP.has(d.name)) continue;
      const child = path.join(dir, d.name);
      check(child);
      await scan(child, depth + 1);
    }
  };
  await scan(base, 1);
  return [...new Set(out)].slice(0, 30);
}

function repoDir(root, rel) {
  const abs = resolveInside(root, rel === '.' ? '' : rel);
  if (!fs.existsSync(path.join(abs, '.git'))) throw httpError(400, 'Burada bir git deposu yok.');
  return abs;
}

const STATUS_LABEL = { M: 'değişti', A: 'eklendi', D: 'silindi', R: 'yeniden adlandırıldı', C: 'kopyalandı', U: 'çakışma', '?': 'yeni' };

async function status(root, rel, env) {
  const cwd = repoDir(root, rel);
  const res = await git(cwd, ['status', '--porcelain=v1', '-b', '-uall', '--no-renames'], env);
  if (!res.ok) throw httpError(500, res.stderr || 'git status çalışmadı.');
  const lines = res.stdout.split('\n').filter(Boolean);
  let branch = '';
  let ahead = 0;
  let behind = 0;
  const files = [];
  for (const line of lines) {
    if (line.startsWith('## ')) {
      branch = line.slice(3).split('...')[0];
      const a = /ahead (\d+)/.exec(line);
      const b = /behind (\d+)/.exec(line);
      ahead = a ? Number(a[1]) : 0;
      behind = b ? Number(b[1]) : 0;
      continue;
    }
    if (files.length >= 500) continue;
    const x = line[0];
    const y = line[1];
    const file = line.slice(3);
    const code = x === '?' ? '?' : y !== ' ' ? y : x;
    files.push({ path: file, staged: x !== ' ' && x !== '?', code, label: STATUS_LABEL[code] || code });
  }
  const remote = await git(cwd, ['remote', '-v'], env);
  const log = await git(cwd, ['log', '-15', '--format=%h%x09%ar%x09%an%x09%s'], env);
  const name = await git(cwd, ['config', 'user.name'], env);
  const email = await git(cwd, ['config', 'user.email'], env);
  return {
    repo: rel || '.',
    branch,
    ahead,
    behind,
    files,
    more: Math.max(0, lines.length - 1 - files.length),
    remote: redactText(remote.stdout.split('\n')[0] || '').replace(/\s+\((fetch|push)\)$/, ''),
    log: log.ok
      ? log.stdout
          .split('\n')
          .filter(Boolean)
          .map((l) => {
            const [hash, when, author, subject] = l.split('\t');
            return { hash, when, author, subject };
          })
      : [],
    identity: { name: name.stdout.trim(), email: email.stdout.trim() },
  };
}

async function diff(root, rel, file, env) {
  const cwd = repoDir(root, rel);
  const target = cleanRel(file);
  resolveInside(cwd, target, { mustExist: false });
  let res = await git(cwd, ['diff', '--no-color', 'HEAD', '--', target], env);
  if (res.ok && !res.stdout.trim()) {
    // Untracked (or no commits yet): show the file as added.
    res = await git(cwd, ['diff', '--no-color', '--no-index', '--', '/dev/null', target], env);
    if (!res.stdout && res.stderr) res.stdout = '';
  }
  let text = res.stdout || res.stderr || '';
  if (text.length > MAX_DIFF_BYTES) text = `${text.slice(0, MAX_DIFF_BYTES)}\n… (fark çok uzun, kırpıldı)`;
  return { file: target, diff: redactText(text) };
}

async function commit(root, rel, message, files, env) {
  const cwd = repoDir(root, rel);
  const msg = String(message || '').trim();
  if (!msg) throw httpError(400, 'Commit mesajı boş olamaz.');
  const add = Array.isArray(files) && files.length ? ['add', '-A', '--', ...files.map(cleanRel)] : ['add', '-A'];
  const added = await git(cwd, add, env);
  if (!added.ok) throw httpError(500, added.stderr || 'git add çalışmadı.');
  const res = await git(cwd, ['commit', '-m', msg.slice(0, 5000)], env);
  if (!res.ok) throw httpError(400, res.stderr || res.stdout || 'Commit yapılamadı.');
  return { output: redactText(res.stdout.trim()) };
}

async function sync(root, rel, action, env) {
  const cwd = repoDir(root, rel);
  const args = action === 'pull' ? ['pull', '--ff-only'] : action === 'push' ? ['push'] : null;
  if (!args) throw httpError(400, 'Bilinmeyen işlem.');
  let res = await git(cwd, args, env, GIT_NET_TIMEOUT_MS);
  if (!res.ok && action === 'push' && /no upstream branch|has no upstream/i.test(res.stderr)) {
    const branch = (await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'], env)).stdout.trim();
    res = await git(cwd, ['push', '-u', 'origin', branch], env, GIT_NET_TIMEOUT_MS);
  }
  if (!res.ok) throw httpError(400, res.killed ? 'Zaman aşımı.' : res.stderr || 'İşlem başarısız.');
  return { output: redactText(`${res.stdout}\n${res.stderr}`.trim()) };
}

async function setIdentity(name, email, env) {
  const n = String(name || '').trim().slice(0, 100);
  const e = String(email || '').trim().slice(0, 200);
  if (!n || !/^[^\s@]+@[^\s@]+$/.test(e)) throw httpError(400, 'Ad ve geçerli bir e-posta gerekli.');
  const home = env.HOME || process.env.HOME;
  await git(home, ['config', '--global', 'user.name', n], env);
  await git(home, ['config', '--global', 'user.email', e], env);
  return { ok: true };
}

module.exports = {
  resolveInside,
  list,
  view,
  rawFile,
  save,
  upload,
  mkdir,
  rename,
  remove,
  zipFolder,
  repos,
  status,
  diff,
  commit,
  sync,
  setIdentity,
};