= 16 UTF-8 bytes) that never leaves your server * - SPURVIK_SIGNING_SECRET: Secret (>= 16 chars) for signed Art. 14 human approval callback links */ final class SpurvikGuard { public const VERSION = '1.0.18'; public const CONSOLE_BASE_URL = 'https://console.spurvik.com'; public const BADGE_SCRIPT_SRC = 'https://spurvik.com/badge.js'; public const TRUST_WIDGET_SRC = 'https://spurvik.com/trust-widget.js'; public const PAYLOAD_SUMMARY_SCHEMA = 'spurvik.payload_summary.v1'; /** @var array */ private const EU_LOCALES = [ 'bg' => true, 'cs' => true, 'da' => true, 'de' => true, 'el' => true, 'en' => true, 'es' => true, 'et' => true, 'fi' => true, 'fr' => true, 'ga' => true, 'hr' => true, 'hu' => true, 'it' => true, 'lt' => true, 'lv' => true, 'mt' => true, 'nl' => true, 'pl' => true, 'pt' => true, 'ro' => true, 'sk' => true, 'sl' => true, 'sv' => true, ]; /** @var array */ private const NOTICE_KINDS = [ 'interaction' => true, 'generated' => true, 'deepfake' => true, 'public-interest' => true, 'emotion-biometric' => true, ]; /** @var array */ private const BADGE_POSITIONS = [ 'bottom-right' => true, 'bottom-left' => true, 'top-right' => true, 'top-left' => true, 'inline' => true, ]; private const MAX_SUMMARY_CHARS = 500; private const MAX_SUMMARY_KEYS = 32; private const DEFAULT_LINK_MAX_AGE_SECONDS = 86400; private const MAX_LINK_MAX_AGE_SECONDS = 604800; private const MAX_CLOCK_SKEW_SECONDS = 300; public static function keyedDigest(string $text, ?string $secret = null): string { $resolved = self::resolveHashSecret($secret); return hash_hmac('sha256', $text, $resolved); } /** * Build canonical `spurvik.payload_summary.v1` JSON containing sorted field names only (0 PII values). * * @param array $payloadOrKeys */ public static function buildPayloadSummary(array $payloadOrKeys, ?string $contentFingerprint = null): string { $isList = array_is_list($payloadOrKeys); $rawKeys = $isList ? array_values($payloadOrKeys) : array_keys($payloadOrKeys); $validKeys = []; foreach ($rawKeys as $candidate) { if (is_string($candidate) && preg_match('/^[A-Za-z_][A-Za-z0-9_]{0,63}$/', $candidate) === 1) { $validKeys[] = $candidate; if (count($validKeys) >= self::MAX_SUMMARY_KEYS) { break; } } } $fp = (is_string($contentFingerprint) && preg_match('/^[0-9a-f]{64}$/', $contentFingerprint) === 1) ? $contentFingerprint : null; $kept = $validKeys; $serialized = self::encodeSummaryDoc($kept, $fp); while (strlen($serialized) > self::MAX_SUMMARY_CHARS && count($kept) > 0) { array_pop($kept); $serialized = self::encodeSummaryDoc($kept, $fp); } return $serialized; } /** * Build a single telemetry event accepted by POST /api/v1/telemetry (0 bytes of prompt or output text). * * @return array */ public static function buildTelemetryEvent( string $prompt, string $output, string $modelProvider = 'openai', string $modelVersion = 'gpt-4o', int $latencyMs = 0, ?float $temperature = null, bool $contentMarkingApplied = false, ?string $markingHookId = null, string $hitlStatus = 'not_required', ?string $secret = null ): array { $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); $timestamp = $now->format('Y-m-d\TH:i:s.v\Z'); $clampedLatency = max(0, min(3600000, $latencyMs)); $provider = substr(trim($modelProvider), 0, 64); $version = substr(trim($modelVersion), 0, 200); return [ 'eventId' => self::uuidV4(), 'timestamp' => $timestamp, 'modelProvider' => $provider !== '' ? $provider : 'custom', 'modelVersion' => $version !== '' ? $version : 'unknown', 'inputHash' => self::keyedDigest($prompt, $secret), 'outputHash' => self::keyedDigest($output, $secret), 'contentHashMode' => 'keyed', 'latencyMs' => $clampedLatency, 'temperature' => $temperature, 'contentMarkingApplied' => $contentMarkingApplied, 'markingHookId' => ($markingHookId !== null && $markingHookId !== '') ? substr($markingHookId, 0, 120) : null, 'hitlStatus' => $hitlStatus, ]; } /** * Send a keyed HMAC-SHA256 telemetry receipt to EU Frankfurt (`fra1`) (`POST /api/v1/telemetry`). * * @return array */ public static function sendTelemetryEvent( string $prompt, string $output, string $modelProvider = 'openai', string $modelVersion = 'gpt-4o', int $latencyMs = 0, ?float $temperature = null, bool $contentMarkingApplied = false, string $hitlStatus = 'not_required', ?string $apiKey = null, ?string $secret = null, string $baseUrl = self::CONSOLE_BASE_URL ): array { $event = self::buildTelemetryEvent( $prompt, $output, $modelProvider, $modelVersion, $latencyMs, $temperature, $contentMarkingApplied, null, $hitlStatus, $secret ); return self::postJson('/api/v1/telemetry', ['events' => [$event]], $apiKey, $baseUrl); } /** * Enqueue a pre-execution Art. 14 human approval item (`POST /api/v1/hitl`, Pro EUR 19/mo & Team EUR 79/mo). * * @param array $payloadOrKeys * @return array */ public static function requestHumanApproval( string $actionName, array $payloadOrKeys, ?string $contentFingerprint = null, ?string $apiKey = null, string $baseUrl = self::CONSOLE_BASE_URL ): array { $name = substr(trim($actionName), 0, 200); if ($name === '') { throw new \InvalidArgumentException('actionName must not be empty.'); } $summary = self::buildPayloadSummary($payloadOrKeys, $contentFingerprint); return self::postJson( '/api/v1/hitl', ['actionName' => $name, 'payloadSummary' => $summary], $apiKey, $baseUrl ); } /** * Return a Blade / Twig safe `', self::BADGE_SCRIPT_SRC, $escapedSys, $safeNotice, $safeLocale, $safePos, $attr ); } /** * Return a Blade / Twig safe `', self::TRUST_WIDGET_SRC, $escapedDom, $locAttr, $safeTheme, $attr ); } /** * Compute deterministic `spurvik:art12:v1` action HMAC matching `spurvik/channels` in Node.js & Python. * * @param array $context */ public static function computeActionHmac( string $gateId, string $actionName, array $context = [], ?string $signingSecret = null ): string { $sec = self::resolveSigningSecret($signingSecret); ksort($context, SORT_STRING); $pairs = []; foreach ($context as $k => $v) { if (is_bool($v)) { $strVal = $v ? 'true' : 'false'; } else { $strVal = (string) $v; } $pairs[] = $k . '=' . $strVal; } $msg = 'spurvik:art12:v1|' . $gateId . '|' . $actionName . '|' . implode('&', $pairs); return hash_hmac('sha256', $msg, $sec); } /** * Create signed Slack / Microsoft Teams Approve & Reject callback URLs (`spurvik:art14:decision:v1`). * * @param array $context * @return array{gateId: string, actionHmac: string, issuedAt: int, nonce: string, approveUrl: string, rejectUrl: string} */ public static function createSignedApprovalLinks( string $callbackBaseUrl, string $gateId, string $actionName, array $context = [], ?string $signingSecret = null, ?int $issuedAtUnix = null, ?string $nonce = null ): array { $sec = self::resolveSigningSecret($signingSecret); $base = rtrim(trim($callbackBaseUrl), '/'); if (!str_starts_with($base, 'https://') && !str_starts_with($base, 'http://localhost')) { throw new \InvalidArgumentException('callbackBaseUrl must start with https:// (or http://localhost in local tests).'); } $actionHmac = self::computeActionHmac($gateId, $actionName, $context, $sec); $issued = $issuedAtUnix ?? time(); $tokNonce = ($nonce !== null && $nonce !== '') ? $nonce : bin2hex(random_bytes(12)); $approveSig = hash_hmac('sha256', self::decisionPayload($gateId, $actionHmac, 'approved', $issued, $tokNonce), $sec); $rejectSig = hash_hmac('sha256', self::decisionPayload($gateId, $actionHmac, 'rejected', $issued, $tokNonce), $sec); $sep = str_contains($base, '?') ? '&' : '?'; $buildUrl = static function (string $decision, string $sig) use ($base, $sep, $gateId, $actionHmac, $issued, $tokNonce): string { return $base . $sep . http_build_query([ 'gateId' => $gateId, 'actionHmac' => $actionHmac, 'decision' => $decision, 'issuedAt' => (string) $issued, 'nonce' => $tokNonce, 'sig' => $sig, ], '', '&', PHP_QUERY_RFC3986); }; return [ 'gateId' => $gateId, 'actionHmac' => $actionHmac, 'issuedAt' => $issued, 'nonce' => $tokNonce, 'approveUrl' => $buildUrl('approved', $approveSig), 'rejectUrl' => $buildUrl('rejected', $rejectSig), ]; } /** * Check a signed Art. 14 callback URL or query array in constant time (`hash_equals`). * Fail-closed: ONLY a valid, unexpired `decision=approved` returns `executeAllowed: true`. * * @param string|array $urlOrQuery * @return array{valid: bool, executeAllowed: bool, decision: string|null, reason: string} */ public static function verifySignedCallback( string|array $urlOrQuery, ?string $expectedActionHmac = null, ?string $signingSecret = null, int $maxAgeSeconds = self::DEFAULT_LINK_MAX_AGE_SECONDS, ?int $nowUnix = null ): array { $sec = self::resolveSigningSecret($signingSecret); $params = []; if (is_string($urlOrQuery)) { $queryStr = str_contains($urlOrQuery, '?') ? (string) parse_url($urlOrQuery, PHP_URL_QUERY) : $urlOrQuery; parse_str($queryStr, $params); } else { $params = $urlOrQuery; } $gateId = isset($params['gateId']) && is_string($params['gateId']) ? $params['gateId'] : ''; $actionHmac = isset($params['actionHmac']) && is_string($params['actionHmac']) ? $params['actionHmac'] : ''; $decision = isset($params['decision']) && is_string($params['decision']) ? $params['decision'] : ''; $issuedRaw = isset($params['issuedAt']) ? (string) $params['issuedAt'] : ''; $nonce = isset($params['nonce']) && is_string($params['nonce']) && $params['nonce'] !== '' ? $params['nonce'] : null; $sig = isset($params['sig']) && is_string($params['sig']) ? $params['sig'] : ''; if ($gateId === '' || preg_match('/^[0-9a-f]{64}$/', $actionHmac) !== 1 || preg_match('/^[0-9a-f]{64}$/', $sig) !== 1) { return ['valid' => false, 'executeAllowed' => false, 'decision' => null, 'reason' => 'malformed_fields']; } if ($decision !== 'approved' && $decision !== 'rejected') { return ['valid' => false, 'executeAllowed' => false, 'decision' => null, 'reason' => 'invalid_decision']; } if (ctype_digit($issuedRaw) === false) { return ['valid' => false, 'executeAllowed' => false, 'decision' => null, 'reason' => 'invalid_timestamp']; } $issuedAt = (int) $issuedRaw; $now = $nowUnix ?? time(); $clampedMaxAge = max(1, min(self::MAX_LINK_MAX_AGE_SECONDS, $maxAgeSeconds)); if ($issuedAt > $now + self::MAX_CLOCK_SKEW_SECONDS) { return ['valid' => false, 'executeAllowed' => false, 'decision' => null, 'reason' => 'future_timestamp']; } if ($now - $issuedAt > $clampedMaxAge) { return ['valid' => false, 'executeAllowed' => false, 'decision' => null, 'reason' => 'expired_token']; } if ($expectedActionHmac !== null && !hash_equals($expectedActionHmac, $actionHmac)) { return ['valid' => false, 'executeAllowed' => false, 'decision' => null, 'reason' => 'action_mismatch']; } $expectedSig = hash_hmac('sha256', self::decisionPayload($gateId, $actionHmac, $decision, $issuedAt, $nonce), $sec); if (!hash_equals($expectedSig, $sig)) { return ['valid' => false, 'executeAllowed' => false, 'decision' => null, 'reason' => 'bad_signature']; } return [ 'valid' => true, 'executeAllowed' => ($decision === 'approved'), 'decision' => $decision, 'reason' => ($decision === 'approved') ? 'approved_ok' : 'explicitly_rejected', ]; } /** * Offline 6-vector Art. 14 human-oversight self-test using an ephemeral random 32-byte key (0 network calls). * * @return array */ public static function runGateSelfTest(string $domain = 'yourdomain.eu'): array { $cleanDomain = self::sanitizePublicHost($domain) ?? 'yourdomain.eu'; $ephemeralSecret = bin2hex(random_bytes(32)); $now = 1764200000; $ctx = ['amount_eur' => 250, 'invoice_id' => 'inv_8841']; $links = self::createSignedApprovalLinks( 'https://api.' . $cleanDomain . '/spurvik/callback', 'gate_refund_01', 'stripe.refunds.create', $ctx, $ephemeralSecret, $now, 'nonce_php_01' ); $expectedAction = $links['actionHmac']; $v1Reject = self::verifySignedCallback($links['rejectUrl'], $expectedAction, $ephemeralSecret, 3600, $now + 10); $tamperedDecision = str_replace('decision=rejected', 'decision=approved', $links['rejectUrl']); $v2Tampered = self::verifySignedCallback($tamperedDecision, $expectedAction, $ephemeralSecret, 3600, $now + 10); $v3Expired = self::verifySignedCallback($links['approveUrl'], $expectedAction, $ephemeralSecret, 3600, $now + 7200); $otherAction = self::computeActionHmac('gate_refund_01', 'stripe.refunds.create', ['amount_eur' => 9999, 'invoice_id' => 'inv_8841'], $ephemeralSecret); $v4Replay = self::verifySignedCallback($links['approveUrl'], $otherAction, $ephemeralSecret, 3600, $now + 10); $v5WrongKey = self::verifySignedCallback($links['approveUrl'], $expectedAction, bin2hex(random_bytes(32)), 3600, $now + 10); $v6Approved = self::verifySignedCallback($links['approveUrl'], $expectedAction, $ephemeralSecret, 3600, $now + 10); $vectors = [ ['id' => 'explicit_reject_blocked', 'blocked' => !$v1Reject['executeAllowed'], 'reason' => $v1Reject['reason']], ['id' => 'tampered_decision_blocked', 'blocked' => !$v2Tampered['executeAllowed'], 'reason' => $v2Tampered['reason']], ['id' => 'expired_link_blocked', 'blocked' => !$v3Expired['executeAllowed'], 'reason' => $v3Expired['reason']], ['id' => 'payload_escalation_blocked', 'blocked' => !$v4Replay['executeAllowed'], 'reason' => $v4Replay['reason']], ['id' => 'forged_secret_blocked', 'blocked' => !$v5WrongKey['executeAllowed'], 'reason' => $v5WrongKey['reason']], ['id' => 'valid_human_approval_allowed', 'allowed' => $v6Approved['executeAllowed'], 'reason' => $v6Approved['reason']], ]; $allPassed = !$v1Reject['executeAllowed'] && !$v2Tampered['executeAllowed'] && !$v3Expired['executeAllowed'] && !$v4Replay['executeAllowed'] && !$v5WrongKey['executeAllowed'] && $v6Approved['executeAllowed']; $enc = rawurlencode($cleanDomain); return [ 'ok' => $allPassed, 'runtime' => 'php-' . PHP_VERSION, 'helperVersion' => self::VERSION, 'domain' => $cleanDomain, 'vectorsPassed' => $allPassed ? 6 : 0, 'vectorsTotal' => 6, 'vectors' => $vectors, 'plans' => [ 'proMonthlyEur19' => self::CONSOLE_BASE_URL . '/signup?plan=pro&interval=monthly&appUrl=' . $enc, 'proAnnualEur190' => self::CONSOLE_BASE_URL . '/signup?plan=pro&interval=annual&appUrl=' . $enc, 'teamMonthlyEur79' => self::CONSOLE_BASE_URL . '/signup?plan=team&interval=monthly&appUrl=' . $enc, 'teamAnnualEur790' => self::CONSOLE_BASE_URL . '/signup?plan=team&interval=annual&appUrl=' . $enc, 'doneForYouEur199' => self::CONSOLE_BASE_URL . '/signup?plan=concierge&appUrl=' . $enc, 'freeEur0' => self::CONSOLE_BASE_URL . '/signup?plan=free&appUrl=' . $enc, ], ]; } private static function resolveHashSecret(?string $secret): string { $raw = $secret ?? (getenv('SPURVIK_CONTENT_HASH_SECRET') ?: ($_ENV['SPURVIK_CONTENT_HASH_SECRET'] ?? '')); if (!is_string($raw) || strlen($raw) < 16) { throw new \InvalidArgumentException('SPURVIK_CONTENT_HASH_SECRET must be at least 16 UTF-8 bytes.'); } return $raw; } private static function resolveSigningSecret(?string $signingSecret): string { $raw = $signingSecret ?? (getenv('SPURVIK_SIGNING_SECRET') ?: ($_ENV['SPURVIK_SIGNING_SECRET'] ?? (getenv('SPURVIK_CONTENT_HASH_SECRET') ?: ($_ENV['SPURVIK_CONTENT_HASH_SECRET'] ?? '')))); if (!is_string($raw) || $raw === '') { throw new \InvalidArgumentException('SPURVIK_SIGNING_SECRET is missing.'); } if ($raw !== trim($raw)) { throw new \InvalidArgumentException('SPURVIK_SIGNING_SECRET must not have leading or trailing whitespace.'); } if (strlen($raw) < 16) { throw new \InvalidArgumentException('SPURVIK_SIGNING_SECRET must be at least 16 characters.'); } return $raw; } /** * @param list $keys */ private static function encodeSummaryDoc(array $keys, ?string $fp): string { $doc = [ 'contentFingerprint' => $fp, 'keys' => array_values($keys), 'schema' => self::PAYLOAD_SUMMARY_SCHEMA, ]; return (string) json_encode($doc, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); } private static function decisionPayload( string $gateId, string $actionHmac, string $decision, int $issuedAtUnix, ?string $nonce ): string { $base = sprintf('spurvik:art14:decision:v1|%s|%s|%s|%d', $gateId, $actionHmac, $decision, $issuedAtUnix); return ($nonce !== null && $nonce !== '') ? ($base . '|' . $nonce) : $base; } private static function uuidV4(): string { $bytes = random_bytes(16); $bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40); $bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); } private static function sanitizePublicHost(string $raw): ?string { $trimmed = strtolower(trim($raw)); if ($trimmed === '' || strlen($trimmed) > 253 || str_contains($trimmed, '@')) { return null; } $candidate = preg_match('#^https?://#', $trimmed) === 1 ? (string) parse_url($trimmed, PHP_URL_HOST) : $trimmed; $candidate = rtrim($candidate, '.'); if (preg_match('/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/', $candidate) !== 1) { return null; } if (preg_match('/(?:^|\.)(?:localhost|local|internal|test|invalid|example)$/', $candidate) === 1) { return null; } return $candidate; } /** * @param array $body * @return array */ private static function postJson( string $path, array $body, ?string $apiKey, string $baseUrl ): array { $token = trim((string) ($apiKey ?? (getenv('SPURVIK_API_KEY') ?: ($_ENV['SPURVIK_API_KEY'] ?? '')))); if ($token === '') { throw new \InvalidArgumentException( 'SPURVIK_API_KEY is missing. Activate a workspace at https://console.spurvik.com/signup?plan=pro' ); } $url = rtrim($baseUrl, '/') . $path; if (!str_starts_with($url, 'https://') && !str_starts_with($url, 'http://localhost')) { throw new \InvalidArgumentException('Spurvik baseUrl must use https:// (or http://localhost in local tests).'); } $payload = (string) json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json', 'Accept: application/json', 'User-Agent: spurvik-php/' . self::VERSION, ]; if (function_exists('curl_init')) { $ch = curl_init($url); if ($ch === false) { throw new \RuntimeException('Failed to initialize cURL for Spurvik request.'); } curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 5, ]); $raw = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (!is_string($raw) || $status < 200 || $status >= 300) { throw new \RuntimeException('Spurvik API returned HTTP ' . $status); } /** @var array $decoded */ $decoded = $raw !== '' ? json_decode($raw, true, 16, JSON_THROW_ON_ERROR) : []; return $decoded; } $ctx = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => implode("\r\n", $headers), 'content' => $payload, 'timeout' => 5.0, 'ignore_errors' => true, ], ]); $raw = file_get_contents($url, false, $ctx); if (!is_string($raw)) { throw new \RuntimeException('Spurvik HTTP request failed.'); } /** @var array $decoded */ $decoded = $raw !== '' ? json_decode($raw, true, 16, JSON_THROW_ON_ERROR) : []; return $decoded; } } if (PHP_SAPI === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) { $args = array_slice($argv, 1); $jsonOut = in_array('--json', $args, true); $positional = array_values(array_filter($args, static fn(string $a): bool => !str_starts_with($a, '-'))); $targetDomain = $positional[0] ?? 'yourdomain.eu'; $report = SpurvikGuard::runGateSelfTest($targetDomain); if ($jsonOut) { fwrite(STDOUT, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL); } else { fwrite(STDOUT, sprintf("Spurvik PHP Guard v%s — Art. 14 Cryptographic Blocking Check (%s)\n", SpurvikGuard::VERSION, $report['domain'])); fwrite(STDOUT, sprintf(" Result: %d/%d adversarial & approval vectors passed (0 network calls)\n", $report['vectorsPassed'], $report['vectorsTotal'])); fwrite(STDOUT, sprintf(" Pro White-Label (EUR 19/mo · EUR 190/yr): %s\n", $report['plans']['proMonthlyEur19'])); fwrite(STDOUT, sprintf(" Team + Annex IV (EUR 79/mo · EUR 790/yr): %s\n", $report['plans']['teamMonthlyEur79'])); fwrite(STDOUT, sprintf(" 24h Engineer Setup (EUR 199 once): %s\n", $report['plans']['doneForYouEur199'])); } exit($report['ok'] ? 0 : 1); }