How to bootstrap a custom script and retrieve the session object?
This is the code I came up with in the end. It works.

Feel free to suggest a more concise version :-)

&lt;?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = realpath(__DIR__ . '/../');
$autoloader = require_once $drupal_root . '/autoload.php';

// Make sure Drupal operates correct when handle request instead of internal server error and twig error
chdir($drupal_root);

$kernel = new DrupalKernel('prod', $autoloader);

// Note: The session_name is generated from the string "{domain}/{script basepath}".
// Need to override the script filename and script name before creating request.
$_SERVER['SCRIPT_FILENAME'] = $drupal_root . '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$request = Request::createFromGlobals();
// Note: may restore script_name and script_filename after this line.

// This handle process would chain up and initialize all services
// in container, include the session handler.
$kernel-&gt;handle($request);

// now we can use session normally
$session_handler = \Drupal::getContainer()-&gt;get('session_handler.storage');
$session_id = $session_handler-&gt;getId();
$logged_in = (bool) $session_handler-&gt;read($session_id);

// restore app
chdir(__DIR__);