72 lines
2.4 KiB
PHP
72 lines
2.4 KiB
PHP
<?php
|
||
/**
|
||
* portspoof_concentrator – HTTP fetch trigger
|
||
*
|
||
* Runs the same fetch logic as cron/fetch.php when called over HTTP.
|
||
* Requires a valid secret token, configured in config.php as TRIGGER_TOKEN.
|
||
*
|
||
* Usage:
|
||
* GET/POST /trigger.php?token=<secret>
|
||
* GET/POST /trigger.php (with header: Authorization: Bearer <secret>)
|
||
*
|
||
* Always returns JSON.
|
||
*/
|
||
|
||
require_once __DIR__ . '/includes/functions.php';
|
||
|
||
header('Content-Type: application/json');
|
||
|
||
// ── Token check ───────────────────────────────────────────────────────────────
|
||
|
||
if (TRIGGER_TOKEN === '') {
|
||
http_response_code(503);
|
||
echo json_encode(['error' => 'Trigger endpoint is disabled. Set TRIGGER_TOKEN in config.php.']);
|
||
exit;
|
||
}
|
||
|
||
$provided = '';
|
||
|
||
// Accept token from Authorization: Bearer header
|
||
$auth_header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
||
if (str_starts_with($auth_header, 'Bearer ')) {
|
||
$provided = substr($auth_header, 7);
|
||
}
|
||
|
||
// Accept token from ?token= query param (lower priority)
|
||
if ($provided === '' && isset($_REQUEST['token'])) {
|
||
$provided = $_REQUEST['token'];
|
||
}
|
||
|
||
if (!hash_equals(TRIGGER_TOKEN, $provided)) {
|
||
http_response_code(401);
|
||
echo json_encode(['error' => 'Unauthorized']);
|
||
exit;
|
||
}
|
||
|
||
// ── Run fetch ─────────────────────────────────────────────────────────────────
|
||
|
||
$started_at = microtime(true);
|
||
$results = run_fetch();
|
||
$elapsed_ms = (int)round((microtime(true) - $started_at) * 1000);
|
||
|
||
$total_fetched = array_sum(array_column($results, 'fetched'));
|
||
$total_inserted = array_sum(array_column($results, 'inserted'));
|
||
$errors = array_filter($results, fn($r) => $r['error'] !== null);
|
||
|
||
http_response_code(empty($errors) ? 200 : 207);
|
||
|
||
echo json_encode([
|
||
'ok' => empty($errors),
|
||
'elapsed_ms' => $elapsed_ms,
|
||
'total_fetched' => $total_fetched,
|
||
'total_inserted' => $total_inserted,
|
||
'nodes' => array_map(fn($r) => [
|
||
'node_id' => $r['node_id'],
|
||
'name' => $r['name'],
|
||
'fetched' => $r['fetched'],
|
||
'inserted' => $r['inserted'],
|
||
'last_event_at' => $r['last_event_at'],
|
||
'error' => $r['error'],
|
||
], $results),
|
||
], JSON_PRETTY_PRINT);
|