linkUrl('https://example.com/fms-callback.php', $_SESSION['fms_state'], $username)); * * // 2. On fms-callback.php: * if (!hash_equals($_SESSION['fms_state'] ?? '', $_GET['state'] ?? '')) exit('Bad state'); * if (isset($_GET['code'])) { $link = $fms->exchange($_GET['code']); save $link['link_token'] on the user; } * * // 3. At login, after the password is correct and before your 2FA: * $r = $fms->check($user['fms_link_token'], $_SERVER['REMOTE_ADDR']); * if (!$r['linked']) -> the user unlinked; clear the stored token and continue normally * elseif (!$r['allowed']) -> refuse the login * * Always pass $_SERVER['REMOTE_ADDR'] (or your trusted proxy's real-client header), never * X-Forwarded-For straight from the request: anyone can type that header. */ class FollowMeSecurity { private $siteId; private $secret; private $baseUrl; private $timeout; private $cacheFile; public function __construct(string $siteId, string $secret, array $options = []) { $this->siteId = $siteId; $this->secret = $secret; $this->baseUrl = rtrim($options['base_url'] ?? 'https://followmesecurity.com', '/'); $this->timeout = (float)($options['timeout'] ?? 3); $dir = $options['cache_dir'] ?? sys_get_temp_dir(); $this->cacheFile = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR . 'fms_' . preg_replace('/[^a-z0-9_]/i', '', $siteId) . '.json'; } /** Builds a client from the one-line connection key shown on your site's page in Follow Me Security. */ public static function fromKey(string $key, array $options = []): self { $key = trim($key); $json = strpos($key, 'fms1_') === 0 ? base64_decode(strtr(substr($key, 5), '-_', '+/'), true) : false; $d = $json !== false ? json_decode($json, true) : null; if (!is_array($d) || empty($d['s']) || empty($d['k']) || empty($d['u'])) throw new InvalidArgumentException('Not a valid Follow Me Security connection key.'); return new self($d['s'], $d['k'], $options + ['base_url' => $d['u']]); } public function siteId(): string { return $this->siteId; } public static function newState(): string { return bin2hex(random_bytes(16)); } /** Where to send a signed-in user to link their account. $ref is shown to them (e.g. their username here). */ public function linkUrl(string $redirectUri, string $state, string $ref = ''): string { return $this->baseUrl . '/link.php?' . http_build_query(['site' => $this->siteId, 'redirect_uri' => $redirectUri, 'state' => $state, 'ref' => $ref]); } /** Swaps the one-time ?code= for a permanent link token. Returns ['link_token' => ..., 'email' => ...]. */ public function exchange(string $code): array { $r = $this->call('POST', '/api/v1/link/exchange', ['code' => $code]); if (empty($r['link_token'])) throw new RuntimeException('Follow Me Security: ' . ($r['message'] ?? 'link failed')); return $r; } /** * Asks whether a login from $ip is allowed. Never throws. Returns: * allowed (bool), linked (bool), reason (string), reachable (bool) * If Follow Me Security can't be reached, allowed follows your site's "allow logins if * Follow Me Security can't be reached" setting (remembered from the last good answer; deny if unknown). */ public function check(string $linkToken, string $ip): array { try { $r = $this->call('POST', '/api/v1/check', ['link_token' => $linkToken, 'ip' => $ip]); if (!isset($r['result'])) throw new RuntimeException($r['message'] ?? 'bad response'); $this->remember((bool)($r['fallback_allow'] ?? false)); return ['allowed' => $r['result'] === 'allow', 'linked' => (bool)($r['linked'] ?? true), 'reason' => (string)$r['reason'], 'reachable' => true]; } catch (Throwable $e) { error_log('[FollowMeSecurity] check failed: ' . $e->getMessage()); return ['allowed' => $this->fallback(), 'linked' => true, 'reason' => 'fms_unreachable', 'reachable' => false]; } } /** Removes the link from your side (e.g. the user clicked "Unlink" in your settings). */ public function unlink(string $linkToken): void { $this->call('POST', '/api/v1/unlink', ['link_token' => $linkToken]); } /** Names of your site's allowed IPs in Follow Me Security: ['ips' => [['label' =>, 'type' =>], ...], ...]. The IPs themselves are never readable. */ public function allowlist(): array { return $this->call('GET', '/api/v1/site/allowlist'); } private function call(string $method, string $path, ?array $data = null): array { $body = $data === null ? '' : json_encode($data); $ts = (string)time(); $sig = hash_hmac('sha256', $ts . '.' . $method . '.' . $path . '.' . $body, $this->secret); $ch = curl_init($this->baseUrl . $path); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT_MS => (int)($this->timeout * 1000), CURLOPT_TIMEOUT_MS => (int)($this->timeout * 1000), CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-FMS-Site: ' . $this->siteId, 'X-FMS-Timestamp: ' . $ts, 'X-FMS-Signature: ' . $sig], ]); if ($body !== '') curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $res = curl_exec($ch); $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); $err = curl_error($ch); curl_close($ch); if ($res === false) throw new RuntimeException('connection failed: ' . $err); $json = json_decode($res, true); if (!is_array($json)) throw new RuntimeException('bad response (HTTP ' . $status . ')'); if ($status >= 500 || in_array($status, [401, 429], true)) throw new RuntimeException(($json['error'] ?? 'error') . ': ' . ($json['message'] ?? '')); return $json; } private function remember(bool $fallbackAllow): void { @file_put_contents($this->cacheFile, json_encode(['fallback_allow' => $fallbackAllow, 'at' => time()]), LOCK_EX); } private function fallback(): bool { $c = @json_decode((string)@file_get_contents($this->cacheFile), true); return !empty($c['fallback_allow']); } }