diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php new file mode 100644 index 0000000..cca116a --- /dev/null +++ b/app/Http/Controllers/ActivityController.php @@ -0,0 +1,11 @@ +json($service->snapshot())->header('Cache-Control', 'public, max-age=60'); } + catch (\Throwable $e) { return response()->json(['error' => 'activity_unavailable'], 503)->header('Cache-Control', 'no-store'); } + } +} diff --git a/app/Models/ActivityCredential.php b/app/Models/ActivityCredential.php new file mode 100644 index 0000000..0b0615d --- /dev/null +++ b/app/Models/ActivityCredential.php @@ -0,0 +1,12 @@ + 'encrypted']; } +} diff --git a/app/Services/ActivityHeatmap.php b/app/Services/ActivityHeatmap.php new file mode 100644 index 0000000..fbe9695 --- /dev/null +++ b/app/Services/ActivityHeatmap.php @@ -0,0 +1,61 @@ +toDateString(); + if ($data = Cache::get($key)) { return $data; } + return Cache::lock('activity:v1:refresh', 20)->block(2, function () use ($key) { + if ($data = Cache::get($key)) { return $data; } + if (Cache::has('activity:v1:failed')) { throw new RuntimeException('Unavailable'); } + try { + $token = ActivityCredential::find('gitea-parsa')?->token; + if (!$token) { throw new RuntimeException('Unavailable'); } + // Fixed upstream and identity; no user-controlled URLs, paths or query strings. + $response = Http::withToken($token, 'token')->acceptJson()->connectTimeout(3)->timeout(10) + ->withOptions(['allow_redirects' => false])->get('https://git.parsaaghayi.ir/api/v1/users/parsa/heatmap'); + if (!$response->successful() || strlen($response->body()) > 2000000) { throw new RuntimeException('Unavailable'); } + $data = $this->aggregate($response->json(), CarbonImmutable::now('Asia/Tehran')); + Cache::put($key, $data, 300); + return $data; + } catch (\Throwable $e) { + // Never propagate/log upstream exceptions: request context can contain credentials. + Cache::put('activity:v1:failed', true, 30); + throw new RuntimeException('Activity unavailable'); + } + }); + } + + public function aggregate(mixed $rows, CarbonImmutable $now): array + { + if (!is_array($rows) || !array_is_list($rows) || count($rows) > 40000) { throw new RuntimeException('Invalid source'); } + $today = $now->setTimezone('Asia/Tehran')->startOfDay(); + $start = $today->subDays(364); + $counts = []; $seen = []; + foreach ($rows as $row) { + if (!is_array($row) || !isset($row['timestamp'], $row['contributions']) || !is_int($row['timestamp']) || !is_int($row['contributions']) || $row['timestamp'] < 0 || $row['contributions'] < 0 || $row['contributions'] > 1000000 || $row['timestamp'] > $now->timestamp + 900) { throw new RuntimeException('Invalid source'); } + $ts = $row['timestamp']; $n = $row['contributions']; + if (isset($seen[$ts])) { if ($seen[$ts] !== $n) { throw new RuntimeException('Conflicting bucket'); } continue; } + $seen[$ts] = $n; + $date = CarbonImmutable::createFromTimestamp($ts, 'Asia/Tehran')->toDateString(); + if ($date >= $start->toDateString() && $date <= $today->toDateString()) { $counts[$date] = ($counts[$date] ?? 0) + $n; } + } + $days = []; $months = []; $active = 0; $total = 0; $longest = 0; $run = 0; + for ($day = $start; $day <= $today; $day = $day->addDay()) { + $date = $day->toDateString(); $n = $counts[$date] ?? 0; + $days[] = ['date' => $date, 'count' => $n]; + $month = $day->format('Y-m'); $months[$month] = ($months[$month] ?? 0) + $n; + $total += $n; $active += (int) ($n > 0); $run = $n > 0 ? $run + 1 : 0; $longest = max($longest, $run); + } + return ['timezone' => 'Asia/Tehran', 'from' => $start->toDateString(), 'to' => $today->toDateString(), 'updated_at' => $now->toIso8601String(), 'days' => $days, + 'stats' => ['total' => $total, 'active_days' => $active, 'daily_average' => round($total / 365, 2), 'longest_streak' => $longest], + 'months' => array_map(fn ($m, $n) => ['month' => $m, 'count' => $n], array_keys($months), array_values($months))]; + } +} diff --git a/database/migrations/2026_11_18_000001_create_activity_credentials_table.php b/database/migrations/2026_11_18_000001_create_activity_credentials_table.php new file mode 100644 index 0000000..be3919f --- /dev/null +++ b/database/migrations/2026_11_18_000001_create_activity_credentials_table.php @@ -0,0 +1,8 @@ +string('id')->primary(); $table->text('token'); $table->timestamps(); }); } + public function down(): void { Schema::dropIfExists('activity_credentials'); } +}; diff --git a/ops/deploy-backend.sh b/ops/deploy-backend.sh index 354e53a..32ce117 100644 --- a/ops/deploy-backend.sh +++ b/ops/deploy-backend.sh @@ -15,8 +15,9 @@ compose=(docker compose -p backend -f "$BASE_COMPOSE" -f "$APP_DIR/ops/backend.c "${compose[@]}" build backend # Exercise the autoloader in the built image before touching the current container. docker run --rm --network none --entrypoint php "$PARSA_BACKEND_IMAGE" -r 'require "/var/www/html/vendor/autoload.php"; if (!class_exists("Illuminate\\Foundation\\Application")) { exit(1); }' +# Additive activity-only schema; no unrelated migrations or seeders. +"${compose[@]}" run --rm --no-deps --entrypoint php backend artisan migrate --force --path=database/migrations/2026_11_18_000001_create_activity_credentials_table.php "${compose[@]}" up -d --no-deps --no-build backend -docker exec parsa-backend php artisan db:seed --class="Database\\Seeders\\Blog\\RealBlogContentSeeder" --force || true for i in {1..30}; do code=$(curl --max-time 15 -s -o /dev/null -w '%{http_code}' -H 'Accept: application/json' https://backend.parsaaghayi.ir/api/website/about-me/1/translation/en || true) if [ "$code" = 200 ]; then diff --git a/routes/api.php b/routes/api.php index bcc496e..cbce67e 100644 --- a/routes/api.php +++ b/routes/api.php @@ -25,6 +25,8 @@ use Illuminate\Support\Facades\Route; | endpoint that accepts attacker-controlled credentials. */ +Route::get('website/activity', \App\Http\Controllers\ActivityController::class)->middleware('throttle:30,1'); + Route::post('auth/login', [AuthController::class, 'login']) ->middleware('throttle:5,1') ->name('auth.login'); diff --git a/routes/console.php b/routes/console.php index eff2ed2..b25a4a4 100644 --- a/routes/console.php +++ b/routes/console.php @@ -3,6 +3,25 @@ use Illuminate\Foundation\Inspiring; use Illuminate\Support\Facades\Artisan; +Artisan::command('activity:credential', function () { + // Provision only over a private stdin pipe, never argv/env or HTTP. + try { + $token = trim(stream_get_contents(STDIN, 256)); + if (!preg_match('/^[a-f0-9]{40}$/D', $token)) { throw new \RuntimeException(); } + $response = \Illuminate\Support\Facades\Http::withToken($token, 'token')->timeout(10) + ->withOptions(['allow_redirects' => false])->get('https://git.parsaaghayi.ir/api/v1/user'); + if (!$response->successful() || $response->json('login') !== 'parsa') { throw new \RuntimeException(); } + $credential = \App\Models\ActivityCredential::find('gitea-parsa') ?? new \App\Models\ActivityCredential(); + $credential->id = 'gitea-parsa'; + $credential->token = $token; + $credential->save(); + if ($credential->getRawOriginal('token') === $token || array_key_exists('token', $credential->toArray())) { throw new \RuntimeException(); } + \Illuminate\Support\Facades\Cache::forget('activity:v1:failed'); + $this->info('Credential authenticated and stored encrypted; serialization hidden.'); + } catch (\Throwable $e) { $this->error('Credential provisioning failed (details suppressed).'); return 1; } + return 0; +})->purpose('Store dedicated Gitea read:user token from private stdin'); + Artisan::command('inspire', function () { $this->comment(Inspiring::quote()); })->purpose('Display an inspiring quote')->hourly(); diff --git a/tests/activity_smoke.php b/tests/activity_smoke.php new file mode 100644 index 0000000..8d9514e --- /dev/null +++ b/tests/activity_smoke.php @@ -0,0 +1,30 @@ + 'app/Services/ActivityHeatmap.php', 'App\\Models\\ActivityCredential' => 'app/Models/ActivityCredential.php', 'App\\Http\\Controllers\\ActivityController' => 'app/Http/Controllers/ActivityController.php'] as $class => $file) { $loader->addClassMap([$class => '/activity/'.$file]); } +$app = require '/var/www/html/bootstrap/app.php'; +$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap(); +config(['app.key' => 'base64:'.base64_encode(random_bytes(32)), 'database.default' => 'sqlite', 'database.connections.sqlite.database' => ':memory:', 'cache.default' => 'array']); +Illuminate\Support\Facades\DB::purge(); +$m = require '/activity/database/migrations/2026_11_18_000001_create_activity_credentials_table.php'; $m->up(); +function check($ok, $label) { if (!$ok) { throw new RuntimeException($label); } echo "PASS $label\n"; } +$c = new App\Models\ActivityCredential(); $c->id = 'gitea-parsa'; $c->token = str_repeat('a', 40); $c->save(); +check($c->getRawOriginal('token') !== $c->token && !array_key_exists('token', $c->toArray()), 'encrypted DB and hidden serialization'); +$s = new App\Services\ActivityHeatmap(); $now = Carbon\CarbonImmutable::parse('2026-11-18T03:00:00+03:30'); +$t = Carbon\CarbonImmutable::parse('2026-11-17T21:00:00Z')->timestamp; +$data = $s->aggregate([['timestamp' => $t, 'contributions' => 3], ['timestamp' => $t, 'contributions' => 3]], $now); +check(count($data['days']) === 365 && $data['days'][364]['count'] === 3 && $data['stats']['total'] === 3, 'Tehran midnight and duplicate deduplication'); +check($data['stats']['active_days'] === 1 && $data['stats']['daily_average'] === 0.01 && array_sum(array_column($data['months'], 'count')) === 3, 'derived stats and monthly totals'); +check($s->aggregate([], $now)['stats']['total'] === 0, 'valid sparse empty result'); +foreach ([[['timestamp' => $t, 'contributions' => -1]], [['timestamp' => $now->timestamp+10000, 'contributions' => 1]], [['timestamp' => $t, 'contributions' => 1], ['timestamp' => $t, 'contributions' => 2]], 'invalid'] as $bad) { + $rejected = false; try { $s->aggregate($bad, $now); } catch (RuntimeException $e) { $rejected = true; } check($rejected, 'reject invalid/future/conflicting source'); +} +Illuminate\Support\Facades\Http::fake(['*' => Illuminate\Support\Facades\Http::response(['upstream_private_detail' => 'must-not-appear'], 403)]); +$response = (new App\Http\Controllers\ActivityController())($s); +check($response->getStatusCode() === 503 && $response->getContent() === '{"error":"activity_unavailable"}', 'sanitized unavailable no fallback'); +Illuminate\Support\Facades\Cache::flush(); +Illuminate\Support\Facades\Http::swap(new Illuminate\Http\Client\Factory()); +Illuminate\Support\Facades\Http::fake(['*' => Illuminate\Support\Facades\Http::response([], 200)]); +check(count($s->snapshot()['days']) === 365, 'authenticated fixed upstream snapshot'); +echo "Activity checks complete\n"; diff --git a/tests/deploy_fixture.py b/tests/deploy_fixture.py index 54a2758..47e018b 100644 --- a/tests/deploy_fixture.py +++ b/tests/deploy_fixture.py @@ -43,7 +43,8 @@ class DeployBoundary(unittest.TestCase): self.assertLess(calls.index(' build backend'), calls.index('run --rm')) self.assertLess(calls.index('run --rm'), calls.index(' up ')) self.assertIn('up -d --no-deps --no-build backend', calls) - self.assertNotIn('migrate', calls) + self.assertIn('migrate --force --path=database/migrations/2026_11_18_000001_create_activity_credentials_table.php', calls) + self.assertNotIn('db:seed', calls) self.assertNotIn('prune', calls) if __name__ == '__main__':