Public: anyone can read this; the crew can change it.

A display launches into the arcade host, playable by keyboard and on a phone #9554

Parked opened this
Closed without merging

mason/forge:mason/9468-a-display-launches-into-the-arcade-host → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +1039 −12
docs/design/areas/display.md +4 −2
@@ -1,5 +1,7 @@
11 # Display
22
3 A repository's display, `/:owner/:name/display` (`src/web/pages/display.ts`): the builds its `display.json` holds, as a dense table (`.table`, `.table-scroll`) under the repo header, as whoever looks may read them. It adds no component class. Covers, the player, editing the title waits for `pin_demos.ts` and the Arcade host.
3 A repository's display, `/:owner/:name/display` (`src/web/pages/display.ts`): the builds its `display.json` holds, as a dense table (`.table`, `.table-scroll`) under the repo header, as whoever looks may read them. It adds no component class. Covers, the player and editing the title wait for `pin_demos.ts`.
44
5 Writers also get a form of `.field` fieldset, `.check` rows, a `btn` and a `.hint` status line: no new component class.↵
5 Writers also get a form of `.field` fieldset, `.check` rows, a `btn` and a `.hint` status line: no new component class.
6
7 On the display titled `arcade-builds` in the shelf layout the page head carries **Launch**, a plain link (`.btn`) to the Arcade host (`arcade.<app domain>`, `src/arcade/host.ts`). The host page is its own document, outside the forge's design system: pixel look, no third-party fonts, focus to `#back` when a cart opens and back to its cart when it closes, prev/next buttons for carts off the front, a touch hint under `(hover: none)`, and a `<noscript>` line.
scripts/unreached-allow.json −2
@@ -1,7 +1,5 @@
11 [
22 "src/apps/cloud.ts",
3 "src/arcade/cover.ts",
4 "src/arcade/shelf.ts",
53 "src/boards/machine.ts",
64 "src/crew/governor_log.ts",
75 "src/crew/tries.ts",
src/arcade/arcade.html added +349
@@ -0,0 +1,349 @@
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1">
6 <title>Browser Arcade</title>
7 <link rel="icon" href="data:,">
8 <style>
9 :root {
10 --night: #120a26;
11 --ink: #fff6e0;
12 --dim: #9a90c0;
13 --sun: #ffd200;
14 --pink: #ff4fa0;
15 --lime: #9bbc0f;
16 --line: #08040f;
17 --pixel: "Press Start 2P", ui-monospace, Menlo, monospace;
18 }
19 * { box-sizing: border-box; }
20 html, body { margin: 0; min-height: 100%; color: var(--ink); font: 11px/1.5 var(--pixel); overflow-x: hidden;
21 background-color: #4a2a16; }
22 /* A woodgrain tabletop: planks, with darker grain running along them. */
23 body { background-image:
24 repeating-linear-gradient(0deg, rgba(0,0,0,.35) 0 3px, transparent 3px 96px),
25 repeating-linear-gradient(0deg, rgba(255,210,150,.05) 0 2px, transparent 2px 9px, rgba(0,0,0,.08) 9px 11px, transparent 11px 23px),
26 linear-gradient(90deg, #4a2a16, #5a3420 30%, #4e2c18 55%, #5e3822 80%, #4a2a16); }
27 /* CRT scanlines over the whole shelf. */
28 body::after { content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 5; background: repeating-linear-gradient(0deg, rgba(0,0,0,.16) 0 1px, transparent 1px 3px); }
29 button, a { font: inherit; color: inherit; }
30 /* One line across the top: the producer, and for a snapshot file, its date. */
31 header { position: relative; padding: 10px 16px; background: rgba(8,4,15,.7); border-bottom: 4px solid var(--line); font-size: 10px; color: var(--sun);
32 white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; }
33
34 /* Carts: chunky plastic with a black outline, bevels, screws, a deep grip and a big sticker. */
35 /* Carts turned to the sides must not widen the page. */
36 main { overflow-x: clip; }
37 .stage { position: relative; height: 330px; perspective: 1100px; margin-top: 22px; }
38 .cart { position: absolute; left: 50%; top: 14px; width: 210px; margin-left: -105px; cursor: pointer; border: 0; padding: 0; background: none;
39 transition: transform .45s cubic-bezier(.2,.9,.3,1.1), filter .45s, top .35s ease-in; }
40 .shell { position: relative; padding: 14px 14px 66px; background: var(--body); border: 5px solid var(--line);
41 box-shadow: inset 6px 6px 0 var(--hi), inset -6px -6px 0 var(--lo), 8px 8px 0 var(--line); }
42 .shell::before { content: ""; position: absolute; left: 50%; top: 4px; width: 46px; height: 5px; margin-left: -23px; background: var(--lo); box-shadow: 0 0 0 2px var(--line); }
43 .screw { position: absolute; bottom: 52px; width: 9px; height: 9px; border-radius: 50%; background: var(--hi); box-shadow: 0 0 0 2px var(--line), inset -2px -2px 0 var(--lo); }
44 .screw.l { left: 9px; } .screw.r { right: 9px; }
45 .grip { position: absolute; left: 14px; right: 14px; bottom: 10px; height: 38px; border: 3px solid var(--line);
46 background: repeating-linear-gradient(0deg, var(--lo) 0 5px, var(--hi) 5px 7px, var(--body) 7px 10px); }
47 .sticker { position: relative; aspect-ratio: 1; background: #000; border: 5px solid #fff; box-shadow: 0 0 0 4px var(--line); overflow: hidden; }
48 .sticker img { width: 100%; height: 100%; object-fit: cover; image-rendering: pixelated; display: block; }
49 .sticker .logo { position: absolute; left: 0; right: 0; bottom: 0; padding: 20px 6px 6px; font: 15px/1.05 "Bungee", sans-serif; color: #fff;
50 text-shadow: 2px 2px 0 var(--line), -1px -1px 0 var(--line); background: linear-gradient(transparent, rgba(0,0,0,.75)); text-align: left; }
51 .cart.loading { top: 230px; transform: translateZ(0) scale(.92) !important; }
52
53 /* The console: a heavy slab with a slot, switches, a readout, and big buttons. */
54 .console { position: relative; z-index: 2; max-width: 760px; margin: -6px auto 0; padding: 30px 26px 24px;
55 background: linear-gradient(#45405a, #2c283c); border: 6px solid var(--line);
56 box-shadow: inset 0 8px 0 #6a6488, inset 0 -10px 0 #1c1828, 10px 10px 0 var(--line); }
57 .console .slot { position: absolute; left: 50%; top: -6px; width: 250px; height: 22px; margin-left: -125px; background: #05030a; border: 6px solid var(--line); border-top: 0; }
58 .row { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
59 .row + .row { margin-top: 16px; }
60 .badge { font: 16px "Bungee", sans-serif; letter-spacing: 5px; color: #b8b0d8; text-shadow: 2px 2px 0 var(--line); }
61 .led { width: 14px; height: 14px; border-radius: 50%; background: #5a1010; box-shadow: 0 0 0 3px var(--line); }
62 .led.on { background: #ff3a3a; box-shadow: 0 0 0 3px var(--line), 0 0 14px #ff3a3a; }
63 .led.go { background: #3aff6a; box-shadow: 0 0 0 3px var(--line), 0 0 14px #3aff6a; }
64 .grille { flex: 1; min-width: 80px; height: 24px; background: repeating-linear-gradient(90deg, #1c1828 0 6px, #55507a 6px 9px); border: 3px solid var(--line); }
65 .lcd { flex: 1; min-width: 220px; background: #9bbc0f; color: #0f380f; border: 5px solid var(--line); box-shadow: inset 3px 3px 0 #306230; padding: 10px 12px; font-size: 10px; line-height: 1.7; }
66 .lcd b { display: block; font-size: 12px; }
67 .switches { display: flex; gap: 8px; flex-wrap: wrap; }
68 .switch { cursor: pointer; padding: 10px 10px; font-size: 9px; background: #2c283c; border: 4px solid var(--line); box-shadow: inset 3px 3px 0 #55507a, 4px 4px 0 var(--line); }
69 .switch[aria-pressed="true"] { background: var(--sun); color: var(--line); box-shadow: inset 3px 3px 0 #fff2a0, 2px 2px 0 var(--line); transform: translate(2px, 2px); }
70 .big { cursor: pointer; padding: 14px 18px; font-size: 12px; border: 5px solid var(--line); text-decoration: none; display: inline-block; }
71 .power { background: #ff3a3a; color: #fff; box-shadow: inset 4px 4px 0 #ff8a8a, inset -4px -4px 0 #9a1010, 5px 5px 0 var(--line); }
72 .eject { background: #c8c0e0; color: var(--line); box-shadow: inset 4px 4px 0 #fff, inset -4px -4px 0 #8a80a8, 5px 5px 0 var(--line); }
73 .big:active { transform: translate(4px, 4px); box-shadow: none; }
74 .switch:focus-visible, .big:focus-visible, .cart:focus-visible { outline: 4px solid var(--sun); outline-offset: 4px; }
75 footer { position: relative; text-align: center; color: var(--ink); font-size: 9px; padding: 22px 16px 30px; }
76 .hint-touch { display: none; }
77 @media (hover: none) { .hint-keys { display: none; } .hint-touch { display: inline; } }
78 .pager { display: flex; justify-content: center; gap: 12px; padding: 4px 0 10px; position: relative; z-index: 20; }
79 .pager button { cursor: pointer; padding: 10px 14px; font-size: 10px; background: #2c283c; color: var(--ink); border: 4px solid var(--line); box-shadow: 3px 3px 0 var(--line); }
80 .pager button:disabled { opacity: .5; cursor: default; }
81 .pager button:focus-visible { outline: 4px solid var(--sun); outline-offset: 4px; }
82 .empty { color: var(--ink); }
83 footer a { color: var(--sun); text-decoration: none; margin-left: 14px; }
84 footer a:hover, footer a:focus-visible { text-decoration: underline; }
85 .empty { text-align: center; padding-top: 80px; }
86 @media (max-width: 600px) { .stage { height: 290px; } .cart { width: 170px; margin-left: -85px; } .cart.loading { top: 200px; } }
87
88 /* The player: the game fills the screen, with a way back. */
89 #player { position: fixed; inset: 0; background: #000; display: none; z-index: 10; }
90 #player.on { display: block; }
91 #player iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
92 #back { position: absolute; top: 10px; left: 10px; z-index: 4; cursor: pointer; font-size: 10px; color: var(--ink);
93 background: #2c283c; border: 4px solid var(--line); box-shadow: 3px 3px 0 var(--line); padding: 6px 9px; opacity: 1; }
94 #back:hover, #back:focus-visible { opacity: 1; }
95 /* The jbox boot tag plays over the screen while a cartridge loads. */
96 #boot { position: absolute; inset: 0; display: none; place-items: center; background: #1b1b25; z-index: 1; transition: opacity .25s; }
97 #boot.on { display: grid; }
98 #boot.out { opacity: 0; }
99 #boot canvas { display: block; image-rendering: pixelated; }
100 /* Opened from a link, the cartridge waits for a press so its power-on chord can play. */
101 #power { position: absolute; inset: 0; display: none; place-items: center; z-index: 3; background: #1b1b25; color: var(--lime); cursor: pointer; text-align: center; font-size: 11px; }
102 #power.on { display: grid; }
103 #power b { display: block; font-size: 32px; margin-bottom: 14px; }
104 </style>
105 </head>
106 <body>
107 <header id="topline">JBOX • BROWSER ARCADE</header>
108 <main id="games"><p class="empty">LOADING…</p></main>
109 <noscript><p class="empty">THE ARCADE NEEDS JAVASCRIPT TO SHOW ITS SHELF AND PLAY CARTS.</p></noscript>
110 <footer><span class="hint-keys">◀ ▶ CHOOSE · Z X BUILD · ENTER POWER</span><span class="hint-touch">TAP A CART TO CHOOSE · TAP AGAIN OR POWER TO PLAY · TAP A BUILD NAME TO SWITCH</span><a id="export" href="snapshot.html" download>⤓ EXPORT SNAPSHOT</a></footer>
111
112 <div id="player" aria-hidden="true">
113 <button id="back" type="button">◀ ARCADE</button>
114 <div id="boot"><canvas id="tag"></canvas></div>
115 <div id="power"><div><b>⏻</b>PRESS ANY KEY TO POWER ON</div></div>
116 <iframe id="screen" title="Game" allow="autoplay *; fullscreen *; gamepad *"></iframe>
117 </div>
118
119 <script type="module">
120 import { jboxScale, playJboxSpin } from './boot/jbox-spin.js';
121 const shelfEl = document.getElementById('games');
122 const player = document.getElementById('player');
123 const screen = document.getElementById('screen');
124 const bootEl = document.getElementById('boot');
125 const tag = document.getElementById('tag');
126 const powerEl = document.getElementById('power');
127 /** Bytes as a short size: 38 KB, 1.2 MB. */
128 const size = (n) => (!n ? '' : n < 1e6 ? `${Math.round(n / 1024)} KB` : `${(n / 1048576).toFixed(1)} MB`);
129 // A single-file bundle (a snapshot) carries the shelf, carts and covers inside the
130 // page as window.__ARCADE__; the forge's own display page carries the shelf with
131 // absolute addresses. Served as a folder, the arcade reads its files instead.
132 const BUNDLE = window.__ARCADE__;
133 const HOME = document.title;
134 const urls = new Map();
135 /** Where a cart or label lives: its path, or a blob or data URL from the bundle. */
136 const url = (path) => {
137 if (!BUNDLE || !path || /^(data:|https?:|\/)/.test(path)) return path;
138 if (!urls.has(path)) {
139 const label = BUNDLE.labels[path];
140 urls.set(path, label ?? URL.createObjectURL(new Blob([BUNDLE.carts[path] ?? ''], { type: 'text/html' })));
141 }
142 return urls.get(path);
143 };
144 if (BUNDLE?.snapshot) document.getElementById('topline').textContent = BUNDLE.snapshot;
145 // A snapshot is the export: it has nothing further to export.
146 if (BUNDLE?.exportHref) document.getElementById('export').href = BUNDLE.exportHref;
147 else if (BUNDLE) document.getElementById('export').remove();
148 const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
149
150 /** Cart plastic by game: body, highlight and shadow. Unknown games get grey. */
151 const PLASTIC = {
152 'krazy-karts': ['#e8322a', '#ff7a6a', '#8a1410'],
153 'nova-lantern': ['#5a3ab8', '#8a6ae8', '#2a1a68'],
154 ballistics: ['#f0a020', '#ffd870', '#9a5a0a'],
155 'krazy-karts-fiesta': ['#ff7a1a', '#ffb060', '#a83e00'],
156 'krazy-karts-london': ['#4a6a8a', '#7a9aba', '#24384c'],
157 'krazy-karts-chicago': ['#2a8ad8', '#6ac0ff', '#124a7a'],
158 'nova-moves': ['#1f8a6a', '#4ac89a', '#0e4a38'],
159 };
160 const plastic = (id) => PLASTIC[id] ?? ['#8a8a96', '#c0c0cc', '#4a4a56'];
161
162 /** Wait for a key or click: browsers only play sound after one. */
163 function powerPress() {
164 powerEl.classList.add('on');
165 return new Promise((done) => {
166 const go = (e) => {
167 e.preventDefault();
168 removeEventListener('keydown', go);
169 powerEl.removeEventListener('pointerdown', go);
170 powerEl.classList.remove('on');
171 done();
172 };
173 addEventListener('keydown', go);
174 powerEl.addEventListener('pointerdown', go);
175 });
176 }
177
178 /** The jbox tag spins up while the cartridge loads behind it. `sound` needs a click. */
179 async function bootCartridge(sound) {
180 bootEl.classList.remove('out');
181 bootEl.classList.add('on');
182 const s = jboxScale(innerWidth * 0.8, innerHeight * 0.8);
183 tag.style.width = `${160 * s}px`;
184 tag.style.height = `${144 * s}px`;
185 await playJboxSpin(tag, { sound });
186 }
187
188 async function play(game, build, push = true) {
189 if (push) history.pushState({ game: game.id, build: build.id }, '', `#${game.id}/${build.id}`);
190 player.classList.add('on');
191 player.setAttribute('aria-hidden', 'false');
192 document.getElementById('back').focus();
193 document.title = `${game.name} · ${build.name}`;
194 const ready = new Promise((r) => (screen.onload = r));
195 // Replace, so the frame's own loads never land in the browser's history.
196 screen.contentWindow.location.replace(BUNDLE ? url(build.file) : new URL(build.file, location.href).href);
197 // A click on a cartridge already counts as the press. A link has to ask for one.
198 if (!push) await powerPress();
199 await Promise.all([ready, bootCartridge(true)]);
200 bootEl.classList.add('out');
201 screen.focus();
202 setTimeout(() => bootEl.classList.remove('on', 'out'), 260);
203 }
204
205 function stop() {
206 const wasOn = player.classList.contains('on');
207 player.classList.remove('on');
208 player.setAttribute('aria-hidden', 'true');
209 screen.contentWindow.location.replace('about:blank');
210 document.title = HOME;
211 shelfEl.querySelector('.loading')?.classList.remove('loading');
212 shelfEl.querySelector('.led')?.classList.replace('go', 'on');
213 if (wasOn) shelfEl.querySelector(`.cart[data-i="${gi}"]`)?.focus();
214 }
215
216 document.getElementById('back').addEventListener('click', () => {
217 history.pushState(null, '', location.pathname);
218 stop();
219 });
220
221 const games = BUNDLE ? BUNDLE.games : await fetch('games.json').then((r) => r.json()).catch(() => []);
222 // Builds stand in the display's order.
223 // A build with no cover of its own gets the house cover, drawn from its page's picture.
224 /*COVER_JS*/
225 if (games.some((g) => g.builds.some((b) => !b.label))) {
226 const tpl = await loadImage(url('cover-template.png'));
227 for (const g of games) for (const b of g.builds) {
228 if (b.label) continue;
229 const c = document.createElement('canvas');
230 drawCover(c, b.art ? await loadImage(url(b.art)) : null, tpl, g.name, b.name);
231 b.label = c.toDataURL('image/png');
232 b.titled = true;
233 }
234 }
235 let gi = 0;
236 const bi = games.map(() => 0);
237 const find = (gid, bid) => {
238 const g = games.find((x) => x.id === gid);
239 const b = g?.builds.find((x) => x.id === bid);
240 return g && b ? [g, b] : null;
241 };
242
243 // The carousel of carts is built once; `draw` turns it and refreshes the console.
244 if (!games.length) shelfEl.innerHTML = '<p class="empty">THE SHELF IS EMPTY</p>';
245 else {
246 shelfEl.innerHTML = `
247 <div class="stage">${games.map((g, i) => {
248 const [body, hi, lo] = plastic(g.id);
249 return `<button type="button" class="cart" data-i="${i}" style="--body:${body};--hi:${hi};--lo:${lo}" aria-label="${esc(g.name)}">
250 <div class="shell"><div class="sticker"><img alt=""><div class="logo">${esc(g.name).toUpperCase()}</div></div>
251 <span class="screw l"></span><span class="screw r"></span><div class="grip"></div></div></button>`;
252 }).join('')}</div>
253 <nav class="pager" aria-label="Carts"><button type="button" id="prev">◀ PREV</button><button type="button" id="next">NEXT ▶</button></nav>
254 <section class="console" aria-label="Console">
255 <div class="slot"></div>
256 <div class="row"><span class="led on"></span><span class="badge">JBOX</span><span class="grille"></span></div>
257 <div class="row"><div class="lcd" id="lcd"></div><div class="switches" id="switches"></div></div>
258 <div class="row"><button type="button" class="big power" id="go">⏻ POWER</button><a class="big eject" id="save">⏏ SAVE</a><span class="grille"></span></div>
259 </section>`;
260 }
261
262 function draw() {
263 if (!games.length) return;
264 const g = games[gi];
265 const b = g.builds[bi[gi]];
266 shelfEl.querySelectorAll('.cart').forEach((c, i) => {
267 const d = i - gi;
268 const x = games[i];
269 const xb = x.builds[bi[i]];
270 const img = c.querySelector('img');
271 if (xb.label && img.dataset.label !== xb.label) {
272 img.dataset.label = xb.label;
273 img.src = url(xb.label);
274 }
275 // Cover art carries its own title; a plain snapshot gets the game's name.
276 c.querySelector('.logo').hidden = Boolean(xb.titled);
277 // Far carts turn no more than 70°, so none shows its back.
278 c.style.transform = `translateX(${d * 220}px) translateZ(${-Math.abs(d) * 230}px) rotateY(${-Math.sign(d) * Math.min(Math.abs(d) * 36, 70)}deg)`;
279 c.style.filter = d ? 'brightness(.5)' : 'none';
280 c.style.zIndex = 10 - Math.abs(d);
281 c.tabIndex = 0;
282 });
283 document.getElementById('prev').disabled = gi === 0;
284 document.getElementById('next').disabled = gi === games.length - 1;
285 document.getElementById('lcd').innerHTML = `<b>${esc(g.name).toUpperCase()}</b>${esc(b.name).toUpperCase()}${b.size ? ` · ${size(b.size)}` : ''}${g.producer ? `<br>BY ${esc(g.producer).toUpperCase()}` : ''}`;
286 document.getElementById('switches').innerHTML = g.builds.map((x, k) => `<button type="button" class="switch" data-build="${k}" aria-pressed="${k === bi[gi]}">${esc(x.name).toUpperCase()}</button>`).join('');
287 const save = document.getElementById('save');
288 // A page served elsewhere names where it downloads from.
289 save.href = url(b.save ?? b.file);
290 save.download = b.download ?? `${g.id}-${b.id}.html`;
291 }
292
293 /** Drop the front cart into the slot, light the LED, then boot it. */
294 function insert() {
295 const g = games[gi];
296 shelfEl.querySelector(`.cart[data-i="${gi}"]`).classList.add('loading');
297 shelfEl.querySelector('.led').classList.replace('on', 'go');
298 setTimeout(() => play(g, g.builds[bi[gi]]), 380);
299 }
300
301 shelfEl.addEventListener('click', (e) => {
302 const cart = e.target.closest('.cart');
303 const sw = e.target.closest('.switch');
304 if (cart) {
305 const i = Number(cart.dataset.i);
306 if (i === gi) insert();
307 else { gi = i; draw(); }
308 } else if (sw) {
309 bi[gi] = Number(sw.dataset.build);
310 draw();
311 } else if (e.target.closest('#prev')) { gi = Math.max(0, gi - 1); draw(); }
312 else if (e.target.closest('#next')) { gi = Math.min(games.length - 1, gi + 1); draw(); }
313 else if (e.target.closest('#go')) insert();
314 });
315
316 // Pad controls: left and right turn the carousel, Z and X flip the build, Enter powers on.
317 addEventListener('keydown', (e) => {
318 if (player.classList.contains('on') || !games.length) return;
319 if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
320 e.preventDefault();
321 gi = Math.min(games.length - 1, Math.max(0, gi + (e.key === 'ArrowLeft' ? -1 : 1)));
322 draw();
323 } else if (e.key === 'z' || e.key === 'x') {
324 const n = games[gi].builds.length;
325 bi[gi] = (bi[gi] + (e.key === 'x' ? 1 : n - 1)) % n;
326 draw();
327 } else if (e.key === 'Enter' && !e.target.closest?.('a, button')) {
328 e.preventDefault();
329 insert();
330 }
331 });
332 draw();
333
334 // Links like #krazy-karts/alpha-1025 open a cartridge directly. Back returns to the shelf.
335 const route = () => {
336 const [gid, bid] = location.hash.slice(1).split('/');
337 const hit = gid && find(gid, bid);
338 if (hit) {
339 gi = games.indexOf(hit[0]);
340 bi[gi] = hit[0].builds.indexOf(hit[1]);
341 draw();
342 play(...hit, false);
343 } else stop();
344 };
345 addEventListener('popstate', route);
346 route();
347 </script>
348 </body>
349 </html>
src/arcade/host.ts added +256
@@ -0,0 +1,256 @@
1 /**
2 * The Arcade: one repository's display (`display/config.ts`), served at
3 * `arcade.<app domain>`: the display titled `arcade-builds` in a repository
4 * a site admin owns, the newest of several (`display/known.ts`); with none,
5 * the host answers 404. A display in the shelf layout is browser-arcade's page as
6 * it was — the chunky carousel, the console and the jbox boot tag — fed by
7 * the display's items (`shelf.ts`); any other layout is drawn by the
8 * forge, so the host's root sends a person there.
9 *
10 * The host answers on an app's kind of hostname, its own origin, for two
11 * reasons: a cart is a stranger's page, and must never run as the forge;
12 * and a cart keeps its saves in that origin's storage, which a sandboxed
13 * frame would refuse it. `arcade` is a reserved app name, so no app can
14 * stand in its place. Nobody is signed in on this origin: the display is
15 * read as a stranger reads it: a showcased demo from a private source is
16 * on it, published, by its opaque id and never its repository. It is also
17 * where every display's `file` demos play (`display/launch.ts`), with an
18 * Arcade display or not: a page in a public repository at its plain
19 * address, a private one with a grant, and a published one by its display
20 * and id (`displays/…`), plain when the display is public.
21 */
22
23 import { readFileSync } from "node:fs";
24 import type { App } from "../app.ts";
25 import { appHostSuffix } from "../apps/host.ts";
26 import { parseAppHost } from "../apps/proxy.ts";
27 import { appsRuntime, type AppsRuntime } from "../apps/runtime.ts";
28 import { canRead, getRepo, ownerInStanding, type Repo } from "../core/repos.ts";
29 import { arcadeRepoKnown, arcadeRepoOf } from "../display/known.ts";
30 import { readDisplay, type DisplayConfig } from "../display/config.ts";
31 import { displayItem, displayItems } from "../display/items.ts";
32 import { verifyCart } from "../display/launch.ts";
33 import { coverType, listBuildPins, readCover } from "../git/builds.ts";
34 import { repoDir } from "../git/repos.ts";
35 import type { Result } from "../kernel/result.ts";
36 import { pageFile, readArt, readCapture } from "./carts.ts";
37 import { COVER_JS } from "./cover.ts";
38 import { shelfOf, type Shelf } from "./shelf.ts";
39 import { snapshotFile } from "./snapshot.ts";
40
41 /** The app name the Arcade answers at. */
42 export const ARCADE_SLUG = "arcade";
43
44 /** Whether a request's `Host` is the Arcade's. */
45 export function isArcadeHost(host: string | null, domain: string): boolean {
46 if (host === null) return false;
47 const parsed = parseAppHost(host, domain);
48 return parsed !== undefined && parsed.slug === ARCADE_SLUG && parsed.env === "production" && !parsed.nested;
49 }
50
51 /** Where the Arcade is reached, as the runtime addresses an app. */
52 export function arcadeUrl(runtime: AppsRuntime): string {
53 const { scheme, publicPort, domain } = runtime.options;
54 const port =
55 publicPort === undefined || (scheme === "http" && publicPort === 80) || (scheme === "https" && publicPort === 443)
56 ? ""
57 : `:${publicPort}`;
58 return `${scheme}://${ARCADE_SLUG}${appHostSuffix(domain)}${port}`;
59 }
60
61 /** Whether the forge has an Arcade: apps run and a site admin's display is titled `arcade-builds`. */
62 export function arcadeOn(app: App): boolean {
63 return appsRuntime(app) !== undefined && arcadeRepoKnown(app) !== undefined;
64 }
65
66 /** The Arcade's address when the forge has one. */
67 export function arcadeHome(app: App): string | undefined {
68 const runtime = appsRuntime(app);
69 return runtime !== undefined && arcadeRepoKnown(app) !== undefined ? arcadeUrl(runtime) : undefined;
70 }
71
72 const file = (name: string): string => readFileSync(new URL(name, import.meta.url), "utf8");
73 let page: string | undefined;
74 let boot: string | undefined;
75 let template: Uint8Array | undefined;
76
77 /** The Arcade's page, with the house cover drawing spliced in. */
78 export function arcadePage(): string {
79 page ??= file("./arcade.html").replace("/*COVER_JS*/", () => COVER_JS);
80 return page;
81 }
82 export const bootScript = (): string => (boot ??= file("./jbox-spin.js"));
83 export const coverTemplateBytes = (): Uint8Array =>
84 (template ??= new Uint8Array(readFileSync(new URL("./cover-template.png", import.meta.url))));
85
86 const IMPORT_LINE = "import { jboxScale, playJboxSpin } from './boot/jbox-spin.js';";
87 const escapeText = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]!);
88
89 /**
90 * The shelf page for a display: its title, its producer, and — for a page
91 * that carries its shelf inside it — the data, with the boot tag inline.
92 */
93 export function shelfPage(o: { title: string; producer: string | undefined; data?: unknown; tabTitle?: string; bar?: string }): string {
94 let out = arcadePage();
95 // The forge's own bar above the shelf (a writer's Edit display), outside the arcade's frame.
96 if (o.bar !== undefined) out = out.replace('<body>\n <header id="topline">', () => `<body>\n ${o.bar}\n <header id="topline">`);
97 const topline = o.producer === undefined ? o.title : `${o.producer} • ${o.title}`;
98 out = out
99 .replace("<title>Browser Arcade</title>", () => `<title>${escapeText(o.tabTitle ?? o.title)}</title>`)
100 .replace('<header id="topline">JBOX • BROWSER ARCADE</header>', () => `<header id="topline">${escapeText(topline.toUpperCase())}</header>`)
101 .replace('<button id="back" type="button">◀ ARCADE</button>', () => `<button id="back" type="button">◀ ${escapeText(o.title.toUpperCase())}</button>`);
102 if (o.data === undefined) return out;
103 if (!out.includes(IMPORT_LINE)) throw new Error("the Arcade page no longer imports the boot tag as expected");
104 // The boot tag goes inline, as plain script in the page's module.
105 out = out.replace(IMPORT_LINE, () => bootScript().replace(/^export /gm, ""));
106 // "<" escaped, so a cart's own </script> cannot end this script early.
107 const data = JSON.stringify(o.data).replace(/</g, "\\u003c");
108 return out.replace('<script type="module">', () => `<script>window.__ARCADE__ = ${data};</script>\n <script type="module">`);
109 }
110
111 /** The page's own policy: no third-party fonts, its inline module, carts in frames from itself. */
112 const PAGE_POLICY =
113 "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; " +
114 "font-src 'none'; img-src 'self' data: blob:; frame-src 'self' blob:; media-src 'self' blob: data:; " +
115 "base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
116
117 const answer = (body: string | Uint8Array, type: string, extra: Record<string, string> = {}): Response =>
118 new Response(body, {
119 headers: {
120 "content-type": type,
121 "cache-control": "no-cache",
122 "x-content-type-options": "nosniff",
123 "referrer-policy": "no-referrer",
124 ...extra,
125 },
126 });
127
128 const missing = (): Response =>
129 new Response("not found", {
130 status: 404,
131 headers: { "content-type": "text/plain; charset=utf-8", "content-security-policy": "default-src 'none'", "x-content-type-options": "nosniff" },
132 });
133
134 export interface ArcadeDisplay {
135 readonly repo: Repo;
136 readonly config: Result<DisplayConfig, string>;
137 }
138
139 /**
140 * The Arcade's display, read as a stranger reads it; undefined when there is
141 * none to show. A site admin titling a display `arcade-builds` publishes it,
142 * as Showcase publishes a demo: a private display repository is served all
143 * the same, and its private sources stay unnamed.
144 */
145 export async function arcadeDisplay(app: App): Promise<ArcadeDisplay | undefined> {
146 const repo = await arcadeRepoOf(app);
147 if (repo === undefined) return undefined;
148 const config = await readDisplay(app, repo);
149 return config === undefined ? undefined : { repo, config };
150 }
151
152 /**
153 * A captured page any display may play: the pin at `oid` in that
154 * repository has its demo in the showcase and the page is captured, and
155 * the repository is public or the request carries a grant for this page.
156 */
157 async function servePlayable(app: App, path: string, grant: string | null): Promise<Response> {
158 const m = /^carts\/([^/]+)\/([^/]+)\/([0-9a-f]{40,64})\/([A-Za-z0-9._-]+)\.html$/.exec(path);
159 if (m === null) return missing();
160 const [, owner, name, oid, page] = m as unknown as [string, string, string, string, string];
161 const repo = getRepo(app.db, owner, name);
162 if (repo === undefined || !ownerInStanding(app.db, repo)) return missing();
163 if (!canRead(app.db, repo, undefined) && (grant === null || !verifyCart(app.config.dataDir, path, grant))) return missing();
164 const pins = await listBuildPins(repoDir(app.reposRoot, repo.ownerName, repo.name));
165 const pin = pins.find((p) => p.oid === oid && p.demo?.showcase === true && pageFile(p.demo.page) === page);
166 if (pin?.demo === undefined) return missing();
167 const html = readCapture(app.config.dataDir, repo, oid, pin.demo.page);
168 return html === undefined ? missing() : answer(html, "text/html; charset=utf-8", { "content-security-policy": cartAncestors(app) });
169 }
170
171 /**
172 * A published demo, by the display that shows it and its id there: its
173 * captured page, its cover or its page's picture. The display must be
174 * public or the Arcade's named display, or the request carry a grant for
175 * this path; the demo must be in the display's showcase now.
176 */
177 async function serveShown(app: App, path: string, grant: string | null): Promise<Response> {
178 const m = /^displays\/([^/]+)\/([^/]+)\/([A-Za-z0-9_-]{22})(\.html|\/cover\.png|\/art\.png)$/.exec(path);
179 if (m === null) return missing();
180 const [, owner, name, id, kind] = m as unknown as [string, string, string, string, string];
181 const display = getRepo(app.db, owner, name);
182 if (display === undefined || !ownerInStanding(app.db, display)) return missing();
183 const published = canRead(app.db, display, undefined) || (await arcadeRepoOf(app))?.id === display.id;
184 if (!published && (grant === null || !verifyCart(app.config.dataDir, path, grant))) return missing();
185 const config = await readDisplay(app, display);
186 if (config === undefined || !config.ok) return missing();
187 const item = await displayItem(app, display, config.value, id);
188 if (item === undefined) return missing();
189 const { repo, pin, demo } = item;
190 if (kind === "/cover.png") {
191 const bytes = demo.cover === undefined ? undefined : await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), demo.cover);
192 return bytes === undefined ? missing() : answer(bytes, coverType(bytes) ?? "application/octet-stream");
193 }
194 if (kind === "/art.png") {
195 const bytes = readArt(app.config.dataDir, repo, pin.oid, demo.page);
196 return bytes === undefined ? missing() : answer(bytes, "image/png");
197 }
198 const html = readCapture(app.config.dataDir, repo, pin.oid, demo.page);
199 return html === undefined ? missing() : answer(html, "text/html; charset=utf-8", { "content-security-policy": cartAncestors(app) });
200 }
201
202 /** A cart may frame only inside a display: this origin's or the forge's own. */
203 function cartAncestors(app: App): string {
204 const forge = appsRuntime(app)?.options.forgeUrl;
205 return `frame-ancestors 'self'${forge === undefined ? "" : ` ${new URL(forge).origin}`}`;
206 }
207
208 const errorPage = (message: string): Response =>
209 new Response(`<!doctype html><meta charset="utf-8"><title>Display</title><p>${escapeText(message)}</p>`, {
210 status: 422,
211 headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'", "x-content-type-options": "nosniff" },
212 });
213
214 /** Answer one request to the Arcade's host. */
215 export async function serveArcade(app: App, request: Request): Promise<Response> {
216 if (request.method !== "GET" && request.method !== "HEAD")
217 return new Response("method not allowed", { status: 405, headers: { allow: "GET, HEAD" } });
218 const url = new URL(request.url);
219 const path = decodeURIComponent(url.pathname.slice(1));
220 // Every display's carts play here, Arcade or not.
221 if (path.startsWith("carts/")) return servePlayable(app, path, url.searchParams.get("g"));
222 if (path.startsWith("displays/")) return serveShown(app, path, url.searchParams.get("g"));
223 const display = await arcadeDisplay(app);
224 if (display === undefined) return missing();
225 if (!display.config.ok) return errorPage(display.config.error);
226 const config = display.config.value;
227 // Grid and graph are drawn by the forge.
228 if (config.layout !== "shelf") {
229 const forge = appsRuntime(app)?.options.forgeUrl;
230 if (forge === undefined || (path !== "" && path !== "index.html")) return missing();
231 return new Response(null, { status: 303, headers: { location: `${forge.replace(/\/$/, "")}/${display.repo.ownerName}/${display.repo.name}/display` } });
232 }
233 if (path === "" || path === "index.html")
234 return answer(shelfPage({ title: config.title, producer: config.shelf.producer }), "text/html; charset=utf-8", { "content-security-policy": PAGE_POLICY });
235 if (path === "boot/jbox-spin.js") return answer(bootScript(), "text/javascript; charset=utf-8");
236 if (path === "cover-template.png") return answer(coverTemplateBytes(), "image/png");
237 const shelf: Shelf = shelfOf(await displayItems(app, display.repo, config, undefined), config.shelf.producer);
238 if (path === "games.json") return answer(JSON.stringify(shelf.games), "application/json");
239 // Export snapshot: the display's shelf, in one file that plays offline.
240 if (path === "snapshot.html") {
241 const made = await snapshotFile(app, config, shelf, new Date());
242 return answer(made.html, "text/html; charset=utf-8", { "content-disposition": `attachment; filename="${made.name}"` });
243 }
244 const entry = shelf.entries.get(path);
245 if (entry === undefined) return missing();
246 const { repo, pin, cart } = entry;
247 if (path.startsWith("labels/") && cart.cover !== undefined) {
248 const bytes = await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), cart.cover);
249 return bytes === undefined ? missing() : answer(bytes, coverType(bytes) ?? "application/octet-stream");
250 }
251 if (path.startsWith("art/")) {
252 const bytes = readArt(app.config.dataDir, repo, pin.oid, cart.page);
253 return bytes === undefined ? missing() : answer(bytes, "image/png");
254 }
255 return missing();
256 }
src/arcade/jbox-spin.js added +151
@@ -0,0 +1,151 @@
1 // The jbox boot tag: "L · jbox green, spin", confirmed in
2 // Arcade records/design/1026-loading-tags. A Game Boy green cube spins two and three
3 // quarter turns counterclockwise and settles with the J in front, lighting its groove in
4 // three beats to a rising power-on chord. Drawn at 160x144 and scaled by whole pixels.
5 //
6 // playJboxSpin(canvas) runs it once and resolves when the chord has rung out.
7
8 // The tag: a 160x144 buffer, ray-cast per pixel, scaled up by whole pixels.
9 const VW = 160, VH = 144, SC = 28;
10 let x, img, buf;
11 const mask = new Uint8Array(VW * VH);
12 const rgb = (h) => [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4), 16)];
13 const pack = ([r, g, b], k = 1) => 0xff000000 | Math.min(255, b * k) << 16 | Math.min(255, g * k) << 8 | Math.min(255, r * k);
14 // Game Boy greens. Faces pick a shade by how much light they catch.
15 const BG = pack(rgb("9bbc0f")), INK = pack(rgb("0f380f")), LIP = INK, LIT = pack(rgb("e0f8a0"));
16 const SHADES = [["8bac0f", "c4e050", "306230"], ["6a8c1c", "a0c030", "306230"], ["306230", "5a8a28", "1d4a1d"]].map((r) => r.map((h) => pack(rgb(h))));
17
18 // M's line: one unbroken groove from mid-face on the right, across the
19 // left face and the next side round, over the top and down into the J.
20 // Beat one lights the first two sides, beat two the third side and the
21 // top, beat three the J. Cells are [col, row].
22 const PATHS = [
23 ["z-", [[5, 5], [7, 5], [7, 2], [3, 2], [3, 7], [0, 7]]],
24 ["x-", [[9, 7], [6, 7], [6, 3], [2, 3], [2, 6], [0, 6]]],
25 ["z+", [[9, 6], [7, 6], [7, 8], [3, 8], [3, 4], [6, 4], [6, 0]]],
26 ["y+", [[3, 0], [3, 5], [7, 5], [7, 2], [9, 2]]],
27 ["x+", [[7, 0], [7, 8], [2, 8], [2, 5]]],
28 ];
29 const cells = {}, SEC = { "z-": 0, "x-": 0, "z+": 1, "y+": 1, "x+": 2 };
30 for (const [f, pts] of PATHS) for (let i = 1; i < pts.length; i++) {
31 let [a, b] = pts[i - 1]; const [ea, eb] = pts[i];
32 for (;;) { cells[f + a + "," + b] = 1; if (a === ea && b === eb) break; a += Math.sign(ea - a); b += Math.sign(eb - b); }
33 }
34 const on = (f, a, b) => a < 0 || b < 0 || f + a + "," + b in cells;
35
36 const PITCH = Math.PI / 6, SP = Math.sin(PITCH), CP = Math.cos(PITCH), L = [-0.5, 0.83, -0.17];
37 function toObj([a, b, z], yaw) {
38 const y1 = b * CP - z * SP, z1 = b * SP + z * CP, cs = Math.cos(-yaw), sn = Math.sin(-yaw);
39 return [a * cs - z1 * sn, y1, a * sn + z1 * cs];
40 }
41 const toWorld = ([a, b, z], yaw) => [a * Math.cos(yaw) - z * Math.sin(yaw), b, a * Math.sin(yaw) + z * Math.cos(yaw)];
42 function hitBox(o, d) {
43 let tn = -1e9, tf = 1e9, ax = 0, sg = 0;
44 for (let i = 0; i < 3; i++) {
45 if (Math.abs(d[i]) < 1e-9) { if (Math.abs(o[i]) > 1) return null; continue; }
46 let t1 = (-1 - o[i]) / d[i], t2 = (1 - o[i]) / d[i], s = -1;
47 if (t1 > t2) { const q = t1; t1 = t2; t2 = q; s = 1; }
48 if (t1 > tn) { tn = t1; ax = i; sg = s; }
49 if (t2 < tf) tf = t2;
50 if (tn > tf) return null;
51 }
52 return { ax, sg, p: [o[0] + d[0] * tn, o[1] + d[1] * tn, o[2] + d[2] * tn] };
53 }
54 function uv(ax, sg, p) {
55 const cl = (q) => Math.min(0.9999, Math.max(0, q));
56 if (ax === 1) return [cl((p[0] + 1) / 2), cl((1 - p[2]) / 2)];
57 return [cl(((ax === 0 ? p[2] * sg : -p[0] * sg) + 1) / 2), cl((1 - p[1]) / 2)];
58 }
59
60 // Shade row by light: [face, flashed face, empty groove].
61 function paint(f, u, v, b, lit, flash) {
62 const row = SHADES[b >= 0.95 ? 0 : b >= 0.7 ? 1 : 2], iu = u * 10 | 0, iv = v * 10 | 0;
63 if (!cells[f + iu + "," + iv]) return row[SEC[f] === flash ? 1 : 0];
64 if ((!on(f, iu, iv - 1) && v * 10 - iv < 0.3) || (!on(f, iu - 1, iv) && u * 10 - iu < 0.3)) return LIP;
65 return SEC[f] < lit ? LIT : row[2];
66 }
67 function render(yaw, rev, flash) {
68 buf.fill(BG); mask.fill(0);
69 const ex = toObj([1, 0, 0], yaw), ey = toObj([0, 1, 0], yaw), d = toObj([0, 0, 1], yaw), shade = {};
70 for (const [f, w] of [["x+", [1, 0, 0]], ["x-", [-1, 0, 0]], ["z+", [0, 0, 1]], ["z-", [0, 0, -1]], ["y+", [0, 1, 0]]]) {
71 const q = toWorld(w, yaw);
72 shade[f] = Math.min(1, Math.round((0.4 + 0.7 * Math.max(0, q[0] * L[0] + q[1] * L[1] + q[2] * L[2])) * 8) / 8);
73 }
74 for (let py = 0; py < VH; py++) for (let px = 0; px < VW; px++) {
75 const X = (px + 0.5 - VW / 2) / SC, Y = -(py + 0.5 - VH / 2) / SC, i = py * VW + px;
76 const h = hitBox([ex[0] * X + ey[0] * Y - d[0] * 10, ex[1] * X + ey[1] * Y - d[1] * 10, ex[2] * X + ey[2] * Y - d[2] * 10], d);
77 if (!h) continue;
78 const f = "xyz"[h.ax] + (h.sg > 0 ? "+" : "-"), [u, v] = uv(h.ax, h.sg, h.p);
79 mask[i] = 1; buf[i] = paint(f, u, v, shade[f] ?? 0.4, rev, flash);
80 }
81 for (let i = 0; i < mask.length; i++) if (!mask[i] && (mask[i - 1] || mask[i + 1] || mask[i - VW] || mask[i + VW])) buf[i] = INK;
82 x.putImageData(img, 0, 0);
83 }
84
85 // A gentle three quarter turn counterclockwise, eased in and out, that stops
86 // with the J face in front on the right. It settles before the first beat,
87 // so each beat lights a face that is in view.
88 const FPS = 20, SPIN = 0.9, BEATS = [0.95, 1.25, 1.55];
89 const yawAt = (t) => { const k = Math.min(t / SPIN, 1); return Math.PI / 4 + 1.5 * Math.PI * k * k * (3 - 2 * k); };
90 function frame(t) {
91 const lit = BEATS.filter((b) => t >= b).length;
92 render(yawAt(t), lit, lit && t < BEATS[lit - 1] + 0.1 ? lit - 1 : -1);
93 }
94
95 let A;
96 function tone(f, at, dur, gain, type = "triangle", f2) {
97 const o = A.createOscillator(), g = A.createGain(), s = A.currentTime + at;
98 o.type = type; o.frequency.setValueAtTime(f, s);
99 if (f2) o.frequency.exponentialRampToValueAtTime(f2, s + dur);
100 g.gain.setValueAtTime(0.001, s); g.gain.exponentialRampToValueAtTime(gain, s + 0.02);
101 g.gain.exponentialRampToValueAtTime(0.001, s + dur);
102 o.connect(g).connect(A.destination); o.start(s); o.stop(s + dur);
103 }
104 function sound() {
105 // I's power-on, the standard: a low hum that rises, then each beat stacks
106 // one more held note into a chord that rings out together.
107 tone(55, 0, 0.55, 0.24, "triangle", 110);
108 const END = BEATS[2] + 0.9;
109 tone(131, BEATS[0], END - BEATS[0], 0.1);
110 tone(196, BEATS[1], END - BEATS[1], 0.08);
111 tone(262, BEATS[2], END - BEATS[2], 0.07); tone(392, BEATS[2], END - BEATS[2], 0.025, "square");
112 }
113
114
115 /** Seconds from start until the chord has rung out. */
116 export const JBOX_SPIN_LENGTH = BEATS[2] + 0.9;
117
118 /**
119 * Play the tag once on `canvas`. Call it from a click or key press, so the browser lets
120 * the sound play. Resolves when the tag is done.
121 */
122 export function playJboxSpin(canvas, { sound: withSound = true } = {}) {
123 canvas.width = VW;
124 canvas.height = VH;
125 x = canvas.getContext("2d");
126 img = x.createImageData(VW, VH);
127 buf = new Uint32Array(img.data.buffer);
128 if (withSound) {
129 try {
130 A = A || new AudioContext();
131 A.resume();
132 sound();
133 } catch {}
134 }
135 const t0 = performance.now();
136 let last = -1;
137 return new Promise((done) => {
138 (function loop(now) {
139 const t = (now - t0) / 1000;
140 const step = Math.max(0, Math.floor(t * FPS));
141 if (step !== last) { last = step; frame(Math.min(step / FPS, SPIN + 1)); }
142 if (t >= JBOX_SPIN_LENGTH) return done();
143 requestAnimationFrame(loop);
144 })(t0);
145 });
146 }
147
148 /** Whole-pixel scale that fits the tag in a box. */
149 export function jboxScale(width, height) {
150 return Math.max(1, Math.floor(Math.min(width / VW, height / VH)));
151 }
src/arcade/snapshot.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * Export snapshot: a display's shelf in one offline HTML file, as
3 * browser-arcade's `bun run bundle` made it — the shelf, every cart and
4 * every cover inside the page, so it plays from disk with no server. Its
5 * one top line says it is a dated copy that will never update.
6 */
7
8 import type { App } from "../app.ts";
9 import type { DisplayConfig } from "../display/config.ts";
10 import { readCover } from "../git/builds.ts";
11 import { repoDir } from "../git/repos.ts";
12 import { readArt, readCapture } from "./carts.ts";
13 import { coverTemplateBytes, shelfPage } from "./host.ts";
14 import { slug, type Shelf } from "./shelf.ts";
15
16 /** `yyyymmdd` for a day. */
17 export const snapshotDate = (at: Date): string => at.toISOString().slice(0, 10).replaceAll("-", "");
18
19 /** The line across the top of a snapshot. */
20 export const snapshotLine = (date: string, producer: string | undefined): string =>
21 `${producer === undefined ? "" : `${producer.toUpperCase()} • `}snapshot ${date} | This is an HTML file that doesn't receive updates`;
22
23 const dataUrl = (bytes: Uint8Array): string => {
24 const type =
25 bytes[0] === 0xff ? "image/jpeg" : bytes[0] === 0x52 ? "image/webp" : "image/png";
26 return `data:${type};base64,${Buffer.from(bytes).toString("base64")}`;
27 };
28
29 /** The snapshot file for a display's shelf as it stands. */
30 export async function snapshotFile(
31 app: App,
32 config: Pick<DisplayConfig, "title" | "shelf">,
33 shelf: Shelf,
34 at: Date,
35 ): Promise<{ name: string; html: string }> {
36 const date = snapshotDate(at);
37 const dataDir = app.config.dataDir;
38 const carts: Record<string, string> = {};
39 const labels: Record<string, string> = { "cover-template.png": dataUrl(coverTemplateBytes()) };
40 for (const g of shelf.games)
41 for (const b of g.builds) {
42 const entry = shelf.entries.get(b.file);
43 if (entry === undefined) continue;
44 const { repo, pin, cart } = entry;
45 const html = readCapture(dataDir, repo, pin.oid, cart.page);
46 if (html !== undefined) carts[b.file] = new TextDecoder().decode(html);
47 if (b.label !== undefined && cart.cover !== undefined) {
48 const bytes = await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), cart.cover);
49 if (bytes !== undefined) labels[b.label] = dataUrl(bytes);
50 }
51 if (b.art !== undefined) {
52 const bytes = readArt(dataDir, repo, pin.oid, cart.page);
53 if (bytes !== undefined) labels[b.art] = dataUrl(bytes);
54 }
55 }
56 const html = shelfPage({
57 title: config.title,
58 tabTitle: `${config.title} · snapshot ${date}`,
59 producer: config.shelf.producer,
60 data: { snapshot: snapshotLine(date, config.shelf.producer), games: shelf.games, carts, labels },
61 });
62 return { name: `${slug(config.title)}-${date}.html`, html };
63 }
src/display/launch.ts +89 −5
@@ -1,13 +1,97 @@
11 /**
2 * Where a display item opens, as far as main reads it: a pin's screenshots
3 * on its own repository. Jay Moran's launch.ts (`origin/incoming/jay-main`)
4 * also signs grants for captured pages on the display origin and names the
5 * covers and downloads; those wait for the Arcade host and for `pin_demos.ts`.
2 * Where a display item opens. A `file` demo plays on the display origin,
3 * `arcade.<app domain>`, never on the forge's: a captured page is a
4 * stranger's code. A page in a repository anyone may read plays at its
5 * plain address; one in a repository only the viewer may read carries a
6 * short grant the forge signed for that page alone (`signCart`).
7 *
8 * An item the viewer cannot read the repository of (`open: false`) is
9 * reached only through its display, by its opaque id: on the forge under
10 * `/<owner>/<display>/display/demo/<id>/…`, and on the display origin at
11 * `displays/<owner>/<display>/<id>.html`. Showcase published it, so it
12 * plays without a grant when the display is public; a private display's
13 * page carries a grant for that path.
614 */
715
8 import type { Repo } from "../core/repos.ts";
16 import { createHmac, timingSafeEqual } from "node:crypto";
17 import type { App } from "../app.ts";
18 import { appsRuntime } from "../apps/runtime.ts";
19 import { arcadeUrl } from "../arcade/host.ts";
20 import { cartFile, shownFile } from "../arcade/shelf.ts";
21 import { canRead, type Repo } from "../core/repos.ts";
922 import type { BuildPin } from "../git/builds.ts";
23 import { loadKey } from "../kernel/secret.ts";
24 import type { DisplayItem } from "./items.ts";
25
26 /** How long a grant to play a private page lasts. */
27 export const CART_GRANT_MS = 60 * 60 * 1000;
28
29 const mac = (dataDir: string, payload: string): string =>
30 createHmac("sha256", loadKey(dataDir)).update(`cart:${payload}`).digest("base64url");
31
32 /** A grant to play the capture at `path` (`carts/<owner>/<repo>/<sha>/<page>.html`) until it expires. */
33 export function signCart(dataDir: string, path: string, now = Date.now()): string {
34 const expires = now + CART_GRANT_MS;
35 return `${expires}.${mac(dataDir, `${path}:${expires}`)}`;
36 }
37
38 /** Whether `grant` vouches for `path` now. */
39 export function verifyCart(dataDir: string, path: string, grant: string, now = Date.now()): boolean {
40 const dot = grant.indexOf(".");
41 const expires = grant.slice(0, dot);
42 if (dot === -1 || !/^\d{1,15}$/.test(expires) || Number(expires) <= now) return false;
43 const a = Buffer.from(grant.slice(dot + 1));
44 const b = Buffer.from(mac(dataDir, `${path}:${expires}`));
45 return a.length === b.length && timingSafeEqual(a, b);
46 }
47
48 /** The display origin, or undefined where no apps run. */
49 export function displayOrigin(app: App): string | undefined {
50 const runtime = appsRuntime(app);
51 return runtime === undefined ? undefined : arcadeUrl(runtime);
52 }
53
54 type Hidden = Pick<DisplayItem, "display" | "id">;
55
56 /** An item's own routes on the forge, under its display. */
57 export const shownBase = (item: Hidden): string => `/${item.display.ownerName}/${item.display.name}/display/demo/${item.id}`;
58
59 /** Where a captured demo plays, or undefined where no apps run or nothing is captured. */
60 export function playUrl(app: App, item: DisplayItem): string | undefined {
61 if (item.captured === undefined) return undefined;
62 if (item.open) return pinPlayUrl(app, item.repo, item.pin.oid, item.demo.page);
63 const origin = displayOrigin(app);
64 if (origin === undefined) return undefined;
65 const path = shownFile(item);
66 const plain = canRead(app.db, item.display, undefined);
67 return `${origin}/${path}${plain ? "" : `?g=${signCart(app.config.dataDir, path)}`}`;
68 }
69
70 /**
71 * Where a commit's captured page plays on the display origin, read through
72 * its own repository: plain when anyone may read it, else with a grant.
73 * The caller says it is captured (`captureState`).
74 */
75 export function pinPlayUrl(app: App, repo: Repo, oid: string, page: string): string | undefined {
76 const origin = displayOrigin(app);
77 if (origin === undefined) return undefined;
78 const path = cartFile(repo, oid, page);
79 return `${origin}/${path}${canRead(app.db, repo, undefined) ? "" : `?g=${signCart(app.config.dataDir, path)}`}`;
80 }
81
82 /** Where a captured demo downloads, on the forge. */
83 export const downloadUrl = (item: DisplayItem): string =>
84 item.open
85 ? `/${item.repo.ownerName}/${item.repo.name}/builds/${item.pin.oid}/download?page=${encodeURIComponent(item.demo.page)}`
86 : `${shownBase(item)}/download`;
1087
1188 /** A pin's screenshots, on its repository. */
1289 export const repoShotsUrl = (repo: Pick<Repo, "ownerName" | "name">, pin: Pick<BuildPin, "label">): string =>
1390 `/${repo.ownerName}/${repo.name}/builds/${encodeURIComponent(pin.label)}/shots`;
91
92 /** A demo's screenshots, on the forge. */
93 export const shotsUrl = (item: DisplayItem): string => (item.open ? repoShotsUrl(item.repo, item.pin) : `${shownBase(item)}/shots`);
94
95 /** A demo's cover, or the picture of its captured page, on the forge. */
96 export const coverUrl = (item: DisplayItem): string =>
97 item.open ? `/${item.repo.ownerName}/${item.repo.name}/builds/${encodeURIComponent(item.pin.label)}/cover` : `${shownBase(item)}/cover`;
src/git/builds.ts +9
@@ -647,6 +647,15 @@ export async function storeCover(dir: string, label: string, bytes: Uint8Array):
647647 return kept.code === 0 ? ok(oid) : err("git_failed");
648648 }
649649
650 /** A stored cover's bytes, read only through a pin that names it. */
651 export async function readCover(dir: string, oid: string): Promise<Uint8Array | undefined> {
652 if (!isSafeOid(oid)) return undefined;
653 const kind = await runGitCapture(["cat-file", "-t", oid], { cwd: dir });
654 if (kind.code !== 0 || kind.stdout.trim() !== "blob") return undefined;
655 const bytes = await runGitRaw(["cat-file", "blob", oid], { cwd: dir });
656 return bytes.ok ? bytes.value : undefined;
657 }
658
650659 /**
651660 * Every pin, newest first, read in one `for-each-ref`; or the one `label`.
652661 * A pin's note is its notes file on `refs/forge/notes` when it has one,
src/http/server.ts +5
@@ -521,6 +521,7 @@ import { Router } from "./router.ts";
521521 import { getUserById } from "../core/users.ts";
522522 import { appsRuntime } from "../apps/runtime.ts";
523523 import { holdAppHost } from "../apps/holding.ts";
524 import { isArcadeHost, serveArcade } from "../arcade/host.ts";
524525 import {
525526 appWebSocket,
526527 type AppSocket,
@@ -2400,6 +2401,10 @@ export async function serve(app: App): Promise<Servers> {
24002401 // must not take `<app>--<n>--<parentHost>`. Only its `"unknown"` falls
24012402 // through, since it reads every `--<its host>` label as its own slug.
24022403 let ownUnknown = false;
2404 // The Arcade's origin plays third-party carts; it is answered here, on
2405 // its own host, and nothing of the forge's is served on it.
2406 if (runtime !== undefined && isArcadeHost(request.headers.get("host"), runtime.options.domain))
2407 return securityFloor(await serveArcade(app, request));
24032408 if (runtime !== undefined) {
24042409 const target = resolveAppHost(app, runtime.options.domain, request);
24052410 // A preview's headers are the app's business: what `proxyApp`
src/web/pages/display.ts +8 −3
@@ -3,8 +3,9 @@
33 * `display.json` holds (`display/config.ts`), as whoever is looking may read
44 * them; a build whose repository the viewer cannot read shows its name and
55 * version alone. A writer also gets a form to choose the builds, which works
6 * without script (POST here) and, with script, sends the API's PUT. Editing
7 * the title, covers and the player wait. A bad `display.json` shows its error.
6 * without script (POST here) and, with script, sends the API's PUT. Launch
7 * opens the Arcade host. Editing the title and covers wait. A bad
8 * `display.json` shows its error.
89 */
910
1011 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
@@ -13,7 +14,8 @@ import { displayItems, selectionKeys } from "../../display/items.ts";
1314 import { writesDisplay } from "../../display/selections.ts";
1415 import { exactRefOid } from "../../git/branches.ts";
1516 import { repoDir } from "../../git/repos.ts";
16 import { INVALID_TITLE, displayOf } from "../../display/known.ts";
17 import { INVALID_TITLE, arcadeRepoOf, displayOf } from "../../display/known.ts";
18 import { arcadeHome } from "../../arcade/host.ts";
1719 import { repoShotsUrl } from "../../display/launch.ts";
1820 import type { Ctx } from "../../http/context.ts";
1921 import { crumbsFor, forbiddenPage, loadRepo, notFoundPage, repoBase, repoHeader, repoPalette } from "../chrome.ts";
@@ -44,6 +46,8 @@ export async function displayPage(ctx: Ctx): Promise<Response> {
4446 const config = await timePhaseAsync(ctx.request, "display", () => displayOf(ctx.app, repo));
4547 if (config === undefined) return timePhase(ctx.request, "render", () => notFoundPage(ctx));
4648 const items = config.ok ? await timePhaseAsync(ctx.request, "items", () => displayItems(ctx.app, repo, config.value, ctx.auth.user)) : [];
49 // The Arcade host plays only the display titled `arcade-builds`; Launch is offered on that one.
50 const launch = config.ok && config.value.layout === "shelf" && (await arcadeRepoOf(ctx.app))?.id === repo.id ? arcadeHome(ctx.app) : undefined;
4751 const writes = config.ok && writesDisplay(ctx.app, repo, ctx.auth.user);
4852 const chosen = writes && config.ok ? await selectionKeys(ctx.app, config.value, ctx.auth.user) : [];
4953 const choices = writes && config.ok ? await choosableBuilds(ctx.app, config.value, chosen, ctx.auth.user) : [];
@@ -52,6 +56,7 @@ export async function displayPage(ctx: Ctx): Promise<Response> {
5256 const body = html`${repoHeader(ctx, repo, "code", { compact: true })}
5357 <div class="page-head mt">
5458 <h2>${title}</h2>
59 ${launch === undefined ? "" : html`<a class="btn" data-by="display-launch" href="${launch}/">Launch</a>`}
5560 <a href="/displays">All displays</a>
5661 </div>
5762 ${!config.ok
test/arcade-host.test.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * Launching a display: the display page offers Launch for the Arcade's
3 * display, and the Arcade host (`arcade.<app domain>`) lists its carts,
4 * carries a policy with no third-party origin, and plays only what the
5 * display shows.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { importCart } from "../src/arcade/import.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18
19 const DOMAIN = "apps.test";
20 const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 5]);
21 const tagger = { name: "Jay Moran", email: "[email protected]" };
22
23 describe("the Arcade host", () => {
24 let dataDir: string;
25 let app: App;
26 let servers: Servers;
27 let alice: User;
28 let sha = "";
29
30 const arcade = (path: string, init: RequestInit = {}) =>
31 fetch(`${servers.url}${path}`, { ...init, headers: { host: `arcade.${DOMAIN}`, ...(init.headers ?? {}) }, redirect: "manual" });
32
33 beforeAll(async () => {
34 dataDir = await mkdtemp(join(tmpdir(), "forge-arcade-host-"));
35 app = createApp({ dataDir, port: 0 });
36 servers = await serve(app);
37 await new AppsRuntime(app, { domain: DOMAIN, scheme: "http", publicPort: servers.port, forgeUrl: servers.url }).start();
38 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
39 if (!made.ok) throw new Error(made.error);
40 alice = made.value;
41 for (const name of ["karts", "arcade-display"]) {
42 const r = await createRepo(app, alice, { name, visibility: "public" });
43 if (!r.ok) throw new Error(String(r.error));
44 }
45 const repo = (await import("../src/core/repos.ts")).getRepo(app.db, "alice", "karts")!;
46 const c = await commitToBranch(app, alice, repo, { message: "one", files: [{ path: "a.txt", content: "a" }] });
47 if (!c.ok) throw new Error(JSON.stringify(c.error));
48 sha = c.value.commitOid;
49 const imported = await importCart(dataDir, { repo: "alice/karts", label: "iter-1", sha, note: "n", cart: { name: "fiesta-kart", version: "1.0", page: "/", shelf: true }, html: new TextEncoder().encode("<p>fiesta</p>"), cover: PNG, art: PNG }, tagger);
50 if (!imported.ok) throw new Error(JSON.stringify(imported.error));
51 const display = (await import("../src/core/repos.ts")).getRepo(app.db, "alice", "arcade-display")!;
52 const d = await commitToBranch(app, alice, display, {
53 message: "display",
54 files: [{ path: "display.json", content: JSON.stringify({ title: "arcade-builds", layout: "shelf", sources: ["alice/karts"], shelf: { producer: "jbox" } }) }],
55 });
56 if (!d.ok) throw new Error(JSON.stringify(d.error));
57 });
58
59 afterAll(async () => {
60 app.close();
61 await servers.stop?.();
62 await rm(dataDir, { recursive: true, force: true });
63 });
64
65 test("the display page links Launch to the host", async () => {
66 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
67 const res = await fetch(`${servers.url}/alice/arcade-display/display`, { headers: { cookie } });
68 const body = await res.text();
69 expect(res.status).toBe(200);
70 expect(body).toContain(`href="http://arcade.${DOMAIN}:${servers.port}/"`);
71 expect(body).toContain("Launch");
72 });
73
74 test("the host page carries the floor headers and a policy with no third-party origin", async () => {
75 const res = await arcade("/");
76 expect(res.status).toBe(200);
77 const csp = res.headers.get("content-security-policy") ?? "";
78 expect(csp).toContain("default-src 'self'");
79 expect(csp).toContain("frame-ancestors 'self'");
80 expect(csp).not.toMatch(/https?:\/\//);
81 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
82 expect(res.headers.get("referrer-policy")).toBe("no-referrer");
83 const page = await res.text();
84 expect(page).not.toContain("fonts.googleapis.com");
85 expect(page).toContain("<noscript>");
86 expect(page).toContain('id="prev"');
87 expect(page).toContain("hint-touch");
88 });
89
90 test("the host lists the display's carts and serves their pages", async () => {
91 const games = (await (await arcade("/games.json")).json()) as { name: string; builds: { file: string }[] }[];
92 expect(games.map((g) => g.name)).toEqual(["fiesta-kart"]);
93 const file = games[0]!.builds[0]!.file;
94 const played = await arcade(`/${file}`);
95 expect(played.status).toBe(200);
96 expect(await played.text()).toBe("<p>fiesta</p>");
97 expect(played.headers.get("content-security-policy")).toContain("frame-ancestors");
98 });
99
100 test("the host answers only reads, and nothing outside the display", async () => {
101 expect((await arcade("/", { method: "POST" })).status).toBe(405);
102 expect((await arcade("/carts/alice/karts/" + "0".repeat(40) + "/index.html")).status).toBe(404);
103 expect((await arcade("/settings")).status).toBe(404);
104 });
105 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs