File size: 2,284 Bytes
1e1edce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php
// Sicheres Lesen von Markdown-Dateien, um CORS/Servereinschränkungen zu umgehen

declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');

function fail(string $msg, int $code = 400): void {
    http_response_code($code);
    echo json_encode([ 'status' => 'error', 'error' => $msg ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

try {
    $raw = file_get_contents('php://input');
    if ($raw === false) fail('Konnte Request-Body nicht lesen');
    $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable $e) {
    fail('Ungültiger JSON-Body: ' . $e->getMessage());
}

$path = $data['path'] ?? null;
if (!is_string($path)) fail('Parameter path ist erforderlich');

$protokollDir = realpath(dirname(__DIR__));
$rootDir = realpath(dirname(dirname(__DIR__)));
if ($protokollDir === false || $rootDir === false) fail('Serverpfade nicht auflösbar', 500);

if (!preg_match('/\.md$/i', $path)) fail('Nur .md Dateien');

$targetAbs = null;
if (str_starts_with($path, './')) {
    $rel = ltrim(substr($path, 2), '/\\');
    $targetAbs = $protokollDir . DIRECTORY_SEPARATOR . $rel;
} elseif (str_starts_with($path, '../')) {
    $rel = ltrim(substr($path, 3), '/\\');
    $targetAbs = $rootDir . DIRECTORY_SEPARATOR . $rel;
} else {
    fail('Ungültiges Pfadformat');
}

$targetReal = realpath($targetAbs);
if ($targetReal === false) fail('Datei nicht gefunden', 404);

$ext = strtolower(pathinfo($targetReal, PATHINFO_EXTENSION));
if ($ext !== 'md') fail('Nur .md Dateien');

$protokollPrefix = rtrim(str_replace('\\', '/', $protokollDir), '/') . '/';
$rootPrefix = rtrim(str_replace('\\', '/', $rootDir), '/') . '/';
$targetNorm = rtrim(str_replace('\\', '/', $targetReal), '/');

$allowed = false;
if (str_starts_with($targetNorm, $protokollPrefix)) {
    $allowed = true;
} else if (str_starts_with($targetNorm, $rootPrefix)) {
    $base = basename($targetNorm);
    if (in_array($base, ['StartAIChatRegeln.md', 'StopAIChatRegeln.md'], true)) $allowed = true;
}

if (!$allowed) fail('Zugriff verweigert');

$content = @file_get_contents($targetReal);
if ($content === false) fail('Lesefehler', 500);

echo json_encode([ 'status' => 'ok', 'content' => $content ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);