-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
240 lines (204 loc) · 7.46 KB
/
Copy pathapi.php
File metadata and controls
240 lines (204 loc) · 7.46 KB
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
<?php
/**
* Cross-server chat relay API.
*
* Endpoints (POST or GET, form-encoded):
* action=send token, sid, name, auth, msg -> append message, returns {"ok":true,"id":N}
* action=fetch token, sid, since -> returns {"ok":true,"last":N,"msgs":[{"i":N,"s":"S2","a":123,"n":"Name","m":"text"},...]}
*
* Storage: single JSON file with exclusive lock. No database required.
* Requires PHP 8.5 or newer.
*
* Deployment: upload this file and config.php to any PHP 8.5+ web host;
* the data/ folder is created automatically next to them.
*/
declare(strict_types=1);
if (PHP_VERSION_ID < 80500) {
http_response_code(500);
header('Content-Type: text/plain; charset=utf-8');
exit('CrossChat relay requires PHP 8.5 or newer.');
}
error_reporting(0);
header('Content-Type: application/json; charset=utf-8');
/**
* Data files use a .php suffix with a leading exit guard so that direct web
* access executes PHP and dies with 404, regardless of web server config.
* The guard prefix is stripped transparently when the relay reads the file.
*/
define('DATA_GUARD', "<?php http_response_code(404); exit('Not Found'); ?>\n");
/**
* Reads a guarded data file and strips the guard prefix.
*/
function readDataFile(string $path): string|false
{
$raw = @file_get_contents($path);
if ($raw === false) {
return false;
}
if (str_starts_with($raw, DATA_GUARD)) {
$raw = substr($raw, strlen(DATA_GUARD));
}
return $raw;
}
/**
* Writes a guarded data file.
*/
function writeDataFile(string $path, string $content): bool
{
return @file_put_contents($path, DATA_GUARD . $content) !== false;
}
// Migrate legacy unguarded files (messages.json / token.json) on first access
$legacyFiles = [__DIR__ . '/data/messages.json', __DIR__ . '/data/token.json'];
foreach ($legacyFiles as $legacy) {
if (is_file($legacy)) {
$guarded = preg_replace('/\.json$/', '.json.php', $legacy);
if (!is_file($guarded)) {
@rename($legacy, $guarded);
} else {
@unlink($legacy);
}
}
}
$config = require __DIR__ . '/config.php';
$dataDir = __DIR__ . '/data';
$dataFile = $dataDir . '/messages.json.php';
$tokenFile = $dataDir . '/token.json.php';
/**
* Generates a UUID v7 string per RFC 9562 (48-bit ms timestamp + 74 random bits).
* Uses random_int() for cryptographic randomness; no extensions required.
*/
function uuidv7(): string
{
$timestamp = (int)(microtime(true) * 1000);
return sprintf(
'%08x-%04x-%04x-%04x-%012x',
($timestamp >> 16) & 0xFFFFFFFF,
$timestamp & 0xFFFF,
random_int(0, 0x0FFF) | 0x7000, // version 7
random_int(0, 0x3FFF) | 0x8000, // variant 10xx
random_int(0, 0xFFFFFFFFFFFF) // 48 random bits
);
}
// Ensure the data directory exists before any storage access
if (!is_dir($dataDir)) {
@mkdir($dataDir, 0750, true);
}
// Resolve the shared token: config value wins, otherwise a UUID v7 is
// generated once and persisted to the guarded token file for reuse
$relayToken = trim((string)($config['token'] ?? ''));
if ($relayToken === '') {
if (is_file($tokenFile)) {
$stored = json_decode((string)readDataFile($tokenFile), true);
$relayToken = is_array($stored) && isset($stored['token']) ? (string)$stored['token'] : '';
}
if ($relayToken === '') {
$relayToken = uuidv7();
writeDataFile($tokenFile, (string)json_encode(['token' => $relayToken], JSON_PRETTY_PRINT));
}
}
function jsonOut(array $payload, int $status = 200): void
{
http_response_code($status);
echo json_encode($payload, JSON_UNESCAPED_UNICODE);
exit;
}
function strParam(string $key, string $default = ''): string
{
$value = $_POST[$key] ?? $_GET[$key] ?? $default;
return is_string($value) ? trim($value) : $default;
}
function intParam(string $key, int $default = 0): int
{
$value = $_POST[$key] ?? $_GET[$key] ?? $default;
return is_numeric($value) ? (int)$value : $default;
}
/**
* Strip control characters, drop invalid UTF-8, truncate to N code points.
* Works without the mbstring extension (PCRE + iconv fallback).
*/
function cleanText(string $value, int $maxLength): string
{
// Remove control characters at byte level; UTF-8 sequences never contain them
$value = preg_replace('/[\x00-\x1F\x7F]/', '', $value) ?? '';
// Drop invalid UTF-8 sequences so json_encode can never fail
if ($value !== '' && !preg_match('//u', $value)) {
$clean = function_exists('iconv')
? @iconv('UTF-8', 'UTF-8//IGNORE', $value)
: preg_replace('/[\x80-\xFF]/', '', $value);
$value = is_string($clean) ? $clean : '';
}
// Truncate to N UTF-8 code points via PCRE, no mbstring required
if (preg_match('/^(.{0,' . $maxLength . '})/us', $value, $m)) {
return $m[1];
}
return substr($value, 0, $maxLength);
}
// Validate request token with timing-safe comparison
$token = strParam('token');
if ($token === '' || !hash_equals($relayToken, $token)) {
jsonOut(['ok' => false, 'error' => 'invalid token'], 403);
}
$action = strParam('action');
// Dedicated lock file serialises buffer read-modify-write cycles
$lockFile = $dataDir . '/buffer.lock';
$loadBuffer = static function () use ($dataFile): array {
$raw = readDataFile($dataFile);
$data = $raw !== false ? json_decode($raw, true) : null;
if (!is_array($data) || !isset($data['next'], $data['msgs'])) {
return ['next' => 1, 'msgs' => []];
}
return $data;
};
if ($action === 'send') {
$sid = cleanText(strParam('sid'), $config['max_server_id_length']);
$name = cleanText(strParam('name'), $config['max_name_length']);
$msg = cleanText(strParam('msg'), $config['max_message_length']);
$auth = intParam('auth');
// auth=0 marks a server console message; positive values are player SteamIDs
if ($sid === '' || $name === '' || $msg === '' || $auth < 0) {
jsonOut(['ok' => false, 'error' => 'invalid params'], 400);
}
$lockFh = fopen($lockFile, 'c');
if ($lockFh === false) {
jsonOut(['ok' => false, 'error' => 'storage error'], 500);
}
flock($lockFh, LOCK_EX);
$data = $loadBuffer();
$id = (int)$data['next'];
$data['msgs'][] = ['i' => $id, 's' => $sid, 'a' => $auth, 'n' => $name, 'm' => $msg];
// Trim overflowed messages (retention applies via the same window)
$data['msgs'] = array_slice($data['msgs'], -$config['max_buffer_size']);
$data['next'] = $id + 1;
$saved = writeDataFile($dataFile, (string)json_encode($data, JSON_UNESCAPED_UNICODE));
flock($lockFh, LOCK_UN);
fclose($lockFh);
if (!$saved) {
jsonOut(['ok' => false, 'error' => 'storage error'], 500);
}
jsonOut(['ok' => true, 'id' => $id]);
}
if ($action === 'fetch') {
$sid = cleanText(strParam('sid'), $config['max_server_id_length']);
$since = intParam('since', 0);
if ($sid === '') {
jsonOut(['ok' => false, 'error' => 'invalid params'], 400);
}
$lockFh = @fopen($lockFile, 'c');
if ($lockFh !== false) {
flock($lockFh, LOCK_SH);
}
$data = $loadBuffer();
if ($lockFh !== false) {
flock($lockFh, LOCK_UN);
fclose($lockFh);
}
$last = (int)$data['next'] - 1;
$msgs = [];
foreach ($data['msgs'] as $entry) {
if ($entry['i'] > $since && $entry['s'] !== $sid) {
$msgs[] = $entry;
}
}
jsonOut(['ok' => true, 'last' => $last, 'msgs' => $msgs]);
}
jsonOut(['ok' => false, 'error' => 'unknown action'], 400);