server.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. /**
  3. * Statum frontend demo backend.
  4. *
  5. * Run from this directory with PHP's built-in server:
  6. *
  7. * php -S localhost:8000 server.php
  8. *
  9. * Then open http://localhost:8000/ in your browser.
  10. *
  11. * This is a DEMO only: there is no real signing or encryption. Snapshots are
  12. * wrapped in trivial frames, and per-item action context is carried in the
  13. * action's `private` blob as plain base64. State lives in the PHP session so
  14. * that actions are stateful across requests.
  15. */
  16. session_start();
  17. // Static product catalog used by the demo.
  18. $CATALOG = [
  19. ['id' => 1, 'name' => 'Widget', 'price' => 9.99, 'featured' => true, 'inStock' => true],
  20. ['id' => 2, 'name' => 'Gadget', 'price' => 19.99, 'featured' => false, 'inStock' => true],
  21. ['id' => 3, 'name' => 'Sprocket', 'price' => 4.50, 'featured' => false, 'inStock' => false],
  22. ['id' => 4, 'name' => 'Gizmo', 'price' => 29.99, 'featured' => true, 'inStock' => true],
  23. ];
  24. $TYPES = ['counter', 'products', 'cart', 'user', 'notice'];
  25. // ---------------------------------------------------------------------------
  26. // Helpers
  27. // ---------------------------------------------------------------------------
  28. /** Send a JSON array of Statum directives and stop. */
  29. function statum_respond(array $directives): void
  30. {
  31. header('Content-Type: application/vnd.statum+json');
  32. header('Cache-Control: no-store');
  33. echo json_encode($directives, JSON_PRETTY_PRINT);
  34. exit;
  35. }
  36. /** Wrap a snapshot in a trivial (unsigned) frame. */
  37. function frame(array $snapshot): array
  38. {
  39. return ['content' => json_encode($snapshot), 'signer' => 'demo', 'signature' => ''];
  40. }
  41. /** Stable per-type slot key, kept in the session. */
  42. function key_for(string $type): string
  43. {
  44. if (!isset($_SESSION['keys'][$type])) {
  45. $_SESSION['keys'][$type] = 'k_' . $type;
  46. }
  47. return $_SESSION['keys'][$type];
  48. }
  49. /**
  50. * Build a snapshot for a type. Options:
  51. * - `always`: transmit_after == as_at, so the client sends the base64 frame on
  52. * every request (the always-send path).
  53. * - `stale`: transmit_after is set 10s in the future (with a far-future
  54. * invalid_after). The slot is fresh for 10s, after which the client must
  55. * pre-flight via /_statum/slots before each request. Load the page, wait ~10s,
  56. * then trigger an action to see the pre-flight request.
  57. */
  58. function make_snapshot(string $type, string $scope, array $public, array $opts = []): array
  59. {
  60. $now = time();
  61. $asAt = gmdate('Y-m-d\TH:i:s\Z', $now);
  62. if (!empty($opts['always'])) {
  63. $transmit = $asAt;
  64. } elseif (!empty($opts['stale'])) {
  65. $transmit = gmdate('Y-m-d\TH:i:s\Z', $now + 10);
  66. } else {
  67. $transmit = gmdate('Y-m-d\TH:i:s\Z', $now + 60);
  68. }
  69. return [
  70. 'as_at' => $asAt,
  71. 'slot' => ['key' => key_for($type), 'scope' => $scope, 'type' => $type],
  72. 'transmit_after' => $transmit,
  73. 'invalid_after' => gmdate('Y-m-d\TH:i:s\Z', $now + 600),
  74. 'private' => $opts['private'] ?? '',
  75. 'public' => $public,
  76. ];
  77. }
  78. function set_dir(array $snapshot): array
  79. {
  80. return ['type' => 'set', 'snapshot_frame' => frame($snapshot)];
  81. }
  82. function clear_dir(string $key): array
  83. {
  84. return ['type' => 'clear', 'key' => $key];
  85. }
  86. function product_by_id($id): ?array
  87. {
  88. global $CATALOG;
  89. foreach ($CATALOG as $p) {
  90. if ((string)$p['id'] === (string)$id) return $p;
  91. }
  92. return null;
  93. }
  94. // ---------------------------------------------------------------------------
  95. // Public-data builders
  96. // ---------------------------------------------------------------------------
  97. function build_counter(): array
  98. {
  99. $v = $_SESSION['counter'] ?? 0;
  100. return [
  101. 'value' => $v,
  102. 'high' => $v > 5,
  103. 'increment' => ['uri' => '/api/counter/inc', 'method' => 'POST'],
  104. 'decrement' => ['uri' => '/api/counter/dec', 'method' => 'POST'],
  105. 'reset' => ['uri' => '/api/counter/reset', 'method' => 'POST'],
  106. 'add' => ['uri' => '/api/counter/add', 'method' => 'POST'],
  107. ];
  108. }
  109. function build_products(): array
  110. {
  111. global $CATALOG;
  112. $items = [];
  113. foreach ($CATALOG as $p) {
  114. $pid = (string)$p['id'];
  115. $items[] = [
  116. 'id' => $pid,
  117. 'name' => $p['name'],
  118. 'price' => $p['price'],
  119. 'featured' => $p['featured'],
  120. 'inStock' => $p['inStock'],
  121. // Per-item context rides in `private`; the client echoes it back
  122. // via the X-Statum-Private header (no stm-data expression needed).
  123. 'addToCartAction' => [
  124. 'uri' => '/api/cart/add',
  125. 'method' => 'POST',
  126. 'private' => base64_encode('id=' . $pid),
  127. ],
  128. ];
  129. }
  130. return ['items' => $items];
  131. }
  132. function build_cart(): array
  133. {
  134. $cart = $_SESSION['cart'] ?? [];
  135. $count = 0;
  136. $total = 0.0;
  137. $lines = [];
  138. foreach ($cart as $id => $qty) {
  139. $p = product_by_id($id);
  140. if (!$p) continue;
  141. $count += $qty;
  142. $total += $p['price'] * $qty;
  143. $lines[] = ['id' => (string)$id, 'name' => $p['name'], 'qty' => $qty, 'price' => $p['price']];
  144. }
  145. return [
  146. 'count' => $count,
  147. 'total' => round($total, 2),
  148. 'empty' => $count === 0,
  149. 'items' => $lines,
  150. 'checkoutAction' => ['uri' => '/api/cart/checkout', 'method' => 'POST'],
  151. 'clearAction' => ['uri' => '/api/cart/clear', 'method' => 'POST'],
  152. ];
  153. }
  154. function build_user(): array
  155. {
  156. $role = $_SESSION['role'] ?? 'guest';
  157. $names = ['guest' => 'Guest', 'member' => 'Member Mike', 'admin' => 'Admin Alice'];
  158. return [
  159. 'role' => $role,
  160. 'name' => $names[$role] ?? 'Guest',
  161. 'toggleAction' => ['uri' => '/api/user/toggle', 'method' => 'POST'],
  162. 'resetAllAction' => ['uri' => '/api/reset-all', 'method' => 'POST'],
  163. ];
  164. }
  165. function build_notice(): array
  166. {
  167. return [
  168. 'html' => $_SESSION['notice'] ?? '<em>No notice set.</em>',
  169. 'setAction' => ['uri' => '/api/notice/set', 'method' => 'POST'],
  170. 'failAction' => ['uri' => '/api/notice/fail', 'method' => 'POST'],
  171. ];
  172. }
  173. /** Build the snapshot for a type with its demo scope/options. */
  174. function snap(string $type): ?array
  175. {
  176. switch ($type) {
  177. case 'counter': return make_snapshot('counter', 'session', build_counter());
  178. case 'products': return make_snapshot('products', 'session', build_products());
  179. case 'cart': return make_snapshot('cart', 'session', build_cart(), ['always' => true]);
  180. case 'user': return make_snapshot('user', 'session', build_user(), ['stale' => true]);
  181. case 'notice': return make_snapshot('notice', 'flow', build_notice());
  182. }
  183. return null;
  184. }
  185. function all_directives(): array
  186. {
  187. global $TYPES;
  188. $dirs = [];
  189. foreach ($TYPES as $t) {
  190. $s = snap($t);
  191. if ($s) $dirs[] = set_dir($s);
  192. }
  193. return $dirs;
  194. }
  195. // ---------------------------------------------------------------------------
  196. // Router
  197. // ---------------------------------------------------------------------------
  198. $method = $_SERVER['REQUEST_METHOD'];
  199. $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  200. // Static assets.
  201. if ($path === '/statum.js') {
  202. header('Content-Type: application/javascript');
  203. readfile(__DIR__ . '/../js/statum.js');
  204. exit;
  205. }
  206. // The page itself.
  207. if ($path === '/' || $path === '/index.html') {
  208. header('Content-Type: text/html; charset=utf-8');
  209. readfile(__DIR__ . '/index.html');
  210. exit;
  211. }
  212. // Landing page after a (post) checkout navigation.
  213. if ($path === '/api/checkout-done') {
  214. header('Content-Type: text/html; charset=utf-8');
  215. $order = htmlspecialchars($_GET['order'] ?? 'UNKNOWN');
  216. echo "<!doctype html><meta charset=utf-8><title>Checkout</title>" .
  217. "<body style='font-family:sans-serif;padding:2rem'>" .
  218. "<h1>Order $order placed</h1><p>This page was reached via a statum <code>post</code> directive.</p>" .
  219. "<p><a href='/'>Back to the demo</a></p>";
  220. exit;
  221. }
  222. // --- Statum endpoints -------------------------------------------------------
  223. if ($path === '/_statum/entrypoint') {
  224. statum_respond(all_directives());
  225. }
  226. if ($path === '/_statum/slots') {
  227. // Pre-flight target: refresh each type whose frame the client sent back.
  228. $body = json_decode(file_get_contents('php://input'), true);
  229. $dirs = [];
  230. if (is_array($body)) {
  231. foreach ($body as $fr) {
  232. $snap = json_decode($fr['content'] ?? 'null', true);
  233. $type = $snap['slot']['type'] ?? null;
  234. if ($type) {
  235. $s = snap($type);
  236. if ($s) $dirs[] = set_dir($s);
  237. }
  238. }
  239. }
  240. statum_respond($dirs);
  241. }
  242. // --- Actions ----------------------------------------------------------------
  243. if ($path === '/api/counter/inc' && $method === 'POST') {
  244. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) + 1;
  245. statum_respond([set_dir(snap('counter'))]);
  246. }
  247. if ($path === '/api/counter/dec' && $method === 'POST') {
  248. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) - 1;
  249. statum_respond([set_dir(snap('counter'))]);
  250. }
  251. if ($path === '/api/counter/reset' && $method === 'POST') {
  252. $_SESSION['counter'] = 0;
  253. statum_respond([set_dir(snap('counter'))]);
  254. }
  255. if ($path === '/api/counter/add' && $method === 'POST') {
  256. $amount = intval($_POST['amount'] ?? 1);
  257. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) + $amount;
  258. statum_respond([set_dir(snap('counter'))]);
  259. }
  260. if ($path === '/api/cart/add' && $method === 'POST') {
  261. $priv = $_SERVER['HTTP_X_STATUM_PRIVATE'] ?? '';
  262. $raw = base64_decode($priv, true) ?: '';
  263. if (preg_match('/id=([0-9]+)/', $raw, $m)) {
  264. $id = $m[1];
  265. $_SESSION['cart'][$id] = ($_SESSION['cart'][$id] ?? 0) + 1;
  266. }
  267. statum_respond([set_dir(snap('cart'))]);
  268. }
  269. if ($path === '/api/cart/clear' && $method === 'POST') {
  270. $_SESSION['cart'] = [];
  271. statum_respond([set_dir(snap('cart'))]);
  272. }
  273. if ($path === '/api/cart/checkout' && $method === 'POST') {
  274. // A `post` directive performs a full-page navigating form POST last.
  275. statum_respond([['type' => 'post', 'uri' => '/api/checkout-done', 'data' => ['order' => 'ORD-' . strtoupper(bin2hex(random_bytes(3)))]]]);
  276. }
  277. if ($path === '/api/user/toggle' && $method === 'POST') {
  278. $order = ['guest', 'member', 'admin'];
  279. $cur = array_search($_SESSION['role'] ?? 'guest', $order);
  280. $_SESSION['role'] = $order[($cur + 1) % count($order)];
  281. statum_respond([set_dir(snap('user'))]);
  282. }
  283. if ($path === '/api/notice/set' && $method === 'POST') {
  284. $_SESSION['notice'] = '<div class="ok"><strong>Notice:</strong> updated at ' . date('H:i:s') . '</div>';
  285. statum_respond([set_dir(snap('notice'))]);
  286. }
  287. if ($path === '/api/notice/fail' && $method === 'POST') {
  288. statum_respond([['type' => 'error', 'message' => 'Intentional failure.', 'code' => 'DEMO_FAIL', 'data' => ['at' => date('c')]]]);
  289. }
  290. if ($path === '/api/reset-all' && $method === 'POST') {
  291. $dirs = [];
  292. foreach ($TYPES as $t) {
  293. if (isset($_SESSION['keys'][$t])) $dirs[] = clear_dir($_SESSION['keys'][$t]);
  294. }
  295. session_unset();
  296. $dirs[] = ['type' => 'navigate', 'uri' => '/'];
  297. statum_respond($dirs);
  298. }
  299. // Fallback 404.
  300. http_response_code(404);
  301. header('Content-Type: text/plain');
  302. echo "404 Not Found: $path";