winzik/tools/embed/jumphp-embed.php

492 lines
22 KiB
PHP

<?php
/**
* JumPHP embed kit: show an application of a JumPHP playground (https://jumphp.net) on your own site, as your own pages: no iframe, no
* CORS, the HTML is yours for the search engines (docs/embed.md, docs/embed.en.md). One file, PHP 7.4+ with curl, no dependency.
*
* The playground's owner of the application declares your site in its studio (domain, base path) and gives you an identifier and a secret.
* This file then:
* - serves the application under your base path (/chat/ -> the play page, /chat/engine/... /chat/files/... everything it loads), relayed
* from the playground with signed requests, big files streamed (Range, gzip passed through), immutable files kept on disk;
* - relays the page's TCP tickets (/chat/api/tcp/ticket) with the visitor's address;
* - gives you the application's blocks (HTML fragments: a login form...) to print in your pages, kept on disk and revalidated (ETag).
*
* Settings: an array given to JumphpEmbed::fromConfig(), or the environment (JUMPHP_EMBED_*):
* server JUMPHP_EMBED_SERVER https://jumphp.net
* app JUMPHP_EMBED_APP the application's slug on the playground (caramail-chat)
* site JUMPHP_EMBED_SITE your site's identifier (es_...)
* secret JUMPHP_EMBED_SECRET your site's secret (jes_...): keep it out of any public file and of git
* base JUMPHP_EMBED_BASE the base path you declared (/chat)
* cache JUMPHP_EMBED_CACHE a writable folder for the cache (default: the system's temporary folder)
* ttl JUMPHP_EMBED_TTL seconds a block is used before it is asked again (default 300)
* cache_mb JUMPHP_EMBED_CACHE_MB the most the kept files may take on disk, in MB (default 1024; the oldest go first)
*
* As the front controller of the base path (nginx / Caddy / Apache send every /chat/... request to this file, docs/embed.md):
* php: require 'jumphp-embed.php'; JumphpEmbed::fromConfig([...])->serve(); or run this file directly with the environment set
* As a library, in your pages:
* echo JumphpEmbed::fromConfig([...])->block('login');
*/
final class JumphpEmbed
{
const VERSION = '1.0.0';
/** files bigger than this are streamed and not kept on disk */
const MAX_CACHED_FILE = 67108864;
/** what is passed back of the playground's answers (nothing else: no cookie, no robots header of the playground) */
const RESPONSE_HEADERS = ['content-type', 'content-length', 'content-encoding', 'content-range', 'accept-ranges', 'etag', 'last-modified',
'cache-control', 'vary', 'cross-origin-opener-policy', 'cross-origin-embedder-policy', 'document-isolation-policy', 'content-security-policy'];
/** @var array<string, mixed> */
private $config;
/** @param array<string, mixed> $config */
public function __construct(array $config)
{
foreach (['server', 'app', 'site', 'secret', 'base'] as $key) {
if (!isset($config[$key]) || !is_string($config[$key]) || $config[$key] === '') {
throw new InvalidArgumentException("jumphp-embed: the setting \"$key\" is missing (JUMPHP_EMBED_" . strtoupper($key) . ')');
}
}
$config['server'] = rtrim($config['server'], '/');
$config['base'] = '/' . trim($config['base'], '/');
$config['cache'] = rtrim((string)($config['cache'] ?? (sys_get_temp_dir() . '/jumphp-embed')), '/');
$config['ttl'] = (int)($config['ttl'] ?? 300);
$config['cache_mb'] = max(16, (int)($config['cache_mb'] ?? 1024));
$this->config = $config;
}
/** the settings given, over the environment's JUMPHP_EMBED_* */
public static function fromConfig(array $config = []): self
{
$env = [];
foreach (['server', 'app', 'site', 'secret', 'base', 'cache', 'ttl', 'cache_mb'] as $key) {
$value = getenv('JUMPHP_EMBED_' . strtoupper($key));
if ($value !== false && $value !== '') {
$env[$key] = $value;
}
}
return new self($config + $env + ['server' => 'https://jumphp.net']);
}
/** the signature headers of a request (the playground's App\Service\EmbedSignature) */
public static function signature(string $secret, string $site, string $method, string $path, string $query, string $body, ?int $time = null): array
{
$time = (string)($time ?? time());
$canonical = strtoupper($method) . "\n" . $path . "\n" . $query . "\n" . $time . "\n" . hash('sha256', $body);
return ['X-JumPHP-Site' => $site, 'X-JumPHP-Time' => $time, 'X-JumPHP-Signature' => hash_hmac('sha256', $canonical, $secret)];
}
/** the playground's address of $relative (a path under the API, already percent-encoded) */
private function apiPath(string $relative): string
{
return '/api/embed/' . rawurlencode($this->config['app']) . '/' . ltrim($relative, '/');
}
// ---------------------------------------------------------------- blocks
/**
* A block of the application (its site/blocks/<name>.html, {{BASE}} = your base address): from the disk while fresh, revalidated with
* its ETag after `ttl` seconds; when the playground does not answer, the last copy (or '' the first time). Never throws.
*/
public function block(string $name): string
{
if (!preg_match('/^[a-z0-9][a-z0-9_-]{0,40}$/', $name)) {
return '';
}
$file = $this->cacheFile('block-' . $name, 'html');
$meta = is_file("$file.json") ? (json_decode((string)@file_get_contents("$file.json"), true) ?: []) : [];
$cached = is_file($file) ? (string)@file_get_contents($file) : null;
if ($cached !== null && isset($meta['at']) && time() - (int)$meta['at'] < $this->config['ttl']) {
return $cached;
}
$headers = $cached !== null && !empty($meta['etag']) ? ['If-None-Match: ' . $meta['etag']] : [];
$answer = $this->fetch('GET', $this->apiPath('block/' . rawurlencode($name)), '', '', $headers);
if ($answer !== null && $answer['status'] === 304 && $cached !== null) {
$this->writeAtomic("$file.json", (string)json_encode(['at' => time(), 'etag' => $meta['etag']]));
return $cached;
}
if ($answer !== null && $answer['status'] === 200) {
$this->writeAtomic($file, $answer['body']);
$this->writeAtomic("$file.json", (string)json_encode(['at' => time(), 'etag' => $answer['headers']['etag'] ?? '']));
return $answer['body'];
}
if ($answer !== null && $answer['status'] !== 200) {
error_log('jumphp-embed: block ' . $name . ': HTTP ' . $answer['status'] . ' ' . substr($answer['body'], 0, 300));
}
return $cached ?? '';
}
// ---------------------------------------------------------------- the application under the base path
/**
* Answers the current request when its path is under the base path (true), else does nothing (false: your site goes on). Call it before
* anything is printed.
*/
public function serve(): bool
{
$uri = (string)($_SERVER['REQUEST_URI'] ?? '/');
$path = (string)parse_url($uri, PHP_URL_PATH);
$query = (string)(parse_url($uri, PHP_URL_QUERY) ?? '');
$base = $this->config['base'];
if ($path !== $base && strpos($path, $base . '/') !== 0) {
return false;
}
$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
// /chat -> /chat/: the page's relative addresses need the slash
if ($path === $base) {
$this->status(301);
header('Location: ' . $base . '/' . ($query !== '' ? "?$query" : ''));
return true;
}
$relative = substr($path, strlen($base) + 1);
if (preg_match('#(^|/)\.\.?(/|$)#', rawurldecode($relative))) {
$this->status(400);
return true;
}
$this->securityHeaders();
if ($relative === 'api/tcp/ticket' || $relative === 'api/runtime/wake') {
if ($method !== 'POST') {
$this->status(405);
return true;
}
$body = (string)file_get_contents('php://input', false, null, 0, 65536);
$answer = $this->fetch('POST', $this->apiPath($relative === 'api/tcp/ticket' ? 'tcp/ticket' : 'runtime/wake'), '', $body,
['Content-Type: application/json', 'X-JumPHP-Client-IP: ' . $this->clientIp()]);
$this->sendAnswer($answer);
return true;
}
if (!in_array($method, ['GET', 'HEAD', 'POST'], true) || ($method === 'POST' && $relative !== '')) {
$this->status(405);
return true;
}
$apiPath = $this->apiPath('app/' . $relative);
if ($method === 'POST') {
// the page itself, from a form sent with POST: its fields go to the playground as they came
$body = (string)file_get_contents('php://input', false, null, 0, 65536);
$type = (string)($_SERVER['CONTENT_TYPE'] ?? 'application/x-www-form-urlencoded');
$this->sendAnswer($this->fetch('POST', $apiPath, $query, $body, ['Content-Type: ' . $type]));
return true;
}
// files whose address names their version (?v=..., the engine's folder): kept on disk, served from it
$immutable = $relative !== 'manifest.json' && (preg_match('/(^|&)v=[0-9a-f]{6,64}(&|$)/', $query) || preg_match('#^engine/\d+\.\d+\.\d+[^/]*/#', $relative));
if ($immutable && $method === 'GET' && $this->serveCached($apiPath, $query)) {
return true;
}
$this->stream($method, $apiPath, $query, $immutable);
return true;
}
/** a file kept on disk, answered with its headers (and a Range) */
private function serveCached(string $apiPath, string $query): bool
{
$file = $this->cacheFile('file-' . hash('sha256', $apiPath . '?' . $query), 'bin');
if (!is_file($file) || !is_file("$file.json")) {
return false;
}
$meta = json_decode((string)@file_get_contents("$file.json"), true);
if (!is_array($meta)) {
return false;
}
$size = (int)filesize($file);
if (!empty($meta['encoding']) && stripos((string)($_SERVER['HTTP_ACCEPT_ENCODING'] ?? ''), (string)$meta['encoding']) === false) {
return false; // kept compressed, the visitor does not take it so: asked again
}
$etag = (string)($meta['etag'] ?? '');
if ($etag !== '' && trim((string)($_SERVER['HTTP_IF_NONE_MATCH'] ?? '')) === $etag) {
$this->status(304);
header("ETag: $etag");
return true;
}
$start = 0;
$end = $size - 1;
$range = (string)($_SERVER['HTTP_RANGE'] ?? '');
if ($range !== '' && empty($meta['encoding'])) {
if (!preg_match('/^bytes=(\d*)-(\d*)$/', $range, $m) || ($m[1] === '' && $m[2] === '')) {
$this->status(416);
header("Content-Range: bytes */$size");
return true;
}
if ($m[1] === '') {
$start = max(0, $size - (int)$m[2]);
} else {
$start = (int)$m[1];
$end = $m[2] === '' ? $size - 1 : min((int)$m[2], $size - 1);
}
if ($start > $end || $start >= $size) {
$this->status(416);
header("Content-Range: bytes */$size");
return true;
}
$this->status(206);
header("Content-Range: bytes $start-$end/$size");
}
header('Content-Type: ' . ($meta['type'] ?? 'application/octet-stream'));
header('Cache-Control: ' . ($meta['cache'] ?? 'public, max-age=31536000, immutable'));
header('Accept-Ranges: ' . (empty($meta['encoding']) ? 'bytes' : 'none'));
if (!empty($meta['encoding'])) {
header('Content-Encoding: ' . $meta['encoding']);
header('Vary: Accept-Encoding');
}
if ($etag !== '') {
header("ETag: $etag");
}
header('Content-Length: ' . ($end - $start + 1));
if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) === 'HEAD') {
return true;
}
$in = fopen($file, 'rb');
fseek($in, $start);
$left = $end - $start + 1;
while ($left > 0 && !feof($in)) {
$chunk = (string)fread($in, (int)min(65536, $left));
echo $chunk;
$left -= strlen($chunk);
flush();
}
fclose($in);
return true;
}
/** the playground's answer streamed to the visitor as it comes (and kept on disk when it is an immutable file) */
private function stream(string $method, string $apiPath, string $query, bool $keep): void
{
$headers = [];
foreach (['HTTP_RANGE' => 'Range', 'HTTP_IF_NONE_MATCH' => 'If-None-Match', 'HTTP_IF_MODIFIED_SINCE' => 'If-Modified-Since'] as $server => $name) {
if (!empty($_SERVER[$server])) {
$headers[] = "$name: " . $_SERVER[$server];
}
}
$gzip = stripos((string)($_SERVER['HTTP_ACCEPT_ENCODING'] ?? ''), 'gzip') !== false;
$headers[] = 'Accept-Encoding: ' . ($gzip ? 'gzip' : 'identity');
$keep = $keep && empty($_SERVER['HTTP_RANGE']) && $method === 'GET';
$tmp = null;
$out = null;
if ($keep && $this->ensureCacheDir()) {
$tmp = $this->cacheFile('file-' . hash('sha256', $apiPath . '?' . $query), 'bin') . '.tmp-' . bin2hex(random_bytes(4));
$out = @fopen($tmp, 'wb');
}
$received = [];
$status = 0;
$written = 0;
$sent = false;
$sendHeaders = function () use (&$received, &$status, &$sent) {
if ($sent) {
return;
}
$sent = true;
$this->status($status ?: 502);
foreach ($received as $name => $value) {
if (in_array($name, self::RESPONSE_HEADERS, true)) {
header(ucwords($name, '-') . ': ' . $value);
}
}
};
$ch = $this->curl($method, $apiPath, $query, '', $headers);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $line) use (&$received, &$status) {
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $line, $m)) {
$status = (int)$m[1];
$received = [];
} elseif (strpos($line, ':') !== false) {
[$name, $value] = explode(':', $line, 2);
$received[strtolower(trim($name))] = trim($value);
}
return strlen($line);
});
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $data) use (&$out, &$written, $sendHeaders, $method) {
$sendHeaders();
if ($out) {
$written += strlen($data);
if ($written > self::MAX_CACHED_FILE) {
fclose($out);
$out = null;
} else {
fwrite($out, $data);
}
}
if ($method !== 'HEAD') {
echo $data;
flush();
}
return strlen($data);
});
$ok = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($ok === false && !$sent) {
error_log("jumphp-embed: $apiPath: $error");
$this->status(502);
header('Content-Type: text/plain; charset=utf-8');
echo 'The application does not answer for now.';
} else {
$sendHeaders();
}
if ($out) {
fclose($out);
if ($ok !== false && $status === 200 && strpos((string)($received['cache-control'] ?? ''), 'immutable') !== false) {
$file = substr($tmp, 0, (int)strrpos($tmp, '.tmp-'));
@rename($tmp, $file);
$this->writeAtomic("$file.json", (string)json_encode(['type' => $received['content-type'] ?? 'application/octet-stream',
'cache' => $received['cache-control'], 'etag' => $received['etag'] ?? '', 'encoding' => $received['content-encoding'] ?? '']));
$this->pruneCache();
}
}
if ($tmp && is_file($tmp)) {
@unlink($tmp);
}
}
// ---------------------------------------------------------------- HTTP
/** @return resource|\CurlHandle */
private function curl(string $method, string $apiPath, string $query, string $body, array $headers)
{
$url = $this->config['server'] . $apiPath . ($query !== '' ? "?$query" : '');
foreach (self::signature($this->config['secret'], $this->config['site'], $method, $apiPath, $query, $body) as $name => $value) {
$headers[] = "$name: $value";
}
$headers[] = 'User-Agent: jumphp-embed/' . self::VERSION;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 300,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_NOBODY => $method === 'HEAD',
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
return $ch;
}
/** @return array{status: int, headers: array<string, string>, body: string}|null a whole answer (small ones: blocks, tickets), null = no answer */
private function fetch(string $method, string $apiPath, string $query, string $body, array $headers = []): ?array
{
$ch = $this->curl($method, $apiPath, $query, $body, $headers);
$received = [];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $line) use (&$received) {
if (strpos($line, ':') !== false) {
[$name, $value] = explode(':', $line, 2);
$received[strtolower(trim($name))] = trim($value);
}
return strlen($line);
});
$content = curl_exec($ch);
$status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($content === false) {
error_log("jumphp-embed: $apiPath: $error");
return null;
}
return ['status' => $status, 'headers' => $received, 'body' => (string)$content];
}
/** @param array{status: int, headers: array<string, string>, body: string}|null $answer */
private function sendAnswer(?array $answer): void
{
if ($answer === null) {
$this->status(502);
header('Content-Type: application/json');
echo '{"error":"the application does not answer for now"}';
return;
}
$this->status($answer['status']);
foreach ($answer['headers'] as $name => $value) {
if (in_array($name, self::RESPONSE_HEADERS, true) && $name !== 'content-length' && $name !== 'content-encoding') {
header(ucwords($name, '-') . ': ' . $value);
}
}
echo $answer['body'];
}
/** the visitor's address; behind your own proxy, set $_SERVER['REMOTE_ADDR'] to the real one before calling serve() */
private function clientIp(): string
{
$ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
return filter_var($ip, FILTER_VALIDATE_IP) !== false ? $ip : '';
}
private function securityHeaders(): void
{
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('X-Frame-Options: SAMEORIGIN');
}
private function status(int $code): void
{
if (!headers_sent()) {
http_response_code($code);
}
}
// ---------------------------------------------------------------- disk cache
private function ensureCacheDir(): bool
{
$dir = $this->config['cache'];
return is_dir($dir) || @mkdir($dir, 0700, true) || is_dir($dir);
}
private function cacheFile(string $key, string $extension): string
{
return $this->config['cache'] . '/' . preg_replace('/[^a-z0-9_.-]/i', '_', $this->config['app']) . '-' . $key . '.' . $extension;
}
/**
* Keeps the files on disk under cache_mb: the least recently written go first. Any visitor can make this file fetch an address with a new
* ?v=..., so without a limit the disk could be filled.
*/
private function pruneCache(): void
{
$files = glob($this->config['cache'] . '/*-file-*.bin') ?: [];
$total = 0;
$list = [];
foreach ($files as $f) {
$size = (int)@filesize($f);
$total += $size;
$list[] = [(int)@filemtime($f), $size, $f];
}
$max = $this->config['cache_mb'] * 1048576;
if ($total <= $max) {
return;
}
sort($list);
foreach ($list as [, $size, $f]) {
@unlink($f);
@unlink("$f.json");
$total -= $size;
if ($total <= $max * 0.8) {
break;
}
}
}
private function writeAtomic(string $file, string $content): void
{
if (!$this->ensureCacheDir()) {
return;
}
$tmp = $file . '.tmp-' . bin2hex(random_bytes(4));
if (@file_put_contents($tmp, $content) !== false) {
@rename($tmp, $file);
}
}
}
// run directly (php-fpm / php -S pointed at this file): the settings come from the environment
if (PHP_SAPI !== 'cli' && realpath((string)($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
try {
if (!JumphpEmbed::fromConfig()->serve()) {
http_response_code(404);
echo 'Not found';
}
} catch (InvalidArgumentException $e) {
http_response_code(500);
error_log($e->getMessage());
echo 'jumphp-embed is not configured.';
}
}