allow( 'webhook|' . $ipBucket, self::IP_LIMIT, self::WINDOW ) && $limiter->allow( 'webhook|*global*', self::GLOBAL_LIMIT, self::WINDOW ); } /** Lower-cases header names and maps '-' to '_'. @param array $headers @return array */ public static function normalizeHeaders( array $headers ): array { $h = array(); foreach ( $headers as $k => $v ) { $h[ strtolower( str_replace( '-', '_', (string) $k ) ) ] = is_array( $v ) ? (string) ( $v[0] ?? '' ) : (string) $v; } return $h; } /** * @param array $headers * @return array{status:int,code:string}|null Null when the request may be sent on to PayPal for verification. */ public static function check( array $headers, string $rawBody, int $now ): ?array { if ( strlen( $rawBody ) > self::MAX_BODY_BYTES ) { return array( 'status' => 413, 'code' => 'sg_webhook_too_large' ); } $h = self::normalizeHeaders( $headers ); foreach ( self::REQUIRED as $n ) { if ( '' === trim( $h[ $n ] ?? '' ) ) { return array( 'status' => 401, 'code' => 'sg_webhook_headers' ); } } if ( ! self::isPayPalCertUrl( $h['paypal_cert_url'] ) ) { return array( 'status' => 401, 'code' => 'sg_webhook_cert_url' ); } if ( ! self::timeWithinWindow( $h['paypal_transmission_time'], $now ) ) { return array( 'status' => 401, 'code' => 'sg_webhook_time' ); } return null; } /** https, no credentials/odd port, host is paypal.com or a subdomain of it. */ public static function isPayPalCertUrl( string $url ): bool { $p = parse_url( trim( $url ) ); if ( ! is_array( $p ) || 'https' !== strtolower( (string) ( $p['scheme'] ?? '' ) ) || isset( $p['user'] ) || isset( $p['pass'] ) ) { return false; } if ( isset( $p['port'] ) && 443 !== (int) $p['port'] ) { return false; } $host = strtolower( (string) ( $p['host'] ?? '' ) ); return 'paypal.com' === $host || ( strlen( $host ) > 11 && str_ends_with( $host, '.paypal.com' ) ); } /** ISO-8601 timestamp within +-MAX_SKEW_SECONDS of $now; unparsable is rejected. */ public static function timeWithinWindow( string $iso, int $now ): bool { $iso = trim( $iso ); if ( 1 !== preg_match( '/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/', $iso ) ) { return false; } $t = strtotime( $iso ); return false !== $t && abs( $now - $t ) <= self::MAX_SKEW_SECONDS; } }