. * * The secret travels only inside this text, by hand; it is never sent over the network. Every request the * destination makes is signed with it (see Auth), so the source can tell a request came from whoever holds * the key without the secret crossing the wire again. * * The signature on the key itself is an integrity check, so a key damaged or edited in the clipboard is * refused up front with a clear message. It is not what protects the source: anyone holding a whole key * can sign. The protection is the key's short life, one-time use, the pinned address and the rate limit. */ final class ConnectionKey { public const PREFIX = 'omk1'; /** * @param string $site_url Source site address. * @param string $id Public identifier, 32 hex characters. * @param string $secret_hex The 32-byte secret as 64 hex characters. */ public static function encode( string $site_url, string $id, string $secret_hex, int $created ): string { $payload = (string) wp_json_encode( array( 'v' => 1, 'u' => $site_url, 'i' => $id, 's' => $secret_hex, 't' => $created, ), JSON_UNESCAPED_SLASHES ); return self::PREFIX . '.' . self::b64( $payload ) . '.' . self::b64( self::sign( $payload, $secret_hex ) ); } /** * @return array{url:string,id:string,secret:string,created:int}|null Null for anything that is not an intact key. */ public static function decode( string $key ): ?array { $parts = explode( '.', trim( $key ) ); if ( 3 !== count( $parts ) || self::PREFIX !== $parts[0] ) { return null; } $payload = self::unb64( $parts[1] ); $sig = self::unb64( $parts[2] ); $data = null === $payload ? null : json_decode( $payload, true ); if ( null === $sig || ! is_array( $data ) || 1 !== ( $data['v'] ?? null ) ) { return null; } $url = $data['u'] ?? null; $id = $data['i'] ?? null; $secret = $data['s'] ?? null; $created = $data['t'] ?? null; if ( ! is_string( $url ) || ! is_string( $id ) || ! is_string( $secret ) || ! is_int( $created ) ) { return null; } if ( 1 !== preg_match( '/^[a-f0-9]{32}$/', $id ) || 1 !== preg_match( '/^[a-f0-9]{64}$/', $secret ) || '' === $url || strlen( $url ) > 2000 ) { return null; } if ( ! hash_equals( self::sign( $payload, $secret ), $sig ) ) { return null; } return array( 'url' => $url, 'id' => $id, 'secret' => $secret, 'created' => $created, ); } private static function sign( string $payload, string $secret_hex ): string { return hash_hmac( 'sha256', 'migratex-key-v1|' . $payload, (string) hex2bin( $secret_hex ), true ); } private static function b64( string $raw ): string { return rtrim( strtr( base64_encode( $raw ), '+/', '-_' ), '=' ); } private static function unb64( string $text ): ?string { if ( 1 !== preg_match( '/^[A-Za-z0-9_-]+$/', $text ) ) { return null; } $raw = base64_decode( strtr( $text, '-_', '+/' ), true ); return false === $raw ? null : $raw; } }